diff --git a/flake.lock b/flake.lock index 0cbb734..97dffd2 100644 --- a/flake.lock +++ b/flake.lock @@ -248,6 +248,22 @@ "type": "github" } }, + "new-repo": { + "flake": false, + "locked": { + "lastModified": 1791671941, + "narHash": "sha256-fi7ZpV/VqPlXeDQB38ueIzpgek5NeyqnniXyquN+N3Q=", + "owner": "kiskaadee", + "repo": "new-repo", + "rev": "75a09f2ad87dab673dcbcd84c4c966da2e69560a", + "type": "github" + }, + "original": { + "owner": "kiskaadee", + "repo": "new-repo", + "type": "github" + } + }, "nixpkgs": { "locked": { "lastModified": 1791594108, @@ -270,6 +286,7 @@ "dgop": "dgop", "dms": "dms", "home-manager": "home-manager", + "new-repo": "new-repo", "nixpkgs": "nixpkgs", "zen-browser": "zen-browser" } diff --git a/flake.nix b/flake.nix index 840b164..c2f8099 100644 --- a/flake.nix +++ b/flake.nix @@ -53,6 +53,12 @@ url = "github:jacopone/antigravity-nix"; inputs.nixpkgs.follows = "nixpkgs"; }; + + # new-repo - Automated repository provisioning CLI across Gitea and GitHub + new-repo = { + url = "github:kiskaadee/new-repo"; + flake = false; + }; }; # --- System Outputs --- diff --git a/home/scripts/new-repo.py b/home/scripts/new-repo.py deleted file mode 100755 index 734355d..0000000 --- a/home/scripts/new-repo.py +++ /dev/null @@ -1,975 +0,0 @@ -#!/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 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. - """ - - gitea_url: str - gitea_user: str - gitea_token: str - github_user: str - github_token: str - - -class SecretProvider: - """Resolves API credentials using a multi-tier fallback strategy. - - Hierarchy: - 1. Process environment variables (GITEA_TOKEN, GITHUB_TOKEN, etc.). - 2. Local .env file in the current working directory or repository root. - 3. Laptop SOPS encrypted secrets file (~/Config/secrets.yaml). - 4. Legacy fallbacks (tea CLI config for Gitea, Homelab SOPS file for GitHub). - """ - - @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 - - @staticmethod - def _extract_tea_login() -> tuple[str | None, str | None, str | None]: - """Extract Gitea credentials from ~/.config/tea/config.yml if the tea CLI is configured. - - Returns: - A tuple of (token, url, user), or None for missing values. - """ - tea_cfg = Path.home() / ".config" / "tea" / "config.yml" - if not tea_cfg.is_file(): - return None, None, None - - token: str | None = None - url: str | None = None - user: str | None = None - - try: - with open(tea_cfg, "r", encoding="utf-8") as f: - for line in f: - line = line.strip() - if line.startswith("token:"): - token = line.split(":", 1)[1].strip().strip("\"'") - elif line.startswith("url:"): - url = line.split(":", 1)[1].strip().strip("\"'") - elif line.startswith("user:"): - user = line.split(":", 1)[1].strip().strip("\"'") - return token, url, user - except OSError: - return None, None, None - - @classmethod - def resolve(cls) -> Credentials: - """Resolve all necessary credentials following the multi-tier hierarchy. - - 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) - - 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 = ( - Path(os.environ["HOMELAB_SECRETS_FILE"]) - if "HOMELAB_SECRETS_FILE" in os.environ - else Path.home() / "Homelab" / "Core" / "nixos" / "secrets.yaml" - ) - - # 1. Gitea resolution - tea_token, tea_url, tea_user = cls._extract_tea_login() - - gitea_url = get_val("GITEA_URL") or tea_url or "https://gitea.roadtotech.me" - gitea_user = get_val("GITEA_USER") or tea_user or "kiskaadee" - gitea_token = ( - get_val("GITEA_TOKEN") - or cls._extract_sops_key(["gitea", "api_token"], config_secrets) - or tea_token - ) - - if not gitea_token: - print( - "Error: Unable to resolve Gitea API token.\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. Configure tea CLI via 'tea login add'\n" - "\n" - "Note: In Gitea, generate a token at: User Settings -> Applications -> Manage Access Tokens.", - file=sys.stderr, - ) - sys.exit(1) - - # 2. GitHub resolution - 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(["system", "gh_repo_token"], homelab_secrets) - ) - - if not github_token: - print( - "Error: Unable to resolve GitHub API token.\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, - ) - - -# ============================================================================== -# 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 - raise RuntimeError(f"Gitea API error ({e.code} {e.reason}): {msg}") from e - except urllib.error.URLError as e: - raise RuntimeError(f"Gitea network error: {e.reason}") from e - - def create_repo( - self, - name: str, - private: bool = True, - description: str = "", - auto_init: bool = True, - license_name: str = "UNLICENSE", - ) -> dict[str, Any]: - """Create a new repository under the authenticated user account.""" - payload: dict[str, Any] = { - "name": name, - "private": private, - "description": description, - "auto_init": auto_init, - "default_branch": "main", - } - if license_name: - payload["license"] = license_name - - return self._request("POST", "/api/v1/user/repos", payload) - - def generate_from_template( - self, - template_owner: str, - template_name: str, - name: str, - private: bool = True, - description: str = "", - ) -> dict[str, Any]: - """Generate a new repository from an existing Gitea template repository.""" - payload = { - "owner": 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") - raise RuntimeError( - f"Gitea API error ({e.code} {e.reason}): {raw_err}" - ) from e - except urllib.error.URLError as e: - raise RuntimeError(f"Gitea network error: {e.reason}") from e - - def migrate_repo( - self, - clone_addr: str, - repo_name: str, - github_token: str, - private: bool = True, - description: str = "", - ) -> 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. - """ - payload = { - "clone_addr": clone_addr, - "auth_token": github_token, - "repo_name": repo_name, - "repo_owner": self.user, - "service": "github", - "mirror": False, - "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", - ) -> 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, - } - path = f"/api/v1/repos/{self.user}/{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 create_empty_repo( - self, - name: str, - private: bool = True, - description: str = "", - ) -> 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") - - req = urllib.request.Request( - url=f"{self.api_url}/user/repos", - data=data, - headers={ - "Authorization": f"Bearer {self.token}", - "Accept": "application/vnd.github+json", - "X-GitHub-Api-Version": "2022-11-28", - "Content-Type": "application/json", - }, - method="POST", - ) - - 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 - raise RuntimeError(f"GitHub API error ({e.code} {e.reason}): {msg}") from e - except urllib.error.URLError as e: - raise RuntimeError(f"GitHub network error: {e.reason}") from e - - -# ============================================================================== -# Local Git Orchestration -# ============================================================================== - - -def clone_locally(gitea_host: str, user: str, repo_name: str, target_dir: Path) -> 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 - - clone_url = f"git@{gitea_host}:{user}/{repo_name}.git" - print(f"šŸ“¦ Cloning repository locally into '{target_dir.name}'...") - try: - subprocess.run( - ["git", "clone", clone_url, str(target_dir)], - check=True, - capture_output=True, - text=True, - ) - 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 -) -> None: - """Links an existing local git repository to the new Gitea remote and pushes commits.""" - clone_url = f"git@{gitea_host}:{user}/{repo_name}.git" - print(f"šŸ”— Setting remote 'origin' to {clone_url}...") - 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", clone_url], - cwd=target_dir, - check=True, - ) - print(" Updated existing 'origin' remote URL.") - else: - subprocess.run( - ["git", "remote", "add", "origin", 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, - ) - print(f"āœ… Successfully pushed '{current_branch}' to Gitea!") - except subprocess.CalledProcessError as e: - print(f"āš ļø Failed to link/push repository: {e}", file=sys.stderr) - - -def determine_target(name_arg: str | None) -> tuple[str, Path, bool]: - """Determine (repo_name, target_dir, is_existing_git). - - Returns: - repo_name: The clean repository name for Gitea and GitHub. - target_dir: The directory on disk. - is_existing_git: True if target_dir is an existing git repository. - """ - cwd = Path.cwd() - if not name_arg or name_arg.strip() == ".": - repo_name = cwd.name - target_dir = cwd - else: - name_clean = name_arg.strip() - if name_clean == cwd.name: - repo_name = name_clean - target_dir = cwd - elif (cwd / name_clean).is_dir(): - repo_name = name_clean - target_dir = cwd / name_clean - else: - repo_name = name_clean - target_dir = cwd / name_clean - - is_existing_git = (target_dir / ".git").is_dir() - return repo_name, target_dir, is_existing_git - - -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 across self-hosted Gitea and GitHub push mirror.", - ) - parser.add_argument( - "name", - nargs="?", - default=None, - type=str, - help="Name of the repository to create (defaults to current directory if omitted or '.')", - ) - parser.add_argument( - "-p", - "--public", - action="store_true", - default=False, - help="Make repository public (default: private)", - ) - parser.add_argument( - "-d", - "--description", - type=str, - default="", - help="Description for the repository", - ) - parser.add_argument( - "-l", - "--license", - type=str, - default="UNLICENSE", - help="License identifier template (default: UNLICENSE, pass empty string to disable)", - ) - parser.add_argument( - "-t", - "--template", - type=str, - default=None, - help="Optional Gitea template repository ('[owner/]template-name')", - ) - parser.add_argument( - "-M", - "--no-mirror", - action="store_true", - default=False, - help="Disable automatic offsite push mirroring to GitHub", - ) - parser.add_argument( - "--no-clone", - action="store_true", - default=False, - help="Skip cloning the repository locally after creation", - ) - parser.add_argument( - "--migrate", - 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)", - ) - return parser.parse_args() - - -def main() -> None: - """Main orchestration flow.""" - args = parse_args() - is_private: bool = not args.public - - # 1. Resolve Credentials - creds = SecretProvider.resolve() - 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] - - # -------------------------------------------------------------------------- - # Migration Workflow (--migrate) - # -------------------------------------------------------------------------- - if args.migrate is not None: - try: - migrated_name, gh_owner, gh_clone_url = parse_github_target( - args.migrate, Path.cwd() - ) - except (ValueError, RuntimeError) as e: - print(f"āŒ Error: {e}", file=sys.stderr) - sys.exit(1) - - # Allow explicit positional name to override destination repo name - if args.name and args.name.strip() and args.name.strip() != ".": - dest_name = args.name.strip() - else: - dest_name = migrated_name - - print( - f"šŸš€ Initiating repository migration: '{gh_owner}/{migrated_name}' -> Gitea '{creds.gitea_user}/{dest_name}'" - ) - print(f" Visibility: {'Private' if is_private else 'Public'}") - - # Fail-safe conflict check - if gitea_client.repo_exists(creds.gitea_user, dest_name): - print( - f"āŒ Error: Repository '{dest_name}' already exists on Gitea under '{creds.gitea_user}'.\n" - f" Inspect at: {creds.gitea_url}/{creds.gitea_user}/{dest_name}\n" - " Aborting migration 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..." - ) - 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, - ) - gitea_html_url = res.get( - "html_url", f"{creds.gitea_url}/{creds.gitea_user}/{dest_name}" - ) - print(f"āœ… Gitea repository created from GitHub: {gitea_html_url}") - except RuntimeError as e: - print(f"āŒ Migration 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", - ) - 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 = f"git@{gitea_host}:{creds.gitea_user}/{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=creds.gitea_user, - repo_name=dest_name, - target_dir=Path.cwd() / dest_name, - ) - - print("\nšŸŽ‰ Migration complete!") - print(f" Primary Forge (Gitea): {gitea_html_url}") - print(f" Backup Mirror (GitHub): {gh_clone_url}") - return - - # -------------------------------------------------------------------------- - # Standard Provisioning Workflow - # -------------------------------------------------------------------------- - repo_name, target_dir, is_existing_git = determine_target(args.name) - - if not repo_name: - print("Error: Repository name cannot be determined.", file=sys.stderr) - sys.exit(1) - - print(f"šŸš€ Initializing repository provisioning: '{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 - try: - if is_existing_git: - print( - "šŸ—ļø Creating empty primary repository on Gitea (preserving local history)..." - ) - res = gitea_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="", - ) - 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 = creds.gitea_user, template_parts[0] - - print( - f"šŸ—ļø Generating Gitea repository from template '{tmpl_owner}/{tmpl_name}'..." - ) - res = gitea_client.generate_from_template( - template_owner=tmpl_owner, - template_name=tmpl_name, - name=repo_name, - private=is_private, - description=args.description, - ) - else: - print("šŸ—ļø Creating primary repository on Gitea...") - res = gitea_client.create_repo( - name=repo_name, - private=is_private, - description=args.description, - auto_init=True, - license_name=args.license, - ) - gitea_html_url = res.get( - "html_url", f"{creds.gitea_url}/{creds.gitea_user}/{repo_name}" - ) - print(f"āœ… Gitea repository created: {gitea_html_url}") - except RuntimeError as e: - print(f"āŒ Failed to create Gitea 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, - ) - github_html_url = gh_res.get( - "html_url", f"https://github.com/{creds.github_user}/{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/{creds.github_user}/{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", - ) - 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: - link_and_push_existing( - gitea_host=gitea_host, - user=creds.gitea_user, - repo_name=repo_name, - target_dir=target_dir, - ) - elif not args.no_clone: - clone_locally( - gitea_host=gitea_host, - user=creds.gitea_user, - repo_name=repo_name, - target_dir=target_dir, - ) - - # 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" Working Tree: {target_dir}") - - -if __name__ == "__main__": - main() diff --git a/home/shell.nix b/home/shell.nix index 7f60b21..68f004d 100644 --- a/home/shell.nix +++ b/home/shell.nix @@ -1,7 +1,7 @@ # 🐚 User Shell, Terminal Multiplexing & Git Environment # Bash aliases, modular shell scripts, Git, Delta, Gh, Direnv, SSH client, Tmux, Starship, and Fastfetch. -{ pkgs, ... }: +{ inputs, pkgs, ... }: let # Hermetic packaging for project-driven persistent terminal workspaces @@ -19,10 +19,21 @@ let ]; text = builtins.readFile ./scripts/tmux-sessionizer.sh; }; + + # Declarative provisioning CLI packaged hermetically from remote flake input + newRepo = pkgs.runCommand "new-repo" { + nativeBuildInputs = [ pkgs.python3 ]; + } '' + mkdir -p $out/bin + cp ${inputs.new-repo}/new_repo.py $out/bin/new-repo + chmod +x $out/bin/new-repo + patchShebangs $out/bin/new-repo + ''; in { home.packages = [ tmuxSessionizer + newRepo ]; programs = { @@ -269,9 +280,4 @@ in # Link fastfetch config home.file.".config/fastfetch/config.jsonc".source = ./config/fastfetch/config.jsonc; - # Declarative workstation scripts - home.file.".local/bin/new-repo" = { - source = ./scripts/new-repo.py; - executable = true; - }; }