#!/usr/bin/env bash # The build lock serializes compiles into one machine target. Cargo's mtime # freshness also needs an honest source epoch. Equal crate contents inherit # the same epoch across trees, so previous compiles stay warm; changed inputs # advance it. Dependencies and artifacts are never removed. # --run holds the target's cargo lock through preparation AND the command. set -euo pipefail HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" if [ "${1-}" = --run ]; then shift [ "$#" -gt 0 ] || { echo 'cargo-target-guard: --run needs a command' >&2; exit 2; } export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$(bash "$HERE/ci/cargo-target-dir.sh" --ensure shared)}" export COTTON_CARGO_LOCK="$CARGO_TARGET_DIR.lock" exec bash "$HERE/ci/with-cargo-lock.sh" "$@" fi CHECK=0 case "${1-}" in --check) CHECK=1; shift ;; '') ;; *) echo 'usage: cargo-target-guard.sh [--check | --run command...]' >&2; exit 2 ;; esac [ "$#" = 0 ] || exit 2 target="${CARGO_TARGET_DIR:-$(bash "$HERE/ci/cargo-target-dir.sh" shared)}" # Explicit isolated targets (build slots, retained cuts) keep their own policy. [ "$(basename "$target")" = shared ] || exit 0 if [ "$CHECK" = 0 ] && [ "${COTTON_CARGO_LOCK_HELD:-}" != "$target.lock" ]; then echo 'cargo-target-guard: shared target preparation requires its cargo lock; use --run command' >&2 exit 2 fi python3 - "$HERE/../crates" "$target" "$CHECK" <<'PYCODE' import hashlib import json import os from pathlib import Path import sys import time crates, target = Path(sys.argv[1]).resolve(), Path(sys.argv[2]) check = sys.argv[3] == '1' marker = target / '.cotton-source-epochs.json' last_tree = target / '.last-worktree' previous = json.loads(marker.read_text()) if marker.exists() else {} # Adopt the existing guard's timestamps only for the tree it prepared. Its # source timestamps already invalidate every artifact it did not rebuild. prepared_here = last_tree.exists() and last_tree.read_text().strip() == str(crates.parent) common = hashlib.sha256() for name in ('Cargo.toml', 'Cargo.lock'): path = crates / name if path.is_file(): common.update(path.read_bytes()) current, changes = {}, [] for crate in sorted(crates.iterdir()): if not crate.is_dir() or crate.is_symlink() or crate.name.startswith('.') or crate.name == 'target': continue files = [] for directory, dirs, names in os.walk(crate): dirs[:] = sorted(d for d in dirs if d not in ('target', '.git') and not d.startswith('.') and not (Path(directory) / d).is_symlink()) files.extend(Path(directory) / name for name in sorted(names) if not (Path(directory) / name).is_symlink()) digest = common.copy() for path in files: digest.update(str(path.relative_to(crate)).encode() + b'\0') digest.update(hashlib.sha256(path.read_bytes()).digest()) held = previous.get(crate.name, {}) same = held.get('hash') == digest.hexdigest() epoch = held.get('epoch') if same else ( max((path.stat().st_mtime_ns for path in files), default=time.time_ns()) if not previous and prepared_here else time.time_ns()) current[crate.name] = {'hash': digest.hexdigest(), 'epoch': epoch} # Equal contents in another tree inherit the SAME freshness epoch. Built # artifacts newer than it stay warm; artifacts from a partially completed # build still predate it and rebuild, even if that crate was never compiled. changes.extend((path, epoch) for path in files if path.stat().st_mtime_ns != epoch) if check: sys.exit(1 if changes else 0) for path, epoch in changes: os.utime(path, ns=(path.stat().st_atime_ns, epoch)) target.mkdir(parents=True, exist_ok=True) for path, contents in ((marker, json.dumps(current) + '\n'), (last_tree, str(crates.parent) + '\n')): temporary = path.with_suffix('.tmp') temporary.write_text(contents) temporary.replace(path) PYCODE