Skip to main content

fallow_core/discover/
walk.rs

1use std::ffi::OsStr;
2use std::path::{Path, PathBuf};
3use std::sync::{Arc, Mutex, OnceLock};
4
5use fallow_config::{
6    DEFAULT_IGNORE_PATTERNS, IgnorePatternSet, PermutationSite, ResolvedConfig,
7    WorkspaceDiagnostic, WorkspaceDiagnosticKind, sort_permuted,
8};
9use fallow_types::discover::{DiscoveredFile, FileId};
10use fallow_types::path_util::display_relative;
11use fallow_types::workspace::glob_first_literal_segment;
12use ignore::WalkBuilder;
13use rustc_hash::{FxHashMap, FxHashSet};
14
15use super::{ALLOWED_HIDDEN_DIRS, SCRIPT_SCOPE_DENYLIST};
16
17/// Process-wide dedupe of the size-skip / largest-files stderr notes, keyed by a
18/// content-derived string, so combined-mode (`fallow` runs check + dupes +
19/// health, each of which can trigger a source walk) emits each note at most once
20/// per distinct content. Mirrors the workspace-diagnostics `should_emit`
21/// pattern (issue #1086).
22pub(super) fn should_emit_note_once(key: String) -> bool {
23    static EMITTED: OnceLock<Mutex<FxHashSet<String>>> = OnceLock::new();
24    EMITTED
25        .get_or_init(|| Mutex::new(FxHashSet::default()))
26        .lock()
27        .map_or(true, |mut set| set.insert(key))
28}
29
30/// A discovered file path paired with its on-disk size in bytes, as collected
31/// by the parallel walker before [`DiscoveredFile`] ids are assigned.
32type SizedFile = (PathBuf, u64);
33
34/// Dot-prefixed directories the walk dropped, collected inside the parallel
35/// walker's `filter_entry` predicate.
36///
37/// `Arc<Mutex<..>>` and not a borrow: `WalkBuilder::filter_entry` requires
38/// `Fn(&DirEntry) -> bool + Send + Sync + 'static`, so the closure can neither
39/// borrow a local nor mutate captured state directly, and the predicate runs
40/// on every walker thread.
41type SkippedDotdirSink = Arc<Mutex<Vec<PathBuf>>>;
42
43/// Candidate source files ONE built-in ignore pattern removed from a walk,
44/// with the directories they sat in (issue #2638).
45///
46/// The scope map is deliberately uncapped, and its size is not the risk it
47/// looks like. For a directory-shaped pattern every file under one matched
48/// directory collapses to a single key, the one built-in that could span a
49/// whole dependency tree is never tallied at all (see
50/// [`UNREPORTED_DEFAULT_IGNORES`]), and only the file-shaped patterns
51/// (`**/*.min.js` and friends) key on a file's parent, on files that are rare
52/// by construction. The map is therefore strictly smaller than the file list
53/// the same walk already holds. A ceiling would buy nothing and would cost
54/// both determinism and honesty: the parallel walk fills per-thread maps in
55/// nondeterministic order, so "the first N directories" is not a stable set,
56/// the anchor picked from a truncated set would differ between runs of the
57/// same command, and `directory_count` would become a floor rather than a
58/// count.
59#[derive(Default)]
60struct ExcludedByPattern {
61    /// Candidate source files this pattern excluded. Exact.
62    file_count: u32,
63    /// Excluded files per scope directory, project-root-relative.
64    scopes: FxHashMap<PathBuf, u32>,
65}
66
67impl ExcludedByPattern {
68    fn record(&mut self, scope: PathBuf) {
69        self.file_count = self.file_count.saturating_add(1);
70        *self.scopes.entry(scope).or_insert(0) += 1;
71    }
72
73    fn merge(&mut self, other: Self) {
74        self.file_count = self.file_count.saturating_add(other.file_count);
75        for (scope, count) in other.scopes {
76            *self.scopes.entry(scope).or_insert(0) += count;
77        }
78    }
79
80    /// Distinct directories this pattern MATCHED at, which for a
81    /// directory-shaped pattern is not the number of directories that held
82    /// the files: everything under one matched `dist/` collapses to that one
83    /// scope. Exact, and the number the message needs to say whether
84    /// [`Self::anchor`] names the whole exclusion or one matched location of
85    /// several.
86    fn directory_count(&self) -> u32 {
87        u32::try_from(self.scopes.len()).unwrap_or(u32::MAX)
88    }
89
90    /// The matched directory this pattern excluded the most files from, ties
91    /// broken by the lexicographically first path so two runs on one tree
92    /// report the same anchor.
93    fn anchor(&self) -> PathBuf {
94        self.scopes
95            .iter()
96            .max_by(|(left_path, left_count), (right_path, right_count)| {
97                left_count
98                    .cmp(right_count)
99                    .then_with(|| right_path.cmp(left_path))
100            })
101            .map(|(path, _)| path.clone())
102            .unwrap_or_default()
103    }
104}
105
106/// Per-built-in-pattern exclusion tallies, keyed by index into
107/// [`DEFAULT_IGNORE_PATTERNS`].
108type ExclusionTally = FxHashMap<usize, ExcludedByPattern>;
109
110/// Built-in ignore patterns whose exclusions are never reported (issue #2638).
111///
112/// The diagnostic exists to say "first-party source of yours was dropped".
113/// `**/node_modules/**` drops installed dependencies, which are nobody's
114/// first-party source: on a project whose `node_modules` is not gitignored it
115/// would report a five-figure count whose only honest remedy is "that is your
116/// dependency tree", and it would be the one built-in able to dominate the
117/// walk's memory with per-package scope directories. `**/.git/**` cannot fire
118/// at all, because hidden directories are not traversed; it is listed so the
119/// two exclusions read as one policy rather than as an accident.
120const UNREPORTED_DEFAULT_IGNORES: &[&str] = &["**/node_modules/**", "**/.git/**"];
121
122/// The directory a built-in pattern excluded a file "at": the LONGEST prefix
123/// of the file's project-relative parent directory ending in the pattern's
124/// literal segment, or the parent itself when the pattern has no literal
125/// segment.
126///
127/// `**/build/**` with `projects/app/build/static/js/main.js` gives
128/// `projects/app/build`, which is the directory a reader can act on and the
129/// one `fallow --root` takes. The deepest match is what makes that remedy
130/// true: the glob is tested against the path relative to the run root, so on
131/// `build/tools/build/a.ts` an anchor at the outer `build` leaves the inner
132/// one in the relative path and the built-in matches again. `**/*.min.js` has
133/// no literal segment, so `vendor/a.min.js` gives `vendor`. A root-level match
134/// returns the empty path, which the diagnostic renders as the root itself.
135fn exclusion_scope(relative: &Path, pattern: &str) -> PathBuf {
136    let parent = relative.parent().unwrap_or_else(|| Path::new(""));
137    let Some(literal) = glob_first_literal_segment(pattern) else {
138        return parent.to_path_buf();
139    };
140    let mut prefix = PathBuf::new();
141    let mut deepest = None;
142    for component in parent.components() {
143        prefix.push(component);
144        if component.as_os_str() == OsStr::new(literal) {
145            deepest = Some(prefix.clone());
146        }
147    }
148    deepest.unwrap_or_else(|| parent.to_path_buf())
149}
150
151/// Number of example file paths named in the aggregated skipped-large-file and
152/// largest-files stderr notes before the tail collapses to "and N more". Keeps
153/// the notes to one bounded line on a monorepo that skips many files.
154const NOTE_EXAMPLE_CAP: usize = 5;
155
156/// Directory levels below a skipped dotdir the bounded scan descends. The
157/// dotdir itself is level 0. Two levels reach the conventional
158/// `<dotdir>/<group>/<file>` layout (`.claude/hooks/probe.mjs`) with one level
159/// of headroom, and stop well above a vendored toolchain tree.
160const DOTDIR_SCAN_MAX_DEPTH: usize = 2;
161
162/// Directory entries the bounded scan reads across all levels of ONE skipped
163/// dotdir. The ceiling this buys is a SYSCALL count, not a wall-clock figure:
164/// a directory-heavy dotdir spends budget on subdirectories that each cost an
165/// opendir of their own, so 256 entries can still mean 257 directory reads and
166/// several milliseconds. State the bound in syscalls, never in milliseconds.
167const DOTDIR_SCAN_MAX_ENTRIES: usize = 256;
168
169/// Directory entries the bounded scan reads across ALL skipped dotdirs in one
170/// walk. [`DOTDIR_SCAN_MAX_ENTRIES`] bounds a single directory and nothing
171/// bounded the sum, so the added cost was linear in the candidate count: a
172/// synthetic tree of 1000 directory-heavy dotdirs turned a 191 ms run into
173/// 6.6 s. Candidates are scanned in sorted order and share this budget, so
174/// exhausting it drops the advisory for the remaining candidates
175/// deterministically instead of paying an unbounded cost. With this ceiling
176/// and [`DOTDIR_SCAN_MAX_CANDIDATES`] the same synthetic trees measure about
177/// 30 ms of added work whether they hold 300 or 1000 candidates, and a real
178/// repository stays inside run-to-run noise.
179const DOTDIR_SCAN_TOTAL_ENTRIES: usize = 1024;
180
181/// Skipped dotdirs the bounded scan OPENS in one walk. The entry budget does
182/// not bound the per-candidate setup cost, since each scan builds its own
183/// gitignore matcher chain (about 0.2 ms) before it reads a single entry, so
184/// the candidate count needs a ceiling of its own. Counted after the name
185/// checks, so a monorepo full of `.turbo` and `.next` directories cannot spend
186/// the ceiling on directories that were never going to be scanned.
187const DOTDIR_SCAN_MAX_CANDIDATES: usize = 64;
188
189/// File extensions that put a file in the module graph the advisory talks
190/// about. Narrower than [`SOURCE_EXTENSIONS`] on purpose: the message states
191/// that the directory's imports and exports are not analyzed, and that is only
192/// true of code. A dotdir holding nothing but a generated Lighthouse
193/// `report.html`, a Sanity runtime page, a `schema.graphql`, or a stylesheet
194/// has no imports or exports to lose, so it does not earn the advisory.
195const DOTDIR_MODULE_EXTENSIONS: &[&str] = &[
196    "ts", "tsx", "mts", "cts", "gts", "js", "jsx", "mjs", "cjs", "gjs", "vue", "svelte", "astro",
197    "mdx",
198];
199
200/// Discovered-file-count threshold above which the pre-parse largest-files note
201/// fires, so an out-of-memory hang at the parse stage has a visible suspect
202/// list (issue #1086).
203const LARGE_SET_THRESHOLD: usize = 20_000;
204
205/// Single-file byte threshold above which the pre-parse largest-files note
206/// fires even on a small project. Set just under the default 5 MB skip so the
207/// note fires for kept files that are approaching the skip limit (the genuine
208/// out-of-memory suspects), not for ordinary large-but-benign files.
209const LARGE_FILE_NOTE_BYTES: u64 = 4 * 1024 * 1024;
210
211/// Minimum size for a file to appear in the largest-files note. Filters out the
212/// `0.0 MB` entries that would otherwise pad the list once it fires, keeping the
213/// named files to plausible memory contributors.
214const NOTE_FILE_FLOOR_BYTES: u64 = 256 * 1024;
215
216/// Minimum size for content-shape based minified-bundle skipping. Smaller
217/// one-line files can be hand-written utilities, while multi-MB one-line JS is
218/// generated output in practice.
219const MINIFIED_FILE_SKIP_BYTES: u64 = 1024 * 1024;
220
221/// Number of bytes inspected when deciding whether a large JS file is minified.
222const MINIFIED_SAMPLE_BYTES: usize = 256 * 1024;
223
224/// A single line this long in a multi-MB JS file is treated as generated
225/// minified output. This avoids parsing assets that can expand to huge ASTs.
226const MINIFIED_LONG_LINE_BYTES: usize = 128 * 1024;
227
228/// Whether a path is a TypeScript declaration file (`.d.ts`/`.d.mts`/`.d.cts`).
229/// Declaration files are exempt from the per-file size skip because they are
230/// reachability roots for global types: skipping a large `auto-imports.d.ts`
231/// would false-flag the files whose types it provides.
232fn is_declaration_file(path: &Path) -> bool {
233    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
234    name.ends_with(".d.ts") || name.ends_with(".d.mts") || name.ends_with(".d.cts")
235}
236
237fn is_plain_js_file(path: &Path) -> bool {
238    matches!(
239        path.extension().and_then(|ext| ext.to_str()),
240        Some("js" | "mjs" | "cjs")
241    )
242}
243
244fn has_minified_line_shape(path: &Path) -> bool {
245    use std::io::Read;
246
247    let Ok(mut file) = std::fs::File::open(path) else {
248        return false;
249    };
250    let mut sample = vec![0; MINIFIED_SAMPLE_BYTES];
251    let Ok(len) = file.read(&mut sample) else {
252        return false;
253    };
254    sample.truncate(len);
255    if sample.is_empty() {
256        return false;
257    }
258
259    let mut current_line = 0usize;
260    for byte in sample {
261        if byte == b'\n' || byte == b'\r' {
262            current_line = 0;
263            continue;
264        }
265        current_line += 1;
266        if current_line >= MINIFIED_LONG_LINE_BYTES {
267            return true;
268        }
269    }
270    false
271}
272
273fn is_probably_minified_generated_js(path: &Path, size_bytes: u64) -> bool {
274    size_bytes >= MINIFIED_FILE_SKIP_BYTES
275        && is_plain_js_file(path)
276        && !is_declaration_file(path)
277        && has_minified_line_shape(path)
278}
279
280/// Render a byte count as a megabyte figure with one decimal place.
281fn format_size_mb(bytes: u64) -> String {
282    #[expect(
283        clippy::cast_precision_loss,
284        reason = "display-only size figure; precision loss past 2^53 bytes is irrelevant"
285    )]
286    let mb = bytes as f64 / (1024.0 * 1024.0);
287    format!("{mb:.1} MB")
288}
289
290/// Join up to [`NOTE_EXAMPLE_CAP`] `path (size)` examples (already ordered) into
291/// one comma-separated string, collapsing the tail to "and N more".
292fn summarize_examples(root: &Path, examples: &[SizedFile]) -> String {
293    let shown: Vec<String> = examples
294        .iter()
295        .take(NOTE_EXAMPLE_CAP)
296        .map(|(path, size)| {
297            let display = display_relative(root, path);
298            format!("{display} ({})", format_size_mb(*size))
299        })
300        .collect();
301    let remaining = examples.len().saturating_sub(NOTE_EXAMPLE_CAP);
302    if remaining > 0 {
303        format!("{}, and {remaining} more", shown.join(", "))
304    } else {
305        shown.join(", ")
306    }
307}
308
309/// Split discovered `(path, size)` pairs into the kept set and the set skipped
310/// for exceeding `max_file_size_bytes`. Declaration files are never skipped.
311fn partition_by_size(
312    raw: Vec<SizedFile>,
313    max_file_size_bytes: Option<u64>,
314) -> (Vec<SizedFile>, Vec<SizedFile>) {
315    let Some(limit) = max_file_size_bytes else {
316        return (raw, Vec::new());
317    };
318    raw.into_iter()
319        .partition(|(path, size)| *size <= limit || is_declaration_file(path))
320}
321
322/// Split discovered `(path, size)` pairs into files kept for parsing and files
323/// skipped because they look like generated minified JavaScript.
324fn partition_minified_generated_js(
325    raw: Vec<SizedFile>,
326    max_file_size_bytes: Option<u64>,
327) -> (Vec<SizedFile>, Vec<SizedFile>) {
328    if max_file_size_bytes.is_none() {
329        return (raw, Vec::new());
330    }
331    raw.into_iter()
332        .partition(|(path, size)| !is_probably_minified_generated_js(path, *size))
333}
334
335/// Build the typed diagnostics for the over-limit files this walk dropped and
336/// emit one aggregated `tracing::warn!` so a human running `fallow` sees what
337/// was dropped. Mirrors the JSON-plus-gated-warn pattern used for undeclared
338/// workspaces. The caller writes the returned list to the registry.
339/// Report an uninstalled dependency tree as part of the walk's own
340/// source-discovery set.
341///
342/// It belongs here rather than beside the two pipelines that used to warn
343/// about it: the walk owns this root's source-discovery diagnostics, and any
344/// second writer would be replaced by whichever walk finished last.
345fn report_missing_node_modules(config: &ResolvedConfig) -> Vec<WorkspaceDiagnostic> {
346    let Some(diagnostic) = fallow_config::missing_node_modules_diagnostic(&config.root) else {
347        return Vec::new();
348    };
349    if !config.quiet
350        && should_emit_note_once(format!("node-modules-missing::{}", config.root.display()))
351    {
352        tracing::warn!("fallow: {}", diagnostic.message);
353    }
354    vec![diagnostic]
355}
356
357fn report_skipped_large_files(
358    config: &ResolvedConfig,
359    skipped: &[SizedFile],
360) -> Vec<WorkspaceDiagnostic> {
361    if skipped.is_empty() {
362        return Vec::new();
363    }
364    let diagnostics: Vec<WorkspaceDiagnostic> = skipped
365        .iter()
366        .map(|(path, size_bytes)| {
367            WorkspaceDiagnostic::new(
368                &config.root,
369                path.clone(),
370                WorkspaceDiagnosticKind::SkippedLargeFile {
371                    size_bytes: *size_bytes,
372                },
373            )
374        })
375        .collect();
376
377    let mut sorted: Vec<SizedFile> = skipped.to_vec();
378    sorted.sort_unstable_by_key(|f| std::cmp::Reverse(f.1));
379    let count = skipped.len();
380    if !config.quiet
381        && should_emit_note_once(format!(
382            "skip::{}::{count}::{}",
383            config.root.display(),
384            sorted.first().map_or(0, |f| f.1)
385        ))
386    {
387        let examples = summarize_examples(&config.root, &sorted);
388        let noun = if count == 1 { "file" } else { "files" };
389        tracing::warn!(
390            "fallow: skipped {count} {noun} over the max file size limit ({examples}). \
391             Raise the limit with --max-file-size <MB> (or FALLOW_MAX_FILE_SIZE), or add them to ignorePatterns."
392        );
393    }
394    diagnostics
395}
396
397/// Build the typed diagnostics for generated minified JS files skipped before
398/// parsing. The caller writes the returned list to the registry.
399fn report_skipped_minified_files(
400    config: &ResolvedConfig,
401    skipped: &[SizedFile],
402) -> Vec<WorkspaceDiagnostic> {
403    if skipped.is_empty() {
404        return Vec::new();
405    }
406    let diagnostics: Vec<WorkspaceDiagnostic> = skipped
407        .iter()
408        .map(|(path, size_bytes)| {
409            WorkspaceDiagnostic::new(
410                &config.root,
411                path.clone(),
412                WorkspaceDiagnosticKind::SkippedMinifiedFile {
413                    size_bytes: *size_bytes,
414                },
415            )
416        })
417        .collect();
418
419    let mut sorted: Vec<SizedFile> = skipped.to_vec();
420    sorted.sort_unstable_by_key(|f| std::cmp::Reverse(f.1));
421    let count = skipped.len();
422    if !config.quiet
423        && should_emit_note_once(format!(
424            "minified::{}::{count}::{}",
425            config.root.display(),
426            sorted.first().map_or(0, |f| f.1)
427        ))
428    {
429        let examples = summarize_examples(&config.root, &sorted);
430        let noun = if count == 1 { "file" } else { "files" };
431        let pronoun = if count == 1 { "it" } else { "them" };
432        tracing::warn!(
433            "fallow: skipped {count} minified generated JS {noun} ({examples}). \
434             Add {pronoun} to ignorePatterns, rename {pronoun} with a .min.js suffix, or use --max-file-size 0 to analyze {pronoun}."
435        );
436    }
437    diagnostics
438}
439
440/// Join up to [`NOTE_EXAMPLE_CAP`] root-relative paths (already ordered) into
441/// one comma-separated string, collapsing the tail to "and N more". The
442/// size-bearing sibling is [`summarize_examples`].
443fn summarize_paths(root: &Path, examples: &[&PathBuf]) -> String {
444    let shown: Vec<String> = examples
445        .iter()
446        .take(NOTE_EXAMPLE_CAP)
447        .map(|path| display_relative(root, path))
448        .collect();
449    let remaining = examples.len().saturating_sub(NOTE_EXAMPLE_CAP);
450    if remaining > 0 {
451        format!("{}, and {remaining} more", shown.join(", "))
452    } else {
453        shown.join(", ")
454    }
455}
456
457/// Like [`summarize_paths`], but for a list already known to be incomplete: the
458/// tail reads "and more" rather than naming a count the run cannot vouch for.
459fn summarize_paths_open_ended(root: &Path, examples: &[&PathBuf]) -> String {
460    let shown: Vec<String> = examples
461        .iter()
462        .take(NOTE_EXAMPLE_CAP)
463        .map(|path| display_relative(root, path))
464        .collect();
465    if examples.len() > NOTE_EXAMPLE_CAP {
466        format!("{}, and more", shown.join(", "))
467    } else {
468        shown.join(", ")
469    }
470}
471
472/// Whether a candidate file inside a skipped dotdir is one this run had
473/// already excluded from analysis, matching what [`FileVisitor`] applies to
474/// every discovered file: the compiled `ignorePatterns` set (user entries plus
475/// the built-in defaults) against the ROOT-RELATIVE path, plus the production
476/// excludes when the run is a `--production` run.
477///
478/// The root-relative path is what matters. Matching the directory path instead
479/// would miss the pattern a user actually writes, because `.claude/**` does not
480/// match `.claude`.
481///
482/// Production excludes ARE applied, even though the skip the diagnostic reports
483/// is a traversal decision that `--production` does not change. A `--production`
484/// run that named a dotdir holding only `thing.test.ts` would print a remedy
485/// (`fallow --root .qa --production`) that returns nothing, so the advisory has
486/// to agree with the file set the run would actually analyze. Combined mode's
487/// two walks can therefore disagree, which the documented union semantics of
488/// the combined root already cover.
489fn is_excluded_from_analysis(
490    config: &ResolvedConfig,
491    production_excludes: Option<&globset::GlobSet>,
492    path: &Path,
493) -> bool {
494    let relative = path.strip_prefix(&config.root).unwrap_or(path);
495    config.ignore_patterns.is_match(relative)
496        || production_excludes.is_some_and(|excludes| excludes.is_match(relative))
497}
498
499/// True when `path` carries an extension that puts it in the module graph the
500/// advisory describes. See [`DOTDIR_MODULE_EXTENSIONS`] for why this is
501/// narrower than [`has_source_extension`].
502fn has_module_extension(path: &Path) -> bool {
503    path.extension()
504        .and_then(OsStr::to_str)
505        .is_some_and(|ext| DOTDIR_MODULE_EXTENSIONS.contains(&ext))
506}
507
508/// Depth- and entry-capped search for one reportable source file, stopping at
509/// the first hit. Never a recursive walk of an unbounded tree: the ceiling is
510/// `1 + DOTDIR_SCAN_MAX_ENTRIES` directory reads for one dotdir, and
511/// [`DOTDIR_SCAN_TOTAL_ENTRIES`] across the whole walk.
512///
513/// Runs on `fallow_config::source_walk_builder`, the git settings of the
514/// source walk, rather than a bare `read_dir`, because "the project has not excluded it" has
515/// to mean what git means. Only the DIRECTORY form of a gitignore rule
516/// (`.build-tools/`) prunes a dotdir before the walk's own filter sees it: the
517/// `dir/**`, `dir/*`, `**/dir/**` and file-level (`*.ts`) forms all leave the
518/// directory reaching this scan with every file inside it ignored, and a cache
519/// directory that ignores itself through its own nested `.gitignore` does the
520/// same. Reporting those would advertise two remedies that both do nothing,
521/// since a re-rooted `fallow --root <dir>` still reads the parent repository's
522/// gitignore and would find no files either.
523///
524/// Accepted tradeoff: for a dotdir with more than [`DOTDIR_SCAN_MAX_ENTRIES`]
525/// entries whose only source file sits past the budget, the verdict is
526/// readdir-order dependent, so the advisory can flap between runs. The
527/// alternative is unbounded I/O, and the consequence of a flap is a missing
528/// advisory line, never a changed analysis. No test may depend on that
529/// boundary.
530fn scan_for_reportable_source(
531    config: &ResolvedConfig,
532    production_excludes: Option<&globset::GlobSet>,
533    dir: &Path,
534    budget: &mut usize,
535) -> bool {
536    let mut builder = fallow_config::source_walk_builder(dir);
537    builder
538        .follow_links(false)
539        .max_depth(Some(DOTDIR_SCAN_MAX_DEPTH + 1))
540        .threads(1);
541    builder.filter_entry(|entry| {
542        if entry.depth() == 0 || !entry.file_type().is_some_and(|ft| ft.is_dir()) {
543            return true;
544        }
545        entry
546            .file_name()
547            .to_str()
548            .is_none_or(|name| !SCRIPT_SCOPE_DENYLIST.contains(&name) && name != "node_modules")
549    });
550
551    let mut per_dotdir = DOTDIR_SCAN_MAX_ENTRIES;
552    for entry in builder.build() {
553        if per_dotdir == 0 || *budget == 0 {
554            return false;
555        }
556        per_dotdir -= 1;
557        *budget -= 1;
558        let Ok(entry) = entry else {
559            continue;
560        };
561        // Regular files only. A symlink is never followed out of the scan, and
562        // a fifo or a socket named `pipe.ts` is not source either.
563        #[expect(
564            clippy::filetype_is_file,
565            reason = "regular files only is the point: !is_dir() would readmit fifos and sockets"
566        )]
567        let is_regular_file = entry
568            .file_type()
569            .is_some_and(|file_type| file_type.is_file());
570        if !is_regular_file {
571            continue;
572        }
573        if has_module_extension(entry.path())
574            && !is_excluded_from_analysis(config, production_excludes, entry.path())
575        {
576            return true;
577        }
578    }
579    false
580}
581
582/// Path components whose subtrees never earn the skipped-source-dotdir
583/// advisory. A hidden directory under one of these is test scaffolding rather
584/// than first-party source the project meant to analyze.
585const DOTDIR_NOISE_PATH_COMPONENTS: &[&str] = &[
586    "__fixtures__",
587    "__mocks__",
588    "__tests__",
589    "e2e",
590    "fixture",
591    "fixtures",
592    "playground",
593    "playgrounds",
594    "spec",
595    "test",
596    "tests",
597];
598
599/// Whether a dropped dotdir is worth opening at all. Decided from the PATH
600/// alone, so it costs no I/O and runs before the scan budget is touched:
601/// `.git` in a large repository, a `.jj` object store, and `node_modules/.pnpm`
602/// are never opened. `ALLOWED_HIDDEN_DIRS` and every plugin- or
603/// script-contributed scope are already excluded by construction, since a
604/// directory they admit is never dropped and so never reaches this list.
605fn dotdir_is_scan_candidate(config: &ResolvedConfig, dir: &Path) -> bool {
606    let Some(name) = dir.file_name().and_then(OsStr::to_str) else {
607        return false;
608    };
609    if SCRIPT_SCOPE_DENYLIST.contains(&name) {
610        return false;
611    }
612    let relative = dir.strip_prefix(&config.root).unwrap_or(dir);
613    // Pure cost saving, not a further condition: the built-in `**/node_modules/**`
614    // ignore default makes every file under a `node_modules` component ignored,
615    // so the scan could only ever return false.
616    if relative
617        .components()
618        .any(|component| component.as_os_str() == OsStr::new("node_modules"))
619    {
620        return false;
621    }
622    // Precision, and the one place this check is deliberately less complete
623    // than it could be. A hidden directory under a test, fixture, or playground
624    // tree is usually there BECAUSE it is hidden: some of these exist purely to
625    // exercise hidden-directory handling, so an advisory about them is wrong
626    // about the project every time it fires. Measured on a ten-repository
627    // corpus, this component filter removes every false positive one framework
628    // contributed and half of another's while keeping the true positives, which
629    // sit at a repository root rather than under a test tree.
630    !relative.components().any(|component| {
631        DOTDIR_NOISE_PATH_COMPONENTS.contains(&component.as_os_str().to_string_lossy().as_ref())
632    })
633}
634
635/// Build the typed diagnostics for the built-in ignore patterns that removed
636/// candidate source files from this walk (issue #2638).
637///
638/// One entry per pattern, in [`DEFAULT_IGNORE_PATTERNS`] order, so the array
639/// grows by at most the number of built-in patterns on a project of any size
640/// and its order does not depend on the parallel walk. No stderr output: the
641/// kind answers `warns_on_stderr()` with `false`, and the CLI prints a note
642/// only under `--explain-skipped`.
643fn report_default_ignore_exclusions(
644    config: &ResolvedConfig,
645    tally: &ExclusionTally,
646) -> Vec<WorkspaceDiagnostic> {
647    let mut indices: Vec<usize> = tally.keys().copied().collect();
648    indices.sort_unstable();
649    indices
650        .into_iter()
651        .filter_map(|index| {
652            let excluded = tally.get(&index)?;
653            let pattern = DEFAULT_IGNORE_PATTERNS.get(index)?;
654            Some(
655                WorkspaceDiagnostic::new(
656                    &config.root,
657                    config.root.join(excluded.anchor()),
658                    WorkspaceDiagnosticKind::ExcludedByDefaultIgnore {
659                        pattern: (*pattern).to_owned(),
660                        file_count: excluded.file_count,
661                        directory_count: excluded.directory_count(),
662                    },
663                )
664                // A file-shaped built-in that matched a file directly at the
665                // analysis root anchors at the root, and `root.join("")` is the
666                // root itself. The analysis envelopes' post-serialisation strip
667                // only removes a `root + separator` prefix, so without this the
668                // entry would carry the absolute host path into every JSON
669                // surface while its siblings render `.`.
670                .into_root_relative(&config.root),
671            )
672        })
673        .collect()
674}
675
676/// Report that the walk finished with nothing to analyze (issue #2686).
677///
678/// The condition is the file list being empty, not any particular exclusion,
679/// so it also covers a docs-only repository, a workspace member with no
680/// TypeScript and a path filter that matched nothing. The built-in-ignore
681/// tally rides along as `excluded_file_count` so the common cause stays
682/// attributable without making it the trigger.
683///
684/// Recorded by discovery rather than by the CLI's human note, so every envelope
685/// built from a diagnostics snapshot carries it: the MCP tools and the
686/// programmatic routes share this list, and a kind that existed on the CLI path
687/// alone would break that.
688fn report_no_source_files_analyzed(
689    config: &ResolvedConfig,
690    analyzed_file_count: usize,
691    tally: &ExclusionTally,
692) -> Vec<WorkspaceDiagnostic> {
693    if analyzed_file_count > 0 {
694        return Vec::new();
695    }
696    let excluded_file_count = tally.values().map(|excluded| excluded.file_count).sum();
697    vec![
698        WorkspaceDiagnostic::new(
699            &config.root,
700            config.root.clone(),
701            WorkspaceDiagnosticKind::NoSourceFilesAnalyzed {
702                excluded_file_count,
703            },
704        )
705        .into_root_relative(&config.root),
706    ]
707}
708
709/// Build the typed diagnostics for the dot-prefixed directories this walk
710/// dropped that hold source files the project has not excluded, and emit one
711/// aggregated `tracing::warn!` so the otherwise silent skip is visible on
712/// stderr too (issue #461). The caller writes the returned list to the
713/// registry.
714fn report_skipped_source_dotdirs(
715    config: &ResolvedConfig,
716    production_excludes: Option<&globset::GlobSet>,
717    candidates: &[PathBuf],
718) -> Vec<WorkspaceDiagnostic> {
719    if candidates.is_empty() {
720        return Vec::new();
721    }
722    // The caller sorted and deduped, so both caps truncate deterministically:
723    // the same tree reports the same prefix on every run.
724    let mut budget = DOTDIR_SCAN_TOTAL_ENTRIES;
725    let scannable: Vec<&PathBuf> = candidates
726        .iter()
727        .filter(|dir| dotdir_is_scan_candidate(config, dir))
728        .collect();
729    let reportable: Vec<&PathBuf> = scannable
730        .iter()
731        .copied()
732        .take(DOTDIR_SCAN_MAX_CANDIDATES)
733        .filter(|dir| scan_for_reportable_source(config, production_excludes, dir, &mut budget))
734        .collect();
735    // Either ceiling can stop the scan with candidates left unexamined, so the
736    // count is a floor rather than a total whenever one of them binds.
737    let truncated = scannable.len() > DOTDIR_SCAN_MAX_CANDIDATES || budget == 0;
738    if reportable.is_empty() {
739        return Vec::new();
740    }
741
742    let diagnostics: Vec<WorkspaceDiagnostic> = reportable
743        .iter()
744        .map(|dir| {
745            WorkspaceDiagnostic::new(
746                &config.root,
747                (*dir).clone(),
748                WorkspaceDiagnosticKind::SkippedSourceDotdir,
749            )
750        })
751        .collect();
752
753    let count = reportable.len();
754    if !config.quiet
755        && should_emit_note_once(format!(
756            "dotdir::{}::{count}::{}",
757            config.root.display(),
758            reportable
759                .first()
760                .map_or_else(String::new, |dir| display_relative(&config.root, dir))
761        ))
762    {
763        tracing::warn!(
764            "{}",
765            build_skipped_dotdirs_note(&config.root, &reportable, truncated)
766        );
767    }
768    diagnostics
769}
770
771/// Build the skipped-source-dotdir note. Pure so the singular and plural forms,
772/// the truncated prefix, and the single-directory remedy substitution are
773/// unit-testable without a tracing subscriber, mirroring
774/// [`build_largest_files_note`].
775///
776/// With exactly one directory the remedy names it instead of printing a `<dir>`
777/// placeholder: the path is already known and was printed a few words earlier,
778/// so a placeholder would make the one case a user can act on directly the one
779/// case they have to retype.
780fn build_skipped_dotdirs_note(root: &Path, reportable: &[&PathBuf], truncated: bool) -> String {
781    let count = reportable.len();
782    // An exact remainder inside an explicitly inexact total reads as a
783    // contradiction ("at least 64 ... and 59 more"), so a truncated run drops
784    // the tail count.
785    let examples = if truncated {
786        summarize_paths_open_ended(root, reportable)
787    } else {
788        summarize_paths(root, reportable)
789    };
790    let noun = if count == 1 {
791        "directory"
792    } else {
793        "directories"
794    };
795    let verb = if count == 1 { "contains" } else { "contain" };
796    let at_least = if truncated { "at least " } else { "" };
797    let (target, pronoun) = match reportable {
798        [only] => (display_relative(root, only), "it"),
799        _ => ("<dir>".to_owned(), "one"),
800    };
801    format!(
802        "fallow: skipped {at_least}{count} hidden {noun} that {verb} source files ({examples}). \
803         Hidden directories are not traversed, so a file, export or dependency used only \
804         there can be reported as unused: add '!{target}/**' to ignorePatterns to analyze \
805         {pronoun}, or add it to entry, ignoreExports or ignoreDependencies, or add \
806         '{target}/**' to ignorePatterns to silence this. fallow --root {target} analyzes \
807         {pronoun} on its own and does not fix this run."
808    )
809}
810
811/// Build the pre-parse largest-files note, or `None` when the discovered set is
812/// neither unusually large nor contains an unusually large file. Pure so the
813/// pluralization, floor filtering, and count-only fallback are unit-testable
814/// without a tracing subscriber. See issue #1086.
815fn build_largest_files_note(root: &Path, files: &[DiscoveredFile]) -> Option<String> {
816    if files.is_empty() {
817        return None;
818    }
819    let largest = files.iter().map(|f| f.size_bytes).max().unwrap_or(0);
820    if files.len() <= LARGE_SET_THRESHOLD && largest < LARGE_FILE_NOTE_BYTES {
821        return None;
822    }
823    let count = files.len();
824    let noun = if count == 1 { "file" } else { "files" };
825    let mut by_size: Vec<SizedFile> = files
826        .iter()
827        .filter(|f| f.size_bytes >= NOTE_FILE_FLOOR_BYTES)
828        .map(|f| (f.path.clone(), f.size_bytes))
829        .collect();
830    by_size.sort_unstable_by_key(|f| std::cmp::Reverse(f.1));
831    if by_size.is_empty() {
832        // Large file SET with no individually large file: report the count only,
833        // omitting a "largest:" list that would otherwise be all sub-floor noise.
834        return Some(format!(
835            "fallow: discovered {count} {noun}. If analysis stalls or runs out of memory, \
836             exclude large generated files via ignorePatterns or --max-file-size."
837        ));
838    }
839    let examples = summarize_examples(root, &by_size);
840    Some(format!(
841        "fallow: discovered {count} {noun}; largest: {examples}. If analysis stalls or runs out of memory, \
842         exclude large generated files via ignorePatterns or --max-file-size."
843    ))
844}
845
846/// Emit a pre-parse note listing the largest kept files when the discovered set
847/// is unusually large or contains an unusually large file, so an out-of-memory
848/// hang at the parse stage is diagnosable (issue #1086). Visible before the
849/// expensive parse begins, so it survives a subsequent crash.
850fn note_largest_files(config: &ResolvedConfig, files: &[DiscoveredFile]) {
851    if config.quiet {
852        return;
853    }
854    if let Some(message) = build_largest_files_note(&config.root, files)
855        && should_emit_note_once(format!("note::{}::{}", config.root.display(), files.len()))
856    {
857        tracing::warn!("{message}");
858    }
859}
860
861/// How a [`HiddenDirScope`] matches a hidden directory during the walk.
862#[derive(Debug, Clone, Copy, PartialEq, Eq)]
863pub enum HiddenDirMatch {
864    /// Match by directory NAME at any depth beneath the scope root.
865    ///
866    /// Framework plugins declare bundle-boundary conventions like `.client`
867    /// and `.server` that a project may place under any route directory, so
868    /// the name is the whole rule and the depth is not knowable in advance.
869    AnyDepth,
870    /// Match the exact root-relative directory PATH.
871    ///
872    /// A `package.json` script naming `.a/.b/build.mjs` states where the file
873    /// it needs actually lives, so the scope admits `<root>/.a` and
874    /// `<root>/.a/.b` and nothing else. An unrelated `packages/x/.b` stays
875    /// untraversed (issue #461).
876    ExactPath,
877}
878
879/// Package-scoped hidden directories that source discovery should traverse.
880#[derive(Debug, Clone, PartialEq, Eq)]
881pub struct HiddenDirScope {
882    root: PathBuf,
883    dirs: Vec<String>,
884    match_mode: HiddenDirMatch,
885}
886
887impl HiddenDirScope {
888    /// Build a scope rooted at a package directory that admits the given
889    /// hidden directory names at any depth beneath it.
890    ///
891    /// This is the plugin-contributed shape. For a scope inferred from a
892    /// concrete path, use [`HiddenDirScope::new_exact_paths`], which does not
893    /// admit the same name elsewhere in the tree.
894    #[must_use]
895    pub fn new(root: PathBuf, dirs: Vec<String>) -> Self {
896        Self {
897            root,
898            dirs,
899            match_mode: HiddenDirMatch::AnyDepth,
900        }
901    }
902
903    /// Build a scope rooted at a package directory that admits exactly the
904    /// given root-relative directory paths.
905    #[must_use]
906    pub fn new_exact_paths(root: PathBuf, dirs: Vec<String>) -> Self {
907        Self {
908            root,
909            dirs,
910            match_mode: HiddenDirMatch::ExactPath,
911        }
912    }
913
914    /// Rebuild a scope with an explicit match mode.
915    ///
916    /// Used when a scope crosses a crate boundary and must arrive with the
917    /// same semantics it left with.
918    #[must_use]
919    pub fn with_match_mode(root: PathBuf, dirs: Vec<String>, match_mode: HiddenDirMatch) -> Self {
920        Self {
921            root,
922            dirs,
923            match_mode,
924        }
925    }
926
927    #[must_use]
928    pub fn root(&self) -> &Path {
929        &self.root
930    }
931
932    #[must_use]
933    pub fn dirs(&self) -> &[String] {
934        &self.dirs
935    }
936
937    #[must_use]
938    pub fn match_mode(&self) -> HiddenDirMatch {
939        self.match_mode
940    }
941
942    fn allows(&self, path: &Path, name: &OsStr) -> bool {
943        match self.match_mode {
944            HiddenDirMatch::AnyDepth => {
945                path.starts_with(&self.root) && self.dirs.iter().any(|dir| OsStr::new(dir) == name)
946            }
947            HiddenDirMatch::ExactPath => {
948                // `Path` compares component-wise, so a `/`-separated entry
949                // from a script string matches on every platform.
950                let Ok(relative) = path.strip_prefix(&self.root) else {
951                    return false;
952                };
953                self.dirs.iter().any(|dir| Path::new(dir) == relative)
954            }
955        }
956    }
957}
958
959/// Per-thread file collector for the parallel walker.
960///
961/// Source files (by extension) flow to `shared`; when `config_shared` is set,
962/// non-source files admitted by the config-candidate type group flow to it
963/// instead. The two channels are disjoint and the source channel is byte-for-byte
964/// identical to the config-capture-disabled walk.
965struct FileVisitor<'a> {
966    root: &'a Path,
967    canonical_root: Option<&'a Path>,
968    ignore_patterns: &'a IgnorePatternSet,
969    /// Globs at the front of `ignore_patterns` that came from the project's
970    /// own `ignorePatterns`; the built-in defaults follow them.
971    user_ignore_pattern_count: usize,
972    /// Plugin- and script-contributed hidden directory scopes. Read only when
973    /// the project wrote a `!` exception, to tell a hidden directory that the
974    /// exception opened from one the walk always opens.
975    hidden_dir_scopes: &'a [HiddenDirScope],
976    production_excludes: &'a Option<globset::GlobSet>,
977    shared: &'a Mutex<Vec<(std::path::PathBuf, u64)>>,
978    config_shared: Option<&'a Mutex<Vec<std::path::PathBuf>>>,
979    excluded_shared: &'a Mutex<ExclusionTally>,
980    local: Vec<(std::path::PathBuf, u64)>,
981    config_local: Vec<std::path::PathBuf>,
982    excluded_local: ExclusionTally,
983    /// Reused across every excluded candidate so attribution allocates once
984    /// per walker thread rather than once per file.
985    match_buf: Vec<usize>,
986}
987
988impl FileVisitor<'_> {
989    /// Attribute one excluded candidate source file to the built-in pattern
990    /// that removed it (issue #2638), and credit the `ignorePatterns` globs
991    /// that removed any file that no built-in matches (issue #3824).
992    ///
993    /// Runs only on files `is_match` already rejected, so the kept-file path
994    /// still pays a single boolean match.
995    fn record_ignore_exclusion(&mut self, relative: &Path, is_source: bool) {
996        // Cheap pre-filter, not a second rule: `**/node_modules/**` is in
997        // UNREPORTED_DEFAULT_IGNORES, and it is also the one built-in that
998        // fires on an entire dependency tree. Testing a path component beats
999        // running the whole glob union over tens of thousands of files whose
1000        // attribution the report would then discard.
1001        if (!is_source && self.user_ignore_pattern_count == 0)
1002            || relative
1003                .components()
1004                .any(|component| component.as_os_str() == OsStr::new("node_modules"))
1005        {
1006            return;
1007        }
1008        self.match_buf.clear();
1009        self.ignore_patterns
1010            .excluded_matches_into(relative, &mut self.match_buf);
1011        // globset returns ascending indices, so the first match is both the
1012        // cheapest user-pattern test and the lowest-index built-in.
1013        let Some(&first) = self.match_buf.first().filter(|_| is_source) else {
1014            return;
1015        };
1016        if first < self.user_ignore_pattern_count {
1017            // An `ignorePatterns` entry also matched. The project chose this
1018            // exclusion, so reporting it as a surprise would be wrong.
1019            return;
1020        }
1021        let Some(pattern) = DEFAULT_IGNORE_PATTERNS.get(first - self.user_ignore_pattern_count)
1022        else {
1023            return;
1024        };
1025        if UNREPORTED_DEFAULT_IGNORES.contains(pattern) {
1026            return;
1027        }
1028        self.excluded_local
1029            .entry(first - self.user_ignore_pattern_count)
1030            .or_default()
1031            .record(exclusion_scope(relative, pattern));
1032    }
1033}
1034
1035impl ignore::ParallelVisitor for FileVisitor<'_> {
1036    fn visit(&mut self, result: Result<ignore::DirEntry, ignore::Error>) -> ignore::WalkState {
1037        let Ok(entry) = result else {
1038            return ignore::WalkState::Continue;
1039        };
1040        if entry.file_type().is_some_and(|ft| ft.is_dir()) {
1041            return ignore::WalkState::Continue;
1042        }
1043        let relative = entry
1044            .path()
1045            .strip_prefix(self.root)
1046            .unwrap_or_else(|_| entry.path());
1047        if self.ignore_patterns.is_match(relative) {
1048            self.record_ignore_exclusion(relative, has_source_extension(entry.path()));
1049            return ignore::WalkState::Continue;
1050        }
1051        if self
1052            .production_excludes
1053            .as_ref()
1054            .is_some_and(|excludes| excludes.is_match(relative))
1055        {
1056            return ignore::WalkState::Continue;
1057        }
1058        if self.ignore_patterns.has_exceptions()
1059            && is_under_exception_only_hidden_dir(self.root, entry.path(), self.hidden_dir_scopes)
1060            && !self.ignore_patterns.is_lifted(relative)
1061        {
1062            return ignore::WalkState::Continue;
1063        }
1064        let symlink_size = if entry.file_type().is_some_and(|ft| ft.is_symlink()) {
1065            let Some(size) = contained_symlink_file_size(entry.path(), self.canonical_root) else {
1066                tracing::debug!(
1067                    path = %entry.path().display(),
1068                    "skipping source symlink with a broken, non-file, or outside-root target"
1069                );
1070                return ignore::WalkState::Continue;
1071            };
1072            Some(size)
1073        } else {
1074            None
1075        };
1076        if has_source_extension(entry.path()) {
1077            let size_bytes =
1078                symlink_size.unwrap_or_else(|| entry.metadata().map_or(0, |m| m.len()));
1079            self.local.push((entry.into_path(), size_bytes));
1080        } else if self.config_shared.is_some() {
1081            // A non-source file admitted by the config-candidate type group. No
1082            // size metadata is needed; these are pattern-matched, never parsed.
1083            self.config_local.push(entry.into_path());
1084        }
1085        ignore::WalkState::Continue
1086    }
1087}
1088
1089fn contained_symlink_file_size(path: &Path, canonical_root: Option<&Path>) -> Option<u64> {
1090    let root = canonical_root?;
1091    let target = path.canonicalize().ok()?;
1092    if !target.starts_with(root) {
1093        return None;
1094    }
1095    let metadata = target.metadata().ok()?;
1096    metadata.is_file().then_some(metadata.len())
1097}
1098
1099impl Drop for FileVisitor<'_> {
1100    #[expect(
1101        clippy::expect_used,
1102        reason = "poisoned walk collector lock means worker state is unrecoverable"
1103    )]
1104    fn drop(&mut self) {
1105        if !self.local.is_empty() {
1106            self.shared
1107                .lock()
1108                .expect("walk collector lock poisoned")
1109                .append(&mut self.local);
1110        }
1111        if let Some(config_shared) = self.config_shared
1112            && !self.config_local.is_empty()
1113        {
1114            config_shared
1115                .lock()
1116                .expect("walk config collector lock poisoned")
1117                .append(&mut self.config_local);
1118        }
1119        if !self.excluded_local.is_empty() {
1120            let mut shared = self
1121                .excluded_shared
1122                .lock()
1123                .expect("walk exclusion collector lock poisoned");
1124            for (index, tally) in std::mem::take(&mut self.excluded_local) {
1125                shared.entry(index).or_default().merge(tally);
1126            }
1127        }
1128    }
1129}
1130
1131/// Builder that creates per-thread `FileVisitor` instances for the parallel walker.
1132struct FileVisitorBuilder<'a> {
1133    root: &'a Path,
1134    canonical_root: Option<&'a Path>,
1135    ignore_patterns: &'a IgnorePatternSet,
1136    user_ignore_pattern_count: usize,
1137    hidden_dir_scopes: &'a [HiddenDirScope],
1138    production_excludes: &'a Option<globset::GlobSet>,
1139    shared: &'a Mutex<Vec<(std::path::PathBuf, u64)>>,
1140    config_shared: Option<&'a Mutex<Vec<std::path::PathBuf>>>,
1141    excluded_shared: &'a Mutex<ExclusionTally>,
1142}
1143
1144impl<'s> ignore::ParallelVisitorBuilder<'s> for FileVisitorBuilder<'s> {
1145    fn build(&mut self) -> Box<dyn ignore::ParallelVisitor + 's> {
1146        Box::new(FileVisitor {
1147            root: self.root,
1148            canonical_root: self.canonical_root,
1149            ignore_patterns: self.ignore_patterns,
1150            user_ignore_pattern_count: self.user_ignore_pattern_count,
1151            hidden_dir_scopes: self.hidden_dir_scopes,
1152            production_excludes: self.production_excludes,
1153            shared: self.shared,
1154            config_shared: self.config_shared,
1155            excluded_shared: self.excluded_shared,
1156            local: Vec::new(),
1157            config_local: Vec::new(),
1158            excluded_local: ExclusionTally::default(),
1159            match_buf: Vec::new(),
1160        })
1161    }
1162}
1163
1164/// File extensions discovery treats as analyzable source files.
1165pub const SOURCE_EXTENSIONS: &[&str] = &[
1166    "ts", "tsx", "mts", "cts", "gts", "js", "jsx", "mjs", "cjs", "gjs", "vue", "svelte", "astro",
1167    "mdx", "css", "scss", "sass", "less", "html", "graphql", "gql",
1168];
1169
1170/// Glob patterns for test/dev/story files excluded in production mode.
1171pub const PRODUCTION_EXCLUDE_PATTERNS: &[&str] = &[
1172    "**/*.test.*",
1173    "**/*.spec.*",
1174    "**/*.e2e.*",
1175    "**/*.e2e-spec.*",
1176    "**/*.bench.*",
1177    "**/*.fixture.*",
1178    "**/*.stories.*",
1179    "**/*.story.*",
1180    "**/__tests__/**",
1181    "**/__mocks__/**",
1182    "**/__snapshots__/**",
1183    "**/__fixtures__/**",
1184    "**/test-d/**",
1185    "**/test/**",
1186    "**/tests/**",
1187    "*.config.*",
1188    "**/.*.js",
1189    "**/.*.ts",
1190    "**/.*.mjs",
1191    "**/.*.cjs",
1192];
1193
1194/// Check if a hidden directory name is on the allowlist.
1195pub fn is_allowed_hidden_dir(name: &OsStr) -> bool {
1196    ALLOWED_HIDDEN_DIRS.iter().any(|&d| OsStr::new(d) == name)
1197}
1198
1199fn is_allowed_scoped_hidden_dir(
1200    name: &OsStr,
1201    path: &Path,
1202    additional_hidden_dir_scopes: &[HiddenDirScope],
1203) -> bool {
1204    additional_hidden_dir_scopes
1205        .iter()
1206        .any(|scope| scope.allows(path, name))
1207}
1208
1209/// Files Yarn Plug'n'Play writes at the workspace root. They carry source
1210/// extensions (`.pnp.cjs` is the multi-megabyte generated loader with the
1211/// install state inlined, `.pnp.loader.mjs` its ESM shim) but are install
1212/// artifacts, not project source, so the walker drops them by name.
1213const YARN_PNP_GENERATED_FILES: &[&str] = &[".pnp.cjs", ".pnp.loader.mjs"];
1214
1215fn is_yarn_pnp_generated_file(name: &OsStr) -> bool {
1216    YARN_PNP_GENERATED_FILES
1217        .iter()
1218        .any(|&f| OsStr::new(f) == name)
1219}
1220
1221/// Check if a hidden directory entry should be allowed through the filter.
1222///
1223/// Returns `true` if the entry is not hidden or is on the allowlist.
1224/// Hidden files (not directories) are allowed through since the type filter
1225/// handles them, except for the generated Yarn PnP files.
1226fn is_allowed_hidden_with_scopes(
1227    entry: &ignore::DirEntry,
1228    additional_hidden_dir_scopes: &[HiddenDirScope],
1229) -> bool {
1230    let name = entry.file_name();
1231    let name_str = name.to_string_lossy();
1232
1233    if !name_str.starts_with('.') {
1234        return true;
1235    }
1236
1237    if entry.file_type().is_some_and(|ft| !ft.is_dir()) {
1238        return !is_yarn_pnp_generated_file(name);
1239    }
1240
1241    is_allowed_hidden_dir(name)
1242        || is_allowed_scoped_hidden_dir(name, entry.path(), additional_hidden_dir_scopes)
1243}
1244
1245/// True when a parent directory of `path` is hidden and only a `!` exception
1246/// in `ignorePatterns` opened it: the allowlist and the plugin and script
1247/// scopes do not admit it. A file there is kept only when an exception
1248/// matches the file itself.
1249fn is_under_exception_only_hidden_dir(
1250    root: &Path,
1251    path: &Path,
1252    hidden_dir_scopes: &[HiddenDirScope],
1253) -> bool {
1254    path.ancestors()
1255        .skip(1)
1256        .take_while(|dir| *dir != root && dir.starts_with(root))
1257        .any(|dir| {
1258            dir.file_name().is_some_and(|name| {
1259                name.to_string_lossy().starts_with('.')
1260                    && !is_allowed_hidden_dir(name)
1261                    && !is_allowed_scoped_hidden_dir(name, dir, hidden_dir_scopes)
1262            })
1263        })
1264}
1265
1266/// Discover all source files in the project.
1267///
1268/// # Panics
1269///
1270/// Panics if the file type glob or progress template is invalid (compile-time constants).
1271pub fn discover_files(config: &ResolvedConfig) -> Vec<DiscoveredFile> {
1272    discover_files_with_additional_hidden_dirs(config, &[])
1273}
1274
1275/// The set of config-file basenames (last path component of every built-in
1276/// plugin `config_patterns()` entry, brace forms preserved) that the walk should
1277/// additionally admit so non-source configs (`tsconfig.json`, `bunfig.toml`,
1278/// `.eslintrc.json`, ...) can be captured in one traversal instead of being
1279/// re-discovered by a filesystem re-walk in `discover_config_files`.
1280///
1281/// Derived live from the built-in plugin list, so it can never drift behind a
1282/// new plugin's config patterns. Source-extension config basenames
1283/// (`vite.config.{ts,js}`) are admitted too, but the walk visitor routes them
1284/// back to the source channel by extension, so the config channel only ever
1285/// collects genuinely non-source files.
1286fn config_candidate_basename_globs() -> &'static [String] {
1287    static GLOBS: OnceLock<Vec<String>> = OnceLock::new();
1288    GLOBS.get_or_init(|| {
1289        let mut set: FxHashSet<String> = FxHashSet::default();
1290        for plugin in crate::plugins::registry::builtin::create_builtin_plugins() {
1291            for pattern in plugin.config_patterns() {
1292                let basename = pattern.rsplit('/').next().unwrap_or(pattern);
1293                set.insert(basename.to_string());
1294            }
1295            // Tooling evidence resolves always-used files, such as `.c8rc.json`,
1296            // in workspace directories against the candidate index. A wildcard
1297            // basename such as `*` would capture every file, so it stays out.
1298            if plugin.tooling_dependencies().is_empty() {
1299                continue;
1300            }
1301            for pattern in plugin.always_used() {
1302                let basename = pattern.rsplit('/').next().unwrap_or(pattern);
1303                if !basename.starts_with('!') && !basename.contains(['*', '?', '[']) {
1304                    set.insert(basename.to_string());
1305                }
1306            }
1307        }
1308        let mut globs: Vec<String> = set.into_iter().collect();
1309        globs.sort_unstable();
1310        globs
1311    })
1312}
1313
1314/// True when `path`'s extension is one of the known source extensions, i.e. the
1315/// file belongs in the source channel rather than the config-candidate channel.
1316fn has_source_extension(path: &Path) -> bool {
1317    path.extension()
1318        .and_then(OsStr::to_str)
1319        .is_some_and(|ext| SOURCE_EXTENSIONS.contains(&ext))
1320}
1321
1322/// Build the file-type filter. Always selects known source extensions; when
1323/// `capture_config` is set, also selects config-candidate basenames so the
1324/// walker yields them for the second collection channel.
1325#[expect(
1326    clippy::expect_used,
1327    reason = "source file globs are hard-coded compile-time constants"
1328)]
1329fn build_walk_types(capture_config: bool) -> ignore::types::Types {
1330    static SOURCE_TYPES: OnceLock<ignore::types::Types> = OnceLock::new();
1331    static SOURCE_AND_CONFIG_TYPES: OnceLock<ignore::types::Types> = OnceLock::new();
1332
1333    let cache = if capture_config {
1334        &SOURCE_AND_CONFIG_TYPES
1335    } else {
1336        &SOURCE_TYPES
1337    };
1338    cache
1339        .get_or_init(|| {
1340            let mut types_builder = ignore::types::TypesBuilder::new();
1341            let source_glob = format!("*.{{{}}}", SOURCE_EXTENSIONS.join(","));
1342            types_builder
1343                .add("source", &source_glob)
1344                .expect("valid glob");
1345            types_builder.select("source");
1346            if capture_config {
1347                for glob in config_candidate_basename_globs() {
1348                    // Ignore individually-invalid plugin patterns rather than panicking;
1349                    // a malformed pattern simply fails to admit its config file (the
1350                    // pre-existing filesystem fallback still covers production mode).
1351                    let _ = types_builder.add("config", glob);
1352                }
1353                types_builder.select("config");
1354            }
1355            types_builder.build().expect("valid types")
1356        })
1357        .clone()
1358}
1359
1360/// Construct the parallel walker, applying the appropriate hidden-dir filter.
1361/// When `capture_config` is set the walk also yields config-candidate files for
1362/// the secondary collection channel.
1363fn build_source_walk_builder(
1364    config: &ResolvedConfig,
1365    additional_hidden_dir_scopes: &[HiddenDirScope],
1366    capture_config: bool,
1367    skipped_dotdirs: &SkippedDotdirSink,
1368) -> WalkBuilder {
1369    let mut walk_builder = fallow_config::source_walk_builder(&config.root);
1370    walk_builder
1371        .types(build_walk_types(capture_config))
1372        .threads(config.threads);
1373    // One filter, not two: `filter_entry` replaces rather than chains, and the
1374    // dropped-dotdir record has to happen on the same false path that decides
1375    // the skip so the allowlist and every plugin- or script-contributed scope
1376    // are excluded by construction (issue #461).
1377    let scopes = additional_hidden_dir_scopes.to_vec();
1378    let sink = Arc::clone(skipped_dotdirs);
1379    let root = config.root.clone();
1380    let ignore_patterns = config.ignore_patterns.clone();
1381    walk_builder.filter_entry(move |entry| {
1382        if is_allowed_hidden_with_scopes(entry, &scopes) {
1383            return true;
1384        }
1385        // A `!` entry in `ignorePatterns` that can match a file in this hidden
1386        // directory opens it (issue #2452). The visitor then keeps only the
1387        // files an exception matches.
1388        if ignore_patterns.has_exceptions()
1389            && entry.file_type().is_some_and(|ft| ft.is_dir())
1390            && ignore_patterns.admits_hidden_dir(
1391                entry
1392                    .path()
1393                    .strip_prefix(&root)
1394                    .unwrap_or_else(|_| entry.path()),
1395            )
1396        {
1397            return true;
1398        }
1399        if entry.file_type().is_some_and(|ft| ft.is_dir())
1400            && let Ok(mut collected) = sink.lock()
1401        {
1402            collected.push(entry.path().to_path_buf());
1403        }
1404        false
1405    });
1406    walk_builder
1407}
1408
1409/// Compile the production-mode exclude glob set, or `None` outside production mode.
1410fn build_production_excludes(config: &ResolvedConfig) -> Option<globset::GlobSet> {
1411    if !config.production {
1412        return None;
1413    }
1414    let mut builder = globset::GlobSetBuilder::new();
1415    for pattern in PRODUCTION_EXCLUDE_PATTERNS {
1416        if let Ok(glob) = globset::GlobBuilder::new(pattern)
1417            .literal_separator(true)
1418            .build()
1419        {
1420            builder.add(glob);
1421        }
1422    }
1423    builder.build().ok()
1424}
1425
1426/// Discover all source files in the project, with package-scoped hidden dirs.
1427///
1428/// # Panics
1429///
1430/// Panics if the file type glob or progress template is invalid (compile-time constants).
1431pub fn discover_files_with_additional_hidden_dirs(
1432    config: &ResolvedConfig,
1433    additional_hidden_dir_scopes: &[HiddenDirScope],
1434) -> Vec<DiscoveredFile> {
1435    discover_files_and_config_candidates(config, additional_hidden_dir_scopes).0
1436}
1437
1438/// Discover source files AND, in one traversal, the non-source config-candidate
1439/// files (`tsconfig.json`, `bunfig.toml`, `.eslintrc.json`, ...) used by
1440/// `discover_config_files` to resolve plugin config patterns in-memory instead of
1441/// re-walking the filesystem.
1442///
1443/// The returned `Vec<DiscoveredFile>` is byte-for-byte identical to the
1444/// config-capture-disabled walk: config candidates are routed to the second
1445/// return value by extension and never enter the source channel. Config capture
1446/// is skipped in production mode (where the walk applies `PRODUCTION_EXCLUDE_PATTERNS`
1447/// and `discover_config_files` keeps its filesystem path), so the second vector is
1448/// empty there.
1449///
1450/// # Panics
1451///
1452/// Panics if the file type glob or progress template is invalid (compile-time constants).
1453pub fn discover_files_and_config_candidates(
1454    config: &ResolvedConfig,
1455    additional_hidden_dir_scopes: &[HiddenDirScope],
1456) -> (Vec<DiscoveredFile>, Vec<PathBuf>) {
1457    let discovered =
1458        discover_files_config_candidates_and_diagnostics(config, additional_hidden_dir_scopes);
1459    (discovered.files, discovered.config_candidates)
1460}
1461
1462/// Source files, config candidates, and the source-discovery diagnostics one
1463/// walk produced.
1464///
1465/// `diagnostics` is the walk's OWN skip list, not a read of the process-wide
1466/// registry: combined mode can run two walks on the same root concurrently, and
1467/// each walk replaces the registry's source-discovery entries, so only the
1468/// by-value list is a stable answer to "what did THIS analysis skip" (issue
1469/// #2366).
1470pub struct DiscoveredSources {
1471    /// Source files with stable path-sorted [`FileId`]s.
1472    pub files: Vec<DiscoveredFile>,
1473    /// Non-source config-candidate paths captured in the same traversal.
1474    pub config_candidates: Vec<PathBuf>,
1475    /// Skipped-large-file, skipped-minified-file, and skipped-source-dotdir
1476    /// diagnostics from this walk.
1477    pub diagnostics: Vec<WorkspaceDiagnostic>,
1478}
1479
1480/// [`discover_files_and_config_candidates`] plus the source-discovery
1481/// diagnostics this walk recorded, for callers that must carry a per-analysis
1482/// snapshot instead of reading the shared registry back (issue #2366).
1483///
1484/// # Panics
1485///
1486/// Panics if the file type glob or progress template is invalid (compile-time constants).
1487#[expect(
1488    clippy::cast_possible_truncation,
1489    reason = "file count is bounded by project size, well under u32::MAX"
1490)]
1491#[expect(clippy::expect_used, reason = "the collector lock must remain usable")]
1492pub fn discover_files_config_candidates_and_diagnostics(
1493    config: &ResolvedConfig,
1494    additional_hidden_dir_scopes: &[HiddenDirScope],
1495) -> DiscoveredSources {
1496    let _span = tracing::info_span!("discover_files").entered();
1497
1498    let capture_config = !config.production;
1499    let skipped_dotdirs: SkippedDotdirSink = Arc::new(Mutex::new(Vec::new()));
1500    let walk_builder = build_source_walk_builder(
1501        config,
1502        additional_hidden_dir_scopes,
1503        capture_config,
1504        &skipped_dotdirs,
1505    );
1506    let production_excludes = build_production_excludes(config);
1507    let canonical_root = config.root.canonicalize().ok();
1508
1509    let collected: Mutex<Vec<(std::path::PathBuf, u64)>> = Mutex::new(Vec::new());
1510    let config_collected: Mutex<Vec<std::path::PathBuf>> = Mutex::new(Vec::new());
1511    let excluded_collected: Mutex<ExclusionTally> = Mutex::new(ExclusionTally::default());
1512    let mut visitor_builder = FileVisitorBuilder {
1513        root: &config.root,
1514        canonical_root: canonical_root.as_deref(),
1515        ignore_patterns: &config.ignore_patterns,
1516        user_ignore_pattern_count: config.user_ignore_pattern_count,
1517        hidden_dir_scopes: additional_hidden_dir_scopes,
1518        production_excludes: &production_excludes,
1519        shared: &collected,
1520        config_shared: capture_config.then_some(&config_collected),
1521        excluded_shared: &excluded_collected,
1522    };
1523    walk_builder.build_parallel().visit(&mut visitor_builder);
1524    config.ignore_patterns.mark_walked();
1525
1526    let mut raw = collected
1527        .into_inner()
1528        .expect("walk collector lock poisoned");
1529    // ADR-004 (path-sorted FileIds): the parallel walk visits files in
1530    // nondeterministic order, so we sort by absolute path BEFORE the
1531    // `.enumerate()` FileId assignment below. This is the stable-cross-run
1532    // identity invariant the persisted graph cache depends on: an identical
1533    // file set yields identical FileIds, so a cache hit (same paths +
1534    // fingerprints) can trust graph data persisted by FileId. Do not replace
1535    // this with insertion-order assignment.
1536    sort_permuted(&mut raw, PermutationSite::Files, |a, b| a.0.cmp(&b.0));
1537
1538    let mut config_candidates = config_collected
1539        .into_inner()
1540        .expect("walk config collector lock poisoned");
1541    sort_permuted(&mut config_candidates, PermutationSite::Configs, Ord::cmp);
1542
1543    let excluded_by_default_ignore = excluded_collected
1544        .into_inner()
1545        .expect("walk exclusion collector lock poisoned");
1546
1547    // The parallel walk records dotdirs in nondeterministic thread order, and
1548    // the diagnostic array order is part of the JSON contract, so sort and
1549    // dedupe before the predicate runs (issue #2366).
1550    let mut dotdir_candidates = skipped_dotdirs
1551        .lock()
1552        .map_or_else(|_| Vec::new(), |mut guard| std::mem::take(&mut *guard));
1553    sort_permuted(&mut dotdir_candidates, PermutationSite::Dotdirs, Ord::cmp);
1554    dotdir_candidates.dedup();
1555
1556    let (kept, skipped) = partition_by_size(raw, config.max_file_size_bytes);
1557    let (kept, skipped_minified) =
1558        partition_minified_generated_js(kept, config.max_file_size_bytes);
1559    // One registry write replaces this root's whole source-discovery set, so a
1560    // stale entry from a previous pass drops out (issue #1086) without a window
1561    // in which a concurrent walk on the same root can observe or clobber a
1562    // half-written set (issue #2366).
1563    let diagnostics = fallow_config::replace_source_discovery_diagnostics(
1564        &config.root,
1565        report_skipped_large_files(config, &skipped)
1566            .into_iter()
1567            .chain(report_skipped_minified_files(config, &skipped_minified))
1568            .chain(report_skipped_source_dotdirs(
1569                config,
1570                production_excludes.as_ref(),
1571                &dotdir_candidates,
1572            ))
1573            .chain(report_default_ignore_exclusions(
1574                config,
1575                &excluded_by_default_ignore,
1576            ))
1577            .chain(report_missing_node_modules(config))
1578            .chain(report_no_source_files_analyzed(
1579                config,
1580                kept.len(),
1581                &excluded_by_default_ignore,
1582            ))
1583            .collect(),
1584    );
1585
1586    let files: Vec<DiscoveredFile> = kept
1587        .into_iter()
1588        .enumerate()
1589        .map(|(idx, (path, size_bytes))| DiscoveredFile {
1590            id: FileId(idx as u32),
1591            path,
1592            size_bytes,
1593        })
1594        .collect();
1595
1596    note_largest_files(config, &files);
1597    super::legacy_glob::warn_legacy_glob_narrowings(config, &files);
1598
1599    DiscoveredSources {
1600        files,
1601        config_candidates,
1602        diagnostics,
1603    }
1604}
1605
1606#[cfg(test)]
1607mod tests {
1608    use std::ffi::OsStr;
1609    use std::path::MAIN_SEPARATOR;
1610
1611    use super::*;
1612
1613    /// Issue #2638: the anchor a directory-shaped built-in reports is the
1614    /// directory a reader can act on and the one `fallow --root` takes, not
1615    /// the deepest directory that happens to hold the file.
1616    #[test]
1617    fn exclusion_scope_stops_at_the_patterns_literal_directory_segment() {
1618        assert_eq!(
1619            exclusion_scope(
1620                Path::new("projects/app/build/static/js/main.js"),
1621                "**/build/**"
1622            ),
1623            PathBuf::from("projects/app/build")
1624        );
1625        assert_eq!(
1626            exclusion_scope(Path::new("dist/a.ts"), "**/dist/**"),
1627            PathBuf::from("dist")
1628        );
1629        assert_eq!(
1630            exclusion_scope(
1631                Path::new("node_modules/react/index.js"),
1632                "**/node_modules/**"
1633            ),
1634            PathBuf::from("node_modules"),
1635            "the helper is shape-only: `**/node_modules/**` is never tallied, \
1636             but a directory-shaped pattern still collapses to its literal segment"
1637        );
1638    }
1639
1640    /// The DEEPEST matching segment wins, because the anchor is the directory
1641    /// the `--root` remedy names. Anchoring at the outermost `build` would
1642    /// leave the inner one in the path relative to the new root, so the
1643    /// built-in would match again and the advertised remedy would recover
1644    /// nothing.
1645    #[test]
1646    fn exclusion_scope_takes_the_deepest_matching_segment() {
1647        assert_eq!(
1648            exclusion_scope(Path::new("build/tools/build/a.ts"), "**/build/**"),
1649            PathBuf::from("build/tools/build")
1650        );
1651        assert_eq!(
1652            exclusion_scope(Path::new("dist/pkg/dist/inner/a.ts"), "**/dist/**"),
1653            PathBuf::from("dist/pkg/dist")
1654        );
1655    }
1656
1657    /// A file-shaped pattern has no literal segment to stop at, so the file's
1658    /// own directory is the most specific honest answer.
1659    #[test]
1660    fn exclusion_scope_falls_back_to_the_parent_for_a_file_shaped_pattern() {
1661        assert_eq!(
1662            exclusion_scope(Path::new("vendor/a.min.js"), "**/*.min.js"),
1663            PathBuf::from("vendor")
1664        );
1665        assert_eq!(
1666            exclusion_scope(Path::new("a.min.js"), "**/*.min.js"),
1667            PathBuf::new(),
1668            "a root-level match anchors at the root itself"
1669        );
1670    }
1671
1672    /// A pattern whose literal segment is absent from the path (only reachable
1673    /// through a future pattern shape) degrades to the parent rather than
1674    /// returning the whole path.
1675    #[test]
1676    fn exclusion_scope_falls_back_when_the_literal_segment_is_absent() {
1677        assert_eq!(
1678            exclusion_scope(Path::new("src/nested/a.ts"), "**/build/**"),
1679            PathBuf::from("src/nested")
1680        );
1681    }
1682
1683    /// Issue #2638: `directory_count` distinguishes one contained tree from an
1684    /// exclusion scattered over sibling packages, which is what keeps the
1685    /// rendered message from claiming a majority it does not have.
1686    #[test]
1687    fn the_directory_count_is_the_number_of_distinct_scopes() {
1688        let mut one_tree = ExcludedByPattern::default();
1689        one_tree.record(PathBuf::from("packages/web/build"));
1690        one_tree.record(PathBuf::from("packages/web/build"));
1691        assert_eq!(one_tree.file_count, 2);
1692        assert_eq!(one_tree.directory_count(), 1);
1693
1694        let mut scattered = ExcludedByPattern::default();
1695        scattered.record(PathBuf::from("packages/a/dist"));
1696        scattered.record(PathBuf::from("packages/b/dist"));
1697        assert_eq!(scattered.directory_count(), 2);
1698    }
1699
1700    /// Issue #2638 (AC2): the anchor is the directory with the most excluded
1701    /// files, and a tie resolves to the lexicographically first path so two
1702    /// runs on one tree report the same location.
1703    #[test]
1704    fn the_anchor_is_the_largest_group_with_ties_broken_by_path() {
1705        let mut tally = ExcludedByPattern::default();
1706        for _ in 0..3 {
1707            tally.record(PathBuf::from("packages/web/build"));
1708        }
1709        tally.record(PathBuf::from("packages/api/build"));
1710        assert_eq!(tally.file_count, 4);
1711        assert_eq!(tally.anchor(), PathBuf::from("packages/web/build"));
1712
1713        let mut tied = ExcludedByPattern::default();
1714        tied.record(PathBuf::from("z/build"));
1715        tied.record(PathBuf::from("a/build"));
1716        assert_eq!(tied.anchor(), PathBuf::from("a/build"));
1717    }
1718
1719    /// Per-thread tallies merge into one exact total, which is what makes
1720    /// `file_count` trustworthy on a parallel walk.
1721    #[test]
1722    fn merging_two_thread_tallies_keeps_the_count_exact() {
1723        let mut left = ExcludedByPattern::default();
1724        left.record(PathBuf::from("dist"));
1725        left.record(PathBuf::from("dist"));
1726        let mut right = ExcludedByPattern::default();
1727        right.record(PathBuf::from("dist"));
1728        right.record(PathBuf::from("packages/ui/dist"));
1729
1730        left.merge(right);
1731        assert_eq!(left.file_count, 4);
1732        assert_eq!(left.scopes.get(Path::new("dist")), Some(&3));
1733        assert_eq!(left.anchor(), PathBuf::from("dist"));
1734    }
1735
1736    #[test]
1737    fn skipped_dotdirs_note_names_the_directory_when_there_is_one() {
1738        let root = Path::new("/repo");
1739        let only = PathBuf::from("/repo/.tooling");
1740        let note = build_skipped_dotdirs_note(root, &[&only], false);
1741        assert!(note.contains("skipped 1 hidden directory that contains source files"));
1742        assert!(note.contains("add it to entry, ignoreExports or ignoreDependencies"));
1743        assert!(note.contains("fallow --root .tooling analyzes it on its own"));
1744        assert!(note.contains("does not fix this run"));
1745        assert!(note.contains("add '.tooling/**' to"));
1746        assert!(note.contains("add '!.tooling/**' to ignorePatterns to analyze it"));
1747        assert!(
1748            !note.contains("<dir>"),
1749            "the single-directory remedy must be copy-pasteable: {note}"
1750        );
1751    }
1752
1753    #[test]
1754    fn skipped_dotdirs_note_pluralizes_and_keeps_the_placeholder() {
1755        let root = Path::new("/repo");
1756        let a = PathBuf::from("/repo/.a");
1757        let b = PathBuf::from("/repo/.b");
1758        let note = build_skipped_dotdirs_note(root, &[&a, &b], false);
1759        assert!(note.contains("skipped 2 hidden directories that contain source files"));
1760        assert!(note.contains("fallow --root <dir> analyzes one on its own"));
1761    }
1762
1763    #[test]
1764    fn skipped_dotdirs_note_drops_the_tail_count_when_truncated() {
1765        let root = Path::new("/repo");
1766        let owned: Vec<PathBuf> = (0..8)
1767            .map(|i| PathBuf::from(format!("/repo/.d{i}")))
1768            .collect();
1769        let reportable: Vec<&PathBuf> = owned.iter().collect();
1770
1771        let bounded = build_skipped_dotdirs_note(root, &reportable, true);
1772        assert!(bounded.contains("skipped at least 8 hidden directories"));
1773        assert!(
1774            bounded.contains("and more") && !bounded.contains("and 3 more"),
1775            "an inexact total must not carry an exact remainder: {bounded}"
1776        );
1777
1778        let complete = build_skipped_dotdirs_note(root, &reportable, false);
1779        assert!(!complete.contains("at least"));
1780        assert!(complete.contains("and 3 more"));
1781    }
1782
1783    #[test]
1784    fn dotdir_noise_path_components_stay_sorted_and_lowercase() {
1785        let mut sorted = DOTDIR_NOISE_PATH_COMPONENTS.to_vec();
1786        sorted.sort_unstable();
1787        assert_eq!(sorted, DOTDIR_NOISE_PATH_COMPONENTS);
1788        for component in DOTDIR_NOISE_PATH_COMPONENTS {
1789            assert!(!component.starts_with('.'), "'{component}' is not hidden");
1790            assert_eq!(
1791                *component,
1792                component.to_lowercase(),
1793                "'{component}' is matched verbatim against a path component"
1794            );
1795        }
1796    }
1797
1798    #[test]
1799    fn script_scope_denylist_stays_disjoint_and_sorted() {
1800        let mut sorted = SCRIPT_SCOPE_DENYLIST.to_vec();
1801        sorted.sort_unstable();
1802        assert_eq!(
1803            sorted, SCRIPT_SCOPE_DENYLIST,
1804            "keep the list sorted so additions stay reviewable"
1805        );
1806        for dir in SCRIPT_SCOPE_DENYLIST {
1807            assert!(dir.starts_with('.'), "'{dir}' is not a hidden directory");
1808            assert!(
1809                !ALLOWED_HIDDEN_DIRS.contains(dir),
1810                "'{dir}' is traversed, so it can never be a skipped candidate"
1811            );
1812        }
1813    }
1814
1815    #[test]
1816    fn dotdir_module_extensions_are_a_subset_of_source_extensions() {
1817        for ext in DOTDIR_MODULE_EXTENSIONS {
1818            assert!(
1819                SOURCE_EXTENSIONS.contains(ext),
1820                "'{ext}' is not discovered as source, so it cannot be a trigger"
1821            );
1822        }
1823        for ext in ["css", "scss", "sass", "less", "html", "graphql", "gql"] {
1824            assert!(
1825                !DOTDIR_MODULE_EXTENSIONS.contains(&ext),
1826                "'{ext}' carries no imports or exports for the message to be about"
1827            );
1828        }
1829    }
1830
1831    /// Reproduce the FileId-assignment rule used by `walk_source_files`: sort by
1832    /// absolute path, then assign `FileId(idx)` in that order.
1833    fn assign_file_ids(mut raw: Vec<(std::path::PathBuf, u64)>) -> Vec<DiscoveredFile> {
1834        raw.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1835        raw.into_iter()
1836            .enumerate()
1837            .map(|(idx, (path, size_bytes))| DiscoveredFile {
1838                id: FileId(idx as u32),
1839                path,
1840                size_bytes,
1841            })
1842            .collect()
1843    }
1844
1845    /// ADR-004: an identical file set must yield identical FileIds regardless of
1846    /// the (nondeterministic, parallel) discovery order. The persisted graph
1847    /// cache keys persisted graph data by FileId, so a cache HIT (same paths +
1848    /// fingerprints) must reproduce the exact same FileId-to-path mapping the
1849    /// graph was built against. This guards the cache's soundness prerequisite.
1850    #[test]
1851    fn file_id_assignment_is_deterministic_for_identical_file_set() {
1852        let paths = [
1853            "/project/src/z.ts",
1854            "/project/src/a.ts",
1855            "/project/src/components/Button.tsx",
1856            "/project/src/components/Button.module.css",
1857            "/project/index.ts",
1858        ];
1859
1860        // Two independent walks that observe the same paths in DIFFERENT orders.
1861        let walk_one: Vec<(std::path::PathBuf, u64)> = paths
1862            .iter()
1863            .map(|p| (std::path::PathBuf::from(p), 10))
1864            .collect();
1865        let mut walk_two = walk_one.clone();
1866        walk_two.reverse();
1867
1868        let files_one = assign_file_ids(walk_one);
1869        let files_two = assign_file_ids(walk_two);
1870
1871        // Identical (FileId -> path) mapping despite the different walk orders.
1872        assert_eq!(files_one.len(), files_two.len());
1873        for (a, b) in files_one.iter().zip(files_two.iter()) {
1874            assert_eq!(a.id, b.id);
1875            assert_eq!(a.path, b.path);
1876        }
1877
1878        // The mapping is the path-sorted order, and each FileId equals its index
1879        // (the density invariant `project.rs` asserts and the graph relies on).
1880        for (idx, file) in files_one.iter().enumerate() {
1881            assert_eq!(file.id, FileId(idx as u32));
1882        }
1883        assert_eq!(
1884            files_one[0].path,
1885            std::path::PathBuf::from("/project/index.ts")
1886        );
1887    }
1888
1889    #[test]
1890    fn file_id_assignment_recomputes_after_rename_or_delete() {
1891        let before = assign_file_ids(vec![
1892            (std::path::PathBuf::from("/project/src/a.ts"), 10),
1893            (std::path::PathBuf::from("/project/src/b.ts"), 10),
1894            (std::path::PathBuf::from("/project/src/c.ts"), 10),
1895        ]);
1896        let after_delete = assign_file_ids(vec![
1897            (std::path::PathBuf::from("/project/src/a.ts"), 10),
1898            (std::path::PathBuf::from("/project/src/c.ts"), 10),
1899        ]);
1900        let after_rename = assign_file_ids(vec![
1901            (std::path::PathBuf::from("/project/src/a.ts"), 10),
1902            (std::path::PathBuf::from("/project/src/c.ts"), 10),
1903            (std::path::PathBuf::from("/project/src/d.ts"), 10),
1904        ]);
1905
1906        assert_eq!(before[0].id, FileId(0));
1907        assert_eq!(before[1].id, FileId(1));
1908        assert_eq!(before[2].id, FileId(2));
1909        assert_eq!(after_delete[0].id, FileId(0));
1910        assert_eq!(after_delete[1].id, FileId(1));
1911        assert_eq!(
1912            after_delete[1].path,
1913            std::path::PathBuf::from("/project/src/c.ts")
1914        );
1915        assert_eq!(after_rename[0].id, FileId(0));
1916        assert_eq!(after_rename[1].id, FileId(1));
1917        assert_eq!(
1918            after_rename[1].path,
1919            std::path::PathBuf::from("/project/src/c.ts")
1920        );
1921        assert_eq!(after_rename[2].id, FileId(2));
1922        assert_eq!(
1923            after_rename[2].path,
1924            std::path::PathBuf::from("/project/src/d.ts")
1925        );
1926    }
1927
1928    #[test]
1929    fn allowed_hidden_dirs() {
1930        assert!(is_allowed_hidden_dir(OsStr::new(".storybook")));
1931        assert!(is_allowed_hidden_dir(OsStr::new(".vitepress")));
1932        assert!(is_allowed_hidden_dir(OsStr::new(".well-known")));
1933        assert!(is_allowed_hidden_dir(OsStr::new(".changeset")));
1934        assert!(is_allowed_hidden_dir(OsStr::new(".github")));
1935    }
1936
1937    #[test]
1938    fn disallowed_hidden_dirs() {
1939        assert!(!is_allowed_hidden_dir(OsStr::new(".git")));
1940        assert!(!is_allowed_hidden_dir(OsStr::new(".cache")));
1941        assert!(!is_allowed_hidden_dir(OsStr::new(".vscode")));
1942        assert!(!is_allowed_hidden_dir(OsStr::new(".fallow")));
1943        assert!(!is_allowed_hidden_dir(OsStr::new(".next")));
1944    }
1945
1946    #[test]
1947    fn non_hidden_dirs_not_in_allowlist() {
1948        assert!(!is_allowed_hidden_dir(OsStr::new("src")));
1949        assert!(!is_allowed_hidden_dir(OsStr::new("node_modules")));
1950    }
1951
1952    #[test]
1953    fn walk_types_match_every_supported_source_extension() {
1954        for capture_config in [false, true] {
1955            let types = build_walk_types(capture_config);
1956            for extension in SOURCE_EXTENSIONS {
1957                let path = format!("packages/ui/src/nested/component.{extension}");
1958                assert!(
1959                    types.matched(&path, false).is_whitelist(),
1960                    "expected source match for {path} with capture_config={capture_config}"
1961                );
1962            }
1963        }
1964    }
1965
1966    #[test]
1967    fn walk_types_match_typescript_declaration_files() {
1968        let types = build_walk_types(true);
1969        for path in [
1970            "src/env.d.ts",
1971            "packages/app/types/generated.d.mts",
1972            "packages/app/types/compat.d.cts",
1973        ] {
1974            assert!(
1975                types.matched(path, false).is_whitelist(),
1976                "expected declaration source match for {path}"
1977            );
1978        }
1979    }
1980
1981    #[test]
1982    fn walk_types_reject_source_extension_near_misses() {
1983        for capture_config in [false, true] {
1984            let types = build_walk_types(capture_config);
1985            for path in [
1986                "src/component.tsx.bak",
1987                "src/component.tsxmap",
1988                "src/component.TS",
1989                "src/component.gqlx",
1990                "src/component.htm",
1991                "src/component",
1992                "assets/component.png",
1993            ] {
1994                assert!(
1995                    types.matched(path, false).is_ignore(),
1996                    "expected non-source rejection for {path} with capture_config={capture_config}"
1997                );
1998            }
1999        }
2000    }
2001
2002    #[test]
2003    fn walk_types_keep_config_candidate_selection_separate() {
2004        assert!(
2005            build_walk_types(true)
2006                .matched("packages/app/tsconfig.json", false)
2007                .is_whitelist()
2008        );
2009        assert!(
2010            build_walk_types(false)
2011                .matched("packages/app/tsconfig.json", false)
2012                .is_ignore()
2013        );
2014    }
2015
2016    #[test]
2017    fn source_extensions_are_exactly_the_supported_set() {
2018        let mut actual = SOURCE_EXTENSIONS.to_vec();
2019        actual.sort_unstable();
2020        let mut expected = vec![
2021            "ts", "tsx", "mts", "cts", "gts", "js", "jsx", "mjs", "cjs", "gjs", "vue", "svelte",
2022            "astro", "mdx", "css", "scss", "sass", "less", "html", "graphql", "gql",
2023        ];
2024        expected.sort_unstable();
2025        assert_eq!(actual, expected);
2026    }
2027
2028    /// The production exclude set that discovery uses in production mode.
2029    fn production_excludes() -> globset::GlobSet {
2030        let config = fallow_config::FallowConfig {
2031            production: true.into(),
2032            ..Default::default()
2033        }
2034        .resolve(
2035            std::path::PathBuf::from("/project"),
2036            fallow_config::OutputFormat::Human,
2037            1,
2038            true,
2039            true,
2040            None,
2041        );
2042        build_production_excludes(&config).expect("production mode builds an exclude set")
2043    }
2044
2045    /// `build_production_excludes` drops a pattern that does not compile, so a
2046    /// broken pattern would silently stop excluding its files.
2047    #[test]
2048    fn production_exclude_patterns_all_compile() {
2049        for pattern in PRODUCTION_EXCLUDE_PATTERNS {
2050            assert!(
2051                globset::GlobBuilder::new(pattern)
2052                    .literal_separator(true)
2053                    .build()
2054                    .is_ok(),
2055                "production exclude pattern does not compile: {pattern}"
2056            );
2057        }
2058    }
2059
2060    #[test]
2061    fn production_excludes_test_files() {
2062        let set = production_excludes();
2063        assert!(set.is_match("src/Button.test.ts"));
2064        assert!(set.is_match("src/utils.spec.tsx"));
2065        assert!(set.is_match("src/__tests__/helper.ts"));
2066        assert!(!set.is_match("src/Button.ts"));
2067        assert!(!set.is_match("src/utils.tsx"));
2068    }
2069
2070    #[test]
2071    fn production_excludes_story_files() {
2072        let set = production_excludes();
2073        assert!(set.is_match("src/Button.stories.tsx"));
2074        assert!(set.is_match("src/Card.story.ts"));
2075        assert!(!set.is_match("src/Button.tsx"));
2076    }
2077
2078    #[test]
2079    fn production_excludes_config_files_at_root_only() {
2080        let set = production_excludes();
2081        assert!(set.is_match("vitest.config.ts"));
2082        assert!(set.is_match("jest.config.js"));
2083        assert!(!set.is_match("src/app/app.config.ts"));
2084        assert!(!set.is_match("src/app/app.config.server.ts"));
2085        assert!(!set.is_match("packages/foo/vitest.config.ts"));
2086        assert!(!set.is_match("src/config.ts"));
2087    }
2088
2089    #[test]
2090    fn disallowed_hidden_dirs_idea() {
2091        assert!(!is_allowed_hidden_dir(OsStr::new(".idea")));
2092    }
2093
2094    #[test]
2095    fn is_declaration_file_matches_dts_variants() {
2096        assert!(is_declaration_file(Path::new("env.d.ts")));
2097        assert!(is_declaration_file(Path::new("src/auto-imports.d.ts")));
2098        assert!(is_declaration_file(Path::new("mod.d.mts")));
2099        assert!(is_declaration_file(Path::new("compat.d.cts")));
2100        assert!(!is_declaration_file(Path::new("index.ts")));
2101        assert!(!is_declaration_file(Path::new("component.tsx")));
2102        assert!(!is_declaration_file(Path::new("notes.d.txt")));
2103    }
2104
2105    #[test]
2106    fn format_size_mb_renders_one_decimal() {
2107        assert_eq!(format_size_mb(5 * 1024 * 1024), "5.0 MB");
2108        assert_eq!(format_size_mb(1024 * 1024 + 512 * 1024), "1.5 MB");
2109        assert_eq!(format_size_mb(0), "0.0 MB");
2110    }
2111
2112    #[test]
2113    fn partition_by_size_no_limit_keeps_all() {
2114        let raw = vec![(PathBuf::from("a.ts"), 10), (PathBuf::from("b.ts"), 10_000)];
2115        let (kept, skipped) = partition_by_size(raw, None);
2116        assert_eq!(kept.len(), 2);
2117        assert!(skipped.is_empty());
2118    }
2119
2120    #[test]
2121    fn partition_by_size_skips_strictly_over_limit() {
2122        let raw = vec![
2123            (PathBuf::from("under.ts"), 99),
2124            (PathBuf::from("exact.ts"), 100),
2125            (PathBuf::from("over.ts"), 101),
2126        ];
2127        let (kept, skipped) = partition_by_size(raw, Some(100));
2128        let kept_has = |name: &str| kept.iter().any(|(p, _)| p.as_path() == Path::new(name));
2129        assert!(kept_has("under.ts"));
2130        assert!(
2131            kept_has("exact.ts"),
2132            "a file exactly at the limit is kept (skip is strictly-greater)"
2133        );
2134        assert_eq!(skipped.len(), 1);
2135        assert_eq!(skipped[0].0, PathBuf::from("over.ts"));
2136    }
2137
2138    #[test]
2139    fn partition_by_size_exempts_declaration_files() {
2140        let raw = vec![
2141            (PathBuf::from("huge.ts"), 10_000),
2142            (PathBuf::from("auto-imports.d.ts"), 10_000),
2143        ];
2144        let (kept, skipped) = partition_by_size(raw, Some(100));
2145        assert!(
2146            kept.iter()
2147                .any(|(p, _)| p.as_path() == Path::new("auto-imports.d.ts")),
2148            "declaration files are exempt from the size skip regardless of size"
2149        );
2150        assert_eq!(skipped.len(), 1);
2151        assert_eq!(skipped[0].0, PathBuf::from("huge.ts"));
2152    }
2153
2154    fn disco(path: &str, size_bytes: u64) -> DiscoveredFile {
2155        DiscoveredFile {
2156            id: FileId(0),
2157            path: PathBuf::from(path),
2158            size_bytes,
2159        }
2160    }
2161
2162    #[test]
2163    fn largest_files_note_below_threshold_is_none() {
2164        let files = [disco("a.ts", 100), disco("b.ts", 200)];
2165        assert!(build_largest_files_note(Path::new("/p"), &files).is_none());
2166    }
2167
2168    #[test]
2169    fn largest_files_note_single_file_uses_singular() {
2170        let files = [disco("big.ts", 5 * 1024 * 1024)];
2171        let note = build_largest_files_note(Path::new("/p"), &files).expect("note fires");
2172        assert!(
2173            note.contains("discovered 1 file;"),
2174            "singular noun on the single-big-file path (issue #1086 regression): {note}"
2175        );
2176        assert!(!note.contains("discovered 1 files"));
2177        assert!(note.contains("big.ts (5.0 MB)"));
2178    }
2179
2180    #[test]
2181    fn largest_files_note_filters_sub_floor_files() {
2182        let files = [disco("big.ts", 5 * 1024 * 1024), disco("tiny.ts", 10)];
2183        let note = build_largest_files_note(Path::new("/p"), &files).expect("note fires");
2184        assert!(note.contains("discovered 2 files;"));
2185        assert!(note.contains("big.ts (5.0 MB)"));
2186        assert!(
2187            !note.contains("tiny.ts"),
2188            "sub-floor files are not listed as `0.0 MB` chaff: {note}"
2189        );
2190    }
2191
2192    #[test]
2193    fn largest_files_note_large_set_no_big_file_omits_list() {
2194        let files: Vec<DiscoveredFile> = (0..=LARGE_SET_THRESHOLD)
2195            .map(|i| disco(&format!("f{i}.ts"), 100))
2196            .collect();
2197        let note = build_largest_files_note(Path::new("/p"), &files).expect("large set fires");
2198        assert!(note.contains(&format!("discovered {} files", LARGE_SET_THRESHOLD + 1)));
2199        assert!(
2200            !note.contains("largest:"),
2201            "no sub-floor `largest:` list when no file clears the floor: {note}"
2202        );
2203    }
2204
2205    mod discover_files_integration {
2206        use std::path::PathBuf;
2207
2208        use fallow_config::{
2209            DuplicatesConfig, FallowConfig, FlagsConfig, HealthConfig, OutputFormat, ResolveConfig,
2210            RulesConfig,
2211        };
2212
2213        use super::*;
2214
2215        /// Create a minimal ResolvedConfig pointing at the given root directory.
2216        fn make_config(root: PathBuf, production: bool) -> ResolvedConfig {
2217            FallowConfig {
2218                production: production.into(),
2219                ..Default::default()
2220            }
2221            .resolve(root, OutputFormat::Human, 1, true, true, None)
2222        }
2223
2224        /// Helper to collect discovered file names (relative to root) for assertions.
2225        /// Normalizes path separators to `/` for cross-platform test consistency.
2226        fn file_names(files: &[DiscoveredFile], root: &std::path::Path) -> Vec<String> {
2227            files
2228                .iter()
2229                .map(|f| {
2230                    f.path
2231                        .strip_prefix(root)
2232                        .unwrap_or(&f.path)
2233                        .to_string_lossy()
2234                        .replace('\\', "/")
2235                })
2236                .collect()
2237        }
2238
2239        #[cfg(unix)]
2240        fn symlink_file(target: &Path, link: &Path) {
2241            std::os::unix::fs::symlink(target, link).expect("create file symlink");
2242        }
2243
2244        #[cfg(windows)]
2245        fn symlink_file(target: &Path, link: &Path) {
2246            std::os::windows::fs::symlink_file(target, link).expect("create file symlink");
2247        }
2248
2249        #[cfg(unix)]
2250        fn symlink_dir(target: &Path, link: &Path) {
2251            std::os::unix::fs::symlink(target, link).expect("create directory symlink");
2252        }
2253
2254        #[cfg(windows)]
2255        fn symlink_dir(target: &Path, link: &Path) {
2256            std::os::windows::fs::symlink_dir(target, link).expect("create directory symlink");
2257        }
2258
2259        #[test]
2260        fn source_symlinks_must_target_regular_files_inside_root() {
2261            let dir = tempfile::tempdir().expect("create project");
2262            let outside = tempfile::tempdir().expect("create outside dir");
2263            let src = dir.path().join("src");
2264            std::fs::create_dir_all(&src).unwrap();
2265            std::fs::write(src.join("regular.ts"), "export const regular = 1;").unwrap();
2266            std::fs::write(src.join("inside-target.ts"), "export const inside = 1;").unwrap();
2267            std::fs::write(
2268                outside.path().join("outside-target.ts"),
2269                "export const outside = 1;",
2270            )
2271            .unwrap();
2272            std::fs::create_dir_all(src.join("directory-target")).unwrap();
2273
2274            symlink_file(&src.join("inside-target.ts"), &src.join("inside-link.ts"));
2275            symlink_file(
2276                &outside.path().join("outside-target.ts"),
2277                &src.join("outside-link.ts"),
2278            );
2279            symlink_file(&src.join("missing-target.ts"), &src.join("broken-link.ts"));
2280            symlink_dir(
2281                &src.join("directory-target"),
2282                &src.join("directory-link.ts"),
2283            );
2284
2285            let config = make_config(dir.path().to_path_buf(), false);
2286            let names = file_names(&discover_files(&config), dir.path());
2287
2288            assert!(names.contains(&"src/regular.ts".to_string()));
2289            assert!(names.contains(&"src/inside-target.ts".to_string()));
2290            assert!(names.contains(&"src/inside-link.ts".to_string()));
2291            assert!(!names.contains(&"src/outside-link.ts".to_string()));
2292            assert!(!names.contains(&"src/broken-link.ts".to_string()));
2293            assert!(!names.contains(&"src/directory-link.ts".to_string()));
2294        }
2295
2296        /// Yarn PnP writes `.pnp.cjs` and `.pnp.loader.mjs` at the workspace
2297        /// root. They match the source extension filter but are generated
2298        /// install state, not code to analyze.
2299        #[test]
2300        fn skips_yarn_pnp_generated_files() {
2301            let dir = tempfile::tempdir().expect("create temp dir");
2302            std::fs::write(dir.path().join(".pnp.cjs"), "module.exports = {};").unwrap();
2303            std::fs::write(dir.path().join(".pnp.loader.mjs"), "export {};").unwrap();
2304            std::fs::write(dir.path().join("index.ts"), "export const a = 1;").unwrap();
2305
2306            let config = make_config(dir.path().to_path_buf(), false);
2307            let names = file_names(&discover_files(&config), dir.path());
2308
2309            assert_eq!(names, vec!["index.ts".to_string()]);
2310        }
2311
2312        #[test]
2313        fn discovers_source_files_with_valid_extensions() {
2314            let dir = tempfile::tempdir().expect("create temp dir");
2315            let src = dir.path().join("src");
2316            std::fs::create_dir_all(&src).unwrap();
2317
2318            std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
2319            std::fs::write(src.join("component.tsx"), "export default () => {};").unwrap();
2320            std::fs::write(src.join("utils.js"), "module.exports = {};").unwrap();
2321            std::fs::write(src.join("helper.jsx"), "export const h = 1;").unwrap();
2322            std::fs::write(src.join("config.mjs"), "export default {};").unwrap();
2323            std::fs::write(src.join("legacy.cjs"), "module.exports = {};").unwrap();
2324            std::fs::write(src.join("types.mts"), "export type T = string;").unwrap();
2325            std::fs::write(src.join("compat.cts"), "module.exports = {};").unwrap();
2326
2327            let config = make_config(dir.path().to_path_buf(), false);
2328            let files = discover_files(&config);
2329            let names = file_names(&files, dir.path());
2330
2331            assert!(names.contains(&"src/app.ts".to_string()));
2332            assert!(names.contains(&"src/component.tsx".to_string()));
2333            assert!(names.contains(&"src/utils.js".to_string()));
2334            assert!(names.contains(&"src/helper.jsx".to_string()));
2335            assert!(names.contains(&"src/config.mjs".to_string()));
2336            assert!(names.contains(&"src/legacy.cjs".to_string()));
2337            assert!(names.contains(&"src/types.mts".to_string()));
2338            assert!(names.contains(&"src/compat.cts".to_string()));
2339        }
2340
2341        #[test]
2342        fn compact_source_glob_preserves_discovered_file_inventory() {
2343            let dir = tempfile::tempdir().expect("create temp dir");
2344            let nested = dir.path().join("packages/ui/src/nested");
2345            std::fs::create_dir_all(&nested).unwrap();
2346
2347            let mut expected = Vec::new();
2348            for (index, extension) in SOURCE_EXTENSIONS.iter().enumerate() {
2349                let relative = format!("packages/ui/src/nested/source-{index}.{extension}");
2350                std::fs::write(dir.path().join(&relative), "export const value = 1;").unwrap();
2351                expected.push(relative);
2352            }
2353            for relative in [
2354                "packages/ui/src/nested/env.d.ts",
2355                "packages/ui/src/nested/generated.d.mts",
2356                "packages/ui/src/nested/compat.d.cts",
2357            ] {
2358                std::fs::write(dir.path().join(relative), "export type Value = string;").unwrap();
2359                expected.push(relative.to_string());
2360            }
2361            let rejected = [
2362                "packages/ui/src/nested/component.tsx.bak",
2363                "packages/ui/src/nested/component.tsxmap",
2364                "packages/ui/src/nested/component.TS",
2365                "packages/ui/src/nested/component.gqlx",
2366                "packages/ui/src/nested/component.htm",
2367                "packages/ui/src/nested/component",
2368                "packages/ui/src/nested/component.png",
2369            ];
2370            for relative in rejected {
2371                std::fs::write(dir.path().join(relative), "not source").unwrap();
2372            }
2373
2374            let config = make_config(dir.path().to_path_buf(), false);
2375            let names = file_names(&discover_files(&config), dir.path());
2376
2377            for relative in expected {
2378                assert!(
2379                    names.contains(&relative),
2380                    "missing supported source {relative}"
2381                );
2382            }
2383            for relative in rejected {
2384                assert!(
2385                    !names.iter().any(|name| name == relative),
2386                    "unexpected near-miss source {relative}"
2387                );
2388            }
2389        }
2390
2391        #[test]
2392        fn excludes_non_source_extensions() {
2393            let dir = tempfile::tempdir().expect("create temp dir");
2394            let src = dir.path().join("src");
2395            std::fs::create_dir_all(&src).unwrap();
2396
2397            std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
2398
2399            std::fs::write(src.join("data.json"), "{}").unwrap();
2400            std::fs::write(src.join("readme.md"), "# Hello").unwrap();
2401            std::fs::write(src.join("notes.txt"), "notes").unwrap();
2402            std::fs::write(src.join("logo.png"), [0u8; 8]).unwrap();
2403
2404            let config = make_config(dir.path().to_path_buf(), false);
2405            let files = discover_files(&config);
2406            let names = file_names(&files, dir.path());
2407
2408            assert_eq!(names.len(), 1, "only the .ts file should be discovered");
2409            assert!(names.contains(&"src/app.ts".to_string()));
2410        }
2411
2412        #[test]
2413        fn excludes_disallowed_hidden_directories() {
2414            let dir = tempfile::tempdir().expect("create temp dir");
2415
2416            let git_dir = dir.path().join(".git");
2417            std::fs::create_dir_all(&git_dir).unwrap();
2418            std::fs::write(git_dir.join("hooks.ts"), "// git hook").unwrap();
2419
2420            let idea_dir = dir.path().join(".idea");
2421            std::fs::create_dir_all(&idea_dir).unwrap();
2422            std::fs::write(idea_dir.join("workspace.ts"), "// idea").unwrap();
2423
2424            let cache_dir = dir.path().join(".cache");
2425            std::fs::create_dir_all(&cache_dir).unwrap();
2426            std::fs::write(cache_dir.join("cached.js"), "// cached").unwrap();
2427
2428            let src = dir.path().join("src");
2429            std::fs::create_dir_all(&src).unwrap();
2430            std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
2431
2432            let config = make_config(dir.path().to_path_buf(), false);
2433            let files = discover_files(&config);
2434            let names = file_names(&files, dir.path());
2435
2436            assert_eq!(names.len(), 1, "only src/app.ts should be discovered");
2437            assert!(names.contains(&"src/app.ts".to_string()));
2438        }
2439
2440        #[test]
2441        fn includes_allowed_hidden_directories() {
2442            let dir = tempfile::tempdir().expect("create temp dir");
2443
2444            let storybook = dir.path().join(".storybook");
2445            std::fs::create_dir_all(&storybook).unwrap();
2446            std::fs::write(storybook.join("main.ts"), "export default {};").unwrap();
2447
2448            let github = dir.path().join(".github");
2449            std::fs::create_dir_all(&github).unwrap();
2450            std::fs::write(github.join("actions.js"), "module.exports = {};").unwrap();
2451
2452            let changeset = dir.path().join(".changeset");
2453            std::fs::create_dir_all(&changeset).unwrap();
2454            std::fs::write(changeset.join("config.js"), "module.exports = {};").unwrap();
2455
2456            let config = make_config(dir.path().to_path_buf(), false);
2457            let files = discover_files(&config);
2458            let names = file_names(&files, dir.path());
2459
2460            assert!(
2461                names.contains(&".storybook/main.ts".to_string()),
2462                "files in .storybook should be discovered"
2463            );
2464            assert!(
2465                names.contains(&".github/actions.js".to_string()),
2466                "files in .github should be discovered"
2467            );
2468            assert!(
2469                names.contains(&".changeset/config.js".to_string()),
2470                "files in .changeset should be discovered"
2471            );
2472        }
2473
2474        #[test]
2475        fn default_discovery_excludes_client_and_server_hidden_directories() {
2476            let dir = tempfile::tempdir().expect("create temp dir");
2477            let app = dir.path().join("app");
2478            std::fs::create_dir_all(app.join(".client")).unwrap();
2479            std::fs::create_dir_all(app.join(".server")).unwrap();
2480            std::fs::write(app.join(".client/analytics.ts"), "export const a = 1;").unwrap();
2481            std::fs::write(app.join(".server/db.ts"), "export const db = {};").unwrap();
2482            std::fs::write(app.join("root.tsx"), "export default function Root() {}").unwrap();
2483
2484            let config = make_config(dir.path().to_path_buf(), false);
2485            let files = discover_files(&config);
2486            let names = file_names(&files, dir.path());
2487
2488            assert!(names.contains(&"app/root.tsx".to_string()));
2489            assert!(!names.contains(&"app/.client/analytics.ts".to_string()));
2490            assert!(!names.contains(&"app/.server/db.ts".to_string()));
2491        }
2492
2493        #[test]
2494        fn scoped_hidden_dirs_include_client_and_server_under_package_root() {
2495            let dir = tempfile::tempdir().expect("create temp dir");
2496            let package = dir.path().join("packages/app");
2497            std::fs::create_dir_all(package.join("app/.client")).unwrap();
2498            std::fs::create_dir_all(package.join("app/.server")).unwrap();
2499            std::fs::write(
2500                package.join("app/.client/analytics.ts"),
2501                "export const track = () => {};",
2502            )
2503            .unwrap();
2504            std::fs::write(package.join("app/.server/db.ts"), "export const db = {};").unwrap();
2505
2506            let config = make_config(dir.path().to_path_buf(), false);
2507            let scopes = [HiddenDirScope::new(
2508                package,
2509                vec![".client".to_string(), ".server".to_string()],
2510            )];
2511            let files = discover_files_with_additional_hidden_dirs(&config, &scopes);
2512            let names = file_names(&files, dir.path());
2513
2514            assert!(names.contains(&"packages/app/app/.client/analytics.ts".to_string()));
2515            assert!(names.contains(&"packages/app/app/.server/db.ts".to_string()));
2516        }
2517
2518        #[test]
2519        fn scoped_hidden_dirs_do_not_include_unscoped_packages() {
2520            let dir = tempfile::tempdir().expect("create temp dir");
2521            let active = dir.path().join("packages/active");
2522            let inactive = dir.path().join("packages/inactive");
2523            std::fs::create_dir_all(active.join("app/.server")).unwrap();
2524            std::fs::create_dir_all(inactive.join("app/.server")).unwrap();
2525            std::fs::write(active.join("app/.server/db.ts"), "export const db = {};").unwrap();
2526            std::fs::write(inactive.join("app/.server/db.ts"), "export const db = {};").unwrap();
2527
2528            let config = make_config(dir.path().to_path_buf(), false);
2529            let scopes = [HiddenDirScope::new(active, vec![".server".to_string()])];
2530            let files = discover_files_with_additional_hidden_dirs(&config, &scopes);
2531            let names = file_names(&files, dir.path());
2532
2533            assert!(names.contains(&"packages/active/app/.server/db.ts".to_string()));
2534            assert!(!names.contains(&"packages/inactive/app/.server/db.ts".to_string()));
2535        }
2536
2537        #[test]
2538        fn exact_path_scope_does_not_admit_the_same_name_elsewhere() {
2539            // A script naming `.a/.b/deep.mjs` says where the file it needs
2540            // lives. Before issue #461 the scope stored the bare names, so an
2541            // unrelated `elsewhere/.b` and `unrelated/.a` were pulled in too.
2542            let dir = tempfile::tempdir().expect("create temp dir");
2543            std::fs::create_dir_all(dir.path().join(".a/.b")).unwrap();
2544            std::fs::create_dir_all(dir.path().join("elsewhere/.b")).unwrap();
2545            std::fs::create_dir_all(dir.path().join("unrelated/.a")).unwrap();
2546            std::fs::write(dir.path().join(".a/.b/deep.mjs"), "export const a = 1;").unwrap();
2547            std::fs::write(dir.path().join("elsewhere/.b/y.mjs"), "export const b = 1;").unwrap();
2548            std::fs::write(dir.path().join("unrelated/.a/u.mjs"), "export const c = 1;").unwrap();
2549
2550            let config = make_config(dir.path().to_path_buf(), false);
2551            let scopes = [HiddenDirScope::new_exact_paths(
2552                dir.path().to_path_buf(),
2553                vec![".a".to_string(), format!(".a{MAIN_SEPARATOR}.b")],
2554            )];
2555            let files = discover_files_with_additional_hidden_dirs(&config, &scopes);
2556            let names = file_names(&files, dir.path());
2557
2558            assert!(names.contains(&".a/.b/deep.mjs".to_string()));
2559            assert!(!names.contains(&"elsewhere/.b/y.mjs".to_string()));
2560            assert!(!names.contains(&"unrelated/.a/u.mjs".to_string()));
2561        }
2562
2563        #[test]
2564        fn exact_path_scope_admits_a_hidden_dir_under_a_visible_parent() {
2565            let dir = tempfile::tempdir().expect("create temp dir");
2566            std::fs::create_dir_all(dir.path().join("tools/.config")).unwrap();
2567            std::fs::create_dir_all(dir.path().join("other/.config")).unwrap();
2568            std::fs::write(
2569                dir.path().join("tools/.config/eslint.config.js"),
2570                "export default [];",
2571            )
2572            .unwrap();
2573            std::fs::write(
2574                dir.path().join("other/.config/eslint.config.js"),
2575                "export default [];",
2576            )
2577            .unwrap();
2578
2579            let config = make_config(dir.path().to_path_buf(), false);
2580            let scopes = [HiddenDirScope::new_exact_paths(
2581                dir.path().to_path_buf(),
2582                vec![format!("tools{MAIN_SEPARATOR}.config")],
2583            )];
2584            let files = discover_files_with_additional_hidden_dirs(&config, &scopes);
2585            let names = file_names(&files, dir.path());
2586
2587            assert!(names.contains(&"tools/.config/eslint.config.js".to_string()));
2588            assert!(!names.contains(&"other/.config/eslint.config.js".to_string()));
2589        }
2590
2591        #[test]
2592        fn any_depth_scope_keeps_matching_by_name_for_plugins() {
2593            // Framework plugins declare `.client` / `.server` conventions that
2594            // may sit under any route directory, so the plugin shape must keep
2595            // matching at any depth.
2596            let dir = tempfile::tempdir().expect("create temp dir");
2597            std::fs::create_dir_all(dir.path().join("app/routes/deep/.server")).unwrap();
2598            std::fs::write(
2599                dir.path().join("app/routes/deep/.server/db.ts"),
2600                "export const db = {};",
2601            )
2602            .unwrap();
2603
2604            let config = make_config(dir.path().to_path_buf(), false);
2605            let scopes = [HiddenDirScope::new(
2606                dir.path().to_path_buf(),
2607                vec![".server".to_string()],
2608            )];
2609            let files = discover_files_with_additional_hidden_dirs(&config, &scopes);
2610            let names = file_names(&files, dir.path());
2611
2612            assert!(names.contains(&"app/routes/deep/.server/db.ts".to_string()));
2613        }
2614
2615        #[test]
2616        fn excludes_root_build_directory() {
2617            let dir = tempfile::tempdir().expect("create temp dir");
2618
2619            std::fs::write(dir.path().join(".ignore"), "/build/\n").unwrap();
2620
2621            let build_dir = dir.path().join("build");
2622            std::fs::create_dir_all(&build_dir).unwrap();
2623            std::fs::write(build_dir.join("output.js"), "// build output").unwrap();
2624
2625            let src = dir.path().join("src");
2626            std::fs::create_dir_all(&src).unwrap();
2627            std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
2628
2629            let config = make_config(dir.path().to_path_buf(), false);
2630            let files = discover_files(&config);
2631            let names = file_names(&files, dir.path());
2632
2633            assert_eq!(names.len(), 1, "root build/ should be excluded via .ignore");
2634            assert!(names.contains(&"src/app.ts".to_string()));
2635        }
2636
2637        #[test]
2638        fn excludes_nested_build_directory() {
2639            let dir = tempfile::tempdir().expect("create temp dir");
2640
2641            let nested_build = dir.path().join("src").join("build");
2642            std::fs::create_dir_all(&nested_build).unwrap();
2643            std::fs::write(nested_build.join("helper.ts"), "export const h = 1;").unwrap();
2644
2645            let config = make_config(dir.path().to_path_buf(), false);
2646            let files = discover_files(&config);
2647            let names = file_names(&files, dir.path());
2648
2649            assert!(
2650                !names.contains(&"src/build/helper.ts".to_string()),
2651                "build/ is treated as generated output at any depth: {names:?}"
2652            );
2653        }
2654
2655        #[test]
2656        #[expect(
2657            clippy::cast_possible_truncation,
2658            reason = "test file counts are trivially small"
2659        )]
2660        fn file_ids_are_sequential_after_sorting() {
2661            let dir = tempfile::tempdir().expect("create temp dir");
2662            let src = dir.path().join("src");
2663            std::fs::create_dir_all(&src).unwrap();
2664
2665            std::fs::write(src.join("z_last.ts"), "export const z = 1;").unwrap();
2666            std::fs::write(src.join("a_first.ts"), "export const a = 1;").unwrap();
2667            std::fs::write(src.join("m_middle.ts"), "export const m = 1;").unwrap();
2668
2669            let config = make_config(dir.path().to_path_buf(), false);
2670            let files = discover_files(&config);
2671
2672            for (idx, file) in files.iter().enumerate() {
2673                assert_eq!(file.id, FileId(idx as u32), "FileId should be sequential");
2674            }
2675
2676            for pair in files.windows(2) {
2677                assert!(
2678                    pair[0].path < pair[1].path,
2679                    "files should be sorted by path"
2680                );
2681            }
2682        }
2683
2684        #[test]
2685        fn production_mode_excludes_test_files() {
2686            let dir = tempfile::tempdir().expect("create temp dir");
2687            let src = dir.path().join("src");
2688            std::fs::create_dir_all(&src).unwrap();
2689
2690            std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
2691            std::fs::write(src.join("app.test.ts"), "test('a', () => {});").unwrap();
2692            std::fs::write(src.join("app.spec.ts"), "describe('a', () => {});").unwrap();
2693            std::fs::write(src.join("app.stories.tsx"), "export default {};").unwrap();
2694
2695            let config = make_config(dir.path().to_path_buf(), true);
2696            let files = discover_files(&config);
2697            let names = file_names(&files, dir.path());
2698
2699            assert!(
2700                names.contains(&"src/app.ts".to_string()),
2701                "source files should be included in production mode"
2702            );
2703            assert!(
2704                !names.contains(&"src/app.test.ts".to_string()),
2705                "test files should be excluded in production mode"
2706            );
2707            assert!(
2708                !names.contains(&"src/app.spec.ts".to_string()),
2709                "spec files should be excluded in production mode"
2710            );
2711            assert!(
2712                !names.contains(&"src/app.stories.tsx".to_string()),
2713                "story files should be excluded in production mode"
2714            );
2715        }
2716
2717        #[test]
2718        fn non_production_mode_includes_test_files() {
2719            let dir = tempfile::tempdir().expect("create temp dir");
2720            let src = dir.path().join("src");
2721            std::fs::create_dir_all(&src).unwrap();
2722
2723            std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
2724            std::fs::write(src.join("app.test.ts"), "test('a', () => {});").unwrap();
2725
2726            let config = make_config(dir.path().to_path_buf(), false);
2727            let files = discover_files(&config);
2728            let names = file_names(&files, dir.path());
2729
2730            assert!(names.contains(&"src/app.ts".to_string()));
2731            assert!(
2732                names.contains(&"src/app.test.ts".to_string()),
2733                "test files should be included in non-production mode"
2734            );
2735        }
2736
2737        #[test]
2738        fn empty_directory_returns_no_files() {
2739            let dir = tempfile::tempdir().expect("create temp dir");
2740            let config = make_config(dir.path().to_path_buf(), false);
2741            let files = discover_files(&config);
2742            assert!(files.is_empty(), "empty project should discover no files");
2743        }
2744
2745        #[test]
2746        fn hidden_files_not_discovered_as_source() {
2747            let dir = tempfile::tempdir().expect("create temp dir");
2748
2749            std::fs::write(dir.path().join(".env"), "SECRET=abc").unwrap();
2750            std::fs::write(dir.path().join(".gitignore"), "node_modules").unwrap();
2751            std::fs::write(dir.path().join(".eslintrc.js"), "module.exports = {};").unwrap();
2752
2753            let src = dir.path().join("src");
2754            std::fs::create_dir_all(&src).unwrap();
2755            std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
2756
2757            let config = make_config(dir.path().to_path_buf(), false);
2758            let files = discover_files(&config);
2759            let names = file_names(&files, dir.path());
2760
2761            assert!(
2762                !names.contains(&".env".to_string()),
2763                ".env should not be discovered"
2764            );
2765            assert!(
2766                !names.contains(&".gitignore".to_string()),
2767                ".gitignore should not be discovered"
2768            );
2769        }
2770
2771        /// Create a config with custom ignore patterns.
2772        fn make_config_with_ignores(root: PathBuf, ignores: Vec<String>) -> ResolvedConfig {
2773            FallowConfig {
2774                type_aware: fallow_config::TypeAwareConfig::default(),
2775                schema: None,
2776                minimum_version: None,
2777                extends: vec![],
2778                entry: vec![],
2779                ignore_patterns: ignores,
2780                ignore_findings: vec![],
2781                framework: vec![],
2782                workspaces: None,
2783                ignore_dependencies: vec![],
2784                ignore_command_entries: vec![],
2785                ignore_unresolved_imports: vec![],
2786                ignore_exports: vec![],
2787                ignore_catalog_references: vec![],
2788                ignore_dependency_overrides: vec![],
2789                ignore_exports_used_in_file: fallow_config::IgnoreExportsUsedInFileConfig::default(
2790                ),
2791                used_class_members: vec![],
2792                ignore_decorators: vec![],
2793                unused_component_props: fallow_config::UnusedComponentPropsConfig::default(),
2794                circular_dependencies: fallow_config::CircularDependenciesConfig::default(),
2795                duplicates: DuplicatesConfig::default(),
2796                similar_code: fallow_config::SimilarCodeConfig::default(),
2797                mutation: fallow_config::MutationConfig::default(),
2798                health: HealthConfig::default(),
2799                rules: RulesConfig::default(),
2800                boundaries: fallow_config::BoundaryConfig::default(),
2801                production: false.into(),
2802                plugins: vec![],
2803                rule_packs: vec![],
2804                overrides: vec![],
2805                regression: None,
2806                audit: fallow_config::AuditConfig::default(),
2807                codeowners: None,
2808                public_packages: vec![],
2809                flags: FlagsConfig::default(),
2810                security: fallow_config::SecurityConfig::default(),
2811                fix: fallow_config::FixConfig::default(),
2812                resolve: ResolveConfig::default(),
2813                sealed: false,
2814                include_entry_exports: false,
2815                show_cascade: false,
2816                auto_imports: false,
2817                fail_on_parse_error: false,
2818                cache: fallow_config::CacheConfig::default(),
2819                ..Default::default()
2820            }
2821            .resolve(root, OutputFormat::Human, 1, true, true, None)
2822        }
2823
2824        #[test]
2825        fn custom_ignore_patterns_exclude_matching_files() {
2826            let dir = tempfile::tempdir().expect("create temp dir");
2827
2828            let generated = dir.path().join("src").join("api").join("generated");
2829            std::fs::create_dir_all(&generated).unwrap();
2830            std::fs::write(generated.join("client.ts"), "export const api = {};").unwrap();
2831
2832            let client = dir.path().join("src").join("api").join("client");
2833            std::fs::create_dir_all(&client).unwrap();
2834            std::fs::write(client.join("fetch.ts"), "export const fetch = {};").unwrap();
2835
2836            let src = dir.path().join("src");
2837            std::fs::write(src.join("index.ts"), "export const x = 1;").unwrap();
2838
2839            let config = make_config_with_ignores(
2840                dir.path().to_path_buf(),
2841                vec![
2842                    "src/api/generated/**".to_string(),
2843                    "src/api/client/**".to_string(),
2844                ],
2845            );
2846            let files = discover_files(&config);
2847            let names = file_names(&files, dir.path());
2848
2849            assert_eq!(names.len(), 1, "only non-ignored files: {names:?}");
2850            assert!(names.contains(&"src/index.ts".to_string()));
2851        }
2852
2853        #[test]
2854        fn leading_dot_ignore_patterns_exclude_matching_files() {
2855            let dir = tempfile::tempdir().expect("create temp dir");
2856
2857            let generated = dir.path().join("src").join("generated");
2858            std::fs::create_dir_all(&generated).unwrap();
2859            std::fs::write(generated.join("client.ts"), "export const api = {};").unwrap();
2860
2861            let src = dir.path().join("src");
2862            std::fs::write(src.join("index.ts"), "export const x = 1;").unwrap();
2863
2864            let config = make_config_with_ignores(
2865                dir.path().to_path_buf(),
2866                vec!["./src/generated/**".to_string()],
2867            );
2868            let files = discover_files(&config);
2869            let names = file_names(&files, dir.path());
2870
2871            assert_eq!(names, vec!["src/index.ts"]);
2872        }
2873
2874        #[test]
2875        fn default_ignore_patterns_exclude_node_modules_and_dist() {
2876            let dir = tempfile::tempdir().expect("create temp dir");
2877
2878            let nm = dir.path().join("node_modules").join("lodash");
2879            std::fs::create_dir_all(&nm).unwrap();
2880            std::fs::write(nm.join("lodash.js"), "module.exports = {};").unwrap();
2881
2882            let dist = dir.path().join("dist");
2883            std::fs::create_dir_all(&dist).unwrap();
2884            std::fs::write(dist.join("bundle.js"), "// bundled").unwrap();
2885
2886            let src = dir.path().join("src");
2887            std::fs::create_dir_all(&src).unwrap();
2888            std::fs::write(src.join("index.ts"), "export const x = 1;").unwrap();
2889
2890            let config = make_config(dir.path().to_path_buf(), false);
2891            let files = discover_files(&config);
2892            let names = file_names(&files, dir.path());
2893
2894            assert_eq!(names.len(), 1);
2895            assert!(names.contains(&"src/index.ts".to_string()));
2896        }
2897
2898        #[test]
2899        fn default_ignore_patterns_exclude_build_at_any_depth() {
2900            let dir = tempfile::tempdir().expect("create temp dir");
2901
2902            let build = dir.path().join("build");
2903            std::fs::create_dir_all(&build).unwrap();
2904            std::fs::write(build.join("output.js"), "// built").unwrap();
2905
2906            let nested_build = dir.path().join("src").join("build");
2907            std::fs::create_dir_all(&nested_build).unwrap();
2908            std::fs::write(nested_build.join("helper.ts"), "export const h = 1;").unwrap();
2909
2910            let src = dir.path().join("src");
2911            std::fs::write(src.join("index.ts"), "export const x = 1;").unwrap();
2912
2913            let config = make_config(dir.path().to_path_buf(), false);
2914            let files = discover_files(&config);
2915            let names = file_names(&files, dir.path());
2916
2917            assert_eq!(names, vec!["src/index.ts".to_string()]);
2918        }
2919
2920        /// A monorepo keeps its generated output inside each package, so the
2921        /// built-in exclusion has to survive the workspace prefix.
2922        #[test]
2923        fn default_ignore_patterns_exclude_nested_build() {
2924            let dir = tempfile::tempdir().expect("create temp dir");
2925
2926            let build = dir.path().join("build");
2927            std::fs::create_dir_all(&build).unwrap();
2928            std::fs::write(build.join("output.js"), "// built").unwrap();
2929
2930            let package_build = dir.path().join("projects").join("app").join("build");
2931            std::fs::create_dir_all(&package_build).unwrap();
2932            std::fs::write(package_build.join("index.js"), "// built").unwrap();
2933
2934            let src = dir.path().join("src");
2935            std::fs::create_dir_all(&src).unwrap();
2936            std::fs::write(src.join("index.ts"), "export const x = 1;").unwrap();
2937
2938            let config = make_config(dir.path().to_path_buf(), false);
2939            let files = discover_files(&config);
2940            let names = file_names(&files, dir.path());
2941
2942            assert_eq!(names, vec!["src/index.ts".to_string()]);
2943        }
2944
2945        /// `build` only counts as output when it is a whole path segment.
2946        #[test]
2947        fn default_ignore_patterns_keep_paths_that_merely_contain_build() {
2948            let dir = tempfile::tempdir().expect("create temp dir");
2949
2950            let src = dir.path().join("src");
2951            std::fs::create_dir_all(src.join("rebuild")).unwrap();
2952            std::fs::create_dir_all(src.join("buildings")).unwrap();
2953            std::fs::write(src.join("build.ts"), "export const a = 1;").unwrap();
2954            std::fs::write(src.join("rebuild").join("helper.ts"), "export const b = 1;").unwrap();
2955            std::fs::write(src.join("buildings").join("a.ts"), "export const c = 1;").unwrap();
2956
2957            let config = make_config(dir.path().to_path_buf(), false);
2958            let files = discover_files(&config);
2959            let mut names = file_names(&files, dir.path());
2960            names.sort();
2961
2962            assert_eq!(
2963                names,
2964                vec![
2965                    "src/build.ts".to_string(),
2966                    "src/buildings/a.ts".to_string(),
2967                    "src/rebuild/helper.ts".to_string(),
2968                ]
2969            );
2970        }
2971
2972        /// Resolve a config then override the per-file size limit in bytes.
2973        fn make_config_with_max_file_size(
2974            root: PathBuf,
2975            max_file_size_bytes: Option<u64>,
2976        ) -> ResolvedConfig {
2977            let mut config = make_config(root, false);
2978            config.max_file_size_bytes = max_file_size_bytes;
2979            config
2980        }
2981
2982        #[test]
2983        fn skips_files_over_max_file_size() {
2984            let dir = tempfile::tempdir().expect("create temp dir");
2985            let src = dir.path().join("src");
2986            std::fs::create_dir_all(&src).unwrap();
2987            std::fs::write(src.join("small.ts"), "export const a = 1;").unwrap();
2988            std::fs::write(src.join("huge.ts"), "x".repeat(5_000)).unwrap();
2989
2990            let config = make_config_with_max_file_size(dir.path().to_path_buf(), Some(1_000));
2991            let files = discover_files(&config);
2992            let names = file_names(&files, dir.path());
2993
2994            assert!(names.contains(&"src/small.ts".to_string()));
2995            assert!(
2996                !names.contains(&"src/huge.ts".to_string()),
2997                "a file over the size limit must not be discovered"
2998            );
2999        }
3000
3001        #[test]
3002        fn declaration_files_exempt_from_size_skip() {
3003            let dir = tempfile::tempdir().expect("create temp dir");
3004            let src = dir.path().join("src");
3005            std::fs::create_dir_all(&src).unwrap();
3006            std::fs::write(src.join("auto-imports.d.ts"), "x".repeat(5_000)).unwrap();
3007            std::fs::write(src.join("huge.ts"), "x".repeat(5_000)).unwrap();
3008
3009            let config = make_config_with_max_file_size(dir.path().to_path_buf(), Some(1_000));
3010            let files = discover_files(&config);
3011            let names = file_names(&files, dir.path());
3012
3013            assert!(
3014                names.contains(&"src/auto-imports.d.ts".to_string()),
3015                "a large .d.ts is exempt from the skip (reachability root for global types)"
3016            );
3017            assert!(!names.contains(&"src/huge.ts".to_string()));
3018        }
3019
3020        #[test]
3021        fn unlimited_size_keeps_large_files() {
3022            let dir = tempfile::tempdir().expect("create temp dir");
3023            let src = dir.path().join("src");
3024            std::fs::create_dir_all(&src).unwrap();
3025            std::fs::write(src.join("huge.ts"), "x".repeat(5_000)).unwrap();
3026
3027            let config = make_config_with_max_file_size(dir.path().to_path_buf(), None);
3028            let files = discover_files(&config);
3029            let names = file_names(&files, dir.path());
3030
3031            assert!(
3032                names.contains(&"src/huge.ts".to_string()),
3033                "no limit keeps every file"
3034            );
3035        }
3036
3037        #[test]
3038        fn skipped_file_recorded_in_workspace_diagnostics() {
3039            let dir = tempfile::tempdir().expect("create temp dir");
3040            let src = dir.path().join("src");
3041            std::fs::create_dir_all(&src).unwrap();
3042            std::fs::write(src.join("huge.ts"), "x".repeat(5_000)).unwrap();
3043
3044            let config = make_config_with_max_file_size(dir.path().to_path_buf(), Some(1_000));
3045            let _ = discover_files(&config);
3046
3047            let diagnostics = fallow_config::workspace_diagnostics_for(dir.path());
3048            let skipped: Vec<_> = diagnostics
3049                .iter()
3050                .filter(|d| {
3051                    matches!(
3052                        d.kind,
3053                        fallow_config::WorkspaceDiagnosticKind::SkippedLargeFile { .. }
3054                    )
3055                })
3056                .collect();
3057            assert_eq!(
3058                skipped.len(),
3059                1,
3060                "the skipped file is recorded in workspace diagnostics for JSON output"
3061            );
3062            assert!(skipped[0].path.ends_with("src/huge.ts"));
3063            assert!(
3064                matches!(
3065                    skipped[0].kind,
3066                    fallow_config::WorkspaceDiagnosticKind::SkippedLargeFile { size_bytes }
3067                        if size_bytes == 5_000
3068                ),
3069                "the recorded diagnostic carries the on-disk byte size"
3070            );
3071        }
3072
3073        /// The skipped-source-dotdir entries the last walk on `root` recorded.
3074        fn dotdir_diagnostics(root: &Path) -> Vec<fallow_config::WorkspaceDiagnostic> {
3075            fallow_config::workspace_diagnostics_for(root)
3076                .into_iter()
3077                .filter(|d| {
3078                    matches!(
3079                        d.kind,
3080                        fallow_config::WorkspaceDiagnosticKind::SkippedSourceDotdir
3081                    )
3082                })
3083                .collect()
3084        }
3085
3086        fn write_at(root: &Path, relative: &str, contents: &str) {
3087            let path = root.join(relative);
3088            std::fs::create_dir_all(path.parent().expect("has a parent")).unwrap();
3089            std::fs::write(path, contents).unwrap();
3090        }
3091
3092        #[test]
3093        fn skipped_source_dotdir_recorded_in_workspace_diagnostics() {
3094            let dir = tempfile::tempdir().expect("create temp dir");
3095            write_at(
3096                dir.path(),
3097                ".claude/hooks/probe.mjs",
3098                "export const a = 1;\n",
3099            );
3100            write_at(dir.path(), "src/app.ts", "export const b = 2;\n");
3101
3102            let config = make_config(dir.path().to_path_buf(), false);
3103            let files = discover_files(&config);
3104            let names = file_names(&files, dir.path());
3105
3106            let reported = dotdir_diagnostics(dir.path());
3107            assert_eq!(reported.len(), 1, "one skipped dotdir holds source files");
3108            assert!(reported[0].path.ends_with(".claude"));
3109            assert_eq!(reported[0].kind.id(), "skipped-source-dotdir");
3110            assert!(
3111                reported[0].message.contains("--root"),
3112                "message names the real remedy: {}",
3113                reported[0].message
3114            );
3115            assert!(
3116                names.contains(&"src/app.ts".to_string()),
3117                "traversal is unchanged for ordinary directories"
3118            );
3119            assert!(
3120                !names.contains(&".claude/hooks/probe.mjs".to_string()),
3121                "the diagnostic reports the skip, it does not change traversal"
3122            );
3123        }
3124
3125        #[test]
3126        fn allowlisted_dotdir_is_not_reported() {
3127            let dir = tempfile::tempdir().expect("create temp dir");
3128            write_at(dir.path(), ".storybook/main.ts", "export const a = 1;\n");
3129
3130            let config = make_config(dir.path().to_path_buf(), false);
3131            let files = discover_files(&config);
3132            let names = file_names(&files, dir.path());
3133
3134            assert!(dotdir_diagnostics(dir.path()).is_empty());
3135            assert!(
3136                names.contains(&".storybook/main.ts".to_string()),
3137                "an allowlisted dotdir is still traversed"
3138            );
3139        }
3140
3141        #[test]
3142        fn denylisted_dotdir_is_not_reported() {
3143            let dir = tempfile::tempdir().expect("create temp dir");
3144            write_at(dir.path(), ".idea/workspace.ts", "export const a = 1;\n");
3145            write_at(dir.path(), ".husky/hook.js", "export const b = 2;\n");
3146            write_at(dir.path(), ".next/page.js", "export const c = 3;\n");
3147            write_at(dir.path(), ".pnpm/x.js", "export const d = 4;\n");
3148
3149            let config = make_config(dir.path().to_path_buf(), false);
3150            let _ = discover_files(&config);
3151
3152            assert!(
3153                dotdir_diagnostics(dir.path()).is_empty(),
3154                "build caches, VCS and package-manager state never advise"
3155            );
3156        }
3157
3158        #[test]
3159        fn scoped_dotdir_is_traversed_and_not_reported() {
3160            let dir = tempfile::tempdir().expect("create temp dir");
3161            write_at(
3162                dir.path(),
3163                ".claude/hooks/probe.mjs",
3164                "export const a = 1;\n",
3165            );
3166
3167            let config = make_config(dir.path().to_path_buf(), false);
3168            let scopes = [HiddenDirScope::new(
3169                dir.path().to_path_buf(),
3170                vec![".claude".to_owned()],
3171            )];
3172            let files = discover_files_with_additional_hidden_dirs(&config, &scopes);
3173            let names = file_names(&files, dir.path());
3174
3175            assert!(
3176                dotdir_diagnostics(dir.path()).is_empty(),
3177                "a plugin- or script-contributed scope is admitted, so nothing was skipped"
3178            );
3179            assert!(names.contains(&".claude/hooks/probe.mjs".to_string()));
3180        }
3181
3182        #[test]
3183        fn ignore_patterns_silence_the_skipped_source_dotdir() {
3184            let dir = tempfile::tempdir().expect("create temp dir");
3185            write_at(
3186                dir.path(),
3187                ".claude/hooks/probe.mjs",
3188                "export const a = 1;\n",
3189            );
3190
3191            let config =
3192                make_config_with_ignores(dir.path().to_path_buf(), vec![".claude/**".to_owned()]);
3193            let _ = discover_files(&config);
3194
3195            assert!(
3196                dotdir_diagnostics(dir.path()).is_empty(),
3197                "the documented silencing route works"
3198            );
3199        }
3200
3201        #[test]
3202        fn dotdir_without_source_files_is_not_reported() {
3203            let dir = tempfile::tempdir().expect("create temp dir");
3204            write_at(dir.path(), ".claude/settings.json", "{}\n");
3205            write_at(dir.path(), ".claude/README.md", "# notes\n");
3206
3207            let config = make_config(dir.path().to_path_buf(), false);
3208            let _ = discover_files(&config);
3209
3210            assert!(dotdir_diagnostics(dir.path()).is_empty());
3211        }
3212
3213        #[test]
3214        fn dotdir_source_at_scan_depth_limit_is_reported() {
3215            let dir = tempfile::tempdir().expect("create temp dir");
3216            write_at(dir.path(), ".claude/a/b/deep.ts", "export const a = 1;\n");
3217
3218            let config = make_config(dir.path().to_path_buf(), false);
3219            let _ = discover_files(&config);
3220
3221            assert_eq!(dotdir_diagnostics(dir.path()).len(), 1);
3222        }
3223
3224        #[test]
3225        fn dotdir_source_below_scan_depth_limit_is_not_reported() {
3226            let dir = tempfile::tempdir().expect("create temp dir");
3227            write_at(
3228                dir.path(),
3229                ".claude/a/b/c/deeper.ts",
3230                "export const a = 1;\n",
3231            );
3232
3233            let config = make_config(dir.path().to_path_buf(), false);
3234            let _ = discover_files(&config);
3235
3236            assert!(
3237                dotdir_diagnostics(dir.path()).is_empty(),
3238                "the depth cap is real, so widening it stays a deliberate act"
3239            );
3240        }
3241
3242        /// Mark `root` as a git worktree so the `ignore` crate applies the
3243        /// gitignore files below it. `require_git` is on by default, and it
3244        /// tests for the presence of `.git`, not for a valid object store.
3245        fn mark_as_git_repo(root: &Path) {
3246            std::fs::create_dir_all(root.join(".git")).expect("create .git marker");
3247        }
3248
3249        #[test]
3250        fn gitignored_dotdir_contents_are_not_reported() {
3251            // The directory FORM (`.tooling/`) prunes the dotdir upstream of the
3252            // predicate, so these are the forms that reach it with every file
3253            // inside already ignored.
3254            for pattern in [".tooling/**", ".tooling/*", "**/.tooling/**", "*.ts"] {
3255                let dir = tempfile::tempdir().expect("create temp dir");
3256                mark_as_git_repo(dir.path());
3257                write_at(dir.path(), ".gitignore", &format!("{pattern}\n"));
3258                write_at(dir.path(), ".tooling/mod.ts", "export const a = 1;\n");
3259
3260                let config = make_config(dir.path().to_path_buf(), false);
3261                let _ = discover_files(&config);
3262
3263                assert!(
3264                    dotdir_diagnostics(dir.path()).is_empty(),
3265                    "gitignore pattern '{pattern}' excludes the contents, so neither \
3266                     advertised remedy would find anything there"
3267                );
3268            }
3269        }
3270
3271        #[test]
3272        fn self_ignoring_dotdir_is_not_reported() {
3273            let dir = tempfile::tempdir().expect("create temp dir");
3274            mark_as_git_repo(dir.path());
3275            write_at(dir.path(), ".toolcache/.gitignore", "*\n");
3276            write_at(dir.path(), ".toolcache/mod.ts", "export const a = 1;\n");
3277
3278            let config = make_config(dir.path().to_path_buf(), false);
3279            let _ = discover_files(&config);
3280
3281            assert!(
3282                dotdir_diagnostics(dir.path()).is_empty(),
3283                "a cache directory that ignores itself has excluded its own contents"
3284            );
3285        }
3286
3287        #[test]
3288        fn ungitignored_dotdir_in_a_git_repo_is_still_reported() {
3289            let dir = tempfile::tempdir().expect("create temp dir");
3290            mark_as_git_repo(dir.path());
3291            write_at(dir.path(), ".gitignore", "dist/\n");
3292            write_at(dir.path(), ".tooling/mod.ts", "export const a = 1;\n");
3293
3294            let config = make_config(dir.path().to_path_buf(), false);
3295            let _ = discover_files(&config);
3296
3297            assert_eq!(
3298                dotdir_diagnostics(dir.path()).len(),
3299                1,
3300                "the gitignore check must not swallow the case the diagnostic exists for"
3301            );
3302        }
3303
3304        #[test]
3305        fn production_run_does_not_report_a_test_only_dotdir() {
3306            let dir = tempfile::tempdir().expect("create temp dir");
3307            write_at(dir.path(), ".qa/thing.test.ts", "export const a = 1;\n");
3308            write_at(dir.path(), ".qa/thing.stories.tsx", "export const b = 2;\n");
3309
3310            let config = make_config(dir.path().to_path_buf(), true);
3311            let _ = discover_files(&config);
3312
3313            assert!(
3314                dotdir_diagnostics(dir.path()).is_empty(),
3315                "a --production run would analyze none of those files, so the \
3316                 --root remedy would return nothing"
3317            );
3318        }
3319
3320        #[test]
3321        fn production_run_still_reports_a_dotdir_with_production_source() {
3322            let dir = tempfile::tempdir().expect("create temp dir");
3323            write_at(dir.path(), ".qa/thing.test.ts", "export const a = 1;\n");
3324            write_at(dir.path(), ".qa/helper.ts", "export const b = 2;\n");
3325
3326            let config = make_config(dir.path().to_path_buf(), true);
3327            let _ = discover_files(&config);
3328
3329            assert_eq!(dotdir_diagnostics(dir.path()).len(), 1);
3330        }
3331
3332        #[test]
3333        fn dotdir_with_only_generated_markup_is_not_reported() {
3334            let dir = tempfile::tempdir().expect("create temp dir");
3335            write_at(dir.path(), ".lighthouseci/lhr-1.html", "<html></html>\n");
3336            write_at(dir.path(), ".styles/theme.css", ":root { color: red; }\n");
3337            write_at(dir.path(), ".gql/schema.graphql", "type Query { a: Int }\n");
3338
3339            let config = make_config(dir.path().to_path_buf(), false);
3340            let _ = discover_files(&config);
3341
3342            assert!(
3343                dotdir_diagnostics(dir.path()).is_empty(),
3344                "the message claims imports and exports are lost, and these have none"
3345            );
3346        }
3347
3348        #[test]
3349        fn generated_tool_and_foreign_vcs_dotdirs_are_not_reported() {
3350            let dir = tempfile::tempdir().expect("create temp dir");
3351            write_at(dir.path(), ".astro/types.d.ts", "export {};\n");
3352            write_at(dir.path(), ".wxt/types/imports.d.ts", "export {};\n");
3353            write_at(dir.path(), ".yalc/pkg/index.js", "export const a = 1;\n");
3354            write_at(dir.path(), ".jj/repo/config.js", "export const b = 2;\n");
3355            write_at(dir.path(), ".svn/pristine/y.js", "export const c = 3;\n");
3356
3357            let config = make_config(dir.path().to_path_buf(), false);
3358            let _ = discover_files(&config);
3359
3360            assert!(
3361                dotdir_diagnostics(dir.path()).is_empty(),
3362                "generated output and foreign VCS metadata are not first-party source"
3363            );
3364        }
3365
3366        #[test]
3367        fn denylisted_dotdirs_do_not_consume_the_candidate_ceiling() {
3368            let dir = tempfile::tempdir().expect("create temp dir");
3369            // Sorted before the real candidate, and more of them than the
3370            // ceiling, so a cap applied before the name checks would hide it.
3371            for index in 0..(DOTDIR_SCAN_MAX_CANDIDATES + 8) {
3372                write_at(
3373                    dir.path(),
3374                    &format!("packages/pkg{index:03}/.turbo/blob.js"),
3375                    "export const a = 1;\n",
3376                );
3377            }
3378            write_at(dir.path(), "zz/.tooling/mod.ts", "export const b = 2;\n");
3379
3380            let config = make_config(dir.path().to_path_buf(), false);
3381            let _ = discover_files(&config);
3382
3383            let reported = dotdir_diagnostics(dir.path());
3384            assert_eq!(reported.len(), 1, "{reported:?}");
3385            assert!(reported[0].path.ends_with(".tooling"));
3386        }
3387
3388        #[test]
3389        fn one_pathological_dotdir_cannot_starve_the_rest() {
3390            let dir = tempfile::tempdir().expect("create temp dir");
3391            // Wide and shallow, no source: exhausts this candidate's own budget.
3392            for index in 0..(DOTDIR_SCAN_MAX_ENTRIES * 2) {
3393                write_at(dir.path(), &format!(".aaa-noise/f{index}.bin"), "x");
3394            }
3395            write_at(dir.path(), ".zzz-real/mod.ts", "export const a = 1;\n");
3396
3397            let config = make_config(dir.path().to_path_buf(), false);
3398            let _ = discover_files(&config);
3399
3400            let reported = dotdir_diagnostics(dir.path());
3401            assert_eq!(reported.len(), 1, "{reported:?}");
3402            assert!(reported[0].path.ends_with(".zzz-real"));
3403        }
3404
3405        #[test]
3406        fn repeat_walks_do_not_stack_skipped_source_dotdirs() {
3407            let dir = tempfile::tempdir().expect("create temp dir");
3408            write_at(
3409                dir.path(),
3410                ".claude/hooks/probe.mjs",
3411                "export const a = 1;\n",
3412            );
3413
3414            let config = make_config(dir.path().to_path_buf(), false);
3415            let _ = discover_files(&config);
3416            let _ = discover_files(&config);
3417
3418            assert_eq!(
3419                dotdir_diagnostics(dir.path()).len(),
3420                1,
3421                "each walk replaces its own root's source-discovery set"
3422            );
3423        }
3424
3425        #[test]
3426        fn skips_large_one_line_js_as_minified_generated_output() {
3427            let dir = tempfile::tempdir().expect("create temp dir");
3428            let src = dir.path().join("src");
3429            std::fs::create_dir_all(&src).unwrap();
3430            let asset = src.join("index-abc123.js");
3431            std::fs::write(&asset, "x".repeat(MINIFIED_FILE_SKIP_BYTES as usize + 1)).unwrap();
3432
3433            let config = make_config(dir.path().to_path_buf(), false);
3434            let files = discover_files(&config);
3435            let names = file_names(&files, dir.path());
3436
3437            assert!(
3438                !names.contains(&"src/index-abc123.js".to_string()),
3439                "large one-line JS assets should be skipped before parsing"
3440            );
3441
3442            let diagnostics = fallow_config::workspace_diagnostics_for(dir.path());
3443            assert!(
3444                diagnostics.iter().any(|diag| {
3445                    diag.path.ends_with("src/index-abc123.js")
3446                        && matches!(
3447                            diag.kind,
3448                            fallow_config::WorkspaceDiagnosticKind::SkippedMinifiedFile { .. }
3449                        )
3450                }),
3451                "the skipped minified asset is recorded for JSON output: {diagnostics:?}"
3452            );
3453        }
3454
3455        #[test]
3456        fn unlimited_size_keeps_large_one_line_js() {
3457            let dir = tempfile::tempdir().expect("create temp dir");
3458            let src = dir.path().join("src");
3459            std::fs::create_dir_all(&src).unwrap();
3460            let asset = src.join("index-abc123.js");
3461            std::fs::write(&asset, "x".repeat(MINIFIED_FILE_SKIP_BYTES as usize + 1)).unwrap();
3462
3463            let config = make_config_with_max_file_size(dir.path().to_path_buf(), None);
3464            let files = discover_files(&config);
3465            let names = file_names(&files, dir.path());
3466
3467            assert!(
3468                names.contains(&"src/index-abc123.js".to_string()),
3469                "--max-file-size 0 should opt out of generated JS skipping"
3470            );
3471        }
3472
3473        #[test]
3474        fn keeps_large_multiline_js() {
3475            let dir = tempfile::tempdir().expect("create temp dir");
3476            let src = dir.path().join("src");
3477            std::fs::create_dir_all(&src).unwrap();
3478            let asset = src.join("handwritten.js");
3479            let mut content = String::new();
3480            while content.len() <= MINIFIED_FILE_SKIP_BYTES as usize + 1 {
3481                content.push_str("export const value = 1;\n");
3482            }
3483            std::fs::write(&asset, content).unwrap();
3484
3485            let config = make_config(dir.path().to_path_buf(), false);
3486            let files = discover_files(&config);
3487            let names = file_names(&files, dir.path());
3488
3489            assert!(
3490                names.contains(&"src/handwritten.js".to_string()),
3491                "large multiline JS should not be treated as a generated minified asset"
3492            );
3493        }
3494    }
3495}