diff --git a/new_repo.py b/new_repo.py index 59146e6..345c5de 100755 --- a/new_repo.py +++ b/new_repo.py @@ -330,50 +330,45 @@ class SecretProvider: # License Registry & Normalization # ============================================================================== -GITEA_LICENSES: dict[str, str] = { - "0bsd": "0BSD", - "agpl-3.0": "AGPL-3.0", - "apache-2.0": "Apache-2.0", - "bsd-2-clause": "BSD-2-Clause", - "bsd-3-clause": "BSD-3-Clause", - "bsd-3-clause-clear": "BSD-3-Clause-Clear", - "bsl-1.0": "BSL-1.0", - "cc-by-4.0": "CC-BY-4.0", - "cc-by-sa-4.0": "CC-BY-SA-4.0", - "cc0-1.0": "CC0-1.0", - "epl-1.0": "EPL-1.0", - "epl-2.0": "EPL-2.0", - "eupl-1.2": "EUPL-1.2", - "gpl-2.0": "GPL-2.0", - "gpl-3.0": "GPL-3.0", - "isc": "ISC", - "lgpl-2.1": "LGPL-2.1", - "lgpl-3.0": "LGPL-3.0", - "mit": "MIT", - "mit-0": "MIT-0", - "mpl-2.0": "MPL-2.0", - "mulanpsl-2.0": "MulanPSL-2.0", - "ofl-1.1": "OFL-1.1", - "osl-3.0": "OSL-3.0", - "upl-1.0": "UPL-1.0", - "unlicense": "Unlicense", - "wtfpl": "WTFPL", - "zlib": "Zlib", +GITHUB_LICENSES: dict[str, str] = { + "0bsd": "0bsd", + "agpl-3.0": "agpl-3.0", + "apache-2.0": "apache-2.0", + "bsd-2-clause": "bsd-2-clause", + "bsd-3-clause": "bsd-3-clause", + "bsd-3-clause-clear": "bsd-3-clause-clear", + "bsl-1.0": "bsl-1.0", + "cc-by-4.0": "cc-by-4.0", + "cc-by-sa-4.0": "cc-by-sa-4.0", + "cc0-1.0": "cc0-1.0", + "epl-1.0": "epl-1.0", + "epl-2.0": "epl-2.0", + "eupl-1.2": "eupl-1.2", + "gpl-2.0": "gpl-2.0", + "gpl-3.0": "gpl-3.0", + "isc": "isc", + "lgpl-2.1": "lgpl-2.1", + "lgpl-3.0": "lgpl-3.0", + "mit": "mit", + "mit-0": "mit-0", + "mpl-2.0": "mpl-2.0", + "ofl-1.1": "ofl-1.1", + "osl-3.0": "osl-3.0", + "upl-1.0": "upl-1.0", + "unlicense": "unlicense", + "wtfpl": "wtfpl", + "zlib": "zlib", } def normalize_license(license_name: str | None) -> str: - """Normalize license identifier to match Gitea's case-sensitive template registry. - - Gitea resolves license templates by exact filename in its internal assets. - For example, 'UNLICENSE' fails with a 500 error while 'Unlicense' succeeds. - """ + """Normalize license identifier to GitHub's lowercase license_template registry.""" if not license_name: return "" clean = license_name.strip() if not clean: return "" - return GITEA_LICENSES.get(clean.lower(), clean) + return GITHUB_LICENSES.get(clean.lower(), clean.lower()) # ============================================================================== @@ -582,19 +577,16 @@ class GiteaClient: private: bool = False, description: str = "", repo_owner: str | None = None, + mirror: bool = False, ) -> dict[str, Any]: - """Import an existing GitHub repository server-side into Gitea. - - Uses Gitea's POST /api/v1/repos/migrate with mirror=False to perform - a complete one-time import of all git branches, tags, and commits. - """ + """Import or pull-mirror an existing GitHub repository into Gitea.""" payload = { "clone_addr": clone_addr, "auth_token": github_token, "repo_name": repo_name, "repo_owner": repo_owner or self.user, "service": "github", - "mirror": False, + "mirror": mirror, "private": private, "description": description, } @@ -631,41 +623,21 @@ class GitHubClient: self.token = token self.api_url = "https://api.github.com" - def create_empty_repo( - self, - name: str, - private: bool = False, - description: str = "", - org: str | None = None, + def _request( + self, method: str, path: str, payload: dict[str, Any] | None = None ) -> dict[str, Any]: - """Create an empty target repository on GitHub with auto_init=False. - - Crucial invariant: The repository MUST be empty (no README, no license) - so that Gitea's push mirror can push all refs without fast-forward conflicts. - """ - payload = { - "name": name, - "private": private, - "description": description, - "auto_init": False, + """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", } - 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={ - "Authorization": f"Bearer {self.token}", - "Accept": "application/vnd.github+json", - "X-GitHub-Api-Version": "2022-11-28", - "Content-Type": "application/json", - }, - method="POST", - ) + if data is not None: + headers["Content-Type"] = "application/json" + req = urllib.request.Request(url=url, data=data, headers=headers, method=method) try: with urllib.request.urlopen(req) as resp: raw = resp.read().decode("utf-8") @@ -686,6 +658,65 @@ class GitHubClient: sanitized_reason = redact_sensitive(str(e.reason), self.token) raise RuntimeError(f"GitHub network error: {sanitized_reason}") from e + def create_repo( + self, + name: str, + private: bool = False, + description: str = "", + auto_init: bool = False, + license_template: str = "", + org: str | None = None, + ) -> dict[str, Any]: + """Create a repository on GitHub (personal or organization).""" + payload: dict[str, Any] = { + "name": name, + "private": private, + "description": description, + "auto_init": auto_init, + } + normalized_license = normalize_license(license_template) + if auto_init and normalized_license: + payload["license_template"] = normalized_license + endpoint = f"/orgs/{org}/repos" if org else "/user/repos" + return self._request("POST", endpoint, payload) + + def create_empty_repo( + self, + name: str, + private: bool = False, + description: str = "", + org: str | None = None, + ) -> dict[str, Any]: + """Create an empty target repository on GitHub with auto_init=False.""" + return self.create_repo( + name=name, + private=private, + description=description, + auto_init=False, + license_template="", + org=org, + ) + + def generate_from_template( + self, + template_owner: str, + template_name: str, + name: str, + private: bool = False, + description: str = "", + owner: str | None = None, + ) -> dict[str, Any]: + """Generate a new GitHub repository from a GitHub template repository.""" + payload = { + "owner": owner or self.user, + "name": name, + "private": private, + "description": description, + "include_all_branches": False, + } + path = f"/repos/{template_owner}/{template_name}/generate" + return self._request("POST", path, payload) + # ============================================================================== # Local Git Orchestration @@ -777,7 +808,7 @@ def link_and_push_existing( check=True, env=env, ) - print(f"✅ Successfully pushed '{current_branch}' to Gitea!") + print(f"✅ Successfully pushed '{current_branch}' to origin!") except subprocess.CalledProcessError as e: print(f"⚠️ Failed to link/push repository: {e}", file=sys.stderr) @@ -992,7 +1023,7 @@ def parse_args() -> argparse.Namespace: """Parse command line arguments.""" parser = argparse.ArgumentParser( prog="new-repo", - description="Provision repositories across self-hosted Gitea and GitHub push mirror.", + description="Provision repositories on GitHub with an automated Gitea pull mirror.", ) parser.add_argument( "name", @@ -1006,13 +1037,13 @@ def parse_args() -> argparse.Namespace: "--org", type=str, default=None, - help="Target Gitea organization to own the repository (auto-created if missing)", + help="Target GitHub organization to own the repository (defaults to personal GITHUB_USER)", ) parser.add_argument( - "--github-org", + "--gitea-org", type=str, default=None, - help="Optional GitHub organization for the offsite backup mirror (defaults to personal GITHUB_USER)", + help="Optional Gitea organization for the homelab pull mirror (auto-created if missing; defaults to GITEA_USER)", ) parser.add_argument( "-p", @@ -1032,22 +1063,22 @@ def parse_args() -> argparse.Namespace: "-l", "--license", type=str, - default="Unlicense", - help="License identifier template (default: Unlicense, pass empty string to disable)", + default="unlicense", + help="GitHub license template identifier (default: unlicense, pass empty string to disable)", ) parser.add_argument( "-t", "--template", type=str, default=None, - help="Optional Gitea template repository ('[owner/]template-name')", + help="Optional GitHub template repository ('[owner/]template-name')", ) parser.add_argument( "-M", "--no-mirror", action="store_true", default=False, - help="Disable automatic offsite push mirroring to GitHub", + help="Disable automatic homelab pull mirroring to Gitea", ) parser.add_argument( "--no-clone", @@ -1063,12 +1094,12 @@ def parse_args() -> argparse.Namespace: help="Persona / login identity to provision as (e.g. anneux)", ) parser.add_argument( - "--migrate", + "--gitea-mirror", nargs="?", const="", default=None, metavar="GITHUB_URL", - help="Migrate an existing GitHub repository to Gitea with automated push mirroring (URL or auto-detect from local origin)", + help="Attach a Gitea pull mirror to an existing GitHub repository (URL or auto-detect from local origin)", ) return parser.parse_args() @@ -1092,60 +1123,60 @@ def main() -> None: gitea_host = creds.gitea_url.split("://", 1)[-1].split("/", 1)[0].split(":", 1)[0] # -------------------------------------------------------------------------- - # Migration Workflow (--migrate) + # Attach Gitea Pull Mirror Workflow (--gitea-mirror) # -------------------------------------------------------------------------- - if args.migrate is not None: + if args.gitea_mirror is not None: try: - migrated_name, gh_owner, gh_clone_url = parse_github_target( - args.migrate, Path.cwd() + mirrored_name, gh_owner, gh_clone_url = parse_github_target( + args.gitea_mirror, Path.cwd() ) - override_name, target_org = resolve_name_and_org(args.name, args.org) + override_name, _ = resolve_name_and_org(args.name, None) except (ValueError, RuntimeError) as e: print(f"❌ Error: {e}", file=sys.stderr) sys.exit(1) - dest_name = override_name or migrated_name - gitea_owner = target_org or creds.gitea_user + dest_name = override_name or mirrored_name + gitea_org = ( + args.gitea_org.strip() + if args.gitea_org and args.gitea_org.strip() + else None + ) + gitea_owner = gitea_org or creds.gitea_user - # Align with token authenticated user if targeting user namespace - if not target_org: + if not gitea_org: auth_user = gitea_client.get_authenticated_user() if auth_user and auth_user.lower() != gitea_owner.lower(): print( f"⚠️ Identity Warning: Gitea token belongs to '{auth_user}', but session persona is '{gitea_owner}'.\n" - f" Aligning primary owner to token owner '{auth_user}'.", + f" Aligning mirror owner to token owner '{auth_user}'.", file=sys.stderr, ) gitea_owner = auth_user print( - f"🚀 Initiating repository migration: '{gh_owner}/{migrated_name}' -> Gitea '{gitea_owner}/{dest_name}'" + f"🚀 Attaching Gitea pull mirror: '{gh_owner}/{mirrored_name}' -> Gitea '{gitea_owner}/{dest_name}'" ) print(f" Visibility: {'Private' if is_private else 'Public'}") - if target_org: + if gitea_org: try: - created_org = gitea_client.ensure_org(target_org, private=is_private) + created_org = gitea_client.ensure_org(gitea_org, private=is_private) if created_org: - print(f"🏢 Created new Gitea organization '{target_org}'") + print(f"🏢 Created new Gitea organization '{gitea_org}'") except RuntimeError as e: print(f"❌ Error: {e}", file=sys.stderr) sys.exit(1) - # Fail-safe conflict check if gitea_client.repo_exists(gitea_owner, dest_name): print( f"❌ Error: Repository '{dest_name}' already exists on Gitea under '{gitea_owner}'.\n" f" Inspect at: {creds.gitea_url}/{gitea_owner}/{dest_name}\n" - " Aborting migration to prevent overwriting existing repositories.", + " Aborting to prevent overwriting existing repositories.", file=sys.stderr, ) sys.exit(1) - # Step 1: Server-side import via Gitea Migration API - print( - "🏗️ Importing full repository history from GitHub via Gitea Migration API..." - ) + print("🔗 Creating Gitea pull mirror from GitHub...") try: res = gitea_client.migrate_repo( clone_addr=gh_clone_url, @@ -1154,54 +1185,24 @@ def main() -> None: private=is_private, description=args.description, repo_owner=gitea_owner, + mirror=True, ) actual_owner = res.get("owner", {}).get("username") or gitea_owner gitea_html_url = res.get( "html_url", f"{creds.gitea_url}/{actual_owner}/{dest_name}" ) - print(f"✅ Gitea repository created from GitHub: {gitea_html_url}") + print(f"✅ Gitea pull mirror created: {gitea_html_url}") except RuntimeError as e: - print(f"❌ Migration failed: {e}", file=sys.stderr) + print(f"❌ Pull mirror creation failed: {e}", file=sys.stderr) sys.exit(1) - # Step 2: Register automated push mirror to GitHub - if not args.no_mirror: - print("🔗 Registering automated push mirror to GitHub...") - try: - gitea_client.create_push_mirror( - repo_name=dest_name, - remote_address=gh_clone_url, - remote_username=creds.github_user, - remote_password=creds.github_token, - sync_on_commit=True, - interval="8h", - owner=actual_owner, - ) - print("✅ Gitea push mirror registered (sync on commit enabled)") - except RuntimeError as e: - print(f"⚠️ Push mirror registration failed: {e}", file=sys.stderr) - - # Step 3: Reconfigure local working tree if inside a Git repository - gitea_clone_target = res.get("ssh_url") or f"git@{gitea_host}:{actual_owner}/{dest_name}.git" - if (Path.cwd() / ".git").is_dir(): - reconfigure_local_remotes(Path.cwd(), gitea_clone_target) - elif not args.no_clone: - clone_locally( - gitea_host=gitea_host, - user=actual_owner, - repo_name=dest_name, - target_dir=Path.cwd() / dest_name, - clone_url=gitea_clone_target, - ssh_key=creds.ssh_key, - ) - - print("\n🎉 Migration complete!") - print(f" Primary Forge (Gitea): {gitea_html_url}") - print(f" Backup Mirror (GitHub): {gh_clone_url}") + print("\n🎉 Mirror setup complete!") + print(f" Primary Forge (GitHub): {gh_clone_url}") + print(f" Pull Mirror (Gitea): {gitea_html_url}") return # -------------------------------------------------------------------------- - # Standard Provisioning Workflow + # Standard Provisioning Workflow (GitHub Primary + Gitea Pull Mirror) # -------------------------------------------------------------------------- try: repo_name, target_dir, is_existing_git, target_org = determine_target( @@ -1215,48 +1216,43 @@ def main() -> None: print("Error: Repository name cannot be determined.", file=sys.stderr) sys.exit(1) - gitea_owner = target_org or creds.gitea_user - github_org = ( - args.github_org.strip() if args.github_org and args.github_org.strip() else None + github_owner = target_org or creds.github_user + gitea_org = ( + args.gitea_org.strip() if args.gitea_org and args.gitea_org.strip() else None ) - github_owner = github_org or creds.github_user + gitea_owner = gitea_org or creds.gitea_user - # Align with token authenticated user if targeting user namespace - if not target_org: + if not gitea_org: auth_user = gitea_client.get_authenticated_user() if auth_user and auth_user.lower() != gitea_owner.lower(): print( f"⚠️ Identity Warning: Gitea token belongs to '{auth_user}', but session persona is '{gitea_owner}'.\n" - f" Aligning primary owner to token owner '{auth_user}'.", + f" Aligning mirror owner to token owner '{auth_user}'.", file=sys.stderr, ) gitea_owner = auth_user - print(f"🚀 Initializing repository provisioning: '{gitea_owner}/{repo_name}'") + print(f"🚀 Initializing repository provisioning: '{github_owner}/{repo_name}'") print(f" Visibility: {'Private' if is_private else 'Public'}") if is_existing_git: print(f" Mode: Existing local repository at '{target_dir}'") else: print(f" Mode: Greenfield creation at '{target_dir}'") - # 2. Provision Gitea Primary Repository - gitea_html_url: str | None = None + # 2. Provision GitHub Primary Repository + github_html_url: str + github_ssh_url: str try: - if target_org: - created_org = gitea_client.ensure_org(target_org, private=is_private) - if created_org: - print(f"🏢 Created new Gitea organization '{target_org}'") - if is_existing_git: print( - "🏗️ Creating empty primary repository on Gitea (preserving local history)..." + "🏗️ Creating empty primary repository on GitHub (preserving local history)..." ) - res = gitea_client.create_repo( + res = github_client.create_repo( name=repo_name, private=is_private, description=args.description, - auto_init=False, # CRUCIAL: Do not create remote README/license to prevent divergent commit histories - license_name="", + auto_init=False, + license_template="", org=target_org, ) elif args.template: @@ -1264,103 +1260,100 @@ def main() -> None: if len(template_parts) == 2: tmpl_owner, tmpl_name = template_parts[0], template_parts[1] else: - tmpl_owner, tmpl_name = gitea_owner, template_parts[0] + tmpl_owner, tmpl_name = github_owner, template_parts[0] print( - f"🏗️ Generating Gitea repository from template '{tmpl_owner}/{tmpl_name}'..." + f"🏗️ Generating GitHub repository from template '{tmpl_owner}/{tmpl_name}'..." ) - res = gitea_client.generate_from_template( + res = github_client.generate_from_template( template_owner=tmpl_owner, template_name=tmpl_name, name=repo_name, private=is_private, description=args.description, - owner=gitea_owner, + owner=github_owner, ) else: - print("🏗️ Creating primary repository on Gitea...") - res = gitea_client.create_repo( + print("🏗️ Creating primary repository on GitHub...") + res = github_client.create_repo( name=repo_name, private=is_private, description=args.description, auto_init=True, - license_name=args.license, + license_template=args.license, org=target_org, ) - actual_owner = res.get("owner", {}).get("username") or gitea_owner - actual_clone_url = res.get("ssh_url") or f"git@{gitea_host}:{actual_owner}/{repo_name}.git" - gitea_html_url = res.get( - "html_url", f"{creds.gitea_url}/{actual_owner}/{repo_name}" + actual_gh_owner = res.get("owner", {}).get("login") or github_owner + github_ssh_url = res.get("ssh_url") or f"git@github.com:{actual_gh_owner}/{repo_name}.git" + github_html_url = res.get( + "html_url", f"https://github.com/{actual_gh_owner}/{repo_name}" ) - print(f"✅ Gitea repository created: {gitea_html_url}") + print(f"✅ GitHub repository created: {github_html_url}") except RuntimeError as e: - print(f"❌ Failed to create Gitea repository: {e}", file=sys.stderr) + print(f"❌ Failed to create GitHub repository: {e}", file=sys.stderr) sys.exit(1) - # 3. Provision GitHub Backup Mirror & Push Mirror Registration - github_html_url: str | None = None - if not args.no_mirror: - print("☁️ Provisioning offsite mirror target on GitHub...") - try: - gh_res = github_client.create_empty_repo( - name=repo_name, - private=is_private, - description=args.description, - org=github_org, - ) - github_html_url = gh_res.get( - "html_url", f"https://github.com/{github_owner}/{repo_name}" - ) - print(f"✅ GitHub mirror target created: {github_html_url}") - - print("🔗 Registering automated push mirror on Gitea...") - github_clone_target = f"https://github.com/{github_owner}/{repo_name}.git" - gitea_client.create_push_mirror( - repo_name=repo_name, - remote_address=github_clone_target, - remote_username=creds.github_user, - remote_password=creds.github_token, - sync_on_commit=True, - interval="8h", - owner=actual_owner, - ) - print("✅ Gitea push mirror registered (sync on commit enabled)") - except RuntimeError as e: - # Retain & Report policy: Gitea repo exists, so inform the user rather than deleting it - print(f"⚠️ Push mirror provisioning failed: {e}", file=sys.stderr) - print( - f" Your primary Gitea repository remains intact at: {gitea_html_url}\n" - " You can inspect or configure mirroring manually if needed.", - file=sys.stderr, - ) - - # 4. Local Git Workflow + # 3. Local Git Workflow (push existing commits before Gitea pull-mirroring) if is_existing_git: link_and_push_existing( - gitea_host=gitea_host, - user=actual_owner, + gitea_host="github.com", + user=actual_gh_owner, repo_name=repo_name, target_dir=target_dir, - clone_url=actual_clone_url, + clone_url=github_ssh_url, ssh_key=creds.ssh_key, ) elif not args.no_clone: clone_locally( - gitea_host=gitea_host, - user=actual_owner, + gitea_host="github.com", + user=actual_gh_owner, repo_name=repo_name, target_dir=target_dir, - clone_url=actual_clone_url, + clone_url=github_ssh_url, ssh_key=creds.ssh_key, ) + # 4. Provision Gitea Pull Mirror + gitea_html_url: str | None = None + if not args.no_mirror: + print("🪞 Provisioning homelab pull mirror on Gitea...") + try: + if gitea_org: + created_org = gitea_client.ensure_org(gitea_org, private=is_private) + if created_org: + print(f"🏢 Created new Gitea organization '{gitea_org}'") + + github_clone_target = f"https://github.com/{actual_gh_owner}/{repo_name}.git" + gitea_res = gitea_client.migrate_repo( + clone_addr=github_clone_target, + repo_name=repo_name, + github_token=creds.github_token, + private=is_private, + description=args.description, + repo_owner=gitea_owner, + mirror=True, + ) + actual_gitea_owner = gitea_res.get("owner", {}).get("username") or gitea_owner + gitea_html_url = gitea_res.get( + "html_url", f"{creds.gitea_url}/{actual_gitea_owner}/{repo_name}" + ) + print(f"✅ Gitea pull mirror created: {gitea_html_url}") + except RuntimeError as e: + # Retain & Report policy: GitHub repo exists, so inform the user rather than deleting it + print(f"⚠️ Gitea pull mirror provisioning failed: {e}", file=sys.stderr) + print( + f" Your primary GitHub repository remains intact at: {github_html_url}\n" + " You can attach a pull mirror later via: new-repo --gitea-mirror", + file=sys.stderr, + ) + # 5. Final Summary print("\n🎉 Provisioning complete!") - print(f" Primary Forge: {gitea_html_url}") - if github_html_url: - print(f" Backup Mirror: {github_html_url}") - print(f" Working Tree: {target_dir}") + 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__": diff --git a/test_new_repo.py b/test_new_repo.py index 07783ca..aa301eb 100755 --- a/test_new_repo.py +++ b/test_new_repo.py @@ -37,14 +37,14 @@ class TestArgParsing(unittest.TestCase): args = parse_args() self.assertEqual(args.name, "sample-project") self.assertIsNone(args.org) - self.assertIsNone(args.github_org) + self.assertIsNone(args.gitea_org) self.assertFalse(args.private) - self.assertEqual(args.license, "Unlicense") + self.assertEqual(args.license, "unlicense") self.assertIsNone(args.template) self.assertFalse(args.no_mirror) self.assertFalse(args.no_clone) self.assertIsNone(args.as_persona) - self.assertIsNone(args.migrate) + self.assertIsNone(args.gitea_mirror) def test_as_persona_argument(self) -> None: import sys @@ -53,16 +53,16 @@ class TestArgParsing(unittest.TestCase): args = parse_args() self.assertEqual(args.as_persona, "anneux") - def test_migrate_arguments(self) -> None: + def test_gitea_mirror_arguments(self) -> None: import sys - sys.argv = ["new-repo", "--migrate"] + sys.argv = ["new-repo", "--gitea-mirror"] args = parse_args() - self.assertEqual(args.migrate, "") + self.assertEqual(args.gitea_mirror, "") - sys.argv = ["new-repo", "--migrate", "https://github.com/octocat/Hello-World"] + sys.argv = ["new-repo", "--gitea-mirror", "https://github.com/octocat/Hello-World"] args = parse_args() - self.assertEqual(args.migrate, "https://github.com/octocat/Hello-World") + self.assertEqual(args.gitea_mirror, "https://github.com/octocat/Hello-World") def test_omitted_name_defaults_to_none(self) -> None: import sys @@ -78,9 +78,9 @@ class TestArgParsing(unittest.TestCase): "new-repo", "open-api", "-o", + "my-gh-org", + "--gitea-org", "homelab", - "--github-org", - "homelab-gh", "--private", "-d", "My public API", @@ -93,54 +93,74 @@ class TestArgParsing(unittest.TestCase): ] args = parse_args() self.assertEqual(args.name, "open-api") - self.assertEqual(args.org, "homelab") - self.assertEqual(args.github_org, "homelab-gh") + self.assertEqual(args.org, "my-gh-org") + self.assertEqual(args.gitea_org, "homelab") self.assertTrue(args.private) self.assertEqual(args.description, "My public API") self.assertEqual(args.license, "MIT") self.assertEqual(args.template, "template-fastapi") self.assertTrue(args.no_mirror) self.assertTrue(args.no_clone) - self.assertIsNone(args.migrate) + self.assertIsNone(args.gitea_mirror) class TestLicenseNormalization(unittest.TestCase): - """Test license identifier normalization against Gitea's registry.""" + """Test license identifier normalization against GitHub's lowercase registry.""" def test_unlicense_casing_variants(self) -> None: - self.assertEqual(normalize_license("UNLICENSE"), "Unlicense") - self.assertEqual(normalize_license("unlicense"), "Unlicense") - self.assertEqual(normalize_license("Unlicense"), "Unlicense") + self.assertEqual(normalize_license("UNLICENSE"), "unlicense") + self.assertEqual(normalize_license("unlicense"), "unlicense") + self.assertEqual(normalize_license("Unlicense"), "unlicense") def test_common_licenses_case_insensitivity(self) -> None: - self.assertEqual(normalize_license("mit"), "MIT") - self.assertEqual(normalize_license("MIT"), "MIT") - self.assertEqual(normalize_license("apache-2.0"), "Apache-2.0") - self.assertEqual(normalize_license("APACHE-2.0"), "Apache-2.0") - self.assertEqual(normalize_license("gpl-3.0"), "GPL-3.0") - self.assertEqual(normalize_license("bsd-3-clause"), "BSD-3-Clause") + self.assertEqual(normalize_license("mit"), "mit") + self.assertEqual(normalize_license("MIT"), "mit") + self.assertEqual(normalize_license("apache-2.0"), "apache-2.0") + self.assertEqual(normalize_license("APACHE-2.0"), "apache-2.0") + self.assertEqual(normalize_license("gpl-3.0"), "gpl-3.0") + self.assertEqual(normalize_license("bsd-3-clause"), "bsd-3-clause") def test_empty_and_whitespace_licenses(self) -> None: self.assertEqual(normalize_license(""), "") self.assertEqual(normalize_license(" "), "") self.assertEqual(normalize_license(None), "") - def test_unrecognized_license_passthrough(self) -> None: - self.assertEqual(normalize_license("Custom-Proprietary"), "Custom-Proprietary") + def test_unrecognized_license_lowercase(self) -> None: + self.assertEqual(normalize_license("Custom-Proprietary"), "custom-proprietary") - def test_gitea_client_create_repo_normalizes_license(self) -> None: + def test_github_client_create_repo_normalizes_license(self) -> None: + client = GitHubClient("kiskaadee", "secret-token") + with patch.object(client, "_request", return_value={}) as mock_req: + client.create_repo( + "my-repo", auto_init=True, license_template="UNLICENSE" + ) + mock_req.assert_called_once() + payload = mock_req.call_args[0][2] + self.assertEqual(payload["license_template"], "unlicense") + self.assertTrue(payload["auto_init"]) + + with patch.object(client, "_request", return_value={}) as mock_req: + client.create_repo("my-repo-no-license", auto_init=True, license_template="") + mock_req.assert_called_once() + payload = mock_req.call_args[0][2] + self.assertNotIn("license_template", payload) + + def test_gitea_migrate_repo_supports_pull_mirror(self) -> None: client = GiteaClient("https://gitea.local", "kiskaadee", "secret-token") with patch.object(client, "_request", return_value={}) as mock_req: - client.create_repo("my-repo", license_name="UNLICENSE") + client.migrate_repo( + clone_addr="https://github.com/kiskaadee/my-repo.git", + repo_name="my-repo", + github_token="gh-secret", + private=True, + repo_owner="kiskaadee", + mirror=True, + ) mock_req.assert_called_once() payload = mock_req.call_args[0][2] - self.assertEqual(payload["license"], "Unlicense") - - with patch.object(client, "_request", return_value={}) as mock_req: - client.create_repo("my-repo-no-license", license_name="") - mock_req.assert_called_once() - payload = mock_req.call_args[0][2] - self.assertNotIn("license", payload) + self.assertTrue(payload["mirror"]) + self.assertTrue(payload["private"]) + self.assertEqual(payload["service"], "github") class TestOrganizationAndTargetResolution(unittest.TestCase):