Compare commits
10
Commits
717e326a2b
...
e72b46a42e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e72b46a42e | ||
|
|
c950ff2e73 | ||
|
|
aff2098f7f | ||
|
|
06cc3254c0 | ||
|
|
412fc3e77b | ||
|
|
75a09f2ad8 | ||
|
|
acdd91dd10 | ||
|
|
5c29be4fb7 | ||
|
|
2d0731ebe7 | ||
|
|
9d07c3ecd4 |
No files matched your search
@@ -1 +1,209 @@
|
||||
# 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**: A self-hosted Gitea instance for local sovereignty and CI/CD automation.
|
||||
- **Backup Forge**: GitHub for offsite redundancy via automated server-side push mirroring.
|
||||
|
||||
It automates the multi-step setup required to create a repository, establish push mirroring, and prepare a local working tree 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 backup mirror provisioning or push mirror registration encounters an error after the primary repository is created, the primary repository is preserved and diagnostic URLs are printed for manual review.
|
||||
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 Gitea organization to own the repository (auto-created if missing)
|
||||
--github-org ORG Optional GitHub organization for the offsite backup mirror (defaults to personal GITHUB_USER)
|
||||
--migrate [URL] Migrate an existing GitHub repo to Gitea with automated push mirroring (URL or auto-detect from local origin)
|
||||
-p, --private Make repository private (default: public)
|
||||
-d, --description Optional repository description string
|
||||
-l, --license License template identifier (default: Unlicense, pass "" to disable)
|
||||
-t, --template Optional Gitea template repository ('[owner/]template-name')
|
||||
-M, --no-mirror Disable automatic offsite push mirroring to GitHub
|
||||
--no-clone Skip cloning the repository locally after creation
|
||||
--as PERSONA Persona / login identity to provision as (matches tea login or SOPS persona, e.g. anneux)
|
||||
-h, --help Show help message and exit
|
||||
```
|
||||
|
||||
### Examples
|
||||
|
||||
```bash
|
||||
# 1. Standard greenfield creation (Public Gitea + GitHub push mirror + Unlicense + auto-clone)
|
||||
new-repo service-api
|
||||
|
||||
# 2. Provision as a specific agent persona (binds Gitea/GitHub credentials and SSH keys to persona)
|
||||
new-repo frontend-app --as anneux
|
||||
|
||||
# 2. Provision under a Gitea organization (via shorthand or -o/--org flag; auto-creates org if missing)
|
||||
new-repo homelab/core
|
||||
new-repo core -o homelab
|
||||
|
||||
# 3. Attach remotes & push an existing local repository (into personal account or organization)
|
||||
cd ~/Projects/my-existing-app
|
||||
new-repo -o homelab
|
||||
|
||||
# 4. Provision from an existing Gitea template
|
||||
new-repo web-client --template template-react-app
|
||||
|
||||
# 5. Local-only repository (no GitHub mirror)
|
||||
new-repo private-notes --no-mirror
|
||||
|
||||
# 6. Private repository with MIT license
|
||||
new-repo utility-lib --private --license MIT
|
||||
|
||||
# 7. Migrate an existing GitHub repository to Gitea (personal or organization) with push mirror
|
||||
new-repo --migrate https://github.com/my-org/existing-service
|
||||
new-repo homelab/existing-service --migrate https://github.com/my-org/existing-service
|
||||
|
||||
# 8. Migrate repository in-place from inside a local checkout
|
||||
cd ~/Projects/existing-service
|
||||
new-repo --migrate
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔐 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 Gitea as Gitea API (Primary)
|
||||
participant GitHub as GitHub API (Backup)
|
||||
participant Git as Local Git
|
||||
|
||||
User->>CLI: new-repo <repo-name> [flags]
|
||||
CLI->>SP: Resolve API credentials
|
||||
SP-->>CLI: Credentials (Gitea token, GitHub token)
|
||||
|
||||
alt Template Repo Specified (-t <template>)
|
||||
CLI->>Gitea: POST /api/v1/repos/{owner}/{template}/generate
|
||||
Gitea-->>CLI: Primary repository generated
|
||||
else Standard Repository
|
||||
CLI->>Gitea: POST /api/v1/user/repos (with license & auto-init)
|
||||
Gitea-->>CLI: Primary repository created
|
||||
end
|
||||
|
||||
opt Push Mirroring Enabled (Default)
|
||||
CLI->>GitHub: POST https://api.github.com/user/repos (empty target)
|
||||
GitHub-->>CLI: Mirror target created
|
||||
CLI->>Gitea: POST /api/v1/repos/{owner}/{repo}/push_mirrors
|
||||
Gitea-->>CLI: Push mirror registered (sync on commit)
|
||||
end
|
||||
|
||||
opt Local Clone Enabled (Default)
|
||||
CLI->>Git: git clone git@<gitea-host>:<user>/<repo>.git
|
||||
Git-->>CLI: Working tree cloned to ./<repo-name>
|
||||
end
|
||||
```
|
||||
|
||||
### Migration Workflow (`--migrate`)
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
autonumber
|
||||
actor User as Developer
|
||||
participant CLI as new-repo (--migrate)
|
||||
participant Gitea as Gitea API (Primary)
|
||||
participant GitHub as GitHub (Source)
|
||||
participant Git as Local Working Tree
|
||||
|
||||
User->>CLI: new-repo --migrate [github-target]
|
||||
CLI->>Gitea: GET /api/v1/repos/{user}/{repo} (Conflict Check)
|
||||
alt Repo Exists
|
||||
Gitea-->>CLI: 200 OK (Abort migration)
|
||||
else Repo Does Not Exist
|
||||
CLI->>Gitea: POST /api/v1/repos/migrate (mirror=False, auth_token=gh_token)
|
||||
Gitea->>GitHub: Server-to-server clone of branches, tags, and commits
|
||||
Gitea-->>CLI: Repository imported
|
||||
CLI->>Gitea: POST /api/v1/repos/{user}/{repo}/push_mirrors
|
||||
Gitea-->>CLI: Push mirror registered (sync on commit)
|
||||
opt Inside Local Git Repo
|
||||
CLI->>Git: Rename remote 'origin' -> 'github'
|
||||
CLI->>Git: Add remote 'origin' -> Gitea clone URL
|
||||
CLI->>Git: git branch --set-upstream-to=origin/<branch>
|
||||
end
|
||||
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`).
|
||||
+822
-81
File diff suppressed because it is too large.
Load diff
+439
-5
@@ -3,11 +3,23 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
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,
|
||||
resolve_name_and_org,
|
||||
)
|
||||
|
||||
|
||||
class TestArgParsing(unittest.TestCase):
|
||||
@@ -19,11 +31,40 @@ class TestArgParsing(unittest.TestCase):
|
||||
sys.argv = ["new-repo", "sample-project"]
|
||||
args = parse_args()
|
||||
self.assertEqual(args.name, "sample-project")
|
||||
self.assertFalse(args.public)
|
||||
self.assertEqual(args.license, "UNLICENSE")
|
||||
self.assertIsNone(args.org)
|
||||
self.assertIsNone(args.github_org)
|
||||
self.assertFalse(args.private)
|
||||
self.assertEqual(args.license, "Unlicense")
|
||||
self.assertIsNone(args.template)
|
||||
self.assertFalse(args.no_mirror)
|
||||
self.assertFalse(args.no_clone)
|
||||
self.assertIsNone(args.as_persona)
|
||||
self.assertIsNone(args.migrate)
|
||||
|
||||
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_migrate_arguments(self) -> None:
|
||||
import sys
|
||||
|
||||
sys.argv = ["new-repo", "--migrate"]
|
||||
args = parse_args()
|
||||
self.assertEqual(args.migrate, "")
|
||||
|
||||
sys.argv = ["new-repo", "--migrate", "https://github.com/octocat/Hello-World"]
|
||||
args = parse_args()
|
||||
self.assertEqual(args.migrate, "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:
|
||||
import sys
|
||||
@@ -31,7 +72,11 @@ class TestArgParsing(unittest.TestCase):
|
||||
sys.argv = [
|
||||
"new-repo",
|
||||
"open-api",
|
||||
"--public",
|
||||
"-o",
|
||||
"homelab",
|
||||
"--github-org",
|
||||
"homelab-gh",
|
||||
"--private",
|
||||
"-d",
|
||||
"My public API",
|
||||
"-l",
|
||||
@@ -43,12 +88,190 @@ class TestArgParsing(unittest.TestCase):
|
||||
]
|
||||
args = parse_args()
|
||||
self.assertEqual(args.name, "open-api")
|
||||
self.assertTrue(args.public)
|
||||
self.assertEqual(args.org, "homelab")
|
||||
self.assertEqual(args.github_org, "homelab-gh")
|
||||
self.assertTrue(args.private)
|
||||
self.assertEqual(args.description, "My public API")
|
||||
self.assertEqual(args.license, "MIT")
|
||||
self.assertEqual(args.template, "template-fastapi")
|
||||
self.assertTrue(args.no_mirror)
|
||||
self.assertTrue(args.no_clone)
|
||||
self.assertIsNone(args.migrate)
|
||||
|
||||
|
||||
class TestLicenseNormalization(unittest.TestCase):
|
||||
"""Test license identifier normalization against Gitea's 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_passthrough(self) -> None:
|
||||
self.assertEqual(normalize_license("Custom-Proprietary"), "Custom-Proprietary")
|
||||
|
||||
def test_gitea_client_create_repo_normalizes_license(self) -> None:
|
||||
client = GiteaClient("https://gitea.local", "kiskaadee", "secret-token")
|
||||
with patch.object(client, "_request", return_value={}) as mock_req:
|
||||
client.create_repo("my-repo", license_name="UNLICENSE")
|
||||
mock_req.assert_called_once()
|
||||
payload = mock_req.call_args[0][2]
|
||||
self.assertEqual(payload["license"], "Unlicense")
|
||||
|
||||
with patch.object(client, "_request", return_value={}) as mock_req:
|
||||
client.create_repo("my-repo-no-license", license_name="")
|
||||
mock_req.assert_called_once()
|
||||
payload = mock_req.call_args[0][2]
|
||||
self.assertNotIn("license", payload)
|
||||
|
||||
|
||||
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):
|
||||
@@ -71,5 +294,216 @@ class TestDotenvLoader(unittest.TestCase):
|
||||
self.assertEqual(loaded.get("GITEA_USER"), "custom-user")
|
||||
|
||||
|
||||
class TestTeaLoginParserAndPersonaResolution(unittest.TestCase):
|
||||
"""Test YAML block parsing of tea logins and persona identity resolution."""
|
||||
|
||||
def setUp(self) -> None:
|
||||
self.sample_tea_yaml = (
|
||||
"logins:\n"
|
||||
"- name: kiskaadee\n"
|
||||
" url: https://gitea.roadtotech.me\n"
|
||||
" token: token-kiskaadee-123\n"
|
||||
" default: true\n"
|
||||
" user: kiskaadee\n"
|
||||
"- name: anneux\n"
|
||||
" url: https://gitea.roadtotech.me\n"
|
||||
" token: token-anneux-456\n"
|
||||
" default: false\n"
|
||||
" ssh_key: /path/to/anne_key\n"
|
||||
" user: anneux\n"
|
||||
"preferences:\n"
|
||||
" editor: false\n"
|
||||
)
|
||||
|
||||
def test_parse_tea_logins(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
cfg_path = Path(tmpdir) / "config.yml"
|
||||
cfg_path.write_text(self.sample_tea_yaml)
|
||||
logins = SecretProvider._parse_tea_logins(cfg_path)
|
||||
self.assertEqual(len(logins), 2)
|
||||
self.assertEqual(logins[0]["name"], "kiskaadee")
|
||||
self.assertTrue(logins[0]["default"])
|
||||
self.assertEqual(logins[1]["name"], "anneux")
|
||||
self.assertFalse(logins[1]["default"])
|
||||
self.assertEqual(logins[1]["ssh_key"], "/path/to/anne_key")
|
||||
|
||||
def test_extract_tea_login_default(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
tea_dir = Path(tmpdir) / ".config" / "tea"
|
||||
tea_dir.mkdir(parents=True)
|
||||
(tea_dir / "config.yml").write_text(self.sample_tea_yaml)
|
||||
with patch("pathlib.Path.home", return_value=Path(tmpdir)):
|
||||
token, url, user, ssh_key = SecretProvider._extract_tea_login(target_persona=None)
|
||||
self.assertEqual(user, "kiskaadee")
|
||||
self.assertEqual(token, "token-kiskaadee-123")
|
||||
self.assertIsNone(ssh_key)
|
||||
|
||||
def test_extract_tea_login_by_persona(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
tea_dir = Path(tmpdir) / ".config" / "tea"
|
||||
tea_dir.mkdir(parents=True)
|
||||
(tea_dir / "config.yml").write_text(self.sample_tea_yaml)
|
||||
with patch("pathlib.Path.home", return_value=Path(tmpdir)):
|
||||
token, url, user, ssh_key = SecretProvider._extract_tea_login(target_persona="anneux")
|
||||
self.assertEqual(user, "anneux")
|
||||
self.assertEqual(token, "token-anneux-456")
|
||||
self.assertEqual(ssh_key, "/path/to/anne_key")
|
||||
|
||||
def test_extract_tea_login_missing_persona_exits(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
tea_dir = Path(tmpdir) / ".config" / "tea"
|
||||
tea_dir.mkdir(parents=True)
|
||||
(tea_dir / "config.yml").write_text(self.sample_tea_yaml)
|
||||
with patch("pathlib.Path.home", return_value=Path(tmpdir)), self.assertRaises(SystemExit):
|
||||
SecretProvider._extract_tea_login(target_persona="unknown-agent")
|
||||
|
||||
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 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__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user