diff --git a/CHANGES b/CHANGES index 137449eb9..3b16b17da 100644 --- a/CHANGES +++ b/CHANGES @@ -104,6 +104,29 @@ Minimum `libvcs>=0.47.0,<0.48.0` (was `>=0.46.0,<0.47.0`). ### What's new +#### Apply checkout policy to linked worktrees (#578) + +{ref}`cli-worktree-sync` and {ref}`cli-sync` with `--include-worktrees` +resolve typed targets, honor drift and dirty policy, and retain native +recovery results. Existing tag and commit checkouts move when their target +changes. Parent Git options, selected remotes, and explicit detachment apply +to worktree planning and updates. Missing worktrees fetch and create under the +same native ownership lock; requested lock failures retain the completed +creation result. + +Configured discard requires `--yes`; included worktree policies are checked +before the main checkout changes. JSON and NDJSON retain exact recovery +locations after restoration or conflict, and human output shows recovery +identity. Read-only worktree planning and `--dry-run` previews never fetch and +exit cleanly when remote targets have not been fetched yet; live `worktree sync` +exits `1` when any worktree is blocked or errors. + +`worktree sync` and `sync --include-worktrees` stop owned native processes on +timeout or Ctrl-C and report retained recovery tokens. Each linked checkout +has a separate deadline; standalone `worktree sync` accepts `--timeout`. +Interrupted metadata remains unknown, and a timeout skips remaining worktrees +for that repository. + #### Preserve Mercurial fetch and push remotes during sync (#590) Mercurial remotes reach native sync with separate fetch and push URLs, both diff --git a/MIGRATION b/MIGRATION index 77fdc565b..382b7d382 100644 --- a/MIGRATION +++ b/MIGRATION @@ -30,6 +30,17 @@ the worker and its native descendants before the command continues or exits. Interrupted JSON/NDJSON events report unknown state and `retained_recoveries` discovered by a separately bounded inspection. Discovery can include tokens from earlier operations; it does not restore or release them automatically. +The same ownership applies to `sync --include-worktrees` and `worktree sync`. +Each linked checkout has a separate deadline; standalone `worktree sync` +accepts `--timeout`. A timed-out worktree prevents further worktrees for that +repository from starting. Interrupted worktree metadata remains unknown when +the worker did not return it. + +### Guarded worktree creation + +Worktree creation fetches configured remotes before selecting its initial +target. A failed requested worktree lock returns an error with completed +creation state; inspect that result before retrying an occupied destination. ### Explicit checkout policy and sync results diff --git a/docs/cli/sync.md b/docs/cli/sync.md index feef49b26..32b107dfa 100644 --- a/docs/cli/sync.md +++ b/docs/cli/sync.md @@ -20,10 +20,12 @@ synchronized with remote repositories. ## Timeouts and interruption -`--timeout` bounds each repository sync. On timeout or Ctrl-C, vcspull stops +`--timeout` bounds each main checkout and each included worktree separately. +On timeout or Ctrl-C, vcspull stops its worker and native process group before continuing or exiting. Progress and output are streamed to the parent process, which owns the terminal and JSON output. CLI synchronization requires POSIX process groups. +An included worktree timeout skips the remaining worktrees for that repository. A stopped update can leave partially changed files. Its result remains unknown unless the worker returned a complete native result. Retained diff --git a/docs/cli/worktree/index.md b/docs/cli/worktree/index.md index 002d6d7df..ff2084d20 100644 --- a/docs/cli/worktree/index.md +++ b/docs/cli/worktree/index.md @@ -40,7 +40,7 @@ prune Worktrees are configured as a list under a repository entry. Each worktree requires a `dir` (relative to workspace root or absolute) and exactly one -ref type: `tag`, `branch`, or `commit`. +ref type: `tag`, `branch`, `commit`, or native `rev`. ```yaml ~/code/: @@ -68,12 +68,17 @@ ref type: `tag`, `branch`, or `commit`. |-------|----------|-------------| | `dir` | yes | Worktree path (relative to workspace root or absolute) | | `tag` | one of | Tag to checkout (creates detached HEAD) | -| `branch` | one of | Branch to checkout (can be updated/pulled) | +| `branch` | one of | Branch to follow with fast-forward updates | | `commit` | one of | Commit SHA to checkout (creates detached HEAD) | +| `rev` | one of | Native revision expression; attachment follows its resolved kind | +| `remote` | no | Fetch source for a branch target | +| `sync` | no | Drift and dirty policies described in {ref}`cli-worktree-sync` | +| `detach` | no | Keep the resolved target detached, including a branch | | `lock` | no | Lock the worktree to prevent accidental removal | | `lock_reason` | no | Reason for locking (implies `lock: true`) | -Exactly one of `tag`, `branch`, or `commit` must be specified per entry. +Exactly one of `tag`, `branch`, `commit`, or `rev` must be specified per entry. +Worktrees inherit the parent repository's Git transport options and remotes. ## Integration with vcspull sync @@ -105,14 +110,32 @@ Each worktree entry emits: ```json { + "reason": "worktree", "worktree_path": "~/code/myproject-v2.0", "ref_type": "tag", "ref_value": "v2.0.0", "action": "unchanged", "exists": true, "is_dirty": false, - "detail": "tag worktree already exists", - "error": null + "detail": "already at configured target", + "error": null, + "position": { + "revision": "3b8a1f2c9d0e4b5a6c7d8e9f0a1b2c3d4e5f6a7b", + "ref_name": "3b8a1f2c9d0e4b5a6c7d8e9f0a1b2c3d4e5f6a7b", + "ref_kind": "commit", + "follows": false, + "mixed": false, + "switched": false + }, + "target_position": { + "revision": "3b8a1f2c9d0e4b5a6c7d8e9f0a1b2c3d4e5f6a7b", + "ref_name": "v2.0.0", + "ref_kind": "tag", + "follows": false, + "mixed": false, + "switched": false + }, + "drifted": false } ``` @@ -133,13 +156,17 @@ log aggregation. vcspull refuses to touch work it could destroy: -**Uncommitted changes stop updates.** If a worktree has uncommitted changes, -vcspull will not update or remove it — commit or stash first. These entries -show as blocked (`⚠`) in {ref}`vcspull worktree list `. - -**Unknown refs stop creation.** If a configured tag, branch, or commit -doesn't exist in the repository, the entry is reported as an error (`✗`) -rather than guessed at. Fetch from the remote to make the ref available. +**Dirty policy governs updates.** Updates abort on local changes by default. +Configure `sync.dirty: preserve` to retain and restore them, or configure +`discard` and pass `--yes` to authorize their removal. See +{ref}`cli-worktree-sync` for recovery output and drift policy. Worktree +pruning still refuses dirty checkouts. + +**Unknown refs stop creation.** `vcspull worktree list` and `--dry-run` +inspect local metadata only, reporting unfetched refs as errors (`✗`) without +contacting remotes. `vcspull worktree sync` fetches configured remotes before +creating missing worktrees or updating branches, and reports an error (`✗`) if +the target still cannot be resolved. **Locks guard against removal.** Worktrees created with `lock: true` or `lock_reason` are locked via `git worktree lock`, preventing accidental diff --git a/docs/cli/worktree/sync.md b/docs/cli/worktree/sync.md index beef60cee..4b1ea21bd 100644 --- a/docs/cli/worktree/sync.md +++ b/docs/cli/worktree/sync.md @@ -22,15 +22,65 @@ Sync all configured worktrees: $ vcspull worktree sync '*' ``` -The sync subcommand: -- Creates missing worktrees at the configured `dir` -- Pulls latest changes for `branch` worktrees -- Leaves `tag` and `commit` worktrees unchanged (they're immutable) -- Skips worktrees with uncommitted changes (BLOCKED) +Missing worktrees fetch configured remotes and establish their initial target +with Git's linked-worktree operation. Creation holds the repository's ownership +lock through fetch, target selection, worktree creation, and lock setup. Existing +worktrees follow their configured `branch`, `tag`, `commit`, or native `rev`; +changing a tag or commit target moves the checkout to that resolved commit. +Branch updates are fast-forward only. A matching commit is not drift, even +when its branch or tag name differs. `detach: true` keeps a branch target +detached, and `remote` chooses the branch's fetch source. + +Each worktree accepts the same `sync` policies as {ref}`cli-sync`: +`drift: keep` leaves an existing checkout untouched; `drift: warn` also logs +when its resolved target differs. The default `dirty: abort` blocks updates +with local changes. `dirty: preserve` retains native recovery material and +restores changes, including the Git index. Conflicts retain their recovery +token and make the operation fail. + +`dirty: discard` requires explicit invocation consent, including clean or +missing checkouts: + +```console +$ vcspull worktree sync --yes '*' +``` + +For {ref}`cli-sync` with `--include-worktrees`, the same `--yes` authorizes +configured discard. Worktree consent is checked before the main checkout +changes. Main and linked checkouts are synchronized serially. + +Both commands print retained recovery identity after success or failure. +JSON and NDJSON include update/preservation states, ordered errors, +conflicts, and the exact token location required by libvcs recovery. Tokens +remain retained until explicitly released through libvcs; synchronization +does not automatically restore interrupted operations into their source. + +## Timeouts and interruption + +A requested worktree lock that fails reports an error even when the checkout +was created. Inspect `update_state` before retrying; failed creation can leave +refs or a partial checkout. + +Each worktree has its own deadline, including native creation and update. +Set it with `--timeout` or `VCSPULL_SYNC_TIMEOUT_SECONDS`; the default is +10 seconds: + +```console +$ vcspull worktree sync --timeout 60 '*' +``` + +Timeout or Ctrl-C stops the owned worker and its native process group before +the command continues or exits. A timeout skips the remaining worktrees for +that repository. Ctrl-C reports completed entries and retained recovery +material before exiting. An interrupted worker that did not report metadata +leaves `exists` and `is_dirty` unknown (`null` in JSON), not clean or missing. +See {ref}`cli-sync` for recovery inspection and process-group limits. ## Dry run -Preview what would happen without making changes: +Preview local target metadata without fetching or changing checkouts. An +unavailable target produces an error plan; execution may resolve it after +fetching: ```console $ vcspull worktree sync --dry-run '*' @@ -56,8 +106,51 @@ $ vcspull worktree sync 'django*' $ vcspull worktree sync --json '*' ``` +Each synchronized entry includes native position, update/preservation state, +recovery metadata, and ordered errors: + +```json +[ + { + "reason": "worktree", + "worktree_path": "~/code/myproject-dev", + "ref_type": "branch", + "ref_value": "develop", + "action": "update", + "exists": true, + "is_dirty": false, + "detail": "worktree updated", + "error": null, + "position": { + "revision": "1111111111111111111111111111111111111111", + "ref_name": "develop", + "ref_kind": "branch", + "follows": true, + "mixed": false, + "switched": false + }, + "target_position": { + "revision": "2222222222222222222222222222222222222222", + "ref_name": "develop", + "ref_kind": "branch", + "follows": true, + "mixed": false, + "switched": false + }, + "drifted": true, + "update_state": "completed", + "preservation_state": "not-needed", + "recovery": null, + "conflicts": [], + "errors": [] + } +] +``` + ## NDJSON output +Stream one JSON object per line as each worktree completes: + ```console $ vcspull worktree sync --ndjson '*' ``` diff --git a/src/vcspull/_internal/sync_process.py b/src/vcspull/_internal/sync_process.py index f0c12f5d5..07aa6c155 100644 --- a/src/vcspull/_internal/sync_process.py +++ b/src/vcspull/_internal/sync_process.py @@ -43,6 +43,8 @@ class SyncOutcome: Deserialized synchronization result from the worker, if reported. retained_recoveries : tuple[SyncResult, ...] Retained recovery records discovered by post-failure inspection. + worktree : dict[str, t.Any] | None + Serialized worktree plan entry returned by a ``"worktree"`` worker. """ status: t.Literal["synced", "failed", "timed_out"] @@ -51,6 +53,7 @@ class SyncOutcome: duration: float = 0.0 result: SyncResult | None = None retained_recoveries: tuple[SyncResult, ...] = () + worktree: dict[str, t.Any] | None = None class SyncInterrupted(KeyboardInterrupt): @@ -315,6 +318,7 @@ def run_sync_process( timeout: float, is_human: bool, yes: bool = False, + worktree: collections.abc.Mapping[str, t.Any] | None = None, ) -> SyncOutcome: """Run one owned mutation process; inspect retained records after a timeout.""" if os.name != "posix": @@ -322,7 +326,12 @@ def run_sync_process( raise RuntimeError(message) started = time.monotonic() exchange = _exchange( - {"repo": dict(repo), "yes": yes, "operation": "sync"}, + { + "repo": dict(repo), + "yes": yes, + "operation": "worktree" if worktree is not None else "sync", + "worktree": dict(worktree) if worktree is not None else None, + }, timeout=timeout, progress_callback=progress_callback, is_human=is_human, @@ -414,6 +423,7 @@ def run_sync_process( duration=time.monotonic() - started, result=result, retained_recoveries=retained, + worktree=terminal.get("worktree"), ) if interrupted: raise SyncInterrupted(outcome) @@ -448,6 +458,41 @@ def emit(self, record: logging.LogRecord) -> None: try: from vcspull.cli.sync import SyncFailedError, guess_vcs, update_repo + if request["operation"] == "worktree": + from vcspull._internal.worktree_sync import ( + WorktreeAction, + sync_worktree, + worktree_entry_data, + ) + + settings = request["worktree"] + entry = sync_worktree( + pathlib.Path(settings["repo_path"]), + settings["config"], + pathlib.Path(settings["workspace_root"]), + allow_discard=request["yes"], + repo_config=settings["repo_config"], + ) + worktree_result = ( + entry.result if entry.result is not None else SyncResult() + ) + if ( + entry.action in (WorktreeAction.ERROR, WorktreeAction.BLOCKED) + and worktree_result.ok + ): + worktree_result.add_error( + "worktree", entry.error or entry.detail or "worktree failed" + ) + send( + { + "event": "result", + "ok": worktree_result.ok, + "error": entry.error, + "result": _result_data(worktree_result), + "worktree": worktree_entry_data(entry), + } + ) + return if request["operation"] == "inspect": from vcspull._internal.sync import create_sync_project diff --git a/src/vcspull/_internal/worktree_sync.py b/src/vcspull/_internal/worktree_sync.py index 2c63a57fa..251e22b8a 100644 --- a/src/vcspull/_internal/worktree_sync.py +++ b/src/vcspull/_internal/worktree_sync.py @@ -2,13 +2,29 @@ from __future__ import annotations +import collections.abc import dataclasses import enum import logging import pathlib import subprocess +import typing as t + +from libvcs import ( + SyncPolicy, + SyncResult, + SyncTarget, + WorkingCopyPosition, + exc as vcs_exc, +) +from libvcs.sync.git import GitSync from vcspull import exc +from vcspull._internal.sync import ( + checkout_settings, + create_sync_project, + require_discard_authorization, +) from vcspull.types import WorktreeConfigDict from vcspull.validator import validate_working_copy @@ -22,91 +38,292 @@ class WorktreeAction(enum.Enum): """Worktree doesn't exist, will be created.""" UPDATE = "update" - """Branch worktree exists, will pull latest.""" + """Configured position or attachment requires an update.""" UNCHANGED = "unchanged" - """Tag/commit worktree exists, already at target.""" + """Checkout is kept by policy or already matches its target.""" BLOCKED = "blocked" - """Worktree has uncommitted changes (safety).""" + """Dirty policy prevents updating this checkout.""" ERROR = "error" """Operation failed (ref not found, permission, etc.).""" -@dataclasses.dataclass +@dataclasses.dataclass(slots=True) class WorktreeCheck: - """A single check performed during worktree planning.""" + """A single check performed during worktree planning. - name: str - """Check name: 'validate_config', 'ref_exists', 'worktree_exists', 'is_dirty'.""" + Attributes + ---------- + name : str + Check name (``'validate_config'``, ``'ref_exists'``, + ``'worktree_exists'``, or ``'is_dirty'``). + passed : bool + Whether the check passed. + detail : str + Human-readable description of the check result. + exception : exc.WorktreeError | None + Typed exception if the check failed. + """ + name: str passed: bool - """Whether the check passed.""" - detail: str - """Human-readable description of the check result.""" - exception: exc.WorktreeError | None = None - """Typed exception if the check failed.""" -@dataclasses.dataclass +@dataclasses.dataclass(slots=True) class WorktreePlanEntry: - """Planning information for a single worktree operation.""" + """Planning and execution record for a single worktree operation. - worktree_path: pathlib.Path - """Absolute path where the worktree will be/is located.""" + Attributes + ---------- + worktree_path : pathlib.Path + Absolute path where the worktree is or will be located. + ref_type : str + Configured selector kind (``'tag'``, ``'branch'``, ``'commit'``, or ``'rev'``). + ref_value : str + Configured tag name, branch name, commit SHA, or revision expression. + action : WorktreeAction + Planned or executed worktree action. + detail : str | None + Human-readable explanation of the action. + error : str | None + Error summary when ``action`` is ``ERROR``. + exists : bool | None + Whether the worktree existed before synchronization, or ``None`` if unknown. + is_dirty : bool | None + Whether the worktree had uncommitted changes, or ``None`` if unknown. + current_ref : str | None + Observed HEAD commit SHA when the worktree exists. + position : WorkingCopyPosition | None + Observed native position before synchronization. + target_position : WorkingCopyPosition | None + Configured target resolved from available native metadata. + drifted : bool | None + Whether observed and configured revisions differ, or ``None`` if unresolved. + result : SyncResult | None + Complete native synchronization outcome, including recovery metadata. + status : {"timed_out", "interrupted"} | None + Watchdog termination state when execution did not finish normally. + retained_recoveries : tuple[SyncResult, ...] + Retained recovery records discovered after worker termination. + checks : list[WorktreeCheck] + Ordered audit trail of checks recorded for the entry. + """ + worktree_path: pathlib.Path ref_type: str - """Type of reference: 'tag', 'branch', or 'commit'.""" - ref_value: str - """The actual tag name, branch name, or commit SHA.""" - action: WorktreeAction - """What action will be/was taken.""" - detail: str | None = None - """Human-readable explanation of the action.""" - error: str | None = None - """Error message if action is ERROR.""" - - exists: bool = False - """Whether the worktree currently exists.""" - - is_dirty: bool = False - """Whether the worktree has uncommitted changes.""" - + exists: bool | None = False + is_dirty: bool | None = False current_ref: str | None = None - """Current HEAD reference if worktree exists.""" - + position: WorkingCopyPosition | None = None + target_position: WorkingCopyPosition | None = None + drifted: bool | None = None + result: SyncResult | None = None + status: t.Literal["timed_out", "interrupted"] | None = None + retained_recoveries: tuple[SyncResult, ...] = () checks: list[WorktreeCheck] = dataclasses.field(default_factory=list) - """Ordered audit trail of checks performed during planning.""" -@dataclasses.dataclass +@dataclasses.dataclass(slots=True) class WorktreeSyncResult: - """Result of a worktree sync operation.""" + """Aggregated result of synchronizing a repository's worktrees. - entries: list[WorktreePlanEntry] = dataclasses.field(default_factory=list) - """List of worktree plan entries.""" + Attributes + ---------- + entries : list[WorktreePlanEntry] + Evaluated or executed worktree entries in configuration order. + created : int + Number of worktrees created (or planned for creation in dry-run). + updated : int + Number of worktrees updated. + unchanged : int + Number of worktrees left unchanged. + blocked : int + Number of worktrees blocked by dirty policy. + errors : int + Number of worktrees that encountered errors. + """ + entries: list[WorktreePlanEntry] = dataclasses.field(default_factory=list) created: int = 0 - """Number of worktrees created.""" - updated: int = 0 - """Number of worktrees updated.""" - unchanged: int = 0 - """Number of worktrees left unchanged.""" - blocked: int = 0 - """Number of worktrees blocked due to dirty state.""" - errors: int = 0 - """Number of worktrees that encountered errors.""" + + +class WorktreeInterrupted(KeyboardInterrupt): + """Carry completed and interrupted entries to the CLI before exiting.""" + + def __init__(self, result: WorktreeSyncResult) -> None: + self.result = result + super().__init__() + + +def worktree_entry_data(entry: WorktreePlanEntry) -> dict[str, t.Any]: + """Serialize operation metadata without native exception objects.""" + return { + "worktree_path": str(entry.worktree_path), + "ref_type": entry.ref_type, + "ref_value": entry.ref_value, + "action": entry.action.value, + "detail": entry.detail, + "error": entry.error, + "exists": entry.exists, + "is_dirty": entry.is_dirty, + "current_ref": entry.current_ref, + "position": dataclasses.asdict(entry.position) if entry.position else None, + "target_position": dataclasses.asdict(entry.target_position) + if entry.target_position + else None, + "drifted": entry.drifted, + "checks": [ + {"name": check.name, "passed": check.passed, "detail": check.detail} + for check in entry.checks + ], + } + + +def _worktree_entry_from_data( + data: collections.abc.Mapping[str, t.Any], + path: pathlib.Path, + ref_type: str, + ref_value: str, +) -> WorktreePlanEntry: + """Validate the worker's metadata before it can count as a completed action.""" + fields = dict(data) + expected = { + "worktree_path", + "ref_type", + "ref_value", + "action", + "detail", + "error", + "exists", + "is_dirty", + "current_ref", + "position", + "target_position", + "drifted", + "checks", + } + if fields.keys() != expected: + message = "unexpected worktree metadata fields" + raise ValueError(message) + for key in ("worktree_path", "ref_type", "ref_value"): + if not isinstance(fields[key], str): + raise TypeError(key) + if pathlib.Path(fields["worktree_path"]) != path: + message = "worker returned a different worktree path" + raise ValueError(message) + if (fields["ref_type"], fields["ref_value"]) != (ref_type, ref_value): + message = "worker returned a different worktree selector" + raise ValueError(message) + for key in ("detail", "error", "current_ref"): + if fields[key] is not None and not isinstance(fields[key], str): + raise TypeError(key) + for key in ("exists", "is_dirty", "drifted"): + if fields[key] is not None and type(fields[key]) is not bool: + raise TypeError(key) + fields["worktree_path"] = path + fields["action"] = WorktreeAction(fields["action"]) + for name in ("position", "target_position"): + position = fields[name] + if position is not None: + for key in ("revision", "ref_name", "ref_kind"): + if not isinstance(position[key], str): + message = f"{name}.{key}" + raise TypeError(message) + for key in ("follows", "mixed", "switched"): + if type(position[key]) is not bool: + message = f"{name}.{key}" + raise TypeError(message) + if position["ref_kind"] not in {"branch", "tag", "commit"}: + message = "invalid Git position kind" + raise ValueError(message) + fields[name] = WorkingCopyPosition(**position) + if not isinstance(fields["checks"], list): + message = "checks must be a list" + raise TypeError(message) + for check in fields["checks"]: + if ( + not isinstance(check, dict) + or check.keys() != {"name", "passed", "detail"} + or not isinstance(check["name"], str) + or type(check["passed"]) is not bool + or not isinstance(check["detail"], str) + ): + message = "invalid worktree check" + raise TypeError(message) + fields["checks"] = [WorktreeCheck(**check) for check in fields["checks"]] + return WorktreePlanEntry(**fields) + + +def _sync_worktree_process( + repo_path: pathlib.Path, + wt_config: WorktreeConfigDict, + workspace_root: pathlib.Path, + *, + allow_discard: bool, + repo_config: collections.abc.Mapping[str, t.Any] | None, + timeout: float, +) -> WorktreePlanEntry: + """Stop one owned worktree process before reporting results or recovery.""" + from vcspull._internal.sync_process import SyncInterrupted, run_sync_process + + path = _resolve_worktree_path(wt_config, workspace_root) + repo = {**(repo_config or {}), "path": path, "vcs": "git"} + repo.setdefault("url", str(repo_path)) + interrupted = False + try: + outcome = run_sync_process( + repo, + progress_callback=lambda *args: None, + timeout=timeout, + is_human=False, + yes=allow_discard, + worktree={ + "repo_path": repo_path, + "workspace_root": workspace_root, + "config": wt_config, + "repo_config": dict(repo_config) if repo_config is not None else None, + }, + ) + except SyncInterrupted as error: + interrupted = True + outcome = error.outcome + ref_type, ref_value = _get_ref_type_and_value(wt_config) or ("unknown", "unknown") + entry = WorktreePlanEntry( + path, ref_type, ref_value, WorktreeAction.ERROR, exists=None, is_dirty=None + ) + if outcome.worktree is not None: + try: + entry = _worktree_entry_from_data( + outcome.worktree, path, ref_type, ref_value + ) + except (TypeError, ValueError, KeyError) as error: + entry.error = f"invalid worktree result: {error}" + elif outcome.status == "synced": + entry.error = "worker did not report a complete worktree result" + entry.result = outcome.result + entry.retained_recoveries = outcome.retained_recoveries + if entry.error is not None and entry.result is not None and entry.result.ok: + entry.result.add_error("worker", entry.error) + if interrupted or outcome.status == "timed_out": + entry.status = "interrupted" if interrupted else "timed_out" + entry.action = WorktreeAction.ERROR + entry.error = "worktree interrupted" if interrupted else "worktree timed out" + elif outcome.status == "failed" and entry.action != WorktreeAction.BLOCKED: + entry.action = WorktreeAction.ERROR + entry.error = entry.error or str(outcome.error) + return entry def _get_ref_type_and_value( @@ -422,163 +639,160 @@ def _resolve_worktree_path( return (workspace_root / dir_path).resolve() +def _worktree_project( + repo_path: pathlib.Path, + worktree_path: pathlib.Path, + repo_config: collections.abc.Mapping[str, t.Any] | None, +) -> GitSync: + values = dict(repo_config or {"url": str(repo_path)}) + values["path"] = worktree_path + project = create_sync_project(values, vcs="git") + assert isinstance(project, GitSync) + return project + + +def require_worktree_authorization( + configs: list[WorktreeConfigDict], *, allow_discard: bool +) -> None: + """Reject unauthorized discard before any checkout in an operation mutates.""" + for config in configs: + _, policy = checkout_settings(config, worktree=True) + require_discard_authorization(policy, allow_discard=allow_discard) + + def plan_worktree_sync( repo_path: pathlib.Path, worktrees_config: list[WorktreeConfigDict], workspace_root: pathlib.Path, + *, + repo_config: collections.abc.Mapping[str, t.Any] | None = None, ) -> list[WorktreePlanEntry]: - """Plan worktree sync operations without executing them. + """Inspect local worktree targets and policy without fetching or changing refs. - Parameters - ---------- - repo_path : pathlib.Path - Path to the main repository. - worktrees_config : list[WorktreeConfigDict] - List of worktree configurations. - workspace_root : pathlib.Path - The workspace root directory for resolving relative paths. + Unavailable target metadata produces an error plan. Execution can resolve it + after an authorized fetch; planning never performs that fetch implicitly. - Returns - ------- - list[WorktreePlanEntry] - List of planned operations. - - Examples - -------- - >>> import pathlib >>> entries = plan_worktree_sync( ... pathlib.Path("/nonexistent/repo"), ... [{"dir": "../wt", "tag": "v1.0.0"}], ... pathlib.Path("/nonexistent"), ... ) - >>> len(entries) - 1 >>> entries[0].action == WorktreeAction.ERROR True """ - entries: list[WorktreePlanEntry] = [] - - for wt_config in worktrees_config: - try: - validate_worktree_config(wt_config) - except exc.WorktreeConfigError as e: - entries.append( - WorktreePlanEntry( - worktree_path=pathlib.Path(wt_config.get("dir", "unknown")), - ref_type="unknown", - ref_value="unknown", - action=WorktreeAction.ERROR, - error=str(e), - checks=[ - WorktreeCheck( - name="validate_config", - passed=False, - detail=str(e), - exception=e, - ), - ], - ) - ) - continue - - entry_checks: list[WorktreeCheck] = [ - WorktreeCheck(name="validate_config", passed=True, detail="config valid"), - ] - - ref_info = _get_ref_type_and_value(wt_config) - if ref_info is None: - log.warning( - "Worktree config passed validation but has no ref: %s", - wt_config, - ) - continue - ref_type, ref_value = ref_info - - worktree_path = _resolve_worktree_path(wt_config, workspace_root) - exists = _worktree_exists(repo_path, worktree_path) - + entries = [] + for config in worktrees_config: + ref_type, ref_value = _get_ref_type_and_value(config) or ("unknown", "unknown") entry = WorktreePlanEntry( - worktree_path=worktree_path, + worktree_path=pathlib.Path(config.get("dir", "unknown")), ref_type=ref_type, ref_value=ref_value, - action=WorktreeAction.CREATE, - exists=exists, + action=WorktreeAction.ERROR, ) - - # Check if ref exists - if not _ref_exists(repo_path, ref_value, ref_type): - ref_exc = exc.WorktreeRefNotFoundError(ref_value, ref_type, str(repo_path)) - entry_checks.append( + entries.append(entry) + try: + validate_worktree_config(config) + target, policy = checkout_settings(config, worktree=True) + entry.checks.append(WorktreeCheck("validate_config", True, "config valid")) + entry.worktree_path = _resolve_worktree_path(config, workspace_root) + entry.exists = _worktree_exists(repo_path, entry.worktree_path) + if entry.worktree_path.exists() and not entry.exists: + message = "destination is not a registered worktree" + raise exc.WorktreeConfigError(message) + project = _worktree_project( + repo_path, + entry.worktree_path if entry.exists else repo_path, + repo_config, + ) + try: + entry.target_position = project.resolve_target(target) + except (vcs_exc.LibVCSException, OSError, ValueError) as error: + ref_error = exc.WorktreeRefNotFoundError( + ref_value, ref_type, str(repo_path) + ) + entry.checks.append( + WorktreeCheck("ref_exists", False, str(error), ref_error) + ) + raise ref_error from error + entry.checks.append( + WorktreeCheck("ref_exists", True, "target resolved locally") + ) + entry.checks.append( WorktreeCheck( - name="ref_exists", - passed=False, - detail=str(ref_exc), - exception=ref_exc, + "worktree_exists", + True, + f"worktree {'exists' if entry.exists else 'not found'}" + f" at {entry.worktree_path}", ) ) - entry.action = WorktreeAction.ERROR - entry.error = str(ref_exc) - entry.checks = entry_checks - entries.append(entry) - continue - - entry_checks.append( - WorktreeCheck( - name="ref_exists", - passed=True, - detail=f"{ref_type.capitalize()} '{ref_value}' found", + if not entry.exists: + entry.action = WorktreeAction.CREATE + entry.detail = "will create configured worktree" + continue + entry.position = project.get_position() + entry.current_ref = entry.position.revision + entry.is_dirty = project.is_dirty() + entry.drifted = entry.position.revision != entry.target_position.revision + dirty_error = ( + exc.WorktreeDirtyError(str(entry.worktree_path)) + if entry.is_dirty + else None ) - ) - - entry_checks.append( - WorktreeCheck( - name="worktree_exists", - passed=True, - detail=f"worktree {'exists' if exists else 'not found'}" - f" at {worktree_path}", + blocked = ( + entry.is_dirty and policy.dirty == "abort" and policy.drift == "follow" ) - ) - - if not exists: - # Worktree doesn't exist, create it - entry.action = WorktreeAction.CREATE - entry.detail = f"will create {ref_type} worktree" - else: - # Worktree exists - entry.current_ref = _get_worktree_head(worktree_path) - entry.is_dirty = _is_worktree_dirty(worktree_path) - - if entry.is_dirty: - dirty_exc = exc.WorktreeDirtyError(str(worktree_path)) - entry_checks.append( - WorktreeCheck( - name="is_dirty", - passed=False, - detail=str(dirty_exc), - exception=dirty_exc, - ) + entry.checks.append( + WorktreeCheck( + "is_dirty", + not blocked, + str(dirty_error) if entry.is_dirty else "worktree is clean", + dirty_error if blocked else None, ) + ) + if policy.drift != "follow": + entry.action = WorktreeAction.UNCHANGED + entry.detail = "checkout kept by drift policy" + elif blocked: entry.action = WorktreeAction.BLOCKED - entry.detail = str(dirty_exc) + entry.detail = str(dirty_error) else: - entry_checks.append( + attach = entry.target_position.follows and not config.get( + "detach", False + ) + attachment_changed = ( + attach + and ( + not entry.position.follows + or entry.position.ref_name != entry.target_position.ref_name + ) + ) or (not attach and entry.position.follows) + entry.action = ( + WorktreeAction.UPDATE + if entry.drifted or attachment_changed + else WorktreeAction.UNCHANGED + ) + entry.detail = ( + "configured target differs" + if entry.action == WorktreeAction.UPDATE + else "already at configured target" + ) + except ( + exc.VCSPullException, + vcs_exc.LibVCSException, + OSError, + ValueError, + ) as error: + entry.action = WorktreeAction.ERROR + entry.error = str(error) + if not entry.checks: + entry.checks.append( WorktreeCheck( - name="is_dirty", - passed=True, - detail="worktree is clean", + "validate_config", + False, + str(error), + t.cast(exc.WorktreeError, error), ) ) - if ref_type == "branch": - entry.action = WorktreeAction.UPDATE - entry.detail = "branch worktree may be updated" - else: - # Tags and commits are immutable - entry.action = WorktreeAction.UNCHANGED - entry.detail = f"{ref_type} worktree already exists" - - entry.checks = entry_checks - entries.append(entry) - return entries @@ -588,199 +802,123 @@ def sync_worktree( workspace_root: pathlib.Path, *, dry_run: bool = False, + allow_discard: bool = False, + repo_config: collections.abc.Mapping[str, t.Any] | None = None, ) -> WorktreePlanEntry: - """Synchronize a single worktree. + """Synchronize a linked checkout and retain its complete native outcome. - Parameters - ---------- - repo_path : pathlib.Path - Path to the main repository. - wt_config : WorktreeConfigDict - Worktree configuration. - workspace_root : pathlib.Path - The workspace root directory. - dry_run : bool - If True, only plan without executing. + Discard requires explicit caller authorization, including clean and missing + worktrees. Missing paths use native worktree-add; they are never cloned. - Returns - ------- - WorktreePlanEntry - Result of the sync operation. - - Examples - -------- - >>> import pathlib >>> entry = sync_worktree( ... pathlib.Path("/nonexistent/repo"), ... {"dir": "../wt", "tag": "v1.0.0"}, - ... pathlib.Path("/nonexistent"), - ... dry_run=True, + ... pathlib.Path("/nonexistent"), dry_run=True, ... ) >>> entry.action == WorktreeAction.ERROR True """ - # Plan the operation - entries = plan_worktree_sync(repo_path, [wt_config], workspace_root) + if not dry_run: + require_worktree_authorization([wt_config], allow_discard=allow_discard) + entries = plan_worktree_sync( + repo_path, [wt_config], workspace_root, repo_config=repo_config + ) if not entries: - log.warning("plan_worktree_sync returned empty list for %s", wt_config) return WorktreePlanEntry( - worktree_path=_resolve_worktree_path(wt_config, workspace_root), - ref_type="unknown", - ref_value="unknown", - action=WorktreeAction.ERROR, + _resolve_worktree_path(wt_config, workspace_root), + "unknown", + "unknown", + WorktreeAction.ERROR, error="internal: planning produced no entries", ) entry = entries[0] - - if dry_run or entry.action in (WorktreeAction.ERROR, WorktreeAction.BLOCKED): + if dry_run: return entry - - ref_info = _get_ref_type_and_value(wt_config) - if ref_info is None: - return entry - ref_type, ref_value = ref_info - - worktree_path = entry.worktree_path - try: - if entry.action == WorktreeAction.CREATE: - _create_worktree( - repo_path, - worktree_path, - ref_type, - ref_value, - wt_config, + validate_worktree_config(wt_config) + target, policy = checkout_settings(wt_config, worktree=True) + assert target is not None + path = _resolve_worktree_path(wt_config, workspace_root) + exists = _worktree_exists(repo_path, path) + if path.exists() and not exists: + message = "destination is not a registered worktree" + raise exc.WorktreeConfigError(message) + project = _worktree_project( + repo_path, path if exists else repo_path, repo_config + ) + if not exists: + entry.result = project.create_worktree( + path, + target=target, + detach=wt_config.get("detach", False), + lock=wt_config.get("lock", False), + lock_reason=wt_config.get("lock_reason"), + set_remotes=repo_config is not None, ) - entry.detail = f"created {ref_type} worktree" - - elif entry.action == WorktreeAction.UPDATE: - _update_worktree(worktree_path, ref_value) - entry.detail = "branch worktree updated" - - elif entry.action == WorktreeAction.UNCHANGED: - entry.detail = f"{ref_type} worktree already exists" - - except subprocess.CalledProcessError as e: - entry.action = WorktreeAction.ERROR - entry.error = e.stderr.strip() if e.stderr else str(e) - except OSError as e: - entry.action = WorktreeAction.ERROR - entry.error = str(e) - - return entry - - -def _create_worktree( - repo_path: pathlib.Path, - worktree_path: pathlib.Path, - ref_type: str, - ref_value: str, - wt_config: WorktreeConfigDict, -) -> None: - """Create a new worktree. - - Parameters - ---------- - repo_path : pathlib.Path - Path to the main repository. - worktree_path : pathlib.Path - Path for the new worktree. - ref_type : str - Type of reference: 'tag', 'branch', or 'commit'. - ref_value : str - The reference value. - wt_config : WorktreeConfigDict - Full worktree configuration. - - Raises - ------ - subprocess.CalledProcessError - If the git command fails (e.g., ref not found). - FileNotFoundError - If the repository path does not exist. - - Examples - -------- - This function requires a valid git repository. When called with an invalid - path, it raises FileNotFoundError: - - >>> import pathlib - >>> _create_worktree( - ... pathlib.Path("/nonexistent"), - ... pathlib.Path("/tmp/wt"), - ... "tag", - ... "v1.0.0", - ... {"dir": "../wt", "tag": "v1.0.0"}, - ... ) # doctest: +ELLIPSIS - Traceback (most recent call last): - ... - FileNotFoundError: ... - """ - cmd = ["git", "worktree", "add"] - - # Determine if we should detach - detach = wt_config.get("detach") - if detach is None: - # Default: detach for tags and commits, not for branches - detach = ref_type in ("tag", "commit", "rev") - - if detach: - cmd.append("--detach") - - # Handle locking - # git worktree add --lock does NOT support --reason, so when lock_reason - # is specified, we skip --lock here and use "git worktree lock --reason" after - lock_reason = wt_config.get("lock_reason") - should_lock = wt_config.get("lock") - if should_lock and not lock_reason: - # Lock without reason - can use --lock flag directly - cmd.append("--lock") - - cmd.append(str(worktree_path)) - cmd.append(ref_value) - - subprocess.run( - cmd, - cwd=repo_path, - check=True, - capture_output=True, - text=True, - ) - - # Apply lock with reason via separate command - # This handles both cases: - # 1. lock=True with lock_reason - lock with reason - # 2. lock_reason without explicit lock=True - also locks with reason - if lock_reason: - lock_cmd = [ - "git", - "worktree", - "lock", - "--reason", - lock_reason, - str(worktree_path), - ] - try: - subprocess.run( - lock_cmd, - cwd=repo_path, - check=True, - capture_output=True, - text=True, + else: + entry.result = project.update_repo( + set_remotes=repo_config is not None, + target=target, + policy=policy, + detach=wt_config.get("detach", False), ) - except subprocess.CalledProcessError as e: - log.warning( - "Worktree created at %s but lock failed: %s", - worktree_path, - e.stderr.strip() if e.stderr else str(e), + result = entry.result + if not result.ok: + entry.action = ( + WorktreeAction.BLOCKED + if any(error.step == "dirty" for error in result.errors) + else WorktreeAction.ERROR + ) + entry.error = "; ".join( + f"{error.step}: {error.message}" for error in result.errors + ) + entry.detail = entry.error + else: + entry.checks = [ + WorktreeCheck("ref_exists", True, "target resolved during sync") + if check.name == "ref_exists" and not check.passed + else check + for check in entry.checks + ] + entry.target_position = ( + project.resolve_target(target) + if exists + else _worktree_project(repo_path, path, repo_config).get_position() + ) + if entry.position is not None: + entry.drifted = ( + entry.position.revision != entry.target_position.revision + ) + entry.error = None + entry.action = ( + WorktreeAction.CREATE + if not exists + else WorktreeAction.UPDATE + if result.update_state == "completed" + else WorktreeAction.UNCHANGED ) + entry.detail = { + WorktreeAction.CREATE: "created configured worktree", + WorktreeAction.UPDATE: "worktree updated", + WorktreeAction.UNCHANGED: "checkout kept or target already matched", + }[entry.action] + except ( + exc.VCSPullException, + vcs_exc.LibVCSException, + OSError, + ValueError, + subprocess.CalledProcessError, + ) as error: + entry.action = WorktreeAction.ERROR + entry.error = str(error) + if entry.result is None: + entry.result = SyncResult() + entry.result.add_error("worktree", str(error), error) + return entry def _update_worktree(worktree_path: pathlib.Path, branch: str) -> None: - """Update a branch worktree by pulling latest changes. - - Verifies the worktree is on the expected branch before pulling. - If the worktree is on a different branch, checks out the expected branch first. + """Follow a branch with native fast-forward and dirty-abort safeguards. Parameters ---------- @@ -791,8 +929,8 @@ def _update_worktree(worktree_path: pathlib.Path, branch: str) -> None: Raises ------ - subprocess.CalledProcessError - If the git command fails. + WorktreeError + If native synchronization fails. FileNotFoundError If the worktree path does not exist. @@ -807,56 +945,12 @@ def _update_worktree(worktree_path: pathlib.Path, branch: str) -> None: ... FileNotFoundError: ... """ - # Get current branch name - result = subprocess.run( - ["git", "symbolic-ref", "--short", "HEAD"], - cwd=worktree_path, - capture_output=True, - text=True, - check=False, - ) - - current_branch = result.stdout.strip() if result.returncode == 0 else None - - # Checkout expected branch if detached or on a different branch - if current_branch is None or current_branch != branch: - log.debug( - "Worktree %s is on branch %s, checking out %s", - worktree_path, - current_branch, - branch, - ) - subprocess.run( - ["git", "checkout", branch], - cwd=worktree_path, - check=True, - capture_output=True, - text=True, - ) - - # Check if the branch has an upstream tracking ref before pulling - upstream_check = subprocess.run( - ["git", "config", f"branch.{branch}.remote"], - cwd=worktree_path, - capture_output=True, - text=True, - check=False, - ) - if upstream_check.returncode != 0 or not upstream_check.stdout.strip(): - log.debug( - "Worktree %s branch %s has no upstream tracking, skipping pull", - worktree_path, - branch, - ) - return - - subprocess.run( - ["git", "pull", "--ff-only"], - cwd=worktree_path, - check=True, - capture_output=True, - text=True, - ) + if not worktree_path.exists(): + raise FileNotFoundError(str(worktree_path)) + project = _worktree_project(worktree_path, worktree_path, None) + result = project.update_repo(target=SyncTarget(branch=branch), policy=SyncPolicy()) + if not result.ok: + raise exc.WorktreeError("; ".join(error.message for error in result.errors)) def sync_all_worktrees( @@ -865,6 +959,9 @@ def sync_all_worktrees( workspace_root: pathlib.Path, *, dry_run: bool = False, + allow_discard: bool = False, + repo_config: collections.abc.Mapping[str, t.Any] | None = None, + timeout: float | None = None, ) -> WorktreeSyncResult: """Synchronize all worktrees for a repository. @@ -898,15 +995,29 @@ def sync_all_worktrees( >>> len(result.entries) 1 """ + if not dry_run: + require_worktree_authorization(worktrees_config, allow_discard=allow_discard) result = WorktreeSyncResult() for wt_config in worktrees_config: - entry = sync_worktree( - repo_path, - wt_config, - workspace_root, - dry_run=dry_run, - ) + if timeout is not None and not dry_run: + entry = _sync_worktree_process( + repo_path, + wt_config, + workspace_root, + allow_discard=allow_discard, + repo_config=repo_config, + timeout=timeout, + ) + else: + entry = sync_worktree( + repo_path, + wt_config, + workspace_root, + dry_run=dry_run, + allow_discard=allow_discard, + repo_config=repo_config, + ) result.entries.append(entry) if entry.action == WorktreeAction.CREATE: @@ -919,6 +1030,10 @@ def sync_all_worktrees( result.blocked += 1 elif entry.action == WorktreeAction.ERROR: result.errors += 1 + if entry.status == "interrupted": + raise WorktreeInterrupted(result) + if entry.status == "timed_out": + break return result diff --git a/src/vcspull/cli/sync.py b/src/vcspull/cli/sync.py index f99ac72ea..ab286e352 100644 --- a/src/vcspull/cli/sync.py +++ b/src/vcspull/cli/sync.py @@ -38,8 +38,9 @@ run_sync_process, ) from vcspull._internal.worktree_sync import ( - WorktreeAction, + WorktreeInterrupted, plan_worktree_sync, + require_worktree_authorization, sync_all_worktrees, ) from vcspull.config import ( @@ -67,6 +68,7 @@ from ._progress import SyncStatusIndicator, build_indicator from ._workspaces import filter_by_workspace from .status import check_repo_status +from .worktree import _emit_worktree_entry log = logging.getLogger(__name__) @@ -1577,35 +1579,16 @@ def _sync_impl( if not worktrees_config: continue - repo_name = str(repo.get("name", "unknown")) repo_path = _get_repo_path(repo) workspace_label = str(repo.get("workspace_root", "")) workspace_path = expand_dir(pathlib.Path(workspace_label)) wt_entries = plan_worktree_sync( - repo_path, worktrees_config, workspace_path + repo_path, worktrees_config, workspace_path, repo_config=repo ) for entry in wt_entries: - ref_display = f"{entry.ref_type}:{entry.ref_value}" - wt_path_display = str(PrivatePath(entry.worktree_path)) - - action_symbols = { - WorktreeAction.CREATE: colors.success("+"), - WorktreeAction.UPDATE: colors.warning("~"), - WorktreeAction.UNCHANGED: colors.muted("✓"), - WorktreeAction.BLOCKED: colors.warning("⚠"), - WorktreeAction.ERROR: colors.error("✗"), - } - sym = action_symbols.get(entry.action, "?") - ref = colors.info(ref_display) - detail = entry.detail or entry.error or "" - - formatter.emit_text( - f" {sym} worktree {colors.info(repo_name)} " - f"{ref} {colors.muted('→')} {wt_path_display}" - f" {colors.muted(detail)}".rstrip(), - ) + _emit_worktree_entry(entry, formatter, colors) formatter.finalize() return @@ -1802,6 +1785,10 @@ def _run_sync_loop( # flicker reporters have called out. indicator.start_repo(repo_name) try: + if include_worktrees: + require_worktree_authorization( + repo.get("worktrees") or [], allow_discard=yes + ) outcome = _sync_repo_with_watchdog( repo, progress_callback=progress_callback, @@ -1821,6 +1808,8 @@ def _run_sync_loop( formatter.emit(event) _emit_recoveries(formatter, error.outcome) raise + except exc.VCSPullException as error: + outcome = _SyncOutcome(status="failed", error=error) except BaseException: # Any exception (KeyboardInterrupt, runtime crash) tears the # indicator down with no replacement line; the surrounding @@ -1944,42 +1933,22 @@ def _run_sync_loop( workspace_path = expand_dir(pathlib.Path(str(workspace_label))) repo_path_obj = pathlib.Path(str(repo_path)) - wt_result = sync_all_worktrees( - repo_path_obj, - worktrees_config, - workspace_path, - dry_run=dry_run, - ) - + interrupted = False + try: + wt_result = sync_all_worktrees( + repo_path_obj, + worktrees_config, + workspace_path, + dry_run=dry_run, + allow_discard=yes, + repo_config=repo, + timeout=repo_timeout, + ) + except WorktreeInterrupted as error: + wt_result = error.result + interrupted = True for entry in wt_result.entries: - ref_display = f"{entry.ref_type}:{entry.ref_value}" - wt_path_display = str(PrivatePath(entry.worktree_path)) - - if entry.action == WorktreeAction.CREATE: - sym = colors.success("+") - ref = colors.info(ref_display) - arrow = colors.muted("→") - formatter.emit_text( - f" {sym} worktree {ref} {arrow} {wt_path_display}", - ) - elif entry.action == WorktreeAction.UPDATE: - sym = colors.warning("~") - ref = colors.info(ref_display) - arrow = colors.muted("→") - formatter.emit_text( - f" {sym} worktree {ref} {arrow} {wt_path_display}", - ) - elif entry.action == WorktreeAction.BLOCKED: - sym = colors.warning("⚠") - ref = colors.info(ref_display) - formatter.emit_text( - f" {sym} worktree {ref} blocked: {entry.detail}", - ) - elif entry.action == WorktreeAction.ERROR: - formatter.emit_text( - f" {colors.error('✗')} worktree {colors.info(ref_display)} " - f"error: {entry.error}", - ) + _emit_worktree_entry(entry, formatter, colors) # Tally worktree results into summary summary["worktree_created"] = ( @@ -1989,12 +1958,16 @@ def _run_sync_loop( summary.get("worktree_updated", 0) + wt_result.updated ) summary["worktree_failed"] = ( - summary.get("worktree_failed", 0) + wt_result.errors + summary.get("worktree_failed", 0) + wt_result.errors + wt_result.blocked ) # Count worktree errors as failures for exit code - summary["failed"] += wt_result.errors + summary["failed"] += wt_result.errors + wt_result.blocked + + if interrupted: + summary["interrupted"] = summary.get("interrupted", 0) + 1 + raise KeyboardInterrupt - if exit_on_error and wt_result.errors > 0: + if exit_on_error and (wt_result.errors or wt_result.blocked): _emit_summary(formatter, colors, summary) formatter.finalize() if parser is not None: diff --git a/src/vcspull/cli/worktree.py b/src/vcspull/cli/worktree.py index e8571011e..5492a815f 100644 --- a/src/vcspull/cli/worktree.py +++ b/src/vcspull/cli/worktree.py @@ -3,12 +3,17 @@ from __future__ import annotations import argparse +import dataclasses import pathlib +import sys import typing as t +from vcspull import exc from vcspull._internal.private_path import PrivatePath +from vcspull._internal.sync import format_recovery_lines, sync_result_data from vcspull._internal.worktree_sync import ( WorktreeAction, + WorktreeInterrupted, WorktreePlanEntry, list_existing_worktrees, plan_worktree_sync, @@ -42,6 +47,8 @@ def create_worktree_subparser(parser: argparse.ArgumentParser) -> None: parser : argparse.ArgumentParser The parser to configure """ + from .sync import _DEFAULT_REPO_TIMEOUT_SECONDS, _positive_int_arg + subparsers = parser.add_subparsers(dest="worktree_action") # List subcommand @@ -57,6 +64,16 @@ def create_worktree_subparser(parser: argparse.ArgumentParser) -> None: help="create or update worktrees", ) _add_common_args(sync_parser) + sync_parser.add_argument( + "--timeout", + type=_positive_int_arg, + default=None, + metavar="SECONDS", + help=( + "per-worktree deadline (default: VCSPULL_SYNC_TIMEOUT_SECONDS or " + f"{_DEFAULT_REPO_TIMEOUT_SECONDS})" + ), + ) sync_parser.add_argument( "--dry-run", "-n", @@ -64,6 +81,12 @@ def create_worktree_subparser(parser: argparse.ArgumentParser) -> None: help="preview what would be synced without making changes", ) + sync_parser.add_argument( + "--yes", + action="store_true", + help="authorize configured dirty: discard policies", + ) + # Prune subcommand prune_parser = subparsers.add_parser( "prune", @@ -175,15 +198,26 @@ def handle_worktree_command(args: argparse.Namespace) -> None: formatter = OutputFormatter(output_mode) colors = Colors(get_color_mode(args.color)) + succeeded = True if args.worktree_action == "list": _handle_list(repos_with_worktrees, formatter, colors) elif args.worktree_action == "sync": - _handle_sync( - repos_with_worktrees, - formatter, - colors, - dry_run=args.dry_run, - ) + from .sync import _exit_on_sigint, _resolve_repo_timeout + + try: + succeeded = _handle_sync( + repos_with_worktrees, + formatter, + colors, + dry_run=args.dry_run, + allow_discard=args.yes, + timeout=_resolve_repo_timeout(getattr(args, "timeout", None)), + ) + except KeyboardInterrupt: + formatter.finalize() + sys.stderr.write("Interrupted by user.\n") + sys.stderr.flush() + _exit_on_sigint() elif args.worktree_action == "prune": # Use found_repos (not repos_with_worktrees) so repos whose worktree # config was removed can still have orphaned worktrees pruned. @@ -195,6 +229,8 @@ def handle_worktree_command(args: argparse.Namespace) -> None: ) formatter.finalize() + if not succeeded: + raise SystemExit(1) def _handle_list( @@ -233,7 +269,9 @@ def _handle_list( continue workspace_path = expand_dir(pathlib.Path(workspace_root)) - entries = plan_worktree_sync(repo_path, worktrees_config, workspace_path) + entries = plan_worktree_sync( + repo_path, worktrees_config, workspace_path, repo_config=repo + ) # Human output: repo header formatter.emit_text( @@ -275,11 +313,14 @@ def _emit_worktree_entry( color_fn = colors.error ref_display = f"{entry.ref_type}:{entry.ref_value}" - status = "exists" if entry.exists else "missing" + status = ( + "unknown" if entry.exists is None else "exists" if entry.exists else "missing" + ) # JSON output formatter.emit( { + "reason": "worktree", "worktree_path": str(PrivatePath(entry.worktree_path)), "ref_type": entry.ref_type, "ref_value": entry.ref_value, @@ -288,6 +329,22 @@ def _emit_worktree_entry( "is_dirty": entry.is_dirty, "detail": entry.detail, "error": entry.error, + "position": dataclasses.asdict(entry.position) if entry.position else None, + "target_position": dataclasses.asdict(entry.target_position) + if entry.target_position + else None, + "drifted": entry.drifted, + **({"status": entry.status} if entry.status is not None else {}), + **( + { + "retained_recoveries": [ + sync_result_data(result) for result in entry.retained_recoveries + ] + } + if entry.retained_recoveries + else {} + ), + **(sync_result_data(entry.result) if entry.result is not None else {}), } ) @@ -299,6 +356,9 @@ def _emit_worktree_entry( f"({color_fn(detail_text)})" ) + for line in format_recovery_lines(entry.result, entry.retained_recoveries): + formatter.emit_text(line) + def _handle_sync( repos: list[ConfigDict], @@ -306,7 +366,9 @@ def _handle_sync( colors: Colors, *, dry_run: bool = False, -) -> None: + allow_discard: bool = False, + timeout: float | None = None, +) -> bool: """Handle the worktree sync subcommand. Parameters @@ -328,7 +390,7 @@ def _handle_sync( formatter.emit_text( colors.warning("No repositories with worktrees configured.") ) - return + return True total_created = 0 total_updated = 0 @@ -351,12 +413,32 @@ def _handle_sync( f"\n{colors.highlight(repo_name)} ({PrivatePath(repo_path)})" ) - result = sync_all_worktrees( - repo_path, - worktrees_config, - workspace_path, - dry_run=dry_run, - ) + interrupted = False + try: + result = sync_all_worktrees( + repo_path, + worktrees_config, + workspace_path, + dry_run=dry_run, + allow_discard=allow_discard, + repo_config=repo, + timeout=timeout, + ) + except WorktreeInterrupted as error: + result = error.result + interrupted = True + except exc.VCSPullException as error: + total_errors += 1 + formatter.emit( + { + "reason": "worktree", + "status": "error", + "name": repo_name, + "error": str(error), + } + ) + formatter.emit_text(colors.error(str(error))) + continue for entry in result.entries: _emit_worktree_entry(entry, formatter, colors) @@ -366,6 +448,8 @@ def _handle_sync( total_unchanged += result.unchanged total_blocked += result.blocked total_errors += result.errors + if interrupted: + raise KeyboardInterrupt # Summary action_word = "Would sync" if dry_run else "Synced" @@ -383,6 +467,8 @@ def _handle_sync( colors.muted("Tip: run without --dry-run to apply changes.") ) + return True if dry_run else not (total_blocked or total_errors) + def _handle_prune( repos: list[ConfigDict], diff --git a/tests/cli/test_sync_sigint.py b/tests/cli/test_sync_sigint.py index a7095094d..987692117 100644 --- a/tests/cli/test_sync_sigint.py +++ b/tests/cli/test_sync_sigint.py @@ -21,11 +21,40 @@ @pytest.mark.skipif(os.name != "posix", reason="POSIX process-group supervision") -def test_sync_interrupt_stops_worker(git_repo: GitSync, tmp_path: pathlib.Path) -> None: +@pytest.mark.parametrize("mode", ["main", "included", "worktree"]) +def test_sync_interrupt_stops_worker( + git_repo: GitSync, tmp_path: pathlib.Path, mode: str +) -> None: """SIGINT stops an active native checkout and reports retained changes.""" git_repo.run(["tag", "before-update"]) git_repo.run(["commit", "--allow-empty", "-m", "advance"]) - (git_repo.path / "local.txt").write_text("retain this\n") + from libvcs import GitSync + + checkout = git_repo + entry: dict[str, t.Any] = { + "repo": f"git+{git_repo.url}", + "working_copy": { + "tag": "before-update", + "sync": {"dirty": "preserve"}, + }, + } + arguments = ["sync", "--all", "--no-log-file", "--timeout", "30"] + if mode != "main": + path = tmp_path / "linked" + git_repo.run(["worktree", "add", "--detach", str(path), "HEAD"]) + checkout = GitSync(url=git_repo.url, path=path) + entry["working_copy"] = { + "commit": git_repo.get_revision(), + "sync": {"drift": "keep"}, + } + entry["worktrees"] = [ + {"dir": str(path), "tag": "before-update", "sync": {"dirty": "preserve"}} + ] + if mode == "included": + arguments.append("--include-worktrees") + else: + arguments = ["worktree", "sync"] + (checkout.path / "local.txt").write_text("retain this\n") address = str(tmp_path / "s") helper = tmp_path / "hook.py" helper.write_text( @@ -42,19 +71,7 @@ def test_sync_interrupt_stops_worker(git_repo: GitSync, tmp_path: pathlib.Path) hook.chmod(0o700) config = tmp_path / "repos.json" config.write_text( - json.dumps( - { - str(git_repo.path.parent): { - git_repo.path.name: { - "repo": f"git+{git_repo.url}", - "working_copy": { - "tag": "before-update", - "sync": {"dirty": "preserve"}, - }, - } - } - } - ) + json.dumps({str(git_repo.path.parent): {git_repo.path.name: entry}}) ) spec = importlib.util.find_spec("vcspull") assert spec is not None and spec.origin is not None @@ -68,14 +85,10 @@ def test_sync_interrupt_stops_worker(git_repo: GitSync, tmp_path: pathlib.Path) sys.executable, "-c", "from vcspull.cli import cli; cli()", - "sync", + *arguments, "--file", str(config), - "--all", "--ndjson", - "--no-log-file", - "--timeout", - "30", ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, @@ -93,13 +106,18 @@ def test_sync_interrupt_stops_worker(git_repo: GitSync, tmp_path: pathlib.Path) process.send_signal(signal.SIGINT) output, error = process.communicate(timeout=3) assert process.returncode == -signal.SIGINT, (output, error) + if mode == "worktree": + assert b"Interrupted by user." in error assert connection.recv(1) == b"" events = [json.loads(line) for line in output.splitlines()] event = next(item for item in events if item.get("status") == "interrupted") assert event["update_state"] == "unknown" + if mode != "main": + assert event["exists"] is None + assert event["is_dirty"] is None retained = event["retained_recoveries"] assert len(retained) == 1 - discovered = git_repo.list_recoveries() + discovered = checkout.list_recoveries() assert discovered[0].recovery is not None assert retained[0]["recovery"]["id"] == discovered[0].recovery.id finally: @@ -116,31 +134,9 @@ def test_sync_interrupt_stops_worker(git_repo: GitSync, tmp_path: pathlib.Path) reason="POSIX signal semantics only; Windows uses exit-code 130", ) def test_exit_on_sigint_produces_wifsignaled_sigint() -> None: - """``_exit_on_sigint`` makes the process terminate via ``WIFSIGNALED(SIGINT)``. - - Bash's ``cmd1; cmd2`` sequential-list abort only kicks in when the - child was killed by a signal -- a clean ``SystemExit(130)`` leaves - the shell no reason to stop and the chain keeps running. This - assertion locks in the actual kernel signal bit, not just the exit - code. - - Why a subprocess: the production helper ends with - ``signal.raise_signal(SIGINT)`` under ``SIG_DFL``, which would take - the pytest runner down with us if we called it in-process. The only - reliable observation point is ``subprocess.Popen.returncode``, - which CPython stores as the *negative* of the terminating signal - number when ``os.waitstatus_to_exitcode`` reports ``WIFSIGNALED``. + """The exit helper preserves POSIX signal termination for shell command lists. - Scope: we target ``_exit_on_sigint`` directly in a fresh interpreter - rather than driving ``vcspull sync`` end-to-end, because getting the - sync loop into a deterministic mid-flight state where SIGINT lands - on the watchdog's ``done.wait(...)`` requires either a blocking fake - remote or a monkey-patched ``update_repo`` -- both reintroduce - flake and add nothing over the existing in-process control-flow - tests in ``test_sync_watchdog.py`` (which use the - ``_fake_sigint_escalation`` fixture). The one thing those tests - can't show is that the kernel actually marks the exit as - WIFSIGNALED(SIGINT); that's what this subprocess proves. + Run it in a child interpreter so the real signal cannot kill pytest. """ # Simulate Ctrl-C in a fresh interpreter, then route it through the # real helper. We install ``default_int_handler`` explicitly because diff --git a/tests/cli/test_sync_watchdog.py b/tests/cli/test_sync_watchdog.py index c04cbd9a9..48674e1e2 100644 --- a/tests/cli/test_sync_watchdog.py +++ b/tests/cli/test_sync_watchdog.py @@ -354,6 +354,133 @@ def test_watchdog_propagates_interrupt_during_inspection( ) +def test_worktree_timeout_retains_token_and_stops_same_repository( + worker_command: t.Any, monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path +) -> None: + """A stopped worktree retains inspection results and prevents sibling writes.""" + from libvcs import RecoveryToken, SyncResult + + from vcspull._internal.worktree_sync import sync_all_worktrees + + retained = SyncResult( + recovery=RecoveryToken("worktree-token", "git", str(tmp_path / "retained")) + ) + worker_command(""" +send({'event': 'progress', 'text': 'ready', + 'time': datetime.datetime.now().isoformat()}) +signal.pause() +""") + clock = time.monotonic + offset = 0.0 + monkeypatch.setattr( + sync_process, "time", types.SimpleNamespace(monotonic=lambda: clock() + offset) + ) + + def ready(*args: t.Any) -> None: + nonlocal offset + offset += 100 + + exchange = sync_process._exchange + + def with_ready(request: dict[str, t.Any], **kwargs: t.Any) -> t.Any: + if request["operation"] == "worktree": + kwargs["progress_callback"] = ready + return exchange(request, **kwargs) + + # Advance the deadline only after the fresh worker reports its readiness. + monkeypatch.setattr(sync_process, "_exchange", with_ready) + result = sync_all_worktrees( + tmp_path, + [{"dir": "one", "commit": "HEAD"}, {"dir": "two", "commit": "HEAD"}], + tmp_path, + repo_config={"retained": [sync_process._result_data(retained)]}, + timeout=5, + ) + assert result.errors == 1 + assert len(result.entries) == 1 + entry = result.entries[0] + assert entry.status == "timed_out" + assert entry.result is not None and entry.result.update_state == "unknown" + assert entry.retained_recoveries == (retained,) + + +@pytest.mark.parametrize( + "invalid", ["exists", "ref_value", "path", "position", "check", "selector"] +) +def test_worktree_rejects_malformed_metadata_with_known_token( + monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path, invalid: str +) -> None: + """Malformed worker metadata cannot count a checkout as successfully created.""" + from libvcs import RecoveryToken, SyncResult + + from vcspull._internal.worktree_sync import ( + WorktreeAction, + WorktreePlanEntry, + sync_all_worktrees, + worktree_entry_data, + ) + + token = RecoveryToken("known-token", "git", str(tmp_path / "retained")) + native = SyncResult(recovery=token, update_state="completed") + data = worktree_entry_data( + WorktreePlanEntry(tmp_path / "linked", "commit", "HEAD", WorktreeAction.CREATE) + ) + if invalid == "exists": + data["exists"] = "not-a-bool" + elif invalid == "ref_value": + data["ref_value"] = {"not": "scalar"} + elif invalid == "path": + data["worktree_path"] = str(tmp_path / "different") + elif invalid == "selector": + data["ref_type"] = "tag" + data["ref_value"] = "wrong-target" + elif invalid == "position": + data["position"] = { + "revision": "abc", + "ref_name": "main", + "ref_kind": "branch", + "follows": "false", + "mixed": False, + "switched": False, + } + else: + data["checks"] = [{"name": "native", "passed": "yes", "detail": "done"}] + # Framing is tested separately; inject the decoded worker's scalar payload. + monkeypatch.setattr( + sync_process, + "run_sync_process", + lambda *args, **kwargs: sync_process.SyncOutcome( + "synced", result=native, worktree=data + ), + ) + result = sync_all_worktrees( + tmp_path, [{"dir": "linked", "commit": "HEAD"}], tmp_path, timeout=1 + ) + assert result.created == 0 and result.errors == 1 + entry = result.entries[0] + assert entry.error is not None and "invalid worktree result" in entry.error + assert entry.result is not None and entry.result.recovery == token + + +def test_worktree_timeout_option_preserves_unconfigured_remotes( + git_repo: GitSync, tmp_path: pathlib.Path +) -> None: + """Adding process supervision cannot manufacture authoritative remote settings.""" + from vcspull._internal.worktree_sync import sync_all_worktrees + + path = tmp_path / "linked" + git_repo.run(["worktree", "add", "--detach", str(path), "HEAD"]) + original_url = git_repo.run(["remote", "get-url", "origin"]) + result = sync_all_worktrees( + git_repo.path, + [{"dir": str(path), "commit": git_repo.get_revision()}], + tmp_path, + timeout=5, + ) + assert result.errors == 0, result.entries + assert git_repo.run(["remote", "get-url", "origin"]) == original_url + + def test_recovery_inspection_finds_svn_after_source_loss(svn_repo: SvnSync) -> None: """The subprocess inspector retains SVN's source-independent recovery scope.""" import shutil diff --git a/tests/test_worktree.py b/tests/test_worktree.py index e7751c9f8..c1dd6fcc2 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -618,7 +618,7 @@ class WorktreeCheckTrailFixture(t.NamedTuple): setup="create_existing_branch_worktree", ref_key="branch", ref_value="trail-update-branch", - expected_action=WorktreeAction.UPDATE, + expected_action=WorktreeAction.UNCHANGED, expected_check_count=4, expected_check_names=[ "validate_config", @@ -1450,7 +1450,7 @@ def test_sync_worktree_branch_update( entries = plan_worktree_sync(git_repo.path, [wt_config], workspace_root) assert len(entries) == 1 - assert entries[0].action == WorktreeAction.UPDATE + assert entries[0].action == WorktreeAction.UNCHANGED assert entries[0].exists is True @@ -1493,9 +1493,9 @@ def test_sync_worktree_executes_update_no_upstream( entry = sync_worktree(git_repo.path, wt_config, workspace_root, dry_run=False) # UPDATE succeeds because pull is skipped when there's no upstream - assert entry.action == WorktreeAction.UPDATE + assert entry.action == WorktreeAction.UNCHANGED assert entry.exists is True - assert "updated" in (entry.detail or "").lower() + assert entry.result is not None and entry.result.ok def test_sync_all_worktrees_counts_mixed( @@ -1587,8 +1587,8 @@ def test_sync_all_worktrees_counts_mixed( # Verify counts (all branches through lines 713-722) assert sync_result.created == 1 - assert sync_result.updated == 1 - assert sync_result.unchanged == 1 + assert sync_result.updated == 0 + assert sync_result.unchanged == 2 assert sync_result.blocked == 1 assert sync_result.errors == 1 assert len(sync_result.entries) == 5 @@ -2885,7 +2885,7 @@ def test_sync_worktree_unchanged_execution( # Verify the UNCHANGED path was executed (lines 549-552) assert entry.action == WorktreeAction.UNCHANGED assert entry.exists is True - assert "already exists" in (entry.detail or "") + assert entry.result is not None and entry.result.update_state == "not-started" # --------------------------------------------------------------------------- @@ -2915,9 +2915,9 @@ def test_sync_worktree_oserror_exception( wt_config: WorktreeConfigDict = {"dir": str(worktree_path), "tag": "v-oserror-test"} - # Mock _create_worktree to raise OSError + # Fail the native creation boundary to verify CLI error conversion. mocker.patch( - "vcspull._internal.worktree_sync._create_worktree", + "libvcs.sync.git.GitSync.create_worktree", side_effect=OSError("Mocked OSError: permission denied"), ) @@ -3357,50 +3357,76 @@ def test_sync_exit_on_error_worktree_failures( ) -def test_sync_worktree_lock_failure_still_creates( +def test_sync_worktree_lock_failure_reports_partial_creation( git_repo: GitSync, tmp_path: pathlib.Path, - mocker: MockerFixture, + monkeypatch: pytest.MonkeyPatch, ) -> None: - """Test worktree creation succeeds even if lock fails. + """A failed requested lock retains the completed creation and reports failure.""" + from libvcs.cmd.git import Git - Regression test: lock failure after successful creation marked the entire - operation as ERROR. Lock is non-critical — the worktree is still usable. - """ - workspace_root = git_repo.path.parent - worktree_path = workspace_root / "lock-fail-test-wt" + path = tmp_path / "lock-failed" + original_run = Git.run - # Create a tag - subprocess.run( - ["git", "tag", "v-lock-fail-test"], - cwd=git_repo.path, - check=True, - capture_output=True, - ) + def fail_lock(command: Git, args: list[str], **kwargs: t.Any) -> str: + if args[:2] == ["worktree", "lock"]: + message = "worktree lock failed" + raise OSError(message) + return original_run(command, args, **kwargs) - wt_config: WorktreeConfigDict = { - "dir": str(worktree_path), - "tag": "v-lock-fail-test", - "lock": True, - "lock_reason": "This lock will fail", - } + # Fail only lock metadata after native worktree creation has completed. + monkeypatch.setattr(Git, "run", fail_lock) + entry = sync_worktree( + git_repo.path, + {"dir": str(path), "commit": "HEAD", "lock": True}, + tmp_path, + ) + assert entry.action == WorktreeAction.ERROR + assert path.is_dir() + assert entry.result is not None and entry.result.update_state == "completed" + assert entry.result.errors[0].step == "worktree-lock" - # Mock only the lock command to fail (let creation succeed) - original_run = subprocess.run - def mock_run(*args: t.Any, **kwargs: t.Any) -> t.Any: - cmd = args[0] if args else kwargs.get("args", []) - if isinstance(cmd, list) and "lock" in cmd: - raise subprocess.CalledProcessError(1, cmd, stderr="lock failed") - return original_run(*args, **kwargs) +def test_worktree_creation_fetches_configured_remote( + policy_worktree: tuple[GitSync, pathlib.Path, str, str], +) -> None: + """Creation establishes a branch that exists only in a configured remote.""" + from libvcs.sync.git import GitSync - mocker.patch("vcspull._internal.worktree_sync.subprocess.run", side_effect=mock_run) + repo, existing, _, target = policy_worktree + upstream = GitSync(url=str(repo.path), path=existing.parent / "new-upstream") + upstream.obtain() + upstream.cmd.run(["branch", "new-remote-branch", target], check_returncode=True) + path = existing.parent / "new-remote-worktree" + entry = sync_worktree( + repo.path, + {"dir": str(path), "branch": "new-remote-branch", "remote": "upstream"}, + path.parent, + repo_config={"url": repo.url, "remotes": {"upstream": str(upstream.path)}}, + ) + assert entry.action == WorktreeAction.CREATE, entry.error + assert entry.result is not None and entry.result.ok + assert entry.target_position is not None + assert entry.target_position.revision == target + assert repo.cmd.run(["-C", str(path), "symbolic-ref", "HEAD"]).strip() == ( + "refs/heads/new-remote-branch" + ) - entry = sync_worktree(git_repo.path, wt_config, workspace_root) - # Creation should succeed despite lock failure - assert entry.action == WorktreeAction.CREATE - assert worktree_path.exists() +def test_worktree_creation_reports_resolved_relative_revision( + policy_worktree: tuple[GitSync, pathlib.Path, str, str], +) -> None: + """Reporting cannot resolve HEAD~1 again against the new detached checkout.""" + repo, existing, base, _ = policy_worktree + path = existing.parent / "relative-worktree" + entry = sync_worktree( + repo.path, {"dir": str(path), "commit": "HEAD~1"}, path.parent + ) + assert entry.action == WorktreeAction.CREATE, entry.error + assert entry.result is not None and entry.result.ok + assert entry.target_position is not None + assert entry.target_position.revision == base + assert repo.cmd.run(["-C", str(path), "rev-parse", "HEAD"]).strip() == base def test_sync_worktree_empty_plan_returns_error( @@ -3429,3 +3455,489 @@ def test_sync_worktree_empty_plan_returns_error( assert entry.action == WorktreeAction.ERROR assert entry.error is not None assert "no entries" in entry.error + + +@pytest.fixture +def policy_worktree( + git_repo: GitSync, tmp_path: pathlib.Path +) -> tuple[GitSync, pathlib.Path, str, str]: + """Keep a detached linked checkout behind locally available typed targets.""" + for name in ("local.txt", "advance.txt"): + (git_repo.path / name).write_text("base\n") + git_repo.cmd.run(["add", "local.txt", "advance.txt"], check_returncode=True) + git_repo.cmd.run(["commit", "-m", "worktree base"], check_returncode=True) + base = git_repo.get_position().revision + path = tmp_path / "policy-worktree" + git_repo.cmd.run( + ["worktree", "add", "--detach", str(path), base], check_returncode=True + ) + (git_repo.path / "advance.txt").write_text("advanced\n") + git_repo.cmd.run(["add", "advance.txt"], check_returncode=True) + git_repo.cmd.run(["commit", "-m", "advance target"], check_returncode=True) + target = git_repo.get_position().revision + git_repo.cmd.run(["tag", "policy-target"], check_returncode=True) + return git_repo, path, base, target + + +@pytest.mark.parametrize("selector", ["tag", "commit"]) +@pytest.mark.parametrize("drift", ["follow", "keep", "warn"]) +def test_worktree_policy_updates_wrong_oid( + policy_worktree: tuple[GitSync, pathlib.Path, str, str], + selector: str, + drift: str, + caplog: pytest.LogCaptureFixture, +) -> None: + """An existing pinned checkout must move when its configured target differs.""" + repo, path, _, target = policy_worktree + config = t.cast( + WorktreeConfigDict, + { + "dir": str(path), + selector: "policy-target" if selector == "tag" else target, + "sync": {"drift": drift}, + }, + ) + entry = sync_worktree(repo.path, config, path.parent) + assert entry.action == ( + WorktreeAction.UPDATE if drift == "follow" else WorktreeAction.UNCHANGED + ), entry.error + assert entry.result is not None and entry.result.ok + assert (path / "advance.txt").read_text() == ( + "advanced\n" if drift == "follow" else "base\n" + ) + assert bool( + [ + record + for record in caplog.records + if getattr(record, "vcs_event", None) == "target_drift" + ] + ) == (drift == "warn") + assert entry.target_position is not None + assert entry.target_position.revision == target + + +@pytest.mark.parametrize("drift", ["follow", "keep", "warn"]) +def test_worktree_policy_same_oid_attachment( + policy_worktree: tuple[GitSync, pathlib.Path, str, str], + drift: str, + caplog: pytest.LogCaptureFixture, +) -> None: + """OID aliases are not drift, but follow still attaches the requested branch.""" + repo, path, base, _ = policy_worktree + repo.cmd.run(["branch", "same-position", base], check_returncode=True) + config = t.cast( + WorktreeConfigDict, + {"dir": str(path), "branch": "same-position", "sync": {"drift": drift}}, + ) + entry = sync_worktree(repo.path, config, path.parent) + assert entry.result is not None and entry.result.ok, entry.error + assert entry.drifted is False + observed = repo.cmd.run( + ["-C", str(path), "symbolic-ref", "-q", "HEAD"], check_returncode=False + ) + assert (observed.strip() == "refs/heads/same-position") == (drift == "follow") + assert not any( + getattr(record, "vcs_event", None) == "target_drift" + for record in caplog.records + ) + + +@pytest.mark.parametrize("dirty", ["abort", "preserve", "discard"]) +def test_worktree_policy_dirty_native_state( + policy_worktree: tuple[GitSync, pathlib.Path, str, str], dirty: str +) -> None: + """Preserve retains staged bytes and unknown files; discard needs authorization.""" + repo, path, base, _ = policy_worktree + (path / "local.txt").write_text("staged\n") + repo.cmd.run(["-C", str(path), "add", "local.txt"], check_returncode=True) + (path / "local.txt").write_text("working\n") + (path / "unknown.txt").write_text("unknown\n") + config = t.cast( + WorktreeConfigDict, + {"dir": str(path), "tag": "policy-target", "sync": {"dirty": dirty}}, + ) + entry = sync_worktree(repo.path, config, path.parent, allow_discard=True) + assert entry.result is not None + if dirty == "abort": + assert not entry.result.ok + assert entry.action == WorktreeAction.BLOCKED + assert repo.cmd.run(["-C", str(path), "rev-parse", "HEAD"]).strip() == base + else: + assert entry.result.ok, entry.result.errors + assert (path / "advance.txt").read_text() == "advanced\n" + if dirty != "discard": + assert (path / "local.txt").read_text() == "working\n" + assert (path / "unknown.txt").read_text() == "unknown\n" + assert repo.cmd.run(["-C", str(path), "show", ":local.txt"]) == "staged\n" + else: + assert (path / "local.txt").read_text() == "base\n" + assert not (path / "unknown.txt").exists() + if dirty == "preserve": + assert entry.result.recovery is not None + assert entry.result.preservation_state == "restored" + + +@pytest.mark.parametrize("included", [False, True]) +@pytest.mark.parametrize("mode", ["json", "ndjson", "human"]) +@pytest.mark.parametrize("conflicted", [False, True]) +def test_worktree_policy_cli_retains_recovery( + policy_worktree: tuple[GitSync, pathlib.Path, str, str], + tmp_path: pathlib.Path, + capsys: pytest.CaptureFixture[str], + included: bool, + mode: str, + conflicted: bool, +) -> None: + """Both CLI entrypoints retain usable tokens after successful restoration.""" + import json + + from vcspull.cli import cli + + from .helpers import write_config + + repo, path, _, target = policy_worktree + (path / "local.txt").write_text("local changes\n") + if conflicted: + (path / "advance.txt").write_text("conflicting caller change\n") + config = write_config( + tmp_path / "policy.yaml", + f"""{repo.path.parent}/: + {repo.path.name}: + repo: git+{repo.url} + working_copy: + commit: {target} + worktrees: + - dir: {path} + tag: policy-target + sync: + dirty: preserve +""", + ) + args = ( + ["sync", "--all", "--include-worktrees", "--no-log-file"] + if included + else ["worktree", "sync"] + ) + args += ["--file", str(config), "--color", "never"] + if mode != "human": + args += ["--" + mode] + if conflicted: + if included: + args.append("--exit-on-error") + with pytest.raises(SystemExit): + cli(args) + else: + cli(args) + output = capsys.readouterr().out + if mode == "human": + assert "Recovery retained (git):" in output + assert f"local changes: {'conflicted' if conflicted else 'restored'}" in output + if conflicted: + assert "Conflict: advance.txt" in output + else: + events = ( + json.loads(output) + if mode == "json" + else [json.loads(line) for line in output.splitlines()] + ) + worktree = next(event for event in events if event.get("worktree_path")) + assert worktree["preservation_state"] == ( + "conflicted" if conflicted else "restored" + ) + if conflicted: + assert worktree["conflicts"][0]["path"] == "advance.txt" + assert worktree["errors"][0]["step"] == "restore" + token = worktree["recovery"] + assert token["backend"] == "git" + assert pathlib.Path(token["location"]).is_absolute() + assert (pathlib.Path(token["location"]) / "operation.json").exists() + assert (path / "local.txt").read_text() == "local changes\n" + + +@pytest.mark.parametrize("included", [False, True]) +def test_worktree_policy_cli_discard_preflight( + policy_worktree: tuple[GitSync, pathlib.Path, str, str], + tmp_path: pathlib.Path, + capsys: pytest.CaptureFixture[str], + included: bool, +) -> None: + """A worktree requiring consent prevents its main checkout from changing.""" + from vcspull.cli import cli + + from .helpers import write_config + + repo, path, base, target = policy_worktree + (path / "local.txt").write_text("caller bytes\n") + config = write_config( + tmp_path / "discard.yaml", + f"""{repo.path.parent}/: + {repo.path.name}: + repo: git+{repo.url} + working_copy: + commit: {base} + worktrees: + - dir: {path} + tag: policy-target + sync: + dirty: discard +""", + ) + args = ( + ["sync", "--all", "--include-worktrees", "--no-log-file", "--exit-on-error"] + if included + else ["worktree", "sync"] + ) + args += ["--file", str(config), "--color", "never"] + with pytest.raises(SystemExit) as stopped: + cli(args) + assert stopped.value.code == 1 + assert "requires --yes" in capsys.readouterr().out + assert repo.get_position().revision == target + assert (path / "local.txt").read_text() == "caller bytes\n" + cli([*args, "--yes"]) + assert (path / "local.txt").read_text() == "base\n" + + +@pytest.mark.parametrize("drift", ["follow", "keep", "warn"]) +def test_worktree_policy_creation_keeps_target_kind( + policy_worktree: tuple[GitSync, pathlib.Path, str, str], + drift: str, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A same-named tag cannot redirect branch creation or force detachment.""" + from libvcs.sync.git import GitSync + + repo, existing, base, target = policy_worktree + repo.cmd.run(["branch", "policy-target", base], check_returncode=True) + + def no_clone(*args: t.Any, **kwargs: t.Any) -> None: + message = "linked worktrees must not clone" + raise AssertionError(message) + + # Clone is forbidden after the native parent fixture has been created. + monkeypatch.setattr(GitSync, "obtain", no_clone) + for selector, expected in (("branch", base), ("tag", target)): + path = existing.parent / f"created-{selector}" + config = t.cast( + WorktreeConfigDict, + { + "dir": str(path), + selector: "policy-target", + "sync": {"drift": drift}, + "lock_reason": "managed checkout", + }, + ) + entry = sync_worktree(repo.path, config, path.parent) + assert entry.action == WorktreeAction.CREATE, entry.error + assert entry.result is not None and entry.result.ok + assert (path / ".git").is_file() + assert repo.cmd.run(["-C", str(path), "rev-parse", "HEAD"]).strip() == expected + attached = repo.cmd.run( + ["-C", str(path), "symbolic-ref", "-q", "HEAD"], check_returncode=False + ).strip() + assert bool(attached) == (selector == "branch") + assert "locked managed checkout" in repo.cmd.run( + ["worktree", "list", "--porcelain"] + ) + + +def test_worktree_policy_remote_detach_fetches_before_resolving( + policy_worktree: tuple[GitSync, pathlib.Path, str, str], + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Detached branch execution resolves newly fetched selected-remote metadata.""" + import shutil + + from libvcs.cmd.git import Git + from libvcs.sync.git import GitSync + + repo, path, base, _ = policy_worktree + remote = path.parent / "upstream" + shutil.copytree(repo.path, remote) + upstream = GitSync(url=repo.url, path=remote) + upstream.cmd.run(["checkout", "-b", "chosen", base], check_returncode=True) + repo.cmd.run(["remote", "add", "upstream", str(remote)], check_returncode=True) + repo.cmd.run(["fetch", "upstream"], check_returncode=True) + (remote / "advance.txt").write_text("upstream advancement\n") + upstream.cmd.run(["add", "advance.txt"], check_returncode=True) + upstream.cmd.run(["commit", "-m", "upstream advances"], check_returncode=True) + target = upstream.get_position().revision + config: WorktreeConfigDict = { + "dir": str(path), + "branch": "chosen", + "remote": "upstream", + "detach": True, + } + parent = { + "path": repo.path, + "url": repo.url, + "git": {"tls_verify": False}, + "remotes": {"upstream": str(remote)}, + } + original_fetch = Git.fetch + fetched = [] + + def fetch(command: Git, *args: t.Any, **kwargs: t.Any) -> str: + fetched.append(kwargs) + return original_fetch(command, *args, **kwargs) + + # Observe actual transport arguments while retaining the native fetch. + monkeypatch.setattr(Git, "fetch", fetch) + plan = plan_worktree_sync(repo.path, [config], path.parent, repo_config=parent)[0] + assert not fetched + assert plan.target_position is not None and plan.target_position.revision == base + entry = sync_worktree(repo.path, config, path.parent, repo_config=parent) + assert entry.result is not None and entry.result.ok, entry.error + assert fetched and all( + call["config"] == {"http.sslVerify": False} for call in fetched + ) + assert repo.cmd.run(["-C", str(path), "rev-parse", "HEAD"]).strip() == target + assert not repo.cmd.run( + ["-C", str(path), "symbolic-ref", "-q", "HEAD"], check_returncode=False + ) + assert repo.cmd.run(["remote", "get-url", "upstream"]).strip() == str(remote) + + +@pytest.mark.parametrize("drift", ["keep", "warn"]) +def test_worktree_policy_creation_positions_before_keep( + policy_worktree: tuple[GitSync, pathlib.Path, str, str], drift: str +) -> None: + """Initial creation fast-forwards a local branch to its configured remote ref.""" + repo, existing, base, target = policy_worktree + repo.cmd.run(["branch", "initial", base], check_returncode=True) + repo.cmd.run( + ["update-ref", "refs/remotes/selected/initial", target], check_returncode=True + ) + path = existing.parent / "initial" + config = t.cast( + WorktreeConfigDict, + { + "dir": str(path), + "branch": "initial", + "remote": "selected", + "sync": {"drift": drift}, + }, + ) + entry = sync_worktree(repo.path, config, path.parent) + assert entry.result is not None and entry.result.ok, entry.error + assert repo.cmd.run(["-C", str(path), "rev-parse", "HEAD"]).strip() == target + + +@pytest.mark.parametrize("missing", [False, True]) +def test_worktree_policy_retained_owner_prevents_preparation( + policy_worktree: tuple[GitSync, pathlib.Path, str, str], missing: bool +) -> None: + """Unfinished native ownership prevents shared-remote edits and worktree-add.""" + from libvcs.sync.git import GitSync + + repo, existing, base, _ = policy_worktree + path = existing.parent / "not-created" if missing else existing + owner = repo if missing else GitSync(url=repo.url, path=existing) + store = owner._store() + token, _ = store.create(original={}, target={}) + config: WorktreeConfigDict = {"dir": str(path), "commit": base, "detach": True} + parent = {"path": repo.path, "url": repo.url, "remotes": {"unexpected": repo.url}} + entry = sync_worktree(repo.path, config, path.parent, repo_config=parent) + assert "unexpected" not in repo.cmd.run(["remote"]).splitlines() + assert entry.result is not None and not entry.result.ok + assert entry.result.recovery == token + if missing: + assert not path.exists() + + +def test_handle_list_forwards_repo_config_options( + policy_worktree: tuple[GitSync, pathlib.Path, str, str], + capsys: pytest.CaptureFixture[str], +) -> None: + """Worktree list forwards parent repo_config into planning.""" + import json + + from vcspull.cli._colors import ColorMode, Colors + from vcspull.cli._output import OutputFormatter, OutputMode + from vcspull.cli.worktree import _handle_list + + repo, path, _, _ = policy_worktree + formatter = OutputFormatter(OutputMode.JSON) + colors = Colors(ColorMode.NEVER) + repos = [ + t.cast( + "t.Any", + { + "name": repo.path.name, + "path": str(repo.path), + "url": repo.url, + "workspace_root": str(path.parent), + "git": {"depth": -1}, + "worktrees": [{"dir": str(path), "tag": "policy-target"}], + }, + ) + ] + _handle_list(repos, formatter, colors) + formatter.finalize() + payload = json.loads(capsys.readouterr().out) + assert payload[0]["action"] == "error" + assert "depth must be a positive integer or None" in payload[0]["error"] + + +def test_sync_worktree_updates_ref_exists_check_after_fetch( + policy_worktree: tuple[GitSync, pathlib.Path, str, str], + tmp_path: pathlib.Path, +) -> None: + """Creation of a remote-only ref replaces the offline pre-fetch check failure.""" + import shutil + + from libvcs.sync.git import GitSync + + repo, existing, _, _ = policy_worktree + remote_dir = tmp_path / "remote-origin" + shutil.copytree(repo.path, remote_dir) + remote = GitSync(url=str(remote_dir), path=remote_dir) + (remote_dir / "remote_only.txt").write_text("from remote\n") + remote.cmd.run(["add", "remote_only.txt"], check_returncode=True) + remote.cmd.run(["commit", "-m", "remote tag commit"], check_returncode=True) + remote.cmd.run(["tag", "remote-only-tag"], check_returncode=True) + repo.cmd.run( + ["remote", "set-url", "origin", str(remote_dir)], check_returncode=True + ) + + wt_path = existing.parent / "wt-remote-tag" + config: WorktreeConfigDict = {"dir": str(wt_path), "tag": "remote-only-tag"} + entry = sync_worktree( + repo.path, + config, + existing.parent, + repo_config={"path": repo.path, "url": str(remote_dir)}, + ) + assert entry.action == WorktreeAction.CREATE, entry.error + assert entry.result is not None and entry.result.ok + assert all(check.passed for check in entry.checks), entry.checks + + +def test_cli_worktree_sync_dry_run_exits_zero_when_blocked_or_missing_ref( + policy_worktree: tuple[GitSync, pathlib.Path, str, str], + tmp_path: pathlib.Path, + capsys: pytest.CaptureFixture[str], +) -> None: + """Dry-run worktree sync previews blocked and unfetched entries with exit code 0.""" + from vcspull.cli import cli + + from .helpers import write_config + + repo, path, _, _ = policy_worktree + (path / "local.txt").write_text("dirty checkout\n") + config = write_config( + tmp_path / "dry-run.yaml", + f"""{repo.path.parent}/: + {repo.path.name}: + repo: git+{repo.url} + worktrees: + - dir: {path} + tag: policy-target + - dir: {path.parent / "unfetched-wt"} + tag: unfetched-remote-tag +""", + ) + cli(["worktree", "sync", "--dry-run", "--file", str(config), "--color", "never"]) + output = capsys.readouterr().out + assert "1 blocked" in output + assert "1 errors" in output