1818import subprocess
1919from collections .abc import Sequence
2020from dataclasses import dataclass
21+ from pathlib import Path
2122from typing import Protocol
2223
2324#: Feature-branch namespace (PARITY §8/§14, renamed from cloude-cade's ``cloude/``).
2425BRANCH_PREFIX = "panopticon"
2526
27+ #: URL schemes that mean a networked (hosted-forge) remote rather than a local path.
28+ _FORGE_SCHEMES = ("https://" , "http://" , "ssh://" , "git://" , "ftp://" , "ftps://" )
29+
30+
31+ def is_forge_url (git_url : str ) -> bool :
32+ """True when ``git_url`` names a hosted-forge remote (network push/PR/CI), not a local path.
33+
34+ Recognizes URL-scheme remotes (``https://…``, ``ssh://…``, …) and scp-like ``user@host:path``
35+ remotes; treats a bare filesystem path or a ``file://`` URL as local-only.
36+ """
37+ url = git_url .strip ()
38+ if url .lower ().startswith ("file://" ):
39+ return False
40+ if url .lower ().startswith (_FORGE_SCHEMES ):
41+ return True
42+ # scp-like syntax: user@host:path — an '@' and a ':' before any '/'. A Windows drive path
43+ # (``C:\…``) has the ':' but no '@', so it stays local.
44+ at , colon , slash = url .find ("@" ), url .find (":" ), url .find ("/" )
45+ return at != - 1 and colon > at and (slash == - 1 or colon < slash )
46+
47+
48+ def local_repo_path (git_url : str ) -> str | None :
49+ """The filesystem path ``git_url`` names, or ``None`` when it names a networked remote.
50+
51+ The counterpart of :func:`is_forge_url`: a bare path or a ``file://`` URL is somewhere on this
52+ host — which is what makes panopticon's host-side push, and cloning a task's submodules from
53+ the repo's own checkout (:func:`panopticon.sessionservice.spawn.hydrate_submodules`), possible
54+ at all.
55+ """
56+ if is_forge_url (git_url ):
57+ return None
58+ url = git_url .strip ()
59+ if url .lower ().startswith ("file://" ):
60+ url = url [len ("file://" ) :]
61+ return str (Path (url ).expanduser ()) if url else None
62+
2663
2764class GitError (RuntimeError ):
2865 """A ``git`` command that exited non-zero, carrying its ``stderr``.
@@ -87,6 +124,27 @@ def parse_submodule_status(output: str) -> dict[str, str]:
87124 return states
88125
89126
127+ def parse_submodule_paths (output : str ) -> dict [str , str ]:
128+ """Parse ``git config --get-regexp`` output into ``{submodule name: path}``.
129+
130+ Each line is ``submodule.<name>.path <path>`` — read from ``.gitmodules`` rather than from
131+ ``git submodule status`` because it answers *before* ``submodule init`` has run and for
132+ submodules that aren't checked out. The name is whatever sits between the ``submodule.``
133+ prefix and the ``.path`` suffix (it usually **is** the path, dots and slashes included), and
134+ the value is the rest of the line, so a path containing spaces survives. Lines that don't
135+ match the shape are skipped.
136+ """
137+ paths : dict [str , str ] = {}
138+ for line in output .splitlines ():
139+ key , _ , value = line .partition (" " )
140+ if not value or not key .startswith ("submodule." ) or not key .endswith (".path" ):
141+ continue
142+ name = key [len ("submodule." ) : - len (".path" )]
143+ if name :
144+ paths [name ] = value
145+ return paths
146+
147+
90148@dataclass (frozen = True )
91149class Worktree :
92150 """A created worktree: its branch and on-disk path."""
@@ -164,8 +222,59 @@ def submodule_status(self, *, repo_path: str) -> dict[str, str]:
164222 out = self ._run (["git" , "-C" , repo_path , "submodule" , "status" , "--recursive" ])
165223 return parse_submodule_status (out )
166224
167- def update_submodules (self , * , repo_path : str ) -> None :
168- """``git -C <repo> submodule update --init --recursive`` — fill in the submodule checkouts.
225+ def submodule_paths (self , * , repo_path : str ) -> dict [str , str ]:
226+ """The submodules this repo *declares* — ``{name: path}``, empty when there are none.
227+
228+ Reads ``.gitmodules`` (``git config --file``), not ``git submodule status``: the caller
229+ overriding a submodule's URL (:meth:`set_submodule_url`) needs the **name** git keys that
230+ config on, and needs it for a submodule that isn't checked out yet. Only this level's
231+ submodules — a nested one is declared in its own superproject's ``.gitmodules``, so the
232+ caller recurses. ``check=False`` because ``git config`` exits non-zero when the file (or a
233+ match) is absent, which is just "no submodules".
234+ """
235+ out = self ._run (
236+ [
237+ "git" ,
238+ "-C" ,
239+ repo_path ,
240+ "config" ,
241+ "--file" ,
242+ ".gitmodules" ,
243+ "--get-regexp" ,
244+ "^submodule\\ ..*\\ .path$" ,
245+ ],
246+ check = False ,
247+ )
248+ return parse_submodule_paths (out )
249+
250+ def init_submodules (self , * , repo_path : str ) -> None :
251+ """``git -C <repo> submodule init`` — resolve each declared URL into ``submodule.<n>.url``.
252+
253+ Separated from ``update`` so a caller can *override* the resolved URL in between (the
254+ donor hydration in ``sessionservice.spawn``); ``update --init`` would clone before the
255+ override could land.
256+ """
257+ self ._run (["git" , "-C" , repo_path , "submodule" , "init" ])
258+
259+ def set_submodule_url (self , * , repo_path : str , name : str , url : str ) -> None :
260+ """``git -C <repo> config submodule.<name>.url <url>`` — where ``update`` clones from.
261+
262+ The config value wins over ``.gitmodules`` until :meth:`sync_submodules` restores it.
263+ """
264+ self ._run (["git" , "-C" , repo_path , "config" , f"submodule.{ name } .url" , url ])
265+
266+ def sync_submodules (self , * , repo_path : str ) -> None :
267+ """``git -C <repo> submodule sync --recursive`` — restore the canonical submodule URLs.
268+
269+ Rewrites every ``submodule.<name>.url`` from ``.gitmodules`` (resolved against the
270+ superproject's ``origin``) **and** repoints each checked-out submodule's own
271+ ``remote.origin.url`` at it — so a temporary local-donor override leaves nothing of the
272+ host's paths behind in the checkout the container gets.
273+ """
274+ self ._run (["git" , "-C" , repo_path , "submodule" , "sync" , "--recursive" ])
275+
276+ def update_submodules (self , * , repo_path : str , recursive : bool = True ) -> None :
277+ """``git -C <repo> submodule update --init [--recursive]`` — fill in the submodule checkouts.
169278
170279 ``protocol.file.allow=always`` is **required**, not cosmetic: since git 2.38 a submodule
171280 whose resolved URL is a local path is refused (``transport 'file' not allowed``,
@@ -178,20 +287,24 @@ def update_submodules(self, *, repo_path: str) -> None:
178287 Submodule URLs are resolved against the superproject's ``remote.origin.url`` *here*, so the
179288 caller must point ``origin`` at the forge first (:meth:`set_origin`) — resolving a relative
180289 URL against the cache path would look for the submodule next to the cache clone.
290+
291+ ``recursive=False`` updates **this level only**: a nested submodule's URL can't be resolved
292+ (or overridden) before its parent exists, so the donor hydration walks the tree a level at
293+ a time instead.
181294 """
182- self . _run (
183- [
184- "git " ,
185- "-C" ,
186- repo_path ,
187- "-c " ,
188- "protocol.file.allow=always " ,
189- "submodule " ,
190- "update " ,
191- "--init" ,
192- "-- recursive" ,
193- ]
194- )
295+ args = [
296+ "git" ,
297+ "-C " ,
298+ repo_path ,
299+ "-c" ,
300+ "protocol.file.allow=always " ,
301+ "submodule " ,
302+ "update " ,
303+ "--init " ,
304+ ]
305+ if recursive :
306+ args . append ( "--recursive" )
307+ self . _run ( args )
195308
196309 def push (self , * , repo_path : str , remote : str , branch : str ) -> None :
197310 """``git -C <repo> push <remote> <branch>`` — send one branch, as-is (never forced).
0 commit comments