#!/usr/bin/env python3 """new-repo: Automated repository provisioning across Gitea and GitHub push mirrors. This tool provisions a sovereign primary repository on self-hosted Gitea (with license, auto-init, or template), provisions an empty offsite backup repository on GitHub, registers Gitea automated push mirroring with in-memory authentication, and clones the working tree locally. Architecture & Design: - Primary Configuration Contract: 12-Factor Environment Variables (`GITEA_TOKEN`, `GITHUB_TOKEN`). - Workstation Secret Fallback: Mozilla SOPS / Age RAM decryption when environment variables are unset. - Zero External Dependencies: Built strictly with Python 3 standard library modules. - Type Safety & Standards: Full static type annotations (Pyright) and Ruff formatted. """ from __future__ import annotations import argparse import json import os import re import subprocess import sys import urllib.error import urllib.request from collections.abc import Mapping from dataclasses import dataclass from pathlib import Path from typing import Any # ============================================================================== # Configuration & Credentials Management # ============================================================================== @dataclass(frozen=True) class Credentials: """Resolved credentials and endpoint targets for Gitea and GitHub APIs. Attributes: gitea_url: Base HTTPS/HTTP URL of the Gitea instance (e.g. 'https://gitea.roadtotech.me'). gitea_user: Gitea username owning the primary repository. gitea_token: Gitea Personal Access Token with repository read/write permissions. github_user: GitHub username owning the offsite backup mirror repository. github_token: GitHub Personal Access Token with repository creation permissions. ssh_key: Optional path to dedicated SSH identity file for git operations. """ gitea_url: str gitea_user: str gitea_token: str github_user: str github_token: str ssh_key: str | None = None def redact_sensitive(text: str, *sensitive_values: str | None) -> str: """Scrub sensitive tokens, credentials, and URL userinfo from string.""" if not text: return text result = text # 1. Explicitly replace known sensitive values for val in sensitive_values: if val and isinstance(val, str) and len(val.strip()) > 3: result = result.replace(val.strip(), "[REDACTED]") # 2. Redact credentials embedded in URLs: http(s)://user:pass@host or http(s)://token@host result = re.sub(r"(https?://)([^:]+):([^@]+)@", r"\1\2:[REDACTED]@", result) result = re.sub(r"(https?://)([^@/:]+)@", r"\1[REDACTED]@", result) # 3. Redact Authorization header values if present in text result = re.sub( r"(?i)(token|bearer)\s+[a-zA-Z0-9_\-\.]{8,}", r"\1 [REDACTED]", result ) return result class SecretProvider: """Resolves API credentials using a multi-tier fallback strategy. Precedence Hierarchy: 1. Direct environment variables (GITEA_URL, GITEA_USER, GITEA_TOKEN, GITHUB_TOKEN). 2. Local .env file (development overrides). 3. Persona-scoped SOPS (~/Config/secrets..yaml or persona secrets file when --as is passed). 4. Default SOPS (~/Config/secrets.yaml, ~/Homelab/secrets.yaml). 5. System host CLI fallback: gt token via environment or gt auth token execution. """ @staticmethod def _load_dotenv(dotenv_path: Path) -> dict[str, str]: """Parse a simple .env file without external dependencies. Lines starting with '#' or lacking '=' are ignored. Quotes around values are stripped. Variables already present in `os.environ` take precedence. """ env_vars: dict[str, str] = {} if not dotenv_path.is_file(): return env_vars try: with open(dotenv_path, "r", encoding="utf-8") as f: for line in f: line = line.strip() if not line or line.startswith("#") or "=" not in line: continue k, v = line.split("=", 1) k = k.strip() v = v.strip().strip("'\"") if k and k not in os.environ: env_vars[k] = v except OSError: pass return env_vars @staticmethod def _extract_sops_key(key_path: list[str], secrets_file: Path) -> str | None: """Extract a single key from a SOPS-encrypted file directly into process memory. Uses `sops -d --extract` to retrieve only the requested key string without decrypting the entire file to disk or leaking plaintext into command-line arguments. """ if not secrets_file.is_file(): return None extract_arg = "".join(f'["{k}"]' for k in key_path) try: res = subprocess.run( ["sops", "-d", "--extract", extract_arg, str(secrets_file)], capture_output=True, text=True, check=False, ) if res.returncode == 0 and res.stdout.strip(): return res.stdout.strip() except FileNotFoundError: return None return None @classmethod def _extract_gt_token(cls, target_persona: str | None = None) -> str | None: """Extract Gitea token from host 'gt' CLI fallback.""" cmd = ["gt", "auth", "token"] if target_persona: cmd.extend(["--user", target_persona]) try: res = subprocess.run( cmd, capture_output=True, text=True, check=False, ) if res.returncode == 0 and res.stdout.strip(): return res.stdout.strip() except FileNotFoundError: return None return None @classmethod def resolve(cls, as_persona: str | None = None) -> Credentials: """Resolve all necessary credentials following the multi-tier hierarchy. Args: as_persona: Optional persona/login name (e.g. 'anneux'). Raises: SystemExit: If Gitea or GitHub tokens cannot be resolved from any source. """ # Load local .env if present dotenv = cls._load_dotenv(Path.cwd() / ".env") def get_val(key: str) -> str | None: return os.environ.get(key) or dotenv.get(key) persona = as_persona or get_val("NEW_REPO_AS") or get_val("TEA_LOGIN") gitea_url = get_val("GITEA_URL") or "https://gitea.roadtotech.me" if persona: # ------------------------------------------------------------------ # Persona-Scoped Credential Resolution # Strict isolation: NEVER fall through to default root credentials. # ------------------------------------------------------------------ persona_norm = persona.strip() persona_upper = persona_norm.upper() env_gitea_user = get_val("GITEA_USER") # Check if env/dotenv explicitly provides credentials for this persona. # If GITEA_USER is set and does not match the persona, direct GITEA_TOKEN # belongs to a different forge user and must not be used. persona_env_token = get_val(f"GITEA_TOKEN_{persona_upper}") if not persona_env_token and ( env_gitea_user is None or env_gitea_user.lower() == persona_norm.lower() ): persona_env_token = get_val("GITEA_TOKEN") persona_gh_token = get_val(f"GITHUB_TOKEN_{persona_upper}") or get_val("GITHUB_TOKEN") # Candidate persona SOPS files persona_sops: Path | None = None persona_candidates: list[Path] = [] if os.environ.get("PERSONA_SECRETS_FILE"): persona_candidates.append(Path(os.environ["PERSONA_SECRETS_FILE"])) persona_candidates.extend([ Path.home() / "Config" / f"secrets.{persona_norm}.yaml", Path.home() / "Config" / f"{persona_norm}-secrets.yaml", Path.home() / "Config" / f"secrets.{persona_norm.rstrip('ux')}.yaml", Path.home() / "Config" / f"{persona_norm.rstrip('ux')}-secrets.yaml", ]) for c in persona_candidates: if c.is_file(): persona_sops = c break gitea_user = persona_norm gitea_token = ( persona_env_token or (cls._extract_sops_key(["gitea", "token"], persona_sops) if persona_sops else None) or (cls._extract_sops_key(["gitea", "api_token"], persona_sops) if persona_sops else None) or cls._extract_gt_token(target_persona=persona_norm) ) github_user = get_val("GITHUB_USER") or persona_norm github_token = ( persona_gh_token or (cls._extract_sops_key(["github", "token"], persona_sops) if persona_sops else None) or (cls._extract_sops_key(["github", "api_token"], persona_sops) if persona_sops else None) ) ssh_key = ( get_val("GITEA_SSH_KEY") or (cls._extract_sops_key(["gitea", "ssh_key"], persona_sops) if persona_sops else None) ) if not gitea_token: print( f"Error: Unable to resolve Gitea API token for persona '{gitea_user}'.\n" "To provide credentials for this persona, either:\n" " 1. Export GITEA_TOKEN in your environment (or define in a .env file)\n" f" 2. Add 'gitea.token' or 'gitea.api_token' to ~/Config/secrets.{persona_norm}.yaml (or {persona_norm}-secrets.yaml) via SOPS\n" f" 3. Authenticate the persona using 'gt auth login --user {gitea_user}'\n\n" "Note: In Gitea, generate a token at: User Settings -> Applications -> Manage Access Tokens.", file=sys.stderr, ) sys.exit(1) if not github_token: print( f"Error: Unable to resolve GitHub API token for persona '{github_user}'.\n" "To provide credentials for this persona, either:\n" " 1. Export GITHUB_TOKEN in your environment (or define in a .env file)\n" f" 2. Add 'github.token' or 'github.api_token' to ~/Config/secrets.{persona_norm}.yaml (or {persona_norm}-secrets.yaml) via SOPS\n", file=sys.stderr, ) sys.exit(1) else: # ------------------------------------------------------------------ # Default / Root User Credential Resolution # ------------------------------------------------------------------ secrets_file_env = os.environ.get("SECRETS_FILE") config_secrets = ( Path(secrets_file_env) if secrets_file_env else Path.home() / "Config" / "secrets.yaml" ) homelab_secrets_env = os.environ.get("HOMELAB_SECRETS_FILE") homelab_candidates = [ Path(homelab_secrets_env) if homelab_secrets_env else None, Path.home() / "Homelab" / "secrets.yaml", Path.home() / "Homelab" / "Core" / "nixos" / "secrets.yaml", ] homelab_secrets = next((p for p in homelab_candidates if p and p.is_file()), None) gitea_user = get_val("GITEA_USER") or "kiskaadee" gitea_token = ( get_val("GITEA_TOKEN") or cls._extract_sops_key(["gitea", "token"], config_secrets) or cls._extract_sops_key(["gitea", "api_token"], config_secrets) or (cls._extract_sops_key(["gitea", "token"], homelab_secrets) if homelab_secrets else None) or (cls._extract_sops_key(["gitea", "api_token"], homelab_secrets) if homelab_secrets else None) or cls._extract_gt_token() ) github_user = get_val("GITHUB_USER") or "kiskaadee" github_token = ( get_val("GITHUB_TOKEN") or cls._extract_sops_key(["system", "gh_repo_token"], config_secrets) or cls._extract_sops_key(["github", "token"], config_secrets) or (cls._extract_sops_key(["system", "gh_repo_token"], homelab_secrets) if homelab_secrets else None) or (cls._extract_sops_key(["github", "token"], homelab_secrets) if homelab_secrets else None) ) ssh_key = ( get_val("GITEA_SSH_KEY") or cls._extract_sops_key(["gitea", "ssh_key"], config_secrets) or (cls._extract_sops_key(["gitea", "ssh_key"], homelab_secrets) if homelab_secrets else None) ) if not gitea_token: print( f"Error: Unable to resolve Gitea API token for user '{gitea_user}'.\n" "To provide credentials, either:\n" " 1. Export GITEA_TOKEN in your environment (or define in a .env file)\n" " 2. Add 'gitea.api_token' to ~/Config/secrets.yaml via SOPS\n" " 3. Authenticate using 'gt auth login'\n\n" "Note: In Gitea, generate a token at: User Settings -> Applications -> Manage Access Tokens.", file=sys.stderr, ) sys.exit(1) if not github_token: print( f"Error: Unable to resolve GitHub API token for user '{github_user}'.\n" "To provide credentials, either:\n" " 1. Export GITHUB_TOKEN in your environment (or define in a .env file)\n" " 2. Add 'system.gh_repo_token' to ~/Config/secrets.yaml via SOPS\n", file=sys.stderr, ) sys.exit(1) return Credentials( gitea_url=gitea_url, gitea_user=gitea_user, gitea_token=gitea_token, github_user=github_user, github_token=github_token, ssh_key=ssh_key, ) # ============================================================================== # License Registry & Normalization # ============================================================================== 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 GitHub's lowercase license_template registry.""" if not license_name: return "" clean = license_name.strip() if not clean: return "" return GITHUB_LICENSES.get(clean.lower(), clean.lower()) # ============================================================================== # API Clients # ============================================================================== class GiteaClient: """REST API Client for self-hosted Gitea instances. Handles repo creation, template repository generation, and push mirror configuration. """ def __init__(self, base_url: str, user: str, token: str) -> None: self.base_url = base_url.rstrip("/") self.user = user self.token = token def _request( self, method: str, path: str, payload: Mapping[str, Any] | None = None, ) -> dict[str, Any]: """Send an authenticated JSON HTTP request to the Gitea API.""" url = f"{self.base_url}{path}" data = json.dumps(payload).encode("utf-8") if payload is not None else None req = urllib.request.Request( url=url, data=data, headers={ "Authorization": f"token {self.token}", "Content-Type": "application/json", "Accept": "application/json", }, method=method, ) try: with urllib.request.urlopen(req) as resp: raw = resp.read().decode("utf-8") return json.loads(raw) if raw.strip() else {} except urllib.error.HTTPError as e: raw_err = e.read().decode("utf-8", errors="replace") try: err_data = json.loads(raw_err) msg = err_data.get("message", raw_err) except (json.JSONDecodeError, UnicodeDecodeError): msg = raw_err payload_tokens = [] if payload and isinstance(payload, dict): for k in ("remote_password", "auth_token", "token", "password"): v = payload.get(k) if isinstance(v, str): payload_tokens.append(v) sanitized_msg = redact_sensitive(msg, self.token, *payload_tokens) sanitized_reason = redact_sensitive(str(e.reason), self.token, *payload_tokens) raise RuntimeError( f"Gitea API error ({e.code} {sanitized_reason}): {sanitized_msg}" ) from e except urllib.error.URLError as e: sanitized_reason = redact_sensitive(str(e.reason), self.token) raise RuntimeError(f"Gitea network error: {sanitized_reason}") from e def get_authenticated_user(self) -> str: """Return the authenticated username associated with the token.""" try: res = self._request("GET", "/api/v1/user") return res.get("username") or res.get("login") or "" except (RuntimeError, urllib.error.URLError, urllib.error.HTTPError, OSError): return "" def org_exists(self, org: str) -> bool: """Check if an organization exists on Gitea.""" url = f"{self.base_url}/api/v1/orgs/{org}" req = urllib.request.Request( url=url, headers={ "Authorization": f"token {self.token}", "Accept": "application/json", }, method="GET", ) try: with urllib.request.urlopen(req) as resp: return resp.status == 200 except urllib.error.HTTPError as e: if e.code == 404: return False raw_err = e.read().decode("utf-8", errors="replace") sanitized_err = redact_sensitive(raw_err, self.token) sanitized_reason = redact_sensitive(str(e.reason), self.token) raise RuntimeError( f"Gitea API error checking org '{org}' ({e.code} {sanitized_reason}): {sanitized_err}" ) from e except urllib.error.URLError as e: sanitized_reason = redact_sensitive(str(e.reason), self.token) raise RuntimeError(f"Gitea network error: {sanitized_reason}") from e def create_org( self, org: str, visibility: str = "private", ) -> dict[str, Any]: """Create a new organization on Gitea.""" payload: dict[str, Any] = { "username": org, "visibility": visibility, } return self._request("POST", "/api/v1/orgs", payload) def ensure_org(self, org: str, private: bool = False) -> bool: """Ensure a Gitea organization exists, creating it if missing. Returns: True if a new organization was created, False if it already existed. """ if self.org_exists(org): return False visibility = "private" if private else "public" try: self.create_org(org, visibility=visibility) return True except RuntimeError as e: raise RuntimeError( f"Failed to create Gitea organization '{org}': {e}\n" "Hint: Ensure your GITEA_TOKEN has 'write:organization' (or 'admin:org') permission scope." ) from e def create_repo( self, name: str, private: bool = False, description: str = "", auto_init: bool = True, license_name: str = "Unlicense", org: str | None = None, ) -> dict[str, Any]: """Create a new repository under the authenticated user or specified organization.""" payload: dict[str, Any] = { "name": name, "private": private, "description": description, "auto_init": auto_init, "default_branch": "main", } normalized_license = normalize_license(license_name) if normalized_license: payload["license"] = normalized_license endpoint = f"/api/v1/orgs/{org}/repos" if org else "/api/v1/user/repos" return self._request("POST", endpoint, payload) 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 repository from an existing Gitea template repository.""" payload = { "owner": owner or self.user, "name": name, "private": private, "description": description, } path = f"/api/v1/repos/{template_owner}/{template_name}/generate" return self._request("POST", path, payload) def repo_exists(self, owner: str, name: str) -> bool: """Check if a repository already exists on Gitea under the given owner.""" url = f"{self.base_url}/api/v1/repos/{owner}/{name}" req = urllib.request.Request( url=url, headers={ "Authorization": f"token {self.token}", "Accept": "application/json", }, method="GET", ) try: with urllib.request.urlopen(req) as resp: return resp.status == 200 except urllib.error.HTTPError as e: if e.code == 404: return False raw_err = e.read().decode("utf-8", errors="replace") sanitized_err = redact_sensitive(raw_err, self.token) sanitized_reason = redact_sensitive(str(e.reason), self.token) raise RuntimeError( f"Gitea API error ({e.code} {sanitized_reason}): {sanitized_err}" ) from e except urllib.error.URLError as e: sanitized_reason = redact_sensitive(str(e.reason), self.token) raise RuntimeError(f"Gitea network error: {sanitized_reason}") from e def migrate_repo( self, clone_addr: str, repo_name: str, github_token: str, private: bool = False, description: str = "", repo_owner: str | None = None, mirror: bool = False, ) -> dict[str, Any]: """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": mirror, "private": private, "description": description, } return self._request("POST", "/api/v1/repos/migrate", payload) def create_push_mirror( self, repo_name: str, remote_address: str, remote_username: str, remote_password: str, sync_on_commit: bool = True, interval: str = "8h", owner: str | None = None, ) -> dict[str, Any]: """Register a push mirror for a Gitea repository to an external Git target.""" payload = { "remote_address": remote_address, "remote_username": remote_username, "remote_password": remote_password, "sync_on_commit": sync_on_commit, "interval": interval, } target_owner = owner or self.user path = f"/api/v1/repos/{target_owner}/{repo_name}/push_mirrors" return self._request("POST", path, payload) class GitHubClient: """REST API Client for GitHub repository management.""" def __init__(self, user: str, token: str) -> None: self.user = user self.token = token self.api_url = "https://api.github.com" def _request( self, method: str, path: str, payload: dict[str, Any] | None = None ) -> dict[str, Any]: """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", } 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") return json.loads(raw) if raw.strip() else {} except urllib.error.HTTPError as e: raw_err = e.read().decode("utf-8", errors="replace") try: err_data = json.loads(raw_err) msg = err_data.get("message", raw_err) except (json.JSONDecodeError, UnicodeDecodeError): msg = raw_err sanitized_msg = redact_sensitive(msg, self.token) sanitized_reason = redact_sensitive(str(e.reason), self.token) raise RuntimeError( f"GitHub API error ({e.code} {sanitized_reason}): {sanitized_msg}" ) from e except urllib.error.URLError as e: 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 # ============================================================================== def clone_locally( gitea_host: str, user: str, repo_name: str, target_dir: Path, clone_url: str | None = None, ssh_key: str | None = None, ) -> None: """Clones the newly created repository into the target directory.""" if target_dir.exists(): print(f"āš ļø Target directory '{target_dir}' already exists. Skipping clone.") return final_clone_url = clone_url or f"git@{gitea_host}:{user}/{repo_name}.git" print(f"šŸ“¦ Cloning repository locally into '{target_dir.name}'...") env = os.environ.copy() if ssh_key and Path(ssh_key).is_file(): env["GIT_SSH_COMMAND"] = f"ssh -i {ssh_key} -o IdentitiesOnly=yes" try: subprocess.run( ["git", "clone", final_clone_url, str(target_dir)], check=True, capture_output=True, text=True, env=env, ) print(f"āœ… Cloned successfully to {target_dir}") except subprocess.CalledProcessError as e: print(f"āš ļø Failed to clone repository: {e.stderr.strip()}", file=sys.stderr) def link_and_push_existing( gitea_host: str, user: str, repo_name: str, target_dir: Path, clone_url: str | None = None, ssh_key: str | None = None, ) -> None: """Links an existing local git repository to the new Gitea remote and pushes commits.""" final_clone_url = clone_url or f"git@{gitea_host}:{user}/{repo_name}.git" print(f"šŸ”— Setting remote 'origin' to {final_clone_url}...") env = os.environ.copy() if ssh_key and Path(ssh_key).is_file(): env["GIT_SSH_COMMAND"] = f"ssh -i {ssh_key} -o IdentitiesOnly=yes" try: remotes_out = subprocess.run( ["git", "remote"], cwd=target_dir, capture_output=True, text=True, check=True, ) remotes = remotes_out.stdout.split() if "origin" in remotes: subprocess.run( ["git", "remote", "set-url", "origin", final_clone_url], cwd=target_dir, check=True, ) print(" Updated existing 'origin' remote URL.") else: subprocess.run( ["git", "remote", "add", "origin", final_clone_url], cwd=target_dir, check=True, ) print(" Added 'origin' remote.") # Detect current branch branch_res = subprocess.run( ["git", "branch", "--show-current"], cwd=target_dir, capture_output=True, text=True, check=False, ) current_branch = branch_res.stdout.strip() or "main" print(f"šŸš€ Pushing branch '{current_branch}' to origin...") subprocess.run( ["git", "push", "-u", "origin", current_branch], cwd=target_dir, check=True, env=env, ) print(f"āœ… Successfully pushed '{current_branch}' to origin!") except subprocess.CalledProcessError as e: print(f"āš ļø Failed to link/push repository: {e}", file=sys.stderr) def resolve_name_and_org( name_arg: str | None, org_arg: str | None = None, ) -> tuple[str | None, str | None]: """Parse repository name and optional Gitea organization from CLI arguments. Supports both explicit `--org ` and positional `org/repo` shorthand. Raises: ValueError: If `name_arg` has an invalid slash format or conflicts with `org_arg`. """ explicit_org = org_arg.strip() if org_arg and org_arg.strip() else None if not name_arg or name_arg.strip() == ".": return None, explicit_org raw_name = name_arg.strip() if "/" in raw_name: parts = [p.strip() for p in raw_name.split("/") if p.strip()] if len(parts) != 2 or raw_name.startswith("/") or raw_name.endswith("/"): raise ValueError( f"Invalid repository target '{raw_name}'. Expected '' or '/'." ) shorthand_org, repo_name = parts[0], parts[1] if explicit_org and explicit_org != shorthand_org: raise ValueError( f"Conflicting organizations specified: positional '{shorthand_org}' vs --org '{explicit_org}'." ) return repo_name, shorthand_org return raw_name, explicit_org def determine_target( name_arg: str | None, org_arg: str | None = None, cwd: Path | None = None, ) -> tuple[str, Path, bool, str | None]: """Determine (repo_name, target_dir, is_existing_git, target_org). Returns: repo_name: The clean repository name for Gitea and GitHub. target_dir: The flat directory path on disk. is_existing_git: True if target_dir is an existing git repository. target_org: The resolved Gitea organization name, or None for personal user. """ base_dir = cwd if cwd is not None else Path.cwd() parsed_name, target_org = resolve_name_and_org(name_arg, org_arg) if not parsed_name: repo_name = base_dir.name target_dir = base_dir else: if parsed_name == base_dir.name: repo_name = parsed_name target_dir = base_dir else: repo_name = parsed_name target_dir = base_dir / parsed_name is_existing_git = (target_dir / ".git").is_dir() return repo_name, target_dir, is_existing_git, target_org def parse_github_target(target_str: str | None, cwd: Path) -> tuple[str, str, str]: """Parse a GitHub target string or detect it from local git remotes. Args: target_str: GitHub URL (HTTPS, SSH) or shorthand ('owner/repo'). If None or empty, auto-detects from the local 'origin' remote in cwd. cwd: Current working directory for auto-detection. Returns: tuple of (repo_name, github_owner, github_clone_url) Raises: ValueError: If target string cannot be parsed as a valid GitHub repository. RuntimeError: If auto-detection fails because cwd lacks a GitHub remote. """ raw = target_str.strip() if target_str else "" if not raw: # Auto-detect from local git repo if not (cwd / ".git").is_dir(): raise RuntimeError( "No GitHub URL provided, and current directory is not a Git repository. " "Please specify a target (e.g. --migrate https://github.com/owner/repo)." ) try: origin_url = subprocess.check_output( ["git", "remote", "get-url", "origin"], cwd=cwd, text=True, stderr=subprocess.DEVNULL, ).strip() raw = origin_url print(f"šŸ” Auto-detected GitHub target from local origin: {raw}") except subprocess.CalledProcessError as e: raise RuntimeError( "Could not detect 'origin' remote from current Git repository. " "Please specify a target (e.g. --migrate https://github.com/owner/repo)." ) from e clean = raw.strip().rstrip("/").removesuffix(".git") owner: str = "" name: str = "" if "github.com" in clean: # Matches https://github.com/owner/repo or git@github.com:owner/repo if ":" in clean and "@" in clean: path_part = clean.split(":", 1)[1] else: path_part = clean.split("github.com/", 1)[1] parts = [p for p in path_part.split("/") if p] if len(parts) >= 2: owner, name = parts[0], parts[1] elif "/" in clean: parts = [p for p in clean.split("/") if p] if len(parts) == 2: owner, name = parts[0], parts[1] if not owner or not name: raise ValueError( f"Could not parse GitHub repository owner and name from '{raw}'. " "Expected formats: https://github.com/owner/repo, git@github.com:owner/repo.git, or owner/repo." ) clone_url = f"https://github.com/{owner}/{name}.git" return name, owner, clone_url def reconfigure_local_remotes(target_dir: Path, gitea_clone_url: str) -> None: """Reconfigures local git remotes for a migrated repository. Renames existing 'origin' to 'github', sets Gitea as the new 'origin', and updates upstream tracking for the active branch. """ try: remotes_out = subprocess.run( ["git", "remote"], cwd=target_dir, capture_output=True, text=True, check=True, ) remotes = remotes_out.stdout.split() if "origin" in remotes: if "github" in remotes: print(" Remote 'github' already exists. Removing legacy 'origin'...") subprocess.run( ["git", "remote", "remove", "origin"], cwd=target_dir, check=True, ) else: print("šŸ”„ Renaming existing remote 'origin' to 'github'...") subprocess.run( ["git", "remote", "rename", "origin", "github"], cwd=target_dir, check=True, ) print(f"šŸ”— Setting new primary remote 'origin' to {gitea_clone_url}...") subprocess.run( ["git", "remote", "add", "origin", gitea_clone_url], cwd=target_dir, check=True, ) # Detect active branch branch_res = subprocess.run( ["git", "branch", "--show-current"], cwd=target_dir, capture_output=True, text=True, check=False, ) active_branch = branch_res.stdout.strip() or "main" print( f"šŸš€ Updating upstream tracking for branch '{active_branch}' to origin..." ) subprocess.run( [ "git", "branch", f"--set-upstream-to=origin/{active_branch}", active_branch, ], cwd=target_dir, capture_output=True, text=True, check=False, ) print("āœ… Local remotes reconfigured successfully!") except subprocess.CalledProcessError as e: print(f"āš ļø Failed to reconfigure local remotes: {e}", file=sys.stderr) # ============================================================================== # CLI Entrypoint & Workflow # ============================================================================== def parse_args() -> argparse.Namespace: """Parse command line arguments.""" parser = argparse.ArgumentParser( prog="new-repo", description="Provision repositories on GitHub with an automated Gitea pull mirror.", ) parser.add_argument( "name", nargs="?", default=None, type=str, help="Name of the repository to create ('[org/]repo', defaults to current directory if omitted or '.')", ) parser.add_argument( "-o", "--org", type=str, default=None, help="Target GitHub organization to own the repository (defaults to personal GITHUB_USER)", ) parser.add_argument( "--gitea-org", type=str, default=None, help="Optional Gitea organization for the homelab pull mirror (auto-created if missing; defaults to GITEA_USER)", ) parser.add_argument( "-p", "--private", action="store_true", default=False, help="Make repository private (default: public)", ) parser.add_argument( "-d", "--description", type=str, default="", help="Description for the repository", ) parser.add_argument( "-l", "--license", type=str, 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 GitHub template repository ('[owner/]template-name')", ) parser.add_argument( "-M", "--no-mirror", action="store_true", default=False, help="Disable automatic homelab pull mirroring to Gitea", ) parser.add_argument( "--no-clone", action="store_true", default=False, help="Skip cloning the repository locally after creation", ) parser.add_argument( "--empty", action="store_true", default=False, help="Create an empty GitHub repository with auto_init=False (no initial README or license commit)", ) parser.add_argument( "--as", dest="as_persona", type=str, default=None, help="Persona / login identity to provision as (e.g. anneux)", ) parser.add_argument( "--gitea-mirror", nargs="?", const="", default=None, metavar="GITHUB_URL", help="Attach a Gitea pull mirror to an existing GitHub repository (URL or auto-detect from local origin)", ) return parser.parse_args() def main() -> None: """Main orchestration flow.""" args = parse_args() is_private: bool = args.private # 1. Resolve Credentials creds = SecretProvider.resolve(as_persona=args.as_persona) gitea_client = GiteaClient( base_url=creds.gitea_url, user=creds.gitea_user, token=creds.gitea_token, ) github_client = GitHubClient( user=creds.github_user, token=creds.github_token, ) gitea_host = creds.gitea_url.split("://", 1)[-1].split("/", 1)[0].split(":", 1)[0] # -------------------------------------------------------------------------- # Attach Gitea Pull Mirror Workflow (--gitea-mirror) # -------------------------------------------------------------------------- if args.gitea_mirror is not None: try: mirrored_name, gh_owner, gh_clone_url = parse_github_target( args.gitea_mirror, Path.cwd() ) 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 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 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 mirror owner to token owner '{auth_user}'.", file=sys.stderr, ) gitea_owner = auth_user print( f"šŸš€ Attaching Gitea pull mirror: '{gh_owner}/{mirrored_name}' -> Gitea '{gitea_owner}/{dest_name}'" ) print(f" Visibility: {'Private' if is_private else 'Public'}") if gitea_org: try: created_org = gitea_client.ensure_org(gitea_org, private=is_private) if created_org: print(f"šŸ¢ Created new Gitea organization '{gitea_org}'") except RuntimeError as e: print(f"āŒ Error: {e}", file=sys.stderr) sys.exit(1) 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 to prevent overwriting existing repositories.", file=sys.stderr, ) sys.exit(1) print("šŸ”— Creating Gitea pull mirror from GitHub...") try: res = gitea_client.migrate_repo( clone_addr=gh_clone_url, repo_name=dest_name, github_token=creds.github_token, 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 pull mirror created: {gitea_html_url}") except RuntimeError as e: print(f"āŒ Pull mirror creation failed: {e}", file=sys.stderr) sys.exit(1) 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 (GitHub Primary + Gitea Pull Mirror) # -------------------------------------------------------------------------- try: repo_name, target_dir, is_existing_git, target_org = determine_target( args.name, args.org ) except ValueError as e: print(f"āŒ Error: {e}", file=sys.stderr) sys.exit(1) if not repo_name: print("Error: Repository name cannot be determined.", file=sys.stderr) sys.exit(1) 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 ) gitea_owner = gitea_org or creds.gitea_user 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 mirror owner to token owner '{auth_user}'.", file=sys.stderr, ) gitea_owner = auth_user 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 GitHub Primary Repository if args.empty and args.template: print("āŒ Error: --empty cannot be combined with --template.", file=sys.stderr) sys.exit(1) github_html_url: str github_ssh_url: str try: if is_existing_git or args.empty: print( "šŸ—ļø Creating empty primary repository on GitHub (auto_init=False)..." ) res = github_client.create_empty_repo( name=repo_name, private=is_private, description=args.description, org=target_org, ) elif args.template: template_parts = args.template.split("/", 1) if len(template_parts) == 2: tmpl_owner, tmpl_name = template_parts[0], template_parts[1] else: tmpl_owner, tmpl_name = github_owner, template_parts[0] print( f"šŸ—ļø Generating GitHub repository from template '{tmpl_owner}/{tmpl_name}'..." ) res = github_client.generate_from_template( template_owner=tmpl_owner, template_name=tmpl_name, name=repo_name, private=is_private, description=args.description, owner=github_owner, ) else: print("šŸ—ļø Creating primary repository on GitHub...") res = github_client.create_repo( name=repo_name, private=is_private, description=args.description, auto_init=True, license_template=args.license, org=target_org, ) 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"āœ… GitHub repository created: {github_html_url}") except RuntimeError as e: print(f"āŒ Failed to create GitHub repository: {e}", file=sys.stderr) sys.exit(1) # 3. Local Git Workflow (push existing commits before Gitea pull-mirroring) if is_existing_git: link_and_push_existing( gitea_host="github.com", user=actual_gh_owner, repo_name=repo_name, target_dir=target_dir, clone_url=github_ssh_url, ssh_key=creds.ssh_key, ) elif not args.no_clone: clone_locally( gitea_host="github.com", user=actual_gh_owner, repo_name=repo_name, target_dir=target_dir, 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 (GitHub): {github_html_url}") if gitea_html_url: print(f" Pull Mirror (Gitea): {gitea_html_url}") print(f" Working Tree: {target_dir}") if __name__ == "__main__": main()