From 7837a236e728988fcd501917444828b790c367f9 Mon Sep 17 00:00:00 2001 From: tv Date: Fri, 20 Nov 2026 01:48:55 +0000 Subject: populate: lock files rewritten in place change only if they differ A file or git source whose lock file the flakes step rewrites in place gets the original back from delivering it, on every run, from rsync, or from git reset, which also printed HEAD is now at, and Nix printed that it updates the lock file, so the record said the source changed on every run. Populate keeps a copy of the rewritten lock file in .populate/locks/, and the flakes step compares with it, printing what Nix says about the lock file, and changed, only if it differs. Delivering such a source doesn't count bringing back the lock file: rsync returns the paths of what it changed, and the git source's script takes the lock file's path, and resets quietly if that's all that differs. relock also checks that the second, unchanged, run prints nothing about lock files, and says nothing changed, now for rewriting in place too. --- pkgs/populate/README.md | 10 +++-- pkgs/populate/src/flake.rs | 19 ++++++++- pkgs/populate/src/flake_input.rs | 4 +- pkgs/populate/src/populate.rs | 18 +++++++-- pkgs/populate/src/rsync.rs | 59 ++++++++++++++++++--------- pkgs/populate/src/sh.rs | 85 ++++++++++++++++++++++++++++----------- pkgs/populate/tests/scenarios.nix | 16 +++++--- 7 files changed, 151 insertions(+), 60 deletions(-) (limited to 'pkgs') diff --git a/pkgs/populate/README.md b/pkgs/populate/README.md index b53fb07..a947c60 100644 --- a/pkgs/populate/README.md +++ b/pkgs/populate/README.md @@ -264,9 +264,7 @@ wasn't locked throughout doesn't get recorded. Until a run finishes, populate keeps a journal in `.populate/journal` of what it began changing, and what that changed, which the next run that -finishes sums up in its record. A `file` or `git` source whose lock file -populate rewrites in place gets its original lock file back, and rewritten -again, on every run, so it counts as changed every time. +finishes sums up in its record. ## Source Types @@ -623,7 +621,11 @@ much like `NIX_PATH` does for Nix expressions. Populate rewrites the lock file of the flake in each source that draws inputs from other sources, using `nix flake lock --override-input`, so the flake in the source itself uses the other sources. `file` and `git` sources -get their lock file rewritten in place. `flake` and `flake-input` sources +get their lock file rewritten in place. Delivering them brings back the +original lock file on every run, so populate keeps a copy of the rewritten +one in `.populate/locks/`, and only prints what Nix says about the +lock file, and records a change, if it differs from that. `flake` and +`flake-input` sources get delivered as a copy with the rewritten lock file, which gets added to the store, unless materialized, so the target path links to that instead of the delivered store path, as it does for patched ones. A source drawing an input diff --git a/pkgs/populate/src/flake.rs b/pkgs/populate/src/flake.rs index 9658bff..62ed8d6 100644 --- a/pkgs/populate/src/flake.rs +++ b/pkgs/populate/src/flake.rs @@ -43,6 +43,12 @@ pub fn has_generated_flake(source: &Source) -> bool { && (source.kind == "symlink" || !bool_setting(&source.settings, "rewriteLock", true)) } +/// Whether the flakes step rewrites the lock file of the flake in a source +/// in place, which is how a file or git source draws inputs. +pub fn rewrites_lock(source: &Source) -> bool { + !source.follows().is_empty() && !has_generated_flake(source) && !derives_flake(source) +} + /// Whether a flake or flake-input source gets delivered as a copy, which /// gets patched, gets its lock file rewritten, or is materialized. pub fn derives_flake(source: &Source) -> bool { @@ -543,7 +549,8 @@ impl<'a> Flakes<'a> { let args = self.override_args(name)?; let resolved = self.resolve(&[self.path(name)], false)?; let url = Self::flake_url(name, &resolved[0])?; - let mut all = vec![resolved[0].path.as_str(), url.as_str()]; + let kept = self.state("locks", name); + let mut all = vec![resolved[0].path.as_str(), url.as_str(), kept.as_str()]; all.extend(args.iter().map(String::as_str)); self.changed(sh::draw::LOCK, true, &all) } @@ -649,7 +656,7 @@ impl<'a> Flakes<'a> { } if rewrite_lock { let url = self.own_url(name)?; - let mut all = vec![target_path.as_str(), url.as_str()]; + let mut all = vec![target_path.as_str(), url.as_str(), ""]; all.extend(args.iter().map(String::as_str)); outcome.changed |= self.changed(sh::draw::LOCK, true, &all)?.changed; } @@ -743,6 +750,13 @@ impl<'a> Flakes<'a> { .filter(|(_, s)| !patches(&s.settings).is_empty()) .map(|(n, _)| n.as_str()), ); + let locks = list( + &mut self + .sources + .iter() + .filter(|(_, s)| rewrites_lock(s)) + .map(|(n, _)| n.as_str()), + ); self.run( sh::draw::CLEAN_UP, false, @@ -753,6 +767,7 @@ impl<'a> Flakes<'a> { &generated, &derived, &patched, + &locks, ], ) } diff --git a/pkgs/populate/src/flake_input.rs b/pkgs/populate/src/flake_input.rs index b38965d..9763ade 100644 --- a/pkgs/populate/src/flake_input.rs +++ b/pkgs/populate/src/flake_input.rs @@ -595,7 +595,7 @@ fn upload_patches( &dir.to_string_lossy(), &format!("{sentinel}/patches/{name}"), ) - .map(|_| ()) + .map(drop) } /// Uploads the flake itself to a target that can't fetch it, unless the @@ -615,7 +615,7 @@ fn upload_self(context: &Context, name: &str, sentinel: &str, self_path: &str) - .join("flake-uploads") .join(name) .join("tree"); - rsync::transfer(context, &config, self_path, &upload.to_string_lossy()).map(|_| ()) + rsync::transfer(context, &config, self_path, &upload.to_string_lossy()).map(drop) } #[cfg(test)] diff --git a/pkgs/populate/src/populate.rs b/pkgs/populate/src/populate.rs index 617d39f..efcf5c3 100644 --- a/pkgs/populate/src/populate.rs +++ b/pkgs/populate/src/populate.rs @@ -135,7 +135,7 @@ impl Delivery<'_> { &source_path.to_string_lossy(), self.path, )?; - Ok(Outcome::changed(changed)) + Ok(Outcome::changed(!changed.is_empty())) } } @@ -188,6 +188,12 @@ fn string<'a>(settings: &'a Map, key: &str) -> Result<&'a str> { .ok_or_else(|| Failure::Message(format!("populate: the source has no {key}"))) } +/// The path, relative to the source, of the lock file of the flake in a +/// source, if the flakes step rewrites it in place, see flake::rewrite. +fn in_place_lock(source: &Source) -> Option<&'static str> { + flake::rewrites_lock(source).then_some("flake.lock") +} + /// A Nix expression, built on the target, delivered as a link to the result. struct Derivation; @@ -221,7 +227,12 @@ impl Kind for File { ..Config::from_settings(settings) }; let changed = rsync::transfer(d.context, &config, source_path, d.path)?; - Ok(Outcome::changed(changed)) + // The lock file the flakes step rewrites, which delivering brings + // back, changed if the flakes step says so. + let lock = in_place_lock(d.source); + Ok(Outcome::changed( + changed.iter().any(|path| Some(path.as_str()) != lock), + )) } } @@ -250,7 +261,7 @@ impl Kind for Pipe { ..Config::default() }; let changed = rsync::transfer(d.context, &config, &out.to_string_lossy(), d.path)?; - Ok(Outcome::changed(changed)) + Ok(Outcome::changed(!changed.is_empty())) } } @@ -289,6 +300,7 @@ impl Kind for Git { flag("shallow"), flag("fetchAlways"), flag("reclone"), + in_place_lock(d.source).unwrap_or_default(), ]; args.extend(excludes); // With standard input, which Git may ask for credentials on. diff --git a/pkgs/populate/src/rsync.rs b/pkgs/populate/src/rsync.rs index 7858e4a..1b46723 100644 --- a/pkgs/populate/src/rsync.rs +++ b/pkgs/populate/src/rsync.rs @@ -84,8 +84,14 @@ impl Config { } /// Transfers source_path, a directory's contents or a file, to path on the -/// target, returning whether that changed anything there. -pub fn transfer(context: &Context, config: &Config, source_path: &str, path: &str) -> Result { +/// target, returning the paths, relative to path, of what that changed +/// there. +pub fn transfer( + context: &Context, + config: &Config, + source_path: &str, + path: &str, +) -> Result> { context.run(&sh::break_hard_links(), &[path, &context.name(path)])?; let mut source = source_path.to_string(); if Path::new(source_path).is_dir() { @@ -124,23 +130,33 @@ pub fn transfer(context: &Context, config: &Config, source_path: &str, path: &st command.arg("--delete-excluded"); } command.arg(&source).arg(context.rsync_destination(path)); - let mut changed = false; + let mut changed = Vec::new(); run::lines(&mut command, |line| { - changed |= itemizes_change(line); + changed.extend(changed_path(line)); eprintln!("{line}"); })?; Ok(changed) } -/// Whether a line rsync prints itemizes a change: what --itemize-changes -/// prints for an item, eleven characters, the second the type of the item, -/// or *deleting, followed by a blank. -fn itemizes_change(line: &str) -> bool { - let Some((item, _)) = line.split_once(' ') else { - return false; +/// The path of what a line rsync prints itemizes a change of: what +/// --itemize-changes prints for an item, eleven characters, the second the +/// type of the item, or *deleting, followed by a blank, and the path, which +/// the sizes follow for items, and a symlink's target, after ->. +fn changed_path(line: &str) -> Option { + let (item, rest) = line.split_once(' ')?; + if item == "*deleting" { + return Some(rest.trim_start().to_string()); + } + if item.len() != 11 || !matches!(item.as_bytes()[1], b'f' | b'd' | b'L' | b'D' | b'S') { + return None; + } + let (path, _sizes) = rest.rsplit_once(' ')?; + let path = if item.as_bytes()[1] == b'L' { + path.split_once(" -> ").map_or(path, |(path, _)| path) + } else { + path }; - item == "*deleting" - || item.len() == 11 && matches!(item.as_bytes()[1], b'f' | b'd' | b'L' | b'D' | b'S') + Some(path.to_string()) } /// rsync 3.5.0 and later open .rsync-filter files with a stricter walk than @@ -315,13 +331,18 @@ mod tests { use super::*; #[test] - fn itemized_changes() { - assert!(itemizes_change(">f.st...... flake.nix 82/39")); - assert!(itemizes_change("cd+++++++++ .git/objects/25/ 0/4.00K")); - assert!(itemizes_change(".f..t...... x 0/1")); - assert!(itemizes_change("*deleting old")); - assert!(!itemizes_change("skipping non-regular file \"x\"")); - assert!(!itemizes_change("sent 10 bytes")); + fn changed_paths() { + let path = |line| changed_path(line); + assert_eq!( + path(">f.st...... flake.nix 82/39").as_deref(), + Some("flake.nix") + ); + assert_eq!(path("cd+++++++++ a b/ 0/4.00K").as_deref(), Some("a b/")); + assert_eq!(path(".f..t...... x 0/1").as_deref(), Some("x")); + assert_eq!(path("cL+++++++++ l -> t 0/0").as_deref(), Some("l")); + assert_eq!(path("*deleting old").as_deref(), Some("old")); + assert_eq!(path("skipping non-regular file \"x\""), None); + assert_eq!(path("sent 10 bytes"), None); } #[test] diff --git a/pkgs/populate/src/sh.rs b/pkgs/populate/src/sh.rs index ebc1f10..3df2cc4 100644 --- a/pkgs/populate/src/sh.rs +++ b/pkgs/populate/src/sh.rs @@ -6,7 +6,7 @@ /// for each source that needs one. Besides, there is backup, which holds /// copies of the sources, and the files lock, journal, and run.json, see /// LOCK and RECORD. -pub const STATE_KINDS: &str = "derived flake-inputs flake-uploads flakes patches"; +pub const STATE_KINDS: &str = "derived flake-inputs flake-uploads flakes locks patches"; /// Defines use_state SENTINEL NAME..., which prepares keeping state below /// the sentinel for the sources named NAME. Populate changes and removes @@ -388,11 +388,12 @@ git_problems() ( ) "#; -/// git PATH NAME URL REF SHALLOW FETCH_ALWAYS RECLONE EXCLUDE...: makes -/// PATH a Git work tree of the repository at URL, with REF checked out, -/// and everything removed that Git doesn't track, except what matches an -/// EXCLUDE pattern. SHALLOW, FETCH_ALWAYS, and RECLONE are flags, empty -/// for false. NAME is PATH's name in messages. Prints checked if +/// git PATH NAME URL REF SHALLOW FETCH_ALWAYS RECLONE LOCK EXCLUDE...: +/// makes PATH a Git work tree of the repository at URL, with REF checked +/// out, and everything removed that Git doesn't track, except what matches +/// an EXCLUDE pattern. SHALLOW, FETCH_ALWAYS, and RECLONE are flags, empty +/// for false. LOCK, if not empty, is the path of a lock file the flakes +/// step rewrites in place, so bringing it back doesn't count as a change. NAME is PATH's name in messages. Prints checked if /// git_problems found nothing wrong with the work tree that was there, /// which then is what's there, changed if anything changed, and commit and /// the commit checked out, on lines of their own; what commands print goes @@ -409,7 +410,13 @@ pub fn git() -> String { checked= changed= deliver_git() { path=$1 name=$2 url=$3 ref=$4 shallow=$5 fetch_always=$6 reclone=$7 - shift 7 + lock=$8 + shift 8 + # Whether lines of what Git prints name anything but LOCK, after the + # first $1 characters. + names_others() { + test -n "$(printf '%s\n' "$2" | cut -c"$(($1 + 1))"- | grep -vxF -e "$lock" -e '')" + } # Hooks and commands a repository's configuration names run with Git's # commands, so populate's Git doesn't run any. The configuration gets # checked as well, but Git also runs a hook it has itself. @@ -500,8 +507,13 @@ deliver_git() { commit=$(git rev-parse --verify --quiet "$hash^{commit}") || commit= changes=$(git status --porcelain --untracked-files=no) || changes=unknown if test -z "$head" || test "$head" != "$commit" || test -n "$changes"; then - changed=1 - git reset --hard "$hash" + if test "$head" != "$commit" || names_others 3 "$changes"; then + changed=1 + git reset --hard "$hash" + else + # Only bringing back LOCK, which is nothing to tell. + git reset --quiet --hard "$hash" + fi fi log=$(mktemp) git submodule update --init --recursive > "$log" @@ -517,7 +529,9 @@ deliver_git() { done git clean -dfx "$@" > "$log" if test -s "$log"; then - changed=1 + if names_others 9 "$(cat "$log")"; then + changed=1 + fi cat "$log" fi rm "$log" @@ -1041,18 +1055,38 @@ fi rm -R "$empty" "#; - /// lock DIR URL ARG...: rewrites the lock file of the flake in DIR, - /// at URL, with nix flake lock's arguments ARG, printing changed if - /// that changed it. + /// lock DIR URL KEPT ARG...: rewrites the lock file of the flake in + /// DIR, at URL, with nix flake lock's arguments ARG. If it differs + /// from the one rewritten before, it prints changed, after what Nix + /// says about it. That's in KEPT, if not empty, which gets a copy: + /// delivering a file or git source brings back the original lock file + /// on every run. Else it's the lock file there, as for a materialized + /// copy. pub const LOCK: &str = r#" -dir=$1 url=$2 -shift 2 +dir=$1 url=$2 kept=$3 +shift 3 own_lock "$dir" -old=$(cat "$dir"/flake.lock 2>/dev/null) || old= -nix flake lock "$@" "$url" >&2 -if test "$(cat "$dir"/flake.lock)" != "$old"; then +if test -n "$kept"; then + old=$(cat "$kept" 2>/dev/null) || old= +else + old=$(cat "$dir"/flake.lock 2>/dev/null) || old= +fi +log=$(mktemp) +if ! nix flake lock "$@" "$url" >&2 2>"$log"; then + cat "$log" >&2 + rm "$log" + exit 1 +fi +new=$(cat "$dir"/flake.lock) +if test "$new" != "$old"; then + cat "$log" >&2 echo changed fi +rm "$log" +if test -n "$kept"; then + mkdir -p "$(dirname "$kept")" + write_key "$kept" "$new" +fi "#; /// derived_state DIR TARGET_PATH PATCH_DIR CHECKED DRAWN...: removes @@ -1209,12 +1243,13 @@ fi rm "$log" "#; - /// clean_up SENTINEL NAMES NOT_FLAKES GENERATED DERIVED PATCHED: removes - /// the state sources don't need anymore. Each argument after SENTINEL - /// is a list of source names, separated by blanks: of all sources, of - /// those that are neither flake nor flake-input sources, whose roots - /// for the garbage collector go, and of those that have a generated - /// flake, derived state, and patches. + /// clean_up SENTINEL NAMES NOT_FLAKES GENERATED DERIVED PATCHED LOCKS: + /// removes the state sources don't need anymore. Each argument after + /// SENTINEL is a list of source names, separated by blanks: of all + /// sources, of those that are neither flake nor flake-input sources, + /// whose roots for the garbage collector go, and of those that have a + /// generated flake, derived state, patches, and a copy of the lock file + /// rewritten in place. pub const CLEAN_UP: &str = r#" sentinel=$1 # The names are portable file names, so splitting them at blanks is fine. @@ -1244,5 +1279,7 @@ remove_stale "$sentinel"/flakes $4 remove_stale "$sentinel"/derived $5 # shellcheck disable=SC2086 remove_stale "$sentinel"/patches $6 +# shellcheck disable=SC2086 +remove_stale "$sentinel"/locks $7 "#; } diff --git a/pkgs/populate/tests/scenarios.nix b/pkgs/populate/tests/scenarios.nix index a5ac6ea..fbcae73 100644 --- a/pkgs/populate/tests/scenarios.nix +++ b/pkgs/populate/tests/scenarios.nix @@ -546,11 +546,13 @@ in }; })) # The lock file gets rewritten or generated again when a source inputs - # get drawn from changes. What Nix prints about a generated flake's lock - # file only gets printed then. + # get drawn from changes. What Nix prints about the lock file only gets + # printed then, and the record only says x changed then, also when + # delivering x brings back the lock file that gets rewritten in place. (modes "relock" ({ draw, flake, mode, ... }: let x.file = { path = "/fixtures/filesrc"; } // draw { dep.follows = "a"; }; - generated = optional (mode == "generated"); + # Nix updates the lock file of x, or creates it, if x has none. + message = if mode == "generated" then "creating lock file" else "lock file"; in { phases = [ { @@ -558,20 +560,22 @@ in check = '' expect_eq msg "$(nix_eval_online ${flake "x"}#msg)" top:alt,sub ''; - output = generated "creating lock file"; + output = [ message ]; } { sources = { inherit x; a.file = "/fixtures/alt"; }; check = '' expect_eq msg "$(nix_eval_online ${flake "x"}#msg)" top:alt,sub + expect_eq changed "$(record changed)" false ''; - unexpected = generated "lock file"; + unexpected = [ "lock file" ]; } { - output = generated "creating lock file"; + output = [ message ]; sources = { inherit x; a.file = "/fixtures/alt2"; }; check = '' expect_eq msg "$(nix_eval_online ${flake "x"}#msg)" top:alt2,sub + expect_eq "x changed" "$(record sources.x.changed)" true ''; } ]; -- cgit v1.3.1