Skip to main content

aft_base/
file_kind.rs

1//! What kind of content a file holds, decided once for every tool that asks.
2//!
3//! grep prints the matching lines of source, docs, config and tests, and only
4//! counts the lines of lockfiles, generated and minified files, logs and
5//! captured command output, and JSON data files. inspect needs to know which
6//! files are generated, and aft_search ranks some kinds below source. This
7//! module is the one place that names those kinds.
8//!
9//! The name decides first, with no I/O: lockfile names, minified and
10//! source-map suffixes, generated path shapes, log and capture names. Only when
11//! the name does not decide, and only for extensions where content can change
12//! the answer, does the classifier look at the start of the file: at most
13//! [`HEAD_BYTES`], or [`JSON_HEAD_BYTES`] for JSON documents, whose long-line
14//! test needs more. A file is never read past that bound, however long its
15//! first line is.
16//!
17//! Whether a file is a test or test support (fixtures, mocks, snapshots) is a
18//! separate flag, [`TestRole`], decided by the same path predicates inspect and
19//! aft_search already use. A captured `stderr` under `tests/fixtures/` is
20//! command output and test support at once.
21
22use std::collections::HashMap;
23use std::io::Read;
24#[cfg(windows)]
25use std::path::PathBuf;
26use std::path::{Component, Path};
27use std::time::SystemTime;
28
29/// Bytes read from the start of a file for the generated-header and minified
30/// checks.
31pub const HEAD_BYTES: usize = 8 * 1024;
32
33pub mod generated;
34
35/// Bytes read from the start of a JSON document for the long-line test.
36pub(crate) const JSON_HEAD_BYTES: usize = 64 * 1024;
37
38/// Lines at the top of a file searched for a generated-code header.
39pub(crate) const GENERATED_HEADER_LINES: usize = 5;
40
41/// Shortest JSON line, in bytes, taken as a sign that the file holds data
42/// (a captured file body, a serialized list) rather than hand-edited
43/// settings.
44pub(crate) const DATA_JSON_LONG_LINE_BYTES: usize = 256;
45
46/// Smallest head that can be judged minified by line density.
47const MINIFIED_MIN_HEAD_BYTES: usize = 2 * 1024;
48
49/// What a file's content is, for deciding how search output treats it.
50#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
51pub enum ContentKind {
52    /// Source code, docs and configuration: what a reader searches for.
53    Text,
54    /// A package manager's lockfile (`bun.lock`, `Cargo.lock`, `*.lock`).
55    Lockfile,
56    /// Generated code: a generated path shape, a source map, or a
57    /// generated-code header.
58    Generated,
59    /// A minified bundle, by name (`*.min.js`) or by line density.
60    Minified,
61    /// A log or captured command output (`*.log`, `stdout`, `*.stderr.txt`,
62    /// line-delimited JSON records).
63    Capture,
64    /// A JSON document holding data rather than configuration.
65    DataJson,
66}
67
68impl ContentKind {
69    /// True for every kind grep counts instead of printing by default.
70    pub fn is_counted(self) -> bool {
71        self != Self::Text
72    }
73
74    /// The kind as grep names it in one entry (`3 lines (lockfile)`).
75    pub fn label(self) -> &'static str {
76        match self {
77            Self::Text => "text",
78            Self::Lockfile => "lockfile",
79            Self::Generated => "generated",
80            Self::Minified => "minified",
81            Self::Capture => "log or command output",
82            Self::DataJson => "JSON data",
83        }
84    }
85
86    /// The kind as grep names several files of it (`+3 more lockfiles`).
87    pub fn plural(self) -> &'static str {
88        match self {
89            Self::Text => "text files",
90            Self::Lockfile => "lockfiles",
91            Self::Generated => "generated files",
92            Self::Minified => "minified files",
93            Self::Capture => "log or command-output files",
94            Self::DataJson => "JSON data files",
95        }
96    }
97}
98
99/// Whether a file is an automated test, test support, or neither.
100#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
101pub enum TestRole {
102    None,
103    /// An automated-test file (`*.test.ts`, `tests/`, `*_test.go`, ...).
104    Test,
105    /// Test support: fixtures, mocks, snapshots, corpora.
106    Support,
107}
108
109/// A file's content kind, its test role, and what decided the kind.
110#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
111pub struct FileKind {
112    pub content: ContentKind,
113    pub test: TestRole,
114    /// The file name or name part that decided `content`: a lockfile name
115    /// (`bun.lock`), a suffix (`.log`, `.json`, `.min.js`, `.lock`), or a name
116    /// segment (`stdout`, `stderr`). `None` when the path shape or the
117    /// content decided it. An `include` glob that names the marker asks for
118    /// files of this kind.
119    pub marker: Option<&'static str>,
120}
121
122impl FileKind {
123    /// Whether the marker is a suffix of the file name (`.log`) rather than
124    /// a whole name (`bun.lock`) or a name segment (`stdout`).
125    pub fn marker_is_suffix(&self) -> bool {
126        self.marker.is_some_and(|marker| marker.starts_with('.'))
127    }
128}
129
130/// Lockfiles by exact file name, compared ASCII case-insensitively.
131const LOCKFILE_NAMES: &[&str] = &[
132    "bun.lock",
133    "bun.lockb",
134    "package-lock.json",
135    "npm-shrinkwrap.json",
136    "yarn.lock",
137    "pnpm-lock.yaml",
138    "deno.lock",
139    "Cargo.lock",
140    "go.sum",
141    "go.work.sum",
142    "poetry.lock",
143    "uv.lock",
144    "Pipfile.lock",
145    "pdm.lock",
146    "pixi.lock",
147    "conda-lock.yml",
148    "Gemfile.lock",
149    "gems.locked",
150    "composer.lock",
151    "mix.lock",
152    "pubspec.lock",
153    "Podfile.lock",
154    "Package.resolved",
155    "Cartfile.resolved",
156    "packages.lock.json",
157    "paket.lock",
158    "flake.lock",
159    "gradle.lockfile",
160    ".terraform.lock.hcl",
161    "renv.lock",
162    "cabal.project.freeze",
163    "stack.yaml.lock",
164    "shard.lock",
165    "rebar.lock",
166    "MODULE.bazel.lock",
167    "conan.lock",
168    "Chart.lock",
169    "jsonnetfile.lock.json",
170];
171
172const MINIFIED_SUFFIXES: &[&str] = &[".min.js", ".min.mjs", ".min.cjs", ".min.css"];
173
174/// Source maps of compiled output. A bare `*.map` is not enough: the
175/// extension is used for unrelated files too.
176const SOURCE_MAP_SUFFIXES: &[&str] = &[".js.map", ".mjs.map", ".cjs.map", ".css.map", ".ts.map"];
177
178/// Extensions of logs and line-delimited records. `.jsonl` and `.ndjson`
179/// belong here rather than with JSON data: one record per line is the shape
180/// of a log. `.out` and `.err` alone are not captures, because test suites
181/// keep expected outputs under those names.
182const CAPTURE_EXTENSIONS: &[(&str, &str)] = &[
183    ("log", ".log"),
184    ("jsonl", ".jsonl"),
185    ("ndjson", ".ndjson"),
186    ("stdout", ".stdout"),
187    ("stderr", ".stderr"),
188];
189
190/// Extensions a `stdout`/`stderr` name segment may end in and still be a
191/// capture (`stderr.txt`, `bash-1.stdout.txt`, `run.stdout.out`).
192const CAPTURE_SEGMENT_EXTENSIONS: &[&str] = &["txt", "log", "out"];
193
194const JSON_DATA_EXTENSIONS: &[(&str, &str)] = &[("json", ".json"), ("geojson", ".geojson")];
195
196const MINIFIED_CANDIDATE_EXTENSIONS: &[&str] = &["js", "mjs", "cjs", "css"];
197
198/// Name the kind of `path` with no cache. See [`FileKindCache::classify`].
199pub fn classify(project_root: &Path, path: &Path, held_bytes: Option<&[u8]>) -> FileKind {
200    FileKindCache::new().classify(project_root, path, held_bytes)
201}
202
203/// Kinds of files already examined in one request, so a file seen several
204/// times is read at most once. Entries are keyed by path, length and
205/// modification time, so a file rewritten mid-request is examined again.
206#[derive(Debug, Default)]
207pub struct FileKindCache {
208    entries: HashMap<(std::path::PathBuf, u64, Option<SystemTime>), FileKind>,
209}
210
211impl FileKindCache {
212    pub fn new() -> Self {
213        Self::default()
214    }
215
216    /// Name the kind of `path`. Only the part of `path` below
217    /// `project_root` decides path shapes and the test role; a relative
218    /// `path` is taken as already relative to the root.
219    ///
220    /// `held_bytes`, when the caller already holds the file's bytes, replaces
221    /// the bounded read; only their first [`HEAD_BYTES`] (or
222    /// [`JSON_HEAD_BYTES`]) are looked at.
223    pub fn classify(
224        &mut self,
225        project_root: &Path,
226        path: &Path,
227        held_bytes: Option<&[u8]>,
228    ) -> FileKind {
229        let relative = relative_within(project_root, path);
230        let test = test_role(relative.as_deref().unwrap_or(path));
231        let file_name = path
232            .file_name()
233            .map(|name| name.to_string_lossy().into_owned())
234            .unwrap_or_default();
235        if let Some((content, marker)) = classify_by_name(relative.as_deref(), &file_name) {
236            return FileKind {
237                content,
238                test,
239                marker,
240            };
241        }
242        let checks = ContentChecks::for_name(&file_name);
243        if !checks.any() {
244            return FileKind {
245                content: ContentKind::Text,
246                test,
247                marker: None,
248            };
249        }
250
251        let (content, marker) = if let Some(bytes) = held_bytes {
252            checks.decide(&file_name, bytes)
253        } else {
254            let absolute = if path.is_absolute() {
255                path.to_path_buf()
256            } else {
257                project_root.join(path)
258            };
259            let metadata = std::fs::metadata(&absolute).ok();
260            let key = (
261                absolute.clone(),
262                metadata.as_ref().map(|meta| meta.len()).unwrap_or(0),
263                metadata.as_ref().and_then(|meta| meta.modified().ok()),
264            );
265            if let Some(kind) = self.entries.get(&key) {
266                return FileKind { test, ..*kind };
267            }
268            let head = read_head(&absolute, checks.head_limit()).unwrap_or_default();
269            let decided = checks.decide(&file_name, &head);
270            self.entries.insert(
271                key,
272                FileKind {
273                    content: decided.0,
274                    test,
275                    marker: decided.1,
276                },
277            );
278            decided
279        };
280        FileKind {
281            content,
282            test,
283            marker,
284        }
285    }
286}
287
288/// The kind a file name alone decides (lockfile names, minified and
289/// source-map suffixes, generated path shapes, log and capture names), or
290/// `None` when only content can tell. `relative` is the project-relative path, or
291/// `None` for a file outside the project (or one whose spelling could not be
292/// matched to the root), whose folders never decide a kind: its generated
293/// shape is then judged on the file name alone (`api_pb.ts`,
294/// `types.generated.ts`).
295fn classify_by_name(
296    relative: Option<&Path>,
297    file_name: &str,
298) -> Option<(ContentKind, Option<&'static str>)> {
299    let lower = file_name.to_ascii_lowercase();
300    let extension = extension_of(&lower);
301
302    // 1. Lockfiles.
303    if let Some(name) = LOCKFILE_NAMES
304        .iter()
305        .find(|name| name.eq_ignore_ascii_case(file_name))
306    {
307        return Some((ContentKind::Lockfile, Some(*name)));
308    }
309    if extension == "lock" {
310        return Some((ContentKind::Lockfile, Some(".lock")));
311    }
312
313    // 2. Minified bundles by name.
314    if let Some(suffix) = MINIFIED_SUFFIXES
315        .iter()
316        .find(|suffix| lower.ends_with(*suffix))
317    {
318        return Some((ContentKind::Minified, Some(*suffix)));
319    }
320
321    // 3. Source maps, then the generated path shapes.
322    if let Some(suffix) = SOURCE_MAP_SUFFIXES
323        .iter()
324        .find(|suffix| lower.ends_with(*suffix))
325    {
326        return Some((ContentKind::Generated, Some(*suffix)));
327    }
328    if path_has_generated_shape(relative.unwrap_or(Path::new(file_name))) {
329        return Some((ContentKind::Generated, None));
330    }
331
332    // 4. Logs and command output, by name only. A folder name never decides
333    // (`logs/README.md`, `log/contract.mjs` stay text), and neither does a
334    // source extension (`log.rs`, `stdout.rs`, `foo.log.ts`).
335    if let Some((_, marker)) = CAPTURE_EXTENSIONS
336        .iter()
337        .find(|(candidate, _)| *candidate == extension)
338    {
339        return Some((ContentKind::Capture, Some(*marker)));
340    }
341    if is_rotated_log(&lower) {
342        return Some((ContentKind::Capture, Some(".log")));
343    }
344    if let Some(segment) = capture_segment(&lower, extension) {
345        return Some((ContentKind::Capture, Some(segment)));
346    }
347    None
348}
349
350/// The extension as `Path::extension` reads it, lowercased: the part after
351/// the last dot, empty for no dot or a leading dot only (`.bashrc`).
352fn extension_of(lower_name: &str) -> &str {
353    match lower_name.rfind('.') {
354        Some(0) | None => "",
355        Some(dot) => &lower_name[dot + 1..],
356    }
357}
358
359/// `app.log.1`, `server.log.20`: a log rotated with a numeric suffix.
360fn is_rotated_log(lower_name: &str) -> bool {
361    let Some((head, digits)) = lower_name.rsplit_once('.') else {
362        return false;
363    };
364    !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit()) && head.ends_with(".log")
365}
366
367/// `stdout`/`stderr` when the file is named exactly that, or carries it as a
368/// dot-separated name segment and ends in a plain-text extension
369/// (`stderr.txt`, `bash-1.stdout.txt`).
370fn capture_segment(lower_name: &str, extension: &str) -> Option<&'static str> {
371    let as_marker = |segment: &str| match segment {
372        "stdout" => Some("stdout"),
373        "stderr" => Some("stderr"),
374        _ => None,
375    };
376    if extension.is_empty() {
377        return as_marker(lower_name);
378    }
379    if !CAPTURE_SEGMENT_EXTENSIONS.contains(&extension) {
380        return None;
381    }
382    let stem = &lower_name[..lower_name.len() - extension.len() - 1];
383    stem.split('.').find_map(as_marker)
384}
385
386/// Which content checks apply to a file whose name did not decide its kind.
387#[derive(Clone, Copy, Debug)]
388struct ContentChecks {
389    generated_header: bool,
390    minified_density: bool,
391    json_data: Option<&'static str>,
392}
393
394impl ContentChecks {
395    fn for_name(file_name: &str) -> Self {
396        let lower = file_name.to_ascii_lowercase();
397        let extension = extension_of(&lower);
398        let json_data = JSON_DATA_EXTENSIONS
399            .iter()
400            .find(|(candidate, _)| *candidate == extension)
401            .map(|(_, marker)| *marker);
402        let minified_density = MINIFIED_CANDIDATE_EXTENSIONS.contains(&extension);
403        let generated_header =
404            json_data.is_some() || minified_density || is_source_file_name(file_name);
405        Self {
406            generated_header,
407            minified_density,
408            json_data,
409        }
410    }
411
412    fn any(self) -> bool {
413        self.generated_header || self.minified_density || self.json_data.is_some()
414    }
415
416    fn head_limit(self) -> usize {
417        if self.json_data.is_some() {
418            JSON_HEAD_BYTES
419        } else {
420            HEAD_BYTES
421        }
422    }
423
424    /// The content checks, run on the first bytes of a file whose name did
425    /// not decide its kind.
426    fn decide(self, file_name: &str, bytes: &[u8]) -> (ContentKind, Option<&'static str>) {
427        let head = &bytes[..bytes.len().min(self.head_limit())];
428        let short_head = &head[..head.len().min(HEAD_BYTES)];
429        if self.generated_header && head_has_generated_marker(short_head) {
430            return (ContentKind::Generated, None);
431        }
432        if self.minified_density && head_is_minified(short_head) {
433            return (ContentKind::Minified, None);
434        }
435        if let Some(marker) = self.json_data {
436            if is_json_data(file_name, short_head, head) {
437                return (ContentKind::DataJson, Some(marker));
438            }
439        }
440        (ContentKind::Text, None)
441    }
442}
443
444#[rustfmt::skip]
445test_support_visibility! {
446
447/// A source-language file whose header may mark it generated. Docs and
448/// config formats are excluded: their text is what a reader searches.
449fn is_source_file_name(file_name: &str) -> bool {
450    use crate::lang_id::LangId;
451    matches!(
452        crate::lang_id::language_by_extension(Path::new(file_name)),
453        Some(lang) if !matches!(lang, LangId::Markdown | LangId::Html | LangId::Yaml | LangId::Toml)
454    )
455}
456}
457
458/// At least 2 KiB of head with at most one newline per KiB of it: lines
459/// that long are what minifiers produce and hand-written code rarely has.
460/// Whether the file at `path` with these bytes is a minified bundle: by
461/// name (`*.min.js`, `*.min.css`), or a JavaScript or CSS file whose first
462/// 8 KiB has almost no line breaks. The index store neither parses such a
463/// file for the call graph nor embeds it for meaning search, since its names
464/// are mangled and its chunks say nothing a search could use; grep still
465/// searches it.
466pub fn is_minified(path: &str, bytes: &[u8]) -> bool {
467    let lower = path.to_ascii_lowercase();
468    if MINIFIED_SUFFIXES
469        .iter()
470        .any(|suffix| lower.ends_with(suffix))
471    {
472        return true;
473    }
474    let file_name = lower.rsplit('/').next().unwrap_or(&lower);
475    MINIFIED_CANDIDATE_EXTENSIONS.contains(&extension_of(file_name))
476        && head_is_minified(&bytes[..bytes.len().min(HEAD_BYTES)])
477}
478
479fn head_is_minified(head: &[u8]) -> bool {
480    head.len() >= MINIFIED_MIN_HEAD_BYTES
481        && head.iter().filter(|byte| **byte == b'\n').count() <= head.len() / 1024
482}
483
484/// A JSON document that holds data: not a hand-edited manifest, not a
485/// schema, and with a line of at least [`DATA_JSON_LONG_LINE_BYTES`] bytes in
486/// its first [`JSON_HEAD_BYTES`]. Size alone does not make data here: a long
487/// file of short lines (a provenance record, a config schema) stays text.
488fn is_json_data(file_name: &str, short_head: &[u8], head: &[u8]) -> bool {
489    let lower = file_name.to_ascii_lowercase();
490    if is_hand_edited_manifest(&lower) || is_schema(&lower, short_head) {
491        return false;
492    }
493    head.split(|byte| *byte == b'\n')
494        .any(|line| line.len() >= DATA_JSON_LONG_LINE_BYTES)
495}
496
497/// Hand-edited manifests that share the JSON extension but describe a
498/// project rather than hold data about it.
499pub(crate) fn is_hand_edited_manifest(lower_name: &str) -> bool {
500    lower_name.starts_with('.')
501        || matches!(
502            lower_name,
503            "package.json" | "composer.json" | "deno.json" | "app.json" | "manifest.json"
504        )
505        || ((lower_name.starts_with("tsconfig") || lower_name.starts_with("jsconfig"))
506            && lower_name.ends_with(".json"))
507}
508
509/// A JSON Schema document or a config that names its schema: by name
510/// (`*.schema.json`) or by a `"$schema"` key near the top.
511fn is_schema(lower_name: &str, short_head: &[u8]) -> bool {
512    lower_name.ends_with(".schema.json")
513        || memchr::memmem::find(short_head, br#""$schema""#).is_some()
514}
515
516/// Whether the first [`GENERATED_HEADER_LINES`] lines of `head` carry a
517/// generated-code marker. Only the first [`HEAD_BYTES`] are looked at.
518pub fn head_has_generated_marker(head: &[u8]) -> bool {
519    let head = &head[..head.len().min(HEAD_BYTES)];
520    text_has_generated_marker(&String::from_utf8_lossy(head))
521}
522
523/// The generated-code markers inspect has always used, over the first
524/// [`GENERATED_HEADER_LINES`] lines of `text`.
525fn text_has_generated_marker(text: &str) -> bool {
526    let prefix = text
527        .lines()
528        .take(GENERATED_HEADER_LINES)
529        .collect::<Vec<_>>()
530        .join("\n")
531        .to_ascii_lowercase();
532
533    if prefix.contains("@generated")
534        || prefix.contains("code generated by")
535        || prefix.contains("do not edit")
536    {
537        return true;
538    }
539
540    prefix.contains("eslint-disable")
541        && (prefix.contains("codegen")
542            || prefix.contains("generated")
543            || prefix.contains("auto-generated")
544            || prefix.contains("automatically generated"))
545}
546
547/// Whether the file at `path` starts with a generated-code header, reading
548/// at most [`HEAD_BYTES`].
549pub(crate) fn file_head_has_generated_marker(path: &Path) -> bool {
550    read_head(path, HEAD_BYTES).is_some_and(|head| head_has_generated_marker(&head))
551}
552
553/// The first `limit` bytes of the file at `path`, or `None` when it cannot
554/// be opened. Never reads past `limit`.
555pub fn read_head(path: &Path, limit: usize) -> Option<Vec<u8>> {
556    let file = crate::project_content::open(path).ok()?;
557    let mut head = Vec::with_capacity(limit.min(HEAD_BYTES));
558    let mut reader = read_probe::Counting::new(file, path).take(limit as u64);
559    reader.read_to_end(&mut head).ok()?;
560    Some(head)
561}
562
563/// Generated path shapes: a `gen`, `generated` or `__generated__` folder,
564/// protobuf outputs (`*_pb.ts`), or a `.generated.` name.
565pub(crate) fn path_has_generated_shape(path: &Path) -> bool {
566    if path.components().any(is_generated_segment) {
567        return true;
568    }
569
570    let Some(file_name) = path.file_name().and_then(|name| name.to_str()) else {
571        return false;
572    };
573    let file_name = file_name.to_ascii_lowercase();
574    file_name.ends_with("_pb.ts")
575        || file_name.ends_with("_pb.js")
576        || file_name.ends_with("_pb.d.ts")
577        || file_name.contains(".generated.")
578}
579
580fn is_generated_segment(component: Component<'_>) -> bool {
581    let Component::Normal(segment) = component else {
582        return false;
583    };
584    matches!(
585        segment.to_str().map(str::to_ascii_lowercase).as_deref(),
586        Some("gen" | "generated" | "__generated__")
587    )
588}
589
590/// Only the part of `path` below `project_root` decides a generated shape;
591/// folders above the project (a checkout under `~/gen/`) must not.
592pub fn relative_shape_is_generated(project_root: &Path, path: &Path) -> bool {
593    relative_within(project_root, path).is_some_and(|relative| path_has_generated_shape(&relative))
594}
595
596/// The part of `path` below `project_root`, or `None` when `path` is not
597/// under it. A plainly relative `path` (no root, no drive) is taken as
598/// already relative to the root and returned as is.
599///
600/// The prefix match is tried first whatever the spelling, because on Windows
601/// a path such as `/home/gen/project/src/main.rs` has a root but no drive, so
602/// `Path::is_absolute` calls it relative even though it names folders above
603/// the project. On Windows the root and the path can also arrive in different
604/// spellings (`\\?\C:\...` from canonicalization versus `C:\...`), so a
605/// failed prefix match is retried on normalized copies. A rooted path that
606/// still does not match (a Windows short-name alias such as `PROJEC~1`, or a
607/// path on another drive) is outside the
608/// root: callers then decide by the file name alone and never by folder
609/// names that may lie above the project.
610fn relative_within(project_root: &Path, path: &Path) -> Option<std::path::PathBuf> {
611    if let Ok(relative) = path.strip_prefix(project_root) {
612        return Some(relative.to_path_buf());
613    }
614    let rooted = path
615        .components()
616        .any(|component| matches!(component, Component::Prefix(_) | Component::RootDir));
617    if !rooted {
618        return Some(path.to_path_buf());
619    }
620    #[cfg(windows)]
621    {
622        let root = crate::windows_path::normalize_windows_path(project_root);
623        let path = crate::windows_path::normalize_windows_path(path);
624        let lowercase = |value: &Path| PathBuf::from(value.to_string_lossy().to_lowercase());
625        if let Ok(relative) = lowercase(&path).strip_prefix(lowercase(&root)) {
626            return Some(relative.to_path_buf());
627        }
628    }
629    None
630}
631
632fn test_role(relative: &Path) -> TestRole {
633    let relative = relative.to_string_lossy();
634    if crate::file_kind::is_test_file(&relative) {
635        TestRole::Test
636    } else if crate::file_kind::is_test_support_file(&relative) {
637        TestRole::Support
638    } else {
639        TestRole::None
640    }
641}
642
643#[rustfmt::skip]
644test_support_visibility! {
645/// Byte accounting for content reads, so tests can prove a read stayed
646/// within its bound. Outside tests the wrapper only forwards.
647pub(crate) mod read_probe {
648    use std::io::Read;
649    use std::path::Path;
650    #[cfg(any(test, feature = "test-support"))]
651    use std::path::PathBuf;
652
653    #[cfg(any(test, feature = "test-support"))]
654    static BYTES_READ: std::sync::OnceLock<
655        std::sync::Mutex<std::collections::BTreeMap<PathBuf, usize>>,
656    > = std::sync::OnceLock::new();
657
658    /// A reader that, in tests, records how many bytes it returned for its
659    /// path.
660    pub(crate) struct Counting<R> {
661        inner: R,
662        #[cfg(any(test, feature = "test-support"))]
663        path: PathBuf,
664    }
665
666    impl<R> Counting<R> {
667        pub(crate) fn new(inner: R, path: &Path) -> Self {
668            #[cfg(not(any(test, feature = "test-support")))]
669            let _ = path;
670            Self {
671                inner,
672                #[cfg(any(test, feature = "test-support"))]
673                path: path.to_path_buf(),
674            }
675        }
676    }
677
678    impl<R: Read> Read for Counting<R> {
679        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
680            let read = self.inner.read(buf)?;
681            #[cfg(any(test, feature = "test-support"))]
682            if let Ok(mut bytes) = BYTES_READ.get_or_init(Default::default).lock() {
683                *bytes.entry(self.path.clone()).or_default() += read;
684            }
685            Ok(read)
686        }
687    }
688
689    /// Bytes read so far from `path` through a [`Counting`] reader.
690    #[cfg(any(test, feature = "test-support"))]
691    pub fn bytes_read(path: &Path) -> usize {
692        BYTES_READ
693            .get_or_init(Default::default)
694            .lock()
695            .map(|bytes| bytes.get(path).copied().unwrap_or(0))
696            .unwrap_or(0)
697    }
698}
699}
700
701/// Whether a project-relative path is a test-support / standalone file that
702/// should be EXCLUDED from dead_code and unused_exports reporting. These files
703/// (test fixtures, corpora, mock data, snapshots) are consumed by file path or
704/// loaded dynamically — never imported as modules — so static reachability
705/// always reports their symbols as dead/unused. They are noise, not signal.
706///
707/// Edges FROM these files are still honored elsewhere (their imports keep
708/// product code live); only their own exported symbols are suppressed from the
709/// dead/unused lists. The match is on conventional directory names anywhere in
710/// the path, kept conservative to avoid hiding real product directories.
711pub fn is_test_support_file(relative_path: &str) -> bool {
712    let normalized = relative_path.replace('\\', "/");
713    normalized.split('/').any(is_test_support_dir_name)
714}
715
716/// Whether one path segment is a conventional test-support directory name
717/// (fixtures, corpora, mock data, snapshots). Shared by the reporting filter
718/// above and the language-server walk, which starts no server for these
719/// directories.
720pub fn is_test_support_dir_name(segment: &str) -> bool {
721    matches!(
722        segment,
723        "fixtures"
724            | "__fixtures__"
725            | "testdata"
726            | "test-data"
727            | "__mocks__"
728            | "__snapshots__"
729            | "corpora"
730    )
731}
732
733/// Whether a project-relative path is an actual automated-test file (unit /
734/// integration / spec), as opposed to product code. Search uses this to hide test
735/// files by default; inspect uses it to distinguish test-origin references from
736/// production usage without excluding the test files from analysis.
737///
738/// This is intentionally SEPARATE from `is_test_support_file`: test-support files
739/// are reporting noise excluded by path, while real tests remain scanned and can
740/// move otherwise-dead production symbols into the test-only bucket. Matching is
741/// high-precision to avoid hiding real product code.
742pub fn is_test_file(relative_path: &str) -> bool {
743    let normalized = relative_path.replace('\\', "/");
744
745    // Directory-segment conventions: `__tests__` (JS/TS) and a `tests` test root
746    // (Rust integration tests, Python). Singular `test`/`spec` are omitted —
747    // they collide with product modules and their files are caught by name below.
748    if normalized
749        .split('/')
750        .any(|segment| matches!(segment, "__tests__" | "__test__" | "tests"))
751    {
752        return true;
753    }
754
755    let file = normalized.rsplit('/').next().unwrap_or(&normalized);
756    let lower = file.to_ascii_lowercase();
757
758    // `*.test.<ext>` / `*.spec.<ext>` — JS/TS/JSX/TSX/Vue/mjs/cjs/…
759    if lower.contains(".test.") || lower.contains(".spec.") {
760        return true;
761    }
762
763    // Per-language filename suffixes (lowercase conventions).
764    if lower.ends_with("_test.rs")
765        || lower.ends_with("_test.go")
766        || lower.ends_with("_test.py")
767        || lower.ends_with("_test.rb")
768        || lower.ends_with("_test.exs")
769        || lower.ends_with("_spec.rb")
770        || (lower.starts_with("test_") && lower.ends_with(".py"))
771    {
772        return true;
773    }
774
775    // CamelCase test classes — matched case-SENSITIVELY so product files like
776    // `latest.java` (which ends with "test.java" lowercased) don't false-match.
777    const CAMEL_SUFFIXES: &[&str] = &[
778        "Test.java",
779        "Tests.java",
780        "Test.kt",
781        "Tests.kt",
782        "Test.cs",
783        "Tests.cs",
784        "Test.swift",
785        "Tests.swift",
786        "Test.scala",
787        "Spec.scala",
788    ];
789    CAMEL_SUFFIXES.iter().any(|suffix| file.ends_with(suffix))
790}
791
792#[cfg(test)]
793mod tests {
794
795    use super::*;
796
797    fn kind_of(root: &Path, relative: &str) -> FileKind {
798        classify(root, &root.join(relative), None)
799    }
800
801    fn content_of(relative: &str) -> (ContentKind, Option<&'static str>) {
802        let root = Path::new("/project");
803        let kind = classify(root, &root.join(relative), Some(b"".as_slice()));
804        (kind.content, kind.marker)
805    }
806
807    #[test]
808    fn file_kind_every_lockfile_name_is_a_lockfile_marked_by_its_name() {
809        for name in LOCKFILE_NAMES {
810            assert_eq!(
811                content_of(&format!("sub/{name}")),
812                (ContentKind::Lockfile, Some(*name)),
813                "{name}"
814            );
815            let lower = name.to_ascii_lowercase();
816            assert_eq!(
817                content_of(&lower).0,
818                ContentKind::Lockfile,
819                "lowercased {lower}"
820            );
821        }
822        assert_eq!(
823            content_of("vendor/custom.lock"),
824            (ContentKind::Lockfile, Some(".lock"))
825        );
826    }
827
828    #[test]
829    fn file_kind_capture_names_are_logs_or_command_output() {
830        let cases: &[(&str, &str)] = &[
831            ("runs/io/stdout", "stdout"),
832            ("runs/io/stderr", "stderr"),
833            ("runs/stderr.txt", "stderr"),
834            ("receipts/bash-1.stdout.txt", "stdout"),
835            ("receipts/run.stdout.out", "stdout"),
836            ("receipts/run.stderr.log", ".log"),
837            ("var/app.log", ".log"),
838            ("var/app.log.1", ".log"),
839            ("var/app.log.20", ".log"),
840            ("records/x.jsonl", ".jsonl"),
841            ("records/x.ndjson", ".ndjson"),
842            ("receipts/build.stdout", ".stdout"),
843            ("receipts/build.stderr", ".stderr"),
844        ];
845        for (path, marker) in cases {
846            assert_eq!(
847                content_of(path),
848                (ContentKind::Capture, Some(*marker)),
849                "{path}"
850            );
851        }
852    }
853
854    #[test]
855    fn file_kind_capture_rule_never_catches_source_docs_or_folder_names() {
856        let dir = tempfile::tempdir().unwrap();
857        let root = dir.path();
858        let never = [
859            "src/log.rs",
860            "src/logger.ts",
861            "src/stdout.rs",
862            "src/stderr.ts",
863            "tools/capture.py",
864            "tools/capture-sink.js",
865            "src/foo.log.ts",
866            "CHANGELOG.md",
867            "changelog",
868            "notes/release.log.md",
869            "test/common-auth-094-adoption/log/contract.mjs",
870            "logs/README.md",
871            "receipts/README.md",
872            "research/v1/analysis.py",
873            "tests/golden/expected.out",
874            "tests/golden/expected.err",
875            "src/stdout_writer.go",
876        ];
877        for path in never {
878            let file = root.join(path);
879            std::fs::create_dir_all(file.parent().unwrap()).unwrap();
880            std::fs::write(&file, "const needle = 1;\n").unwrap();
881            assert_eq!(kind_of(root, path).content, ContentKind::Text, "{path}");
882        }
883    }
884
885    #[test]
886    fn file_kind_minified_and_generated_names() {
887        assert_eq!(
888            content_of("vendor/highlight.min.js"),
889            (ContentKind::Minified, Some(".min.js"))
890        );
891        assert_eq!(
892            content_of("dist/site.MIN.CSS"),
893            (ContentKind::Minified, Some(".min.css"))
894        );
895        assert_eq!(
896            content_of("dist/app.js.map"),
897            (ContentKind::Generated, Some(".js.map"))
898        );
899        assert_eq!(
900            content_of("src/generated/types.ts"),
901            (ContentKind::Generated, None)
902        );
903        assert_eq!(content_of("src/api_pb.ts"), (ContentKind::Generated, None));
904        // A bare `.map` is too generic to mean a source map.
905        assert_eq!(content_of("data/world.map").0, ContentKind::Text);
906        // Folders above the project root never decide a generated shape.
907        let kind = classify(
908            Path::new("/home/gen/project"),
909            Path::new("/home/gen/project/src/main.rs"),
910            Some(b"fn main() {}\n".as_slice()),
911        );
912        assert_eq!(kind.content, ContentKind::Text);
913    }
914
915    #[test]
916    fn file_kind_path_outside_the_root_is_decided_by_its_file_name() {
917        // A file the root does not contain: its folders (`gen/`) never
918        // decide, but a generated file name still does.
919        let root = Path::new("/project");
920        let text = b"fn main() {}\n".as_slice();
921        let kind = classify(root, Path::new("/elsewhere/gen/main.rs"), Some(text));
922        assert_eq!(kind.content, ContentKind::Text);
923        let kind = classify(root, Path::new("/elsewhere/gen/api_pb.ts"), Some(text));
924        assert_eq!(kind.content, ContentKind::Generated);
925    }
926
927    #[cfg(windows)]
928    #[test]
929    fn file_kind_windows_folders_above_the_root_never_decide() {
930        let text = b"fn main() {}\n".as_slice();
931        let content =
932            |root: &str, path: &str| classify(Path::new(root), Path::new(path), Some(text)).content;
933        // Drive-letter root and file.
934        let root = r"C:\Users\gen\project";
935        assert_eq!(
936            content(root, r"C:\Users\gen\project\src\main.rs"),
937            ContentKind::Text
938        );
939        assert_eq!(
940            content(root, r"C:\Users\gen\project\src\generated\types.ts"),
941            ContentKind::Generated
942        );
943        // A `\\?\`-prefixed root (the form Windows canonicalization returns)
944        // with a plainly spelled file.
945        let verbatim = r"\\?\C:\Users\gen\project";
946        assert_eq!(
947            content(verbatim, r"C:\Users\gen\project\src\main.rs"),
948            ContentKind::Text
949        );
950        assert_eq!(
951            content(verbatim, r"C:\Users\gen\project\gen\schema.ts"),
952            ContentKind::Generated
953        );
954        // A root with no drive letter, which `Path::is_absolute` calls
955        // relative on Windows.
956        assert_eq!(
957            content(r"\home\gen\project", r"\home\gen\project\src\main.rs"),
958            ContentKind::Text
959        );
960        // A file whose spelling cannot be matched to the root (no drive
961        // letter, or a Windows short-name folder alias such as `PROJEC~1`): only
962        // its file name decides.
963        assert_eq!(
964            content(root, r"\Users\gen\project\src\main.rs"),
965            ContentKind::Text
966        );
967        assert_eq!(
968            content(root, r"C:\Users\gen\PROJEC~1\src\main.rs"),
969            ContentKind::Text
970        );
971        assert_eq!(
972            content(root, r"C:\Users\gen\PROJEC~1\src\api_pb.ts"),
973            ContentKind::Generated
974        );
975    }
976
977    #[test]
978    fn file_kind_content_signals_decide_only_when_the_name_does_not() {
979        let root = Path::new("/project");
980        let header = b"// Code generated by protoc-gen-es. DO NOT EDIT.\nexport const x = 1;\n";
981        let kind = classify(root, &root.join("src/api.ts"), Some(header.as_slice()));
982        assert_eq!((kind.content, kind.marker), (ContentKind::Generated, None));
983
984        let bundle = "x".repeat(4 * 1024);
985        let kind = classify(root, &root.join("dist/bundle.js"), Some(bundle.as_bytes()));
986        assert_eq!((kind.content, kind.marker), (ContentKind::Minified, None));
987
988        // Docs are never read for headers: their text is what a reader wants.
989        let kind = classify(root, &root.join("docs/api.md"), Some(header.as_slice()));
990        assert_eq!(kind.content, ContentKind::Text);
991
992        let source: String = (0..200).map(|i| format!("const v{i} = {i};\n")).collect();
993        let kind = classify(root, &root.join("src/app.js"), Some(source.as_bytes()));
994        assert_eq!(kind.content, ContentKind::Text);
995    }
996
997    #[test]
998    fn file_kind_json_data_needs_a_long_line_and_exempts_schemas_and_manifests() {
999        let root = Path::new("/project");
1000        let long_line = format!("{{\"blob\": \"{}\"}}\n", "a".repeat(300));
1001        let classify_json = |name: &str, body: &str| {
1002            let kind = classify(root, &root.join(name), Some(body.as_bytes()));
1003            (kind.content, kind.marker)
1004        };
1005        assert_eq!(
1006            classify_json("research/mutations.json", &long_line),
1007            (ContentKind::DataJson, Some(".json"))
1008        );
1009        assert_eq!(
1010            classify_json("maps/world.geojson", &long_line),
1011            (ContentKind::DataJson, Some(".geojson"))
1012        );
1013        assert_eq!(
1014            classify_json("assets/aft.schema.json", &long_line).0,
1015            ContentKind::Text
1016        );
1017        let with_schema_key = format!("{{\"$schema\": \"x\",\n{long_line}");
1018        assert_eq!(
1019            classify_json("config/tool.json", &with_schema_key).0,
1020            ContentKind::Text
1021        );
1022        assert_eq!(
1023            classify_json("package.json", &long_line).0,
1024            ContentKind::Text
1025        );
1026        assert_eq!(
1027            classify_json("tsconfig.build.json", &long_line).0,
1028            ContentKind::Text
1029        );
1030        assert_eq!(
1031            classify_json(".eslintrc.json", &long_line).0,
1032            ContentKind::Text
1033        );
1034        // Size alone does not make data: 47 KB of short lines stays text.
1035        let short_lines: String = (0..700)
1036            .map(|i| format!("  \"entry{i}\": \"value of about one hundred bytes ............................\",\n"))
1037            .collect();
1038        assert!(short_lines.len() > 40 * 1024);
1039        assert_eq!(
1040            classify_json("src/source-output.json", &short_lines).0,
1041            ContentKind::Text
1042        );
1043    }
1044
1045    #[test]
1046    fn file_kind_json_long_line_test_reads_at_most_64_kib() {
1047        let dir = tempfile::tempdir().unwrap();
1048        let root = dir.path();
1049        let short_lines = "  \"k\": \"v\",\n".repeat(JSON_HEAD_BYTES / 12 + 100);
1050        assert!(short_lines.len() > JSON_HEAD_BYTES);
1051        let late = root.join("late.json");
1052        std::fs::write(
1053            &late,
1054            format!("{short_lines}\"blob\": \"{}\"\n", "a".repeat(400)),
1055        )
1056        .unwrap();
1057        assert_eq!(kind_of(root, "late.json").content, ContentKind::Text);
1058        assert!(read_probe::bytes_read(&late) <= JSON_HEAD_BYTES);
1059
1060        let early = root.join("early.json");
1061        std::fs::write(
1062            &early,
1063            format!("\"blob\": \"{}\"\n{short_lines}", "a".repeat(400)),
1064        )
1065        .unwrap();
1066        assert_eq!(kind_of(root, "early.json").content, ContentKind::DataJson);
1067        assert!(read_probe::bytes_read(&early) <= JSON_HEAD_BYTES);
1068    }
1069
1070    /// The index store's minified check agrees with the file kinds: by
1071    /// name, or a JavaScript or CSS head with almost no line breaks, and
1072    /// never a source file of another language however dense.
1073    #[test]
1074    fn is_minified_matches_the_minified_file_kind() {
1075        let dense = format!("var a=1;{}", "b();".repeat(2048));
1076        let lines = "export function a() {}\n".repeat(400);
1077        assert!(is_minified("web/app.min.js", lines.as_bytes()));
1078        assert!(is_minified("web/STYLE.MIN.CSS", b""));
1079        assert!(is_minified("web/bundle.js", dense.as_bytes()));
1080        assert!(!is_minified("web/app.js", lines.as_bytes()));
1081        assert!(!is_minified("src/lib.rs", dense.as_bytes()));
1082        assert!(!is_minified("web.min.js/app.ts", lines.as_bytes()));
1083        for (path, bytes) in [
1084            ("bundle.js", dense.as_bytes()),
1085            ("app.js", lines.as_bytes()),
1086        ] {
1087            let kind = classify(Path::new("/p"), &Path::new("/p").join(path), Some(bytes));
1088            assert_eq!(
1089                kind.content == ContentKind::Minified,
1090                is_minified(path, bytes),
1091                "{path}"
1092            );
1093        }
1094    }
1095
1096    #[test]
1097    fn file_kind_single_line_bundle_is_read_at_most_8_kib() {
1098        let dir = tempfile::tempdir().unwrap();
1099        let root = dir.path();
1100        let bundle = root.join("bundle.js");
1101        std::fs::write(&bundle, "x".repeat(10 * 1024 * 1024)).unwrap();
1102
1103        // inspect's generated-header check used to read the whole first line.
1104        assert!(!generated::is_generated_file(root, &bundle));
1105        let after_inspect = read_probe::bytes_read(&bundle);
1106        assert!(
1107            after_inspect <= HEAD_BYTES,
1108            "inspect read {after_inspect} bytes of a single-line bundle"
1109        );
1110
1111        assert_eq!(kind_of(root, "bundle.js").content, ContentKind::Minified);
1112        let after_classify = read_probe::bytes_read(&bundle) - after_inspect;
1113        assert!(
1114            after_classify <= HEAD_BYTES,
1115            "classify read {after_classify} bytes of a single-line bundle"
1116        );
1117    }
1118
1119    #[test]
1120    fn file_kind_held_bytes_and_cache_avoid_reads() {
1121        let dir = tempfile::tempdir().unwrap();
1122        let root = dir.path();
1123        let file = root.join("app.ts");
1124        std::fs::write(&file, "export const x = 1;\n").unwrap();
1125        classify(root, &file, Some(b"export const x = 1;\n".as_slice()));
1126        assert_eq!(read_probe::bytes_read(&file), 0);
1127
1128        let mut cache = FileKindCache::new();
1129        cache.classify(root, &file, None);
1130        let first = read_probe::bytes_read(&file);
1131        assert!(first > 0);
1132        cache.classify(root, &file, None);
1133        assert_eq!(read_probe::bytes_read(&file), first);
1134    }
1135
1136    #[test]
1137    fn file_kind_test_role_is_independent_of_content() {
1138        let kind = classify(
1139            Path::new("/project"),
1140            Path::new("/project/tests/fixtures/run/stderr"),
1141            None,
1142        );
1143        assert_eq!(kind.content, ContentKind::Capture);
1144        assert_eq!(kind.test, TestRole::Test);
1145        let kind = classify(
1146            Path::new("/project"),
1147            Path::new("/project/src/__fixtures__/run/stderr"),
1148            None,
1149        );
1150        assert_eq!(
1151            (kind.content, kind.test),
1152            (ContentKind::Capture, TestRole::Support)
1153        );
1154        let kind = classify(
1155            Path::new("/project"),
1156            Path::new("/project/src/app.test.ts"),
1157            Some(b"".as_slice()),
1158        );
1159        assert_eq!(
1160            (kind.content, kind.test),
1161            (ContentKind::Text, TestRole::Test)
1162        );
1163    }
1164}
1165
1166#[cfg(test)]
1167mod test_support_tests {
1168    use super::is_test_file;
1169    use super::is_test_support_file;
1170
1171    #[test]
1172    fn is_test_file_matches_real_test_files() {
1173        // JS/TS family: *.test.* / *.spec.*
1174        for p in [
1175            "src/foo.test.ts",
1176            "src/foo.test.tsx",
1177            "src/bar.spec.js",
1178            "packages/x/component.test.jsx",
1179            "app/foo.test.mjs",
1180            "src/comp.spec.vue",
1181        ] {
1182            assert!(is_test_file(p), "{p} should be a test file");
1183        }
1184        // __tests__ directory and tests roots.
1185        assert!(is_test_file("packages/x/__tests__/reading.ts"));
1186        assert!(is_test_file("crates/aft/tests/integration/main.rs"));
1187        // Per-language filename suffixes.
1188        assert!(is_test_file("crates/aft/src/foo_test.rs"));
1189        assert!(is_test_file("pkg/handler_test.go"));
1190        assert!(is_test_file("app/test_models.py"));
1191        assert!(is_test_file("app/models_test.py"));
1192        assert!(is_test_file("spec/user_spec.rb"));
1193        // CamelCase test classes (case-sensitive).
1194        assert!(is_test_file("src/main/UserServiceTest.java"));
1195        assert!(is_test_file("src/FooTests.cs"));
1196        assert!(is_test_file("Sources/AppTests.swift"));
1197        // Windows separators normalize.
1198        assert!(is_test_file("packages\\x\\__tests__\\a.ts"));
1199    }
1200
1201    #[test]
1202    fn is_test_file_rejects_product_files() {
1203        for p in [
1204            "crates/aft/src/inspect/job.rs",
1205            "packages/x/src/index.ts",
1206            "src/contestant.ts",     // "test" substring, not a test file
1207            "src/greatest.ts",       // ends with "test" stem, not ".test."
1208            "src/latest.java",       // case-sensitive guard: not "Test.java"
1209            "src/my_attestation.py", // not test_*/*_test
1210            "src/test/helper.ts",    // singular `test` dir must not blanket-match
1211        ] {
1212            assert!(!is_test_file(p), "{p} must NOT be a test file");
1213        }
1214    }
1215
1216    #[test]
1217    fn matches_conventional_support_dirs() {
1218        assert!(is_test_support_file("crates/aft/tests/fixtures/sample.ts"));
1219        assert!(is_test_support_file(
1220            "packages/x/__tests__/e2e/fixtures/a.ts"
1221        ));
1222        assert!(is_test_support_file(
1223            "benchmarks/codegraph/corpora/repo/lib.go"
1224        ));
1225        assert!(is_test_support_file("src/__mocks__/fs.ts"));
1226        assert!(is_test_support_file("src/__snapshots__/render.snap"));
1227        assert!(is_test_support_file("internal/testdata/golden.json"));
1228        // Windows-style separators normalize.
1229        assert!(is_test_support_file("crates\\aft\\tests\\fixtures\\x.rs"));
1230    }
1231
1232    #[test]
1233    fn does_not_match_product_or_test_files() {
1234        // A real product file under src must never be excluded.
1235        assert!(!is_test_support_file("crates/aft/src/inspect/job.rs"));
1236        // Test FILES are not support files (they hold real assertions/roots).
1237        assert!(!is_test_support_file(
1238            "packages/x/__tests__/reading.test.ts"
1239        ));
1240        assert!(!is_test_support_file(
1241            "crates/aft/tests/integration/main.rs"
1242        ));
1243        // Substring of a segment must not match (only whole segments).
1244        assert!(!is_test_support_file("src/fixturesHelper.ts"));
1245        assert!(!is_test_support_file("src/my_corpora_loader.rs"));
1246    }
1247}