gitoxide_core/repository/attributes/
validate_baseline.rs

1use crate::OutputFormat;
2
3pub struct Options {
4    pub format: OutputFormat,
5    pub statistics: bool,
6    pub ignore: bool,
7}
8
9pub(crate) mod function {
10    use std::{
11        collections::BTreeSet,
12        io,
13        io::{BufRead, Write},
14        iter::Peekable,
15        ops::Sub,
16        path::PathBuf,
17        sync::atomic::Ordering,
18    };
19
20    use anyhow::{anyhow, bail};
21    use gix::{attrs::Assignment, bstr::BString, Count, Progress};
22
23    use crate::{
24        repository::attributes::{query::attributes_cache, validate_baseline::Options},
25        OutputFormat,
26    };
27
28    pub fn validate_baseline(
29        repo: gix::Repository,
30        paths: Option<impl Iterator<Item = BString> + Send + 'static>,
31        mut progress: impl gix::NestedProgress + 'static,
32        mut out: impl io::Write,
33        mut err: impl io::Write,
34        Options {
35            format,
36            statistics,
37            mut ignore,
38        }: Options,
39    ) -> anyhow::Result<()> {
40        if format != OutputFormat::Human {
41            bail!("JSON output isn't implemented yet");
42        }
43
44        if repo.is_bare() {
45            writeln!(
46                err,
47                "Repo {:?} is bare - disabling git-ignore baseline as `git check-ignore` needs a worktree",
48                repo.path()
49            )
50            .ok();
51            ignore = false;
52        }
53        let mut num_entries = None;
54        let paths = paths.map_or_else(
55            {
56                let repo = repo.clone();
57                let num_entries = &mut num_entries;
58                move || -> anyhow::Result<_> {
59                    let index = repo.index_or_load_from_head()?.into_owned();
60                    let (entries, path_backing) = index.into_parts().0.into_entries();
61                    *num_entries = Some(entries.len());
62                    let iter = Box::new(entries.into_iter().map(move |e| e.path_in(&path_backing).to_owned()));
63                    Ok(iter as Box<dyn Iterator<Item = BString> + Send + 'static>)
64                }
65            },
66            |paths| anyhow::Result::Ok(Box::new(paths)),
67        )?;
68
69        let (tx_base, rx_base) = std::sync::mpsc::channel::<(String, Baseline)>();
70        let feed_attrs = {
71            let (tx, rx) = std::sync::mpsc::sync_channel::<BString>(100);
72            std::thread::spawn({
73                let path = repo.path().to_owned();
74                let tx_base = tx_base.clone();
75                let mut progress = progress.add_child("attributes");
76                move || -> anyhow::Result<()> {
77                    let mut child =
78                        std::process::Command::from(gix::command::prepare(gix::path::env::exe_invocation()))
79                            .args(["check-attr", "--stdin", "-a"])
80                            .stdin(std::process::Stdio::piped())
81                            .stdout(std::process::Stdio::piped())
82                            .stderr(std::process::Stdio::null())
83                            .current_dir(path)
84                            .spawn()?;
85
86                    std::thread::spawn({
87                        let mut stdin = child.stdin.take().expect("we configured it");
88                        move || -> anyhow::Result<()> {
89                            progress.init(num_entries, gix::progress::count("paths"));
90                            let start = std::time::Instant::now();
91                            for path in rx {
92                                progress.inc();
93                                stdin.write_all(&path)?;
94                                stdin.write_all(b"\n")?;
95                            }
96                            progress.show_throughput(start);
97                            Ok(())
98                        }
99                    });
100
101                    let stdout = std::io::BufReader::new(child.stdout.take().expect("we configured it"));
102                    let mut lines = stdout.lines().map_while(Result::ok).peekable();
103                    while let Some(baseline) = parse_attributes(&mut lines) {
104                        if tx_base.send(baseline).is_err() {
105                            child.kill().ok();
106                            break;
107                        }
108                    }
109
110                    Ok(())
111                }
112            });
113            tx
114        };
115        let work_dir = ignore
116            .then(|| {
117                repo.workdir()
118                    .map(ToOwned::to_owned)
119                    .ok_or_else(|| anyhow!("repository at {:?} must have a worktree checkout", repo.path()))
120            })
121            .transpose()?;
122        let feed_excludes = ignore.then(|| {
123            let (tx, rx) = std::sync::mpsc::sync_channel::<BString>(100);
124            std::thread::spawn({
125                let path = work_dir.expect("present if we are here");
126                let tx_base = tx_base.clone();
127                let mut progress = progress.add_child("excludes");
128                move || -> anyhow::Result<()> {
129                    let mut child =
130                        std::process::Command::from(gix::command::prepare(gix::path::env::exe_invocation()))
131                            .args(["check-ignore", "--stdin", "-nv", "--no-index"])
132                            .stdin(std::process::Stdio::piped())
133                            .stdout(std::process::Stdio::piped())
134                            .stderr(std::process::Stdio::null())
135                            .current_dir(path)
136                            .spawn()?;
137
138                    std::thread::spawn({
139                        let mut stdin = child.stdin.take().expect("we configured it");
140                        move || -> anyhow::Result<()> {
141                            progress.init(num_entries, gix::progress::count("paths"));
142                            let start = std::time::Instant::now();
143                            for path in rx {
144                                progress.inc();
145                                stdin.write_all(path.as_ref())?;
146                                stdin.write_all(b"\n")?;
147                            }
148                            progress.show_throughput(start);
149                            Ok(())
150                        }
151                    });
152
153                    let stdout = std::io::BufReader::new(child.stdout.take().expect("we configured it"));
154                    for line in stdout.lines() {
155                        let line = line?;
156                        if let Some(baseline) = parse_exclude(&line) {
157                            if tx_base.send(baseline).is_err() {
158                                child.kill().ok();
159                                break;
160                            }
161                        } else {
162                            eprintln!("Failed to parse line {line:?} - ignored");
163                        }
164                    }
165
166                    Ok(())
167                }
168            });
169            tx
170        });
171        drop(tx_base);
172
173        std::thread::spawn(move || {
174            for path in paths {
175                if feed_attrs.send(path.clone()).is_err() {
176                    break;
177                }
178                if let Some(ch) = feed_excludes.as_ref() {
179                    if ch.send(path).is_err() {
180                        break;
181                    }
182                }
183            }
184        });
185
186        let (mut cache, _index) = attributes_cache(&repo)?;
187        let mut matches = cache.attribute_matches();
188        let mut progress = progress.add_child("validate");
189        let mut mismatches = Vec::new();
190        let start = std::time::Instant::now();
191        progress.init(
192            num_entries.map(|n| n + if ignore { n } else { 0 }),
193            gix::progress::count("paths"),
194        );
195
196        for (rela_path, baseline) in rx_base {
197            let entry = cache.at_entry(rela_path.as_str(), None)?;
198            match baseline {
199                Baseline::Attribute { assignments: expected } => {
200                    entry.matching_attributes(&mut matches);
201                    let fast_path_mismatch = matches
202                        .iter()
203                        .map(|m| m.assignment)
204                        .zip(expected.iter().map(Assignment::as_ref))
205                        .any(|(a, b)| a != b);
206                    if fast_path_mismatch {
207                        let actual_set = BTreeSet::from_iter(matches.iter().map(|m| m.assignment));
208                        let expected_set = BTreeSet::from_iter(expected.iter().map(Assignment::as_ref));
209                        let too_few_or_too_many =
210                            !(expected_set.sub(&actual_set).is_empty() && actual_set.sub(&expected_set).is_empty());
211                        if too_few_or_too_many {
212                            mismatches.push((
213                                rela_path,
214                                Mismatch::Attributes {
215                                    actual: matches.iter().map(|m| m.assignment.to_owned()).collect(),
216                                    expected,
217                                },
218                            ));
219                        }
220                    }
221                }
222                Baseline::Exclude { location } => {
223                    let match_ = entry.matching_exclude_pattern();
224                    if match_.is_some() != location.is_some() {
225                        mismatches.push((
226                            rela_path,
227                            Mismatch::Exclude {
228                                actual: match_.map(Into::into),
229                                expected: location,
230                            },
231                        ));
232                    }
233                }
234            }
235            progress.inc();
236        }
237
238        if let Some(stats) = statistics.then(|| cache.take_statistics()) {
239            out.flush()?;
240            writeln!(err, "{stats:#?}").ok();
241        }
242        progress.show_throughput(start);
243
244        if mismatches.is_empty() {
245            Ok(())
246        } else {
247            for (rela_path, mm) in &mismatches {
248                writeln!(err, "{rela_path}: {mm:#?}").ok();
249            }
250            bail!(
251                "{}: Validation failed with {} mismatches out of {}",
252                gix::path::realpath(repo.workdir().unwrap_or(repo.git_dir()))?.display(),
253                mismatches.len(),
254                progress.counter().load(Ordering::Relaxed)
255            );
256        }
257    }
258
259    enum Baseline {
260        Attribute { assignments: Vec<gix::attrs::Assignment> },
261        Exclude { location: Option<ExcludeLocation> },
262    }
263
264    #[derive(Debug)]
265    // See note on `Mismatch`
266    #[allow(dead_code)]
267    pub struct ExcludeLocation {
268        pub line: usize,
269        pub rela_source_file: String,
270        pub pattern: String,
271    }
272
273    #[derive(Debug)]
274    // We debug-print this structure, which makes all fields 'used', but it doesn't count.
275    // TODO: find a way to not have to do more work, but make the warning go away.
276    #[allow(dead_code)]
277    pub enum Mismatch {
278        Attributes {
279            actual: Vec<gix::attrs::Assignment>,
280            expected: Vec<gix::attrs::Assignment>,
281        },
282        Exclude {
283            actual: Option<ExcludeMatch>,
284            expected: Option<ExcludeLocation>,
285        },
286    }
287
288    #[derive(Debug)]
289    // See note on `Mismatch`
290    #[allow(dead_code)]
291    pub struct ExcludeMatch {
292        pub pattern: gix::glob::Pattern,
293        pub source: Option<PathBuf>,
294        pub sequence_number: usize,
295    }
296
297    impl From<gix::ignore::search::Match<'_>> for ExcludeMatch {
298        fn from(value: gix::ignore::search::Match<'_>) -> Self {
299            ExcludeMatch {
300                pattern: value.pattern.clone(),
301                source: value.source.map(ToOwned::to_owned),
302                sequence_number: value.sequence_number,
303            }
304        }
305    }
306
307    fn parse_exclude(line: &str) -> Option<(String, Baseline)> {
308        let (left, value) = line.split_at(line.find('\t')?);
309        let value = &value[1..];
310
311        let location = if left == "::" {
312            None
313        } else {
314            let mut tokens = left.split(':');
315            let source = tokens.next()?;
316            let line_number: usize = tokens.next()?.parse().ok()?;
317            let pattern = tokens.next()?;
318            Some(ExcludeLocation {
319                line: line_number,
320                rela_source_file: source.into(),
321                pattern: pattern.into(),
322            })
323        };
324        Some((value.to_string(), Baseline::Exclude { location }))
325    }
326
327    fn parse_attributes(lines: &mut Peekable<impl Iterator<Item = String>>) -> Option<(String, Baseline)> {
328        let first = lines.next()?;
329        let mut out = Vec::new();
330        let (path, assignment) = parse_attribute_line(&first)?;
331
332        let current = path.to_owned();
333        out.push(assignment.to_owned());
334        loop {
335            let next_line = match lines.peek() {
336                None => break,
337                Some(l) => l,
338            };
339            let (next_path, next_assignment) = parse_attribute_line(next_line)?;
340            if next_path != current {
341                return Some((current, Baseline::Attribute { assignments: out }));
342            } else {
343                out.push(next_assignment.to_owned());
344                lines.next();
345            }
346        }
347        Some((current, Baseline::Attribute { assignments: out }))
348    }
349
350    fn parse_attribute_line(line: &str) -> Option<(&str, gix::attrs::AssignmentRef<'_>)> {
351        use gix::{attrs::StateRef, bstr::ByteSlice};
352
353        let mut prev = None;
354        let mut tokens = line.splitn(3, |b| {
355            let is_match = b == ' ' && prev.take() == Some(':');
356            prev = Some(b);
357            is_match
358        });
359        if let Some(((mut path, attr), info)) = tokens.next().zip(tokens.next()).zip(tokens.next()) {
360            let state = match info {
361                "set" => StateRef::Set,
362                "unset" => StateRef::Unset,
363                "unspecified" => StateRef::Unspecified,
364                _ => StateRef::from_bytes(info.as_bytes()),
365            };
366            path = path.trim_end_matches(':');
367            let attr = attr.trim_end_matches(':');
368            let assignment = gix::attrs::AssignmentRef {
369                name: gix::attrs::NameRef::try_from(attr.as_bytes().as_bstr()).ok()?,
370                state,
371            };
372            Some((path, assignment))
373        } else {
374            None
375        }
376    }
377}