build(qt): each worktree builds, and keeps its binary, in its own target
This workstation configures ONE Cargo target outside the checkouts for every worktree below the project directory. A build in any worktree therefore replaced the `qbz` another worktree had just built: a parallel session's release build in its own worktree replaced the binary under test in the main one. scripts/qt-target.py now decides where builds go. When the target Cargo resolves lies outside the worktree and nothing pins it (CARGO_TARGET_DIR or CARGO_BUILD_TARGET_DIR), the worktree builds in its own sibling directory, `<target>-worktrees/<worktree>`; rebuilding the same worktree still replaces its own binary. Cargo's default target inside the checkout (macOS, CI, Windows) and explicit overrides are untouched, and no machine path is committed. Two checkouts that share a directory name get a stable suffix instead of one target. qt-run.sh, the runtime gate and direct qt-cargo.py builds and tests all use it. qt-run.sh prints the target and the binary path, and re-points crates/target after each successful build, never over a real directory. The aarch64 scripts build into and install from the same target, and the qbzd acceptance script names the build command that lands its binary there. The first build of a profile in a new worktree target is seeded from the shared target with copy-on-write clones, skipping incremental caches: Cargo rewrites moved build-script paths through root-output (custom_build.rs, "rewrite paths if the target directory has been moved"), so unchanged crates are not compiled again and no data is duplicated. Without clone support nothing is copied and Cargo builds from scratch. The resolution and shortcut handling start from the uncommitted draft in the build-storage-layout worktree. Verified on the main worktree: seeded from the shared release target, Cargo found everything fresh in two seconds, and crates/target now points at the worktree's own target. 33 build-gate tests cover derivation, overrides, name collisions, linking, seeding and the runner end to end. cc
This commit is contained in:
8 files changed
+541
-7
No files matched your search
@@ -89,8 +89,11 @@ case "$arch" in
|
||||
else jobs="$(nproc)"; fi
|
||||
say "RAM ${mem_mb} MB -> CARGO_BUILD_JOBS=${jobs}"
|
||||
# No RUSTFLAGS, no mold, stable: same cache rule as qt-run.sh.
|
||||
# The target qt-cargo.py builds in (scripts/qt-target.py), resolved once.
|
||||
CARGO_TARGET_DIR="$(python3 scripts/qt-target.py resolve)"
|
||||
export CARGO_TARGET_DIR
|
||||
CARGO_BUILD_JOBS="$jobs" CARGO_INCREMENTAL=0 python3 scripts/qt-cargo.py build --release --manifest-path crates/Cargo.toml -p qbz-qt
|
||||
install -Dm755 "crates/target/release/qbz" "$OUT"
|
||||
install -Dm755 "$CARGO_TARGET_DIR/release/qbz" "$OUT"
|
||||
;;
|
||||
x86_64 | amd64)
|
||||
die "CROSS mode is not supported for the Qt binary (see the header: cxx-qt \
|
||||
|
||||
@@ -48,8 +48,12 @@ case "$arch" in
|
||||
else
|
||||
echo "[qbzd-aarch64] non-apt distro: install the equivalents of: ${DEPS[*]}" >&2
|
||||
fi
|
||||
# This worktree's own target (scripts/qt-target.py): Cargo's default in a
|
||||
# plain checkout, a per-worktree sibling when the host shares one target.
|
||||
CARGO_TARGET_DIR="$(python3 scripts/qt-target.py resolve)"
|
||||
export CARGO_TARGET_DIR
|
||||
( cd crates && cargo build --release -p qbzd )
|
||||
install -Dm755 "crates/target/release/qbzd" "$OUT"
|
||||
install -Dm755 "$CARGO_TARGET_DIR/release/qbzd" "$OUT"
|
||||
;;
|
||||
x86_64 | amd64)
|
||||
echo "[qbzd-aarch64] CROSS-compile from $arch via cross (Docker)"
|
||||
@@ -65,8 +69,12 @@ case "$arch" in
|
||||
export CROSS_CONTAINER_OPTS="${CROSS_CONTAINER_OPTS:---memory=8g --memory-swap=12g}"
|
||||
# crates/Cross.toml injects the arm64 dev libs into the image (the daemon's
|
||||
# set; the Qt desktop is not cross-built, see build-aarch64-linux.sh).
|
||||
# cross mounts CARGO_TARGET_DIR into the container: the worktree's own
|
||||
# target here too, never one another worktree also builds into.
|
||||
CARGO_TARGET_DIR="$(python3 scripts/qt-target.py resolve)"
|
||||
export CARGO_TARGET_DIR
|
||||
( cd crates && cross build --release --target "$TARGET" -p qbzd )
|
||||
install -Dm755 "crates/target/$TARGET/release/qbzd" "$OUT"
|
||||
install -Dm755 "$CARGO_TARGET_DIR/$TARGET/release/qbzd" "$OUT"
|
||||
;;
|
||||
*)
|
||||
echo "[qbzd-aarch64] ERROR: unsupported build host arch: $arch" >&2
|
||||
|
||||
@@ -31,7 +31,7 @@ fail() { echo "FAIL: $1" >&2; exit 1; }
|
||||
command -v curl >/dev/null 2>&1 || fail "curl is required"
|
||||
command -v python3 >/dev/null 2>&1 || fail "python3 is required (status/ping/info shape checks)"
|
||||
command -v timeout >/dev/null 2>&1 || fail "timeout (coreutils) is required"
|
||||
[ -x "$QBZD_BIN" ] || fail "qbzd binary not found/executable at $QBZD_BIN -- build it first (release, on its own: cargo build --release -p qbzd)"
|
||||
[ -x "$QBZD_BIN" ] || fail "qbzd binary not found/executable at $QBZD_BIN -- build it first (release, on its own, into this worktree's target: python3 scripts/qt-cargo.py build --release --manifest-path crates/Cargo.toml -p qbzd)"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Isolated scratch profile root. NEVER the real daemon/desktop roots: dirs::
|
||||
|
||||
@@ -12,9 +12,15 @@ Use this entry point for Qt builds/tests, including direct Cargo invocations:
|
||||
No target cleanup, profile changes, or RUSTFLAGS: a content-derived, unused
|
||||
C++ define invalidates cc-rs consumers when the SDK changes, in either profile
|
||||
and with any Rust toolchain. Existing CXXFLAGS (including MSVC flags) survive.
|
||||
|
||||
Where Cargo builds follows scripts/qt-target.py: a host-level target shared by
|
||||
every worktree becomes this worktree's own sibling of it, so a direct build or
|
||||
test here cannot replace a binary another worktree built. An explicit
|
||||
CARGO_TARGET_DIR, or a target inside the checkout, is left to Cargo.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
@@ -112,12 +118,56 @@ def cargo_environment(env):
|
||||
return result, version, fingerprint
|
||||
|
||||
|
||||
def load_targets():
|
||||
# A hyphenated sibling loaded by path: without this, every build would leave
|
||||
# an untracked scripts/__pycache__ in the checkout.
|
||||
sys.dont_write_bytecode = True
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"qt_target", Path(__file__).with_name("qt-target.py"))
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def manifest_argument(arguments):
|
||||
for index, argument in enumerate(arguments):
|
||||
if argument == "--manifest-path" and index + 1 < len(arguments):
|
||||
return Path(arguments[index + 1])
|
||||
if argument.startswith("--manifest-path="):
|
||||
return Path(argument.split("=", 1)[1])
|
||||
return None
|
||||
|
||||
|
||||
def target_environment(env, arguments, targets=None):
|
||||
"""`env` with CARGO_TARGET_DIR set to this worktree's own target, when the
|
||||
target Cargo would use is shared with other worktrees (qt-target.py)."""
|
||||
targets = targets or load_targets()
|
||||
if targets.explicit(env):
|
||||
return env
|
||||
try:
|
||||
metadata = targets.cargo_metadata(manifest_argument(arguments), dict(env))
|
||||
configured = Path(metadata["target_directory"]).resolve()
|
||||
target = targets.worktree_target(
|
||||
configured, targets.worktree_root(metadata["workspace_root"]), env)
|
||||
except (OSError, subprocess.SubprocessError, KeyError, ValueError) as error:
|
||||
print(f"[qt-cargo] target not resolved ({error}); Cargo's own choice stands",
|
||||
file=sys.stderr, flush=True)
|
||||
return env
|
||||
if target == configured:
|
||||
return env
|
||||
result = dict(env)
|
||||
result["CARGO_TARGET_DIR"] = str(target)
|
||||
print(f"[qt-cargo] worktree target {target}", file=sys.stderr, flush=True)
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
raise RuntimeError("usage: qt-cargo.py <cargo subcommand> [arguments...]")
|
||||
env, version, fingerprint = cargo_environment(os.environ)
|
||||
print(f"[qt-cargo] Qt {version}, SDK {fingerprint}, qmake={env['QMAKE']}",
|
||||
file=sys.stderr, flush=True)
|
||||
env = target_environment(env, sys.argv[2:])
|
||||
# subprocess.run, NOT os.execvpe: on Windows os.exec* is emulated (spawn +
|
||||
# terminate) and segfaulted here — the release-windows build died with
|
||||
# "Segmentation fault ... exit code 139" right after this line on
|
||||
|
||||
+35
-2
@@ -33,6 +33,16 @@
|
||||
# run BEFORE the build — failing in one second beats failing after two minutes,
|
||||
# or worse, at the owner's smoke. NO_AUDIT=1 skips them.
|
||||
#
|
||||
# ─── EACH WORKTREE BUILDS IN ITS OWN TARGET ─────────────────────────────────
|
||||
# scripts/qt-target.py decides where. With Cargo's default target (inside the
|
||||
# checkout: macOS, CI) nothing changes. When the host configures ONE target
|
||||
# outside the checkout for every worktree, this worktree builds in its own
|
||||
# sibling of it, `<target>-worktrees/<worktree>`, so a build in another worktree
|
||||
# can never replace the binary built here; rebuilding THIS worktree still does.
|
||||
# Its first build of a profile is seeded from the shared target with
|
||||
# copy-on-write clones, and crates/target is re-pointed after each successful
|
||||
# build. An explicit CARGO_TARGET_DIR is used exactly as given.
|
||||
#
|
||||
# Usage: ./scripts/qt-run.sh [extra app args]
|
||||
# DEBUG=1 ./scripts/qt-run.sh # debug profile (the binary the gate uses)
|
||||
# NORUN=1 ./scripts/qt-run.sh # build only, don't exec
|
||||
@@ -127,7 +137,6 @@ if [[ "${DEBUG:-0}" == 1 ]]; then
|
||||
else
|
||||
PROFILE=release; PROFILE_ARGS=(--release)
|
||||
fi
|
||||
BIN="${CARGO_TARGET_DIR:-crates/target}/${PROFILE}/qbz"
|
||||
|
||||
# --- ONE BUILD AT A TIME, BOX-WIDE ------------------------------------------
|
||||
# Not paranoia: a Slint `qbz-ui` rustc in another worktree peaks 20-30 GB on a
|
||||
@@ -141,6 +150,13 @@ if [[ "${FORCE:-0}" != 1 ]]; then
|
||||
fi
|
||||
fi
|
||||
|
||||
# --- Where this worktree builds (see the header) -----------------------------
|
||||
# The PHYSICAL path: moc/cc-rs resolve includes wrongly through the crates/target
|
||||
# symlink.
|
||||
CARGO_TARGET_DIR="$(python3 scripts/qt-target.py resolve)" || die "could not resolve the Cargo target directory"
|
||||
export CARGO_TARGET_DIR
|
||||
BIN="${CARGO_TARGET_DIR}/${PROFILE}/qbz"
|
||||
|
||||
# --- The QML audits (fail fast; cargo cannot see QML) ------------------------
|
||||
if [[ "${NO_AUDIT:-0}" != 1 ]]; then
|
||||
if [[ -d "${AUDIT_DIR}" ]] && command -v python3 >/dev/null 2>&1; then
|
||||
@@ -198,6 +214,17 @@ eta_secs=0
|
||||
|
||||
avail_mb=$(mem_avail_mb)
|
||||
say "profile=${PROFILE} jobs=${CARGO_BUILD_JOBS} avail=${avail_mb}MB rustflags='${RUSTFLAGS:-}'"
|
||||
say "target=${CARGO_TARGET_DIR}"
|
||||
|
||||
# A worktree target's first build of a profile starts from the shared target's
|
||||
# artifacts (copy-on-write, nothing duplicated) instead of from nothing. After
|
||||
# the one-build guard on purpose: never clone a target another build is writing.
|
||||
seed_profiles=("${PROFILE}")
|
||||
[[ "${TEST:-0}" == 1 && "${PROFILE}" != debug ]] && seed_profiles+=(debug)
|
||||
if [[ -z "$(other_builds)" ]]; then
|
||||
python3 scripts/qt-target.py seed --target-dir "${CARGO_TARGET_DIR}" "${seed_profiles[@]}" \
|
||||
|| warn "could not seed ${CARGO_TARGET_DIR}; Cargo builds it from scratch"
|
||||
fi
|
||||
|
||||
# --- Start banner ------------------------------------------------------------
|
||||
build_start=$(date +%s)
|
||||
@@ -232,6 +259,11 @@ fi
|
||||
# --- The build ---------------------------------------------------------------
|
||||
python3 scripts/qt-cargo.py build "${PROFILE_ARGS[@]}" --manifest-path crates/Cargo.toml -p qbz-qt
|
||||
|
||||
# The familiar crates/target path follows the target this worktree just built,
|
||||
# and only after a successful build.
|
||||
python3 scripts/qt-target.py link --target-dir "${CARGO_TARGET_DIR}" \
|
||||
|| warn "crates/target was not re-pointed; the binary is ${BIN}"
|
||||
|
||||
# --- Stop the ticker, record the duration, print the final banner ------------
|
||||
[[ -n "${tick_pid}" ]] && { kill "${tick_pid}" 2>/dev/null || true; wait "${tick_pid}" 2>/dev/null || true; }
|
||||
trap - EXIT
|
||||
@@ -239,6 +271,7 @@ build_secs=$(( $(date +%s) - build_start ))
|
||||
mkdir -p "${eta_dir}" 2>/dev/null && printf '%s\n' "${build_secs}" > "${eta_file}" 2>/dev/null || true
|
||||
printf '%s[qt-run] ✔ build finished %s · took %s (%s)%s\n' \
|
||||
"${C_BOLD}${C_GRN}" "$(date '+%H:%M:%S')" "$(fmt_dur "${build_secs}")" "${PROFILE}" "${C_RST}"
|
||||
say "binary=${BIN}"
|
||||
|
||||
# --- Tests (opt-in) ----------------------------------------------------------
|
||||
if [[ "${TEST:-0}" == 1 ]]; then
|
||||
@@ -260,7 +293,7 @@ if [[ "${SMOKE:-0}" == 1 ]]; then
|
||||
# template path so the two agree.
|
||||
log="$(mktemp "${TMPDIR:-/tmp}/qbz-qt-smoke-XXXXXX")"
|
||||
say "offscreen smoke (75s max) → ${log}"
|
||||
QT_QPA_PLATFORM=offscreen RUST_LOG=info run_timeout 75 "./${BIN}" > "${log}" 2>&1 || true
|
||||
QT_QPA_PLATFORM=offscreen RUST_LOG=info run_timeout 75 "${BIN}" > "${log}" 2>&1 || true
|
||||
# A log this short means the process never really started (the macOS
|
||||
# `timeout`-not-found case did exactly that). Zero complaints in an empty log
|
||||
# is not a pass.
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
set -euo pipefail
|
||||
cd "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/.."
|
||||
export QBZ_PREBUILT_SHADERS=1
|
||||
# The same target qt-run.sh builds in: this worktree's own when the host shares
|
||||
# one target across worktrees, Cargo's default otherwise (scripts/qt-target.py).
|
||||
CARGO_TARGET_DIR="$(python3 scripts/qt-target.py resolve)"
|
||||
export CARGO_TARGET_DIR
|
||||
bash scripts/test-search-local-qml.sh
|
||||
bash scripts/test-updates-qml.sh
|
||||
bash scripts/test-playback-cache-qml.sh
|
||||
@@ -23,7 +27,7 @@ node scripts/test_qt_kiosk_navigation.mjs
|
||||
node scripts/test_qt_kiosk_feedback.mjs
|
||||
node scripts/test_qt_exclusive_gate.mjs
|
||||
python3 scripts/qt-cargo.py test --manifest-path crates/Cargo.toml -p qbz-qt --no-fail-fast
|
||||
target_dir="${CARGO_TARGET_DIR:-$PWD/crates/target}"
|
||||
target_dir="$CARGO_TARGET_DIR"
|
||||
logs="$(mktemp -d "${TMPDIR:-/tmp}/qbz-qt-gate-XXXXXX")"
|
||||
printf '[qt-gate] startup logs: %s\n' "$logs"
|
||||
for profile in debug release; do
|
||||
@@ -32,5 +36,7 @@ for profile in debug release; do
|
||||
python3 scripts/qt-cargo.py build "${args[@]}" --manifest-path crates/Cargo.toml -p qbz-qt
|
||||
python3 scripts/qt-smoke.py "$target_dir/$profile/qbz" --log "$logs/$profile.log"
|
||||
done
|
||||
python3 scripts/qt-target.py link --target-dir "$target_dir" \
|
||||
|| printf '[qt-gate] crates/target not re-pointed; binaries are in %s\n' "$target_dir" >&2
|
||||
# A healthy offscreen bus cannot expose Qt's synchronous xcb D-Bus startup.
|
||||
python3 scripts/qt-smoke.py "$target_dir/release/qbz" --silent-bus --log "$logs/release-silent-bus.log"
|
||||
@@ -0,0 +1,213 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Each worktree's own physical Cargo target, and its crates/target shortcut.
|
||||
|
||||
A host may put Cargo's target OUTSIDE the checkout, on a build disk shared by
|
||||
every worktree below one project directory. Then every worktree compiled into
|
||||
the SAME directory, and a build in any of them replaced the `qbz` binary another
|
||||
worktree had just built and was running or smoke-testing (2026-09-14: a parallel
|
||||
session's release build replaced the binary under test in the main worktree).
|
||||
|
||||
So when the target Cargo resolves lies outside the worktree, and nobody pinned it
|
||||
explicitly with CARGO_TARGET_DIR or CARGO_BUILD_TARGET_DIR, the worktree builds
|
||||
in its own sibling directory instead:
|
||||
|
||||
<configured target>-worktrees/<worktree directory name>
|
||||
|
||||
Building the same worktree again still replaces its own binary; other worktrees
|
||||
keep theirs. A target inside the checkout (Cargo's default: macOS, CI, Windows)
|
||||
and an explicit override are returned unchanged. No machine-specific path lives
|
||||
here: Cargo configuration and the environment choose the storage.
|
||||
|
||||
The first build of a profile in a new worktree target is seeded from the shared
|
||||
target with copy-on-write clones (`cp --reflink=always`), so the registry crates
|
||||
that did not change are not compiled again and no data is duplicated; where the
|
||||
filesystem cannot clone, nothing is copied and Cargo simply builds from scratch.
|
||||
Never remove a real target directory to make room for a symlink.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
EXPLICIT_ENV = ("CARGO_TARGET_DIR", "CARGO_BUILD_TARGET_DIR")
|
||||
MARKER = ".qbz-worktree"
|
||||
SUFFIX = "-worktrees"
|
||||
# Workspace crates recompile per worktree anyway (their metadata hash includes
|
||||
# the checkout path), and incremental caches are only kept for those.
|
||||
SEED_SKIP = {"incremental"}
|
||||
|
||||
|
||||
def cargo_metadata(manifest=None, env=None):
|
||||
command = ["cargo", "metadata", "--no-deps", "--format-version", "1"]
|
||||
if manifest is not None:
|
||||
command += ["--manifest-path", str(manifest)]
|
||||
return json.loads(subprocess.check_output(command, text=True, env=env))
|
||||
|
||||
|
||||
def worktree_root(workspace_root):
|
||||
workspace_root = Path(workspace_root)
|
||||
try:
|
||||
top = subprocess.check_output(
|
||||
["git", "-C", str(workspace_root), "rev-parse", "--show-toplevel"],
|
||||
text=True, stderr=subprocess.DEVNULL).strip()
|
||||
if top:
|
||||
return Path(top).resolve()
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
pass
|
||||
# This repository keeps its Cargo workspace in crates/.
|
||||
return workspace_root.resolve().parent
|
||||
|
||||
|
||||
def is_inside(path, root):
|
||||
try:
|
||||
Path(path).relative_to(root)
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def explicit(env):
|
||||
return any(env.get(name) for name in EXPLICIT_ENV)
|
||||
|
||||
|
||||
def worktree_target(configured, root, env):
|
||||
"""The target this worktree builds in (see the module docstring)."""
|
||||
configured = Path(configured).resolve()
|
||||
root = Path(root).resolve()
|
||||
if explicit(env) or is_inside(configured, root):
|
||||
return configured
|
||||
name = re.sub(r"[^A-Za-z0-9._-]+", "-", root.name).strip("-") or "worktree"
|
||||
candidate = configured.parent / f"{configured.name}{SUFFIX}" / name
|
||||
try:
|
||||
claimed = (candidate / MARKER).read_text().strip()
|
||||
except OSError:
|
||||
claimed = ""
|
||||
if claimed and claimed != str(root):
|
||||
# Two checkouts with the same directory name: the second one gets a
|
||||
# stable suffix instead of sharing (and overwriting) the first.
|
||||
digest = hashlib.sha1(str(root).encode()).hexdigest()[:8]
|
||||
candidate = candidate.with_name(f"{name}-{digest}")
|
||||
return candidate
|
||||
|
||||
|
||||
def shared_target(manifest=None, env=None):
|
||||
"""Cargo's configured target with any explicit override removed."""
|
||||
env = dict(os.environ if env is None else env)
|
||||
for name in EXPLICIT_ENV:
|
||||
env.pop(name, None)
|
||||
return Path(cargo_metadata(manifest, env)["target_directory"]).resolve()
|
||||
|
||||
|
||||
def resolve_target(manifest=None, env=None):
|
||||
env = os.environ if env is None else env
|
||||
metadata = cargo_metadata(manifest, dict(env))
|
||||
root = worktree_root(metadata["workspace_root"])
|
||||
return worktree_target(metadata["target_directory"], root, env)
|
||||
|
||||
|
||||
def is_worktree_target(target, shared):
|
||||
target = Path(target).resolve()
|
||||
shared = Path(shared).resolve()
|
||||
return target.parent == shared.parent / f"{shared.name}{SUFFIX}"
|
||||
|
||||
|
||||
def link_target(manifest, target, root=None):
|
||||
target = Path(target).resolve()
|
||||
alias = Path(manifest).resolve().parent / "target"
|
||||
if not target.is_dir():
|
||||
raise RuntimeError(f"build target does not exist: {target}")
|
||||
if root is not None and target.parent.name.endswith(SUFFIX):
|
||||
# Claim this worktree target for its checkout (see worktree_target).
|
||||
(target / MARKER).write_text(f"{Path(root).resolve()}\n")
|
||||
if alias.resolve() == target:
|
||||
return
|
||||
if alias.exists() and not alias.is_symlink():
|
||||
raise RuntimeError(f"preserving existing target directory: {alias}; migrate it before linking")
|
||||
if os.name == "nt":
|
||||
# A normal Windows Cargo target already uses alias. External targets
|
||||
# must remain usable without requiring symlink privileges in CI.
|
||||
print(f"[qt-target] external target: {target} (shortcut not created on Windows)", file=sys.stderr)
|
||||
return
|
||||
temporary = alias.with_name(f".target-link-{uuid.uuid4().hex}")
|
||||
try:
|
||||
temporary.symlink_to(target, target_is_directory=True)
|
||||
temporary.replace(alias)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def seed_target(target, shared, profiles, clone=None):
|
||||
"""Clone each missing profile directory of `shared` into `target`.
|
||||
|
||||
Returns the profiles seeded. A profile already present in `target`, absent
|
||||
from `shared`, or that the filesystem cannot clone is left alone.
|
||||
"""
|
||||
target = Path(target)
|
||||
shared = Path(shared)
|
||||
clone = clone or reflink_clone
|
||||
seeded = []
|
||||
if target.resolve() == shared.resolve() or not is_worktree_target(target, shared):
|
||||
return seeded
|
||||
for profile in profiles:
|
||||
source = shared / profile
|
||||
destination = target / profile
|
||||
if destination.exists() or not source.is_dir():
|
||||
continue
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
staging = target / f".seed-{profile}-{uuid.uuid4().hex}"
|
||||
staging.mkdir()
|
||||
try:
|
||||
entries = sorted(entry for entry in source.iterdir() if entry.name not in SEED_SKIP)
|
||||
if entries:
|
||||
clone(entries, staging)
|
||||
# Appears whole or not at all: an interrupted clone never looks
|
||||
# like a finished target to Cargo.
|
||||
staging.rename(destination)
|
||||
seeded.append(profile)
|
||||
except (OSError, subprocess.SubprocessError) as error:
|
||||
print(f"[qt-target] not seeding {profile} ({error}); Cargo builds it from scratch", file=sys.stderr)
|
||||
finally:
|
||||
if staging.exists():
|
||||
shutil.rmtree(staging, ignore_errors=True)
|
||||
return seeded
|
||||
|
||||
|
||||
def reflink_clone(entries, destination):
|
||||
if not sys.platform.startswith("linux"):
|
||||
raise OSError("copy-on-write clones are only used with GNU cp")
|
||||
subprocess.run(["cp", "-a", "--reflink=always", *map(str, entries), str(destination)],
|
||||
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("operation", choices=["resolve", "link", "seed"])
|
||||
parser.add_argument("profiles", nargs="*", help="seed: profile directories, e.g. release debug")
|
||||
parser.add_argument("--manifest-path", default="crates/Cargo.toml", type=Path)
|
||||
parser.add_argument("--target-dir", type=Path)
|
||||
args = parser.parse_args()
|
||||
if args.operation == "resolve":
|
||||
print(args.target_dir.resolve() if args.target_dir else resolve_target(args.manifest_path))
|
||||
return
|
||||
target = args.target_dir.resolve() if args.target_dir else resolve_target(args.manifest_path)
|
||||
if args.operation == "link":
|
||||
root = worktree_root(Path(args.manifest_path).resolve().parent)
|
||||
link_target(args.manifest_path, target, root)
|
||||
return
|
||||
shared = shared_target(args.manifest_path)
|
||||
for profile in seed_target(target, shared, args.profiles or ["release"]):
|
||||
print(f"[qt-target] seeded {profile} from {shared / profile}", file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (OSError, RuntimeError, subprocess.SubprocessError, KeyError, ValueError) as error:
|
||||
print(f"[qt-target] {error}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -1,9 +1,14 @@
|
||||
#!/usr/bin/env python3
|
||||
"""SDK-cache and crash-aware smoke regressions; no Qt or Cargo build needed."""
|
||||
|
||||
import contextlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
import sys
|
||||
@@ -21,6 +26,222 @@ def load(name, filename):
|
||||
|
||||
qt = load("qt_cargo", "qt-cargo.py")
|
||||
smoke = load("qt_smoke", "qt-smoke.py")
|
||||
targets = load("qt_target", "qt-target.py")
|
||||
|
||||
|
||||
@unittest.skipIf(os.name == "nt", "unprivileged Windows symlinks may be unavailable")
|
||||
class TargetTests(unittest.TestCase):
|
||||
"""Each worktree keeps its own binaries when the host shares one target."""
|
||||
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name).resolve()
|
||||
self.worktree = self.root / "checkouts" / "main-tree"
|
||||
self.crates = self.worktree / "crates"
|
||||
self.crates.mkdir(parents=True)
|
||||
self.manifest = self.crates / "Cargo.toml"
|
||||
self.manifest.touch()
|
||||
self.shared = self.root / "nvme" / "qbz"
|
||||
(self.shared / "release" / "deps").mkdir(parents=True)
|
||||
(self.shared / "release" / "incremental").mkdir()
|
||||
(self.shared / "release" / "deps" / "libdep.rlib").write_bytes(b"registry crate")
|
||||
(self.shared / "release" / "incremental" / "session").write_bytes(b"workspace cache")
|
||||
(self.shared / "release" / "qbz").write_bytes(b"another worktree's binary")
|
||||
self.derived = self.root / "nvme" / "qbz-worktrees" / "main-tree"
|
||||
|
||||
def test_shared_host_target_becomes_this_worktrees_own_sibling(self):
|
||||
self.assertEqual(targets.worktree_target(self.shared, self.worktree, {}), self.derived)
|
||||
other = self.root / "checkouts" / "codex-tree"
|
||||
self.assertEqual(targets.worktree_target(self.shared, other, {}),
|
||||
self.root / "nvme" / "qbz-worktrees" / "codex-tree")
|
||||
|
||||
def test_explicit_override_and_checkout_target_are_used_as_given(self):
|
||||
for name in targets.EXPLICIT_ENV:
|
||||
with self.subTest(env=name):
|
||||
self.assertEqual(targets.worktree_target(self.shared, self.worktree, {name: "/pinned"}),
|
||||
self.shared)
|
||||
inside = self.crates / "target"
|
||||
self.assertEqual(targets.worktree_target(inside, self.worktree, {}), inside)
|
||||
|
||||
def test_two_checkouts_with_one_directory_name_never_share_a_target(self):
|
||||
self.derived.mkdir(parents=True)
|
||||
(self.derived / targets.MARKER).write_text(str(self.root / "elsewhere" / "main-tree") + "\n")
|
||||
second = targets.worktree_target(self.shared, self.worktree, {})
|
||||
self.assertNotEqual(second, self.derived)
|
||||
self.assertTrue(second.name.startswith("main-tree-"))
|
||||
self.assertEqual(second, targets.worktree_target(self.shared, self.worktree, {}))
|
||||
(self.derived / targets.MARKER).write_text(str(self.worktree) + "\n")
|
||||
self.assertEqual(targets.worktree_target(self.shared, self.worktree, {}), self.derived)
|
||||
|
||||
def test_resolve_reads_cargo_metadata_for_the_manifest(self):
|
||||
metadata = {"target_directory": str(self.shared), "workspace_root": str(self.crates)}
|
||||
with patch.object(targets, "cargo_metadata", return_value=metadata) as cargo, \
|
||||
patch.object(targets, "worktree_root", return_value=self.worktree):
|
||||
self.assertEqual(targets.resolve_target(self.manifest, {}), self.derived)
|
||||
self.assertEqual(cargo.call_args.args[0], self.manifest)
|
||||
|
||||
def test_link_keeps_the_familiar_path_and_claims_the_worktree_target(self):
|
||||
(self.derived / "release").mkdir(parents=True)
|
||||
(self.derived / "release" / "qbz").write_bytes(b"this worktree's binary")
|
||||
targets.link_target(self.manifest, self.derived, self.worktree)
|
||||
targets.link_target(self.manifest, self.derived, self.worktree)
|
||||
alias = self.crates / "target"
|
||||
self.assertTrue(alias.is_symlink())
|
||||
self.assertEqual((alias / "release" / "qbz").read_bytes(), b"this worktree's binary")
|
||||
self.assertEqual((self.derived / targets.MARKER).read_text().strip(), str(self.worktree))
|
||||
# A pinned target is linked but never claimed.
|
||||
targets.link_target(self.manifest, self.shared, self.worktree)
|
||||
self.assertFalse((self.shared / targets.MARKER).exists())
|
||||
|
||||
def test_real_directory_is_never_removed(self):
|
||||
alias = self.crates / "target"
|
||||
alias.mkdir()
|
||||
sentinel = alias / "keep"
|
||||
sentinel.write_text("preserve")
|
||||
targets.link_target(self.manifest, alias)
|
||||
with self.assertRaisesRegex(RuntimeError, "preserving"):
|
||||
targets.link_target(self.manifest, self.shared)
|
||||
self.assertEqual(sentinel.read_text(), "preserve")
|
||||
self.assertFalse(alias.is_symlink())
|
||||
|
||||
def test_old_shortcut_is_replaced_but_a_missing_build_cannot_replace_it(self):
|
||||
alias = self.crates / "target"
|
||||
alias.symlink_to(self.root / "old", target_is_directory=True)
|
||||
with self.assertRaisesRegex(RuntimeError, "does not exist"):
|
||||
targets.link_target(self.manifest, self.root / "missing")
|
||||
self.assertEqual(os.readlink(alias), str(self.root / "old"))
|
||||
targets.link_target(self.manifest, self.shared)
|
||||
self.assertEqual(alias.resolve(), self.shared)
|
||||
|
||||
@staticmethod
|
||||
def copy(entries, destination):
|
||||
for entry in entries:
|
||||
if entry.is_dir():
|
||||
shutil.copytree(entry, destination / entry.name)
|
||||
else:
|
||||
shutil.copy2(entry, destination / entry.name)
|
||||
|
||||
def test_seed_clones_a_missing_profile_once_and_skips_incremental(self):
|
||||
self.assertEqual(targets.seed_target(self.derived, self.shared, ["release", "debug"], self.copy),
|
||||
["release"])
|
||||
self.assertEqual((self.derived / "release" / "deps" / "libdep.rlib").read_bytes(), b"registry crate")
|
||||
self.assertFalse((self.derived / "release" / "incremental").exists())
|
||||
(self.derived / "release" / "qbz").write_bytes(b"this worktree's binary")
|
||||
self.assertEqual(targets.seed_target(self.derived, self.shared, ["release"], self.copy), [])
|
||||
self.assertEqual((self.derived / "release" / "qbz").read_bytes(), b"this worktree's binary")
|
||||
self.assertEqual((self.shared / "release" / "qbz").read_bytes(), b"another worktree's binary")
|
||||
|
||||
def test_seed_never_touches_pinned_targets_and_leaves_no_partial_clone(self):
|
||||
pinned = self.root / "pinned"
|
||||
self.assertEqual(targets.seed_target(pinned, self.shared, ["release"], self.copy), [])
|
||||
self.assertFalse(pinned.exists())
|
||||
self.assertEqual(targets.seed_target(self.shared, self.shared, ["release"], self.copy), [])
|
||||
|
||||
def broken(entries, destination):
|
||||
(destination / "half").write_bytes(b"partial")
|
||||
raise OSError("clone not supported")
|
||||
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertEqual(targets.seed_target(self.derived, self.shared, ["release"], broken), [])
|
||||
self.assertEqual(list(self.derived.iterdir()), [])
|
||||
|
||||
|
||||
class CargoTargetEnvironmentTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name).resolve()
|
||||
self.worktree = self.root / "tree"
|
||||
self.shared = self.root / "shared" / "qbz"
|
||||
self.metadata = {"target_directory": str(self.shared), "workspace_root": str(self.worktree / "crates")}
|
||||
for name, value in (("cargo_metadata", lambda *_: self.metadata),
|
||||
("worktree_root", lambda *_: self.worktree)):
|
||||
mock = patch.object(targets, name, side_effect=value)
|
||||
mock.start()
|
||||
self.addCleanup(mock.stop)
|
||||
|
||||
def environment(self, env, arguments=("--manifest-path", "crates/Cargo.toml")):
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
return qt.target_environment(env, list(arguments), targets)
|
||||
|
||||
def test_direct_builds_and_tests_use_the_worktree_target(self):
|
||||
env = self.environment({"PATH": "/bin"})
|
||||
self.assertEqual(env["CARGO_TARGET_DIR"], str(self.root / "shared" / "qbz-worktrees" / "tree"))
|
||||
self.assertEqual(targets.cargo_metadata.call_args.args[0], Path("crates/Cargo.toml"))
|
||||
|
||||
def test_explicit_and_checkout_targets_are_left_to_cargo(self):
|
||||
pinned = {"CARGO_TARGET_DIR": "/pinned"}
|
||||
self.assertIs(self.environment(pinned), pinned)
|
||||
self.metadata["target_directory"] = str(self.worktree / "crates" / "target")
|
||||
plain = {"PATH": "/bin"}
|
||||
self.assertIs(self.environment(plain), plain)
|
||||
|
||||
def test_unresolvable_metadata_keeps_cargos_own_choice(self):
|
||||
targets.cargo_metadata.side_effect = subprocess.CalledProcessError(101, "cargo")
|
||||
plain = {"PATH": "/bin"}
|
||||
self.assertIs(self.environment(plain), plain)
|
||||
|
||||
def test_manifest_argument_forms(self):
|
||||
self.assertEqual(qt.manifest_argument(["-p", "qbz-qt", "--manifest-path", "a/Cargo.toml"]),
|
||||
Path("a/Cargo.toml"))
|
||||
self.assertEqual(qt.manifest_argument(["--manifest-path=b/Cargo.toml"]), Path("b/Cargo.toml"))
|
||||
self.assertIsNone(qt.manifest_argument(["--release"]))
|
||||
|
||||
|
||||
@unittest.skipUnless(os.name == "posix" and shutil.which("bash"), "requires bash")
|
||||
class RunnerTargetTests(unittest.TestCase):
|
||||
def test_runner_builds_in_the_worktree_target_links_after_success_and_runs_it(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
base = Path(directory).resolve()
|
||||
root = base / "main tree"
|
||||
scripts = root / "scripts"
|
||||
scripts.mkdir(parents=True)
|
||||
(root / "crates").mkdir()
|
||||
(root / "crates/Cargo.toml").touch()
|
||||
shared = base / "shared target"
|
||||
expected = base / "shared target-worktrees" / "main-tree"
|
||||
for filename in ("qt-run.sh", "qt-target.py"):
|
||||
shutil.copyfile(Path(__file__).with_name(filename), scripts / filename)
|
||||
fake_bin = base / "bin"
|
||||
fake_bin.mkdir()
|
||||
cargo = fake_bin / "cargo"
|
||||
cargo.write_text('#!/bin/sh\n[ "$FAIL_METADATA" = 1 ] && exit 7\nprintf \'%s\\n\' "$TARGET_METADATA"\n')
|
||||
cargo.chmod(0o755)
|
||||
git = fake_bin / "git"
|
||||
git.write_text("#!/bin/sh\nexit 128\n")
|
||||
git.chmod(0o755)
|
||||
(scripts / "qt-cargo.py").write_text(
|
||||
'import os, pathlib, sys\n'
|
||||
'target = pathlib.Path(os.environ["CARGO_TARGET_DIR"])\n'
|
||||
'assert target == pathlib.Path(os.environ["EXPECTED_TARGET"]), target\n'
|
||||
'if os.environ.get("FAIL_BUILD") == "1": sys.exit(9)\n'
|
||||
'(target / "release").mkdir(parents=True, exist_ok=True)\n'
|
||||
'binary = target / "release/qbz"\n'
|
||||
'binary.write_text("#!/bin/sh\\nprintf \'artifact executed: %s\\\\n\' \\"$1\\"\\n")\n'
|
||||
'binary.chmod(0o755)\n'
|
||||
)
|
||||
metadata = json.dumps({"target_directory": str(shared), "workspace_root": str(root / "crates")})
|
||||
env = dict(os.environ, PATH=str(fake_bin) + os.pathsep + os.environ["PATH"],
|
||||
TARGET_METADATA=metadata, EXPECTED_TARGET=str(expected), NO_AUDIT="1",
|
||||
NO_TICKER="1", FORCE="1", NORUN="0", SMOKE="0", TEST="0", DEBUG="0",
|
||||
MOLD="0", XDG_CACHE_HOME=str(base / "cache"), FAIL_METADATA="1", FAIL_BUILD="0")
|
||||
for name in targets.EXPLICIT_ENV:
|
||||
env.pop(name, None)
|
||||
command = ["bash", str(scripts / "qt-run.sh"), "fixture-argument"]
|
||||
failed = subprocess.run(command, env=env, text=True, capture_output=True)
|
||||
self.assertNotEqual(failed.returncode, 0)
|
||||
self.assertFalse(expected.exists())
|
||||
env.update(FAIL_METADATA="0", FAIL_BUILD="1")
|
||||
failed = subprocess.run(command, env=env, text=True, capture_output=True)
|
||||
self.assertEqual(failed.returncode, 9, failed.stderr)
|
||||
self.assertFalse((root / "crates/target").is_symlink())
|
||||
env["FAIL_BUILD"] = "0"
|
||||
result = subprocess.run(command, env=env, text=True, capture_output=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("artifact executed: fixture-argument", result.stdout)
|
||||
self.assertEqual((root / "crates/target/release/qbz").resolve(), expected / "release/qbz")
|
||||
self.assertFalse((shared / "release/qbz").exists(), "the shared target is never built into")
|
||||
|
||||
|
||||
class SdkTests(unittest.TestCase):
|
||||
|
||||
Reference in new issue
Block a user