Compare commits

...
16 Commits
Author SHA1 Message Date
kiskaadee 81f155105b feat(new-repo): add --empty flag for bare GitHub repo creation
- Add --empty flag (auto_init=False) so remote-only migrations avoid root commit conflicts
- Reject combining --empty with --template
- Add test_empty_argument unit test and document --empty in README.md
2026-11-26 09:52:51 -05:00
kiskaadee f2613b0b3a docs(readme): update CLI flags and architecture diagrams for GitHub-primary flow
- Document inverted -o/--org (GitHub), --gitea-org, and --gitea-mirror flags

- Update examples and Mermaid sequence diagrams for GitHub-primary + Gitea pull mirror
2026-11-25 16:39:00 -05:00
kiskaadee 4c5820bace feat(new-repo): invert defaults to GitHub-primary with Gitea pull mirror
- Provision primary repositories on GitHub (auto_init, lowercase license_template, and template generation) and push/clone origin to github.com

- Invert -o/--org to target GitHub organizations and replace --github-org with --gitea-org

- Replace --migrate with --gitea-mirror to attach Gitea pull mirrors (mirror=True) to existing GitHub repos

- Update test_new_repo.py for inverted CLI flags, lowercase GitHub licenses, and Gitea pull-mirror payloads
2026-11-25 16:36:49 -05:00
kiskaadee 36233f50e0 refactor(code-quality): resolve pyright type errors and ruff linter warnings 2026-11-04 09:15:23 -05:00
kiskaadee 750f0cad35 feat(auth): decouple credential resolution from legacy tea config 2026-11-04 08:59:01 -05:00
kiskaadee 6c524b2ed5 test(auth): add tests for persona isolation and decoupled credential resolution 2026-11-04 08:58:38 -05:00
kiskaadee e72b46a42e feat(persona): enforce persona identity and credential isolation via --as
Previously, new-repo extracted tea logins via a naive line-by-line loop
that always resolved to the last entry in ~/.config/tea/config.yml, leading
to split-identity failures where kiskaadee's token was paired with anneux's
username. Furthermore, downstream push mirror registration and git clone
assumed the local username instead of respecting Gitea's creation response.

- Add --as <persona> flag and support NEW_REPO_AS / TEA_LOGIN env fallbacks
- Parse tea logins by discrete YAML block, respecting default: true
- Bind persona tokens, usernames, and dedicated SSH keys together
- Add get_authenticated_user() on GiteaClient to verify token identity
- Rely authoritatively on forge response (owner and ssh_url) for mirroring and clone
- Pass dedicated persona ssh_key to git clone/push when configured
- Add unit tests for tea parsing, persona extraction, and CLI flags
- Document --as flag and persona examples in README
2026-10-22 21:35:22 -05:00
kiskaadee c950ff2e73 fix(license): normalize license identifiers and default to Unlicense
Gitea's repository template engine resolves license templates by exact
case-sensitive filename against its internal asset registry (e.g., 'Unlicense',
'MIT', 'Apache-2.0'). When passed 'UNLICENSE', Gitea returned an unhandled
HTTP 500 error: 'initRepository: prepareRepoCommit: getLicense[UNLICENSE]: file does not exist'.

- Add GITEA_LICENSES mapping and normalize_license() helper
- Change default license identifier from 'UNLICENSE' to 'Unlicense'
- Normalize license argument in GiteaClient.create_repo
- Add unit tests for license casing and client payloads
- Update README CLI documentation and examples
2026-10-22 20:23:42 -05:00
kiskaadee aff2098f7f refactor(visibility): make repositories public by default 2026-10-22 17:24:34 -05:00
kiskaadee 06cc3254c0 docs: document Gitea organization binding and add adr 0006
- Add ADR 0006 detailing Gitea organization binding, auto-provisioning, and decoupled GitHub mirror defaults
- Update CLI specification and usage examples in README.md
2026-10-18 08:00:38 -05:00
kiskaadee 412fc3e77b feat: support Gitea organization binding and auto-provisioning
- Add -o/--org flag and positional <org>/<repo> shorthand resolution
- Auto-provision missing Gitea organizations via GET/POST /api/v1/orgs
- Route repository creation, templates, migrations, and push mirrors to the resolved owner
- Add optional --github-org flag for offsite GitHub mirror targets
- Add unit tests for organization resolution and API endpoint routing
2026-10-18 07:57:46 -05:00
kiskaadee 75a09f2ad8 docs: document github migration workflow and add adr 0005
- Add ADR 0005 detailing GitHub-to-Gitea migration design decisions and trade-offs
- Update README.md with --migrate flag specifications, examples, and Mermaid sequence diagram
2026-10-10 17:39:01 -05:00
kiskaadee acdd91dd10 feat: add --migrate flag for server-side GitHub-to-Gitea migration
- Implement GiteaClient.repo_exists and GiteaClient.migrate_repo
- Add parse_github_target to handle HTTPS, SSH, shorthands, and local origin auto-detection
- Add reconfigure_local_remotes to switch origin to Gitea and github to GitHub
- Add comprehensive unit tests in test_new_repo.py covering arguments, parsing, and remote reconfiguration
2026-10-10 17:38:45 -05:00
kiskaadee 5c29be4fb7 docs: add adr 0004 and rewrite readme to be portable and impersonal
- Add ADR 004 documenting existing repository linking architecture
- Rewrite README with impersonal tone, removing workstation/laptop coupling
- Document existing repository workflow and updated CLI options
2026-10-10 00:17:27 -05:00
kiskaadee 2d0731ebe7 feat: add existing repository auto-detection and remote linking
- Auto-detect existing local Git repositories when name is omitted, '.', or matches current directory
- Provision empty remotes (auto_init=False) to preserve existing commit history
- Configure origin remote and push active local branch
- Add unit test for optional name argument
- Add SECRETS_FILE environment variable support for custom SOPS paths

Rationale: Allows developers to seamlessly attach sovereign dual-forge
infrastructure to existing local projects without divergent commit conflicts.
2026-10-10 00:17:04 -05:00
kiskaadee 9d07c3ecd4 docs: add adrs 0001-0003 and update project documentation
- Add ADR 001 documenting shift from Rust to zero-dependency Python
- Add ADR 002 establishing 12-factor env vars with SOPS fallback
- Add ADR 003 detailing dual-forge topology and retain-and-report policy
- Update README with CLI usage, credentials options, and architecture diagram
2026-10-09 23:43:02 -05:00
9 changed files with 2157 additions and 199 deletions

No files matched your search

+201 -1
View File
@@ -1 +1,201 @@
# new-repo # `new-repo` — Automated Repository Provisioning CLI
`new-repo` is a portable, zero-dependency Python 3 command-line utility designed to automate repository provisioning across a dual-forge Git topology:
- **Primary Forge**: **GitHub** for cloud availability, issue/project planning, and CI/CD automation.
- **Backup Forge**: Self-hosted **Gitea** for homelab redundancy via automated server-side **pull mirroring**.
It automates the multi-step setup required to create a repository on GitHub, prepare a local working tree, and attach a Gitea pull mirror in a single command.
---
## 🎯 Key Design Principles
1. **Zero External Dependencies**: Built strictly with Python 3 standard library modules (`urllib.request`, `argparse`, `json`, `subprocess`, `dataclasses`, `typing`). Requires no virtual environment, compilation step, or third-party package installation.
2. **Universal Portability (12-Factor)**: Standard environment variables (`GITEA_TOKEN`, `GITHUB_TOKEN`) and optional `.env` files serve as the primary configuration contract. The utility runs out-of-the-box on any POSIX system, container, or CI/CD runner.
3. **In-Memory Credential Safety**: Tokens are injected exclusively via native HTTPS authorization headers. Secrets are never passed as command-line arguments to subprocesses, preventing exposure in system process tables (`ps`, `/proc/$PID/cmdline`) or persistent disk logs.
4. **Resilient Failure Recovery**: Adheres to a *retain-and-report* policy. If homelab Gitea pull-mirror registration encounters an error after the primary GitHub repository is created, the GitHub repository is preserved and diagnostic URLs are printed for manual review or `--gitea-mirror` retry.
5. **Strict Static Typing**: Enforces full static type hints validated via **Pyright** and formatted/linted via **Ruff**.
Architecture Decision Records (ADRs) are maintained in [`docs/adr/`](docs/adr/):
- [**ADR 001**: Adopt Zero-Dependency Python Over Compiled Rust](docs/adr/0001-adopt-zero-dependency-python.md)
- [**ADR 002**: Environment Variables as Primary Configuration Interface with Pluggable Secret Resolvers](docs/adr/0002-environment-variables-as-primary-interface-with-sops-fallback.md)
- [**ADR 003**: Dual-Forge Topology with Automated Push Mirroring and Retain-and-Report Error Policy](docs/adr/0003-dual-forge-topology-with-automated-push-mirroring.md)
- [**ADR 004**: Existing Repository Linking and Auto-Detection](docs/adr/0004-existing-repository-linking-and-auto-detection.md)
- [**ADR 005**: GitHub-to-Gitea Migration with Automated Push Mirroring](docs/adr/0005-github-to-gitea-migration-with-automated-push-mirroring.md)
- [**ADR 006**: Gitea Organization Binding and Auto-Provisioning](docs/adr/0006-gitea-organization-binding.md)
---
## 💻 CLI Specification
```text
Usage: new-repo [NAME] [OPTIONS]
Arguments:
name Optional repository name ('[org/]repo', defaults to current directory if omitted or '.')
Options:
-o, --org ORG Target GitHub organization to own the repository (defaults to personal GITHUB_USER)
--gitea-org ORG Optional Gitea organization for the homelab pull mirror (auto-created if missing; defaults to GITEA_USER)
--gitea-mirror [URL] Attach a Gitea pull mirror to an existing GitHub repository (URL or auto-detect from local origin)
-p, --private Make repository private (default: public)
-d, --description Optional repository description string
-l, --license GitHub license template identifier (default: unlicense, pass "" to disable)
-t, --template Optional GitHub template repository ('[owner/]template-name')
-M, --no-mirror Disable automatic homelab pull mirroring to Gitea
--no-clone Skip cloning the repository locally after creation
--empty Create an empty GitHub repository with auto_init=False (no initial commit)
--as PERSONA Persona / login identity to provision as (e.g. anneux)
-h, --help Show help message and exit
```
### Examples
```bash
# 1. Standard greenfield creation (Public GitHub + Gitea pull mirror + unlicense + auto-clone)
new-repo service-api
# 2. Provision as a specific agent persona (binds GitHub/Gitea credentials and SSH keys to persona)
new-repo frontend-app --as anneux
# 3. Provision under a GitHub organization (via shorthand or -o/--org flag)
new-repo my-org/core
new-repo core -o my-org
# 4. Attach remotes & push an existing local repository (into personal account or organization)
cd ~/Projects/my-existing-app
new-repo -o my-org
# 5. Provision from an existing GitHub template
new-repo web-client --template template-react-app
# 6. GitHub-only repository (no Gitea pull mirror)
new-repo cloud-only --no-mirror
# 7. Private repository with MIT license
new-repo utility-lib --private --license mit
# 8. Attach a Gitea pull mirror to an existing GitHub repository (explicit URL or local origin)
new-repo --gitea-mirror https://github.com/my-org/existing-service
cd ~/Projects/existing-service && new-repo --gitea-mirror
```
---
## 🔐 Credentials & Configuration
### 1. Environment Variables (Universal / CI/CD)
The script resolves credentials from standard environment variables:
```bash
# Required
export GITEA_TOKEN="your_gitea_personal_access_token"
export GITHUB_TOKEN="your_github_personal_access_token"
# Optional overrides (defaults shown)
export GITEA_URL="https://gitea.example.com"
export GITEA_USER="git_username"
export GITHUB_USER="github_username"
```
### 2. Local `.env` File
Alternatively, create a `.env` file in the working directory or project root:
```env
GITEA_TOKEN=your_gitea_token
GITHUB_TOKEN=your_github_token
GITEA_URL=https://gitea.example.com
GITEA_USER=git_username
GITHUB_USER=github_username
```
### 3. Optional Workstation SOPS Integration
When environment variables are unset, the built-in `SecretProvider` optionally checks for SOPS-encrypted configuration files (e.g. `~/Config/secrets.yaml`), extracting values directly into process memory without persisting plaintext tokens to disk:
```yaml
system:
gh_repo_token: <github_token>
gitea:
api_token: <gitea_token>
```
---
## 🏛️ Provisioning Architecture & Workflow
```mermaid
sequenceDiagram
autonumber
actor User as Developer / CI Runner
participant CLI as new-repo (Python 3)
participant SP as SecretProvider (Env / .env / SOPS)
participant GitHub as GitHub API (Primary)
participant Git as Local Git
participant Gitea as Gitea API (Pull Mirror)
User->>CLI: new-repo <repo-name> [flags]
CLI->>SP: Resolve API credentials
SP-->>CLI: Credentials (GitHub token, Gitea token)
alt Existing Local Git Repo
CLI->>GitHub: POST /user/repos or /orgs/{org}/repos (auto_init=False)
GitHub-->>CLI: Empty primary repository created
CLI->>Git: git remote add/set-url origin git@github.com:<owner>/<repo>.git && git push -u origin <branch>
else Template Repo Specified (-t <template>)
CLI->>GitHub: POST /repos/{owner}/{template}/generate
GitHub-->>CLI: Primary repository generated
else Standard Greenfield Repository
CLI->>GitHub: POST /user/repos or /orgs/{org}/repos (auto_init=True, license_template)
GitHub-->>CLI: Primary repository created
end
opt Local Clone Enabled (Greenfield Default)
CLI->>Git: git clone git@github.com:<owner>/<repo>.git
Git-->>CLI: Working tree cloned to ./<repo-name>
end
opt Homelab Pull Mirror Enabled (Default)
CLI->>Gitea: POST /api/v1/repos/migrate (mirror=True, service=github, auth_token=gh_token)
Gitea->>GitHub: Server-to-server pull mirror sync
Gitea-->>CLI: Pull mirror registered
end
```
### Attach Pull Mirror Workflow (`--gitea-mirror`)
```mermaid
sequenceDiagram
autonumber
actor User as Developer
participant CLI as new-repo (--gitea-mirror)
participant Gitea as Gitea API (Pull Mirror)
participant GitHub as GitHub (Primary)
User->>CLI: new-repo --gitea-mirror [github-target]
CLI->>Gitea: GET /api/v1/repos/{owner}/{repo} (Conflict Check)
alt Repo Exists on Gitea
Gitea-->>CLI: 200 OK (Abort to avoid overwriting)
else Repo Does Not Exist
CLI->>Gitea: POST /api/v1/repos/migrate (mirror=True, auth_token=gh_token)
Gitea->>GitHub: Server-to-server pull mirror sync
Gitea-->>CLI: Pull mirror created
end
```
---
## 🧪 Development & Quality Assurance
Run verification commands using the standard Python toolchain:
```bash
# Execute unit tests
python3 test_new_repo.py
# Static type checking
pyright new_repo.py test_new_repo.py
# Linting and formatting
ruff check new_repo.py test_new_repo.py
ruff format --check new_repo.py test_new_repo.py
```
@@ -0,0 +1,37 @@
# ADR 001: Adopt Zero-Dependency Python Over Compiled Rust
## Status
Accepted (2026-10-09)
## Context
The initial design for `new-repo` proposed a compiled native Rust binary utilizing `clap`, `reqwest`, `serde`, and `secrecy`. The motivation was strong compile-time type safety and static single-binary distribution.
However, during practical evaluation, several forces made Rust ill-suited for this specific tool:
1. **Compilation Latency & Iteration Friction**: As an interactive CLI used occasionally to provision repositories, waiting for `cargo build` and maintaining dependency trees creates high developer friction when tweaking CLI options or REST payloads.
2. **Boilerplate vs. Scope**: The tool fundamentally orchestrates three HTTP REST calls (Gitea API, GitHub API, push mirror registration) and executes a local `git clone`. Rust's asynchronous/synchronous network ceremony and dependency footprint are disproportionate to this scope.
3. **Workstation Integration**: Modifying a shell or provisioning script should allow immediate execution without an intermediate compile step.
We evaluated three runtime alternatives:
- **Bash with curl and jq**: Lowest barrier, but fragile when constructing nested JSON payloads, parsing multi-step API errors, and managing tokens securely.
- **Python with external libraries (httpx/requests)**: Clean syntax, but introduces virtual environment or `uv` packaging requirements.
- **Python Standard Library only**: Native JSON parsing, structured error handling via `urllib.error`, built-in argument parsing via `argparse`, and process memory safety via `subprocess`.
## Decision
We will implement `new-repo` in **Python 3 using only the standard library** (`urllib.request`, `argparse`, `json`, `subprocess`, `dataclasses`, `typing`).
To maintain the rigor initially sought in Rust:
- The codebase will enforce strict static type hints validated via **Pyright**.
- Code quality, modern Python idiom adherence, and formatting will be continuously enforced via **Ruff**.
## Consequences
### Good
- **Zero Build Step**: Edits are immediately executable without compilation or binary relinking.
- **Zero External Dependencies**: Works out of the box on any system with Python 3.10+ without virtual environments, `pip install`, or wheel caching.
- **Clean JSON Handling**: Native Python dictionaries serialize cleanly to JSON, avoiding escaping and quoting bugs inherent in shell scripts.
- **High Type Safety**: Strict Pyright type checking provides confidence similar to compiled languages without the build overhead.
### Bad
- **No Standalone Static Binary**: Requires an installed Python 3 interpreter on the host machine.
- **Slightly More Verbose HTTP Calls**: `urllib.request` requires more explicit request/header construction than third-party libraries like `httpx` or `requests`.
### Neutral
- Formatting and linting must be maintained using `ruff format` and `ruff check`.
@@ -0,0 +1,46 @@
# ADR 002: Environment Variables as Primary Configuration Interface with Pluggable Secret Resolvers
## Status
Accepted (2026-10-09)
## Context
When automating infrastructure and repository creation across multiple git forges, credentials (API tokens) are required for both Gitea and GitHub.
In the author's primary workstation environment, secrets are managed securely using Mozilla SOPS and Age encryption keys, ensuring tokens never touch disk in plaintext.
However, hard-coding a strict dependency on SOPS, specific filesystem paths (like `~/Config/secrets.yaml`), or NixOS packaging creates tight environmental coupling:
1. If a collaborator, CI pipeline, or developer outside Nix wants to run `new-repo`, they would be blocked by missing SOPS keys and hardcoded local paths.
2. If the author runs the script in temporary containers, GitHub Actions, or alternative workstations, it would fail unless SOPS was configured.
We need a design that satisfies two seemingly conflicting requirements:
- **Maximum Portability**: The tool must run anywhere with standard, universal configuration conventions.
- **Zero Friction on Host**: The author should not have to manually export sensitive tokens in every shell session on their primary workstation.
## Decision
We will establish **12-Factor Environment Variables as the primary configuration contract** for `new-repo`:
- `GITEA_TOKEN`: Personal access token for Gitea REST API.
- `GITHUB_TOKEN`: Personal access token for GitHub REST API.
- `GITEA_URL`: Base URL of the Gitea instance (defaults to `https://gitea.roadtotech.me`).
- `GITEA_USER`: Gitea account owner (defaults to `kiskaadee`).
- `GITHUB_USER`: GitHub account owner (defaults to `kiskaadee`).
To provide zero-friction ergonomics on the author's workstation, the `SecretProvider` will implement a multi-tier fallback resolution hierarchy:
1. **Tier 1 (Explicit Environment)**: Use environment variables if set in the current process.
2. **Tier 2 (Local `.env` File)**: Check for a local `.env` file if present.
3. **Tier 3 (SOPS Decoupled Workstation Secrets)**: If environment variables are absent, invoke `sops -d --extract` against `~/Config/secrets.yaml`.
4. **Tier 4 (Local Client Configurations)**:
- For Gitea: Check `~/.config/tea/config.yml` (official Gitea CLI login).
- For GitHub: Fall back to legacy `~/Homelab/Core/nixos/secrets.yaml` if workstation secrets have not yet migrated.
## Consequences
### Good
- **Universal Portability**: Anyone outside NixOS or without SOPS can execute the script immediately simply by running `export GITEA_TOKEN=... GITHUB_TOKEN=...; new-repo my-app`.
- **Zero Host Friction**: On the author's laptop, the script resolves tokens silently and safely from SOPS without manual shell exports.
- **Process Memory Safety**: Regardless of whether tokens come from environment variables or SOPS, they are handled strictly in memory and injected via HTTPS request headers, never exposed to `/proc/$PID/cmdline` or subprocess arguments.
- **CI/CD Compatibility**: In automated pipelines, standard secret injection (`GITEA_TOKEN`, `GITHUB_TOKEN`) works without modification.
### Bad
- The script includes fallback extraction logic (~40 lines) for SOPS and tea YAML files, which is unused when pure environment variables are provided.
### Neutral
- Standardized environment variable naming conventions (`GITEA_TOKEN`, `GITHUB_TOKEN`) must be clearly documented in the project README.
@@ -0,0 +1,40 @@
# ADR 003: Dual-Forge Topology with Automated Push Mirroring and Retain-and-Report Error Policy
## Status
Accepted (2026-10-09)
## Context
In a sovereign, self-hosted developer environment:
1. **Local Autonomy**: Developers need primary repositories hosted on a private forge (`gitea.roadtotech.me`) to eliminate dependencies on third-party cloud availability, allow high-bandwidth local pushes, and enable local CI/CD pipelines.
2. **Cloud Redundancy**: Offsite disaster recovery is required. If local storage fails or the self-hosted server experiences downtime, code should be preserved on a redundant offsite cloud provider (GitHub).
3. **Operational Overhead**: Manually maintaining dual remotes locally (`git push origin && git push github`) creates cognitive load, is prone to developer forgetfulness, and breaks single-remote automation.
4. **Failure Modes**: When automating a multi-stage remote provisioning pipeline across two external network services, network partitions, authentication errors, or rate limits can cause a failure midway through the sequence.
## Decision
1. **Asymmetric Push Mirror Architecture**:
- Gitea is the authoritative primary forge for all new repositories.
- GitHub is an automated backup mirror target.
- When provisioning, `new-repo` creates the repository on Gitea (with initial license and commit) and creates a completely empty target repository on GitHub (`auto_init=False`).
- `new-repo` configures Gitea's internal push mirror daemon (`POST /api/v1/repos/{owner}/{repo}/push_mirrors`) with `sync_on_commit=True`.
- The developer interacts exclusively with Gitea (`origin`). Gitea automatically synchronizes all branches, tags, and commits to GitHub in the background.
2. **Auto-Clone by Default**:
- Following remote provisioning, `new-repo` clones the repository locally into `$PWD/<name>` by default, enabling the developer to immediately begin work. A `--no-clone` flag is provided to bypass local filesystem operations.
3. **Retain & Report Error Recovery Policy**:
- If GitHub repository creation or push mirror registration fails after Gitea repository creation has succeeded, the tool will **not** roll back or delete the Gitea repository.
- Deleting remote repositories autonomously on partial failure poses catastrophic data-loss risks if the failure was transient.
- Instead, the tool reports actionable diagnostic warnings, prints the URL of the surviving Gitea repository, and exits cleanly.
## Consequences
### Good
- **Single Remote Simplicity**: The developer pushes to `origin` (Gitea) as normal; cloud backups happen asynchronously and server-side.
- **Disaster Proof**: Cloud backup is guaranteed without relying on local git hooks or manual multi-remote pushes.
- **Safe Recovery**: Transient network or GitHub quota errors do not blow away newly created repositories.
- **Immediate Ergonomics**: Running `new-repo my-app` leaves the user inside their cloned directory ready to code.
### Bad
- GitHub Personal Access Token must be stored inside Gitea's push mirror configuration so Gitea's worker can authenticate against GitHub.
### Neutral
- If a push mirror is disrupted, sync status must be inspected via Gitea's repository settings web interface.
@@ -0,0 +1,43 @@
# ADR 004: Existing Repository Linking and Auto-Detection
## Status
Accepted (2026-10-10)
## Context
Initial iterations of `new-repo` assumed a purely greenfield workflow:
1. Create a remote repository on Gitea with `auto_init=True` (generating an initial commit with a README and license).
2. Create an empty backup repository on GitHub.
3. Register Gitea push mirroring.
4. Clone the newly generated repository into `$PWD/<name>`.
However, in daily developer workflows, repositories frequently already exist locally:
- A developer starts prototyping code locally before provisioning remotes.
- An existing standalone repository needs sovereign Gitea hosting and GitHub offsite backup attached.
If executed against an existing local repository:
- Creating the remote on Gitea with `auto_init=True` generates a remote initial commit that diverges from local commits, causing git history conflicts (`fatal: refusing to merge unrelated histories`).
- Skipping the local clone step without adding `origin` or pushing commits leaves the developer with an empty remote and unlinked local working tree.
## Decision
We will add **first-class existing repository support and auto-detection** to `new-repo`:
1. **Target & Name Resolution**:
- If `name` is omitted or passed as `.`, `new-repo` uses the current working directory name and targets `$PWD`.
- If `name` matches the current directory or points to an existing directory containing `.git`, the utility switches into *Existing Repository Mode*.
2. **Empty Remote Creation**:
- When linking an existing repository, Gitea is provisioned with `auto_init=False` and no license generation. Both Gitea and GitHub remotes are initialized completely empty.
3. **Local Remote Wiring & Push**:
- `new-repo` configures `origin` on the local repository pointing to `git@<gitea-host>:<user>/<repo>.git`.
- The tool detects the current active branch (defaulting to `main`) and pushes with upstream tracking (`git push -u origin <branch>`).
- Server-side, Gitea automatically synchronizes all pushed commits to GitHub via the registered push mirror.
## Consequences
### Good
- **Unified Command**: `new-repo` handles both greenfield project generation and remote attachment for existing local code with the same interface.
- **Commit Lineage Preserved**: Eliminates divergent history conflicts by ensuring remote forges remain empty until the local branch is pushed.
- **Developer Ergonomics**: Running `new-repo` inside any existing git project immediately binds it to sovereign dual-forge infrastructure in one step.
### Bad
- The script now requires read/write access to local `.git` configuration and executes local `git remote` and `git push` commands.
### Neutral
- If `origin` already exists, `new-repo` updates the remote URL to the primary Gitea instance.
@@ -0,0 +1,55 @@
# ADR 005: GitHub-to-Gitea Migration with Automated Push Mirroring
## Status
Accepted (2026-10-10)
## Context
Developers frequently have existing repositories hosted on GitHub—either legacy projects created before establishing a sovereign homelab forge, forks of upstream codebases, or collaborative work.
To integrate these projects into the sovereign dual-forge architecture, the repository must be:
1. Replicated onto the private Gitea instance with complete commit history, branches, and tags.
2. Configured with automated push mirroring so future commits pushed to Gitea automatically sync back to GitHub.
3. Linked locally so active development targets Gitea as the primary remote (`origin`) while retaining GitHub as a secondary remote.
Performing these steps manually involves navigating web UIs, copying tokens, configuring mirror settings, and executing manual Git remote renames and upstream branch tracking commands. Furthermore, performing the import via client-side clone and push consumes client storage and upload bandwidth.
## Decision
We introduce a dedicated `--migrate [GITHUB_URL]` option to `new-repo`:
1. **Target Parsing & Auto-Detection**:
- Accepts HTTPS URLs (`https://github.com/owner/repo`), SSH URLs (`git@github.com:owner/repo.git`), and shorthands (`owner/repo`).
- If the target URL is omitted, `new-repo` auto-detects the GitHub target from the local repository's `origin` remote.
- Positional `name` argument can override the repository name on Gitea if desired.
2. **Pre-flight Conflict Validation**:
- Before attempting migration, `new-repo` queries `GET /api/v1/repos/{owner}/{name}` on Gitea.
- If a repository with the same name already exists on Gitea, the migration aborts immediately with an informative error to prevent overwriting or state corruption.
3. **Server-Side Import via Gitea Migration API**:
- Calls Gitea's `POST /api/v1/repos/migrate` with `service="github"`, `mirror=False`, and the GitHub personal access token.
- Gitea performs a direct server-to-server clone of all branches, tags, and commit history without routing data through the local machine.
4. **Automated Push Mirror Registration**:
- Unless `--no-mirror` is specified, registers the GitHub repository as a Gitea push mirror with `sync_on_commit: true` and an 8-hour sync interval.
- This establishes Gitea as the authoritative primary forge and GitHub as the automated replica.
5. **Local Remote Reconfiguration**:
- If executed inside a Git repository tracking the target GitHub repository:
- Renames the existing `origin` remote to `github` (preserving direct access to the GitHub remote).
- Sets Gitea as the new `origin` remote (`git@<gitea-host>:<user>/<repo>.git`).
- Updates upstream tracking for the active branch (`git branch --set-upstream-to=origin/<branch> <branch>`).
- If executed outside a Git repository, clones the newly created Gitea repository locally unless `--no-clone` is passed.
## Consequences
### Good
- **Zero Client Bandwidth Overhead**: Full repository history, branches, and tags transfer directly between GitHub and Gitea servers.
- **Atomic Topology Transition**: Converts a GitHub-only repository into a sovereign dual-forge topology with push mirroring in a single command.
- **Preserved Remote Access**: Retaining GitHub as `github` remote maintains convenient access to GitHub-specific tooling or secondary remotes.
- **Fail-Safe Conflict Protection**: Pre-flight existence checks prevent accidental destructive overwrites.
### Bad
- Requires a GitHub personal access token with repository read permissions and a Gitea token with `write:user` and `write:repository` scopes.
### Neutral
- Standardizes on writable repository migration with reverse push mirroring rather than Gitea read-only pull mirrors.
@@ -0,0 +1,46 @@
# ADR 006: Gitea Organization Binding and Auto-Provisioning
## Status
Accepted (2026-10-18)
## Context
As projects scale beyond flat personal repositories into structured domains (such as `homelab` infrastructure, `sites`, or shared tooling), organizing repositories under Gitea organizations provides logical grouping, cleaner namespace separation, and fine-grained team/access control.
Previously, `new-repo` hardcoded `creds.gitea_user` across all Gitea API endpoints (`/api/v1/user/repos`, template generation, migration, and push mirror registration) and local SSH remote URLs (`git@<host>:<user>/<repo>.git`). Creating a repository under a Gitea organization required manual creation via the Gitea web UI followed by manual remote and mirror configuration.
## Decision
We extend `new-repo` to support binding repositories to a Gitea organization across all provisioning workflows (standard greenfield creation, existing local repository linking, template generation, and GitHub-to-Gitea migration):
1. **Flexible CLI Target Specification**:
- Support both an explicit `-o` / `--org <ORG>` flag and positional `<org>/<repo>` shorthand (e.g., `new-repo homelab/core` or `new-repo core -o homelab`).
- Validate and reject conflicting organization names if both forms are provided with mismatched values.
2. **Automatic Organization Provisioning on Gitea**:
- Before provisioning or migrating a repository under a target organization, `new-repo` checks whether the organization exists via `GET /api/v1/orgs/{org}`.
- If the organization returns `404 Not Found`, `new-repo` automatically provisions it via `POST /api/v1/orgs` with visibility matching the repository's privacy flag (`public` by default, or `private` when `--private` is passed).
3. **Endpoint Routing Across Workflows**:
- **Standard & Existing Git Creation**: Routes to `POST /api/v1/orgs/{org}/repos` when an organization is specified, or `POST /api/v1/user/repos` otherwise.
- **Template Generation**: Passes `"owner": gitea_owner` to `POST /api/v1/repos/{tmpl_owner}/{tmpl_name}/generate`.
- **GitHub Migration**: Passes `"repo_owner": gitea_owner` to `POST /api/v1/repos/migrate` and checks `GET /api/v1/repos/{gitea_owner}/{dest_name}` for pre-flight conflict detection.
- **Push Mirroring**: Registers push mirrors at `POST /api/v1/repos/{gitea_owner}/{repo_name}/push_mirrors`.
4. **Decoupled GitHub Mirror Ownership**:
- Offsite GitHub backup mirrors continue to default to the personal `GITHUB_USER` account (`POST /user/repos`) so users do not need matching GitHub organizations for internal Gitea namespaces.
- An optional `--github-org <GITHUB_ORG>` flag allows routing the GitHub mirror target to `POST /orgs/{org}/repos` when desired.
5. **Flat Local Directory Resolution**:
- Local clones and working tree detection remain flat (`<cwd>/<repo_name>` or `<cwd>` if already inside `<repo_name>`), matching standard `git clone` ergonomics regardless of whether an organization prefix was used.
## Consequences
### Good
- **Zero-Friction Namespace Organization**: Repositories can be grouped under existing or brand-new Gitea organizations in a single CLI invocation.
- **Ergonomic CLI**: Supports both intuitive `org/repo` shorthand and explicit `-o org` flags (useful when inferring the repo name from the current directory via `new-repo -o homelab`).
- **Decoupled Forge Topologies**: Gitea organizations can be used freely for self-hosted categorization without forcing corresponding organization setup on GitHub.
### Bad
- Requires the Gitea Personal Access Token (`GITEA_TOKEN`) to include `write:organization` (or `admin:org`) scope when checking or auto-creating organizations.
### Neutral
- If two different Gitea organizations contain repositories with the exact same name and both mirror to the same personal GitHub account, a naming collision on GitHub will occur (mitigated by `new-repo`'s retain-and-report policy or `--no-mirror` / `--github-org`).
+974 -193
View File
File diff suppressed because it is too large. Load diff
+715 -5
View File
@@ -3,11 +3,28 @@
from __future__ import annotations from __future__ import annotations
import io
import os
import subprocess
import tempfile import tempfile
import unittest import unittest
import urllib.error
from email.message import Message
from pathlib import Path from pathlib import Path
from unittest.mock import MagicMock, patch
from new_repo import SecretProvider, parse_args from new_repo import (
GiteaClient,
GitHubClient,
SecretProvider,
determine_target,
normalize_license,
parse_args,
parse_github_target,
reconfigure_local_remotes,
redact_sensitive,
resolve_name_and_org,
)
class TestArgParsing(unittest.TestCase): class TestArgParsing(unittest.TestCase):
@@ -19,11 +36,50 @@ class TestArgParsing(unittest.TestCase):
sys.argv = ["new-repo", "sample-project"] sys.argv = ["new-repo", "sample-project"]
args = parse_args() args = parse_args()
self.assertEqual(args.name, "sample-project") self.assertEqual(args.name, "sample-project")
self.assertFalse(args.public) self.assertIsNone(args.org)
self.assertEqual(args.license, "UNLICENSE") self.assertIsNone(args.gitea_org)
self.assertFalse(args.private)
self.assertEqual(args.license, "unlicense")
self.assertIsNone(args.template) self.assertIsNone(args.template)
self.assertFalse(args.no_mirror) self.assertFalse(args.no_mirror)
self.assertFalse(args.no_clone) self.assertFalse(args.no_clone)
self.assertFalse(args.empty)
self.assertIsNone(args.as_persona)
self.assertIsNone(args.gitea_mirror)
def test_empty_argument(self) -> None:
import sys
sys.argv = ["new-repo", "sample-project", "--empty", "--no-mirror", "--no-clone"]
args = parse_args()
self.assertTrue(args.empty)
self.assertTrue(args.no_mirror)
self.assertTrue(args.no_clone)
def test_as_persona_argument(self) -> None:
import sys
sys.argv = ["new-repo", "sample-project", "--as", "anneux"]
args = parse_args()
self.assertEqual(args.as_persona, "anneux")
def test_gitea_mirror_arguments(self) -> None:
import sys
sys.argv = ["new-repo", "--gitea-mirror"]
args = parse_args()
self.assertEqual(args.gitea_mirror, "")
sys.argv = ["new-repo", "--gitea-mirror", "https://github.com/octocat/Hello-World"]
args = parse_args()
self.assertEqual(args.gitea_mirror, "https://github.com/octocat/Hello-World")
def test_omitted_name_defaults_to_none(self) -> None:
import sys
sys.argv = ["new-repo"]
args = parse_args()
self.assertIsNone(args.name)
def test_custom_flags(self) -> None: def test_custom_flags(self) -> None:
import sys import sys
@@ -31,7 +87,11 @@ class TestArgParsing(unittest.TestCase):
sys.argv = [ sys.argv = [
"new-repo", "new-repo",
"open-api", "open-api",
"--public", "-o",
"my-gh-org",
"--gitea-org",
"homelab",
"--private",
"-d", "-d",
"My public API", "My public API",
"-l", "-l",
@@ -43,12 +103,210 @@ class TestArgParsing(unittest.TestCase):
] ]
args = parse_args() args = parse_args()
self.assertEqual(args.name, "open-api") self.assertEqual(args.name, "open-api")
self.assertTrue(args.public) self.assertEqual(args.org, "my-gh-org")
self.assertEqual(args.gitea_org, "homelab")
self.assertTrue(args.private)
self.assertEqual(args.description, "My public API") self.assertEqual(args.description, "My public API")
self.assertEqual(args.license, "MIT") self.assertEqual(args.license, "MIT")
self.assertEqual(args.template, "template-fastapi") self.assertEqual(args.template, "template-fastapi")
self.assertTrue(args.no_mirror) self.assertTrue(args.no_mirror)
self.assertTrue(args.no_clone) self.assertTrue(args.no_clone)
self.assertIsNone(args.gitea_mirror)
class TestLicenseNormalization(unittest.TestCase):
"""Test license identifier normalization against GitHub's lowercase registry."""
def test_unlicense_casing_variants(self) -> None:
self.assertEqual(normalize_license("UNLICENSE"), "unlicense")
self.assertEqual(normalize_license("unlicense"), "unlicense")
self.assertEqual(normalize_license("Unlicense"), "unlicense")
def test_common_licenses_case_insensitivity(self) -> None:
self.assertEqual(normalize_license("mit"), "mit")
self.assertEqual(normalize_license("MIT"), "mit")
self.assertEqual(normalize_license("apache-2.0"), "apache-2.0")
self.assertEqual(normalize_license("APACHE-2.0"), "apache-2.0")
self.assertEqual(normalize_license("gpl-3.0"), "gpl-3.0")
self.assertEqual(normalize_license("bsd-3-clause"), "bsd-3-clause")
def test_empty_and_whitespace_licenses(self) -> None:
self.assertEqual(normalize_license(""), "")
self.assertEqual(normalize_license(" "), "")
self.assertEqual(normalize_license(None), "")
def test_unrecognized_license_lowercase(self) -> None:
self.assertEqual(normalize_license("Custom-Proprietary"), "custom-proprietary")
def test_github_client_create_repo_normalizes_license(self) -> None:
client = GitHubClient("kiskaadee", "secret-token")
with patch.object(client, "_request", return_value={}) as mock_req:
client.create_repo(
"my-repo", auto_init=True, license_template="UNLICENSE"
)
mock_req.assert_called_once()
payload = mock_req.call_args[0][2]
self.assertEqual(payload["license_template"], "unlicense")
self.assertTrue(payload["auto_init"])
with patch.object(client, "_request", return_value={}) as mock_req:
client.create_repo("my-repo-no-license", auto_init=True, license_template="")
mock_req.assert_called_once()
payload = mock_req.call_args[0][2]
self.assertNotIn("license_template", payload)
def test_gitea_migrate_repo_supports_pull_mirror(self) -> None:
client = GiteaClient("https://gitea.local", "kiskaadee", "secret-token")
with patch.object(client, "_request", return_value={}) as mock_req:
client.migrate_repo(
clone_addr="https://github.com/kiskaadee/my-repo.git",
repo_name="my-repo",
github_token="gh-secret",
private=True,
repo_owner="kiskaadee",
mirror=True,
)
mock_req.assert_called_once()
payload = mock_req.call_args[0][2]
self.assertTrue(payload["mirror"])
self.assertTrue(payload["private"])
self.assertEqual(payload["service"], "github")
class TestOrganizationAndTargetResolution(unittest.TestCase):
"""Test resolution of repository names, org/repo shorthands, and flat local paths."""
def test_resolve_name_and_org_variants(self) -> None:
self.assertEqual(resolve_name_and_org("my-repo", None), ("my-repo", None))
self.assertEqual(
resolve_name_and_org("my-repo", "homelab"), ("my-repo", "homelab")
)
self.assertEqual(
resolve_name_and_org("homelab/my-repo", None), ("my-repo", "homelab")
)
self.assertEqual(
resolve_name_and_org("homelab/my-repo", "homelab"), ("my-repo", "homelab")
)
self.assertEqual(resolve_name_and_org(None, "homelab"), (None, "homelab"))
self.assertEqual(resolve_name_and_org(".", "homelab"), (None, "homelab"))
def test_resolve_name_and_org_conflicts_and_invalid(self) -> None:
with self.assertRaises(ValueError):
resolve_name_and_org("org1/my-repo", "org2")
with self.assertRaises(ValueError):
resolve_name_and_org("a/b/c", None)
with self.assertRaises(ValueError):
resolve_name_and_org("/leading-slash", None)
with self.assertRaises(ValueError):
resolve_name_and_org("trailing-slash/", None)
def test_determine_target_flat_directory_for_org_shorthand(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
cwd = Path(tmpdir)
repo_name, target_dir, is_existing_git, target_org = determine_target(
"homelab/core", None, cwd=cwd
)
self.assertEqual(repo_name, "core")
self.assertEqual(target_dir, cwd / "core")
self.assertFalse(is_existing_git)
self.assertEqual(target_org, "homelab")
def test_determine_target_inside_matching_directory(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
repo_dir = Path(tmpdir) / "core"
repo_dir.mkdir()
(repo_dir / ".git").mkdir()
repo_name, target_dir, is_existing_git, target_org = determine_target(
"homelab/core", None, cwd=repo_dir
)
self.assertEqual(repo_name, "core")
self.assertEqual(target_dir, repo_dir)
self.assertTrue(is_existing_git)
self.assertEqual(target_org, "homelab")
class TestApiClientOrganizationRouting(unittest.TestCase):
"""Test GiteaClient and GitHubClient organization endpoint routing."""
def test_gitea_create_repo_personal_vs_org(self) -> None:
client = GiteaClient("https://gitea.local", "kiskaadee", "secret-token")
with patch.object(client, "_request", return_value={}) as mock_req:
client.create_repo("personal-repo")
mock_req.assert_called_once()
self.assertEqual(mock_req.call_args[0][1], "/api/v1/user/repos")
with patch.object(client, "_request", return_value={}) as mock_req:
client.create_repo("org-repo", org="homelab")
mock_req.assert_called_once()
self.assertEqual(mock_req.call_args[0][1], "/api/v1/orgs/homelab/repos")
def test_gitea_ensure_org_creates_when_missing(self) -> None:
client = GiteaClient("https://gitea.local", "kiskaadee", "secret-token")
with (
patch.object(client, "org_exists", return_value=False) as mock_exists,
patch.object(client, "create_org", return_value={}) as mock_create,
):
created = client.ensure_org("homelab", private=True)
self.assertTrue(created)
mock_exists.assert_called_once_with("homelab")
mock_create.assert_called_once_with("homelab", visibility="private")
def test_gitea_ensure_org_skips_when_existing(self) -> None:
client = GiteaClient("https://gitea.local", "kiskaadee", "secret-token")
with (
patch.object(client, "org_exists", return_value=True) as mock_exists,
patch.object(client, "create_org", return_value={}) as mock_create,
):
created = client.ensure_org("homelab", private=True)
self.assertFalse(created)
mock_exists.assert_called_once_with("homelab")
mock_create.assert_not_called()
def test_gitea_push_mirror_and_template_and_migrate_owner(self) -> None:
client = GiteaClient("https://gitea.local", "kiskaadee", "secret-token")
with patch.object(client, "_request", return_value={}) as mock_req:
client.create_push_mirror(
"core",
"https://github.com/kiskaadee/core.git",
"kiskaadee",
"gh-token",
owner="homelab",
)
self.assertEqual(
mock_req.call_args[0][1], "/api/v1/repos/homelab/core/push_mirrors"
)
with patch.object(client, "_request", return_value={}) as mock_req:
client.generate_from_template(
"homelab", "tmpl", "new-service", owner="homelab"
)
self.assertEqual(mock_req.call_args[0][2]["owner"], "homelab")
with patch.object(client, "_request", return_value={}) as mock_req:
client.migrate_repo(
"https://github.com/kiskaadee/core.git",
"core",
"gh-token",
repo_owner="homelab",
)
self.assertEqual(mock_req.call_args[0][2]["repo_owner"], "homelab")
def test_github_create_empty_repo_personal_vs_org(self) -> None:
gh_client = GitHubClient("kiskaadee", "gh-token")
mock_resp = MagicMock()
mock_resp.read.return_value = b"{}"
mock_resp.__enter__.return_value = mock_resp
with patch("urllib.request.urlopen", return_value=mock_resp) as mock_urlopen:
gh_client.create_empty_repo("core")
req_personal = mock_urlopen.call_args[0][0]
self.assertEqual(req_personal.full_url, "https://api.github.com/user/repos")
gh_client.create_empty_repo("core", org="homelab-gh")
req_org = mock_urlopen.call_args[0][0]
self.assertEqual(
req_org.full_url, "https://api.github.com/orgs/homelab-gh/repos"
)
class TestDotenvLoader(unittest.TestCase): class TestDotenvLoader(unittest.TestCase):
@@ -71,5 +329,457 @@ class TestDotenvLoader(unittest.TestCase):
self.assertEqual(loaded.get("GITEA_USER"), "custom-user") self.assertEqual(loaded.get("GITEA_USER"), "custom-user")
class TestGiteaClientUser(unittest.TestCase):
"""Test GiteaClient user inspection methods."""
def test_gitea_client_get_authenticated_user(self) -> None:
client = GiteaClient("https://gitea.local", "kiskaadee", "secret-token")
with patch.object(client, "_request", return_value={"username": "kiskaadee"}):
self.assertEqual(client.get_authenticated_user(), "kiskaadee")
class TestSecretResolutionPrecedence(unittest.TestCase):
"""Test deterministic precedence hierarchy for credential discovery."""
def setUp(self) -> None:
self.orig_env = os.environ.copy()
for k in list(os.environ.keys()):
if k.startswith(("GITEA_", "GITHUB_", "NEW_REPO_", "TEA_", "SECRETS_FILE", "HOMELAB_")):
del os.environ[k]
def tearDown(self) -> None:
os.environ.clear()
os.environ.update(self.orig_env)
def test_resolve_from_direct_env_vars(self) -> None:
os.environ["GITEA_URL"] = "https://gitea.custom.io"
os.environ["GITEA_USER"] = "alice"
os.environ["GITEA_TOKEN"] = "token-alice-env"
os.environ["GITHUB_USER"] = "alice-gh"
os.environ["GITHUB_TOKEN"] = "token-alice-gh-env"
creds = SecretProvider.resolve()
self.assertEqual(creds.gitea_url, "https://gitea.custom.io")
self.assertEqual(creds.gitea_user, "alice")
self.assertEqual(creds.gitea_token, "token-alice-env")
self.assertEqual(creds.github_user, "alice-gh")
self.assertEqual(creds.github_token, "token-alice-gh-env")
def test_resolve_from_local_dotenv(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
dotenv_file = Path(tmpdir) / ".env"
dotenv_file.write_text(
"GITEA_URL=https://gitea.dotenv.io\n"
"GITEA_USER=dotenv-user\n"
"GITEA_TOKEN=token-dotenv-123\n"
"GITHUB_USER=dotenv-gh-user\n"
"GITHUB_TOKEN=token-gh-dotenv-456\n"
)
with patch("pathlib.Path.cwd", return_value=Path(tmpdir)), \
patch.object(SecretProvider, "_extract_sops_key", return_value=None), \
patch.object(SecretProvider, "_extract_gt_token", return_value=None):
creds = SecretProvider.resolve()
self.assertEqual(creds.gitea_url, "https://gitea.dotenv.io")
self.assertEqual(creds.gitea_user, "dotenv-user")
self.assertEqual(creds.gitea_token, "token-dotenv-123")
self.assertEqual(creds.github_user, "dotenv-gh-user")
self.assertEqual(creds.github_token, "token-gh-dotenv-456")
def test_direct_env_overrides_dotenv(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
dotenv_file = Path(tmpdir) / ".env"
dotenv_file.write_text(
"GITEA_TOKEN=dotenv-token\n"
"GITHUB_TOKEN=dotenv-gh-token\n"
)
os.environ["GITEA_TOKEN"] = "env-token-override"
with patch("pathlib.Path.cwd", return_value=Path(tmpdir)), \
patch.object(SecretProvider, "_extract_sops_key", return_value=None), \
patch.object(SecretProvider, "_extract_gt_token", return_value=None):
creds = SecretProvider.resolve()
self.assertEqual(creds.gitea_token, "env-token-override")
self.assertEqual(creds.github_token, "dotenv-gh-token")
def test_resolve_from_default_sops(self) -> None:
def fake_extract_sops(key_path: list[str], secrets_file: Path) -> str | None:
if key_path == ["gitea", "token"] or key_path == ["gitea", "api_token"]:
return "sops-gitea-token"
if key_path == ["system", "gh_repo_token"]:
return "sops-github-token"
return None
with (
tempfile.TemporaryDirectory() as tmpdir,
patch("pathlib.Path.cwd", return_value=Path(tmpdir)),
patch.object(SecretProvider, "_extract_sops_key", side_effect=fake_extract_sops),
patch.object(SecretProvider, "_extract_gt_token", return_value=None),
):
creds = SecretProvider.resolve()
self.assertEqual(creds.gitea_token, "sops-gitea-token")
self.assertEqual(creds.github_token, "sops-github-token")
self.assertEqual(creds.gitea_user, "kiskaadee")
def test_resolve_from_gt_host_fallback(self) -> None:
def fake_extract_sops(key_path: list[str], secrets_file: Path) -> str | None:
if key_path == ["system", "gh_repo_token"]:
return "sops-github-token"
return None
with (
tempfile.TemporaryDirectory() as tmpdir,
patch("pathlib.Path.cwd", return_value=Path(tmpdir)),
patch.object(SecretProvider, "_extract_sops_key", side_effect=fake_extract_sops),
patch.object(SecretProvider, "_extract_gt_token", return_value="gt-cli-token"),
):
creds = SecretProvider.resolve()
self.assertEqual(creds.gitea_token, "gt-cli-token")
self.assertEqual(creds.github_token, "sops-github-token")
def test_missing_credentials_exits_cleanly(self) -> None:
with (
tempfile.TemporaryDirectory() as tmpdir,
patch("pathlib.Path.cwd", return_value=Path(tmpdir)),
patch.object(SecretProvider, "_extract_sops_key", return_value=None),
patch.object(SecretProvider, "_extract_gt_token", return_value=None),
self.assertRaises(SystemExit),
):
SecretProvider.resolve()
class TestPersonaIsolation(unittest.TestCase):
"""Test strict persona isolation and non-fallback guarantees."""
def setUp(self) -> None:
self.orig_env = os.environ.copy()
for k in list(os.environ.keys()):
if k.startswith(("GITEA_", "GITHUB_", "NEW_REPO_", "TEA_", "SECRETS_FILE", "HOMELAB_")):
del os.environ[k]
def tearDown(self) -> None:
os.environ.clear()
os.environ.update(self.orig_env)
def test_persona_resolves_from_persona_sops(self) -> None:
def fake_sops(key_path: list[str], secrets_file: Path) -> str | None:
if "anne" in str(secrets_file):
if key_path in (["gitea", "token"], ["gitea", "api_token"]):
return "anne-gitea-token"
if key_path in (["github", "token"], ["github", "api_token"]):
return "anne-github-token"
return None
with (
tempfile.TemporaryDirectory() as tmpdir,
patch("pathlib.Path.home", return_value=Path(tmpdir)),
patch.object(SecretProvider, "_extract_sops_key", side_effect=fake_sops),
patch.object(SecretProvider, "_extract_gt_token", return_value=None),
):
cfg_dir = Path(tmpdir) / "Config"
cfg_dir.mkdir()
(cfg_dir / "secrets.anneux.yaml").write_text("dummy")
creds = SecretProvider.resolve(as_persona="anneux")
self.assertEqual(creds.gitea_user, "anneux")
self.assertEqual(creds.gitea_token, "anne-gitea-token")
self.assertEqual(creds.github_user, "anneux")
self.assertEqual(creds.github_token, "anne-github-token")
def test_persona_missing_fails_and_never_falls_through_to_default_sops(self) -> None:
def fake_sops(key_path: list[str], secrets_file: Path) -> str | None:
# Default secrets file has default user's tokens
if "secrets.yaml" in str(secrets_file) and not any(p in str(secrets_file) for p in ("anne", "unknown")):
if key_path in (["gitea", "token"], ["gitea", "api_token"]):
return "default-root-gitea-token"
if key_path == ["system", "gh_repo_token"]:
return "default-root-gh-token"
return None
with (
tempfile.TemporaryDirectory() as tmpdir,
patch("pathlib.Path.home", return_value=Path(tmpdir)),
patch.object(SecretProvider, "_extract_sops_key", side_effect=fake_sops),
patch.object(SecretProvider, "_extract_gt_token", return_value="default-gt-token"),
self.assertRaises(SystemExit),
):
SecretProvider.resolve(as_persona="unknown-agent")
def test_persona_missing_github_token_does_not_leak_default_gh_token(self) -> None:
def fake_sops(key_path: list[str], secrets_file: Path) -> str | None:
if "anne" in str(secrets_file) and key_path in (["gitea", "token"], ["gitea", "api_token"]):
return "anne-gitea-token"
if "secrets.yaml" in str(secrets_file) and key_path == ["system", "gh_repo_token"]:
return "default-root-gh-token"
return None
with tempfile.TemporaryDirectory() as tmpdir:
cfg_dir = Path(tmpdir) / "Config"
cfg_dir.mkdir()
(cfg_dir / "secrets.anneux.yaml").write_text("dummy")
with (
patch("pathlib.Path.home", return_value=Path(tmpdir)),
patch.object(SecretProvider, "_extract_sops_key", side_effect=fake_sops),
patch.object(SecretProvider, "_extract_gt_token", return_value=None),
self.assertRaises(SystemExit),
):
SecretProvider.resolve(as_persona="anneux")
def test_persona_does_not_use_conflicting_gitea_user_env(self) -> None:
os.environ["GITEA_USER"] = "kiskaadee"
os.environ["GITEA_TOKEN"] = "token-for-kiskaadee"
with (
tempfile.TemporaryDirectory() as tmpdir,
patch("pathlib.Path.home", return_value=Path(tmpdir)),
patch.object(SecretProvider, "_extract_sops_key", return_value=None),
patch.object(SecretProvider, "_extract_gt_token", return_value=None),
self.assertRaises(SystemExit),
):
SecretProvider.resolve(as_persona="anneux")
def test_persona_resolves_from_persona_env_token(self) -> None:
os.environ["GITEA_TOKEN_ANNEUX"] = "anne-env-token"
os.environ["GITHUB_TOKEN_ANNEUX"] = "anne-gh-env-token"
with (
tempfile.TemporaryDirectory() as tmpdir,
patch("pathlib.Path.home", return_value=Path(tmpdir)),
patch.object(SecretProvider, "_extract_sops_key", return_value=None),
patch.object(SecretProvider, "_extract_gt_token", return_value=None),
):
creds = SecretProvider.resolve(as_persona="anneux")
self.assertEqual(creds.gitea_token, "anne-env-token")
self.assertEqual(creds.github_token, "anne-gh-env-token")
self.assertEqual(creds.gitea_user, "anneux")
self.assertEqual(creds.github_user, "anneux")
class TestTokenRedaction(unittest.TestCase):
"""Test scrubbing and redaction of sensitive credentials on error paths."""
def test_redact_sensitive_scrubs_embedded_url_credentials(self) -> None:
raw = "Connection failed to https://alice:secret-token-12345@gitea.local/api/v1/user"
redacted = redact_sensitive(raw)
self.assertNotIn("secret-token-12345", redacted)
self.assertIn("[REDACTED]", redacted)
def test_redact_sensitive_scrubs_explicit_values(self) -> None:
raw = "API error: token token-xyz-98765 is invalid"
redacted = redact_sensitive(raw, "token-xyz-98765")
self.assertNotIn("token-xyz-98765", redacted)
self.assertEqual(redacted, "API error: token [REDACTED] is invalid")
def test_gitea_client_redacts_token_in_http_error(self) -> None:
client = GiteaClient("https://gitea.local", "kiskaadee", "secret-gitea-token-999")
error_body = b'{"message": "Unauthorized with secret-gitea-token-999"}'
mock_http_error = urllib.error.HTTPError(
url="https://gitea.local/api/v1/user",
code=401,
msg="Unauthorized with secret-gitea-token-999",
hdrs=Message(),
fp=io.BytesIO(error_body),
)
with patch("urllib.request.urlopen", side_effect=mock_http_error), \
self.assertRaises(RuntimeError) as ctx:
client._request("GET", "/api/v1/user")
self.assertNotIn("secret-gitea-token-999", str(ctx.exception))
self.assertIn("[REDACTED]", str(ctx.exception))
def test_github_client_redacts_token_in_http_error(self) -> None:
client = GitHubClient("kiskaadee", "secret-github-token-888")
error_body = b'{"message": "Bad credentials for secret-github-token-888"}'
mock_http_error = urllib.error.HTTPError(
url="https://api.github.com/user/repos",
code=401,
msg="Unauthorized for secret-github-token-888",
hdrs=Message(),
fp=io.BytesIO(error_body),
)
with patch("urllib.request.urlopen", side_effect=mock_http_error), \
self.assertRaises(RuntimeError) as ctx:
client.create_empty_repo("test-repo")
self.assertNotIn("secret-github-token-888", str(ctx.exception))
self.assertIn("[REDACTED]", str(ctx.exception))
def test_gitea_client_redacts_push_mirror_remote_password(self) -> None:
client = GiteaClient("https://gitea.local", "kiskaadee", "gitea-token")
error_body = b'{"message": "Mirror failed using remote password super-secret-pass-777"}'
mock_http_error = urllib.error.HTTPError(
url="https://gitea.local/api/v1/repos/kiskaadee/myrepo/push_mirrors",
code=400,
msg="Mirror failed",
hdrs=Message(),
fp=io.BytesIO(error_body),
)
with patch("urllib.request.urlopen", side_effect=mock_http_error), \
self.assertRaises(RuntimeError) as ctx:
client.create_push_mirror(
repo_name="myrepo",
remote_address="https://github.com/myorg/myrepo.git",
remote_username="ghuser",
remote_password="super-secret-pass-777",
)
self.assertNotIn("super-secret-pass-777", str(ctx.exception))
self.assertIn("[REDACTED]", str(ctx.exception))
class TestCLIHelpWithoutTea(unittest.TestCase):
"""Test CLI help executes without tea dependency."""
def test_help_executes_without_tea(self) -> None:
res = subprocess.run(
["python3", "new_repo.py", "--help"],
capture_output=True,
text=True,
check=False,
)
self.assertEqual(res.returncode, 0)
self.assertNotIn("tea login", res.stdout)
class TestTargetParsing(unittest.TestCase):
"""Test parsing of GitHub target URLs, SSH remotes, and shorthands."""
def test_parse_https_url(self) -> None:
dummy_dir = Path("/nonexistent/dir")
name, owner, url = parse_github_target(
"https://github.com/octocat/Hello-World", dummy_dir
)
self.assertEqual(name, "Hello-World")
self.assertEqual(owner, "octocat")
self.assertEqual(url, "https://github.com/octocat/Hello-World.git")
def test_parse_https_url_with_git_suffix(self) -> None:
dummy_dir = Path("/nonexistent/dir")
name, owner, url = parse_github_target(
"https://github.com/octocat/Hello-World.git", dummy_dir
)
self.assertEqual(name, "Hello-World")
self.assertEqual(owner, "octocat")
self.assertEqual(url, "https://github.com/octocat/Hello-World.git")
def test_parse_ssh_url(self) -> None:
dummy_dir = Path("/nonexistent/dir")
name, owner, url = parse_github_target(
"git@github.com:octocat/Hello-World.git", dummy_dir
)
self.assertEqual(name, "Hello-World")
self.assertEqual(owner, "octocat")
self.assertEqual(url, "https://github.com/octocat/Hello-World.git")
def test_parse_shorthand(self) -> None:
dummy_dir = Path("/nonexistent/dir")
name, owner, url = parse_github_target("octocat/Hello-World", dummy_dir)
self.assertEqual(name, "Hello-World")
self.assertEqual(owner, "octocat")
self.assertEqual(url, "https://github.com/octocat/Hello-World.git")
def test_parse_invalid_target_raises_value_error(self) -> None:
dummy_dir = Path("/nonexistent/dir")
with self.assertRaises(ValueError):
parse_github_target("not-a-repo", dummy_dir)
def test_auto_detect_outside_git_repo_raises_runtime_error(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir, self.assertRaises(RuntimeError):
parse_github_target(None, Path(tmpdir))
def test_auto_detect_inside_git_repo(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
repo_path = Path(tmpdir)
subprocess.run(
["git", "init", "-b", "main"],
cwd=repo_path,
check=True,
capture_output=True,
)
subprocess.run(
[
"git",
"remote",
"add",
"origin",
"git@github.com:myorg/cool-project.git",
],
cwd=repo_path,
check=True,
capture_output=True,
)
name, owner, url = parse_github_target("", repo_path)
self.assertEqual(name, "cool-project")
self.assertEqual(owner, "myorg")
self.assertEqual(url, "https://github.com/myorg/cool-project.git")
class TestReconfigureLocalRemotes(unittest.TestCase):
"""Test reconfiguring local git remotes on migration."""
def test_reconfigure_remotes_success(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
repo_path = Path(tmpdir)
subprocess.run(
["git", "init", "-b", "main"],
cwd=repo_path,
check=True,
capture_output=True,
)
subprocess.run(
["git", "config", "user.name", "Test User"],
cwd=repo_path,
check=True,
capture_output=True,
)
subprocess.run(
["git", "config", "user.email", "test@example.com"],
cwd=repo_path,
check=True,
capture_output=True,
)
subprocess.run(
[
"git",
"remote",
"add",
"origin",
"https://github.com/octocat/Hello-World.git",
],
cwd=repo_path,
check=True,
capture_output=True,
)
# Create a dummy commit
(repo_path / "README.md").write_text("# Hello World\n")
subprocess.run(
["git", "add", "."], cwd=repo_path, check=True, capture_output=True
)
subprocess.run(
["git", "commit", "-m", "Initial commit"],
cwd=repo_path,
check=True,
capture_output=True,
)
# Execute reconfiguration
gitea_target = "git@gitea.local:kiskaadee/Hello-World.git"
reconfigure_local_remotes(repo_path, gitea_target)
# Check that origin is now gitea
origin_url = subprocess.check_output(
["git", "remote", "get-url", "origin"],
cwd=repo_path,
text=True,
).strip()
self.assertEqual(origin_url, gitea_target)
# Check that github is now previous origin
github_url = subprocess.check_output(
["git", "remote", "get-url", "github"],
cwd=repo_path,
text=True,
).strip()
self.assertEqual(github_url, "https://github.com/octocat/Hello-World.git")
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()