diff options
Diffstat (limited to 'pkgs/populate/src')
| -rw-r--r-- | pkgs/populate/src/check.rs | 6 | ||||
| -rw-r--r-- | pkgs/populate/src/flake_input.rs | 2 | ||||
| -rw-r--r-- | pkgs/populate/src/populate.rs | 90 | ||||
| -rw-r--r-- | pkgs/populate/src/run.rs | 19 | ||||
| -rw-r--r-- | pkgs/populate/src/sh.rs | 29 |
5 files changed, 126 insertions, 20 deletions
diff --git a/pkgs/populate/src/check.rs b/pkgs/populate/src/check.rs index 155565f..b272446 100644 --- a/pkgs/populate/src/check.rs +++ b/pkgs/populate/src/check.rs @@ -51,6 +51,8 @@ enum Kind { Clean, /// file's filters, each with type include or exclude, and a pattern. Filters, + /// file's record, with commit and digest, flags. + Record, /// Inputs drawn from other sources, each with follows, a string, and /// inputs, again inputs. Inputs, @@ -71,6 +73,7 @@ fn known_settings(kind: &str) -> &'static [(&'static str, Kind, bool)] { ("insecureLinks", Bool, false), ("inputs", Inputs, false), ("rewriteLock", Bool, false), + ("record", Record, false), ], "flake" => &[ ("url", String, true), @@ -129,6 +132,9 @@ fn is_kind(value: &Value, kind: Kind) -> bool { Kind::Clean => value .as_object() .is_some_and(|o| only(o, &["exclude"]) && o.get("exclude").map_or(true, strings)), + Kind::Record => value + .as_object() + .is_some_and(|o| only(o, &["commit", "digest"]) && o.values().all(Value::is_boolean)), Kind::Filters => value.as_array().is_some_and(|a| { a.iter().all(|f| { f.as_object().is_some_and(|o| { diff --git a/pkgs/populate/src/flake_input.rs b/pkgs/populate/src/flake_input.rs index 9763ade..8763c47 100644 --- a/pkgs/populate/src/flake_input.rs +++ b/pkgs/populate/src/flake_input.rs @@ -359,7 +359,7 @@ pub fn deliver( args.extend(paths.iter().map(String::as_str)); let output = context.output(&on_target(sh::flake::LINK, None), &args)?; let changed = !derived && output.contains("changed"); - Ok(Outcome::changed(changed).with("storePath", &paths[0])) + Ok(Outcome::changed(changed).with("storePath", paths[0].as_str())) }; let on_target_output = |what: &'static str| { move |snippet: &str, args: &[&str]| context.output(&on_target(snippet, Some(what)), args) diff --git a/pkgs/populate/src/populate.rs b/pkgs/populate/src/populate.rs index efcf5c3..0366c53 100644 --- a/pkgs/populate/src/populate.rs +++ b/pkgs/populate/src/populate.rs @@ -25,7 +25,7 @@ pub fn populate(context: &Context, spec: &Spec) -> Result<()> { &[&sentinel, &context.name(&sentinel), dir, force], )?; let started = record::now(); - let previous = context.lock(&sentinel, json!({ "run": started }))?; + let (previous, last) = context.lock(&sentinel, json!({ "run": started }))?; if spec.backup { context.run(&sh::backup(), &[dir])?; } @@ -71,12 +71,54 @@ pub fn populate(context: &Context, spec: &Spec) -> Result<()> { context.note(json!({ "pruned": true })); } } - let record = record::record(spec, &started, &previous, &context.entries()); + let mut record = record::record(spec, &started, &previous, &context.entries()); + digests(context, spec, &mut record, &last.join("\n"))?; context.run(sh::RECORD, &[&sentinel, &record.to_string()])?; context.unlock(); Ok(()) } +/// Adds the digest of each file source whose record setting asks for it to +/// the record: of what's at its target path now, after the flakes step, +/// only if it changed since the last record, last, and else the one the +/// last record has, so a run that changes nothing reads nothing more. +fn digests(context: &Context, spec: &Spec, record: &mut Value, last: &str) -> Result<()> { + let last: Value = serde_json::from_str(last).unwrap_or(Value::Null); + let mut names = Vec::new(); + let mut paths = Vec::new(); + for (name, source) in &spec.source { + if !record_setting(source, "digest") { + continue; + } + let entry = &mut record["sources"][name]; + let digest = &last["sources"][name]["digest"]; + if entry["changed"] == json!(false) && digest.is_string() { + entry["digest"] = digest.clone(); + } else { + names.push(name); + paths.push(format!("{}/{name}", spec.target.path)); + } + } + if !paths.is_empty() { + let args: Vec<&str> = paths.iter().map(String::as_str).collect(); + let output = context.output(sh::DIGESTS, &args)?; + for (name, digest) in names.iter().zip(output.lines()) { + record["sources"][name.as_str()]["digest"] = json!(digest); + } + } + Ok(()) +} + +/// Whether a source's record setting has key set. +fn record_setting(source: &Source, key: &str) -> bool { + source + .settings + .get("record") + .and_then(|r| r.get(key)) + .and_then(Value::as_bool) + == Some(true) +} + /// What delivering a source did: whether that changed anything in the /// target directory, and what got delivered, for the record of the run. #[derive(Default)] @@ -94,8 +136,8 @@ impl Outcome { } /// With what got delivered, under key, as value. - pub fn with(mut self, key: &str, value: &str) -> Outcome { - self.delivered.insert(key.to_string(), json!(value)); + pub fn with(mut self, key: &str, value: impl Into<Value>) -> Outcome { + self.delivered.insert(key.to_string(), value.into()); self } @@ -230,9 +272,43 @@ impl Kind for File { // 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), - )) + let outcome = Outcome::changed(changed.iter().any(|path| Some(path.as_str()) != lock)); + if !record_setting(d.source, "commit") { + return Ok(outcome); + } + // What the work tree's Git says, without its hooks and file system + // monitors, and without writing the index. + let git = |args: &[&str]| { + Command::new("git") + .args([ + "-c", + "core.hooksPath=/dev/null", + "-c", + "core.fsmonitor=false", + ]) + .args(["--no-optional-locks", "-C", source_path]) + .args(args) + .stdin(Stdio::null()) + .stderr(Stdio::null()) + .output() + .ok() + .filter(|output| output.status.success()) + .map(|output| { + String::from_utf8_lossy(&output.stdout) + .trim_end() + .to_string() + }) + }; + // Nothing, if the path isn't in a Git work tree. + let Some(commit) = git(&["rev-parse", "--verify", "--quiet", "HEAD"]) else { + return Ok(outcome); + }; + let status = git(&["status", "--porcelain", "--", "."]).ok_or_else(|| { + Failure::Message(format!("error: can't tell the Git status of {source_path}")) + })?; + Ok(outcome + .with("commit", commit) + .with("dirty", !status.is_empty())) } } diff --git a/pkgs/populate/src/run.rs b/pkgs/populate/src/run.rs index acbf279..9817b78 100644 --- a/pkgs/populate/src/run.rs +++ b/pkgs/populate/src/run.rs @@ -281,8 +281,12 @@ impl Context { /// Takes the lock on the target directory, whose sentinel is sentinel, /// adding entry to the journal, which entries go to from now on, until /// unlock. Returns the lines that runs that didn't finish left in the - /// journal. - pub fn lock(&self, sentinel: &str, entry: serde_json::Value) -> Result<Vec<String>> { + /// journal, and the lines of the last run's record. + pub fn lock( + &self, + sentinel: &str, + entry: serde_json::Value, + ) -> Result<(Vec<String>, Vec<String>)> { let mut command = self.shell( crate::sh::LOCK, &[sentinel, &self.name(sentinel), &entry.to_string()], @@ -293,7 +297,8 @@ impl Context { .stderr(Stdio::inherit()); let mut child = command.spawn().map_err(|e| spawn_error(&command, e))?; let stdout = child.stdout.take().expect("piped"); - let mut previous = Vec::new(); + let mut journal = Vec::new(); + let mut record = None; let mut locked = false; for line in BufReader::new(stdout).lines() { let line = line.map_err(|e| { @@ -305,7 +310,11 @@ impl Context { locked = true; break; } - previous.push(line); + match &mut record { + None if line == "record" => record = Some(Vec::new()), + None => journal.push(line), + Some(record) => record.push(line), + } } if !locked { drop(child.stdin.take()); @@ -322,7 +331,7 @@ impl Context { *self.journal.borrow_mut() = Some(format!("{sentinel}/journal")); self.entries.borrow_mut().0.push(entry); self.entries.borrow_mut().1 = 1; - Ok(previous) + Ok((journal, record.unwrap_or_default())) } /// Fails if the command holding the lock ended, e.g. killed on the diff --git a/pkgs/populate/src/sh.rs b/pkgs/populate/src/sh.rs index 3df2cc4..040ec0a 100644 --- a/pkgs/populate/src/sh.rs +++ b/pkgs/populate/src/sh.rs @@ -154,11 +154,13 @@ fi /// lock SENTINEL NAME ENTRY: waits for an exclusive lock on SENTINEL/lock, /// prints what's in SENTINEL/journal, which is there if a run didn't -/// finish, appends ENTRY to it, and prints locked. Then it keeps the lock -/// until its standard input ends, which consumers of the target directory -/// can wait for by taking a shared lock. NAME is the sentinel's name in -/// messages. Writing to a symlink in place of the lock or the journal -/// would write to what it points to, so it refuses those. +/// finish, appends ENTRY to it, prints record and what's in +/// SENTINEL/run.json, the last run's record, if any, and prints locked. +/// Then it keeps the lock until its standard input ends, which consumers +/// of the target directory can wait for by taking a shared lock. NAME is +/// the sentinel's name in messages. Writing to a symlink in place of the +/// lock or the journal would write to what it points to, so it refuses +/// those. pub const LOCK: &str = r#" sentinel=$1 name=$2 entry=$3 for file in lock journal; do @@ -177,6 +179,10 @@ if test -f "$sentinel"/journal; then cat "$sentinel"/journal fi printf '%s\n' "$entry" >> "$sentinel"/journal +echo record +if test -f "$sentinel"/run.json; then + cat "$sentinel"/run.json +fi echo locked exec cat >/dev/null "#; @@ -193,6 +199,14 @@ mv -f "$tmp" "$sentinel"/run.json rm -f "$sentinel"/journal "#; +/// digests PATH...: prints the hash of what's at each PATH, as Nix hashes +/// store paths, in SRI format, on lines of their own. +pub const DIGESTS: &str = r#" +for path; do + nix-hash --type sha256 --sri "$path" +done +"#; + /// The shell code adding the lines a command gets before its own arguments /// to the journal: the journal's path, the number of lines, and the lines. pub const JOURNAL: &str = r#" @@ -312,8 +326,9 @@ fi /// which names another repository, no linked work trees, and only the /// configuration they write: the repository's format, the remote, branches, /// and submodules, whose repositories have their work tree in the work -/// tree. Hooks don't matter: populate's Git doesn't run them. And each .git below the work tree, which Git uses for a -/// submodule there, is a file naming a repository in .git/modules. +/// tree. Hooks don't matter: populate's Git doesn't run them. And each +/// .git below the work tree, which Git uses for a submodule there, is a +/// file naming a repository in .git/modules. pub const GIT_PROBLEMS: &str = r#" git_problems() ( path=$1 |
