Skip to main content

classify_calibrate/
classify_calibrate.rs

1//! Calibration run for `classify`: classifies every file under one or more
2//! corpus roots and prints **aggregates only** (no file lists), so it can be
3//! run on private codebases and the output shared.
4//!
5//! ```text
6//! cargo run --release --example classify_calibrate -- [--show-failures] ROOT...
7//! ```
8//!
9//! A ROOT that is a git checkout is scanned with `git ls-files` (exactly the
10//! tracked, pinned source); anything else is walked recursively without
11//! following symlinks. Prefix `binary:` to a ROOT (e.g. `binary:/tmp/planted`)
12//! to declare that every file under it is a binary: those files must all come
13//! back `Binary`.
14//!
15//! The gate for text roots: no C-family file (`.c .h .inc .cpp .cc .cxx .hpp
16//! .hxx`) is classified `Binary`. For C-family files that come back as
17//! `SourceText`, the run also reports the maximum NUL / control /
18//! invalid-UTF-8 counts and ratios seen, which is the headroom the
19//! thresholds in `classify` must keep.
20//!
21//! `--show-failures` prints the paths of gate failures to stderr. Leave it
22//! off when the corpus is private.
23
24use std::collections::BTreeMap;
25use std::fs::File;
26use std::io::Read;
27use std::path::{Path, PathBuf};
28use std::process::Command;
29
30use lang_parsing_substrate::classify::__byte_counts;
31use lang_parsing_substrate::{
32    classify, language_info_for_file, ClassifyLimits, FileClass, DEFAULT_PREFIX_LEN,
33};
34
35const C_FAMILY: &[&str] = &["c", "h", "inc", "cpp", "cc", "cxx", "hpp", "hxx"];
36
37#[derive(Default)]
38struct Max {
39    count: usize,
40    ratio: f64,
41}
42
43impl Max {
44    fn see(&mut self, n: usize, len: usize) {
45        self.count = self.count.max(n);
46        if len > 0 {
47            self.ratio = self.ratio.max(n as f64 / len as f64);
48        }
49    }
50}
51
52#[derive(Default)]
53struct Tally {
54    files: usize,
55    unreadable: usize,
56    /// class name -> (C-family count, other count)
57    classes: BTreeMap<&'static str, (usize, usize)>,
58    c_text: usize,
59    c_text_with_nul: usize,
60    c_text_with_control: usize,
61    c_text_with_invalid: usize,
62    max_nul: Max,
63    max_control: Max,
64    max_invalid: Max,
65    gate_failures: usize,
66    /// Non-C files with a registered source extension that came back `Binary`.
67    other_source_binary: usize,
68    /// Extension -> count, for every `Binary` result in a text root.
69    binary_exts: BTreeMap<String, usize>,
70}
71
72fn class_name(c: &FileClass) -> &'static str {
73    match c {
74        FileClass::Empty => "Empty",
75        FileClass::Oversize { .. } => "Oversize",
76        FileClass::Binary { .. } => "Binary",
77        FileClass::SourceText(_) => "SourceText",
78        _ => "Other",
79    }
80}
81
82fn list_files(root: &Path) -> Vec<PathBuf> {
83    if root.join(".git").exists() {
84        if let Ok(out) = Command::new("git")
85            .arg("-C")
86            .arg(root)
87            .args(["ls-files", "-z"])
88            .output()
89        {
90            if out.status.success() {
91                return out
92                    .stdout
93                    .split(|&b| b == 0)
94                    .filter(|p| !p.is_empty())
95                    .map(|p| root.join(String::from_utf8_lossy(p).as_ref()))
96                    .collect();
97            }
98        }
99    }
100    let mut files = Vec::new();
101    let mut stack = vec![root.to_path_buf()];
102    while let Some(dir) = stack.pop() {
103        let Ok(entries) = std::fs::read_dir(&dir) else {
104            continue;
105        };
106        for e in entries.flatten() {
107            let Ok(ft) = e.file_type() else { continue };
108            if ft.is_dir() && e.file_name() != ".git" {
109                stack.push(e.path());
110            } else if ft.is_file() {
111                files.push(e.path());
112            }
113        }
114    }
115    files
116}
117
118fn read_prefix(path: &Path) -> Option<(Vec<u8>, u64)> {
119    let meta = std::fs::symlink_metadata(path).ok()?;
120    if !meta.is_file() {
121        return None; // symlinks, gitlinks (submodules), FIFOs: not scanned
122    }
123    let mut buf = Vec::new();
124    File::open(path)
125        .ok()?
126        .take(DEFAULT_PREFIX_LEN as u64)
127        .read_to_end(&mut buf)
128        .ok()?;
129    Some((buf, meta.len()))
130}
131
132fn scan(root: &Path, expect_binary: bool, show_failures: bool) -> Tally {
133    let limits = ClassifyLimits::default();
134    let mut t = Tally::default();
135    for path in list_files(root) {
136        let Some((prefix, size)) = read_prefix(&path) else {
137            t.unreadable += 1;
138            continue;
139        };
140        t.files += 1;
141        let is_c = path
142            .extension()
143            .and_then(|e| e.to_str())
144            .is_some_and(|e| C_FAMILY.contains(&e.to_ascii_lowercase().as_str()));
145        let class = classify(&path, &prefix, size, &limits);
146        let entry = t.classes.entry(class_name(&class)).or_default();
147        if is_c {
148            entry.0 += 1;
149        } else {
150            entry.1 += 1;
151        }
152
153        let failed = if expect_binary {
154            !matches!(class, FileClass::Binary { .. })
155        } else {
156            is_c && matches!(class, FileClass::Binary { .. })
157        };
158        if failed {
159            t.gate_failures += 1;
160            if show_failures {
161                eprintln!("GATE FAILURE: {} -> {class:?}", path.display());
162            }
163        }
164
165        if !expect_binary && matches!(class, FileClass::Binary { .. }) {
166            let ext = path.extension().map_or_else(
167                || "(none)".into(),
168                |e| e.to_string_lossy().to_ascii_lowercase(),
169            );
170            *t.binary_exts.entry(ext).or_default() += 1;
171            if !is_c && language_info_for_file(&path).is_some() {
172                t.other_source_binary += 1;
173                if show_failures {
174                    eprintln!("NOTE non-C source -> Binary: {}", path.display());
175                }
176            }
177        }
178
179        if is_c && class.is_source_text() {
180            let (len, nul, control, invalid) = __byte_counts(&prefix, size);
181            t.c_text += 1;
182            t.c_text_with_nul += usize::from(nul > 0);
183            t.c_text_with_control += usize::from(control > 0);
184            t.c_text_with_invalid += usize::from(invalid > 0);
185            t.max_nul.see(nul, len);
186            t.max_control.see(control, len);
187            t.max_invalid.see(invalid, len);
188        }
189    }
190    t
191}
192
193fn main() {
194    let mut show_failures = false;
195    let mut roots = Vec::new();
196    for arg in std::env::args().skip(1) {
197        if arg == "--show-failures" {
198            show_failures = true;
199        } else {
200            roots.push(arg);
201        }
202    }
203    if roots.is_empty() {
204        eprintln!("usage: classify_calibrate [--show-failures] [binary:]ROOT...");
205        std::process::exit(2);
206    }
207
208    let mut total_failures = 0;
209    for arg in &roots {
210        let (expect_binary, root) = match arg.strip_prefix("binary:") {
211            Some(r) => (true, r),
212            None => (false, arg.as_str()),
213        };
214        let root = Path::new(root);
215        let name = root.file_name().map_or_else(
216            || root.display().to_string(),
217            |n| n.to_string_lossy().into_owned(),
218        );
219        let t = scan(root, expect_binary, show_failures);
220        total_failures += t.gate_failures;
221
222        let kind = if expect_binary {
223            "planted-binary"
224        } else {
225            "text"
226        };
227        println!(
228            "== {name} ({kind}): {} files, {} skipped",
229            t.files, t.unreadable
230        );
231        for (class, (c, other)) in &t.classes {
232            println!("   {class:<10} C-family {c:>7}   other {other:>7}");
233        }
234        if expect_binary {
235            println!("   gate (all Binary): {} failure(s)", t.gate_failures);
236        } else {
237            println!(
238                "   gate (no C-family Binary): {} failure(s)",
239                t.gate_failures
240            );
241            println!(
242                "   other registered-source extensions classified Binary: {}",
243                t.other_source_binary
244            );
245            let mut exts: Vec<_> = t.binary_exts.iter().collect();
246            exts.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
247            let top: Vec<String> = exts
248                .iter()
249                .take(12)
250                .map(|(e, n)| format!("{e}:{n}"))
251                .collect();
252            if !top.is_empty() {
253                println!("   Binary by extension (top 12): {}", top.join(" "));
254            }
255            println!(
256                "   C-family SourceText: {} files; with any NUL {}, control {}, invalid UTF-8 {}",
257                t.c_text, t.c_text_with_nul, t.c_text_with_control, t.c_text_with_invalid
258            );
259            println!(
260                "   max per file:  NUL {} ({:.4}%)  control {} ({:.4}%)  invalid UTF-8 {} ({:.4}%)",
261                t.max_nul.count,
262                t.max_nul.ratio * 100.0,
263                t.max_control.count,
264                t.max_control.ratio * 100.0,
265                t.max_invalid.count,
266                t.max_invalid.ratio * 100.0
267            );
268        }
269    }
270    println!("TOTAL gate failures: {total_failures}");
271    if total_failures > 0 {
272        std::process::exit(1);
273    }
274}