gitoxide_core/repository/attributes/
validate_baseline.rs1use 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::{Count, Progress, attrs::Assignment, bstr::BString};
22
23 use crate::{
24 OutputFormat,
25 repository::attributes::{query::attributes_cache, validate_baseline::Options},
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 at '{repo}' is bare - disabling git-ignore baseline as `git check-ignore` needs a worktree",
48 repo = repo.path().display()
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 #[allow(clippy::unnecessary_debug_formatting)]
118 repo.workdir()
119 .map(ToOwned::to_owned)
120 .ok_or_else(|| anyhow!("repository at {:?} must have a worktree checkout", repo.path()))
121 })
122 .transpose()?;
123 let feed_excludes = ignore.then(|| {
124 let (tx, rx) = std::sync::mpsc::sync_channel::<BString>(100);
125 std::thread::spawn({
126 let path = work_dir.expect("present if we are here");
127 let tx_base = tx_base.clone();
128 let mut progress = progress.add_child("excludes");
129 move || -> anyhow::Result<()> {
130 let mut child =
131 std::process::Command::from(gix::command::prepare(gix::path::env::exe_invocation()))
132 .args(["check-ignore", "--stdin", "-nv", "--no-index"])
133 .stdin(std::process::Stdio::piped())
134 .stdout(std::process::Stdio::piped())
135 .stderr(std::process::Stdio::null())
136 .current_dir(path)
137 .spawn()?;
138
139 std::thread::spawn({
140 let mut stdin = child.stdin.take().expect("we configured it");
141 move || -> anyhow::Result<()> {
142 progress.init(num_entries, gix::progress::count("paths"));
143 let start = std::time::Instant::now();
144 for path in rx {
145 progress.inc();
146 stdin.write_all(path.as_ref())?;
147 stdin.write_all(b"\n")?;
148 }
149 progress.show_throughput(start);
150 Ok(())
151 }
152 });
153
154 let stdout = std::io::BufReader::new(child.stdout.take().expect("we configured it"));
155 for line in stdout.lines() {
156 let line = line?;
157 if let Some(baseline) = parse_exclude(&line) {
158 if tx_base.send(baseline).is_err() {
159 child.kill().ok();
160 break;
161 }
162 } else {
163 eprintln!("Failed to parse line {line:?} - ignored");
164 }
165 }
166
167 Ok(())
168 }
169 });
170 tx
171 });
172 drop(tx_base);
173
174 std::thread::spawn(move || {
175 for path in paths {
176 if feed_attrs.send(path.clone()).is_err() {
177 break;
178 }
179 if feed_excludes.as_ref().is_some_and(|ch| ch.send(path).is_err()) {
180 break;
181 }
182 }
183 });
184
185 let (mut cache, _index) = attributes_cache(&repo)?;
186 let mut matches = cache.attribute_matches();
187 let mut progress = progress.add_child("validate");
188 let mut mismatches = Vec::new();
189 let start = std::time::Instant::now();
190 progress.init(
191 num_entries.map(|n| n + if ignore { n } else { 0 }),
192 gix::progress::count("paths"),
193 );
194
195 for (rela_path, baseline) in rx_base {
196 let entry = cache.at_entry(rela_path.as_str(), None)?;
197 match baseline {
198 Baseline::Attribute { assignments: expected } => {
199 entry.matching_attributes(&mut matches);
200 let fast_path_mismatch = matches
201 .iter()
202 .map(|m| m.assignment)
203 .zip(expected.iter().map(Assignment::as_ref))
204 .any(|(a, b)| a != b);
205 if fast_path_mismatch {
206 let actual_set = BTreeSet::from_iter(matches.iter().map(|m| m.assignment));
207 let expected_set = BTreeSet::from_iter(expected.iter().map(Assignment::as_ref));
208 let too_few_or_too_many =
209 !(expected_set.sub(&actual_set).is_empty() && actual_set.sub(&expected_set).is_empty());
210 if too_few_or_too_many {
211 mismatches.push((
212 rela_path,
213 Mismatch::Attributes {
214 actual: matches.iter().map(|m| m.assignment.to_owned()).collect(),
215 expected,
216 },
217 ));
218 }
219 }
220 }
221 Baseline::Exclude { location } => {
222 let match_ = entry.matching_exclude_pattern();
223 if match_.is_some() != location.is_some() {
224 mismatches.push((
225 rela_path,
226 Mismatch::Exclude {
227 actual: match_.map(Into::into),
228 expected: location,
229 },
230 ));
231 }
232 }
233 }
234 progress.inc();
235 }
236
237 if let Some(stats) = statistics.then(|| cache.take_statistics()) {
238 out.flush()?;
239 writeln!(err, "{stats:#?}").ok();
240 }
241 progress.show_throughput(start);
242
243 if mismatches.is_empty() {
244 Ok(())
245 } else {
246 for (rela_path, mm) in &mismatches {
247 writeln!(err, "{rela_path}: {mm:#?}").ok();
248 }
249 bail!(
250 "{}: Validation failed with {} mismatches out of {}",
251 gix::path::realpath(repo.workdir().unwrap_or(repo.git_dir()))?.display(),
252 mismatches.len(),
253 progress.counter().load(Ordering::Relaxed)
254 );
255 }
256 }
257
258 enum Baseline {
259 Attribute { assignments: Vec<gix::attrs::Assignment> },
260 Exclude { location: Option<ExcludeLocation> },
261 }
262
263 #[derive(Debug)]
264 #[allow(dead_code)]
266 pub struct ExcludeLocation {
267 pub line: usize,
268 pub rela_source_file: String,
269 pub pattern: String,
270 }
271
272 #[derive(Debug)]
273 #[allow(dead_code)]
276 pub enum Mismatch {
277 Attributes {
278 actual: Vec<gix::attrs::Assignment>,
279 expected: Vec<gix::attrs::Assignment>,
280 },
281 Exclude {
282 actual: Option<ExcludeMatch>,
283 expected: Option<ExcludeLocation>,
284 },
285 }
286
287 #[derive(Debug)]
288 #[allow(dead_code)]
290 pub struct ExcludeMatch {
291 pub pattern: gix::glob::Pattern,
292 pub source: Option<PathBuf>,
293 pub sequence_number: usize,
294 }
295
296 impl From<gix::ignore::search::Match<'_>> for ExcludeMatch {
297 fn from(value: gix::ignore::search::Match<'_>) -> Self {
298 ExcludeMatch {
299 pattern: value.pattern.clone(),
300 source: value.source.map(ToOwned::to_owned),
301 sequence_number: value.sequence_number,
302 }
303 }
304 }
305
306 fn parse_exclude(line: &str) -> Option<(String, Baseline)> {
307 let (left, value) = line.split_at(line.find('\t')?);
308 let value = &value[1..];
309
310 let location = if left == "::" {
311 None
312 } else {
313 let mut tokens = left.split(':');
314 let source = tokens.next()?;
315 let line_number: usize = tokens.next()?.parse().ok()?;
316 let pattern = tokens.next()?;
317 Some(ExcludeLocation {
318 line: line_number,
319 rela_source_file: source.into(),
320 pattern: pattern.into(),
321 })
322 };
323 Some((value.to_string(), Baseline::Exclude { location }))
324 }
325
326 fn parse_attributes(lines: &mut Peekable<impl Iterator<Item = String>>) -> Option<(String, Baseline)> {
327 let first = lines.next()?;
328 let mut out = Vec::new();
329 let (path, assignment) = parse_attribute_line(&first)?;
330
331 let current = path.to_owned();
332 out.push(assignment.to_owned());
333 loop {
334 let next_line = match lines.peek() {
335 None => break,
336 Some(l) => l,
337 };
338 let (next_path, next_assignment) = parse_attribute_line(next_line)?;
339 if next_path != current {
340 return Some((current, Baseline::Attribute { assignments: out }));
341 } else {
342 out.push(next_assignment.to_owned());
343 lines.next();
344 }
345 }
346 Some((current, Baseline::Attribute { assignments: out }))
347 }
348
349 fn parse_attribute_line(line: &str) -> Option<(&str, gix::attrs::AssignmentRef<'_>)> {
350 use gix::{attrs::StateRef, bstr::ByteSlice};
351
352 let mut prev = None;
353 let mut tokens = line.splitn(3, |b| {
354 let is_match = b == ' ' && prev.take() == Some(':');
355 prev = Some(b);
356 is_match
357 });
358 if let Some(((mut path, attr), info)) = tokens.next().zip(tokens.next()).zip(tokens.next()) {
359 let state = match info {
360 "set" => StateRef::Set,
361 "unset" => StateRef::Unset,
362 "unspecified" => StateRef::Unspecified,
363 _ => StateRef::from_bytes(info.as_bytes()),
364 };
365 path = path.trim_end_matches(':');
366 let attr = attr.trim_end_matches(':');
367 let assignment = gix::attrs::AssignmentRef {
368 name: gix::attrs::NameRef::try_from(attr.as_bytes().as_bstr()).ok()?,
369 state,
370 };
371 Some((path, assignment))
372 } else {
373 None
374 }
375 }
376}