Skip to content

Commit e8d0158

Browse files
authored
sync(feat): Create linked Git worktrees under lock (#555)
why: Linked Git worktrees need atomic fetch, target resolution, creation, locking, and detached updates under shared repository ownership without touching parent working files. what: - Add GitSync.create_worktree() under the .git common-directory RecoveryStore lock - Support detach=True in GitSync.update_repo() after fetching under lock - Refuse worktree creation when interrupted recovery records remain Fixes #554
2 parents 4b9529c + 580fb2b commit e8d0158

4 files changed

Lines changed: 565 additions & 40 deletions

File tree

‎CHANGES‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,19 @@ repo = GitSync(
7373

7474
### What's new
7575

76+
#### Create linked Git worktrees under shared ownership (#555)
77+
78+
{meth}`~libvcs.sync.git.GitSync.create_worktree` fetches and creates an absent
79+
linked checkout at a typed target while holding the repository ownership lock.
80+
It retains local commits, rejects divergence and occupied destinations, and
81+
supports detached checkouts and worktree lock reasons. Interrupted recovery
82+
records refuse creation with their retained token; parent working files remain
83+
untouched.
84+
85+
`GitSync.update_repo(detach=True)` detaches at the resolved target after
86+
fetching under the ownership lock. Branch targets retain their native
87+
tracking-ref and local-branch fallback rules.
88+
7689
#### Subversion retains complete working copies for recovery (#563)
7790

7891
Explicit preservation in {meth}`~libvcs.sync.svn.SvnSync.update_repo` uses

‎docs/sync/git.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,10 @@ change their configured filter.
4242

4343
Following a branch requires fast-forward ancestry and retains ahead local
4444
commits. Select a tag or commit explicitly when you want a detached checkout.
45+
To detach at a branch's resolved target, pass `detach=True` to `update_repo()`.
46+
The branch resolves after fetching under the ownership lock, including the
47+
normal fallback to a local branch when no tracking ref exists. Existing
48+
keep/warn policies still leave attachment unchanged.
4549
Use the shared {ref}`policy guide <sync-policies>` and executing
4650
{ref}`recovery example <sync-recovery>` to handle results and retained tokens.
4751

@@ -55,6 +59,38 @@ objects in a partial clone cause recovery to fail without fetching. Keep that
5559
database until you release its tokens. Preservation rejects submodule scopes
5660
and independent nested repositories; clean recursive updates remain available.
5761

62+
## Linked worktrees
63+
64+
{meth}`~libvcs.sync.git.GitSync.create_worktree` creates an absent destination
65+
at a typed target. It fetches and resolves the target under the common repository
66+
lock, then creates the checkout and initializes its submodules. Parent working
67+
files remain untouched. Branch targets retain ahead local commits, advance only
68+
by fast-forward, and are refused when checked out elsewhere.
69+
70+
```python
71+
>>> from libvcs.sync.base import SyncTarget
72+
>>> result = example_git_repo.create_worktree(
73+
... tmp_path / "linked",
74+
... target=SyncTarget(commit=example_git_repo.get_revision()),
75+
... lock_reason="retained checkout",
76+
... )
77+
>>> result.ok
78+
True
79+
>>> result.update_state
80+
'completed'
81+
```
82+
83+
`detach=True` detaches at the resolved target. `lock=True` locks the worktree;
84+
`lock_reason` also requests a lock. `set_remotes=True` applies configured remotes
85+
before fetching. Existing interrupted recovery records refuse creation and
86+
retain their token in the result.
87+
88+
An occupied destination is rejected before branch movement. Native failures
89+
can still leave changed refs or a partial checkout: `update_state="unknown"`
90+
means creation began without reported completion. A completed update with errors
91+
means later lock or submodule setup failed. Creation holds the same ownership
92+
lock as updates; callers must exclude external native writers and editors.
93+
5894
```{eval-rst}
5995
.. automodule:: libvcs.sync.git
6096
:members:

‎src/libvcs/sync/git.py‎

Lines changed: 208 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -626,7 +626,7 @@ def _store(self) -> preservation.RecoveryStore:
626626
)
627627
return preservation.RecoveryStore(self.path, "git", common)
628628

629-
def _precondition(self) -> tuple[str, ...]:
629+
def _native_precondition(self) -> None:
630630
root = pathlib.Path(self._read_git(["rev-parse", "--show-toplevel"]).strip())
631631
if root != self.path.absolute():
632632
msg = "Git synchronization requires the working-copy root"
@@ -648,6 +648,9 @@ def _precondition(self) -> tuple[str, ...]:
648648
if path.exists():
649649
msg = f"native Git activity prevents synchronization: {name}"
650650
raise ValueError(msg)
651+
652+
def _precondition(self) -> tuple[str, ...]:
653+
self._native_precondition()
651654
dirty = self._dirty_paths()
652655
tracked = self._read_git(["ls-files", "--stage", "-z"])
653656
submodules = {
@@ -871,19 +874,212 @@ def list_recoveries(self) -> tuple[SyncResult, ...]:
871874
result.add_error("recovery-material", str(error), error)
872875
return results
873876

877+
def _retained_refusal(self, store: preservation.RecoveryStore) -> SyncResult | None:
878+
"""Inspect interrupted owners while the caller holds the common lock."""
879+
result = SyncResult()
880+
try:
881+
active = store.repository / ".libvcs-preserve-active.json"
882+
if active.exists():
883+
preservation.safe_path(active)
884+
owner = json.loads(active.read_text())
885+
owner_store = preservation.RecoveryStore(
886+
pathlib.Path(owner["source"]), "git", store.repository
887+
)
888+
owner_token = RecoveryToken(**owner["token"])
889+
result.recovery = owner_token
890+
result.update_state = "unknown"
891+
result.preservation_state = "unknown"
892+
owner_record = owner_store.read(owner_token)
893+
if owner_record["phase"] not in preservation.TERMINAL:
894+
return owner_store.snapshot(owner_token, owner_record)
895+
result = SyncResult()
896+
for retained in store.discover():
897+
assert retained.recovery is not None
898+
if any(error.step == "recovery-record" for error in retained.errors):
899+
return retained
900+
result = retained
901+
retained_record = store.read(retained.recovery)
902+
if retained_record["phase"] not in preservation.TERMINAL:
903+
return retained
904+
except (
905+
exc.LibVCSException,
906+
OSError,
907+
ValueError,
908+
RuntimeError,
909+
KeyError,
910+
TypeError,
911+
) as error:
912+
result.add_error("precondition", str(error), error)
913+
return result
914+
return None
915+
916+
def _fast_forward_target(self, target: WorkingCopyPosition) -> WorkingCopyPosition:
917+
"""Retain local commits and reject divergence before any checkout writes."""
918+
if target.follows:
919+
try:
920+
local = self._oid(f"refs/heads/{target.ref_name}")
921+
except exc.CommandError:
922+
return target
923+
if self._ancestor(target.revision, local):
924+
return dataclasses.replace(target, revision=local)
925+
if not self._ancestor(local, target.revision):
926+
msg = "target diverges; fast-forward required"
927+
raise ValueError(msg)
928+
return target
929+
930+
def create_worktree(
931+
self,
932+
destination: StrPath,
933+
*,
934+
target: SyncTarget,
935+
detach: bool = False,
936+
lock: bool = False,
937+
lock_reason: str | None = None,
938+
set_remotes: bool = False,
939+
) -> SyncResult:
940+
"""Create a linked checkout at its resolved target under shared ownership.
941+
942+
The destination must be absent. Branches advance only by fast-forward,
943+
retain local commits, and cannot be checked out elsewhere. Parent working
944+
files remain untouched. Fetch, creation, submodules, and lock metadata
945+
share one repository lock; callers must exclude external native writers.
946+
947+
Native failures may leave refs or a partial checkout. An unknown update
948+
state means creation began but did not report completion; a completed
949+
update with errors means subsequent submodule or lock setup failed.
950+
``lock_reason`` implies ``lock=True``.
951+
952+
Parameters
953+
----------
954+
destination : StrPath
955+
Absent target directory for the linked worktree.
956+
target : SyncTarget
957+
Branch, tag, commit, or revision selector to resolve after fetching.
958+
detach : bool, default: False
959+
Create the checkout with ``--detach`` even when ``target`` names a
960+
branch.
961+
lock : bool, default: False
962+
Lock the new worktree via ``git worktree lock`` after creation.
963+
lock_reason : str | None, optional
964+
Reason recorded by ``git worktree lock --reason``; implies
965+
``lock=True``.
966+
set_remotes : bool, default: False
967+
Apply configured remotes before fetching.
968+
969+
Returns
970+
-------
971+
SyncResult
972+
Outcome carrying ``update_state`` and any retained recovery refusal
973+
or native step errors.
974+
"""
975+
result = SyncResult()
976+
step = "precondition"
977+
try:
978+
store = self._store()
979+
with store.lock():
980+
refused = self._retained_refusal(store)
981+
if refused is not None:
982+
return refused
983+
self._native_precondition()
984+
dest = preservation.safe_path(pathlib.Path(destination))
985+
# Native add -B can move a branch before rejecting an occupied path.
986+
if dest.exists():
987+
msg = f"worktree destination already exists: {dest}"
988+
raise ValueError(msg) # noqa: TRY301 - refuse before native mutation
989+
if set_remotes:
990+
step = "set-remotes"
991+
self.set_remotes(overwrite=True)
992+
step = "fetch"
993+
self.cmd.fetch(
994+
_all=True,
995+
prune=True,
996+
config={"http.sslVerify": False}
997+
if not self.options.tls_verify
998+
else None,
999+
check_returncode=True,
1000+
)
1001+
step = "target"
1002+
resolved = self.resolve_target(target)
1003+
args = ["worktree", "add"]
1004+
if resolved.follows and not detach:
1005+
resolved = self._fast_forward_target(resolved)
1006+
try:
1007+
self._oid(f"refs/heads/{resolved.ref_name}")
1008+
except exc.CommandError:
1009+
args += ["-b", resolved.ref_name]
1010+
else:
1011+
args += ["-B", resolved.ref_name]
1012+
else:
1013+
args += ["--detach"]
1014+
args += ["--", str(dest), resolved.revision]
1015+
step = "worktree-add"
1016+
result.update_state = "unknown"
1017+
self.cmd.run(
1018+
args,
1019+
config={"http.sslVerify": False}
1020+
if not self.options.tls_verify
1021+
else None,
1022+
check_returncode=True,
1023+
)
1024+
result.update_state = "completed"
1025+
if lock or lock_reason is not None:
1026+
step = "worktree-lock"
1027+
lock_args = ["worktree", "lock"]
1028+
if lock_reason is not None:
1029+
lock_args += ["--reason", lock_reason]
1030+
self.cmd.run([*lock_args, "--", str(dest)], check_returncode=True)
1031+
step = "submodule-update"
1032+
GitSync(
1033+
url=self.url, path=dest, options=self.options
1034+
)._sync_submodules()
1035+
except (
1036+
exc.LibVCSException,
1037+
OSError,
1038+
ValueError,
1039+
RuntimeError,
1040+
KeyError,
1041+
TypeError,
1042+
) as error:
1043+
result.add_error(step, str(error), error)
1044+
return result
1045+
8741046
def update_repo(
8751047
self,
8761048
set_remotes: bool = False,
8771049
*args: t.Any,
8781050
target: SyncTarget | None = None,
8791051
policy: SyncPolicy | None = None,
1052+
detach: bool = False,
8801053
**kwargs: t.Any,
8811054
) -> SyncResult:
8821055
"""Follow targets by fast-forward; abort on dirt unless explicitly permitted.
8831056
8841057
Preserve retains an owned stash, even after indexed restoration. Recovery
8851058
needs the retained local object database. Callers must exclude other VCS
8861059
writers and editors throughout this operation.
1060+
1061+
``detach=True`` checks out the resolved target without attaching its
1062+
branch. Resolution happens after fetching, under the same ownership lock.
1063+
1064+
Parameters
1065+
----------
1066+
set_remotes : bool, default: False
1067+
Apply configured remotes before fetching when ``policy.drift``
1068+
follows the target.
1069+
target : SyncTarget | None, optional
1070+
Target selector overriding the constructor ``rev``; defaults to the
1071+
checkout's tracked ref.
1072+
policy : SyncPolicy | None, optional
1073+
Drift and dirty-checkout policy; defaults to
1074+
``SyncPolicy(drift="follow", dirty="abort")``.
1075+
detach : bool, default: False
1076+
Check out the resolved target revision detached rather than
1077+
attaching a branch.
1078+
1079+
Returns
1080+
-------
1081+
SyncResult
1082+
Update, preservation, conflict, and recovery token outcomes.
8871083
"""
8881084
result = SyncResult()
8891085
policy = policy or SyncPolicy()
@@ -898,29 +1094,9 @@ def update_repo(
8981094
store = self._store()
8991095
with store.lock():
9001096
active = store.repository / ".libvcs-preserve-active.json"
901-
if active.exists():
902-
preservation.safe_path(active)
903-
owner = json.loads(active.read_text())
904-
owner_store = preservation.RecoveryStore(
905-
pathlib.Path(owner["source"]), "git", store.repository
906-
)
907-
owner_token = RecoveryToken(**owner["token"])
908-
result.recovery = owner_token
909-
result.update_state = "unknown"
910-
result.preservation_state = "unknown"
911-
owner_record = owner_store.read(owner_token)
912-
if owner_record["phase"] not in preservation.TERMINAL:
913-
return owner_store.snapshot(owner_token, owner_record)
914-
result = SyncResult()
915-
for retained in store.discover():
916-
assert retained.recovery is not None
917-
if any(
918-
error.step == "recovery-record" for error in retained.errors
919-
):
920-
return retained
921-
retained_record = store.read(retained.recovery)
922-
if retained_record["phase"] not in preservation.TERMINAL:
923-
return retained
1097+
refused = self._retained_refusal(store)
1098+
if refused is not None:
1099+
return refused
9241100
dirty = self._precondition()
9251101
original = self.get_position()
9261102
step = "target"
@@ -956,23 +1132,19 @@ def update_repo(
9561132
)
9571133
step = "target"
9581134
resolved = self.resolve_target(target)
1135+
if detach and resolved.follows:
1136+
resolved = dataclasses.replace(
1137+
resolved,
1138+
ref_name=resolved.revision,
1139+
ref_kind="commit",
1140+
follows=False,
1141+
)
9591142
if not self._drifted(original, resolved):
9601143
if not dirty:
9611144
step = "submodule-update"
9621145
self._sync_submodules()
9631146
return result
964-
if resolved.follows:
965-
branch_ref = f"refs/heads/{resolved.ref_name}"
966-
try:
967-
local = self._oid(branch_ref)
968-
except exc.CommandError:
969-
local = None
970-
if local is not None:
971-
if self._ancestor(resolved.revision, local):
972-
resolved = dataclasses.replace(resolved, revision=local)
973-
elif not self._ancestor(local, resolved.revision):
974-
msg = "target diverges; fast-forward required"
975-
raise ValueError(msg) # noqa: TRY301 - return target error before capture
1147+
resolved = self._fast_forward_target(resolved)
9761148
target_tree = self._read_git(["ls-tree", "-r", "-z", resolved.revision])
9771149
if dirty and any(
9781150
entry.startswith("160000 ") for entry in target_tree.split("\0")

0 commit comments

Comments
 (0)