Compare commits

...
2 Commits
Author SHA1 Message Date
kiskaadee f2613b0b3a docs(readme): update CLI flags and architecture diagrams for GitHub-primary flow
- Document inverted -o/--org (GitHub), --gitea-org, and --gitea-mirror flags

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

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

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

- Update test_new_repo.py for inverted CLI flags, lowercase GitHub licenses, and Gitea pull-mirror payloads
2026-11-25 16:36:49 -05:00
3 changed files with 323 additions and 319 deletions

No files matched your search

+58 -67
View File
@@ -1,10 +1,10 @@
# `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.
- **Primary Forge**: **GitHub** for cloud availability, issue/project planning, and CI/CD automation.
- **Backup Forge**: Self-hosted **Gitea** for homelab redundancy via automated server-side **pull mirroring**.
It automates the multi-step setup required to create a repository, 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.
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.
4. **Resilient Failure Recovery**: Adheres to a *retain-and-report* policy. If homelab Gitea pull-mirror registration encounters an error after the primary GitHub repository is created, the GitHub repository is preserved and diagnostic URLs are printed for manual review or `--gitea-mirror` retry.
5. **Strict Static Typing**: Enforces full static type hints validated via **Pyright** and formatted/linted via **Ruff**.
Architecture Decision Records (ADRs) are maintained in [`docs/adr/`](docs/adr/):
@@ -35,52 +35,48 @@ 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)
-o, --org ORG Target GitHub organization to own the repository (defaults to personal GITHUB_USER)
--gitea-org ORG Optional Gitea organization for the homelab pull mirror (auto-created if missing; defaults to GITEA_USER)
--gitea-mirror [URL] Attach a Gitea pull mirror to an existing GitHub repository (URL or auto-detect from local origin)
-p, --private Make repository private (default: public)
-d, --description Optional repository description string
-l, --license 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
-l, --license GitHub license template identifier (default: unlicense, pass "" to disable)
-t, --template Optional GitHub template repository ('[owner/]template-name')
-M, --no-mirror Disable automatic homelab pull mirroring to Gitea
--no-clone Skip cloning the repository locally after creation
--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
```
### Examples
```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
# 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
# 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. Provision under a GitHub organization (via shorthand or -o/--org flag)
new-repo my-org/core
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
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
# 5. Local-only repository (no GitHub mirror)
new-repo private-notes --no-mirror
# 6. GitHub-only repository (no Gitea pull mirror)
new-repo cloud-only --no-mirror
# 6. Private repository with MIT license
new-repo utility-lib --private --license MIT
# 7. 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
# 8. Attach a Gitea pull mirror to an existing GitHub repository (explicit URL or local origin)
new-repo --gitea-mirror https://github.com/my-org/existing-service
cd ~/Projects/existing-service && new-repo --gitea-mirror
```
---
@@ -132,61 +128,56 @@ sequenceDiagram
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 GitHub as GitHub API (Primary)
participant Git as Local Git
participant Gitea as Gitea API (Pull Mirror)
User->>CLI: new-repo <repo-name> [flags]
CLI->>SP: Resolve API credentials
SP-->>CLI: Credentials (Gitea token, GitHub token)
SP-->>CLI: Credentials (GitHub token, Gitea 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
alt Existing Local Git Repo
CLI->>GitHub: POST /user/repos or /orgs/{org}/repos (auto_init=False)
GitHub-->>CLI: Empty primary repository created
CLI->>Git: git remote add/set-url origin git@github.com:<owner>/<repo>.git && git push -u origin <branch>
else Template Repo Specified (-t <template>)
CLI->>GitHub: POST /repos/{owner}/{template}/generate
GitHub-->>CLI: Primary repository generated
else Standard Greenfield Repository
CLI->>GitHub: POST /user/repos or /orgs/{org}/repos (auto_init=True, license_template)
GitHub-->>CLI: Primary repository created
end
opt 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
opt Local Clone Enabled (Greenfield Default)
CLI->>Git: git clone git@github.com:<owner>/<repo>.git
Git-->>CLI: Working tree cloned to ./<repo-name>
end
opt Homelab Pull Mirror Enabled (Default)
CLI->>Gitea: POST /api/v1/repos/migrate (mirror=True, service=github, auth_token=gh_token)
Gitea->>GitHub: Server-to-server pull mirror sync
Gitea-->>CLI: Pull mirror registered
end
```
### Migration Workflow (`--migrate`)
### Attach Pull Mirror Workflow (`--gitea-mirror`)
```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
participant CLI as new-repo (--gitea-mirror)
participant Gitea as Gitea API (Pull Mirror)
participant GitHub as GitHub (Primary)
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)
User->>CLI: new-repo --gitea-mirror [github-target]
CLI->>Gitea: GET /api/v1/repos/{owner}/{repo} (Conflict Check)
alt Repo Exists on Gitea
Gitea-->>CLI: 200 OK (Abort to avoid overwriting)
else Repo Does Not Exist
CLI->>Gitea: POST /api/v1/repos/migrate (mirror=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
CLI->>Gitea: POST /api/v1/repos/migrate (mirror=True, auth_token=gh_token)
Gitea->>GitHub: Server-to-server pull mirror sync
Gitea-->>CLI: Pull mirror created
end
```
+211 -218
View File
@@ -330,50 +330,45 @@ class SecretProvider:
# License Registry & Normalization
# ==============================================================================
GITEA_LICENSES: dict[str, str] = {
"0bsd": "0BSD",
"agpl-3.0": "AGPL-3.0",
"apache-2.0": "Apache-2.0",
"bsd-2-clause": "BSD-2-Clause",
"bsd-3-clause": "BSD-3-Clause",
"bsd-3-clause-clear": "BSD-3-Clause-Clear",
"bsl-1.0": "BSL-1.0",
"cc-by-4.0": "CC-BY-4.0",
"cc-by-sa-4.0": "CC-BY-SA-4.0",
"cc0-1.0": "CC0-1.0",
"epl-1.0": "EPL-1.0",
"epl-2.0": "EPL-2.0",
"eupl-1.2": "EUPL-1.2",
"gpl-2.0": "GPL-2.0",
"gpl-3.0": "GPL-3.0",
"isc": "ISC",
"lgpl-2.1": "LGPL-2.1",
"lgpl-3.0": "LGPL-3.0",
"mit": "MIT",
"mit-0": "MIT-0",
"mpl-2.0": "MPL-2.0",
"mulanpsl-2.0": "MulanPSL-2.0",
"ofl-1.1": "OFL-1.1",
"osl-3.0": "OSL-3.0",
"upl-1.0": "UPL-1.0",
"unlicense": "Unlicense",
"wtfpl": "WTFPL",
"zlib": "Zlib",
GITHUB_LICENSES: dict[str, str] = {
"0bsd": "0bsd",
"agpl-3.0": "agpl-3.0",
"apache-2.0": "apache-2.0",
"bsd-2-clause": "bsd-2-clause",
"bsd-3-clause": "bsd-3-clause",
"bsd-3-clause-clear": "bsd-3-clause-clear",
"bsl-1.0": "bsl-1.0",
"cc-by-4.0": "cc-by-4.0",
"cc-by-sa-4.0": "cc-by-sa-4.0",
"cc0-1.0": "cc0-1.0",
"epl-1.0": "epl-1.0",
"epl-2.0": "epl-2.0",
"eupl-1.2": "eupl-1.2",
"gpl-2.0": "gpl-2.0",
"gpl-3.0": "gpl-3.0",
"isc": "isc",
"lgpl-2.1": "lgpl-2.1",
"lgpl-3.0": "lgpl-3.0",
"mit": "mit",
"mit-0": "mit-0",
"mpl-2.0": "mpl-2.0",
"ofl-1.1": "ofl-1.1",
"osl-3.0": "osl-3.0",
"upl-1.0": "upl-1.0",
"unlicense": "unlicense",
"wtfpl": "wtfpl",
"zlib": "zlib",
}
def normalize_license(license_name: str | None) -> str:
"""Normalize license identifier to match Gitea's case-sensitive template registry.
Gitea resolves license templates by exact filename in its internal assets.
For example, 'UNLICENSE' fails with a 500 error while 'Unlicense' succeeds.
"""
"""Normalize license identifier to GitHub's lowercase license_template registry."""
if not license_name:
return ""
clean = license_name.strip()
if not clean:
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,
description: str = "",
repo_owner: str | None = None,
mirror: bool = False,
) -> dict[str, Any]:
"""Import an existing GitHub repository server-side 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.
"""
"""Import or pull-mirror an existing GitHub repository into Gitea."""
payload = {
"clone_addr": clone_addr,
"auth_token": github_token,
"repo_name": repo_name,
"repo_owner": repo_owner or self.user,
"service": "github",
"mirror": False,
"mirror": mirror,
"private": private,
"description": description,
}
@@ -631,41 +623,21 @@ class GitHubClient:
self.token = token
self.api_url = "https://api.github.com"
def create_empty_repo(
self,
name: str,
private: bool = False,
description: str = "",
org: str | None = None,
def _request(
self, method: str, path: str, payload: dict[str, Any] | None = None
) -> dict[str, Any]:
"""Create an empty target repository on GitHub with auto_init=False.
Crucial invariant: The repository MUST be empty (no README, no license)
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={
"""Execute a JSON REST request against the GitHub API."""
url = f"{self.api_url}{path}"
data = json.dumps(payload).encode("utf-8") if payload is not None else None
headers = {
"Authorization": f"Bearer {self.token}",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
"Content-Type": "application/json",
},
method="POST",
)
}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url=url, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req) as resp:
raw = resp.read().decode("utf-8")
@@ -686,6 +658,65 @@ class GitHubClient:
sanitized_reason = redact_sensitive(str(e.reason), self.token)
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
@@ -777,7 +808,7 @@ def link_and_push_existing(
check=True,
env=env,
)
print(f"✅ Successfully pushed '{current_branch}' to Gitea!")
print(f"✅ Successfully pushed '{current_branch}' to origin!")
except subprocess.CalledProcessError as e:
print(f"⚠️ Failed to link/push repository: {e}", file=sys.stderr)
@@ -992,7 +1023,7 @@ def parse_args() -> argparse.Namespace:
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
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(
"name",
@@ -1006,13 +1037,13 @@ def parse_args() -> argparse.Namespace:
"--org",
type=str,
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(
"--github-org",
"--gitea-org",
type=str,
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(
"-p",
@@ -1032,22 +1063,22 @@ def parse_args() -> argparse.Namespace:
"-l",
"--license",
type=str,
default="Unlicense",
help="License identifier template (default: Unlicense, pass empty string to disable)",
default="unlicense",
help="GitHub license template identifier (default: unlicense, pass empty string to disable)",
)
parser.add_argument(
"-t",
"--template",
type=str,
default=None,
help="Optional Gitea template repository ('[owner/]template-name')",
help="Optional GitHub template repository ('[owner/]template-name')",
)
parser.add_argument(
"-M",
"--no-mirror",
action="store_true",
default=False,
help="Disable automatic offsite push mirroring to GitHub",
help="Disable automatic homelab pull mirroring to Gitea",
)
parser.add_argument(
"--no-clone",
@@ -1063,12 +1094,12 @@ def parse_args() -> argparse.Namespace:
help="Persona / login identity to provision as (e.g. anneux)",
)
parser.add_argument(
"--migrate",
"--gitea-mirror",
nargs="?",
const="",
default=None,
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()
@@ -1092,60 +1123,60 @@ def main() -> None:
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:
migrated_name, gh_owner, gh_clone_url = parse_github_target(
args.migrate, Path.cwd()
mirrored_name, gh_owner, gh_clone_url = parse_github_target(
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:
print(f"❌ Error: {e}", file=sys.stderr)
sys.exit(1)
dest_name = override_name or migrated_name
gitea_owner = target_org or creds.gitea_user
dest_name = override_name or mirrored_name
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 target_org:
if not gitea_org:
auth_user = gitea_client.get_authenticated_user()
if auth_user and auth_user.lower() != gitea_owner.lower():
print(
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,
)
gitea_owner = auth_user
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'}")
if target_org:
if gitea_org:
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:
print(f"🏢 Created new Gitea organization '{target_org}'")
print(f"🏢 Created new Gitea organization '{gitea_org}'")
except RuntimeError as e:
print(f"❌ Error: {e}", file=sys.stderr)
sys.exit(1)
# Fail-safe conflict check
if gitea_client.repo_exists(gitea_owner, dest_name):
print(
f"❌ Error: Repository '{dest_name}' already exists on Gitea under '{gitea_owner}'.\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,
)
sys.exit(1)
# Step 1: Server-side import via Gitea Migration API
print(
"🏗️ Importing full repository history from GitHub via Gitea Migration API..."
)
print("🔗 Creating Gitea pull mirror from GitHub...")
try:
res = gitea_client.migrate_repo(
clone_addr=gh_clone_url,
@@ -1154,54 +1185,24 @@ def main() -> None:
private=is_private,
description=args.description,
repo_owner=gitea_owner,
mirror=True,
)
actual_owner = res.get("owner", {}).get("username") or gitea_owner
gitea_html_url = res.get(
"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:
print(f"❌ Migration failed: {e}", file=sys.stderr)
print(f"❌ Pull mirror creation failed: {e}", file=sys.stderr)
sys.exit(1)
# Step 2: Register automated push mirror to GitHub
if not args.no_mirror:
print("🔗 Registering automated push mirror to GitHub...")
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}")
print("\n🎉 Mirror setup complete!")
print(f" Primary Forge (GitHub): {gh_clone_url}")
print(f" Pull Mirror (Gitea): {gitea_html_url}")
return
# --------------------------------------------------------------------------
# Standard Provisioning Workflow
# Standard Provisioning Workflow (GitHub Primary + Gitea Pull Mirror)
# --------------------------------------------------------------------------
try:
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)
sys.exit(1)
gitea_owner = target_org or creds.gitea_user
github_org = (
args.github_org.strip() if args.github_org and args.github_org.strip() else None
github_owner = target_org or creds.github_user
gitea_org = (
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 target_org:
if not gitea_org:
auth_user = gitea_client.get_authenticated_user()
if auth_user and auth_user.lower() != gitea_owner.lower():
print(
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,
)
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'}")
if is_existing_git:
print(f" Mode: Existing local repository at '{target_dir}'")
else:
print(f" Mode: Greenfield creation at '{target_dir}'")
# 2. Provision Gitea Primary Repository
gitea_html_url: str | None = None
# 2. Provision GitHub Primary Repository
github_html_url: str
github_ssh_url: str
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:
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,
private=is_private,
description=args.description,
auto_init=False, # CRUCIAL: Do not create remote README/license to prevent divergent commit histories
license_name="",
auto_init=False,
license_template="",
org=target_org,
)
elif args.template:
@@ -1264,102 +1260,99 @@ def main() -> None:
if len(template_parts) == 2:
tmpl_owner, tmpl_name = template_parts[0], template_parts[1]
else:
tmpl_owner, tmpl_name = gitea_owner, template_parts[0]
tmpl_owner, tmpl_name = github_owner, template_parts[0]
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_name=tmpl_name,
name=repo_name,
private=is_private,
description=args.description,
owner=gitea_owner,
owner=github_owner,
)
else:
print("🏗️ Creating primary repository on Gitea...")
res = gitea_client.create_repo(
print("🏗️ Creating primary repository on GitHub...")
res = github_client.create_repo(
name=repo_name,
private=is_private,
description=args.description,
auto_init=True,
license_name=args.license,
license_template=args.license,
org=target_org,
)
actual_owner = res.get("owner", {}).get("username") or gitea_owner
actual_clone_url = res.get("ssh_url") or f"git@{gitea_host}:{actual_owner}/{repo_name}.git"
gitea_html_url = res.get(
"html_url", f"{creds.gitea_url}/{actual_owner}/{repo_name}"
actual_gh_owner = res.get("owner", {}).get("login") or github_owner
github_ssh_url = res.get("ssh_url") or f"git@github.com:{actual_gh_owner}/{repo_name}.git"
github_html_url = res.get(
"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:
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)
# 3. Provision GitHub Backup Mirror & Push Mirror Registration
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
# 3. Local Git Workflow (push existing commits before Gitea pull-mirroring)
if is_existing_git:
link_and_push_existing(
gitea_host=gitea_host,
user=actual_owner,
gitea_host="github.com",
user=actual_gh_owner,
repo_name=repo_name,
target_dir=target_dir,
clone_url=actual_clone_url,
clone_url=github_ssh_url,
ssh_key=creds.ssh_key,
)
elif not args.no_clone:
clone_locally(
gitea_host=gitea_host,
user=actual_owner,
gitea_host="github.com",
user=actual_gh_owner,
repo_name=repo_name,
target_dir=target_dir,
clone_url=actual_clone_url,
clone_url=github_ssh_url,
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
print("\n🎉 Provisioning complete!")
print(f" Primary Forge: {gitea_html_url}")
if github_html_url:
print(f" Backup Mirror: {github_html_url}")
print(f" Primary Forge (GitHub): {github_html_url}")
if gitea_html_url:
print(f" Pull Mirror (Gitea): {gitea_html_url}")
print(f" Working Tree: {target_dir}")
+54 -34
View File
@@ -37,14 +37,14 @@ class TestArgParsing(unittest.TestCase):
args = parse_args()
self.assertEqual(args.name, "sample-project")
self.assertIsNone(args.org)
self.assertIsNone(args.github_org)
self.assertIsNone(args.gitea_org)
self.assertFalse(args.private)
self.assertEqual(args.license, "Unlicense")
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)
self.assertIsNone(args.gitea_mirror)
def test_as_persona_argument(self) -> None:
import sys
@@ -53,16 +53,16 @@ class TestArgParsing(unittest.TestCase):
args = parse_args()
self.assertEqual(args.as_persona, "anneux")
def test_migrate_arguments(self) -> None:
def test_gitea_mirror_arguments(self) -> None:
import sys
sys.argv = ["new-repo", "--migrate"]
sys.argv = ["new-repo", "--gitea-mirror"]
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()
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:
import sys
@@ -78,9 +78,9 @@ class TestArgParsing(unittest.TestCase):
"new-repo",
"open-api",
"-o",
"my-gh-org",
"--gitea-org",
"homelab",
"--github-org",
"homelab-gh",
"--private",
"-d",
"My public API",
@@ -93,54 +93,74 @@ class TestArgParsing(unittest.TestCase):
]
args = parse_args()
self.assertEqual(args.name, "open-api")
self.assertEqual(args.org, "homelab")
self.assertEqual(args.github_org, "homelab-gh")
self.assertEqual(args.org, "my-gh-org")
self.assertEqual(args.gitea_org, "homelab")
self.assertTrue(args.private)
self.assertEqual(args.description, "My public API")
self.assertEqual(args.license, "MIT")
self.assertEqual(args.template, "template-fastapi")
self.assertTrue(args.no_mirror)
self.assertTrue(args.no_clone)
self.assertIsNone(args.migrate)
self.assertIsNone(args.gitea_mirror)
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:
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:
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")
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_unrecognized_license_lowercase(self) -> None:
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")
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()
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)
self.assertTrue(payload["mirror"])
self.assertTrue(payload["private"])
self.assertEqual(payload["service"], "github")
class TestOrganizationAndTargetResolution(unittest.TestCase):