//! What's at the target paths of the sources whose delivery may find //! nothing to do, found out with one command on the target, right after //! taking the lock, so their delivery doesn't need any: file and passage //! sources, see rsync's Listing, symlink and pass sources, and git sources //! with a commit as ref. use crate::rsync::{self, Listing}; use crate::run::{Context, Result}; use crate::sh; use crate::spec::Spec; use std::collections::BTreeMap; /// What the probe found at a source's target path. #[derive(Debug, Default, PartialEq)] pub struct Target { /// For a file or passage source, its listing, if populate can compare /// it. pub listing: Option, /// For a symlink source, the target of the symlink there, if any. pub link: Option, /// For a pass source, what its .pass_info contains, if anything. pub info: Option, /// For a git source, the state of the work tree there, if it's one /// that git_problems finds nothing wrong with. pub git: Option, } /// The state of a Git work tree. #[derive(Debug, PartialEq)] pub struct Git { /// The commit checked out, or empty if none. pub head: String, /// The URL of the remote origin, or empty if none. pub url: String, /// Whether anything is modified, untracked, or ignored, which git reset /// and git clean -dfx would change. pub dirty: bool, /// Whether each submodule, if any, has its commit checked out. pub submodules: bool, } impl Git { /// Whether delivering the work tree with a commit as ref would change /// nothing: that commit is checked out, the URL is the one of the /// origin, nothing is dirty, and the submodules are up to date. pub fn unchanged(&self, url: &str, commit: &str) -> bool { is_commit(commit) && self.head.len() == 40 && self.head.starts_with(commit) && self.url == url && !self.dirty && self.submodules } } /// Whether ref is a commit, given by its hash or a prefix thereof, like /// the git script tells. pub fn is_commit(r#ref: &str) -> bool { (4..=40).contains(&r#ref.len()) && r#ref .bytes() .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) } /// What's at the target paths of the sources spec delivers, by name, for /// those of kinds that kind gives, F, L, or G, see sh::probe: one command /// on the target probes them all, and none if there are none. pub fn probe( context: &Context, spec: &Spec, kind: impl Fn(&str, &crate::spec::Source) -> Option<&'static str>, ) -> Result> { let dir = &spec.target.path; let probed: Vec<(&String, &str, String)> = spec .source .iter() .filter_map(|(name, source)| { kind(name, source).map(|kind| (name, kind, format!("{dir}/{name}"))) }) .collect(); if probed.is_empty() { return Ok(BTreeMap::new()); } let mut args = Vec::new(); for (_, kind, path) in &probed { args.push(*kind); args.push(path.as_str()); } let mut found = parse(&context.output(&sh::probe(), &args)?); Ok(probed .into_iter() .filter_map(|(name, _, path)| found.remove(&path).map(|target| (name.clone(), target))) .collect()) } /// What sh::probe printed, by path, for the paths whose exit status is 0. fn parse(output: &str) -> BTreeMap { let mut targets = BTreeMap::new(); let mut fields = output.split('\0'); // The path, what's known about it, and whether its listing is still // comparable. let mut current: Option<(String, Target, bool)> = None; while let Some(field) = fields.next() { let Some((_, target, comparable)) = &mut current else { if field == "P" { current = fields .next() .map(|path| (path.to_string(), Target::default(), true)); } continue; }; match field { "E" => { let entry: Vec<&str> = fields.by_ref().take(5).collect(); let canonical = match entry[..] { [mode, size, time, path, link] => { rsync::canonical_found(mode, size, time, path, link) } _ => None, }; match canonical { Some(entry) if *comparable => { target .listing .get_or_insert_with(Listing::new) .insert(entry); } _ => *comparable = false, } } "L" => target.link = fields.next().map(str::to_string), "I" => target.info = fields.next().map(str::to_string), // Dirty until git status says otherwise. "C" => { fields.next(); target.git = Some(Git { head: String::new(), url: String::new(), dirty: true, submodules: true, }); } "H" | "U" | "D" | "M" => { let value = fields.next().unwrap_or_default(); if let Some(git) = &mut target.git { match field { "H" => git.head = value.to_string(), "U" => git.url = value.to_string(), "D" => git.dirty = !value.is_empty(), // A line not starting with a blank is a submodule // not initialized, or not at its commit. _ => git.submodules = value.lines().all(|line| line.starts_with(' ')), } } } "S" => { let ok = fields.next() == Some("0"); if let Some((path, mut target, comparable)) = current.take() { if !comparable { target.listing = None; } if ok { targets.insert(path, target); } } } _ => {} } } targets } #[cfg(test)] mod tests { use super::*; fn output(items: &[&[&str]]) -> String { items .iter() .flat_map(|item| item.iter()) .map(|field| format!("{field}\0")) .collect() } #[test] fn links() { let found = parse(&output(&[ &["P", "/t/a", "L", "../x", "S", "0"], &["P", "/t/b", "S", "0"], ])); assert_eq!(found["/t/a"].link.as_deref(), Some("../x")); assert_eq!(found["/t/b"].link, None); assert!(parse(&output(&[&["P", "/t/a", "L", "x", "S", "1"]])).is_empty()); } const HEAD: &str = "0123456789abcdef0123456789abcdef01234567"; fn git(extra: &[&str]) -> Option { let mut items: Vec<&str> = vec!["P", "/t/g", "C", "", "H", HEAD, "U", "https://x/r"]; items.extend(extra); items.extend(["S", "0"]); parse(&output(&[&items])) .remove("/t/g") .and_then(|target| target.git) } #[test] fn gits() { let clean = git(&["D", ""]).expect("git"); assert!(clean.unchanged("https://x/r", HEAD)); assert!(clean.unchanged("https://x/r", &HEAD[..7])); assert!(!clean.unchanged("https://x/other", HEAD)); assert!(!clean.unchanged("https://x/r", "master")); assert!(!clean.unchanged("https://x/r", "fedcba98")); // Dirty, without git status's answer, and submodules. assert!(!git(&["D", "?? new"]) .expect("git") .unchanged("https://x/r", HEAD)); assert!(!git(&[]).expect("git").unchanged("https://x/r", HEAD)); let submodule = |line: &str| { git(&["D", "", "M", line]) .expect("git") .unchanged("https://x/r", HEAD) }; assert!(submodule(" 89abcdef sub (heads/master)")); assert!(!submodule("+89abcdef sub (heads/master)")); assert!(!submodule("-89abcdef sub")); // A work tree that git_problems doesn't accept prints no C. let rejected = parse(&output(&[&["P", "/t/g", "S", "0"]])); assert_eq!(rejected["/t/g"].git, None); } #[test] fn listings() { let entry = ["E", "drwxr-xr-x", "4096", "1796060000.1", "", ""]; let found = parse(&output(&[&["P", "/t/f"], &entry, &["S", "0"]])); assert_eq!( found["/t/f"].listing, Some(Listing::from(["drwxr-xr-x .".to_string()])) ); let device = ["E", "crw-r--r--", "0", "1796060000.1", "null", ""]; let found = parse(&output(&[&["P", "/t/f"], &entry, &device, &["S", "0"]])); assert_eq!(found["/t/f"].listing, None); } }