Skip to main content

fallow_core/discover/
walk.rs

1use std::ffi::OsStr;
2use std::path::{Path, PathBuf};
3use std::sync::{Mutex, OnceLock};
4
5use fallow_config::{ResolvedConfig, WorkspaceDiagnostic, WorkspaceDiagnosticKind};
6use fallow_types::discover::{DiscoveredFile, FileId};
7use ignore::WalkBuilder;
8use rustc_hash::FxHashSet;
9
10use super::ALLOWED_HIDDEN_DIRS;
11
12/// Process-wide dedupe of the size-skip / largest-files stderr notes, keyed by a
13/// content-derived string, so combined-mode (`fallow` runs check + dupes +
14/// health, each of which can trigger a source walk) emits each note at most once
15/// per distinct content. Mirrors the workspace-diagnostics `should_emit`
16/// pattern (issue #1086).
17fn should_emit_note_once(key: String) -> bool {
18    static EMITTED: OnceLock<Mutex<FxHashSet<String>>> = OnceLock::new();
19    EMITTED
20        .get_or_init(|| Mutex::new(FxHashSet::default()))
21        .lock()
22        .map_or(true, |mut set| set.insert(key))
23}
24
25/// A discovered file path paired with its on-disk size in bytes, as collected
26/// by the parallel walker before [`DiscoveredFile`] ids are assigned.
27type SizedFile = (PathBuf, u64);
28
29/// Number of example file paths named in the aggregated skipped-large-file and
30/// largest-files stderr notes before the tail collapses to "and N more". Keeps
31/// the notes to one bounded line on a monorepo that skips many files.
32const NOTE_EXAMPLE_CAP: usize = 5;
33
34/// Discovered-file-count threshold above which the pre-parse largest-files note
35/// fires, so an out-of-memory hang at the parse stage has a visible suspect
36/// list (issue #1086).
37const LARGE_SET_THRESHOLD: usize = 20_000;
38
39/// Single-file byte threshold above which the pre-parse largest-files note
40/// fires even on a small project. Set just under the default 5 MB skip so the
41/// note fires for kept files that are approaching the skip limit (the genuine
42/// out-of-memory suspects), not for ordinary large-but-benign files.
43const LARGE_FILE_NOTE_BYTES: u64 = 4 * 1024 * 1024;
44
45/// Minimum size for a file to appear in the largest-files note. Filters out the
46/// `0.0 MB` entries that would otherwise pad the list once it fires, keeping the
47/// named files to plausible memory contributors.
48const NOTE_FILE_FLOOR_BYTES: u64 = 256 * 1024;
49
50/// Minimum size for content-shape based minified-bundle skipping. Smaller
51/// one-line files can be hand-written utilities, while multi-MB one-line JS is
52/// generated output in practice.
53const MINIFIED_FILE_SKIP_BYTES: u64 = 1024 * 1024;
54
55/// Number of bytes inspected when deciding whether a large JS file is minified.
56const MINIFIED_SAMPLE_BYTES: usize = 256 * 1024;
57
58/// A single line this long in a multi-MB JS file is treated as generated
59/// minified output. This avoids parsing assets that can expand to huge ASTs.
60const MINIFIED_LONG_LINE_BYTES: usize = 128 * 1024;
61
62/// Whether a path is a TypeScript declaration file (`.d.ts`/`.d.mts`/`.d.cts`).
63/// Declaration files are exempt from the per-file size skip because they are
64/// reachability roots for global types: skipping a large `auto-imports.d.ts`
65/// would false-flag the files whose types it provides.
66fn is_declaration_file(path: &Path) -> bool {
67    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
68    name.ends_with(".d.ts") || name.ends_with(".d.mts") || name.ends_with(".d.cts")
69}
70
71fn is_plain_js_file(path: &Path) -> bool {
72    matches!(
73        path.extension().and_then(|ext| ext.to_str()),
74        Some("js" | "mjs" | "cjs")
75    )
76}
77
78fn has_minified_line_shape(path: &Path) -> bool {
79    use std::io::Read;
80
81    let Ok(mut file) = std::fs::File::open(path) else {
82        return false;
83    };
84    let mut sample = vec![0; MINIFIED_SAMPLE_BYTES];
85    let Ok(len) = file.read(&mut sample) else {
86        return false;
87    };
88    sample.truncate(len);
89    if sample.is_empty() {
90        return false;
91    }
92
93    let mut current_line = 0usize;
94    for byte in sample {
95        if byte == b'\n' || byte == b'\r' {
96            current_line = 0;
97            continue;
98        }
99        current_line += 1;
100        if current_line >= MINIFIED_LONG_LINE_BYTES {
101            return true;
102        }
103    }
104    false
105}
106
107fn is_probably_minified_generated_js(path: &Path, size_bytes: u64) -> bool {
108    size_bytes >= MINIFIED_FILE_SKIP_BYTES
109        && is_plain_js_file(path)
110        && !is_declaration_file(path)
111        && has_minified_line_shape(path)
112}
113
114/// Render a byte count as a megabyte figure with one decimal place.
115fn format_size_mb(bytes: u64) -> String {
116    #[expect(
117        clippy::cast_precision_loss,
118        reason = "display-only size figure; precision loss past 2^53 bytes is irrelevant"
119    )]
120    let mb = bytes as f64 / (1024.0 * 1024.0);
121    format!("{mb:.1} MB")
122}
123
124/// Join up to [`NOTE_EXAMPLE_CAP`] `path (size)` examples (already ordered) into
125/// one comma-separated string, collapsing the tail to "and N more".
126fn summarize_examples(root: &Path, examples: &[SizedFile]) -> String {
127    let shown: Vec<String> = examples
128        .iter()
129        .take(NOTE_EXAMPLE_CAP)
130        .map(|(path, size)| {
131            let display = path
132                .strip_prefix(root)
133                .unwrap_or(path)
134                .display()
135                .to_string()
136                .replace('\\', "/");
137            format!("{display} ({})", format_size_mb(*size))
138        })
139        .collect();
140    let remaining = examples.len().saturating_sub(NOTE_EXAMPLE_CAP);
141    if remaining > 0 {
142        format!("{}, and {remaining} more", shown.join(", "))
143    } else {
144        shown.join(", ")
145    }
146}
147
148/// Split discovered `(path, size)` pairs into the kept set and the set skipped
149/// for exceeding `max_file_size_bytes`. Declaration files are never skipped.
150fn partition_by_size(
151    raw: Vec<SizedFile>,
152    max_file_size_bytes: Option<u64>,
153) -> (Vec<SizedFile>, Vec<SizedFile>) {
154    let Some(limit) = max_file_size_bytes else {
155        return (raw, Vec::new());
156    };
157    raw.into_iter()
158        .partition(|(path, size)| *size <= limit || is_declaration_file(path))
159}
160
161/// Split discovered `(path, size)` pairs into files kept for parsing and files
162/// skipped because they look like generated minified JavaScript.
163fn partition_minified_generated_js(
164    raw: Vec<SizedFile>,
165    max_file_size_bytes: Option<u64>,
166) -> (Vec<SizedFile>, Vec<SizedFile>) {
167    if max_file_size_bytes.is_none() {
168        return (raw, Vec::new());
169    }
170    raw.into_iter()
171        .partition(|(path, size)| !is_probably_minified_generated_js(path, *size))
172}
173
174/// Record the skipped files in the workspace-diagnostics registry (so they
175/// surface in `workspace_diagnostics[]` JSON) and emit one aggregated
176/// `tracing::warn!` so a human running `fallow` sees what was dropped. Mirrors
177/// the JSON-plus-gated-warn pattern used for undeclared workspaces.
178fn report_skipped_large_files(config: &ResolvedConfig, skipped: &[SizedFile]) {
179    if skipped.is_empty() {
180        return;
181    }
182    let diagnostics: Vec<WorkspaceDiagnostic> = skipped
183        .iter()
184        .map(|(path, size_bytes)| {
185            WorkspaceDiagnostic::new(
186                &config.root,
187                path.clone(),
188                WorkspaceDiagnosticKind::SkippedLargeFile {
189                    size_bytes: *size_bytes,
190                },
191            )
192        })
193        .collect();
194    fallow_config::append_workspace_diagnostics(&config.root, diagnostics);
195
196    let mut sorted: Vec<SizedFile> = skipped.to_vec();
197    sorted.sort_unstable_by_key(|f| std::cmp::Reverse(f.1));
198    let count = skipped.len();
199    if !config.quiet
200        && should_emit_note_once(format!(
201            "skip::{}::{count}::{}",
202            config.root.display(),
203            sorted.first().map_or(0, |f| f.1)
204        ))
205    {
206        let examples = summarize_examples(&config.root, &sorted);
207        let noun = if count == 1 { "file" } else { "files" };
208        tracing::warn!(
209            "fallow: skipped {count} {noun} over the max file size limit ({examples}). \
210             Raise the limit with --max-file-size <MB> (or FALLOW_MAX_FILE_SIZE), or add them to ignorePatterns."
211        );
212    }
213}
214
215/// Record generated minified JS files skipped before parsing.
216fn report_skipped_minified_files(config: &ResolvedConfig, skipped: &[SizedFile]) {
217    if skipped.is_empty() {
218        return;
219    }
220    let diagnostics: Vec<WorkspaceDiagnostic> = skipped
221        .iter()
222        .map(|(path, size_bytes)| {
223            WorkspaceDiagnostic::new(
224                &config.root,
225                path.clone(),
226                WorkspaceDiagnosticKind::SkippedMinifiedFile {
227                    size_bytes: *size_bytes,
228                },
229            )
230        })
231        .collect();
232    fallow_config::append_workspace_diagnostics(&config.root, diagnostics);
233
234    let mut sorted: Vec<SizedFile> = skipped.to_vec();
235    sorted.sort_unstable_by_key(|f| std::cmp::Reverse(f.1));
236    let count = skipped.len();
237    if !config.quiet
238        && should_emit_note_once(format!(
239            "minified::{}::{count}::{}",
240            config.root.display(),
241            sorted.first().map_or(0, |f| f.1)
242        ))
243    {
244        let examples = summarize_examples(&config.root, &sorted);
245        let noun = if count == 1 { "file" } else { "files" };
246        let pronoun = if count == 1 { "it" } else { "them" };
247        tracing::warn!(
248            "fallow: skipped {count} minified generated JS {noun} ({examples}). \
249             Add {pronoun} to ignorePatterns, rename {pronoun} with a .min.js suffix, or use --max-file-size 0 to analyze {pronoun}."
250        );
251    }
252}
253
254/// Build the pre-parse largest-files note, or `None` when the discovered set is
255/// neither unusually large nor contains an unusually large file. Pure so the
256/// pluralization, floor filtering, and count-only fallback are unit-testable
257/// without a tracing subscriber. See issue #1086.
258fn build_largest_files_note(root: &Path, files: &[DiscoveredFile]) -> Option<String> {
259    if files.is_empty() {
260        return None;
261    }
262    let largest = files.iter().map(|f| f.size_bytes).max().unwrap_or(0);
263    if files.len() <= LARGE_SET_THRESHOLD && largest < LARGE_FILE_NOTE_BYTES {
264        return None;
265    }
266    let count = files.len();
267    let noun = if count == 1 { "file" } else { "files" };
268    let mut by_size: Vec<SizedFile> = files
269        .iter()
270        .filter(|f| f.size_bytes >= NOTE_FILE_FLOOR_BYTES)
271        .map(|f| (f.path.clone(), f.size_bytes))
272        .collect();
273    by_size.sort_unstable_by_key(|f| std::cmp::Reverse(f.1));
274    if by_size.is_empty() {
275        // Large file SET with no individually large file: report the count only,
276        // omitting a "largest:" list that would otherwise be all sub-floor noise.
277        return Some(format!(
278            "fallow: discovered {count} {noun}. If analysis stalls or runs out of memory, \
279             exclude large generated files via ignorePatterns or --max-file-size."
280        ));
281    }
282    let examples = summarize_examples(root, &by_size);
283    Some(format!(
284        "fallow: discovered {count} {noun}; largest: {examples}. If analysis stalls or runs out of memory, \
285         exclude large generated files via ignorePatterns or --max-file-size."
286    ))
287}
288
289/// Emit a pre-parse note listing the largest kept files when the discovered set
290/// is unusually large or contains an unusually large file, so an out-of-memory
291/// hang at the parse stage is diagnosable (issue #1086). Visible before the
292/// expensive parse begins, so it survives a subsequent crash.
293fn note_largest_files(config: &ResolvedConfig, files: &[DiscoveredFile]) {
294    if config.quiet {
295        return;
296    }
297    if let Some(message) = build_largest_files_note(&config.root, files)
298        && should_emit_note_once(format!("note::{}::{}", config.root.display(), files.len()))
299    {
300        tracing::warn!("{message}");
301    }
302}
303
304/// Package-scoped hidden directories that source discovery should traverse.
305#[derive(Debug, Clone, PartialEq, Eq)]
306pub struct HiddenDirScope {
307    root: PathBuf,
308    dirs: Vec<String>,
309}
310
311impl HiddenDirScope {
312    pub fn new(root: PathBuf, dirs: Vec<String>) -> Self {
313        Self { root, dirs }
314    }
315
316    #[must_use]
317    pub fn root(&self) -> &Path {
318        &self.root
319    }
320
321    #[must_use]
322    pub fn dirs(&self) -> &[String] {
323        &self.dirs
324    }
325
326    fn allows(&self, path: &Path, name: &OsStr) -> bool {
327        path.starts_with(&self.root) && self.dirs.iter().any(|dir| OsStr::new(dir) == name)
328    }
329}
330
331/// Per-thread file collector for the parallel walker.
332///
333/// Source files (by extension) flow to `shared`; when `config_shared` is set,
334/// non-source files admitted by the config-candidate type group flow to it
335/// instead. The two channels are disjoint and the source channel is byte-for-byte
336/// identical to the config-capture-disabled walk.
337struct FileVisitor<'a> {
338    root: &'a Path,
339    ignore_patterns: &'a globset::GlobSet,
340    production_excludes: &'a Option<globset::GlobSet>,
341    shared: &'a Mutex<Vec<(std::path::PathBuf, u64)>>,
342    config_shared: Option<&'a Mutex<Vec<std::path::PathBuf>>>,
343    local: Vec<(std::path::PathBuf, u64)>,
344    config_local: Vec<std::path::PathBuf>,
345}
346
347impl ignore::ParallelVisitor for FileVisitor<'_> {
348    fn visit(&mut self, result: Result<ignore::DirEntry, ignore::Error>) -> ignore::WalkState {
349        let Ok(entry) = result else {
350            return ignore::WalkState::Continue;
351        };
352        if entry.file_type().is_some_and(|ft| ft.is_dir()) {
353            return ignore::WalkState::Continue;
354        }
355        let relative = entry
356            .path()
357            .strip_prefix(self.root)
358            .unwrap_or_else(|_| entry.path());
359        if self.ignore_patterns.is_match(relative) {
360            return ignore::WalkState::Continue;
361        }
362        if self
363            .production_excludes
364            .as_ref()
365            .is_some_and(|excludes| excludes.is_match(relative))
366        {
367            return ignore::WalkState::Continue;
368        }
369        if has_source_extension(entry.path()) {
370            let size_bytes = entry.metadata().map_or(0, |m| m.len());
371            self.local.push((entry.into_path(), size_bytes));
372        } else if self.config_shared.is_some() {
373            // A non-source file admitted by the config-candidate type group. No
374            // size metadata is needed; these are pattern-matched, never parsed.
375            self.config_local.push(entry.into_path());
376        }
377        ignore::WalkState::Continue
378    }
379}
380
381impl Drop for FileVisitor<'_> {
382    #[expect(
383        clippy::expect_used,
384        reason = "poisoned walk collector lock means worker state is unrecoverable"
385    )]
386    fn drop(&mut self) {
387        if !self.local.is_empty() {
388            self.shared
389                .lock()
390                .expect("walk collector lock poisoned")
391                .append(&mut self.local);
392        }
393        if let Some(config_shared) = self.config_shared
394            && !self.config_local.is_empty()
395        {
396            config_shared
397                .lock()
398                .expect("walk config collector lock poisoned")
399                .append(&mut self.config_local);
400        }
401    }
402}
403
404/// Builder that creates per-thread `FileVisitor` instances for the parallel walker.
405struct FileVisitorBuilder<'a> {
406    root: &'a Path,
407    ignore_patterns: &'a globset::GlobSet,
408    production_excludes: &'a Option<globset::GlobSet>,
409    shared: &'a Mutex<Vec<(std::path::PathBuf, u64)>>,
410    config_shared: Option<&'a Mutex<Vec<std::path::PathBuf>>>,
411}
412
413impl<'s> ignore::ParallelVisitorBuilder<'s> for FileVisitorBuilder<'s> {
414    fn build(&mut self) -> Box<dyn ignore::ParallelVisitor + 's> {
415        Box::new(FileVisitor {
416            root: self.root,
417            ignore_patterns: self.ignore_patterns,
418            production_excludes: self.production_excludes,
419            shared: self.shared,
420            config_shared: self.config_shared,
421            local: Vec::new(),
422            config_local: Vec::new(),
423        })
424    }
425}
426
427pub const SOURCE_EXTENSIONS: &[&str] = &[
428    "ts", "tsx", "mts", "cts", "gts", "js", "jsx", "mjs", "cjs", "gjs", "vue", "svelte", "astro",
429    "mdx", "css", "scss", "sass", "less", "html", "graphql", "gql",
430];
431
432/// Glob patterns for test/dev/story files excluded in production mode.
433pub const PRODUCTION_EXCLUDE_PATTERNS: &[&str] = &[
434    "**/*.test.*",
435    "**/*.spec.*",
436    "**/*.e2e.*",
437    "**/*.e2e-spec.*",
438    "**/*.bench.*",
439    "**/*.fixture.*",
440    "**/*.stories.*",
441    "**/*.story.*",
442    "**/__tests__/**",
443    "**/__mocks__/**",
444    "**/__snapshots__/**",
445    "**/__fixtures__/**",
446    "**/test/**",
447    "**/tests/**",
448    "*.config.*",
449    "**/.*.js",
450    "**/.*.ts",
451    "**/.*.mjs",
452    "**/.*.cjs",
453];
454
455/// Check if a hidden directory name is on the allowlist.
456pub fn is_allowed_hidden_dir(name: &OsStr) -> bool {
457    ALLOWED_HIDDEN_DIRS.iter().any(|&d| OsStr::new(d) == name)
458}
459
460fn is_allowed_scoped_hidden_dir(
461    name: &OsStr,
462    path: &Path,
463    additional_hidden_dir_scopes: &[HiddenDirScope],
464) -> bool {
465    additional_hidden_dir_scopes
466        .iter()
467        .any(|scope| scope.allows(path, name))
468}
469
470/// Check if a hidden directory entry should be allowed through the filter.
471///
472/// Returns `true` if the entry is not hidden or is on the allowlist.
473/// Hidden files (not directories) are always allowed through since the type
474/// filter handles them.
475fn is_allowed_hidden(entry: &ignore::DirEntry) -> bool {
476    is_allowed_hidden_with_scopes(entry, &[])
477}
478
479fn is_allowed_hidden_with_scopes(
480    entry: &ignore::DirEntry,
481    additional_hidden_dir_scopes: &[HiddenDirScope],
482) -> bool {
483    let name = entry.file_name();
484    let name_str = name.to_string_lossy();
485
486    if !name_str.starts_with('.') {
487        return true;
488    }
489
490    if entry.file_type().is_some_and(|ft| !ft.is_dir()) {
491        return true;
492    }
493
494    is_allowed_hidden_dir(name)
495        || is_allowed_scoped_hidden_dir(name, entry.path(), additional_hidden_dir_scopes)
496}
497
498/// Discover all source files in the project.
499///
500/// # Panics
501///
502/// Panics if the file type glob or progress template is invalid (compile-time constants).
503pub fn discover_files(config: &ResolvedConfig) -> Vec<DiscoveredFile> {
504    discover_files_with_additional_hidden_dirs(config, &[])
505}
506
507/// The set of config-file basenames (last path component of every built-in
508/// plugin `config_patterns()` entry, brace forms preserved) that the walk should
509/// additionally admit so non-source configs (`tsconfig.json`, `bunfig.toml`,
510/// `.eslintrc.json`, ...) can be captured in one traversal instead of being
511/// re-discovered by a filesystem re-walk in `discover_config_files`.
512///
513/// Derived live from the built-in plugin list, so it can never drift behind a
514/// new plugin's config patterns. Source-extension config basenames
515/// (`vite.config.{ts,js}`) are admitted too, but the walk visitor routes them
516/// back to the source channel by extension, so the config channel only ever
517/// collects genuinely non-source files.
518fn config_candidate_basename_globs() -> &'static [String] {
519    static GLOBS: OnceLock<Vec<String>> = OnceLock::new();
520    GLOBS.get_or_init(|| {
521        let mut set: FxHashSet<String> = FxHashSet::default();
522        for plugin in crate::plugins::registry::builtin::create_builtin_plugins() {
523            for pattern in plugin.config_patterns() {
524                let basename = pattern.rsplit('/').next().unwrap_or(pattern);
525                set.insert(basename.to_string());
526            }
527        }
528        let mut globs: Vec<String> = set.into_iter().collect();
529        globs.sort_unstable();
530        globs
531    })
532}
533
534/// True when `path`'s extension is one of the known source extensions, i.e. the
535/// file belongs in the source channel rather than the config-candidate channel.
536fn has_source_extension(path: &Path) -> bool {
537    path.extension()
538        .and_then(OsStr::to_str)
539        .is_some_and(|ext| SOURCE_EXTENSIONS.contains(&ext))
540}
541
542/// Build the file-type filter. Always selects known source extensions; when
543/// `capture_config` is set, also selects config-candidate basenames so the
544/// walker yields them for the second collection channel.
545#[expect(
546    clippy::expect_used,
547    reason = "source file globs are hard-coded compile-time constants"
548)]
549fn build_walk_types(capture_config: bool) -> ignore::types::Types {
550    let mut types_builder = ignore::types::TypesBuilder::new();
551    for ext in SOURCE_EXTENSIONS {
552        types_builder
553            .add("source", &format!("*.{ext}"))
554            .expect("valid glob");
555    }
556    types_builder.select("source");
557    if capture_config {
558        for glob in config_candidate_basename_globs() {
559            // Ignore individually-invalid plugin patterns rather than panicking;
560            // a malformed pattern simply fails to admit its config file (the
561            // pre-existing filesystem fallback still covers production mode).
562            let _ = types_builder.add("config", glob);
563        }
564        types_builder.select("config");
565    }
566    types_builder.build().expect("valid types")
567}
568
569/// Construct the parallel walker, applying the appropriate hidden-dir filter.
570/// When `capture_config` is set the walk also yields config-candidate files for
571/// the secondary collection channel.
572fn build_source_walk_builder(
573    config: &ResolvedConfig,
574    additional_hidden_dir_scopes: &[HiddenDirScope],
575    capture_config: bool,
576) -> WalkBuilder {
577    let mut walk_builder = WalkBuilder::new(&config.root);
578    walk_builder
579        .hidden(false)
580        .git_ignore(true)
581        .git_global(true)
582        .git_exclude(true)
583        .types(build_walk_types(capture_config))
584        .threads(config.threads);
585    if additional_hidden_dir_scopes.is_empty() {
586        walk_builder.filter_entry(is_allowed_hidden);
587    } else {
588        let scopes = additional_hidden_dir_scopes.to_vec();
589        walk_builder.filter_entry(move |entry| is_allowed_hidden_with_scopes(entry, &scopes));
590    }
591    walk_builder
592}
593
594/// Compile the production-mode exclude glob set, or `None` outside production mode.
595fn build_production_excludes(config: &ResolvedConfig) -> Option<globset::GlobSet> {
596    if !config.production {
597        return None;
598    }
599    let mut builder = globset::GlobSetBuilder::new();
600    for pattern in PRODUCTION_EXCLUDE_PATTERNS {
601        if let Ok(glob) = globset::GlobBuilder::new(pattern)
602            .literal_separator(true)
603            .build()
604        {
605            builder.add(glob);
606        }
607    }
608    builder.build().ok()
609}
610
611/// Discover all source files in the project, with package-scoped hidden dirs.
612///
613/// # Panics
614///
615/// Panics if the file type glob or progress template is invalid (compile-time constants).
616pub fn discover_files_with_additional_hidden_dirs(
617    config: &ResolvedConfig,
618    additional_hidden_dir_scopes: &[HiddenDirScope],
619) -> Vec<DiscoveredFile> {
620    discover_files_and_config_candidates(config, additional_hidden_dir_scopes).0
621}
622
623/// Discover source files AND, in one traversal, the non-source config-candidate
624/// files (`tsconfig.json`, `bunfig.toml`, `.eslintrc.json`, ...) used by
625/// `discover_config_files` to resolve plugin config patterns in-memory instead of
626/// re-walking the filesystem.
627///
628/// The returned `Vec<DiscoveredFile>` is byte-for-byte identical to the
629/// config-capture-disabled walk: config candidates are routed to the second
630/// return value by extension and never enter the source channel. Config capture
631/// is skipped in production mode (where the walk applies `PRODUCTION_EXCLUDE_PATTERNS`
632/// and `discover_config_files` keeps its filesystem path), so the second vector is
633/// empty there.
634///
635/// # Panics
636///
637/// Panics if the file type glob or progress template is invalid (compile-time constants).
638#[expect(
639    clippy::cast_possible_truncation,
640    reason = "file count is bounded by project size, well under u32::MAX"
641)]
642#[expect(clippy::expect_used, reason = "the collector lock must remain usable")]
643pub fn discover_files_and_config_candidates(
644    config: &ResolvedConfig,
645    additional_hidden_dir_scopes: &[HiddenDirScope],
646) -> (Vec<DiscoveredFile>, Vec<PathBuf>) {
647    let _span = tracing::info_span!("discover_files").entered();
648
649    let capture_config = !config.production;
650    let walk_builder =
651        build_source_walk_builder(config, additional_hidden_dir_scopes, capture_config);
652    let production_excludes = build_production_excludes(config);
653
654    let collected: Mutex<Vec<(std::path::PathBuf, u64)>> = Mutex::new(Vec::new());
655    let config_collected: Mutex<Vec<std::path::PathBuf>> = Mutex::new(Vec::new());
656    let mut visitor_builder = FileVisitorBuilder {
657        root: &config.root,
658        ignore_patterns: &config.ignore_patterns,
659        production_excludes: &production_excludes,
660        shared: &collected,
661        config_shared: capture_config.then_some(&config_collected),
662    };
663    walk_builder.build_parallel().visit(&mut visitor_builder);
664
665    let mut raw = collected
666        .into_inner()
667        .expect("walk collector lock poisoned");
668    // ADR-004 (path-sorted FileIds): the parallel walk visits files in
669    // nondeterministic order, so we sort by absolute path BEFORE the
670    // `.enumerate()` FileId assignment below. This is the stable-cross-run
671    // identity invariant the persisted graph cache depends on: an identical
672    // file set yields identical FileIds, so a cache hit (same paths +
673    // fingerprints) can trust graph data persisted by FileId. Do not replace
674    // this with insertion-order assignment.
675    raw.sort_unstable_by(|a, b| a.0.cmp(&b.0));
676
677    let mut config_candidates = config_collected
678        .into_inner()
679        .expect("walk config collector lock poisoned");
680    config_candidates.sort_unstable();
681
682    // Drop any source-discovery diagnostics from a previous pass (watch-mode
683    // rerun, combined-mode re-walk) BEFORE re-recording this walk's skips, so a
684    // file that is no longer skipped does not leave a stale entry (issue #1086).
685    fallow_config::clear_source_discovery_diagnostics(&config.root);
686    let (kept, skipped) = partition_by_size(raw, config.max_file_size_bytes);
687    report_skipped_large_files(config, &skipped);
688    let (kept, skipped_minified) =
689        partition_minified_generated_js(kept, config.max_file_size_bytes);
690    report_skipped_minified_files(config, &skipped_minified);
691
692    let files: Vec<DiscoveredFile> = kept
693        .into_iter()
694        .enumerate()
695        .map(|(idx, (path, size_bytes))| DiscoveredFile {
696            id: FileId(idx as u32),
697            path,
698            size_bytes,
699        })
700        .collect();
701
702    note_largest_files(config, &files);
703
704    (files, config_candidates)
705}
706
707#[cfg(test)]
708mod tests {
709    use std::ffi::OsStr;
710
711    use super::*;
712
713    /// Reproduce the FileId-assignment rule used by `walk_source_files`: sort by
714    /// absolute path, then assign `FileId(idx)` in that order.
715    fn assign_file_ids(mut raw: Vec<(std::path::PathBuf, u64)>) -> Vec<DiscoveredFile> {
716        raw.sort_unstable_by(|a, b| a.0.cmp(&b.0));
717        raw.into_iter()
718            .enumerate()
719            .map(|(idx, (path, size_bytes))| DiscoveredFile {
720                id: FileId(idx as u32),
721                path,
722                size_bytes,
723            })
724            .collect()
725    }
726
727    /// ADR-004: an identical file set must yield identical FileIds regardless of
728    /// the (nondeterministic, parallel) discovery order. The persisted graph
729    /// cache keys persisted graph data by FileId, so a cache HIT (same paths +
730    /// fingerprints) must reproduce the exact same FileId-to-path mapping the
731    /// graph was built against. This guards the cache's soundness prerequisite.
732    #[test]
733    fn file_id_assignment_is_deterministic_for_identical_file_set() {
734        let paths = [
735            "/project/src/z.ts",
736            "/project/src/a.ts",
737            "/project/src/components/Button.tsx",
738            "/project/src/components/Button.module.css",
739            "/project/index.ts",
740        ];
741
742        // Two independent walks that observe the same paths in DIFFERENT orders.
743        let walk_one: Vec<(std::path::PathBuf, u64)> = paths
744            .iter()
745            .map(|p| (std::path::PathBuf::from(p), 10))
746            .collect();
747        let mut walk_two = walk_one.clone();
748        walk_two.reverse();
749
750        let files_one = assign_file_ids(walk_one);
751        let files_two = assign_file_ids(walk_two);
752
753        // Identical (FileId -> path) mapping despite the different walk orders.
754        assert_eq!(files_one.len(), files_two.len());
755        for (a, b) in files_one.iter().zip(files_two.iter()) {
756            assert_eq!(a.id, b.id);
757            assert_eq!(a.path, b.path);
758        }
759
760        // The mapping is the path-sorted order, and each FileId equals its index
761        // (the density invariant `project.rs` asserts and the graph relies on).
762        for (idx, file) in files_one.iter().enumerate() {
763            assert_eq!(file.id, FileId(idx as u32));
764        }
765        assert_eq!(
766            files_one[0].path,
767            std::path::PathBuf::from("/project/index.ts")
768        );
769    }
770
771    #[test]
772    fn allowed_hidden_dirs() {
773        assert!(is_allowed_hidden_dir(OsStr::new(".storybook")));
774        assert!(is_allowed_hidden_dir(OsStr::new(".vitepress")));
775        assert!(is_allowed_hidden_dir(OsStr::new(".well-known")));
776        assert!(is_allowed_hidden_dir(OsStr::new(".changeset")));
777        assert!(is_allowed_hidden_dir(OsStr::new(".github")));
778    }
779
780    #[test]
781    fn disallowed_hidden_dirs() {
782        assert!(!is_allowed_hidden_dir(OsStr::new(".git")));
783        assert!(!is_allowed_hidden_dir(OsStr::new(".cache")));
784        assert!(!is_allowed_hidden_dir(OsStr::new(".vscode")));
785        assert!(!is_allowed_hidden_dir(OsStr::new(".fallow")));
786        assert!(!is_allowed_hidden_dir(OsStr::new(".next")));
787    }
788
789    #[test]
790    fn non_hidden_dirs_not_in_allowlist() {
791        assert!(!is_allowed_hidden_dir(OsStr::new("src")));
792        assert!(!is_allowed_hidden_dir(OsStr::new("node_modules")));
793    }
794
795    #[test]
796    fn source_extensions_include_typescript() {
797        assert!(SOURCE_EXTENSIONS.contains(&"ts"));
798        assert!(SOURCE_EXTENSIONS.contains(&"tsx"));
799        assert!(SOURCE_EXTENSIONS.contains(&"mts"));
800        assert!(SOURCE_EXTENSIONS.contains(&"cts"));
801        assert!(SOURCE_EXTENSIONS.contains(&"gts"));
802    }
803
804    #[test]
805    fn source_extensions_include_javascript() {
806        assert!(SOURCE_EXTENSIONS.contains(&"js"));
807        assert!(SOURCE_EXTENSIONS.contains(&"jsx"));
808        assert!(SOURCE_EXTENSIONS.contains(&"mjs"));
809        assert!(SOURCE_EXTENSIONS.contains(&"cjs"));
810        assert!(SOURCE_EXTENSIONS.contains(&"gjs"));
811    }
812
813    #[test]
814    fn source_extensions_include_sfc_formats() {
815        assert!(SOURCE_EXTENSIONS.contains(&"vue"));
816        assert!(SOURCE_EXTENSIONS.contains(&"svelte"));
817        assert!(SOURCE_EXTENSIONS.contains(&"astro"));
818    }
819
820    #[test]
821    fn source_extensions_include_styles() {
822        assert!(SOURCE_EXTENSIONS.contains(&"css"));
823        assert!(SOURCE_EXTENSIONS.contains(&"scss"));
824        assert!(SOURCE_EXTENSIONS.contains(&"sass"));
825        assert!(SOURCE_EXTENSIONS.contains(&"less"));
826    }
827
828    #[test]
829    fn source_extensions_exclude_non_source() {
830        assert!(!SOURCE_EXTENSIONS.contains(&"json"));
831        assert!(!SOURCE_EXTENSIONS.contains(&"yaml"));
832        assert!(!SOURCE_EXTENSIONS.contains(&"md"));
833        assert!(!SOURCE_EXTENSIONS.contains(&"png"));
834        assert!(!SOURCE_EXTENSIONS.contains(&"htm"));
835    }
836
837    #[test]
838    fn source_extensions_include_html() {
839        assert!(SOURCE_EXTENSIONS.contains(&"html"));
840    }
841
842    #[test]
843    fn source_extensions_include_graphql_documents() {
844        assert!(SOURCE_EXTENSIONS.contains(&"graphql"));
845        assert!(SOURCE_EXTENSIONS.contains(&"gql"));
846    }
847
848    fn build_production_glob_set() -> globset::GlobSet {
849        let mut builder = globset::GlobSetBuilder::new();
850        for pattern in PRODUCTION_EXCLUDE_PATTERNS {
851            builder.add(
852                globset::GlobBuilder::new(pattern)
853                    .literal_separator(true)
854                    .build()
855                    .expect("valid glob pattern"),
856            );
857        }
858        builder.build().expect("valid glob set")
859    }
860
861    #[test]
862    fn production_excludes_test_files() {
863        let set = build_production_glob_set();
864        assert!(set.is_match("src/Button.test.ts"));
865        assert!(set.is_match("src/utils.spec.tsx"));
866        assert!(set.is_match("src/__tests__/helper.ts"));
867        assert!(!set.is_match("src/Button.ts"));
868        assert!(!set.is_match("src/utils.tsx"));
869    }
870
871    #[test]
872    fn production_excludes_story_files() {
873        let set = build_production_glob_set();
874        assert!(set.is_match("src/Button.stories.tsx"));
875        assert!(set.is_match("src/Card.story.ts"));
876        assert!(!set.is_match("src/Button.tsx"));
877    }
878
879    #[test]
880    fn production_excludes_config_files_at_root_only() {
881        let set = build_production_glob_set();
882        assert!(set.is_match("vitest.config.ts"));
883        assert!(set.is_match("jest.config.js"));
884        assert!(!set.is_match("src/app/app.config.ts"));
885        assert!(!set.is_match("src/app/app.config.server.ts"));
886        assert!(!set.is_match("packages/foo/vitest.config.ts"));
887        assert!(!set.is_match("src/config.ts"));
888    }
889
890    #[test]
891    fn production_patterns_are_valid_globs() {
892        let _ = build_production_glob_set();
893    }
894
895    #[test]
896    fn disallowed_hidden_dirs_idea() {
897        assert!(!is_allowed_hidden_dir(OsStr::new(".idea")));
898    }
899
900    #[test]
901    fn source_extensions_include_mdx() {
902        assert!(SOURCE_EXTENSIONS.contains(&"mdx"));
903    }
904
905    #[test]
906    fn source_extensions_exclude_image_and_data_formats() {
907        assert!(!SOURCE_EXTENSIONS.contains(&"png"));
908        assert!(!SOURCE_EXTENSIONS.contains(&"jpg"));
909        assert!(!SOURCE_EXTENSIONS.contains(&"svg"));
910        assert!(!SOURCE_EXTENSIONS.contains(&"txt"));
911        assert!(!SOURCE_EXTENSIONS.contains(&"csv"));
912        assert!(!SOURCE_EXTENSIONS.contains(&"wasm"));
913    }
914
915    #[test]
916    fn is_declaration_file_matches_dts_variants() {
917        assert!(is_declaration_file(Path::new("env.d.ts")));
918        assert!(is_declaration_file(Path::new("src/auto-imports.d.ts")));
919        assert!(is_declaration_file(Path::new("mod.d.mts")));
920        assert!(is_declaration_file(Path::new("compat.d.cts")));
921        assert!(!is_declaration_file(Path::new("index.ts")));
922        assert!(!is_declaration_file(Path::new("component.tsx")));
923        assert!(!is_declaration_file(Path::new("notes.d.txt")));
924    }
925
926    #[test]
927    fn format_size_mb_renders_one_decimal() {
928        assert_eq!(format_size_mb(5 * 1024 * 1024), "5.0 MB");
929        assert_eq!(format_size_mb(1024 * 1024 + 512 * 1024), "1.5 MB");
930        assert_eq!(format_size_mb(0), "0.0 MB");
931    }
932
933    #[test]
934    fn partition_by_size_no_limit_keeps_all() {
935        let raw = vec![(PathBuf::from("a.ts"), 10), (PathBuf::from("b.ts"), 10_000)];
936        let (kept, skipped) = partition_by_size(raw, None);
937        assert_eq!(kept.len(), 2);
938        assert!(skipped.is_empty());
939    }
940
941    #[test]
942    fn partition_by_size_skips_strictly_over_limit() {
943        let raw = vec![
944            (PathBuf::from("under.ts"), 99),
945            (PathBuf::from("exact.ts"), 100),
946            (PathBuf::from("over.ts"), 101),
947        ];
948        let (kept, skipped) = partition_by_size(raw, Some(100));
949        let kept_has = |name: &str| kept.iter().any(|(p, _)| p.as_path() == Path::new(name));
950        assert!(kept_has("under.ts"));
951        assert!(
952            kept_has("exact.ts"),
953            "a file exactly at the limit is kept (skip is strictly-greater)"
954        );
955        assert_eq!(skipped.len(), 1);
956        assert_eq!(skipped[0].0, PathBuf::from("over.ts"));
957    }
958
959    #[test]
960    fn partition_by_size_exempts_declaration_files() {
961        let raw = vec![
962            (PathBuf::from("huge.ts"), 10_000),
963            (PathBuf::from("auto-imports.d.ts"), 10_000),
964        ];
965        let (kept, skipped) = partition_by_size(raw, Some(100));
966        assert!(
967            kept.iter()
968                .any(|(p, _)| p.as_path() == Path::new("auto-imports.d.ts")),
969            "declaration files are exempt from the size skip regardless of size"
970        );
971        assert_eq!(skipped.len(), 1);
972        assert_eq!(skipped[0].0, PathBuf::from("huge.ts"));
973    }
974
975    fn disco(path: &str, size_bytes: u64) -> DiscoveredFile {
976        DiscoveredFile {
977            id: FileId(0),
978            path: PathBuf::from(path),
979            size_bytes,
980        }
981    }
982
983    #[test]
984    fn largest_files_note_below_threshold_is_none() {
985        let files = [disco("a.ts", 100), disco("b.ts", 200)];
986        assert!(build_largest_files_note(Path::new("/p"), &files).is_none());
987    }
988
989    #[test]
990    fn largest_files_note_single_file_uses_singular() {
991        let files = [disco("big.ts", 5 * 1024 * 1024)];
992        let note = build_largest_files_note(Path::new("/p"), &files).expect("note fires");
993        assert!(
994            note.contains("discovered 1 file;"),
995            "singular noun on the single-big-file path (issue #1086 regression): {note}"
996        );
997        assert!(!note.contains("discovered 1 files"));
998        assert!(note.contains("big.ts (5.0 MB)"));
999    }
1000
1001    #[test]
1002    fn largest_files_note_filters_sub_floor_files() {
1003        let files = [disco("big.ts", 5 * 1024 * 1024), disco("tiny.ts", 10)];
1004        let note = build_largest_files_note(Path::new("/p"), &files).expect("note fires");
1005        assert!(note.contains("discovered 2 files;"));
1006        assert!(note.contains("big.ts (5.0 MB)"));
1007        assert!(
1008            !note.contains("tiny.ts"),
1009            "sub-floor files are not listed as `0.0 MB` chaff: {note}"
1010        );
1011    }
1012
1013    #[test]
1014    fn largest_files_note_large_set_no_big_file_omits_list() {
1015        let files: Vec<DiscoveredFile> = (0..=LARGE_SET_THRESHOLD)
1016            .map(|i| disco(&format!("f{i}.ts"), 100))
1017            .collect();
1018        let note = build_largest_files_note(Path::new("/p"), &files).expect("large set fires");
1019        assert!(note.contains(&format!("discovered {} files", LARGE_SET_THRESHOLD + 1)));
1020        assert!(
1021            !note.contains("largest:"),
1022            "no sub-floor `largest:` list when no file clears the floor: {note}"
1023        );
1024    }
1025
1026    mod discover_files_integration {
1027        use std::path::PathBuf;
1028
1029        use fallow_config::{
1030            DuplicatesConfig, FallowConfig, FlagsConfig, HealthConfig, OutputFormat, ResolveConfig,
1031            RulesConfig,
1032        };
1033
1034        use super::*;
1035
1036        /// Create a minimal ResolvedConfig pointing at the given root directory.
1037        fn make_config(root: PathBuf, production: bool) -> ResolvedConfig {
1038            FallowConfig {
1039                production: production.into(),
1040                ..Default::default()
1041            }
1042            .resolve(root, OutputFormat::Human, 1, true, true, None)
1043        }
1044
1045        /// Helper to collect discovered file names (relative to root) for assertions.
1046        /// Normalizes path separators to `/` for cross-platform test consistency.
1047        fn file_names(files: &[DiscoveredFile], root: &std::path::Path) -> Vec<String> {
1048            files
1049                .iter()
1050                .map(|f| {
1051                    f.path
1052                        .strip_prefix(root)
1053                        .unwrap_or(&f.path)
1054                        .to_string_lossy()
1055                        .replace('\\', "/")
1056                })
1057                .collect()
1058        }
1059
1060        #[test]
1061        fn discovers_source_files_with_valid_extensions() {
1062            let dir = tempfile::tempdir().expect("create temp dir");
1063            let src = dir.path().join("src");
1064            std::fs::create_dir_all(&src).unwrap();
1065
1066            std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
1067            std::fs::write(src.join("component.tsx"), "export default () => {};").unwrap();
1068            std::fs::write(src.join("utils.js"), "module.exports = {};").unwrap();
1069            std::fs::write(src.join("helper.jsx"), "export const h = 1;").unwrap();
1070            std::fs::write(src.join("config.mjs"), "export default {};").unwrap();
1071            std::fs::write(src.join("legacy.cjs"), "module.exports = {};").unwrap();
1072            std::fs::write(src.join("types.mts"), "export type T = string;").unwrap();
1073            std::fs::write(src.join("compat.cts"), "module.exports = {};").unwrap();
1074
1075            let config = make_config(dir.path().to_path_buf(), false);
1076            let files = discover_files(&config);
1077            let names = file_names(&files, dir.path());
1078
1079            assert!(names.contains(&"src/app.ts".to_string()));
1080            assert!(names.contains(&"src/component.tsx".to_string()));
1081            assert!(names.contains(&"src/utils.js".to_string()));
1082            assert!(names.contains(&"src/helper.jsx".to_string()));
1083            assert!(names.contains(&"src/config.mjs".to_string()));
1084            assert!(names.contains(&"src/legacy.cjs".to_string()));
1085            assert!(names.contains(&"src/types.mts".to_string()));
1086            assert!(names.contains(&"src/compat.cts".to_string()));
1087        }
1088
1089        #[test]
1090        fn excludes_non_source_extensions() {
1091            let dir = tempfile::tempdir().expect("create temp dir");
1092            let src = dir.path().join("src");
1093            std::fs::create_dir_all(&src).unwrap();
1094
1095            std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
1096
1097            std::fs::write(src.join("data.json"), "{}").unwrap();
1098            std::fs::write(src.join("readme.md"), "# Hello").unwrap();
1099            std::fs::write(src.join("notes.txt"), "notes").unwrap();
1100            std::fs::write(src.join("logo.png"), [0u8; 8]).unwrap();
1101
1102            let config = make_config(dir.path().to_path_buf(), false);
1103            let files = discover_files(&config);
1104            let names = file_names(&files, dir.path());
1105
1106            assert_eq!(names.len(), 1, "only the .ts file should be discovered");
1107            assert!(names.contains(&"src/app.ts".to_string()));
1108        }
1109
1110        #[test]
1111        fn excludes_disallowed_hidden_directories() {
1112            let dir = tempfile::tempdir().expect("create temp dir");
1113
1114            let git_dir = dir.path().join(".git");
1115            std::fs::create_dir_all(&git_dir).unwrap();
1116            std::fs::write(git_dir.join("hooks.ts"), "// git hook").unwrap();
1117
1118            let idea_dir = dir.path().join(".idea");
1119            std::fs::create_dir_all(&idea_dir).unwrap();
1120            std::fs::write(idea_dir.join("workspace.ts"), "// idea").unwrap();
1121
1122            let cache_dir = dir.path().join(".cache");
1123            std::fs::create_dir_all(&cache_dir).unwrap();
1124            std::fs::write(cache_dir.join("cached.js"), "// cached").unwrap();
1125
1126            let src = dir.path().join("src");
1127            std::fs::create_dir_all(&src).unwrap();
1128            std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
1129
1130            let config = make_config(dir.path().to_path_buf(), false);
1131            let files = discover_files(&config);
1132            let names = file_names(&files, dir.path());
1133
1134            assert_eq!(names.len(), 1, "only src/app.ts should be discovered");
1135            assert!(names.contains(&"src/app.ts".to_string()));
1136        }
1137
1138        #[test]
1139        fn includes_allowed_hidden_directories() {
1140            let dir = tempfile::tempdir().expect("create temp dir");
1141
1142            let storybook = dir.path().join(".storybook");
1143            std::fs::create_dir_all(&storybook).unwrap();
1144            std::fs::write(storybook.join("main.ts"), "export default {};").unwrap();
1145
1146            let github = dir.path().join(".github");
1147            std::fs::create_dir_all(&github).unwrap();
1148            std::fs::write(github.join("actions.js"), "module.exports = {};").unwrap();
1149
1150            let changeset = dir.path().join(".changeset");
1151            std::fs::create_dir_all(&changeset).unwrap();
1152            std::fs::write(changeset.join("config.js"), "module.exports = {};").unwrap();
1153
1154            let config = make_config(dir.path().to_path_buf(), false);
1155            let files = discover_files(&config);
1156            let names = file_names(&files, dir.path());
1157
1158            assert!(
1159                names.contains(&".storybook/main.ts".to_string()),
1160                "files in .storybook should be discovered"
1161            );
1162            assert!(
1163                names.contains(&".github/actions.js".to_string()),
1164                "files in .github should be discovered"
1165            );
1166            assert!(
1167                names.contains(&".changeset/config.js".to_string()),
1168                "files in .changeset should be discovered"
1169            );
1170        }
1171
1172        #[test]
1173        fn default_discovery_excludes_client_and_server_hidden_directories() {
1174            let dir = tempfile::tempdir().expect("create temp dir");
1175            let app = dir.path().join("app");
1176            std::fs::create_dir_all(app.join(".client")).unwrap();
1177            std::fs::create_dir_all(app.join(".server")).unwrap();
1178            std::fs::write(app.join(".client/analytics.ts"), "export const a = 1;").unwrap();
1179            std::fs::write(app.join(".server/db.ts"), "export const db = {};").unwrap();
1180            std::fs::write(app.join("root.tsx"), "export default function Root() {}").unwrap();
1181
1182            let config = make_config(dir.path().to_path_buf(), false);
1183            let files = discover_files(&config);
1184            let names = file_names(&files, dir.path());
1185
1186            assert!(names.contains(&"app/root.tsx".to_string()));
1187            assert!(!names.contains(&"app/.client/analytics.ts".to_string()));
1188            assert!(!names.contains(&"app/.server/db.ts".to_string()));
1189        }
1190
1191        #[test]
1192        fn scoped_hidden_dirs_include_client_and_server_under_package_root() {
1193            let dir = tempfile::tempdir().expect("create temp dir");
1194            let package = dir.path().join("packages/app");
1195            std::fs::create_dir_all(package.join("app/.client")).unwrap();
1196            std::fs::create_dir_all(package.join("app/.server")).unwrap();
1197            std::fs::write(
1198                package.join("app/.client/analytics.ts"),
1199                "export const track = () => {};",
1200            )
1201            .unwrap();
1202            std::fs::write(package.join("app/.server/db.ts"), "export const db = {};").unwrap();
1203
1204            let config = make_config(dir.path().to_path_buf(), false);
1205            let scopes = [HiddenDirScope::new(
1206                package,
1207                vec![".client".to_string(), ".server".to_string()],
1208            )];
1209            let files = discover_files_with_additional_hidden_dirs(&config, &scopes);
1210            let names = file_names(&files, dir.path());
1211
1212            assert!(names.contains(&"packages/app/app/.client/analytics.ts".to_string()));
1213            assert!(names.contains(&"packages/app/app/.server/db.ts".to_string()));
1214        }
1215
1216        #[test]
1217        fn scoped_hidden_dirs_do_not_include_unscoped_packages() {
1218            let dir = tempfile::tempdir().expect("create temp dir");
1219            let active = dir.path().join("packages/active");
1220            let inactive = dir.path().join("packages/inactive");
1221            std::fs::create_dir_all(active.join("app/.server")).unwrap();
1222            std::fs::create_dir_all(inactive.join("app/.server")).unwrap();
1223            std::fs::write(active.join("app/.server/db.ts"), "export const db = {};").unwrap();
1224            std::fs::write(inactive.join("app/.server/db.ts"), "export const db = {};").unwrap();
1225
1226            let config = make_config(dir.path().to_path_buf(), false);
1227            let scopes = [HiddenDirScope::new(active, vec![".server".to_string()])];
1228            let files = discover_files_with_additional_hidden_dirs(&config, &scopes);
1229            let names = file_names(&files, dir.path());
1230
1231            assert!(names.contains(&"packages/active/app/.server/db.ts".to_string()));
1232            assert!(!names.contains(&"packages/inactive/app/.server/db.ts".to_string()));
1233        }
1234
1235        #[test]
1236        fn excludes_root_build_directory() {
1237            let dir = tempfile::tempdir().expect("create temp dir");
1238
1239            std::fs::write(dir.path().join(".ignore"), "/build/\n").unwrap();
1240
1241            let build_dir = dir.path().join("build");
1242            std::fs::create_dir_all(&build_dir).unwrap();
1243            std::fs::write(build_dir.join("output.js"), "// build output").unwrap();
1244
1245            let src = dir.path().join("src");
1246            std::fs::create_dir_all(&src).unwrap();
1247            std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
1248
1249            let config = make_config(dir.path().to_path_buf(), false);
1250            let files = discover_files(&config);
1251            let names = file_names(&files, dir.path());
1252
1253            assert_eq!(names.len(), 1, "root build/ should be excluded via .ignore");
1254            assert!(names.contains(&"src/app.ts".to_string()));
1255        }
1256
1257        #[test]
1258        fn includes_nested_build_directory() {
1259            let dir = tempfile::tempdir().expect("create temp dir");
1260
1261            let nested_build = dir.path().join("src").join("build");
1262            std::fs::create_dir_all(&nested_build).unwrap();
1263            std::fs::write(nested_build.join("helper.ts"), "export const h = 1;").unwrap();
1264
1265            let config = make_config(dir.path().to_path_buf(), false);
1266            let files = discover_files(&config);
1267            let names = file_names(&files, dir.path());
1268
1269            assert!(
1270                names.contains(&"src/build/helper.ts".to_string()),
1271                "nested build/ directories should be included"
1272            );
1273        }
1274
1275        #[test]
1276        #[expect(
1277            clippy::cast_possible_truncation,
1278            reason = "test file counts are trivially small"
1279        )]
1280        fn file_ids_are_sequential_after_sorting() {
1281            let dir = tempfile::tempdir().expect("create temp dir");
1282            let src = dir.path().join("src");
1283            std::fs::create_dir_all(&src).unwrap();
1284
1285            std::fs::write(src.join("z_last.ts"), "export const z = 1;").unwrap();
1286            std::fs::write(src.join("a_first.ts"), "export const a = 1;").unwrap();
1287            std::fs::write(src.join("m_middle.ts"), "export const m = 1;").unwrap();
1288
1289            let config = make_config(dir.path().to_path_buf(), false);
1290            let files = discover_files(&config);
1291
1292            for (idx, file) in files.iter().enumerate() {
1293                assert_eq!(file.id, FileId(idx as u32), "FileId should be sequential");
1294            }
1295
1296            for pair in files.windows(2) {
1297                assert!(
1298                    pair[0].path < pair[1].path,
1299                    "files should be sorted by path"
1300                );
1301            }
1302        }
1303
1304        #[test]
1305        fn production_mode_excludes_test_files() {
1306            let dir = tempfile::tempdir().expect("create temp dir");
1307            let src = dir.path().join("src");
1308            std::fs::create_dir_all(&src).unwrap();
1309
1310            std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
1311            std::fs::write(src.join("app.test.ts"), "test('a', () => {});").unwrap();
1312            std::fs::write(src.join("app.spec.ts"), "describe('a', () => {});").unwrap();
1313            std::fs::write(src.join("app.stories.tsx"), "export default {};").unwrap();
1314
1315            let config = make_config(dir.path().to_path_buf(), true);
1316            let files = discover_files(&config);
1317            let names = file_names(&files, dir.path());
1318
1319            assert!(
1320                names.contains(&"src/app.ts".to_string()),
1321                "source files should be included in production mode"
1322            );
1323            assert!(
1324                !names.contains(&"src/app.test.ts".to_string()),
1325                "test files should be excluded in production mode"
1326            );
1327            assert!(
1328                !names.contains(&"src/app.spec.ts".to_string()),
1329                "spec files should be excluded in production mode"
1330            );
1331            assert!(
1332                !names.contains(&"src/app.stories.tsx".to_string()),
1333                "story files should be excluded in production mode"
1334            );
1335        }
1336
1337        #[test]
1338        fn non_production_mode_includes_test_files() {
1339            let dir = tempfile::tempdir().expect("create temp dir");
1340            let src = dir.path().join("src");
1341            std::fs::create_dir_all(&src).unwrap();
1342
1343            std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
1344            std::fs::write(src.join("app.test.ts"), "test('a', () => {});").unwrap();
1345
1346            let config = make_config(dir.path().to_path_buf(), false);
1347            let files = discover_files(&config);
1348            let names = file_names(&files, dir.path());
1349
1350            assert!(names.contains(&"src/app.ts".to_string()));
1351            assert!(
1352                names.contains(&"src/app.test.ts".to_string()),
1353                "test files should be included in non-production mode"
1354            );
1355        }
1356
1357        #[test]
1358        fn empty_directory_returns_no_files() {
1359            let dir = tempfile::tempdir().expect("create temp dir");
1360            let config = make_config(dir.path().to_path_buf(), false);
1361            let files = discover_files(&config);
1362            assert!(files.is_empty(), "empty project should discover no files");
1363        }
1364
1365        #[test]
1366        fn hidden_files_not_discovered_as_source() {
1367            let dir = tempfile::tempdir().expect("create temp dir");
1368
1369            std::fs::write(dir.path().join(".env"), "SECRET=abc").unwrap();
1370            std::fs::write(dir.path().join(".gitignore"), "node_modules").unwrap();
1371            std::fs::write(dir.path().join(".eslintrc.js"), "module.exports = {};").unwrap();
1372
1373            let src = dir.path().join("src");
1374            std::fs::create_dir_all(&src).unwrap();
1375            std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
1376
1377            let config = make_config(dir.path().to_path_buf(), false);
1378            let files = discover_files(&config);
1379            let names = file_names(&files, dir.path());
1380
1381            assert!(
1382                !names.contains(&".env".to_string()),
1383                ".env should not be discovered"
1384            );
1385            assert!(
1386                !names.contains(&".gitignore".to_string()),
1387                ".gitignore should not be discovered"
1388            );
1389        }
1390
1391        /// Create a config with custom ignore patterns.
1392        fn make_config_with_ignores(root: PathBuf, ignores: Vec<String>) -> ResolvedConfig {
1393            FallowConfig {
1394                schema: None,
1395                extends: vec![],
1396                entry: vec![],
1397                ignore_patterns: ignores,
1398                framework: vec![],
1399                workspaces: None,
1400                ignore_dependencies: vec![],
1401                ignore_unresolved_imports: vec![],
1402                ignore_exports: vec![],
1403                ignore_catalog_references: vec![],
1404                ignore_dependency_overrides: vec![],
1405                ignore_exports_used_in_file: fallow_config::IgnoreExportsUsedInFileConfig::default(
1406                ),
1407                used_class_members: vec![],
1408                ignore_decorators: vec![],
1409                unused_component_props: fallow_config::UnusedComponentPropsConfig::default(),
1410                duplicates: DuplicatesConfig::default(),
1411                health: HealthConfig::default(),
1412                rules: RulesConfig::default(),
1413                boundaries: fallow_config::BoundaryConfig::default(),
1414                production: false.into(),
1415                plugins: vec![],
1416                rule_packs: vec![],
1417                dynamically_loaded: vec![],
1418                overrides: vec![],
1419                regression: None,
1420                audit: fallow_config::AuditConfig::default(),
1421                codeowners: None,
1422                public_packages: vec![],
1423                flags: FlagsConfig::default(),
1424                security: fallow_config::SecurityConfig::default(),
1425                fix: fallow_config::FixConfig::default(),
1426                resolve: ResolveConfig::default(),
1427                sealed: false,
1428                include_entry_exports: false,
1429                auto_imports: false,
1430                cache: fallow_config::CacheConfig::default(),
1431            }
1432            .resolve(root, OutputFormat::Human, 1, true, true, None)
1433        }
1434
1435        #[test]
1436        fn custom_ignore_patterns_exclude_matching_files() {
1437            let dir = tempfile::tempdir().expect("create temp dir");
1438
1439            let generated = dir.path().join("src").join("api").join("generated");
1440            std::fs::create_dir_all(&generated).unwrap();
1441            std::fs::write(generated.join("client.ts"), "export const api = {};").unwrap();
1442
1443            let client = dir.path().join("src").join("api").join("client");
1444            std::fs::create_dir_all(&client).unwrap();
1445            std::fs::write(client.join("fetch.ts"), "export const fetch = {};").unwrap();
1446
1447            let src = dir.path().join("src");
1448            std::fs::write(src.join("index.ts"), "export const x = 1;").unwrap();
1449
1450            let config = make_config_with_ignores(
1451                dir.path().to_path_buf(),
1452                vec![
1453                    "src/api/generated/**".to_string(),
1454                    "src/api/client/**".to_string(),
1455                ],
1456            );
1457            let files = discover_files(&config);
1458            let names = file_names(&files, dir.path());
1459
1460            assert_eq!(names.len(), 1, "only non-ignored files: {names:?}");
1461            assert!(names.contains(&"src/index.ts".to_string()));
1462        }
1463
1464        #[test]
1465        fn leading_dot_ignore_patterns_exclude_matching_files() {
1466            let dir = tempfile::tempdir().expect("create temp dir");
1467
1468            let generated = dir.path().join("src").join("generated");
1469            std::fs::create_dir_all(&generated).unwrap();
1470            std::fs::write(generated.join("client.ts"), "export const api = {};").unwrap();
1471
1472            let src = dir.path().join("src");
1473            std::fs::write(src.join("index.ts"), "export const x = 1;").unwrap();
1474
1475            let config = make_config_with_ignores(
1476                dir.path().to_path_buf(),
1477                vec!["./src/generated/**".to_string()],
1478            );
1479            let files = discover_files(&config);
1480            let names = file_names(&files, dir.path());
1481
1482            assert_eq!(names, vec!["src/index.ts"]);
1483        }
1484
1485        #[test]
1486        fn default_ignore_patterns_exclude_node_modules_and_dist() {
1487            let dir = tempfile::tempdir().expect("create temp dir");
1488
1489            let nm = dir.path().join("node_modules").join("lodash");
1490            std::fs::create_dir_all(&nm).unwrap();
1491            std::fs::write(nm.join("lodash.js"), "module.exports = {};").unwrap();
1492
1493            let dist = dir.path().join("dist");
1494            std::fs::create_dir_all(&dist).unwrap();
1495            std::fs::write(dist.join("bundle.js"), "// bundled").unwrap();
1496
1497            let src = dir.path().join("src");
1498            std::fs::create_dir_all(&src).unwrap();
1499            std::fs::write(src.join("index.ts"), "export const x = 1;").unwrap();
1500
1501            let config = make_config(dir.path().to_path_buf(), false);
1502            let files = discover_files(&config);
1503            let names = file_names(&files, dir.path());
1504
1505            assert_eq!(names.len(), 1);
1506            assert!(names.contains(&"src/index.ts".to_string()));
1507        }
1508
1509        #[test]
1510        fn default_ignore_patterns_exclude_root_build() {
1511            let dir = tempfile::tempdir().expect("create temp dir");
1512
1513            let build = dir.path().join("build");
1514            std::fs::create_dir_all(&build).unwrap();
1515            std::fs::write(build.join("output.js"), "// built").unwrap();
1516
1517            let nested_build = dir.path().join("src").join("build");
1518            std::fs::create_dir_all(&nested_build).unwrap();
1519            std::fs::write(nested_build.join("helper.ts"), "export const h = 1;").unwrap();
1520
1521            let src = dir.path().join("src");
1522            std::fs::write(src.join("index.ts"), "export const x = 1;").unwrap();
1523
1524            let config = make_config(dir.path().to_path_buf(), false);
1525            let files = discover_files(&config);
1526            let names = file_names(&files, dir.path());
1527
1528            assert_eq!(
1529                names.len(),
1530                2,
1531                "root build/ excluded, nested kept: {names:?}"
1532            );
1533            assert!(names.contains(&"src/index.ts".to_string()));
1534            assert!(names.contains(&"src/build/helper.ts".to_string()));
1535        }
1536
1537        /// Resolve a config then override the per-file size limit in bytes.
1538        fn make_config_with_max_file_size(
1539            root: PathBuf,
1540            max_file_size_bytes: Option<u64>,
1541        ) -> ResolvedConfig {
1542            let mut config = make_config(root, false);
1543            config.max_file_size_bytes = max_file_size_bytes;
1544            config
1545        }
1546
1547        #[test]
1548        fn skips_files_over_max_file_size() {
1549            let dir = tempfile::tempdir().expect("create temp dir");
1550            let src = dir.path().join("src");
1551            std::fs::create_dir_all(&src).unwrap();
1552            std::fs::write(src.join("small.ts"), "export const a = 1;").unwrap();
1553            std::fs::write(src.join("huge.ts"), "x".repeat(5_000)).unwrap();
1554
1555            let config = make_config_with_max_file_size(dir.path().to_path_buf(), Some(1_000));
1556            let files = discover_files(&config);
1557            let names = file_names(&files, dir.path());
1558
1559            assert!(names.contains(&"src/small.ts".to_string()));
1560            assert!(
1561                !names.contains(&"src/huge.ts".to_string()),
1562                "a file over the size limit must not be discovered"
1563            );
1564        }
1565
1566        #[test]
1567        fn declaration_files_exempt_from_size_skip() {
1568            let dir = tempfile::tempdir().expect("create temp dir");
1569            let src = dir.path().join("src");
1570            std::fs::create_dir_all(&src).unwrap();
1571            std::fs::write(src.join("auto-imports.d.ts"), "x".repeat(5_000)).unwrap();
1572            std::fs::write(src.join("huge.ts"), "x".repeat(5_000)).unwrap();
1573
1574            let config = make_config_with_max_file_size(dir.path().to_path_buf(), Some(1_000));
1575            let files = discover_files(&config);
1576            let names = file_names(&files, dir.path());
1577
1578            assert!(
1579                names.contains(&"src/auto-imports.d.ts".to_string()),
1580                "a large .d.ts is exempt from the skip (reachability root for global types)"
1581            );
1582            assert!(!names.contains(&"src/huge.ts".to_string()));
1583        }
1584
1585        #[test]
1586        fn unlimited_size_keeps_large_files() {
1587            let dir = tempfile::tempdir().expect("create temp dir");
1588            let src = dir.path().join("src");
1589            std::fs::create_dir_all(&src).unwrap();
1590            std::fs::write(src.join("huge.ts"), "x".repeat(5_000)).unwrap();
1591
1592            let config = make_config_with_max_file_size(dir.path().to_path_buf(), None);
1593            let files = discover_files(&config);
1594            let names = file_names(&files, dir.path());
1595
1596            assert!(
1597                names.contains(&"src/huge.ts".to_string()),
1598                "no limit keeps every file"
1599            );
1600        }
1601
1602        #[test]
1603        fn skipped_file_recorded_in_workspace_diagnostics() {
1604            let dir = tempfile::tempdir().expect("create temp dir");
1605            let src = dir.path().join("src");
1606            std::fs::create_dir_all(&src).unwrap();
1607            std::fs::write(src.join("huge.ts"), "x".repeat(5_000)).unwrap();
1608
1609            let config = make_config_with_max_file_size(dir.path().to_path_buf(), Some(1_000));
1610            let _ = discover_files(&config);
1611
1612            let diagnostics = fallow_config::workspace_diagnostics_for(dir.path());
1613            let skipped: Vec<_> = diagnostics
1614                .iter()
1615                .filter(|d| {
1616                    matches!(
1617                        d.kind,
1618                        fallow_config::WorkspaceDiagnosticKind::SkippedLargeFile { .. }
1619                    )
1620                })
1621                .collect();
1622            assert_eq!(
1623                skipped.len(),
1624                1,
1625                "the skipped file is recorded in workspace diagnostics for JSON output"
1626            );
1627            assert!(skipped[0].path.ends_with("src/huge.ts"));
1628            assert!(
1629                matches!(
1630                    skipped[0].kind,
1631                    fallow_config::WorkspaceDiagnosticKind::SkippedLargeFile { size_bytes }
1632                        if size_bytes == 5_000
1633                ),
1634                "the recorded diagnostic carries the on-disk byte size"
1635            );
1636        }
1637
1638        #[test]
1639        fn skips_large_one_line_js_as_minified_generated_output() {
1640            let dir = tempfile::tempdir().expect("create temp dir");
1641            let src = dir.path().join("src");
1642            std::fs::create_dir_all(&src).unwrap();
1643            let asset = src.join("index-abc123.js");
1644            std::fs::write(&asset, "x".repeat(MINIFIED_FILE_SKIP_BYTES as usize + 1)).unwrap();
1645
1646            let config = make_config(dir.path().to_path_buf(), false);
1647            let files = discover_files(&config);
1648            let names = file_names(&files, dir.path());
1649
1650            assert!(
1651                !names.contains(&"src/index-abc123.js".to_string()),
1652                "large one-line JS assets should be skipped before parsing"
1653            );
1654
1655            let diagnostics = fallow_config::workspace_diagnostics_for(dir.path());
1656            assert!(
1657                diagnostics.iter().any(|diag| {
1658                    diag.path.ends_with("src/index-abc123.js")
1659                        && matches!(
1660                            diag.kind,
1661                            fallow_config::WorkspaceDiagnosticKind::SkippedMinifiedFile { .. }
1662                        )
1663                }),
1664                "the skipped minified asset is recorded for JSON output: {diagnostics:?}"
1665            );
1666        }
1667
1668        #[test]
1669        fn unlimited_size_keeps_large_one_line_js() {
1670            let dir = tempfile::tempdir().expect("create temp dir");
1671            let src = dir.path().join("src");
1672            std::fs::create_dir_all(&src).unwrap();
1673            let asset = src.join("index-abc123.js");
1674            std::fs::write(&asset, "x".repeat(MINIFIED_FILE_SKIP_BYTES as usize + 1)).unwrap();
1675
1676            let config = make_config_with_max_file_size(dir.path().to_path_buf(), None);
1677            let files = discover_files(&config);
1678            let names = file_names(&files, dir.path());
1679
1680            assert!(
1681                names.contains(&"src/index-abc123.js".to_string()),
1682                "--max-file-size 0 should opt out of generated JS skipping"
1683            );
1684        }
1685
1686        #[test]
1687        fn keeps_large_multiline_js() {
1688            let dir = tempfile::tempdir().expect("create temp dir");
1689            let src = dir.path().join("src");
1690            std::fs::create_dir_all(&src).unwrap();
1691            let asset = src.join("handwritten.js");
1692            let mut content = String::new();
1693            while content.len() <= MINIFIED_FILE_SKIP_BYTES as usize + 1 {
1694                content.push_str("export const value = 1;\n");
1695            }
1696            std::fs::write(&asset, content).unwrap();
1697
1698            let config = make_config(dir.path().to_path_buf(), false);
1699            let files = discover_files(&config);
1700            let names = file_names(&files, dir.path());
1701
1702            assert!(
1703                names.contains(&"src/handwritten.js".to_string()),
1704                "large multiline JS should not be treated as a generated minified asset"
1705            );
1706        }
1707    }
1708}