diff --git a/glon/cli.py b/glon/cli.py index 42af13b..f1a10e2 100644 --- a/glon/cli.py +++ b/glon/cli.py @@ -37,6 +37,7 @@ DAYS_PER_QUARTER = 90 DAYS_PER_HALF_YEAR = 180 DAYS_PER_YEAR = 365 +PUBLISH_VISIBILITIES = ("private", "public") SSH_URL_RE = re.compile(r"git@[^:]+:([^/]+)/([^/]+)\.git$") HTTPS_URL_RE = re.compile(r"https://[^/]+/([^/]+)/([^/]+)\.git$") @@ -138,9 +139,9 @@ def _read_clipboard_text() -> Optional[str]: ["xclip", "-o", "-selection", "clipboard"], ["xsel", "--clipboard", "--output"], ): - text = _run_clipboard_command(command) - if text: - return text + clipboard_text = _run_clipboard_command(command) + if clipboard_text: + return clipboard_text return None @@ -780,6 +781,365 @@ def _handle_grab(arguments: Sequence[str]) -> None: ) +def detect_github_repo_from_cwd( + cwd: Optional[Path] = None, base_path: Optional[str] = None +) -> Optional[Tuple[str, str, Path]]: + """Detect ``(owner, repo, repo_root)`` when cwd is inside ``github/*/*``.""" + current_dir = (cwd or Path.cwd()).resolve() + base_dir = _expand_base_path(base_path).resolve() + + try: + relative = current_dir.relative_to(base_dir) + except ValueError: + relative = None + + if relative is not None and len(relative.parts) >= 2: + owner, repo = relative.parts[0], relative.parts[1] + return owner, repo, base_dir / owner / repo + + if base_path is None: + parts = current_dir.parts + for index in range(len(parts) - 1, -1, -1): + if parts[index].lower() == "github" and len(parts) >= index + 3: + owner, repo = parts[index + 1], parts[index + 2] + return owner, repo, Path(*parts[: index + 3]) + + return None + + +def _ensure_git_repo_and_commit( + repo_dir: Path, dry_run: bool = False, verbose: bool = False +) -> bool: + """Ensure ``repo_dir`` is an initialized Git repository with at least one commit.""" + git_dir = repo_dir / ".git" + if not git_dir.exists(): + if dry_run: + print(f"Would run: git init (cwd={repo_dir})") + print(f"Would stage files and create initial commit in {repo_dir}") + return True + try: + subprocess.run( + ["git", "init"], + cwd=repo_dir, + capture_output=True, + text=True, + check=True, + ) + if verbose: + print(f"Initialized git repository in {repo_dir}") + except subprocess.CalledProcessError as error: + print(f"Failed to initialize git repository: {error.stderr or error}") + return False + except FileNotFoundError: + print("Git is not installed or not in PATH") + return False + + try: + head_check = subprocess.run( + ["git", "rev-parse", "--verify", "HEAD"], + cwd=repo_dir, + capture_output=True, + text=True, + check=False, + ) + except FileNotFoundError: + print("Git is not installed or not in PATH") + return False + + if head_check.returncode == 0: + return True + + if dry_run: + print(f"Would stage files and create initial commit in {repo_dir}") + return True + + try: + subprocess.run( + ["git", "add", "-A"], + cwd=repo_dir, + capture_output=True, + text=True, + check=True, + ) + subprocess.run( + ["git", "commit", "--allow-empty", "-m", "Initial commit"], + cwd=repo_dir, + capture_output=True, + text=True, + check=True, + ) + if verbose: + print(f"Created initial commit in {repo_dir}") + return True + except subprocess.CalledProcessError as error: + print(f"Failed to create initial commit: {error.stderr or error}") + return False + + +def _has_origin_remote(repo_dir: Path) -> bool: + """Return True when ``origin`` remote is configured in ``repo_dir``.""" + if not (repo_dir / ".git").exists(): + return False + try: + result = subprocess.run( + ["git", "remote", "get-url", "origin"], + cwd=repo_dir, + capture_output=True, + text=True, + check=False, + ) + except FileNotFoundError: + return False + return result.returncode == 0 and bool((result.stdout or "").strip()) + + +def _set_github_visibility( + repo_dir: Path, + full_name: str, + visibility: str, + dry_run: bool = False, + verbose: bool = False, +) -> bool: + """Ensure GitHub repository visibility matches ``visibility`` via ``gh``.""" + command = ["gh", "repo", "edit", full_name, "--visibility", visibility] + if dry_run: + print(f"Would run: {' '.join(command)}") + return True + + try: + subprocess.run( + command, + cwd=repo_dir, + capture_output=True, + text=True, + check=True, + ) + if verbose: + print(f"Set GitHub visibility for {full_name} to {visibility}") + return True + except subprocess.CalledProcessError as error: + stderr = error.stderr or "" + if "--accept-visibility-change-consequences" in stderr: + try: + subprocess.run( + [*command, "--accept-visibility-change-consequences"], + cwd=repo_dir, + capture_output=True, + text=True, + check=True, + ) + return True + except subprocess.CalledProcessError as retry_error: + print( + "Failed to update repository visibility: " + f"{retry_error.stderr or retry_error}" + ) + return False + print(f"Failed to update repository visibility: {stderr or error}") + return False + except FileNotFoundError: + print("GitHub CLI (gh) is not installed or not in PATH") + return False + + +def _attach_origin_and_push( + repo_dir: Path, + full_name: str, + visibility: str, + dry_run: bool = False, + verbose: bool = False, +) -> bool: + """Attach ``origin`` for an existing GitHub repo, update visibility, and push.""" + remote_url = f"https://github.com/{full_name}.git" + if not _has_origin_remote(repo_dir): + if dry_run: + print(f"Would run: git remote add origin {remote_url}") + else: + try: + subprocess.run( + ["git", "remote", "add", "origin", remote_url], + cwd=repo_dir, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as error: + print(f"Failed to add origin remote: {error.stderr or error}") + return False + + if not _set_github_visibility( + repo_dir, full_name, visibility, dry_run=dry_run, verbose=verbose + ): + return False + + push_command = ["git", "push", "-u", "origin", "HEAD"] + if dry_run: + print(f"Would run: {' '.join(push_command)}") + return True + + try: + subprocess.run( + push_command, + cwd=repo_dir, + capture_output=True, + text=True, + check=True, + ) + return True + except subprocess.CalledProcessError as error: + print(f"Failed to push repository to origin: {error.stderr or error}") + return False + + +def _publish_to_github( + repo_dir: Path, + owner: str, + repo: str, + visibility: str = "private", + dry_run: bool = False, + verbose: bool = False, +) -> bool: + """Create or update the GitHub repository via ``gh`` and push.""" + full_name = f"{owner}/{repo}" + if _has_origin_remote(repo_dir): + return _attach_origin_and_push( + repo_dir, full_name, visibility, dry_run=dry_run, verbose=verbose + ) + + command = [ + "gh", + "repo", + "create", + full_name, + f"--{visibility}", + "--source=.", + "--remote=origin", + "--push", + ] + if dry_run: + print(f"Would run: {' '.join(command)} (cwd={repo_dir})") + return True + + try: + subprocess.run( + command, + cwd=repo_dir, + capture_output=True, + text=True, + check=True, + ) + print(f"Published {full_name} ({visibility}) to GitHub") + return True + except subprocess.CalledProcessError as error: + stderr = error.stderr or "" + if "already exists" in stderr.lower(): + return _attach_origin_and_push( + repo_dir, full_name, visibility, dry_run=dry_run, verbose=verbose + ) + print(f"Failed to publish {full_name} via gh: {stderr or error}") + return False + except FileNotFoundError: + print("GitHub CLI (gh) is not installed or not in PATH") + return False + + +def _run_goal_publish( + repo_dir: Path, dry_run: bool = False, verbose: bool = False +) -> bool: + """Run ``goal -a`` to publish the repository to PyPI and other registries.""" + command = ["goal", "-a"] + if dry_run: + print(f"Would run: {' '.join(command)} (cwd={repo_dir})") + return True + + try: + subprocess.run(command, cwd=repo_dir, check=True) + if verbose: + print(f"Completed goal -a in {repo_dir}") + return True + except subprocess.CalledProcessError as error: + print(f"Failed to run goal -a: {error}") + return False + except FileNotFoundError: + print("Goal CLI (goal) is not installed or not in PATH") + return False + + +def publish_repository( + repo_dir: Path, + owner: str, + repo: str, + visibility: str = "private", + dry_run: bool = False, + verbose: bool = False, +) -> bool: + """Publish a local ``github//`` directory via ``gh`` and ``goal -a``.""" + if visibility not in PUBLISH_VISIBILITIES: + print(f"Error: Unsupported visibility '{visibility}'. Use private or public.") + return False + + if verbose: + print(f"Publishing {owner}/{repo} from {repo_dir} as {visibility}") + + if not _ensure_git_repo_and_commit(repo_dir, dry_run=dry_run, verbose=verbose): + return False + if not _publish_to_github( + repo_dir, owner, repo, visibility=visibility, dry_run=dry_run, verbose=verbose + ): + return False + return _run_goal_publish(repo_dir, dry_run=dry_run, verbose=verbose) + + +def _build_publish_parser(default_visibility: str = "private") -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description=( + "Publish current github// directory via gh and goal -a" + ), + prog="glon publish", + ) + parser.add_argument( + "visibility", + nargs="?", + choices=list(PUBLISH_VISIBILITIES), + default=default_visibility, + help="GitHub repository visibility (default: private)", + ) + parser.add_argument("--base-path", help="Base path for github repos (default: ~/github)") + parser.add_argument( + "--dry-run", + action="store_true", + help="Show what would be done without actually publishing", + ) + parser.add_argument("--verbose", action="store_true", help="Verbose output") + return parser + + +def _handle_publish( + arguments: Sequence[str], + default_visibility: str = "private", + cwd: Optional[Path] = None, +) -> bool: + options = _build_publish_parser(default_visibility=default_visibility).parse_args( + arguments + ) + detected = detect_github_repo_from_cwd(cwd=cwd, base_path=options.base_path) + if detected is None: + print( + "Error: Current directory is not inside a github// folder." + ) + return False + + owner, repo, repo_root = detected + return publish_repository( + repo_root, + owner, + repo, + visibility=options.visibility, + dry_run=options.dry_run, + verbose=options.verbose, + ) + + def _build_clone_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description=( @@ -804,6 +1164,20 @@ def _build_clone_parser() -> argparse.ArgumentParser: def _handle_clone(arguments: Sequence[str]) -> None: options = _build_clone_parser().parse_args(arguments) + if options.url is None: + detected = detect_github_repo_from_cwd(base_path=options.base_path) + if detected is not None: + owner, repo, repo_root = detected + publish_repository( + repo_root, + owner, + repo, + visibility="private", + dry_run=options.dry_run, + verbose=options.verbose, + ) + return + url = options.url or _clipboard_url_candidate(max_len=MAX_CLIPBOARD_URL_LENGTH) if url is None: print( @@ -860,6 +1234,15 @@ def main(argv: Optional[Sequence[str]] = None) -> None: if "grab" in arguments: _handle_grab([argument for argument in arguments if argument != "grab"]) return + if arguments[:1] == ["private"]: + _handle_publish(arguments[1:], default_visibility="private") + return + if arguments[:1] == ["public"]: + _handle_publish(arguments[1:], default_visibility="public") + return + if arguments[:1] == ["publish"]: + _handle_publish(arguments[1:], default_visibility="private") + return if arguments[:1] == ["clone"]: arguments = arguments[1:] diff --git a/project/TICKETS.md b/project/TICKETS.md index 9123ac9..5235bb3 100644 --- a/project/TICKETS.md +++ b/project/TICKETS.md @@ -10,4 +10,6 @@ This file indexes governance tickets without taking ownership of | **ticket-005** | [`README.md`](./ticket-005/README.md) | [`preprompt.md`](./ticket-005/preprompt.md) | - | [`ai-claude.md`](./ticket-005/ai-claude.md) | [`ai-claude-logs.txt`](./ticket-005/ai-claude-logs.txt) | [`changelog.md`](./ticket-005/changelog.md) | | **ticket-006** | [`README.md`](./ticket-006/README.md) | [`preprompt.md`](./ticket-006/preprompt.md) | - | [`ai-gemini.md`](./ticket-006/ai-gemini.md) | [`ai-gemini-logs.txt`](./ticket-006/ai-gemini-logs.txt) | [`changelog.md`](./ticket-006/changelog.md) | | **ticket-007** | [`README.md`](./ticket-007/README.md) | [`preprompt.md`](./ticket-007/preprompt.md) | - | [`ai-antigravity.md`](./ticket-007/ai-antigravity.md) | [`ai-antigravity-logs.txt`](./ticket-007/ai-antigravity-logs.txt) | [`changelog.md`](./ticket-007/changelog.md) | +| **ticket-008** | [`README.md`](./ticket-008/README.md) | [`preprompt.md`](./ticket-008/preprompt.md) | - | [`ai-antigravity.md`](./ticket-008/ai-antigravity.md) | [`ai-antigravity-logs.txt`](./ticket-008/ai-antigravity-logs.txt) | [`changelog.md`](./ticket-008/changelog.md) | +| **ticket-010** | [`README.md`](./ticket-010/README.md) | [`preprompt.md`](./ticket-010/preprompt.md) | - | [`ai-antigravity.md`](./ticket-010/ai-antigravity.md) | [`ai-antigravity-logs.txt`](./ticket-010/ai-antigravity-logs.txt) | [`changelog.md`](./ticket-010/changelog.md) | diff --git a/project/ticket-007/README.md b/project/ticket-007/README.md index ffd4fb1..e33800c 100644 --- a/project/ticket-007/README.md +++ b/project/ticket-007/README.md @@ -2,8 +2,8 @@ - **ID**: ticket-007 - **Owner**: agent:antigravity -- **Status**: IN_PROGRESS -- **Workflow state**: EDIT +- **Status**: DONE +- **Workflow state**: DONE - **Created**: 2026-10-17 ## Goal and scope diff --git a/project/ticket-008/README.md b/project/ticket-008/README.md index afda53b..0a1e4c4 100644 --- a/project/ticket-008/README.md +++ b/project/ticket-008/README.md @@ -2,8 +2,8 @@ - **ID**: ticket-008 - **Owner**: agent:antigravity -- **Status**: IN_PROGRESS -- **Workflow state**: EDIT +- **Status**: DONE +- **Workflow state**: DONE - **Created**: 2026-10-18 ## Goal and scope diff --git a/project/ticket-010/README.md b/project/ticket-010/README.md new file mode 100644 index 0000000..eb7588a --- /dev/null +++ b/project/ticket-010/README.md @@ -0,0 +1,22 @@ +# Ticket 010: Publish current github/*/* repo via gh and goal -a + +- **ID**: ticket-010 +- **Owner**: agent:antigravity +- **Status**: IN_PROGRESS +- **Workflow state**: PUBLICATION +- **Created**: 2026-11-23 + +## Goal and scope + +SESSION_EXECUTION_AUTHORIZATION: Explicit user request in active session to update `semcod/glon` so that when invoked from inside a `github/*/*` directory (`glon`, `glon private`, `glon public`, `glon publish [private|public]`), it publishes the current repository to GitHub via `gh` (defaulting to `--private`) and runs `goal -a` to publish to PyPI and other configured registries. + +## Acceptance criteria + +- [x] AC-01: Detecting `github//` from `cwd` works for both default `~/github/*/*` and nested subdirectories. +- [x] AC-02: `glon` (no URL arg inside `github/*/*`), `glon private`, and `glon public` initialize Git if needed, publish/update visibility on GitHub via `gh` (default `private`), and run `goal -a`. +- [x] AC-03: `./project/governance-check.sh`, `pytest -q`, and `mypy glon` pass. + +## Participants + +- Human participant: unresolved; no user-* file was created by this script. +- Agent participant: [ai-antigravity.md](ai-antigravity.md) diff --git a/project/ticket-010/ai-antigravity-logs.txt b/project/ticket-010/ai-antigravity-logs.txt new file mode 100644 index 0000000..9e3638f --- /dev/null +++ b/project/ticket-010/ai-antigravity-logs.txt @@ -0,0 +1,5 @@ +2026-11-23T09:00:00+01:00 ticket-010 verification log +- pytest -q: 68 passed +- mypy --python-version 3.10 glon: pass +- ./project/governance-check.sh: GOV-PASS (0 errors, 0 warnings) +- wellman check --root .: pass diff --git a/project/ticket-010/ai-antigravity.md b/project/ticket-010/ai-antigravity.md new file mode 100644 index 0000000..7324b38 --- /dev/null +++ b/project/ticket-010/ai-antigravity.md @@ -0,0 +1,29 @@ +--- +participant-id: agent:antigravity +participant: antigravity +role: agent +ticket: ticket-010 +--- +# Participant: antigravity (AI agent) + +## Understanding + +User requested updating `semcod/glon` so that running `glon`, `glon private`, or `glon public` while inside a `github//` directory publishes the repository to GitHub using `gh` (defaulting to `--private`) and invokes `goal -a` to publish to PyPI and other configured registries. + +## Execution plan + +1. Close already-merged `ticket-007` and `ticket-008` in this worktree and allocate `ticket-010` via `./project/new-ticket.sh`. +2. Implement `detect_github_repo_from_cwd`, `publish_repository`, `_handle_publish`, and CLI dispatch for `glon`, `glon private`, `glon public`, and `glon publish` in `glon/cli.py`. +3. Add unit tests in `tests/test_cli.py`. +4. Run `pytest -q`, `mypy glon`, `flake8`/`black` (if available), `./project/governance-check.sh`, and `wellman check`. + +## Actual changes + +- Recorded `SESSION_EXECUTION_AUTHORIZATION` from the user's explicit request. +- Added `github/*/*` directory detection and `gh` + `goal -a` publication workflow in `glon/cli.py`. +- Added unit tests in `tests/test_cli.py`. + +## Blockers + +- None inside the recorded intent; proceed without a second confirmation. +- New authority remains required for destructive action, secret access, new external coordination, material objective expansion and trusted merge. diff --git a/project/ticket-010/changelog.md b/project/ticket-010/changelog.md new file mode 100644 index 0000000..11e4241 --- /dev/null +++ b/project/ticket-010/changelog.md @@ -0,0 +1,5 @@ +# Changelog for ticket-010 + +- Added `detect_github_repo_from_cwd` and `publish_repository` in `glon/cli.py` so `glon`, `glon private`, `glon public`, and `glon publish [private|public]` inside a `github//` folder initialize Git if needed, publish/update repository visibility on GitHub via `gh` (default `private`), and invoke `goal -a` for PyPI and other registries. +- Added unit tests in `tests/test_cli.py` covering `github/*/*` detection, `gh` + `goal -a` execution, dry-run mode, and CLI subcommands. +- Closed already-merged `ticket-007` and `ticket-008` in `project/ticket-007/README.md` and `project/ticket-008/README.md`. diff --git a/project/ticket-010/intent.json b/project/ticket-010/intent.json new file mode 100644 index 0000000..5779c99 --- /dev/null +++ b/project/ticket-010/intent.json @@ -0,0 +1,84 @@ +{ + "schema": "new-project.intent/v3", + "ticket": "ticket-010", + "summary": "Publish current github/*/* repo via gh and goal -a", + "workstream": "application", + "classification": { + "kind": "FEATURE", + "priority": "P2", + "origin": "requested" + }, + "allowedPaths": [ + "project/ticket-010/**", + "project/ticket-007/README.md", + "project/ticket-008/README.md", + "TODO.md", + "project/TICKETS.md", + "glon/cli.py", + "tests/test_cli.py" + ], + "forbiddenPaths": [ + "project/ticket-*/user-*.md" + ], + "stacks": [], + "dependsOn": [], + "conflictsWith": [], + "integrationTicket": null, + "delivery": { + "acceptedBaseSha": "b533de46fc88424faf87f2951fdea7cd354280d8", + "targetBranch": "main", + "outcome": "Allow glon, glon private, and glon public inside github/*/* directories to publish via gh (default private) and goal -a.", + "nonGoals": [ + "Add runtime dependencies", + "Modify existing clone/open/list/grab behavior outside github/*/*" + ], + "complexity": "S", + "estimatedMinutes": 15, + "budgets": { + "maxImplementationFiles": 2, + "maxAffectedComponents": 1, + "maxPublicInterfaceChanges": 0, + "maxRuntimeDependencies": 0 + }, + "architecture": { + "status": "accepted", + "decision": "Add cwd github/*/* detection and gh + goal -a publication helpers in glon/cli.py with unit tests in tests/test_cli.py.", + "components": [ + { + "name": "glon-cli", + "paths": [ + "glon/cli.py", + "tests/test_cli.py" + ] + } + ], + "responsibilityChanges": false, + "interfaceChanges": [], + "dataChanges": [], + "ui": { + "impact": "none", + "states": [], + "evidence": [] + }, + "rollback": "Revert commit on ticket/010-publish-github-and-goal." + }, + "runtimeDependencies": [], + "validation": [ + { + "criterion": "AC-01", + "commands": [ + "pytest -q" + ], + "evidence": "All CLI unit tests including github/*/* detection and gh/goal publication pass." + }, + { + "criterion": "AC-02", + "commands": [ + "./project/governance-check.sh", + "mypy glon" + ], + "evidence": "Governance check and static type check pass." + } + ] + } +} diff --git a/project/ticket-010/preprompt.md b/project/ticket-010/preprompt.md new file mode 100644 index 0000000..9443371 --- /dev/null +++ b/project/ticket-010/preprompt.md @@ -0,0 +1,12 @@ +# Ticket preprompt + +- **Task ID**: ticket-010 +- **Task title**: Publish current github/*/* repo via gh and goal -a +- **Created**: 2026-11-23T07:55:48Z + +Keep executable implementation outside this governance/evidence directory. +Read a human-owned user-*.md file only when one exists. +The request to execute this work creates SESSION_EXECUTION_AUTHORIZATION; +proceed within the recorded intent without a redundant confirmation prompt. +Require new authority for destructive action, secrets, external coordination, +material objective expansion and trusted merge approval. diff --git a/tests/test_cli.py b/tests/test_cli.py index 4bb630b..385ece4 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -11,7 +11,9 @@ _extract_git_url_from_text, clone_repository, create_directory_structure, + detect_github_repo_from_cwd, parse_git_url, + publish_repository, ) @@ -385,3 +387,219 @@ def test_main_clone_subcommand(self, mock_parse, mock_create, mock_clone) -> Non mock_parse.assert_called_once_with("https://github.com/owner/repo.git") mock_clone.assert_called_once() + + +class TestDetectGithubRepo: + """Test cases for detecting github// from cwd.""" + + def test_detect_repo_under_base_path(self) -> None: + """Detect owner/repo when cwd is directly under base_path.""" + with tempfile.TemporaryDirectory() as temp_dir: + repo_dir = Path(temp_dir) / "kvmouse" / "pi2w" + repo_dir.mkdir(parents=True) + + result = detect_github_repo_from_cwd(cwd=repo_dir, base_path=temp_dir) + + assert result == ("kvmouse", "pi2w", repo_dir.resolve()) + + def test_detect_repo_from_nested_subdir(self) -> None: + """Detect owner/repo root even when cwd is a subdirectory.""" + with tempfile.TemporaryDirectory() as temp_dir: + repo_dir = Path(temp_dir) / "kvmouse" / "pi2w" + nested_dir = repo_dir / "docs" / "guides" + nested_dir.mkdir(parents=True) + + result = detect_github_repo_from_cwd(cwd=nested_dir, base_path=temp_dir) + + assert result == ("kvmouse", "pi2w", repo_dir.resolve()) + + def test_detect_repo_under_generic_github_dir(self) -> None: + """Detect owner/repo under any .../github// path.""" + with tempfile.TemporaryDirectory() as temp_dir: + repo_dir = Path(temp_dir) / "github" / "semcod" / "glon" + repo_dir.mkdir(parents=True) + + with patch("os.path.expanduser", return_value="/nonexistent/github"): + result = detect_github_repo_from_cwd(cwd=repo_dir) + + assert result == ("semcod", "glon", repo_dir.resolve()) + + def test_detect_returns_none_outside_repo_level(self) -> None: + """Return None at owner level or outside github directory.""" + with tempfile.TemporaryDirectory() as temp_dir: + owner_dir = Path(temp_dir) / "kvmouse" + owner_dir.mkdir(parents=True) + + assert detect_github_repo_from_cwd(cwd=owner_dir, base_path=temp_dir) is None + assert ( + detect_github_repo_from_cwd(cwd=Path(temp_dir), base_path=temp_dir) + is None + ) + + +class TestPublishRepository: + """Test cases for publishing github/*/* repos via gh and goal -a.""" + + @patch("subprocess.run") + def test_publish_new_repo_private_default(self, mock_run) -> None: + """Initialize git, create private GitHub repo via gh, and run goal -a.""" + with tempfile.TemporaryDirectory() as temp_dir: + repo_dir = Path(temp_dir) / "github" / "kvmouse" / "pi2w" + repo_dir.mkdir(parents=True) + + def fake_run(cmd, **kwargs): + if cmd[:3] == ["git", "rev-parse", "--verify"]: + return MagicMock(returncode=1, stdout="", stderr="") + return MagicMock(returncode=0, stdout="", stderr="") + + mock_run.side_effect = fake_run + + result = publish_repository(repo_dir, "kvmouse", "pi2w") + + assert result is True + commands = [call.args[0] for call in mock_run.call_args_list] + assert ["git", "init"] in commands + assert ["git", "add", "-A"] in commands + assert ["git", "commit", "--allow-empty", "-m", "Initial commit"] in commands + assert [ + "gh", + "repo", + "create", + "kvmouse/pi2w", + "--private", + "--source=.", + "--remote=origin", + "--push", + ] in commands + assert ["goal", "-a"] in commands + + @patch("subprocess.run") + def test_publish_existing_origin_public(self, mock_run) -> None: + """Update visibility to public, push origin, and run goal -a.""" + with tempfile.TemporaryDirectory() as temp_dir: + repo_dir = Path(temp_dir) / "github" / "semcod" / "glon" + (repo_dir / ".git").mkdir(parents=True) + + def fake_run(cmd, **kwargs): + if cmd[:3] == ["git", "remote", "get-url"]: + return MagicMock( + returncode=0, + stdout="https://github.com/semcod/glon.git\n", + stderr="", + ) + return MagicMock(returncode=0, stdout="", stderr="") + + mock_run.side_effect = fake_run + + result = publish_repository(repo_dir, "semcod", "glon", visibility="public") + + assert result is True + commands = [call.args[0] for call in mock_run.call_args_list] + assert [ + "gh", + "repo", + "edit", + "semcod/glon", + "--visibility", + "public", + ] in commands + assert ["git", "push", "-u", "origin", "HEAD"] in commands + assert ["goal", "-a"] in commands + + @patch("subprocess.run") + def test_publish_dry_run_skips_mutating_commands(self, mock_run) -> None: + """Dry run prints planned commands without executing gh or goal.""" + with tempfile.TemporaryDirectory() as temp_dir: + repo_dir = Path(temp_dir) / "github" / "kvmouse" / "pi2w" + repo_dir.mkdir(parents=True) + + result = publish_repository( + repo_dir, "kvmouse", "pi2w", visibility="private", dry_run=True + ) + + assert result is True + mock_run.assert_not_called() + + @patch("glon.cli.publish_repository", return_value=True) + @patch("glon.cli.detect_github_repo_from_cwd") + def test_main_no_args_in_github_folder_publishes_private( + self, mock_detect, mock_publish + ) -> None: + """Running `glon` inside github/*/* publishes privately by default.""" + repo_path = Path("/tmp/github/kvmouse/pi2w") + mock_detect.return_value = ("kvmouse", "pi2w", repo_path) + + with patch("sys.argv", ["glon"]): + from glon.cli import main + + main() + + mock_publish.assert_called_once_with( + repo_path, + "kvmouse", + "pi2w", + visibility="private", + dry_run=False, + verbose=False, + ) + + @patch("glon.cli.publish_repository", return_value=True) + @patch("glon.cli.detect_github_repo_from_cwd") + def test_main_public_subcommand_publishes_public( + self, mock_detect, mock_publish + ) -> None: + """Running `glon public` publishes with public visibility.""" + repo_path = Path("/tmp/github/kvmouse/pi2w") + mock_detect.return_value = ("kvmouse", "pi2w", repo_path) + + with patch("sys.argv", ["glon", "public"]): + from glon.cli import main + + main() + + mock_publish.assert_called_once_with( + repo_path, + "kvmouse", + "pi2w", + visibility="public", + dry_run=False, + verbose=False, + ) + + @patch("glon.cli.publish_repository", return_value=True) + @patch("glon.cli.detect_github_repo_from_cwd") + def test_main_private_subcommand_publishes_private( + self, mock_detect, mock_publish + ) -> None: + """Running `glon private` publishes with private visibility.""" + repo_path = Path("/tmp/github/kvmouse/pi2w") + mock_detect.return_value = ("kvmouse", "pi2w", repo_path) + + with patch("sys.argv", ["glon", "private"]): + from glon.cli import main + + main() + + mock_publish.assert_called_once_with( + repo_path, + "kvmouse", + "pi2w", + visibility="private", + dry_run=False, + verbose=False, + ) + + @patch("glon.cli.detect_github_repo_from_cwd", return_value=None) + def test_main_private_outside_github_folder_prints_error( + self, mock_detect + ) -> None: + """Running `glon private` outside github/*/* prints a clear error.""" + with patch("sys.argv", ["glon", "private"]): + with patch("builtins.print") as mock_print: + from glon.cli import main + + main() + + mock_print.assert_any_call( + "Error: Current directory is not inside a github// folder." + )