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
This commit is contained in:
kiskaadee committed 2026-11-25 16:36:49 -05:00
1 parent 36233f50e0
commit 4c5820bace
2 files changed
+264 -251

No files matched your search

+210 -217
View File
@@ -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
View File
@@ -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):