@@ -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