From d0288d68e146c0e558e54c2ec4580c0c08fd0e57 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Mon, 26 Oct 2026 02:59:39 +0000 Subject: [PATCH] fix(cli): repos sync and branches sync report a failed fetch or pull instead of printing success Raise `GitOperationError` on `fetch_all` and `pull_tracking` failures. Name the repository, remote, and git's masked error reason in the exception. Report each failed repository in `repos sync` and `branches sync`. Continue processing all remaining repositories in the workspace. Exit with status 1 when any repository fails to synchronize. Closes #1399 Validated with: `uv run devops ci fail-to-pass --base origin/main` (7 failed on base, 0 errored) --- .../.openspec.yaml | 2 + .../design.md | 40 ++++++++ .../proposal.md | 50 ++++++++++ .../specs/git-sync/spec.md | 29 ++++++ .../tasks.md | 26 +++++ openspec/specs/git-sync/spec.md | 28 ++++++ src/devops_cli/commands/branches.py | 8 +- src/devops_cli/commands/repos.py | 7 +- src/devops_cli/git/operations.py | 52 ++++++++-- tests/test_branches.py | 40 ++++++++ tests/test_git_operations.py | 97 ++++++++++++++++++- tests/test_repos.py | 44 ++++++++- 12 files changed, 409 insertions(+), 14 deletions(-) create mode 100644 openspec/changes/archive/2026-10-26-1399-sync-error-reporting/.openspec.yaml create mode 100644 openspec/changes/archive/2026-10-26-1399-sync-error-reporting/design.md create mode 100644 openspec/changes/archive/2026-10-26-1399-sync-error-reporting/proposal.md create mode 100644 openspec/changes/archive/2026-10-26-1399-sync-error-reporting/specs/git-sync/spec.md create mode 100644 openspec/changes/archive/2026-10-26-1399-sync-error-reporting/tasks.md create mode 100644 openspec/specs/git-sync/spec.md diff --git a/openspec/changes/archive/2026-10-26-1399-sync-error-reporting/.openspec.yaml b/openspec/changes/archive/2026-10-26-1399-sync-error-reporting/.openspec.yaml new file mode 100644 index 0000000000..d58ba02327 --- /dev/null +++ b/openspec/changes/archive/2026-10-26-1399-sync-error-reporting/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-10-26 diff --git a/openspec/changes/archive/2026-10-26-1399-sync-error-reporting/design.md b/openspec/changes/archive/2026-10-26-1399-sync-error-reporting/design.md new file mode 100644 index 0000000000..f0a3964829 --- /dev/null +++ b/openspec/changes/archive/2026-10-26-1399-sync-error-reporting/design.md @@ -0,0 +1,40 @@ +# Design + +## Context + +See proposal.md - Why. +`src/devops_cli/git/operations.py` contains `fetch_all` and `pull_tracking`. +Both functions currently catch `GitCommandError` and execute `pass`. +`src/devops_cli/commands/repos.py` and `src/devops_cli/commands/branches.py` call these operations. +Both command suites print errors to the console but exit with return code 0 when operations fail. + +## Goals / Non-Goals + +**Goals:** +- Raise typed `GitOperationError` on `fetch_all` and `pull_tracking` failures. +- Populate `operation`, `repository`, and `remote` in exception details and message. +- Sanitize git standard error with `mask_secrets`. +- Ensure `repos sync` and `branches sync` continue processing all workspace repositories. +- Exit non-zero (exit code 1) from `repos sync` and `branches sync` when any repository fails. + +**Non-Goals:** +- Change interactive command prompt behavior. +- Add automatic git merge conflict resolution. +- Modify repository cloning or branch creation workflows. + +## Decisions + +### Decision 1: Shape `GitOperationError` to match #900 and #1114 conventions +- *Rationale*: Precedent from `create_branch` (#900) and `clone_repo` (#1114) sanitizes git stderr with `mask_secrets` and attaches structured operation details. Raising `GitOperationError(f"fetch failed for '{repo_dir}' remote '{remote.name}': {reason}", operation="fetch", details={"repository": str(repo_dir)[:CONST_MAX_ERROR_DETAIL_LENGTH], "remote": str(remote.name)[:CONST_MAX_ERROR_DETAIL_LENGTH]})` satisfies both the message naming requirement and structured details. +- *Alternatives considered*: Raise raw `gitlib.GitCommandError`. Rejected because `devops-cli` requires strongly typed domain exceptions inheriting from `DevOpsCLIError`. +- *Alternatives considered*: Only populate `details` without repository and remote in the message string. Rejected because CLI loggers and command error handlers print exception string representations. + +### Decision 2: Record failures per repository and exit non-zero after completion +- *Rationale*: Workspace commands must process all configured repositories so partial connectivity failures do not prevent updating other healthy repositories. A boolean flag tracks whether any repository encountered a failure during iteration. If the flag is set, the command raises `typer.Exit(1)` after iteration finishes. +- *Alternatives considered*: Exit immediately on the first failure (`fail-fast`). Rejected because users need all independent repository updates completed in one command run. +- *Alternatives considered*: Return zero exit code and only print warnings. Rejected by issue acceptance criteria and repository fail-closed invariants. + +## Risks / Trade-offs + +- [Scripts expecting exit code 0 when remotes are offline will fail] → Intentional behavior. Callers must handle non-zero exit codes when repositories fail to synchronize. +- [Long running sync across many broken repositories] → Iteration continues sequentially. Tests verify individual phases remain under 1 second using local bare repositories. diff --git a/openspec/changes/archive/2026-10-26-1399-sync-error-reporting/proposal.md b/openspec/changes/archive/2026-10-26-1399-sync-error-reporting/proposal.md new file mode 100644 index 0000000000..d4655197bb --- /dev/null +++ b/openspec/changes/archive/2026-10-26-1399-sync-error-reporting/proposal.md @@ -0,0 +1,50 @@ +# Proposal + +## Why + +Issue #1399: `fetch_all` and `pull_tracking` in `src/devops_cli/git/operations.py` catch `GitCommandError` and silently pass. +Because of this defect, `devops repos sync` and `devops branches sync` print success when a fetch or pull operation fails. +Users then work on stale clones without receiving a failure notification. + +## What Changes + +- `fetch_all` catches `gitlib.GitCommandError` and raises `GitOperationError` naming the repository, remote, and git's masked reason. +- `pull_tracking` catches `gitlib.GitCommandError` and raises `GitOperationError` naming the repository, remote, and git's masked reason. +- Neither function swallows `gitlib.GitCommandError`. +- `devops repos sync` reports each failed repository with git's reason, finishes all remaining repositories, and exits non-zero if any repository failed. +- `devops branches sync` reports each failed repository with git's reason, finishes all remaining repositories, and exits non-zero if any repository failed. +- This change alters observable CLI failure reporting and exit codes when git operations fail. +- This change fits in one pull request. + +## Capabilities + +### New Capabilities + +- `git-sync`: `fetch_all`, `pull_tracking`, `devops repos sync`, and `devops branches sync` fail closed and report git errors. + +### Modified Capabilities + +None. + +## Impact + +- Code: `src/devops_cli/git/operations.py`, `src/devops_cli/commands/repos.py`, `src/devops_cli/commands/branches.py`. +- Tests: `tests/test_git_operations.py`, `tests/test_repos.py`, `tests/test_branches.py`. +- Documentation: CLI command documentation. + +## Feasibility + +- Premise confirmed at commit `fc30f122` (`origin/main`). +- `src/devops_cli/git/operations.py:159-166` catches `gitlib.GitCommandError` and executes `pass`. +- `src/devops_cli/git/operations.py:169-178` catches `(gitlib.GitCommandError, IndexError)` and executes `pass`. +- `src/devops_cli/commands/branches.py:46-54` catches `(OSError, ValueError)` and returns exit code 0 on failure. +- `src/devops_cli/commands/repos.py:370-380` catches `Exception` and returns exit code 0 on failure. +- `src/devops_cli/security/sanitizer.py:269` provides `mask_secrets` to sanitize git output. +- `src/devops_cli/exceptions/git.py:28` provides `GitOperationError`. + +## Existing Tool Considered + +GitPython (`git`) and OpenSSH provide standard git operations. +`devops_cli.git.operations` wraps these tools to manage multi-repository workspaces. +No new third-party dependency is required. +Internal error suppression blocks (`except gitlib.GitCommandError: pass`) are replaced with fail-closed error propagation. diff --git a/openspec/changes/archive/2026-10-26-1399-sync-error-reporting/specs/git-sync/spec.md b/openspec/changes/archive/2026-10-26-1399-sync-error-reporting/specs/git-sync/spec.md new file mode 100644 index 0000000000..875af07bbc --- /dev/null +++ b/openspec/changes/archive/2026-10-26-1399-sync-error-reporting/specs/git-sync/spec.md @@ -0,0 +1,29 @@ +# Spec Delta + +## Purpose + +Provides fail-closed remote synchronization for git repositories in the workspace, reporting network, authentication, and branch divergence errors. + +## ADDED Requirements + +### Requirement: Fail closed on remote fetch and pull errors +The system SHALL raise a `GitOperationError` naming the repository, remote, and git's reason when a fetch or pull fails. Neither fetch nor pull operations shall swallow `GitCommandError`. + +#### Scenario: Remote refuses fetch +- **WHEN** a git fetch operation encounters an unreachable or forbidden remote +- **THEN** the system raises `GitOperationError` with the repository path, remote name, and sanitized error reason + +#### Scenario: Branch cannot fast-forward on pull +- **WHEN** a git pull operation encounters a divergent tracking branch that cannot fast-forward +- **THEN** the system raises `GitOperationError` with the repository path, remote name, and sanitized error reason + +### Requirement: Workspace synchronization error reporting and non-zero exit +The `devops repos sync` and `devops branches sync` commands SHALL report each failed repository with git's reason, finish processing all remaining workspace repositories, and exit non-zero when any repository fails. + +#### Scenario: One repository fails during repos sync +- **WHEN** one workspace repository encounters a fetch failure during `devops repos sync` +- **THEN** the command prints the failure reason for that repository, synchronizes the remaining repositories, and exits with code 1 + +#### Scenario: One repository fails during branches sync +- **WHEN** one workspace repository encounters a pull failure during `devops branches sync` +- **THEN** the command prints the failure reason for that repository, synchronizes the remaining repositories, and exits with code 1 diff --git a/openspec/changes/archive/2026-10-26-1399-sync-error-reporting/tasks.md b/openspec/changes/archive/2026-10-26-1399-sync-error-reporting/tasks.md new file mode 100644 index 0000000000..6d8e4eb55b --- /dev/null +++ b/openspec/changes/archive/2026-10-26-1399-sync-error-reporting/tasks.md @@ -0,0 +1,26 @@ +# Tasks + +## 1. Failing tests + +- [x] 1.1 Add failing unit and integration tests with local bare remotes for `fetch_all`, `pull_tracking`, `devops repos sync`, and `devops branches sync` + - Verification: `uv run devops ci test tests/test_git_operations.py tests/test_repos.py tests/test_branches.py` + +## 2. Fail-closed git operations and sync reporting + +- [x] 2.1 Update `fetch_all` and `pull_tracking` in `src/devops_cli/git/operations.py` to raise `GitOperationError` with masked stderr, operation, repository, and remote + - Verification: `uv run devops ci test tests/test_git_operations.py` +- [x] 2.2 Update `devops repos sync` in `src/devops_cli/commands/repos.py` and `devops branches sync` in `src/devops_cli/commands/branches.py` to report failed repositories and exit non-zero + - Verification: `uv run devops ci test tests/test_repos.py tests/test_branches.py` +- [x] 2.3 Regenerate CLI documentation + - Verification: `uv run devops docs generate --sync-readme` + +## 3. Verification and checks + +- [x] 3.1 Verify OpenSpec check passes + - Verification: `uv run devops openspec check` +- [x] 3.2 Verify full CI suite passes + - Verification: `uv run devops ci` + +## Workflow follow-up + +- Pending a person: review the diff in tuicr (tuicr -r origin/main..HEAD). diff --git a/openspec/specs/git-sync/spec.md b/openspec/specs/git-sync/spec.md new file mode 100644 index 0000000000..88e5315ca5 --- /dev/null +++ b/openspec/specs/git-sync/spec.md @@ -0,0 +1,28 @@ +# git-sync Specification + +## Purpose +Provides fail-closed remote synchronization for git repositories in the workspace, reporting network, authentication, and branch divergence errors. + +## Requirements + +### Requirement: Fail closed on remote fetch and pull errors +The system SHALL raise a `GitOperationError` naming the repository, remote, and git's reason when a fetch or pull fails. Neither fetch nor pull operations shall swallow `GitCommandError`. + +#### Scenario: Remote refuses fetch +- **WHEN** a git fetch operation encounters an unreachable or forbidden remote +- **THEN** the system raises `GitOperationError` with the repository path, remote name, and sanitized error reason + +#### Scenario: Branch cannot fast-forward on pull +- **WHEN** a git pull operation encounters a divergent tracking branch that cannot fast-forward +- **THEN** the system raises `GitOperationError` with the repository path, remote name, and sanitized error reason + +### Requirement: Workspace synchronization error reporting and non-zero exit +The `devops repos sync` and `devops branches sync` commands SHALL report each failed repository with git's reason, finish processing all remaining workspace repositories, and exit non-zero when any repository fails. + +#### Scenario: One repository fails during repos sync +- **WHEN** one workspace repository encounters a fetch failure during `devops repos sync` +- **THEN** the command prints the failure reason for that repository, synchronizes the remaining repositories, and exits with code 1 + +#### Scenario: One repository fails during branches sync +- **WHEN** one workspace repository encounters a pull failure during `devops branches sync` +- **THEN** the command prints the failure reason for that repository, synchronizes the remaining repositories, and exits with code 1 diff --git a/src/devops_cli/commands/branches.py b/src/devops_cli/commands/branches.py index 4b31d0f7fb..b4498a803a 100755 --- a/src/devops_cli/commands/branches.py +++ b/src/devops_cli/commands/branches.py @@ -11,6 +11,7 @@ from devops_cli.config.constants import CONST_GIT_DIR_NAME from devops_cli.config.settings import load_settings from devops_cli.core.cli import new_typer, repo_label +from devops_cli.exceptions import DevOpsCLIError from devops_cli.git.operations import ( create_branch, delete_merged_branches, @@ -43,15 +44,20 @@ def update( settings = load_settings() root = base_dir or settings.repos.base_dir + failed = False for repo_dir in iter_workspace_repos(root): label = repo_label(repo_dir) try: fetch_all(repo_dir) pull_tracking(repo_dir) print_success(label) - except (OSError, ValueError) as exc: + except (DevOpsCLIError, OSError, ValueError) as exc: + failed = True print_error(f"{label}: {exc}") + if failed: + raise typer.Exit(1) + # ============================================================================= # Command: devops branches jira diff --git a/src/devops_cli/commands/repos.py b/src/devops_cli/commands/repos.py index d6c56cb047..3cedccf66c 100755 --- a/src/devops_cli/commands/repos.py +++ b/src/devops_cli/commands/repos.py @@ -28,6 +28,7 @@ from devops_cli.core.process import run_subprocess from devops_cli.core.repo import find_repo_root from devops_cli.dry_run import is_dry_run +from devops_cli.exceptions import DevOpsCLIError from devops_cli.exceptions.git import GitHubOperationError, GitOperationError from devops_cli.git.operations import clone_repo, fetch_all, iter_workspace_repos, pull_tracking from devops_cli.git.worktree_inventory import inventory_worktrees, prune_worktrees @@ -367,6 +368,7 @@ def update( print_warning(MESSAGES.repos.no_repos_found, prefix=False) raise typer.Exit(0) + failed = False for repo_dir in track_progress(repos_list, description="Updating..."): label = repo_label(repo_dir) try: @@ -374,10 +376,13 @@ def update( if pull: pull_tracking(repo_dir) print_success(f"{label}") - except (OSError, subprocess.SubprocessError, Exception) as exc: + except (DevOpsCLIError, OSError, subprocess.SubprocessError, Exception) as exc: + failed = True print_error(f"{label}: {exc}") _sync_and_reload_workspace(root, settings.workspace.file) + if failed: + raise typer.Exit(1) # ============================================================================= diff --git a/src/devops_cli/git/operations.py b/src/devops_cli/git/operations.py index e976c5d186..a66a190777 100755 --- a/src/devops_cli/git/operations.py +++ b/src/devops_cli/git/operations.py @@ -162,20 +162,56 @@ def fetch_all(repo_dir: Path) -> None: for remote in repo.remotes: try: remote.fetch(prune=True) - except gitlib.GitCommandError: - pass + except gitlib.GitCommandError as exc: + from devops_cli.security.sanitizer import mask_secrets + + stderr = exc.stderr if isinstance(exc.stderr, str) else "" + reason = mask_secrets(stderr.strip() or str(exc)) + raise GitOperationError( + f"Failed to fetch remote '{remote.name}' in '{repo_dir}': {reason}", + operation="fetch", + details={ + "repository": str(repo_dir)[:CONST_MAX_ERROR_DETAIL_LENGTH], + "remote": str(remote.name)[:CONST_MAX_ERROR_DETAIL_LENGTH], + }, + ) from exc def pull_tracking(repo_dir: Path) -> None: """Pull the current tracking branch if one is configured.""" repo = gitlib.Repo(str(repo_dir)) + if repo.head.is_detached: + return + tracking = repo.active_branch.tracking_branch() + if not tracking: + return + remote_name = tracking.remote_name try: - if not repo.head.is_detached: - tracking = repo.active_branch.tracking_branch() - if tracking: - repo.remotes[tracking.remote_name].pull(repo.active_branch.name) - except gitlib.GitCommandError, IndexError: - pass + remote = repo.remotes[remote_name] + except IndexError as exc: + raise GitOperationError( + f"Remote '{remote_name}' configured for tracking in '{repo_dir}' not found", + operation="pull", + details={ + "repository": str(repo_dir)[:CONST_MAX_ERROR_DETAIL_LENGTH], + "remote": str(remote_name)[:CONST_MAX_ERROR_DETAIL_LENGTH], + }, + ) from exc + try: + remote.pull(repo.active_branch.name) + except gitlib.GitCommandError as exc: + from devops_cli.security.sanitizer import mask_secrets + + stderr = exc.stderr if isinstance(exc.stderr, str) else "" + reason = mask_secrets(stderr.strip() or str(exc)) + raise GitOperationError( + f"Failed to pull remote '{remote_name}' in '{repo_dir}': {reason}", + operation="pull", + details={ + "repository": str(repo_dir)[:CONST_MAX_ERROR_DETAIL_LENGTH], + "remote": str(remote_name)[:CONST_MAX_ERROR_DETAIL_LENGTH], + }, + ) from exc def create_branch(repo_dir: Path, branch_name: str) -> None: diff --git a/tests/test_branches.py b/tests/test_branches.py index ec1c392ca1..264782b079 100755 --- a/tests/test_branches.py +++ b/tests/test_branches.py @@ -134,3 +134,43 @@ def test_jira_prints_gits_reason_when_git_refuses_the_branch( assert isinstance(result.exception, SystemExit) assert "Traceback" not in result.output assert "'refs/heads/feature' exists" in result.output + + +def test_branches_sync_reports_failures_and_exits_nonzero( + tmp_path: Path, git: Callable[..., None] +) -> None: + """`branches sync` reports failed repos with git's reason, finishes remaining repos, and exits 1.""" + repos_dir = tmp_path / "repos" + bare1 = tmp_path / "bare1.git" + bare2 = tmp_path / "bare2.git" + bare1.mkdir() + bare2.mkdir() + git(bare1, "init", "--bare", "--initial-branch=main", "--quiet") + git(bare2, "init", "--bare", "--initial-branch=main", "--quiet") + + repo1 = repos_dir / "group" / "repo1" + repo2 = repos_dir / "group" / "repo2" + git(tmp_path, "clone", "--quiet", str(bare1), str(repo1)) + git(tmp_path, "clone", "--quiet", str(bare2), str(repo2)) + + (repo1 / "f.txt").write_text("1", encoding="utf-8") + git(repo1, "add", ".") + git(repo1, "commit", "--quiet", "-m", "init") + git(repo1, "push", "--quiet", "origin", "main") + + (repo2 / "f.txt").write_text("2", encoding="utf-8") + git(repo2, "add", ".") + git(repo2, "commit", "--quiet", "-m", "init") + git(repo2, "push", "--quiet", "origin", "main") + + # Make bare1 refuse fetch + objects_dir = bare1 / "objects" + objects_dir.chmod(0o000) + + try: + res = runner.invoke(branches_app, ["sync", "--base-dir", str(repos_dir)]) + assert res.exit_code == 1 + assert "group/repo1" in res.output + assert "group/repo2" in res.output + finally: + objects_dir.chmod(0o755) diff --git a/tests/test_git_operations.py b/tests/test_git_operations.py index 11623650c0..1997cfc674 100644 --- a/tests/test_git_operations.py +++ b/tests/test_git_operations.py @@ -124,8 +124,18 @@ def test_fetch_all(tmp_path: Path) -> None: mock_remote.fetch.assert_called_once_with(prune=True) # Exception handling + mock_remote.name = "origin" mock_remote.fetch.side_effect = gitlib.GitCommandError("fetch", "network error") - fetch_all(tmp_path) + with pytest.raises(GitOperationError) as exc_info: + fetch_all(tmp_path) + assert ( + "network error" in str(exc_info.value), + str(tmp_path) in str(exc_info.value), + "origin" in str(exc_info.value), + exc_info.value.details["operation"], + exc_info.value.details["repository"], + exc_info.value.details["remote"], + ) == (True, True, True, "fetch", str(tmp_path), "origin") def test_pull_tracking(tmp_path: Path) -> None: @@ -276,7 +286,7 @@ def test_is_git_clean_and_get_latest_tag(tmp_path: Path) -> None: def test_git_operations_edge_cases(tmp_path: Path) -> None: """Verify pull_tracking error handling, delete_merged_branches empty branches, and keyscan failure.""" - # 1. pull_tracking handles GitCommandError and IndexError + # 1. pull_tracking raises GitOperationError on GitCommandError with patch("devops_cli.git.operations.gitlib.Repo") as mock_repo_cls: mock_repo = MagicMock() mock_repo.head.is_detached = False @@ -291,7 +301,16 @@ def test_git_operations_edge_cases(tmp_path: Path) -> None: mock_repo.remotes = {"origin": mock_remote} mock_repo_cls.return_value = mock_repo - pull_tracking(tmp_path) + with pytest.raises(GitOperationError) as exc_info: + pull_tracking(tmp_path) + assert ( + "network down" in str(exc_info.value), + str(tmp_path) in str(exc_info.value), + "origin" in str(exc_info.value), + exc_info.value.details["operation"], + exc_info.value.details["repository"], + exc_info.value.details["remote"], + ) == (True, True, True, "pull", str(tmp_path), "origin") # 2. delete_merged_branches with no default branch with patch("devops_cli.git.operations.gitlib.Repo") as mock_repo_cls: @@ -505,3 +524,75 @@ def test_commit_snapshot_makes_the_same_one_commit_of_the_same_files( "main", 1, ) + + +def test_fetch_all_refused_by_bare_remote_raises_git_operation_error( + tmp_path: Path, git: Callable[..., None] +) -> None: + """A bare remote that refuses fetch raises GitOperationError with repository, remote, and reason.""" + bare = tmp_path / "remote.git" + bare.mkdir() + git(bare, "init", "--bare", "--initial-branch=main", "--quiet") + repo = tmp_path / "clone" + git(tmp_path, "clone", "--quiet", str(bare), str(repo)) + (repo / "file.txt").write_text("content", encoding="utf-8") + git(repo, "add", ".") + git(repo, "commit", "--quiet", "-m", "init") + git(repo, "push", "--quiet", "origin", "main") + + objects_dir = bare / "objects" + objects_dir.chmod(0o000) + try: + with pytest.raises(GitOperationError) as raised: + fetch_all(repo) + finally: + objects_dir.chmod(0o755) + + msg = str(raised.value) + assert ( + str(repo) in msg, + "origin" in msg, + raised.value.details["operation"], + raised.value.details["repository"], + raised.value.details["remote"], + ) == (True, True, "fetch", str(repo), "origin") + + +def test_pull_tracking_divergent_branch_raises_git_operation_error( + tmp_path: Path, git: Callable[..., None] +) -> None: + """A divergent tracking branch that cannot fast-forward raises GitOperationError.""" + bare = tmp_path / "remote.git" + bare.mkdir() + git(bare, "init", "--bare", "--initial-branch=main", "--quiet") + + clone1 = tmp_path / "clone1" + git(tmp_path, "clone", "--quiet", str(bare), str(clone1)) + (clone1 / "file1.txt").write_text("c1", encoding="utf-8") + git(clone1, "add", ".") + git(clone1, "commit", "--quiet", "-m", "commit 1") + git(clone1, "push", "--quiet", "origin", "main") + + clone2 = tmp_path / "clone2" + git(tmp_path, "clone", "--quiet", str(bare), str(clone2)) + + (clone1 / "file2.txt").write_text("c2", encoding="utf-8") + git(clone1, "add", ".") + git(clone1, "commit", "--quiet", "-m", "commit 2") + git(clone1, "push", "--quiet", "origin", "main") + + (clone2 / "file3.txt").write_text("c3", encoding="utf-8") + git(clone2, "add", ".") + git(clone2, "commit", "--quiet", "-m", "commit 3") + + with pytest.raises(GitOperationError) as raised: + pull_tracking(clone2) + + msg = str(raised.value) + assert ( + str(clone2) in msg, + "origin" in msg, + raised.value.details["operation"], + raised.value.details["repository"], + raised.value.details["remote"], + ) == (True, True, "pull", str(clone2), "origin") diff --git a/tests/test_repos.py b/tests/test_repos.py index dda88a9c53..92d7b2e3ad 100755 --- a/tests/test_repos.py +++ b/tests/test_repos.py @@ -297,6 +297,8 @@ def test_repos_update_syncs_workspace(tmp_path: Path) -> None: with ( patch("devops_cli.commands.repos.load_settings") as mock_load, + patch("devops_cli.commands.repos.fetch_all"), + patch("devops_cli.commands.repos.pull_tracking"), patch("devops_cli.commands.repos.sync_from_repos") as mock_sync, patch("devops_cli.commands.repos._reload_workspace") as mock_reload, ): @@ -896,7 +898,47 @@ def test_repos_sync_pull_and_errors(tmp_path: Path) -> None: # Fetch error handled gracefully mock_fetch.side_effect = RuntimeError("Git network timeout") res_err = runner.invoke(repos_app, ["sync"]) - assert res_err.exit_code == 0 + assert res_err.exit_code == 1 + + +def test_repos_sync_reports_failures_and_exits_nonzero( + tmp_path: Path, git: Callable[..., None], process_fake: Any +) -> None: + """`repos sync` reports failed repos with git's reason, finishes remaining repos, and exits 1.""" + repos_dir = tmp_path / "repos" + bare1 = tmp_path / "bare1.git" + bare2 = tmp_path / "bare2.git" + bare1.mkdir() + bare2.mkdir() + git(bare1, "init", "--bare", "--initial-branch=main", "--quiet") + git(bare2, "init", "--bare", "--initial-branch=main", "--quiet") + + repo1 = repos_dir / "group" / "repo1" + repo2 = repos_dir / "group" / "repo2" + git(tmp_path, "clone", "--quiet", str(bare1), str(repo1)) + git(tmp_path, "clone", "--quiet", str(bare2), str(repo2)) + + (repo1 / "f.txt").write_text("1", encoding="utf-8") + git(repo1, "add", ".") + git(repo1, "commit", "--quiet", "-m", "init") + git(repo1, "push", "--quiet", "origin", "main") + + (repo2 / "f.txt").write_text("2", encoding="utf-8") + git(repo2, "add", ".") + git(repo2, "commit", "--quiet", "-m", "init") + git(repo2, "push", "--quiet", "origin", "main") + + # Make bare1 refuse fetch + objects_dir = bare1 / "objects" + objects_dir.chmod(0o000) + + try: + res = runner.invoke(repos_app, ["sync", "--base-dir", str(repos_dir)]) + assert res.exit_code == 1 + assert "group/repo1" in res.output + assert "group/repo2" in res.output + finally: + objects_dir.chmod(0o755) def test_core_repo_safe_paths_and_tracked_files(tmp_path: Path) -> None: