aboutsummaryrefslogtreecommitdiffstats
path: root/pkgs/populate/src/probe.rs
blob: 7228cd29360573ba5517a47bf6482358b0c39451 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
//! 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 sources, see
//! rsync's Listing, symlink 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 source, its listing, if populate can compare it.
    pub listing: Option<Listing>,
    /// For a symlink source, the target of the symlink there, if any.
    pub link: Option<String>,
    /// 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<Git>,
}

/// 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<BTreeMap<String, Target>> {
    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<String, Target> {
    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),
            // 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<Git> {
        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);
    }
}
[cgit] Unable to lock slot /tmp/cgit/ba000000.lock: Permission denied (13)