Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-26
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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).
28 changes: 28 additions & 0 deletions openspec/specs/git-sync/spec.md
Original file line number Diff line number Diff line change
@@ -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
8 changes: 7 additions & 1 deletion src/devops_cli/commands/branches.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
7 changes: 6 additions & 1 deletion src/devops_cli/commands/repos.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -367,17 +368,21 @@ 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:
fetch_all(repo_dir)
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)


# =============================================================================
Expand Down
52 changes: 44 additions & 8 deletions src/devops_cli/git/operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
40 changes: 40 additions & 0 deletions tests/test_branches.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Loading
Loading