Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f2613b0b3a | ||
|
|
4c5820bace |
No files matched your search
@@ -1,10 +1,10 @@
|
|||||||
# `new-repo` — Automated Repository Provisioning CLI
|
# `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:
|
`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.
|
- **Primary Forge**: **GitHub** for cloud availability, issue/project planning, and CI/CD automation.
|
||||||
- **Backup Forge**: GitHub for offsite redundancy via automated server-side push mirroring.
|
- **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, establish push mirroring, and prepare a local working tree in a single command.
|
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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -13,7 +13,7 @@ It automates the multi-step setup required to create a repository, establish pus
|
|||||||
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.
|
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.
|
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.
|
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.
|
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**.
|
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/):
|
Architecture Decision Records (ADRs) are maintained in [`docs/adr/`](docs/adr/):
|
||||||
@@ -35,52 +35,48 @@ Arguments:
|
|||||||
name Optional repository name ('[org/]repo', defaults to current directory if omitted or '.')
|
name Optional repository name ('[org/]repo', defaults to current directory if omitted or '.')
|
||||||
|
|
||||||
Options:
|
Options:
|
||||||
-o, --org ORG Target Gitea organization to own the repository (auto-created if missing)
|
-o, --org ORG Target GitHub organization to own the repository (defaults to personal GITHUB_USER)
|
||||||
--github-org ORG Optional GitHub organization for the offsite backup mirror (defaults to personal GITHUB_USER)
|
--gitea-org ORG Optional Gitea organization for the homelab pull mirror (auto-created if missing; defaults to GITEA_USER)
|
||||||
--migrate [URL] Migrate an existing GitHub repo to Gitea with automated push mirroring (URL or auto-detect from local origin)
|
--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)
|
-p, --private Make repository private (default: public)
|
||||||
-d, --description Optional repository description string
|
-d, --description Optional repository description string
|
||||||
-l, --license License template identifier (default: Unlicense, pass "" to disable)
|
-l, --license GitHub license template identifier (default: unlicense, pass "" to disable)
|
||||||
-t, --template Optional Gitea template repository ('[owner/]template-name')
|
-t, --template Optional GitHub template repository ('[owner/]template-name')
|
||||||
-M, --no-mirror Disable automatic offsite push mirroring to GitHub
|
-M, --no-mirror Disable automatic homelab pull mirroring to Gitea
|
||||||
--no-clone Skip cloning the repository locally after creation
|
--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)
|
--as PERSONA Persona / login identity to provision as (e.g. anneux)
|
||||||
-h, --help Show help message and exit
|
-h, --help Show help message and exit
|
||||||
```
|
```
|
||||||
|
|
||||||
### Examples
|
### Examples
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 1. Standard greenfield creation (Public Gitea + GitHub push mirror + Unlicense + auto-clone)
|
# 1. Standard greenfield creation (Public GitHub + Gitea pull mirror + unlicense + auto-clone)
|
||||||
new-repo service-api
|
new-repo service-api
|
||||||
|
|
||||||
# 2. Provision as a specific agent persona (binds Gitea/GitHub credentials and SSH keys to persona)
|
# 2. Provision as a specific agent persona (binds GitHub/Gitea credentials and SSH keys to persona)
|
||||||
new-repo frontend-app --as anneux
|
new-repo frontend-app --as anneux
|
||||||
|
|
||||||
# 2. Provision under a Gitea organization (via shorthand or -o/--org flag; auto-creates org if missing)
|
# 3. Provision under a GitHub organization (via shorthand or -o/--org flag)
|
||||||
new-repo homelab/core
|
new-repo my-org/core
|
||||||
new-repo core -o homelab
|
new-repo core -o my-org
|
||||||
|
|
||||||
# 3. Attach remotes & push an existing local repository (into personal account or organization)
|
# 4. Attach remotes & push an existing local repository (into personal account or organization)
|
||||||
cd ~/Projects/my-existing-app
|
cd ~/Projects/my-existing-app
|
||||||
new-repo -o homelab
|
new-repo -o my-org
|
||||||
|
|
||||||
# 4. Provision from an existing Gitea template
|
# 5. Provision from an existing GitHub template
|
||||||
new-repo web-client --template template-react-app
|
new-repo web-client --template template-react-app
|
||||||
|
|
||||||
# 5. Local-only repository (no GitHub mirror)
|
# 6. GitHub-only repository (no Gitea pull mirror)
|
||||||
new-repo private-notes --no-mirror
|
new-repo cloud-only --no-mirror
|
||||||
|
|
||||||
# 6. Private repository with MIT license
|
# 7. Private repository with MIT license
|
||||||
new-repo utility-lib --private --license MIT
|
new-repo utility-lib --private --license mit
|
||||||
|
|
||||||
# 7. Migrate an existing GitHub repository to Gitea (personal or organization) with push mirror
|
# 8. Attach a Gitea pull mirror to an existing GitHub repository (explicit URL or local origin)
|
||||||
new-repo --migrate https://github.com/my-org/existing-service
|
new-repo --gitea-mirror https://github.com/my-org/existing-service
|
||||||
new-repo homelab/existing-service --migrate https://github.com/my-org/existing-service
|
cd ~/Projects/existing-service && new-repo --gitea-mirror
|
||||||
|
|
||||||
# 8. Migrate repository in-place from inside a local checkout
|
|
||||||
cd ~/Projects/existing-service
|
|
||||||
new-repo --migrate
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -132,61 +128,56 @@ sequenceDiagram
|
|||||||
actor User as Developer / CI Runner
|
actor User as Developer / CI Runner
|
||||||
participant CLI as new-repo (Python 3)
|
participant CLI as new-repo (Python 3)
|
||||||
participant SP as SecretProvider (Env / .env / SOPS)
|
participant SP as SecretProvider (Env / .env / SOPS)
|
||||||
participant Gitea as Gitea API (Primary)
|
participant GitHub as GitHub API (Primary)
|
||||||
participant GitHub as GitHub API (Backup)
|
|
||||||
participant Git as Local Git
|
participant Git as Local Git
|
||||||
|
participant Gitea as Gitea API (Pull Mirror)
|
||||||
|
|
||||||
User->>CLI: new-repo <repo-name> [flags]
|
User->>CLI: new-repo <repo-name> [flags]
|
||||||
CLI->>SP: Resolve API credentials
|
CLI->>SP: Resolve API credentials
|
||||||
SP-->>CLI: Credentials (Gitea token, GitHub token)
|
SP-->>CLI: Credentials (GitHub token, Gitea token)
|
||||||
|
|
||||||
alt Template Repo Specified (-t <template>)
|
alt Existing Local Git Repo
|
||||||
CLI->>Gitea: POST /api/v1/repos/{owner}/{template}/generate
|
CLI->>GitHub: POST /user/repos or /orgs/{org}/repos (auto_init=False)
|
||||||
Gitea-->>CLI: Primary repository generated
|
GitHub-->>CLI: Empty primary repository created
|
||||||
else Standard Repository
|
CLI->>Git: git remote add/set-url origin git@github.com:<owner>/<repo>.git && git push -u origin <branch>
|
||||||
CLI->>Gitea: POST /api/v1/user/repos (with license & auto-init)
|
else Template Repo Specified (-t <template>)
|
||||||
Gitea-->>CLI: Primary repository created
|
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
|
end
|
||||||
|
|
||||||
opt Push Mirroring Enabled (Default)
|
opt Local Clone Enabled (Greenfield Default)
|
||||||
CLI->>GitHub: POST https://api.github.com/user/repos (empty target)
|
CLI->>Git: git clone git@github.com:<owner>/<repo>.git
|
||||||
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>
|
Git-->>CLI: Working tree cloned to ./<repo-name>
|
||||||
end
|
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
|
||||||
```
|
```
|
||||||
|
|
||||||
### Migration Workflow (`--migrate`)
|
### Attach Pull Mirror Workflow (`--gitea-mirror`)
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
sequenceDiagram
|
sequenceDiagram
|
||||||
autonumber
|
autonumber
|
||||||
actor User as Developer
|
actor User as Developer
|
||||||
participant CLI as new-repo (--migrate)
|
participant CLI as new-repo (--gitea-mirror)
|
||||||
participant Gitea as Gitea API (Primary)
|
participant Gitea as Gitea API (Pull Mirror)
|
||||||
participant GitHub as GitHub (Source)
|
participant GitHub as GitHub (Primary)
|
||||||
participant Git as Local Working Tree
|
|
||||||
|
|
||||||
User->>CLI: new-repo --migrate [github-target]
|
User->>CLI: new-repo --gitea-mirror [github-target]
|
||||||
CLI->>Gitea: GET /api/v1/repos/{user}/{repo} (Conflict Check)
|
CLI->>Gitea: GET /api/v1/repos/{owner}/{repo} (Conflict Check)
|
||||||
alt Repo Exists
|
alt Repo Exists on Gitea
|
||||||
Gitea-->>CLI: 200 OK (Abort migration)
|
Gitea-->>CLI: 200 OK (Abort to avoid overwriting)
|
||||||
else Repo Does Not Exist
|
else Repo Does Not Exist
|
||||||
CLI->>Gitea: POST /api/v1/repos/migrate (mirror=False, auth_token=gh_token)
|
CLI->>Gitea: POST /api/v1/repos/migrate (mirror=True, auth_token=gh_token)
|
||||||
Gitea->>GitHub: Server-to-server clone of branches, tags, and commits
|
Gitea->>GitHub: Server-to-server pull mirror sync
|
||||||
Gitea-->>CLI: Repository imported
|
Gitea-->>CLI: Pull mirror created
|
||||||
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
|
end
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
+210
-217
@@ -330,50 +330,45 @@ class SecretProvider:
|
|||||||
# License Registry & Normalization
|
# License Registry & Normalization
|
||||||
# ==============================================================================
|
# ==============================================================================
|
||||||
|
|
||||||
GITEA_LICENSES: dict[str, str] = {
|
GITHUB_LICENSES: dict[str, str] = {
|
||||||
"0bsd": "0BSD",
|
"0bsd": "0bsd",
|
||||||
"agpl-3.0": "AGPL-3.0",
|
"agpl-3.0": "agpl-3.0",
|
||||||
"apache-2.0": "Apache-2.0",
|
"apache-2.0": "apache-2.0",
|
||||||
"bsd-2-clause": "BSD-2-Clause",
|
"bsd-2-clause": "bsd-2-clause",
|
||||||
"bsd-3-clause": "BSD-3-Clause",
|
"bsd-3-clause": "bsd-3-clause",
|
||||||
"bsd-3-clause-clear": "BSD-3-Clause-Clear",
|
"bsd-3-clause-clear": "bsd-3-clause-clear",
|
||||||
"bsl-1.0": "BSL-1.0",
|
"bsl-1.0": "bsl-1.0",
|
||||||
"cc-by-4.0": "CC-BY-4.0",
|
"cc-by-4.0": "cc-by-4.0",
|
||||||
"cc-by-sa-4.0": "CC-BY-SA-4.0",
|
"cc-by-sa-4.0": "cc-by-sa-4.0",
|
||||||
"cc0-1.0": "CC0-1.0",
|
"cc0-1.0": "cc0-1.0",
|
||||||
"epl-1.0": "EPL-1.0",
|
"epl-1.0": "epl-1.0",
|
||||||
"epl-2.0": "EPL-2.0",
|
"epl-2.0": "epl-2.0",
|
||||||
"eupl-1.2": "EUPL-1.2",
|
"eupl-1.2": "eupl-1.2",
|
||||||
"gpl-2.0": "GPL-2.0",
|
"gpl-2.0": "gpl-2.0",
|
||||||
"gpl-3.0": "GPL-3.0",
|
"gpl-3.0": "gpl-3.0",
|
||||||
"isc": "ISC",
|
"isc": "isc",
|
||||||
"lgpl-2.1": "LGPL-2.1",
|
"lgpl-2.1": "lgpl-2.1",
|
||||||
"lgpl-3.0": "LGPL-3.0",
|
"lgpl-3.0": "lgpl-3.0",
|
||||||
"mit": "MIT",
|
"mit": "mit",
|
||||||
"mit-0": "MIT-0",
|
"mit-0": "mit-0",
|
||||||
"mpl-2.0": "MPL-2.0",
|
"mpl-2.0": "mpl-2.0",
|
||||||
"mulanpsl-2.0": "MulanPSL-2.0",
|
"ofl-1.1": "ofl-1.1",
|
||||||
"ofl-1.1": "OFL-1.1",
|
"osl-3.0": "osl-3.0",
|
||||||
"osl-3.0": "OSL-3.0",
|
"upl-1.0": "upl-1.0",
|
||||||
"upl-1.0": "UPL-1.0",
|
"unlicense": "unlicense",
|
||||||
"unlicense": "Unlicense",
|
"wtfpl": "wtfpl",
|
||||||
"wtfpl": "WTFPL",
|
"zlib": "zlib",
|
||||||
"zlib": "Zlib",
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def normalize_license(license_name: str | None) -> str:
|
def normalize_license(license_name: str | None) -> str:
|
||||||
"""Normalize license identifier to match Gitea's case-sensitive template registry.
|
"""Normalize license identifier to GitHub's lowercase license_template registry."""
|
||||||
|
|
||||||
Gitea resolves license templates by exact filename in its internal assets.
|
|
||||||
For example, 'UNLICENSE' fails with a 500 error while 'Unlicense' succeeds.
|
|
||||||
"""
|
|
||||||
if not license_name:
|
if not license_name:
|
||||||
return ""
|
return ""
|
||||||
clean = license_name.strip()
|
clean = license_name.strip()
|
||||||
if not clean:
|
if not clean:
|
||||||
return ""
|
return ""
|
||||||
return GITEA_LICENSES.get(clean.lower(), clean)
|
return GITHUB_LICENSES.get(clean.lower(), clean.lower())
|
||||||
|
|
||||||
|
|
||||||
# ==============================================================================
|
# ==============================================================================
|
||||||
@@ -582,19 +577,16 @@ class GiteaClient:
|
|||||||
private: bool = False,
|
private: bool = False,
|
||||||
description: str = "",
|
description: str = "",
|
||||||
repo_owner: str | None = None,
|
repo_owner: str | None = None,
|
||||||
|
mirror: bool = False,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""Import an existing GitHub repository server-side into Gitea.
|
"""Import or pull-mirror an existing GitHub repository into Gitea."""
|
||||||
|
|
||||||
Uses Gitea's POST /api/v1/repos/migrate with mirror=False to perform
|
|
||||||
a complete one-time import of all git branches, tags, and commits.
|
|
||||||
"""
|
|
||||||
payload = {
|
payload = {
|
||||||
"clone_addr": clone_addr,
|
"clone_addr": clone_addr,
|
||||||
"auth_token": github_token,
|
"auth_token": github_token,
|
||||||
"repo_name": repo_name,
|
"repo_name": repo_name,
|
||||||
"repo_owner": repo_owner or self.user,
|
"repo_owner": repo_owner or self.user,
|
||||||
"service": "github",
|
"service": "github",
|
||||||
"mirror": False,
|
"mirror": mirror,
|
||||||
"private": private,
|
"private": private,
|
||||||
"description": description,
|
"description": description,
|
||||||
}
|
}
|
||||||
@@ -631,41 +623,21 @@ class GitHubClient:
|
|||||||
self.token = token
|
self.token = token
|
||||||
self.api_url = "https://api.github.com"
|
self.api_url = "https://api.github.com"
|
||||||
|
|
||||||
def create_empty_repo(
|
def _request(
|
||||||
self,
|
self, method: str, path: str, payload: dict[str, Any] | None = None
|
||||||
name: str,
|
|
||||||
private: bool = False,
|
|
||||||
description: str = "",
|
|
||||||
org: str | None = None,
|
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""Create an empty target repository on GitHub with auto_init=False.
|
"""Execute a JSON REST request against the GitHub API."""
|
||||||
|
url = f"{self.api_url}{path}"
|
||||||
Crucial invariant: The repository MUST be empty (no README, no license)
|
data = json.dumps(payload).encode("utf-8") if payload is not None else None
|
||||||
so that Gitea's push mirror can push all refs without fast-forward conflicts.
|
|
||||||
"""
|
|
||||||
payload = {
|
|
||||||
"name": name,
|
|
||||||
"private": private,
|
|
||||||
"description": description,
|
|
||||||
"auto_init": False,
|
|
||||||
}
|
|
||||||
data = json.dumps(payload).encode("utf-8")
|
|
||||||
endpoint = (
|
|
||||||
f"{self.api_url}/orgs/{org}/repos" if org else f"{self.api_url}/user/repos"
|
|
||||||
)
|
|
||||||
|
|
||||||
req = urllib.request.Request(
|
|
||||||
url=endpoint,
|
|
||||||
data=data,
|
|
||||||
headers = {
|
headers = {
|
||||||
"Authorization": f"Bearer {self.token}",
|
"Authorization": f"Bearer {self.token}",
|
||||||
"Accept": "application/vnd.github+json",
|
"Accept": "application/vnd.github+json",
|
||||||
"X-GitHub-Api-Version": "2022-11-28",
|
"X-GitHub-Api-Version": "2022-11-28",
|
||||||
"Content-Type": "application/json",
|
}
|
||||||
},
|
if data is not None:
|
||||||
method="POST",
|
headers["Content-Type"] = "application/json"
|
||||||
)
|
|
||||||
|
|
||||||
|
req = urllib.request.Request(url=url, data=data, headers=headers, method=method)
|
||||||
try:
|
try:
|
||||||
with urllib.request.urlopen(req) as resp:
|
with urllib.request.urlopen(req) as resp:
|
||||||
raw = resp.read().decode("utf-8")
|
raw = resp.read().decode("utf-8")
|
||||||
@@ -686,6 +658,65 @@ class GitHubClient:
|
|||||||
sanitized_reason = redact_sensitive(str(e.reason), self.token)
|
sanitized_reason = redact_sensitive(str(e.reason), self.token)
|
||||||
raise RuntimeError(f"GitHub network error: {sanitized_reason}") from e
|
raise RuntimeError(f"GitHub network error: {sanitized_reason}") from e
|
||||||
|
|
||||||
|
def create_repo(
|
||||||
|
self,
|
||||||
|
name: str,
|
||||||
|
private: bool = False,
|
||||||
|
description: str = "",
|
||||||
|
auto_init: bool = False,
|
||||||
|
license_template: str = "",
|
||||||
|
org: str | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Create a repository on GitHub (personal or organization)."""
|
||||||
|
payload: dict[str, Any] = {
|
||||||
|
"name": name,
|
||||||
|
"private": private,
|
||||||
|
"description": description,
|
||||||
|
"auto_init": auto_init,
|
||||||
|
}
|
||||||
|
normalized_license = normalize_license(license_template)
|
||||||
|
if auto_init and normalized_license:
|
||||||
|
payload["license_template"] = normalized_license
|
||||||
|
endpoint = f"/orgs/{org}/repos" if org else "/user/repos"
|
||||||
|
return self._request("POST", endpoint, payload)
|
||||||
|
|
||||||
|
def create_empty_repo(
|
||||||
|
self,
|
||||||
|
name: str,
|
||||||
|
private: bool = False,
|
||||||
|
description: str = "",
|
||||||
|
org: str | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Create an empty target repository on GitHub with auto_init=False."""
|
||||||
|
return self.create_repo(
|
||||||
|
name=name,
|
||||||
|
private=private,
|
||||||
|
description=description,
|
||||||
|
auto_init=False,
|
||||||
|
license_template="",
|
||||||
|
org=org,
|
||||||
|
)
|
||||||
|
|
||||||
|
def generate_from_template(
|
||||||
|
self,
|
||||||
|
template_owner: str,
|
||||||
|
template_name: str,
|
||||||
|
name: str,
|
||||||
|
private: bool = False,
|
||||||
|
description: str = "",
|
||||||
|
owner: str | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Generate a new GitHub repository from a GitHub template repository."""
|
||||||
|
payload = {
|
||||||
|
"owner": owner or self.user,
|
||||||
|
"name": name,
|
||||||
|
"private": private,
|
||||||
|
"description": description,
|
||||||
|
"include_all_branches": False,
|
||||||
|
}
|
||||||
|
path = f"/repos/{template_owner}/{template_name}/generate"
|
||||||
|
return self._request("POST", path, payload)
|
||||||
|
|
||||||
|
|
||||||
# ==============================================================================
|
# ==============================================================================
|
||||||
# Local Git Orchestration
|
# Local Git Orchestration
|
||||||
@@ -777,7 +808,7 @@ def link_and_push_existing(
|
|||||||
check=True,
|
check=True,
|
||||||
env=env,
|
env=env,
|
||||||
)
|
)
|
||||||
print(f"✅ Successfully pushed '{current_branch}' to Gitea!")
|
print(f"✅ Successfully pushed '{current_branch}' to origin!")
|
||||||
except subprocess.CalledProcessError as e:
|
except subprocess.CalledProcessError as e:
|
||||||
print(f"⚠️ Failed to link/push repository: {e}", file=sys.stderr)
|
print(f"⚠️ Failed to link/push repository: {e}", file=sys.stderr)
|
||||||
|
|
||||||
@@ -992,7 +1023,7 @@ def parse_args() -> argparse.Namespace:
|
|||||||
"""Parse command line arguments."""
|
"""Parse command line arguments."""
|
||||||
parser = argparse.ArgumentParser(
|
parser = argparse.ArgumentParser(
|
||||||
prog="new-repo",
|
prog="new-repo",
|
||||||
description="Provision repositories across self-hosted Gitea and GitHub push mirror.",
|
description="Provision repositories on GitHub with an automated Gitea pull mirror.",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"name",
|
"name",
|
||||||
@@ -1006,13 +1037,13 @@ def parse_args() -> argparse.Namespace:
|
|||||||
"--org",
|
"--org",
|
||||||
type=str,
|
type=str,
|
||||||
default=None,
|
default=None,
|
||||||
help="Target Gitea organization to own the repository (auto-created if missing)",
|
help="Target GitHub organization to own the repository (defaults to personal GITHUB_USER)",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--github-org",
|
"--gitea-org",
|
||||||
type=str,
|
type=str,
|
||||||
default=None,
|
default=None,
|
||||||
help="Optional GitHub organization for the offsite backup mirror (defaults to personal GITHUB_USER)",
|
help="Optional Gitea organization for the homelab pull mirror (auto-created if missing; defaults to GITEA_USER)",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"-p",
|
"-p",
|
||||||
@@ -1032,22 +1063,22 @@ def parse_args() -> argparse.Namespace:
|
|||||||
"-l",
|
"-l",
|
||||||
"--license",
|
"--license",
|
||||||
type=str,
|
type=str,
|
||||||
default="Unlicense",
|
default="unlicense",
|
||||||
help="License identifier template (default: Unlicense, pass empty string to disable)",
|
help="GitHub license template identifier (default: unlicense, pass empty string to disable)",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"-t",
|
"-t",
|
||||||
"--template",
|
"--template",
|
||||||
type=str,
|
type=str,
|
||||||
default=None,
|
default=None,
|
||||||
help="Optional Gitea template repository ('[owner/]template-name')",
|
help="Optional GitHub template repository ('[owner/]template-name')",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"-M",
|
"-M",
|
||||||
"--no-mirror",
|
"--no-mirror",
|
||||||
action="store_true",
|
action="store_true",
|
||||||
default=False,
|
default=False,
|
||||||
help="Disable automatic offsite push mirroring to GitHub",
|
help="Disable automatic homelab pull mirroring to Gitea",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--no-clone",
|
"--no-clone",
|
||||||
@@ -1063,12 +1094,12 @@ def parse_args() -> argparse.Namespace:
|
|||||||
help="Persona / login identity to provision as (e.g. anneux)",
|
help="Persona / login identity to provision as (e.g. anneux)",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--migrate",
|
"--gitea-mirror",
|
||||||
nargs="?",
|
nargs="?",
|
||||||
const="",
|
const="",
|
||||||
default=None,
|
default=None,
|
||||||
metavar="GITHUB_URL",
|
metavar="GITHUB_URL",
|
||||||
help="Migrate an existing GitHub repository to Gitea with automated push mirroring (URL or auto-detect from local origin)",
|
help="Attach a Gitea pull mirror to an existing GitHub repository (URL or auto-detect from local origin)",
|
||||||
)
|
)
|
||||||
return parser.parse_args()
|
return parser.parse_args()
|
||||||
|
|
||||||
@@ -1092,60 +1123,60 @@ def main() -> None:
|
|||||||
gitea_host = creds.gitea_url.split("://", 1)[-1].split("/", 1)[0].split(":", 1)[0]
|
gitea_host = creds.gitea_url.split("://", 1)[-1].split("/", 1)[0].split(":", 1)[0]
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
# --------------------------------------------------------------------------
|
||||||
# Migration Workflow (--migrate)
|
# Attach Gitea Pull Mirror Workflow (--gitea-mirror)
|
||||||
# --------------------------------------------------------------------------
|
# --------------------------------------------------------------------------
|
||||||
if args.migrate is not None:
|
if args.gitea_mirror is not None:
|
||||||
try:
|
try:
|
||||||
migrated_name, gh_owner, gh_clone_url = parse_github_target(
|
mirrored_name, gh_owner, gh_clone_url = parse_github_target(
|
||||||
args.migrate, Path.cwd()
|
args.gitea_mirror, Path.cwd()
|
||||||
)
|
)
|
||||||
override_name, target_org = resolve_name_and_org(args.name, args.org)
|
override_name, _ = resolve_name_and_org(args.name, None)
|
||||||
except (ValueError, RuntimeError) as e:
|
except (ValueError, RuntimeError) as e:
|
||||||
print(f"❌ Error: {e}", file=sys.stderr)
|
print(f"❌ Error: {e}", file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
dest_name = override_name or migrated_name
|
dest_name = override_name or mirrored_name
|
||||||
gitea_owner = target_org or creds.gitea_user
|
gitea_org = (
|
||||||
|
args.gitea_org.strip()
|
||||||
|
if args.gitea_org and args.gitea_org.strip()
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
gitea_owner = gitea_org or creds.gitea_user
|
||||||
|
|
||||||
# Align with token authenticated user if targeting user namespace
|
if not gitea_org:
|
||||||
if not target_org:
|
|
||||||
auth_user = gitea_client.get_authenticated_user()
|
auth_user = gitea_client.get_authenticated_user()
|
||||||
if auth_user and auth_user.lower() != gitea_owner.lower():
|
if auth_user and auth_user.lower() != gitea_owner.lower():
|
||||||
print(
|
print(
|
||||||
f"⚠️ Identity Warning: Gitea token belongs to '{auth_user}', but session persona is '{gitea_owner}'.\n"
|
f"⚠️ Identity Warning: Gitea token belongs to '{auth_user}', but session persona is '{gitea_owner}'.\n"
|
||||||
f" Aligning primary owner to token owner '{auth_user}'.",
|
f" Aligning mirror owner to token owner '{auth_user}'.",
|
||||||
file=sys.stderr,
|
file=sys.stderr,
|
||||||
)
|
)
|
||||||
gitea_owner = auth_user
|
gitea_owner = auth_user
|
||||||
|
|
||||||
print(
|
print(
|
||||||
f"🚀 Initiating repository migration: '{gh_owner}/{migrated_name}' -> Gitea '{gitea_owner}/{dest_name}'"
|
f"🚀 Attaching Gitea pull mirror: '{gh_owner}/{mirrored_name}' -> Gitea '{gitea_owner}/{dest_name}'"
|
||||||
)
|
)
|
||||||
print(f" Visibility: {'Private' if is_private else 'Public'}")
|
print(f" Visibility: {'Private' if is_private else 'Public'}")
|
||||||
|
|
||||||
if target_org:
|
if gitea_org:
|
||||||
try:
|
try:
|
||||||
created_org = gitea_client.ensure_org(target_org, private=is_private)
|
created_org = gitea_client.ensure_org(gitea_org, private=is_private)
|
||||||
if created_org:
|
if created_org:
|
||||||
print(f"🏢 Created new Gitea organization '{target_org}'")
|
print(f"🏢 Created new Gitea organization '{gitea_org}'")
|
||||||
except RuntimeError as e:
|
except RuntimeError as e:
|
||||||
print(f"❌ Error: {e}", file=sys.stderr)
|
print(f"❌ Error: {e}", file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
# Fail-safe conflict check
|
|
||||||
if gitea_client.repo_exists(gitea_owner, dest_name):
|
if gitea_client.repo_exists(gitea_owner, dest_name):
|
||||||
print(
|
print(
|
||||||
f"❌ Error: Repository '{dest_name}' already exists on Gitea under '{gitea_owner}'.\n"
|
f"❌ Error: Repository '{dest_name}' already exists on Gitea under '{gitea_owner}'.\n"
|
||||||
f" Inspect at: {creds.gitea_url}/{gitea_owner}/{dest_name}\n"
|
f" Inspect at: {creds.gitea_url}/{gitea_owner}/{dest_name}\n"
|
||||||
" Aborting migration to prevent overwriting existing repositories.",
|
" Aborting to prevent overwriting existing repositories.",
|
||||||
file=sys.stderr,
|
file=sys.stderr,
|
||||||
)
|
)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
# Step 1: Server-side import via Gitea Migration API
|
print("🔗 Creating Gitea pull mirror from GitHub...")
|
||||||
print(
|
|
||||||
"🏗️ Importing full repository history from GitHub via Gitea Migration API..."
|
|
||||||
)
|
|
||||||
try:
|
try:
|
||||||
res = gitea_client.migrate_repo(
|
res = gitea_client.migrate_repo(
|
||||||
clone_addr=gh_clone_url,
|
clone_addr=gh_clone_url,
|
||||||
@@ -1154,54 +1185,24 @@ def main() -> None:
|
|||||||
private=is_private,
|
private=is_private,
|
||||||
description=args.description,
|
description=args.description,
|
||||||
repo_owner=gitea_owner,
|
repo_owner=gitea_owner,
|
||||||
|
mirror=True,
|
||||||
)
|
)
|
||||||
actual_owner = res.get("owner", {}).get("username") or gitea_owner
|
actual_owner = res.get("owner", {}).get("username") or gitea_owner
|
||||||
gitea_html_url = res.get(
|
gitea_html_url = res.get(
|
||||||
"html_url", f"{creds.gitea_url}/{actual_owner}/{dest_name}"
|
"html_url", f"{creds.gitea_url}/{actual_owner}/{dest_name}"
|
||||||
)
|
)
|
||||||
print(f"✅ Gitea repository created from GitHub: {gitea_html_url}")
|
print(f"✅ Gitea pull mirror created: {gitea_html_url}")
|
||||||
except RuntimeError as e:
|
except RuntimeError as e:
|
||||||
print(f"❌ Migration failed: {e}", file=sys.stderr)
|
print(f"❌ Pull mirror creation failed: {e}", file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
# Step 2: Register automated push mirror to GitHub
|
print("\n🎉 Mirror setup complete!")
|
||||||
if not args.no_mirror:
|
print(f" Primary Forge (GitHub): {gh_clone_url}")
|
||||||
print("🔗 Registering automated push mirror to GitHub...")
|
print(f" Pull Mirror (Gitea): {gitea_html_url}")
|
||||||
try:
|
|
||||||
gitea_client.create_push_mirror(
|
|
||||||
repo_name=dest_name,
|
|
||||||
remote_address=gh_clone_url,
|
|
||||||
remote_username=creds.github_user,
|
|
||||||
remote_password=creds.github_token,
|
|
||||||
sync_on_commit=True,
|
|
||||||
interval="8h",
|
|
||||||
owner=actual_owner,
|
|
||||||
)
|
|
||||||
print("✅ Gitea push mirror registered (sync on commit enabled)")
|
|
||||||
except RuntimeError as e:
|
|
||||||
print(f"⚠️ Push mirror registration failed: {e}", file=sys.stderr)
|
|
||||||
|
|
||||||
# Step 3: Reconfigure local working tree if inside a Git repository
|
|
||||||
gitea_clone_target = res.get("ssh_url") or f"git@{gitea_host}:{actual_owner}/{dest_name}.git"
|
|
||||||
if (Path.cwd() / ".git").is_dir():
|
|
||||||
reconfigure_local_remotes(Path.cwd(), gitea_clone_target)
|
|
||||||
elif not args.no_clone:
|
|
||||||
clone_locally(
|
|
||||||
gitea_host=gitea_host,
|
|
||||||
user=actual_owner,
|
|
||||||
repo_name=dest_name,
|
|
||||||
target_dir=Path.cwd() / dest_name,
|
|
||||||
clone_url=gitea_clone_target,
|
|
||||||
ssh_key=creds.ssh_key,
|
|
||||||
)
|
|
||||||
|
|
||||||
print("\n🎉 Migration complete!")
|
|
||||||
print(f" Primary Forge (Gitea): {gitea_html_url}")
|
|
||||||
print(f" Backup Mirror (GitHub): {gh_clone_url}")
|
|
||||||
return
|
return
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
# --------------------------------------------------------------------------
|
||||||
# Standard Provisioning Workflow
|
# Standard Provisioning Workflow (GitHub Primary + Gitea Pull Mirror)
|
||||||
# --------------------------------------------------------------------------
|
# --------------------------------------------------------------------------
|
||||||
try:
|
try:
|
||||||
repo_name, target_dir, is_existing_git, target_org = determine_target(
|
repo_name, target_dir, is_existing_git, target_org = determine_target(
|
||||||
@@ -1215,48 +1216,43 @@ def main() -> None:
|
|||||||
print("Error: Repository name cannot be determined.", file=sys.stderr)
|
print("Error: Repository name cannot be determined.", file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
gitea_owner = target_org or creds.gitea_user
|
github_owner = target_org or creds.github_user
|
||||||
github_org = (
|
gitea_org = (
|
||||||
args.github_org.strip() if args.github_org and args.github_org.strip() else None
|
args.gitea_org.strip() if args.gitea_org and args.gitea_org.strip() else None
|
||||||
)
|
)
|
||||||
github_owner = github_org or creds.github_user
|
gitea_owner = gitea_org or creds.gitea_user
|
||||||
|
|
||||||
# Align with token authenticated user if targeting user namespace
|
if not gitea_org:
|
||||||
if not target_org:
|
|
||||||
auth_user = gitea_client.get_authenticated_user()
|
auth_user = gitea_client.get_authenticated_user()
|
||||||
if auth_user and auth_user.lower() != gitea_owner.lower():
|
if auth_user and auth_user.lower() != gitea_owner.lower():
|
||||||
print(
|
print(
|
||||||
f"⚠️ Identity Warning: Gitea token belongs to '{auth_user}', but session persona is '{gitea_owner}'.\n"
|
f"⚠️ Identity Warning: Gitea token belongs to '{auth_user}', but session persona is '{gitea_owner}'.\n"
|
||||||
f" Aligning primary owner to token owner '{auth_user}'.",
|
f" Aligning mirror owner to token owner '{auth_user}'.",
|
||||||
file=sys.stderr,
|
file=sys.stderr,
|
||||||
)
|
)
|
||||||
gitea_owner = auth_user
|
gitea_owner = auth_user
|
||||||
|
|
||||||
print(f"🚀 Initializing repository provisioning: '{gitea_owner}/{repo_name}'")
|
print(f"🚀 Initializing repository provisioning: '{github_owner}/{repo_name}'")
|
||||||
print(f" Visibility: {'Private' if is_private else 'Public'}")
|
print(f" Visibility: {'Private' if is_private else 'Public'}")
|
||||||
if is_existing_git:
|
if is_existing_git:
|
||||||
print(f" Mode: Existing local repository at '{target_dir}'")
|
print(f" Mode: Existing local repository at '{target_dir}'")
|
||||||
else:
|
else:
|
||||||
print(f" Mode: Greenfield creation at '{target_dir}'")
|
print(f" Mode: Greenfield creation at '{target_dir}'")
|
||||||
|
|
||||||
# 2. Provision Gitea Primary Repository
|
# 2. Provision GitHub Primary Repository
|
||||||
gitea_html_url: str | None = None
|
github_html_url: str
|
||||||
|
github_ssh_url: str
|
||||||
try:
|
try:
|
||||||
if target_org:
|
|
||||||
created_org = gitea_client.ensure_org(target_org, private=is_private)
|
|
||||||
if created_org:
|
|
||||||
print(f"🏢 Created new Gitea organization '{target_org}'")
|
|
||||||
|
|
||||||
if is_existing_git:
|
if is_existing_git:
|
||||||
print(
|
print(
|
||||||
"🏗️ Creating empty primary repository on Gitea (preserving local history)..."
|
"🏗️ Creating empty primary repository on GitHub (preserving local history)..."
|
||||||
)
|
)
|
||||||
res = gitea_client.create_repo(
|
res = github_client.create_repo(
|
||||||
name=repo_name,
|
name=repo_name,
|
||||||
private=is_private,
|
private=is_private,
|
||||||
description=args.description,
|
description=args.description,
|
||||||
auto_init=False, # CRUCIAL: Do not create remote README/license to prevent divergent commit histories
|
auto_init=False,
|
||||||
license_name="",
|
license_template="",
|
||||||
org=target_org,
|
org=target_org,
|
||||||
)
|
)
|
||||||
elif args.template:
|
elif args.template:
|
||||||
@@ -1264,102 +1260,99 @@ def main() -> None:
|
|||||||
if len(template_parts) == 2:
|
if len(template_parts) == 2:
|
||||||
tmpl_owner, tmpl_name = template_parts[0], template_parts[1]
|
tmpl_owner, tmpl_name = template_parts[0], template_parts[1]
|
||||||
else:
|
else:
|
||||||
tmpl_owner, tmpl_name = gitea_owner, template_parts[0]
|
tmpl_owner, tmpl_name = github_owner, template_parts[0]
|
||||||
|
|
||||||
print(
|
print(
|
||||||
f"🏗️ Generating Gitea repository from template '{tmpl_owner}/{tmpl_name}'..."
|
f"🏗️ Generating GitHub repository from template '{tmpl_owner}/{tmpl_name}'..."
|
||||||
)
|
)
|
||||||
res = gitea_client.generate_from_template(
|
res = github_client.generate_from_template(
|
||||||
template_owner=tmpl_owner,
|
template_owner=tmpl_owner,
|
||||||
template_name=tmpl_name,
|
template_name=tmpl_name,
|
||||||
name=repo_name,
|
name=repo_name,
|
||||||
private=is_private,
|
private=is_private,
|
||||||
description=args.description,
|
description=args.description,
|
||||||
owner=gitea_owner,
|
owner=github_owner,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
print("🏗️ Creating primary repository on Gitea...")
|
print("🏗️ Creating primary repository on GitHub...")
|
||||||
res = gitea_client.create_repo(
|
res = github_client.create_repo(
|
||||||
name=repo_name,
|
name=repo_name,
|
||||||
private=is_private,
|
private=is_private,
|
||||||
description=args.description,
|
description=args.description,
|
||||||
auto_init=True,
|
auto_init=True,
|
||||||
license_name=args.license,
|
license_template=args.license,
|
||||||
org=target_org,
|
org=target_org,
|
||||||
)
|
)
|
||||||
|
|
||||||
actual_owner = res.get("owner", {}).get("username") or gitea_owner
|
actual_gh_owner = res.get("owner", {}).get("login") or github_owner
|
||||||
actual_clone_url = res.get("ssh_url") or f"git@{gitea_host}:{actual_owner}/{repo_name}.git"
|
github_ssh_url = res.get("ssh_url") or f"git@github.com:{actual_gh_owner}/{repo_name}.git"
|
||||||
gitea_html_url = res.get(
|
github_html_url = res.get(
|
||||||
"html_url", f"{creds.gitea_url}/{actual_owner}/{repo_name}"
|
"html_url", f"https://github.com/{actual_gh_owner}/{repo_name}"
|
||||||
)
|
)
|
||||||
print(f"✅ Gitea repository created: {gitea_html_url}")
|
print(f"✅ GitHub repository created: {github_html_url}")
|
||||||
except RuntimeError as e:
|
except RuntimeError as e:
|
||||||
print(f"❌ Failed to create Gitea repository: {e}", file=sys.stderr)
|
print(f"❌ Failed to create GitHub repository: {e}", file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
# 3. Provision GitHub Backup Mirror & Push Mirror Registration
|
# 3. Local Git Workflow (push existing commits before Gitea pull-mirroring)
|
||||||
github_html_url: str | None = None
|
|
||||||
if not args.no_mirror:
|
|
||||||
print("☁️ Provisioning offsite mirror target on GitHub...")
|
|
||||||
try:
|
|
||||||
gh_res = github_client.create_empty_repo(
|
|
||||||
name=repo_name,
|
|
||||||
private=is_private,
|
|
||||||
description=args.description,
|
|
||||||
org=github_org,
|
|
||||||
)
|
|
||||||
github_html_url = gh_res.get(
|
|
||||||
"html_url", f"https://github.com/{github_owner}/{repo_name}"
|
|
||||||
)
|
|
||||||
print(f"✅ GitHub mirror target created: {github_html_url}")
|
|
||||||
|
|
||||||
print("🔗 Registering automated push mirror on Gitea...")
|
|
||||||
github_clone_target = f"https://github.com/{github_owner}/{repo_name}.git"
|
|
||||||
gitea_client.create_push_mirror(
|
|
||||||
repo_name=repo_name,
|
|
||||||
remote_address=github_clone_target,
|
|
||||||
remote_username=creds.github_user,
|
|
||||||
remote_password=creds.github_token,
|
|
||||||
sync_on_commit=True,
|
|
||||||
interval="8h",
|
|
||||||
owner=actual_owner,
|
|
||||||
)
|
|
||||||
print("✅ Gitea push mirror registered (sync on commit enabled)")
|
|
||||||
except RuntimeError as e:
|
|
||||||
# Retain & Report policy: Gitea repo exists, so inform the user rather than deleting it
|
|
||||||
print(f"⚠️ Push mirror provisioning failed: {e}", file=sys.stderr)
|
|
||||||
print(
|
|
||||||
f" Your primary Gitea repository remains intact at: {gitea_html_url}\n"
|
|
||||||
" You can inspect or configure mirroring manually if needed.",
|
|
||||||
file=sys.stderr,
|
|
||||||
)
|
|
||||||
|
|
||||||
# 4. Local Git Workflow
|
|
||||||
if is_existing_git:
|
if is_existing_git:
|
||||||
link_and_push_existing(
|
link_and_push_existing(
|
||||||
gitea_host=gitea_host,
|
gitea_host="github.com",
|
||||||
user=actual_owner,
|
user=actual_gh_owner,
|
||||||
repo_name=repo_name,
|
repo_name=repo_name,
|
||||||
target_dir=target_dir,
|
target_dir=target_dir,
|
||||||
clone_url=actual_clone_url,
|
clone_url=github_ssh_url,
|
||||||
ssh_key=creds.ssh_key,
|
ssh_key=creds.ssh_key,
|
||||||
)
|
)
|
||||||
elif not args.no_clone:
|
elif not args.no_clone:
|
||||||
clone_locally(
|
clone_locally(
|
||||||
gitea_host=gitea_host,
|
gitea_host="github.com",
|
||||||
user=actual_owner,
|
user=actual_gh_owner,
|
||||||
repo_name=repo_name,
|
repo_name=repo_name,
|
||||||
target_dir=target_dir,
|
target_dir=target_dir,
|
||||||
clone_url=actual_clone_url,
|
clone_url=github_ssh_url,
|
||||||
ssh_key=creds.ssh_key,
|
ssh_key=creds.ssh_key,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# 4. Provision Gitea Pull Mirror
|
||||||
|
gitea_html_url: str | None = None
|
||||||
|
if not args.no_mirror:
|
||||||
|
print("🪞 Provisioning homelab pull mirror on Gitea...")
|
||||||
|
try:
|
||||||
|
if gitea_org:
|
||||||
|
created_org = gitea_client.ensure_org(gitea_org, private=is_private)
|
||||||
|
if created_org:
|
||||||
|
print(f"🏢 Created new Gitea organization '{gitea_org}'")
|
||||||
|
|
||||||
|
github_clone_target = f"https://github.com/{actual_gh_owner}/{repo_name}.git"
|
||||||
|
gitea_res = gitea_client.migrate_repo(
|
||||||
|
clone_addr=github_clone_target,
|
||||||
|
repo_name=repo_name,
|
||||||
|
github_token=creds.github_token,
|
||||||
|
private=is_private,
|
||||||
|
description=args.description,
|
||||||
|
repo_owner=gitea_owner,
|
||||||
|
mirror=True,
|
||||||
|
)
|
||||||
|
actual_gitea_owner = gitea_res.get("owner", {}).get("username") or gitea_owner
|
||||||
|
gitea_html_url = gitea_res.get(
|
||||||
|
"html_url", f"{creds.gitea_url}/{actual_gitea_owner}/{repo_name}"
|
||||||
|
)
|
||||||
|
print(f"✅ Gitea pull mirror created: {gitea_html_url}")
|
||||||
|
except RuntimeError as e:
|
||||||
|
# Retain & Report policy: GitHub repo exists, so inform the user rather than deleting it
|
||||||
|
print(f"⚠️ Gitea pull mirror provisioning failed: {e}", file=sys.stderr)
|
||||||
|
print(
|
||||||
|
f" Your primary GitHub repository remains intact at: {github_html_url}\n"
|
||||||
|
" You can attach a pull mirror later via: new-repo --gitea-mirror",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
|
||||||
# 5. Final Summary
|
# 5. Final Summary
|
||||||
print("\n🎉 Provisioning complete!")
|
print("\n🎉 Provisioning complete!")
|
||||||
print(f" Primary Forge: {gitea_html_url}")
|
print(f" Primary Forge (GitHub): {github_html_url}")
|
||||||
if github_html_url:
|
if gitea_html_url:
|
||||||
print(f" Backup Mirror: {github_html_url}")
|
print(f" Pull Mirror (Gitea): {gitea_html_url}")
|
||||||
print(f" Working Tree: {target_dir}")
|
print(f" Working Tree: {target_dir}")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+54
-34
@@ -37,14 +37,14 @@ class TestArgParsing(unittest.TestCase):
|
|||||||
args = parse_args()
|
args = parse_args()
|
||||||
self.assertEqual(args.name, "sample-project")
|
self.assertEqual(args.name, "sample-project")
|
||||||
self.assertIsNone(args.org)
|
self.assertIsNone(args.org)
|
||||||
self.assertIsNone(args.github_org)
|
self.assertIsNone(args.gitea_org)
|
||||||
self.assertFalse(args.private)
|
self.assertFalse(args.private)
|
||||||
self.assertEqual(args.license, "Unlicense")
|
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.assertIsNone(args.as_persona)
|
self.assertIsNone(args.as_persona)
|
||||||
self.assertIsNone(args.migrate)
|
self.assertIsNone(args.gitea_mirror)
|
||||||
|
|
||||||
def test_as_persona_argument(self) -> None:
|
def test_as_persona_argument(self) -> None:
|
||||||
import sys
|
import sys
|
||||||
@@ -53,16 +53,16 @@ class TestArgParsing(unittest.TestCase):
|
|||||||
args = parse_args()
|
args = parse_args()
|
||||||
self.assertEqual(args.as_persona, "anneux")
|
self.assertEqual(args.as_persona, "anneux")
|
||||||
|
|
||||||
def test_migrate_arguments(self) -> None:
|
def test_gitea_mirror_arguments(self) -> None:
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
sys.argv = ["new-repo", "--migrate"]
|
sys.argv = ["new-repo", "--gitea-mirror"]
|
||||||
args = parse_args()
|
args = parse_args()
|
||||||
self.assertEqual(args.migrate, "")
|
self.assertEqual(args.gitea_mirror, "")
|
||||||
|
|
||||||
sys.argv = ["new-repo", "--migrate", "https://github.com/octocat/Hello-World"]
|
sys.argv = ["new-repo", "--gitea-mirror", "https://github.com/octocat/Hello-World"]
|
||||||
args = parse_args()
|
args = parse_args()
|
||||||
self.assertEqual(args.migrate, "https://github.com/octocat/Hello-World")
|
self.assertEqual(args.gitea_mirror, "https://github.com/octocat/Hello-World")
|
||||||
|
|
||||||
def test_omitted_name_defaults_to_none(self) -> None:
|
def test_omitted_name_defaults_to_none(self) -> None:
|
||||||
import sys
|
import sys
|
||||||
@@ -78,9 +78,9 @@ class TestArgParsing(unittest.TestCase):
|
|||||||
"new-repo",
|
"new-repo",
|
||||||
"open-api",
|
"open-api",
|
||||||
"-o",
|
"-o",
|
||||||
|
"my-gh-org",
|
||||||
|
"--gitea-org",
|
||||||
"homelab",
|
"homelab",
|
||||||
"--github-org",
|
|
||||||
"homelab-gh",
|
|
||||||
"--private",
|
"--private",
|
||||||
"-d",
|
"-d",
|
||||||
"My public API",
|
"My public API",
|
||||||
@@ -93,54 +93,74 @@ class TestArgParsing(unittest.TestCase):
|
|||||||
]
|
]
|
||||||
args = parse_args()
|
args = parse_args()
|
||||||
self.assertEqual(args.name, "open-api")
|
self.assertEqual(args.name, "open-api")
|
||||||
self.assertEqual(args.org, "homelab")
|
self.assertEqual(args.org, "my-gh-org")
|
||||||
self.assertEqual(args.github_org, "homelab-gh")
|
self.assertEqual(args.gitea_org, "homelab")
|
||||||
self.assertTrue(args.private)
|
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.migrate)
|
self.assertIsNone(args.gitea_mirror)
|
||||||
|
|
||||||
|
|
||||||
class TestLicenseNormalization(unittest.TestCase):
|
class TestLicenseNormalization(unittest.TestCase):
|
||||||
"""Test license identifier normalization against Gitea's registry."""
|
"""Test license identifier normalization against GitHub's lowercase registry."""
|
||||||
|
|
||||||
def test_unlicense_casing_variants(self) -> None:
|
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")
|
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:
|
def test_common_licenses_case_insensitivity(self) -> None:
|
||||||
self.assertEqual(normalize_license("mit"), "MIT")
|
self.assertEqual(normalize_license("mit"), "mit")
|
||||||
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("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("gpl-3.0"), "gpl-3.0")
|
||||||
self.assertEqual(normalize_license("bsd-3-clause"), "BSD-3-Clause")
|
self.assertEqual(normalize_license("bsd-3-clause"), "bsd-3-clause")
|
||||||
|
|
||||||
def test_empty_and_whitespace_licenses(self) -> None:
|
def test_empty_and_whitespace_licenses(self) -> None:
|
||||||
self.assertEqual(normalize_license(""), "")
|
self.assertEqual(normalize_license(""), "")
|
||||||
self.assertEqual(normalize_license(" "), "")
|
self.assertEqual(normalize_license(" "), "")
|
||||||
self.assertEqual(normalize_license(None), "")
|
self.assertEqual(normalize_license(None), "")
|
||||||
|
|
||||||
def test_unrecognized_license_passthrough(self) -> None:
|
def test_unrecognized_license_lowercase(self) -> None:
|
||||||
self.assertEqual(normalize_license("Custom-Proprietary"), "Custom-Proprietary")
|
self.assertEqual(normalize_license("Custom-Proprietary"), "custom-proprietary")
|
||||||
|
|
||||||
def test_gitea_client_create_repo_normalizes_license(self) -> None:
|
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")
|
client = GiteaClient("https://gitea.local", "kiskaadee", "secret-token")
|
||||||
with patch.object(client, "_request", return_value={}) as mock_req:
|
with patch.object(client, "_request", return_value={}) as mock_req:
|
||||||
client.create_repo("my-repo", license_name="UNLICENSE")
|
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()
|
mock_req.assert_called_once()
|
||||||
payload = mock_req.call_args[0][2]
|
payload = mock_req.call_args[0][2]
|
||||||
self.assertEqual(payload["license"], "Unlicense")
|
self.assertTrue(payload["mirror"])
|
||||||
|
self.assertTrue(payload["private"])
|
||||||
with patch.object(client, "_request", return_value={}) as mock_req:
|
self.assertEqual(payload["service"], "github")
|
||||||
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):
|
class TestOrganizationAndTargetResolution(unittest.TestCase):
|
||||||
|
|||||||
Reference in new issue
Block a user