Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -598,7 +598,8 @@ def cmd_check(args: argparse.Namespace) -> int:
report = sandbox.run_checks(config, wt, progress=lambda command: print(
f"running: {command}", flush=True),
status=lambda message: print(message, flush=True),
checkpoint=lambda partial: _save_report(wt, partial))
checkpoint=lambda partial: _save_report(wt, partial),
workflow=args.config or f"origin/{config.base_branch}:workflow.toml")
except sandbox.SandboxUnavailable as exc:
print(f"sandbox unavailable: {exc}", file=sys.stderr)
return 2
Expand Down
41 changes: 33 additions & 8 deletions src/loopzero/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO
progress: Callable[[str], None] | None = None,
status: Callable[[str], None] | None = None,
checkpoint: Callable[[CheckReport], None] | None = None,
_resolved: bool = False) -> CheckReport:
workflow: str | Path = "workflow.toml", _resolved: bool = False) -> CheckReport:
"""Run checks, stopping at the first failure; status emits only stage metadata.

progress receives each command before launch, as before. Optional status receives
Expand Down Expand Up @@ -179,7 +179,8 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO
for index, command in enumerate(commands):
if progress:
progress(command)
key = _input_key(config, worktree, command, base) if not dirty else None
key = _input_key(config, worktree, command, "" if dirty else base,
status=status, workflow=workflow)
old = previous.get(command)
if key and old and old.input_key == key:
result = old
Expand Down Expand Up @@ -303,19 +304,43 @@ def settings_fingerprint(config: Config, worktree: Path, *, base: str | None = N
return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()


def _input_key(config: Config, worktree: Path, command: str, base: str) -> str | None:
if not base or (command not in config.inputs and "." not in config.inputs.get("*", ())):
return None
paths = (*config.inputs.get(command, ()), *config.inputs.get("*", ()))
def _input_blobs(config: Config, worktree: Path, paths: tuple[str, ...]) -> str | None:
# Empty pathspecs must not accidentally mean the whole tree.
if not paths:
return ""
empty = _git(config, worktree, "hash-object", "-t", "tree", "/dev/null").strip()
try:
blobs = _git(config, worktree, "-c", "core.quotePath=true", "diff-tree", "--no-commit-id",
"--raw", "-r", "--no-abbrev", empty, "HEAD", "--", *paths) if paths else ""
return _git(config, worktree, "-c", "core.quotePath=true", "diff-tree", "--no-commit-id",
"--raw", "-r", "--no-abbrev", empty, "HEAD", "--", *paths)
except OSError as exc:
if exc.errno == errno.E2BIG:
return None
raise


def _input_key(config: Config, worktree: Path, command: str, base: str, *,
status: Callable[[str], None] | None = None,
workflow: str | Path = "workflow.toml") -> str | None:
if command not in config.inputs and "." not in config.inputs.get("*", ()):
return None
if not base and status is None:
return None
entries = {key: config.inputs[key] for key in (command, "*") if key in config.inputs}
try:
blobs = _input_blobs(config, worktree, tuple(path for paths in entries.values() for path in paths))
except (SandboxUnavailable, _proc.ProcTimeout, OSError, ValueError):
if not base:
return None
raise
if blobs == "" and status:
status(f"{workflow}: checks.inputs for {command!r} matches no files in HEAD. "
f"Correct these entries: {entries!r}. Running the check fresh.")
if not blobs or not base:
return None
return _hash_inputs(config, worktree, command, base, blobs)


def _hash_inputs(config: Config, worktree: Path, command: str, base: str, blobs: str) -> str | None:
contents = []
root = worktree.resolve()
try:
Expand Down
37 changes: 37 additions & 0 deletions tests/test_sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -771,6 +771,43 @@ def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, ch
assert report.head == git(git_repo, 'rev-parse', 'HEAD').strip()


@pytest.mark.parametrize("case", ["typo", "empty", "dirty", "no_base"])
def test_unmatched_inputs_run_fresh(git_repo, bwrap_log, fetched_base, case):
(git_repo / ".git/info/exclude").write_text(".loopzero/\n")
command = 'test "$(cat README.md)" = hello'
paths = () if case == "empty" else ("ipnut.txt",)
config = make_config(checks=(command,), inputs={command: paths})
first = sandbox.run_checks(config, git_repo)
assert first.ok
_save_report(git_repo, first)
(git_repo / "README.md").write_text("fail\n")
if case != "dirty":
git(git_repo, "commit", "-qam", "change actual input")
if case == "no_base":
git(git_repo, "update-ref", "-d", "refs/remotes/origin/main")

result = sandbox.run_checks(config, git_repo, status=(messages := []).append)
assert result.results[0].exit_code == 1
assert any("workflow.toml: checks.inputs" in message and repr(paths) in message
for message in messages)


@pytest.mark.parametrize("path", [":(bogus)README.md", "README\0.md", "README.md"])
def test_input_diagnostic_failure_does_not_block_dirty_check(
git_repo, bwrap_log, fetched_base, monkeypatch, path,
):
if path == "README.md":
def timed_out(*args):
raise sandbox._proc.ProcTimeout("input lookup timed out")

monkeypatch.setattr(sandbox, "_input_blobs", timed_out)
(git_repo / "README.md").write_text("dirty\n")
command = 'test "$(cat README.md)" = dirty'
config = make_config(checks=(command,), inputs={command: (path,)})
report = sandbox.run_checks(config, git_repo, status=lambda _: None)
assert report.ok and report.dirty and report.results[0].command == command


def test_local_check_reuse_tracks_checkout_bytes(git_repo, bwrap_log, fetched_base):
(git_repo / ".git/info/exclude").write_text(".loopzero/\n")
path = git_repo / "README.md"
Expand Down
Loading