Skip to content

Commit 06bfa55

Browse files
Merge pull request #1437 from LalatenduMohanty/fix-1431-reuse-git-checkout
fix(sources): reuse matching Git checkouts
2 parents cbe25db + 78f119d commit 06bfa55

7 files changed

Lines changed: 367 additions & 58 deletions

File tree

‎docs/concepts/resolver-architecture.rst‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -173,9 +173,12 @@ These checks compare provider names, so replay should still use the same
173173
package settings. ``download-sequence`` still skips downloading a runtime
174174
``prebuilt`` entry even when the package has source settings.
175175
Built-in archive resolvers cache the resolved file for a later build. Git
176-
checkout resolvers clone into the work directory instead: with cleanup enabled,
177-
a later build removes that checkout and clones again; without cleanup, the
178-
later download fails because the checkout exists. Hook
176+
checkout resolvers clone into the work directory instead. A later build in the
177+
same work directory reuses that checkout if it is still a clean clone of the
178+
same repository at the same commit, so it can run without access to the Git
179+
host. It only checks local state, so a tag moved on the remote is not noticed.
180+
Any other existing checkout is removed and cloned again with cleanup enabled,
181+
and the download fails without cleanup. Hook
179182
download behavior depends on the hook. Legacy packages keep the
180183
``source_url_type`` selection behavior. Build-order entries record the
181184
effective configured ``source_provider`` for provenance; the

‎docs/using.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -266,9 +266,11 @@ download command's optional
266266
`--output-format json` prints both `path` and `kind` when a hook can return
267267
different artifact kinds. Its default output remains the path alone. Git
268268
preparation applies patches to the selected checkout itself, so use a
269-
disposable clone for `--source-path`. Git downloads do not reuse an existing
270-
checkout with `--no-cleanup`; the files remain available for inspection. Enable
271-
cleanup or use a new work directory to download it again.
269+
disposable clone for `--source-path`. Git downloads reuse an existing checkout
270+
only when it is a clean clone of the same repository at the same commit. Any
271+
other existing checkout is cloned again when cleanup is enabled. With
272+
`--no-cleanup` the download fails instead, so the files remain available for
273+
inspection. Enable cleanup or use a new work directory to download it again.
272274

273275
The `step prepare-build` command creates a virtualenv with the build
274276
dependencies for building the wheel. It expects a `--wheel-server-url`

‎src/fromager/gitutils.py‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import logging
44
import pathlib
5+
import subprocess
56
import typing
67
from urllib.parse import urlparse
78

@@ -158,6 +159,94 @@ def git_clean(source_dir: pathlib.Path) -> None:
158159
external_commands.run(cmd, cwd=str(source_dir))
159160

160161

162+
_GIT_STATUS_COMMAND: typing.Final = (
163+
"git",
164+
"status",
165+
"--porcelain=v1",
166+
"--untracked-files=all",
167+
"--ignored=matching",
168+
"--ignore-submodules=none",
169+
)
170+
171+
172+
def git_checkout_changes(checkout_dir: pathlib.Path) -> str:
173+
"""Return ``git status`` lines for local changes in a checkout.
174+
175+
Lists tracked, untracked, and ignored changes in *checkout_dir* and its
176+
initialized submodules. Returns an empty string when there are none.
177+
Raises ``subprocess.CalledProcessError`` if Git cannot inspect it.
178+
179+
.. versionadded:: 0.103.0
180+
"""
181+
changes = external_commands.run(_GIT_STATUS_COMMAND, cwd=str(checkout_dir))
182+
if not changes:
183+
# A parent repository can hide changes inside ignored submodules.
184+
changes = external_commands.run(
185+
[
186+
"git",
187+
"submodule",
188+
"--quiet",
189+
"foreach",
190+
"--recursive",
191+
" ".join(_GIT_STATUS_COMMAND),
192+
],
193+
cwd=str(checkout_dir),
194+
)
195+
return changes
196+
197+
198+
def git_checkout_mismatch(
199+
*,
200+
checkout_dir: pathlib.Path,
201+
repo_url: str,
202+
ref: str,
203+
) -> str | None:
204+
"""Explain why a checkout differs from a fresh clone of *repo_url* at *ref*.
205+
206+
Returns ``None`` when *checkout_dir* is the top of a Git checkout cloned
207+
from *repo_url*, ``HEAD`` is at *ref*, all submodules are initialized at
208+
their recorded commits, and there are no local changes. Otherwise returns
209+
a short reason. Only local state is checked, so a tag that moved on the
210+
remote after the clone is not detected.
211+
212+
.. versionadded:: 0.103.0
213+
"""
214+
if not (checkout_dir / ".git").exists():
215+
return "it is not a Git checkout"
216+
cwd = str(checkout_dir)
217+
try:
218+
# Git searches parent directories when ".git" is broken.
219+
toplevel = external_commands.run(
220+
["git", "rev-parse", "--show-toplevel"], cwd=cwd
221+
).strip()
222+
if pathlib.Path(toplevel).resolve() != checkout_dir.resolve():
223+
return "it is not the top of a Git checkout"
224+
origin = external_commands.run(
225+
["git", "remote", "get-url", "origin"], cwd=cwd
226+
).strip()
227+
if origin != repo_url:
228+
# Do not log URLs; they can contain credentials.
229+
return "it was cloned from a different repository"
230+
head = external_commands.run(
231+
["git", "rev-parse", "--verify", "HEAD"], cwd=cwd
232+
).strip()
233+
wanted = external_commands.run(
234+
["git", "rev-parse", "--verify", f"{ref}^{{commit}}"], cwd=cwd
235+
).strip()
236+
if head != wanted:
237+
return f"HEAD is not at {ref!r}"
238+
submodules = external_commands.run(
239+
["git", "submodule", "status", "--recursive"], cwd=cwd
240+
)
241+
if any(line.startswith(("-", "+", "U")) for line in submodules.splitlines()):
242+
return "a submodule is not initialized at its recorded commit"
243+
if git_checkout_changes(checkout_dir):
244+
return "it has local changes"
245+
except subprocess.CalledProcessError:
246+
return "Git cannot inspect it"
247+
return None
248+
249+
161250
def parse_vcs_url(vcs_url: str, *, require_ref: bool = True) -> tuple[str, str]:
162251
"""Parse a `pip VCS URL`_ into a repo clone URL and git ref.
163252

‎src/fromager/packagesettings/_resolver.py‎

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
import pydantic
1313
from packaging.utils import canonicalize_name
1414

15-
from .. import downloads, overrides, resolver
15+
from .. import downloads, gitutils, overrides, resolver
1616
from ._typedefs import MODEL_CONFIG
1717

1818
if typing.TYPE_CHECKING:
@@ -124,6 +124,10 @@ def _download(
124124
Returns the local path and the kind of artifact that was
125125
downloaded. Dispatches to the appropriate download helper
126126
based on *download_kind*.
127+
128+
An existing Git checkout is reused if it is a clean clone of the
129+
same repository at the same commit. Otherwise it is removed and
130+
cloned again when cleanup is enabled, or rejected when it is not.
127131
"""
128132
if download_kind not in self.download_kinds:
129133
raise ValueError(
@@ -165,14 +169,31 @@ def _download(
165169
destination_dir = (
166170
ctx.work_dir / f"{req.name}-{version}" / f"{req.name}-{version}"
167171
)
168-
if destination_dir.parent.exists():
169-
if ctx.cleanup:
170-
shutil.rmtree(destination_dir.parent)
171-
elif destination_dir.exists():
172+
if destination_dir.exists():
173+
# Reuse a checkout from an earlier download, for example
174+
# from download-sequence, so builds can run offline.
175+
repo_url, ref = gitutils.parse_vcs_url(download_url)
176+
mismatch = gitutils.git_checkout_mismatch(
177+
checkout_dir=destination_dir, repo_url=repo_url, ref=ref
178+
)
179+
if mismatch is None:
180+
logger.info("reusing Git checkout %s", destination_dir)
181+
return DownloadedSource(
182+
path=destination_dir, kind=download_kind
183+
)
184+
if not ctx.cleanup:
172185
raise FileExistsError(
173-
f"Git checkout {destination_dir} already exists; "
174-
"enable cleanup or use a new work directory to download it again"
186+
f"Git checkout {destination_dir} already exists and "
187+
f"cannot be reused because {mismatch}; enable cleanup "
188+
"or use a new work directory to download it again"
175189
)
190+
logger.info(
191+
"cloning again: cannot reuse Git checkout %s because %s",
192+
destination_dir,
193+
mismatch,
194+
)
195+
if destination_dir.parent.exists() and ctx.cleanup:
196+
shutil.rmtree(destination_dir.parent)
176197
path = downloads.download_git_source(
177198
destination_dir=destination_dir,
178199
vcs_url=download_url,

‎src/fromager/sources.py‎

Lines changed: 1 addition & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -554,29 +554,8 @@ def default_prepare_git_checkout(
554554
"""
555555
if not source_filename.is_dir() or not (source_filename / ".git").exists():
556556
raise ValueError(f"{source_filename} is not a Git checkout")
557-
status_command = (
558-
"git",
559-
"status",
560-
"--porcelain=v1",
561-
"--untracked-files=all",
562-
"--ignored=matching",
563-
"--ignore-submodules=none",
564-
)
565557
try:
566-
changes = external_commands.run(status_command, cwd=str(source_filename))
567-
if not changes:
568-
# A parent repository can hide changes inside ignored submodules.
569-
changes = external_commands.run(
570-
[
571-
"git",
572-
"submodule",
573-
"--quiet",
574-
"foreach",
575-
"--recursive",
576-
" ".join(status_command),
577-
],
578-
cwd=str(source_filename),
579-
)
558+
changes = gitutils.git_checkout_changes(source_filename)
580559
except subprocess.CalledProcessError as err:
581560
raise ValueError(f"cannot inspect Git checkout {source_filename}") from err
582561
if changes:

‎tests/test_gitutils.py‎

Lines changed: 141 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,13 @@
77
import pytest
88
from packaging.version import Version
99

10-
from fromager.gitutils import GIT_HEAD, git_clean, git_clone_fast, parse_vcs_url
10+
from fromager.gitutils import (
11+
GIT_HEAD,
12+
git_checkout_mismatch,
13+
git_clean,
14+
git_clone_fast,
15+
parse_vcs_url,
16+
)
1117

1218
needs_git_command = pytest.mark.skipif(
1319
shutil.which("git") is None, reason="requires 'git' command"
@@ -128,3 +134,137 @@ def test_git_clone_real(tmp_path: pathlib.Path) -> None:
128134

129135
# detect version from .git
130136
assert setuptools_scm_version(tmp_path) == Version("0.73.0")
137+
138+
139+
def _git(repo: pathlib.Path, *args: str) -> str:
140+
"""Run git in *repo* with a test identity and local file submodules."""
141+
result = subprocess.run(
142+
[
143+
"git",
144+
"-C",
145+
str(repo),
146+
"-c",
147+
"user.name=Test",
148+
"-c",
149+
"user.email=test@pkg.test",
150+
"-c",
151+
"protocol.file.allow=always",
152+
*args,
153+
],
154+
check=True,
155+
capture_output=True,
156+
text=True,
157+
)
158+
return result.stdout
159+
160+
161+
def _make_repo(repo: pathlib.Path) -> pathlib.Path:
162+
"""Create a Git repository with one commit tagged ``v1.0``."""
163+
repo.mkdir()
164+
_git(repo, "init")
165+
(repo / "README").write_text("source")
166+
_git(repo, "add", ".")
167+
_git(repo, "commit", "-m", "Initial source")
168+
_git(repo, "tag", "v1.0")
169+
return repo
170+
171+
172+
def _clone(repo: pathlib.Path, checkout: pathlib.Path, ref: str) -> pathlib.Path:
173+
"""Clone *repo* to *checkout* and check out *ref* with submodules."""
174+
_git(repo.parent, "clone", "--recurse-submodules", str(repo), str(checkout))
175+
_git(checkout, "checkout", "--recurse-submodules", ref)
176+
return checkout
177+
178+
179+
@needs_git_command
180+
def test_git_checkout_mismatch_accepts_clean_clone(tmp_path: pathlib.Path) -> None:
181+
repo = _make_repo(tmp_path / "repo")
182+
checkout = _clone(repo, tmp_path / "checkout", "refs/tags/v1.0")
183+
184+
result = git_checkout_mismatch(
185+
checkout_dir=checkout, repo_url=str(repo), ref="refs/tags/v1.0"
186+
)
187+
188+
assert result is None
189+
190+
191+
@needs_git_command
192+
@pytest.mark.parametrize(
193+
("change", "reason"),
194+
[
195+
("untracked", "it has local changes"),
196+
("ignored", "it has local changes"),
197+
("other_ref", "HEAD is not at 'refs/tags/v1.0'"),
198+
("unknown_ref", "Git cannot inspect it"),
199+
("other_repo", "it was cloned from a different repository"),
200+
],
201+
)
202+
def test_git_checkout_mismatch_reports_reason(
203+
tmp_path: pathlib.Path, change: str, reason: str
204+
) -> None:
205+
repo = _make_repo(tmp_path / "repo")
206+
checkout = _clone(repo, tmp_path / "checkout", "refs/tags/v1.0")
207+
ref = "refs/tags/v1.0"
208+
repo_url = str(repo)
209+
if change == "untracked":
210+
(checkout / "new.txt").write_text("new")
211+
elif change == "ignored":
212+
(checkout / ".git" / "info" / "exclude").write_text("build/\n")
213+
(checkout / "build").mkdir()
214+
(checkout / "build" / "out.txt").write_text("built")
215+
elif change == "other_ref":
216+
_git(checkout, "commit", "--allow-empty", "-m", "Local commit")
217+
elif change == "unknown_ref":
218+
ref = "refs/tags/missing"
219+
else:
220+
repo_url = str(tmp_path / "other-repo")
221+
222+
result = git_checkout_mismatch(checkout_dir=checkout, repo_url=repo_url, ref=ref)
223+
224+
assert result == reason
225+
226+
227+
@needs_git_command
228+
def test_git_checkout_mismatch_rejects_uninitialized_submodule(
229+
tmp_path: pathlib.Path,
230+
) -> None:
231+
sub = _make_repo(tmp_path / "sub")
232+
repo = _make_repo(tmp_path / "repo")
233+
_git(repo, "submodule", "add", str(sub), "sub")
234+
_git(repo, "commit", "-m", "Add submodule")
235+
_git(repo, "tag", "v2.0")
236+
checkout = _clone(repo, tmp_path / "checkout", "refs/tags/v2.0")
237+
assert (
238+
git_checkout_mismatch(
239+
checkout_dir=checkout, repo_url=str(repo), ref="refs/tags/v2.0"
240+
)
241+
is None
242+
)
243+
_git(checkout, "submodule", "deinit", "--force", "sub")
244+
245+
result = git_checkout_mismatch(
246+
checkout_dir=checkout, repo_url=str(repo), ref="refs/tags/v2.0"
247+
)
248+
249+
assert result == "a submodule is not initialized at its recorded commit"
250+
251+
252+
@needs_git_command
253+
def test_git_checkout_mismatch_rejects_non_checkout(tmp_path: pathlib.Path) -> None:
254+
repo = _make_repo(tmp_path / "repo")
255+
plain_dir = tmp_path / "plain"
256+
plain_dir.mkdir()
257+
# A broken ".git" makes Git search parent directories.
258+
nested = repo / "nested"
259+
nested.mkdir()
260+
(nested / ".git").mkdir()
261+
262+
plain_result = git_checkout_mismatch(
263+
checkout_dir=plain_dir, repo_url=str(repo), ref="refs/tags/v1.0"
264+
)
265+
nested_result = git_checkout_mismatch(
266+
checkout_dir=nested, repo_url=str(repo), ref="refs/tags/v1.0"
267+
)
268+
269+
assert plain_result == "it is not a Git checkout"
270+
assert nested_result == "it is not the top of a Git checkout"

0 commit comments

Comments
 (0)