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::legacy_glob::should_emit_note_once;
16use super::{ALLOWED_HIDDEN_DIRS, SCRIPT_SCOPE_DENYLIST};
17
18type SizedFile = (PathBuf, u64);
21
22type SkippedDotdirSink = Arc<Mutex<Vec<PathBuf>>>;
30
31#[derive(Default)]
48struct ExcludedByPattern {
49 file_count: u32,
51 scopes: FxHashMap<PathBuf, u32>,
53}
54
55impl ExcludedByPattern {
56 fn record(&mut self, scope: PathBuf) {
57 self.file_count = self.file_count.saturating_add(1);
58 *self.scopes.entry(scope).or_insert(0) += 1;
59 }
60
61 fn merge(&mut self, other: Self) {
62 self.file_count = self.file_count.saturating_add(other.file_count);
63 for (scope, count) in other.scopes {
64 *self.scopes.entry(scope).or_insert(0) += count;
65 }
66 }
67
68 fn directory_count(&self) -> u32 {
75 u32::try_from(self.scopes.len()).unwrap_or(u32::MAX)
76 }
77
78 fn anchor(&self) -> PathBuf {
82 self.scopes
83 .iter()
84 .max_by(|(left_path, left_count), (right_path, right_count)| {
85 left_count
86 .cmp(right_count)
87 .then_with(|| right_path.cmp(left_path))
88 })
89 .map(|(path, _)| path.clone())
90 .unwrap_or_default()
91 }
92}
93
94type ExclusionTally = FxHashMap<usize, ExcludedByPattern>;
97
98const UNREPORTED_DEFAULT_IGNORES: &[&str] = &["**/node_modules/**", "**/.git/**", VIZ_MAP];
108const VIZ_MAP: &str = "fallow-viz.html";
109
110fn exclusion_scope(relative: &Path, pattern: &str) -> PathBuf {
124 let parent = relative.parent().unwrap_or_else(|| Path::new(""));
125 let Some(literal) = glob_first_literal_segment(pattern) else {
126 return parent.to_path_buf();
127 };
128 let mut prefix = PathBuf::new();
129 let mut deepest = None;
130 for component in parent.components() {
131 prefix.push(component);
132 if component.as_os_str() == OsStr::new(literal) {
133 deepest = Some(prefix.clone());
134 }
135 }
136 deepest.unwrap_or_else(|| parent.to_path_buf())
137}
138
139const NOTE_EXAMPLE_CAP: usize = 5;
143
144const DOTDIR_SCAN_MAX_DEPTH: usize = 2;
149
150const DOTDIR_SCAN_MAX_ENTRIES: usize = 256;
156
157const DOTDIR_SCAN_TOTAL_ENTRIES: usize = 1024;
168
169const DOTDIR_SCAN_MAX_CANDIDATES: usize = 64;
176
177const DOTDIR_MODULE_EXTENSIONS: &[&str] = &[
184 "ts", "tsx", "mts", "cts", "gts", "js", "jsx", "mjs", "cjs", "gjs", "vue", "svelte", "astro",
185 "mdx",
186];
187
188const LARGE_SET_THRESHOLD: usize = 20_000;
192
193const LARGE_FILE_NOTE_BYTES: u64 = 4 * 1024 * 1024;
198
199const NOTE_FILE_FLOOR_BYTES: u64 = 256 * 1024;
203
204const MINIFIED_FILE_SKIP_BYTES: u64 = 1024 * 1024;
208
209const MINIFIED_SAMPLE_BYTES: usize = 256 * 1024;
211
212const MINIFIED_LONG_LINE_BYTES: usize = 128 * 1024;
215
216fn is_declaration_file(path: &Path) -> bool {
221 let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
222 name.ends_with(".d.ts") || name.ends_with(".d.mts") || name.ends_with(".d.cts")
223}
224
225fn is_plain_js_file(path: &Path) -> bool {
226 matches!(
227 path.extension().and_then(|ext| ext.to_str()),
228 Some("js" | "mjs" | "cjs")
229 )
230}
231
232fn has_minified_line_shape(path: &Path) -> bool {
233 use std::io::Read;
234
235 let Ok(mut file) = std::fs::File::open(path) else {
236 return false;
237 };
238 let mut sample = vec![0; MINIFIED_SAMPLE_BYTES];
239 let Ok(len) = file.read(&mut sample) else {
240 return false;
241 };
242 sample.truncate(len);
243 if sample.is_empty() {
244 return false;
245 }
246
247 let mut current_line = 0usize;
248 for byte in sample {
249 if byte == b'\n' || byte == b'\r' {
250 current_line = 0;
251 continue;
252 }
253 current_line += 1;
254 if current_line >= MINIFIED_LONG_LINE_BYTES {
255 return true;
256 }
257 }
258 false
259}
260
261fn is_probably_minified_generated_js(path: &Path, size_bytes: u64) -> bool {
262 size_bytes >= MINIFIED_FILE_SKIP_BYTES
263 && is_plain_js_file(path)
264 && !is_declaration_file(path)
265 && has_minified_line_shape(path)
266}
267
268fn format_size_mb(bytes: u64) -> String {
270 #[expect(
271 clippy::cast_precision_loss,
272 reason = "display-only size figure; precision loss past 2^53 bytes is irrelevant"
273 )]
274 let mb = bytes as f64 / (1024.0 * 1024.0);
275 format!("{mb:.1} MB")
276}
277
278fn summarize_examples(root: &Path, examples: &[SizedFile]) -> String {
281 let shown: Vec<String> = examples
282 .iter()
283 .take(NOTE_EXAMPLE_CAP)
284 .map(|(path, size)| {
285 let display = display_relative(root, path);
286 format!("{display} ({})", format_size_mb(*size))
287 })
288 .collect();
289 let remaining = examples.len().saturating_sub(NOTE_EXAMPLE_CAP);
290 if remaining > 0 {
291 format!("{}, and {remaining} more", shown.join(", "))
292 } else {
293 shown.join(", ")
294 }
295}
296
297fn partition_by_size(
300 raw: Vec<SizedFile>,
301 max_file_size_bytes: Option<u64>,
302) -> (Vec<SizedFile>, Vec<SizedFile>) {
303 let Some(limit) = max_file_size_bytes else {
304 return (raw, Vec::new());
305 };
306 raw.into_iter()
307 .partition(|(path, size)| *size <= limit || is_declaration_file(path))
308}
309
310fn partition_minified_generated_js(
313 raw: Vec<SizedFile>,
314 max_file_size_bytes: Option<u64>,
315) -> (Vec<SizedFile>, Vec<SizedFile>) {
316 if max_file_size_bytes.is_none() {
317 return (raw, Vec::new());
318 }
319 raw.into_iter()
320 .partition(|(path, size)| !is_probably_minified_generated_js(path, *size))
321}
322
323fn report_missing_node_modules(config: &ResolvedConfig) -> Vec<WorkspaceDiagnostic> {
326 let Some(diagnostic) = fallow_config::missing_node_modules_diagnostic(&config.root) else {
327 return Vec::new();
328 };
329 if !config.quiet
330 && should_emit_note_once(format!("node-modules-missing::{}", config.root.display()))
331 {
332 tracing::warn!("fallow: {}", diagnostic.message);
333 }
334 vec![diagnostic]
335}
336
337fn report_skipped_large_files(
339 config: &ResolvedConfig,
340 skipped: &[SizedFile],
341) -> Vec<WorkspaceDiagnostic> {
342 if skipped.is_empty() {
343 return Vec::new();
344 }
345 let diagnostics: Vec<WorkspaceDiagnostic> = skipped
346 .iter()
347 .map(|(path, size_bytes)| {
348 WorkspaceDiagnostic::new(
349 &config.root,
350 path.clone(),
351 WorkspaceDiagnosticKind::SkippedLargeFile {
352 size_bytes: *size_bytes,
353 },
354 )
355 })
356 .collect();
357
358 let mut sorted: Vec<SizedFile> = skipped.to_vec();
359 sorted.sort_unstable_by_key(|f| std::cmp::Reverse(f.1));
360 let count = skipped.len();
361 if !config.quiet
362 && should_emit_note_once(format!(
363 "skip::{}::{count}::{}",
364 config.root.display(),
365 sorted.first().map_or(0, |f| f.1)
366 ))
367 {
368 let examples = summarize_examples(&config.root, &sorted);
369 let noun = if count == 1 { "file" } else { "files" };
370 tracing::warn!(
371 "fallow: skipped {count} {noun} over the max file size limit ({examples}). \
372 Raise the limit with --max-file-size <MB> (or FALLOW_MAX_FILE_SIZE), or add them to ignorePatterns."
373 );
374 }
375 diagnostics
376}
377
378fn report_skipped_minified_files(
381 config: &ResolvedConfig,
382 skipped: &[SizedFile],
383) -> Vec<WorkspaceDiagnostic> {
384 if skipped.is_empty() {
385 return Vec::new();
386 }
387 let diagnostics: Vec<WorkspaceDiagnostic> = skipped
388 .iter()
389 .map(|(path, size_bytes)| {
390 WorkspaceDiagnostic::new(
391 &config.root,
392 path.clone(),
393 WorkspaceDiagnosticKind::SkippedMinifiedFile {
394 size_bytes: *size_bytes,
395 },
396 )
397 })
398 .collect();
399
400 let mut sorted: Vec<SizedFile> = skipped.to_vec();
401 sorted.sort_unstable_by_key(|f| std::cmp::Reverse(f.1));
402 let count = skipped.len();
403 if !config.quiet
404 && should_emit_note_once(format!(
405 "minified::{}::{count}::{}",
406 config.root.display(),
407 sorted.first().map_or(0, |f| f.1)
408 ))
409 {
410 let examples = summarize_examples(&config.root, &sorted);
411 let noun = if count == 1 { "file" } else { "files" };
412 let pronoun = if count == 1 { "it" } else { "them" };
413 tracing::warn!(
414 "fallow: skipped {count} minified generated JS {noun} ({examples}). \
415 Add {pronoun} to ignorePatterns, rename {pronoun} with a .min.js suffix, or use --max-file-size 0 to analyze {pronoun}."
416 );
417 }
418 diagnostics
419}
420
421fn summarize_paths(root: &Path, examples: &[&PathBuf]) -> String {
425 let shown: Vec<String> = examples
426 .iter()
427 .take(NOTE_EXAMPLE_CAP)
428 .map(|path| display_relative(root, path))
429 .collect();
430 let remaining = examples.len().saturating_sub(NOTE_EXAMPLE_CAP);
431 if remaining > 0 {
432 format!("{}, and {remaining} more", shown.join(", "))
433 } else {
434 shown.join(", ")
435 }
436}
437
438fn summarize_paths_open_ended(root: &Path, examples: &[&PathBuf]) -> String {
441 let shown: Vec<String> = examples
442 .iter()
443 .take(NOTE_EXAMPLE_CAP)
444 .map(|path| display_relative(root, path))
445 .collect();
446 if examples.len() > NOTE_EXAMPLE_CAP {
447 format!("{}, and more", shown.join(", "))
448 } else {
449 shown.join(", ")
450 }
451}
452
453fn is_excluded_from_analysis(
471 config: &ResolvedConfig,
472 production_excludes: Option<&globset::GlobSet>,
473 path: &Path,
474) -> bool {
475 let relative = path.strip_prefix(&config.root).unwrap_or(path);
476 config.ignore_patterns.is_match(relative)
477 || production_excludes.is_some_and(|excludes| excludes.is_match(relative))
478}
479
480fn has_module_extension(path: &Path) -> bool {
484 path.extension()
485 .and_then(OsStr::to_str)
486 .is_some_and(|ext| DOTDIR_MODULE_EXTENSIONS.contains(&ext))
487}
488
489fn scan_for_reportable_source(
512 config: &ResolvedConfig,
513 production_excludes: Option<&globset::GlobSet>,
514 dir: &Path,
515 budget: &mut usize,
516) -> bool {
517 let mut builder = fallow_config::source_walk_builder(dir);
518 builder
519 .follow_links(false)
520 .max_depth(Some(DOTDIR_SCAN_MAX_DEPTH + 1))
521 .threads(1);
522 builder.filter_entry(|entry| {
523 if entry.depth() == 0 || !entry.file_type().is_some_and(|ft| ft.is_dir()) {
524 return true;
525 }
526 entry
527 .file_name()
528 .to_str()
529 .is_none_or(|name| !SCRIPT_SCOPE_DENYLIST.contains(&name) && name != "node_modules")
530 });
531
532 let mut per_dotdir = DOTDIR_SCAN_MAX_ENTRIES;
533 for entry in builder.build() {
534 if per_dotdir == 0 || *budget == 0 {
535 return false;
536 }
537 per_dotdir -= 1;
538 *budget -= 1;
539 let Ok(entry) = entry else {
540 continue;
541 };
542 #[expect(
545 clippy::filetype_is_file,
546 reason = "regular files only is the point: !is_dir() would readmit fifos and sockets"
547 )]
548 let is_regular_file = entry
549 .file_type()
550 .is_some_and(|file_type| file_type.is_file());
551 if !is_regular_file {
552 continue;
553 }
554 if has_module_extension(entry.path())
555 && !is_excluded_from_analysis(config, production_excludes, entry.path())
556 {
557 return true;
558 }
559 }
560 false
561}
562
563const DOTDIR_NOISE_PATH_COMPONENTS: &[&str] = &[
567 "__fixtures__",
568 "__mocks__",
569 "__tests__",
570 "e2e",
571 "fixture",
572 "fixtures",
573 "playground",
574 "playgrounds",
575 "spec",
576 "test",
577 "tests",
578];
579
580fn dotdir_is_scan_candidate(config: &ResolvedConfig, dir: &Path) -> bool {
587 let Some(name) = dir.file_name().and_then(OsStr::to_str) else {
588 return false;
589 };
590 if SCRIPT_SCOPE_DENYLIST.contains(&name) {
591 return false;
592 }
593 let relative = dir.strip_prefix(&config.root).unwrap_or(dir);
594 if relative
598 .components()
599 .any(|component| component.as_os_str() == OsStr::new("node_modules"))
600 {
601 return false;
602 }
603 !relative.components().any(|component| {
612 DOTDIR_NOISE_PATH_COMPONENTS.contains(&component.as_os_str().to_string_lossy().as_ref())
613 })
614}
615
616fn report_default_ignore_exclusions(
625 config: &ResolvedConfig,
626 tally: &ExclusionTally,
627) -> Vec<WorkspaceDiagnostic> {
628 let mut indices: Vec<usize> = tally.keys().copied().collect();
629 indices.sort_unstable();
630 indices
631 .into_iter()
632 .filter_map(|index| {
633 let excluded = tally.get(&index)?;
634 let pattern = DEFAULT_IGNORE_PATTERNS.get(index)?;
635 Some(
636 WorkspaceDiagnostic::new(
637 &config.root,
638 config.root.join(excluded.anchor()),
639 WorkspaceDiagnosticKind::ExcludedByDefaultIgnore {
640 pattern: (*pattern).to_owned(),
641 file_count: excluded.file_count,
642 directory_count: excluded.directory_count(),
643 },
644 )
645 .into_root_relative(&config.root),
652 )
653 })
654 .collect()
655}
656
657fn report_no_source_files_analyzed(
670 config: &ResolvedConfig,
671 analyzed_file_count: usize,
672 tally: &ExclusionTally,
673) -> Vec<WorkspaceDiagnostic> {
674 if analyzed_file_count > 0 {
675 return Vec::new();
676 }
677 let excluded_file_count = tally.values().map(|excluded| excluded.file_count).sum();
678 vec![
679 WorkspaceDiagnostic::new(
680 &config.root,
681 config.root.clone(),
682 WorkspaceDiagnosticKind::NoSourceFilesAnalyzed {
683 excluded_file_count,
684 },
685 )
686 .into_root_relative(&config.root),
687 ]
688}
689
690fn report_skipped_source_dotdirs(
696 config: &ResolvedConfig,
697 production_excludes: Option<&globset::GlobSet>,
698 candidates: &[PathBuf],
699) -> Vec<WorkspaceDiagnostic> {
700 if candidates.is_empty() {
701 return Vec::new();
702 }
703 let mut budget = DOTDIR_SCAN_TOTAL_ENTRIES;
706 let scannable: Vec<&PathBuf> = candidates
707 .iter()
708 .filter(|dir| dotdir_is_scan_candidate(config, dir))
709 .collect();
710 let reportable: Vec<&PathBuf> = scannable
711 .iter()
712 .copied()
713 .take(DOTDIR_SCAN_MAX_CANDIDATES)
714 .filter(|dir| scan_for_reportable_source(config, production_excludes, dir, &mut budget))
715 .collect();
716 let truncated = scannable.len() > DOTDIR_SCAN_MAX_CANDIDATES || budget == 0;
719 if reportable.is_empty() {
720 return Vec::new();
721 }
722
723 let diagnostics: Vec<WorkspaceDiagnostic> = reportable
724 .iter()
725 .map(|dir| {
726 WorkspaceDiagnostic::new(
727 &config.root,
728 (*dir).clone(),
729 WorkspaceDiagnosticKind::SkippedSourceDotdir,
730 )
731 })
732 .collect();
733
734 let count = reportable.len();
735 if !config.quiet
736 && should_emit_note_once(format!(
737 "dotdir::{}::{count}::{}",
738 config.root.display(),
739 reportable
740 .first()
741 .map_or_else(String::new, |dir| display_relative(&config.root, dir))
742 ))
743 {
744 tracing::warn!(
745 "{}",
746 build_skipped_dotdirs_note(&config.root, &reportable, truncated)
747 );
748 }
749 diagnostics
750}
751
752fn build_skipped_dotdirs_note(root: &Path, reportable: &[&PathBuf], truncated: bool) -> String {
762 let count = reportable.len();
763 let examples = if truncated {
767 summarize_paths_open_ended(root, reportable)
768 } else {
769 summarize_paths(root, reportable)
770 };
771 let noun = if count == 1 {
772 "directory"
773 } else {
774 "directories"
775 };
776 let verb = if count == 1 { "contains" } else { "contain" };
777 let at_least = if truncated { "at least " } else { "" };
778 let (target, pronoun) = match reportable {
779 [only] => (display_relative(root, only), "it"),
780 _ => ("<dir>".to_owned(), "one"),
781 };
782 format!(
783 "fallow: skipped {at_least}{count} hidden {noun} that {verb} source files ({examples}). \
784 Hidden directories are not traversed, so a file, export or dependency used only \
785 there can be reported as unused: add '!{target}/**' to ignorePatterns to analyze \
786 {pronoun}, or add it to entry, ignoreExports or ignoreDependencies, or add \
787 '{target}/**' to ignorePatterns to silence this. fallow --root {target} analyzes \
788 {pronoun} on its own and does not fix this run."
789 )
790}
791
792fn build_largest_files_note(root: &Path, files: &[DiscoveredFile]) -> Option<String> {
797 if files.is_empty() {
798 return None;
799 }
800 let largest = files.iter().map(|f| f.size_bytes).max().unwrap_or(0);
801 if files.len() <= LARGE_SET_THRESHOLD && largest < LARGE_FILE_NOTE_BYTES {
802 return None;
803 }
804 let count = files.len();
805 let noun = if count == 1 { "file" } else { "files" };
806 let mut by_size: Vec<SizedFile> = files
807 .iter()
808 .filter(|f| f.size_bytes >= NOTE_FILE_FLOOR_BYTES)
809 .map(|f| (f.path.clone(), f.size_bytes))
810 .collect();
811 by_size.sort_unstable_by_key(|f| std::cmp::Reverse(f.1));
812 if by_size.is_empty() {
813 return Some(format!(
816 "fallow: discovered {count} {noun}. If analysis stalls or runs out of memory, \
817 exclude large generated files via ignorePatterns or --max-file-size."
818 ));
819 }
820 let examples = summarize_examples(root, &by_size);
821 Some(format!(
822 "fallow: discovered {count} {noun}; largest: {examples}. If analysis stalls or runs out of memory, \
823 exclude large generated files via ignorePatterns or --max-file-size."
824 ))
825}
826
827fn note_largest_files(config: &ResolvedConfig, files: &[DiscoveredFile]) {
832 if config.quiet {
833 return;
834 }
835 if let Some(message) = build_largest_files_note(&config.root, files)
836 && should_emit_note_once(format!("note::{}::{}", config.root.display(), files.len()))
837 {
838 tracing::warn!("{message}");
839 }
840}
841
842#[derive(Debug, Clone, Copy, PartialEq, Eq)]
844pub enum HiddenDirMatch {
845 AnyDepth,
851 ExactPath,
858}
859
860#[derive(Debug, Clone, PartialEq, Eq)]
862pub struct HiddenDirScope {
863 root: PathBuf,
864 dirs: Vec<String>,
865 match_mode: HiddenDirMatch,
866}
867
868impl HiddenDirScope {
869 #[must_use]
876 pub fn new(root: PathBuf, dirs: Vec<String>) -> Self {
877 Self {
878 root,
879 dirs,
880 match_mode: HiddenDirMatch::AnyDepth,
881 }
882 }
883
884 #[must_use]
887 pub fn new_exact_paths(root: PathBuf, dirs: Vec<String>) -> Self {
888 Self {
889 root,
890 dirs,
891 match_mode: HiddenDirMatch::ExactPath,
892 }
893 }
894
895 #[must_use]
900 pub fn with_match_mode(root: PathBuf, dirs: Vec<String>, match_mode: HiddenDirMatch) -> Self {
901 Self {
902 root,
903 dirs,
904 match_mode,
905 }
906 }
907
908 #[must_use]
909 pub fn root(&self) -> &Path {
910 &self.root
911 }
912
913 #[must_use]
914 pub fn dirs(&self) -> &[String] {
915 &self.dirs
916 }
917
918 #[must_use]
919 pub fn match_mode(&self) -> HiddenDirMatch {
920 self.match_mode
921 }
922
923 fn allows(&self, path: &Path, name: &OsStr) -> bool {
924 match self.match_mode {
925 HiddenDirMatch::AnyDepth => {
926 path.starts_with(&self.root) && self.dirs.iter().any(|dir| OsStr::new(dir) == name)
927 }
928 HiddenDirMatch::ExactPath => {
929 let Ok(relative) = path.strip_prefix(&self.root) else {
932 return false;
933 };
934 self.dirs.iter().any(|dir| Path::new(dir) == relative)
935 }
936 }
937 }
938}
939
940struct FileVisitor<'a> {
947 root: &'a Path,
948 canonical_root: Option<&'a Path>,
949 ignore_patterns: &'a IgnorePatternSet,
950 user_ignore_pattern_count: usize,
953 hidden_dir_scopes: &'a [HiddenDirScope],
957 production_excludes: &'a Option<globset::GlobSet>,
958 shared: &'a Mutex<Vec<(std::path::PathBuf, u64)>>,
959 config_shared: Option<&'a Mutex<Vec<std::path::PathBuf>>>,
960 excluded_shared: &'a Mutex<ExclusionTally>,
961 local: Vec<(std::path::PathBuf, u64)>,
962 config_local: Vec<std::path::PathBuf>,
963 excluded_local: ExclusionTally,
964 match_buf: Vec<usize>,
967}
968
969impl FileVisitor<'_> {
970 fn record_ignore_exclusion(&mut self, relative: &Path, is_source: bool) {
977 if (!is_source && self.user_ignore_pattern_count == 0)
983 || relative
984 .components()
985 .any(|component| component.as_os_str() == OsStr::new("node_modules"))
986 {
987 return;
988 }
989 self.match_buf.clear();
990 self.ignore_patterns
991 .excluded_matches_into(relative, &mut self.match_buf);
992 let Some(&first) = self.match_buf.first().filter(|_| is_source) else {
995 return;
996 };
997 if first < self.user_ignore_pattern_count {
998 return;
1001 }
1002 let Some(pattern) = DEFAULT_IGNORE_PATTERNS.get(first - self.user_ignore_pattern_count)
1003 else {
1004 return;
1005 };
1006 if UNREPORTED_DEFAULT_IGNORES.contains(pattern) {
1007 return;
1008 }
1009 self.excluded_local
1010 .entry(first - self.user_ignore_pattern_count)
1011 .or_default()
1012 .record(exclusion_scope(relative, pattern));
1013 }
1014}
1015
1016impl ignore::ParallelVisitor for FileVisitor<'_> {
1017 fn visit(&mut self, result: Result<ignore::DirEntry, ignore::Error>) -> ignore::WalkState {
1018 let Ok(entry) = result else {
1019 return ignore::WalkState::Continue;
1020 };
1021 if entry.file_type().is_some_and(|ft| ft.is_dir()) {
1022 return ignore::WalkState::Continue;
1023 }
1024 let relative = entry
1025 .path()
1026 .strip_prefix(self.root)
1027 .unwrap_or_else(|_| entry.path());
1028 if self.ignore_patterns.is_match(relative) {
1029 self.record_ignore_exclusion(relative, has_source_extension(entry.path()));
1030 return ignore::WalkState::Continue;
1031 }
1032 if self
1033 .production_excludes
1034 .as_ref()
1035 .is_some_and(|excludes| excludes.is_match(relative))
1036 {
1037 return ignore::WalkState::Continue;
1038 }
1039 if self.ignore_patterns.has_exceptions()
1040 && is_under_exception_only_hidden_dir(self.root, entry.path(), self.hidden_dir_scopes)
1041 && !self.ignore_patterns.is_lifted(relative)
1042 {
1043 return ignore::WalkState::Continue;
1044 }
1045 let symlink_size = if entry.file_type().is_some_and(|ft| ft.is_symlink()) {
1046 let Some(size) = contained_symlink_file_size(entry.path(), self.canonical_root) else {
1047 tracing::debug!(
1048 path = %entry.path().display(),
1049 "skipping source symlink with a broken, non-file, or outside-root target"
1050 );
1051 return ignore::WalkState::Continue;
1052 };
1053 Some(size)
1054 } else {
1055 None
1056 };
1057 if has_source_extension(entry.path()) {
1058 let size_bytes =
1059 symlink_size.unwrap_or_else(|| entry.metadata().map_or(0, |m| m.len()));
1060 self.local.push((entry.into_path(), size_bytes));
1061 } else if self.config_shared.is_some() {
1062 self.config_local.push(entry.into_path());
1065 }
1066 ignore::WalkState::Continue
1067 }
1068}
1069
1070fn contained_symlink_file_size(path: &Path, canonical_root: Option<&Path>) -> Option<u64> {
1071 let root = canonical_root?;
1072 let target = path.canonicalize().ok()?;
1073 if !target.starts_with(root) {
1074 return None;
1075 }
1076 let metadata = target.metadata().ok()?;
1077 metadata.is_file().then_some(metadata.len())
1078}
1079
1080impl Drop for FileVisitor<'_> {
1081 #[expect(
1082 clippy::expect_used,
1083 reason = "poisoned walk collector lock means worker state is unrecoverable"
1084 )]
1085 fn drop(&mut self) {
1086 if !self.local.is_empty() {
1087 self.shared
1088 .lock()
1089 .expect("walk collector lock poisoned")
1090 .append(&mut self.local);
1091 }
1092 if let Some(config_shared) = self.config_shared
1093 && !self.config_local.is_empty()
1094 {
1095 config_shared
1096 .lock()
1097 .expect("walk config collector lock poisoned")
1098 .append(&mut self.config_local);
1099 }
1100 if !self.excluded_local.is_empty() {
1101 let mut shared = self
1102 .excluded_shared
1103 .lock()
1104 .expect("walk exclusion collector lock poisoned");
1105 for (index, tally) in std::mem::take(&mut self.excluded_local) {
1106 shared.entry(index).or_default().merge(tally);
1107 }
1108 }
1109 }
1110}
1111
1112struct FileVisitorBuilder<'a> {
1114 root: &'a Path,
1115 canonical_root: Option<&'a Path>,
1116 ignore_patterns: &'a IgnorePatternSet,
1117 user_ignore_pattern_count: usize,
1118 hidden_dir_scopes: &'a [HiddenDirScope],
1119 production_excludes: &'a Option<globset::GlobSet>,
1120 shared: &'a Mutex<Vec<(std::path::PathBuf, u64)>>,
1121 config_shared: Option<&'a Mutex<Vec<std::path::PathBuf>>>,
1122 excluded_shared: &'a Mutex<ExclusionTally>,
1123}
1124
1125impl<'s> ignore::ParallelVisitorBuilder<'s> for FileVisitorBuilder<'s> {
1126 fn build(&mut self) -> Box<dyn ignore::ParallelVisitor + 's> {
1127 Box::new(FileVisitor {
1128 root: self.root,
1129 canonical_root: self.canonical_root,
1130 ignore_patterns: self.ignore_patterns,
1131 user_ignore_pattern_count: self.user_ignore_pattern_count,
1132 hidden_dir_scopes: self.hidden_dir_scopes,
1133 production_excludes: self.production_excludes,
1134 shared: self.shared,
1135 config_shared: self.config_shared,
1136 excluded_shared: self.excluded_shared,
1137 local: Vec::new(),
1138 config_local: Vec::new(),
1139 excluded_local: ExclusionTally::default(),
1140 match_buf: Vec::new(),
1141 })
1142 }
1143}
1144
1145pub const SOURCE_EXTENSIONS: &[&str] = &[
1147 "ts", "tsx", "mts", "cts", "gts", "js", "jsx", "mjs", "cjs", "gjs", "vue", "svelte", "astro",
1148 "mdx", "css", "scss", "sass", "less", "html", "graphql", "gql",
1149];
1150
1151pub fn is_allowed_hidden_dir(name: &OsStr) -> bool {
1153 ALLOWED_HIDDEN_DIRS.iter().any(|&d| OsStr::new(d) == name)
1154}
1155
1156fn is_allowed_scoped_hidden_dir(
1157 name: &OsStr,
1158 path: &Path,
1159 additional_hidden_dir_scopes: &[HiddenDirScope],
1160) -> bool {
1161 additional_hidden_dir_scopes
1162 .iter()
1163 .any(|scope| scope.allows(path, name))
1164}
1165
1166const YARN_PNP_GENERATED_FILES: &[&str] = &[".pnp.cjs", ".pnp.loader.mjs"];
1171
1172fn is_yarn_pnp_generated_file(name: &OsStr) -> bool {
1173 YARN_PNP_GENERATED_FILES
1174 .iter()
1175 .any(|&f| OsStr::new(f) == name)
1176}
1177
1178fn is_allowed_hidden_with_scopes(
1184 entry: &ignore::DirEntry,
1185 additional_hidden_dir_scopes: &[HiddenDirScope],
1186) -> bool {
1187 let name = entry.file_name();
1188 let name_str = name.to_string_lossy();
1189
1190 if !name_str.starts_with('.') {
1191 return true;
1192 }
1193
1194 if entry.file_type().is_some_and(|ft| !ft.is_dir()) {
1195 return !is_yarn_pnp_generated_file(name);
1196 }
1197
1198 is_allowed_hidden_dir(name)
1199 || is_allowed_scoped_hidden_dir(name, entry.path(), additional_hidden_dir_scopes)
1200}
1201
1202fn is_under_exception_only_hidden_dir(
1207 root: &Path,
1208 path: &Path,
1209 hidden_dir_scopes: &[HiddenDirScope],
1210) -> bool {
1211 path.ancestors()
1212 .skip(1)
1213 .take_while(|dir| *dir != root && dir.starts_with(root))
1214 .any(|dir| {
1215 dir.file_name().is_some_and(|name| {
1216 name.to_string_lossy().starts_with('.')
1217 && !is_allowed_hidden_dir(name)
1218 && !is_allowed_scoped_hidden_dir(name, dir, hidden_dir_scopes)
1219 })
1220 })
1221}
1222
1223pub fn discover_files(config: &ResolvedConfig) -> Vec<DiscoveredFile> {
1229 discover_files_with_additional_hidden_dirs(config, &[])
1230}
1231
1232fn config_candidate_basename_globs() -> &'static [String] {
1244 static GLOBS: OnceLock<Vec<String>> = OnceLock::new();
1245 GLOBS.get_or_init(|| {
1246 let mut set: FxHashSet<String> = FxHashSet::default();
1247 for plugin in crate::plugins::registry::builtin::create_builtin_plugins() {
1248 for pattern in plugin.config_patterns() {
1249 let basename = pattern.rsplit('/').next().unwrap_or(pattern);
1250 set.insert(basename.to_string());
1251 }
1252 if plugin.tooling_dependencies().is_empty() {
1256 continue;
1257 }
1258 for pattern in plugin.always_used() {
1259 let basename = pattern.rsplit('/').next().unwrap_or(pattern);
1260 if !basename.starts_with('!') && !basename.contains(['*', '?', '[']) {
1261 set.insert(basename.to_string());
1262 }
1263 }
1264 }
1265 let mut globs: Vec<String> = set.into_iter().collect();
1266 globs.sort_unstable();
1267 globs
1268 })
1269}
1270
1271fn has_source_extension(path: &Path) -> bool {
1274 path.extension()
1275 .and_then(OsStr::to_str)
1276 .is_some_and(|ext| SOURCE_EXTENSIONS.contains(&ext))
1277}
1278
1279#[expect(
1283 clippy::expect_used,
1284 reason = "source file globs are hard-coded compile-time constants"
1285)]
1286fn build_walk_types(capture_config: bool) -> ignore::types::Types {
1287 static SOURCE_TYPES: OnceLock<ignore::types::Types> = OnceLock::new();
1288 static SOURCE_AND_CONFIG_TYPES: OnceLock<ignore::types::Types> = OnceLock::new();
1289
1290 let cache = if capture_config {
1291 &SOURCE_AND_CONFIG_TYPES
1292 } else {
1293 &SOURCE_TYPES
1294 };
1295 cache
1296 .get_or_init(|| {
1297 let mut types_builder = ignore::types::TypesBuilder::new();
1298 let source_glob = format!("*.{{{}}}", SOURCE_EXTENSIONS.join(","));
1299 types_builder
1300 .add("source", &source_glob)
1301 .expect("valid glob");
1302 types_builder.select("source");
1303 if capture_config {
1304 for glob in config_candidate_basename_globs() {
1305 let _ = types_builder.add("config", glob);
1309 }
1310 types_builder.select("config");
1311 }
1312 types_builder.build().expect("valid types")
1313 })
1314 .clone()
1315}
1316
1317fn build_source_walk_builder(
1321 config: &ResolvedConfig,
1322 additional_hidden_dir_scopes: &[HiddenDirScope],
1323 capture_config: bool,
1324 skipped_dotdirs: &SkippedDotdirSink,
1325) -> WalkBuilder {
1326 let mut walk_builder = fallow_config::source_walk_builder(&config.root);
1327 walk_builder
1328 .types(build_walk_types(capture_config))
1329 .threads(config.threads);
1330 let scopes = additional_hidden_dir_scopes.to_vec();
1335 let sink = Arc::clone(skipped_dotdirs);
1336 let root = config.root.clone();
1337 let ignore_patterns = config.ignore_patterns.clone();
1338 walk_builder.filter_entry(move |entry| {
1339 if is_allowed_hidden_with_scopes(entry, &scopes) {
1340 return true;
1341 }
1342 if ignore_patterns.has_exceptions()
1346 && entry.file_type().is_some_and(|ft| ft.is_dir())
1347 && ignore_patterns.admits_hidden_dir(
1348 entry
1349 .path()
1350 .strip_prefix(&root)
1351 .unwrap_or_else(|_| entry.path()),
1352 )
1353 {
1354 return true;
1355 }
1356 if entry.file_type().is_some_and(|ft| ft.is_dir())
1357 && let Ok(mut collected) = sink.lock()
1358 {
1359 collected.push(entry.path().to_path_buf());
1360 }
1361 false
1362 });
1363 walk_builder
1364}
1365
1366pub fn discover_files_with_additional_hidden_dirs(
1372 config: &ResolvedConfig,
1373 additional_hidden_dir_scopes: &[HiddenDirScope],
1374) -> Vec<DiscoveredFile> {
1375 discover_files_and_config_candidates(config, additional_hidden_dir_scopes).0
1376}
1377
1378pub fn discover_files_and_config_candidates(
1394 config: &ResolvedConfig,
1395 additional_hidden_dir_scopes: &[HiddenDirScope],
1396) -> (Vec<DiscoveredFile>, Vec<PathBuf>) {
1397 let discovered =
1398 discover_files_config_candidates_and_diagnostics(config, additional_hidden_dir_scopes);
1399 (discovered.files, discovered.config_candidates)
1400}
1401
1402pub struct DiscoveredSources {
1411 pub files: Vec<DiscoveredFile>,
1413 pub config_candidates: Vec<PathBuf>,
1415 pub diagnostics: Vec<WorkspaceDiagnostic>,
1418}
1419
1420#[expect(
1428 clippy::cast_possible_truncation,
1429 reason = "file count is bounded by project size, well under u32::MAX"
1430)]
1431#[expect(clippy::expect_used, reason = "the collector lock must remain usable")]
1432pub fn discover_files_config_candidates_and_diagnostics(
1433 config: &ResolvedConfig,
1434 additional_hidden_dir_scopes: &[HiddenDirScope],
1435) -> DiscoveredSources {
1436 let _span = tracing::info_span!("discover_files").entered();
1437
1438 let capture_config = !config.production;
1439 let skipped_dotdirs: SkippedDotdirSink = Arc::new(Mutex::new(Vec::new()));
1440 let walk_builder = build_source_walk_builder(
1441 config,
1442 additional_hidden_dir_scopes,
1443 capture_config,
1444 &skipped_dotdirs,
1445 );
1446 let production_excludes = super::production_excludes::build_production_excludes(config);
1447 let canonical_root = config.root.canonicalize().ok();
1448
1449 let collected: Mutex<Vec<(std::path::PathBuf, u64)>> = Mutex::new(Vec::new());
1450 let config_collected: Mutex<Vec<std::path::PathBuf>> = Mutex::new(Vec::new());
1451 let excluded_collected: Mutex<ExclusionTally> = Mutex::new(ExclusionTally::default());
1452 let mut visitor_builder = FileVisitorBuilder {
1453 root: &config.root,
1454 canonical_root: canonical_root.as_deref(),
1455 ignore_patterns: &config.ignore_patterns,
1456 user_ignore_pattern_count: config.user_ignore_pattern_count,
1457 hidden_dir_scopes: additional_hidden_dir_scopes,
1458 production_excludes: &production_excludes,
1459 shared: &collected,
1460 config_shared: capture_config.then_some(&config_collected),
1461 excluded_shared: &excluded_collected,
1462 };
1463 walk_builder.build_parallel().visit(&mut visitor_builder);
1464 config.ignore_patterns.mark_walked();
1465
1466 let mut raw = collected
1467 .into_inner()
1468 .expect("walk collector lock poisoned");
1469 sort_permuted(&mut raw, PermutationSite::Files, |a, b| a.0.cmp(&b.0));
1477
1478 let mut config_candidates = config_collected
1479 .into_inner()
1480 .expect("walk config collector lock poisoned");
1481 sort_permuted(&mut config_candidates, PermutationSite::Configs, Ord::cmp);
1482
1483 let excluded_by_default_ignore = excluded_collected
1484 .into_inner()
1485 .expect("walk exclusion collector lock poisoned");
1486
1487 let mut dotdir_candidates = skipped_dotdirs
1491 .lock()
1492 .map_or_else(|_| Vec::new(), |mut guard| std::mem::take(&mut *guard));
1493 sort_permuted(&mut dotdir_candidates, PermutationSite::Dotdirs, Ord::cmp);
1494 dotdir_candidates.dedup();
1495
1496 let (kept, skipped) = partition_by_size(raw, config.max_file_size_bytes);
1497 let (kept, skipped_minified) =
1498 partition_minified_generated_js(kept, config.max_file_size_bytes);
1499 let diagnostics = fallow_config::replace_source_discovery_diagnostics(
1504 &config.root,
1505 report_skipped_large_files(config, &skipped)
1506 .into_iter()
1507 .chain(report_skipped_minified_files(config, &skipped_minified))
1508 .chain(report_skipped_source_dotdirs(
1509 config,
1510 production_excludes.as_ref(),
1511 &dotdir_candidates,
1512 ))
1513 .chain(report_default_ignore_exclusions(
1514 config,
1515 &excluded_by_default_ignore,
1516 ))
1517 .chain(report_missing_node_modules(config))
1518 .chain(report_no_source_files_analyzed(
1519 config,
1520 kept.len(),
1521 &excluded_by_default_ignore,
1522 ))
1523 .collect(),
1524 );
1525
1526 let files: Vec<DiscoveredFile> = kept
1527 .into_iter()
1528 .enumerate()
1529 .map(|(idx, (path, size_bytes))| DiscoveredFile {
1530 id: FileId(idx as u32),
1531 path,
1532 size_bytes,
1533 })
1534 .collect();
1535
1536 note_largest_files(config, &files);
1537 super::legacy_glob::warn_legacy_glob_narrowings(config, &files);
1538
1539 DiscoveredSources {
1540 files,
1541 config_candidates,
1542 diagnostics,
1543 }
1544}
1545
1546#[cfg(test)]
1547mod tests {
1548 use std::ffi::OsStr;
1549 use std::path::MAIN_SEPARATOR;
1550
1551 use super::*;
1552
1553 #[test]
1557 fn exclusion_scope_stops_at_the_patterns_literal_directory_segment() {
1558 assert_eq!(
1559 exclusion_scope(
1560 Path::new("projects/app/build/static/js/main.js"),
1561 "**/build/**"
1562 ),
1563 PathBuf::from("projects/app/build")
1564 );
1565 assert_eq!(
1566 exclusion_scope(Path::new("dist/a.ts"), "**/dist/**"),
1567 PathBuf::from("dist")
1568 );
1569 assert_eq!(
1570 exclusion_scope(
1571 Path::new("node_modules/react/index.js"),
1572 "**/node_modules/**"
1573 ),
1574 PathBuf::from("node_modules"),
1575 "the helper is shape-only: `**/node_modules/**` is never tallied, \
1576 but a directory-shaped pattern still collapses to its literal segment"
1577 );
1578 }
1579
1580 #[test]
1586 fn exclusion_scope_takes_the_deepest_matching_segment() {
1587 assert_eq!(
1588 exclusion_scope(Path::new("build/tools/build/a.ts"), "**/build/**"),
1589 PathBuf::from("build/tools/build")
1590 );
1591 assert_eq!(
1592 exclusion_scope(Path::new("dist/pkg/dist/inner/a.ts"), "**/dist/**"),
1593 PathBuf::from("dist/pkg/dist")
1594 );
1595 }
1596
1597 #[test]
1600 fn exclusion_scope_falls_back_to_the_parent_for_a_file_shaped_pattern() {
1601 assert_eq!(
1602 exclusion_scope(Path::new("vendor/a.min.js"), "**/*.min.js"),
1603 PathBuf::from("vendor")
1604 );
1605 assert_eq!(
1606 exclusion_scope(Path::new("a.min.js"), "**/*.min.js"),
1607 PathBuf::new(),
1608 "a root-level match anchors at the root itself"
1609 );
1610 }
1611
1612 #[test]
1616 fn exclusion_scope_falls_back_when_the_literal_segment_is_absent() {
1617 assert_eq!(
1618 exclusion_scope(Path::new("src/nested/a.ts"), "**/build/**"),
1619 PathBuf::from("src/nested")
1620 );
1621 }
1622
1623 #[test]
1627 fn the_directory_count_is_the_number_of_distinct_scopes() {
1628 let mut one_tree = ExcludedByPattern::default();
1629 one_tree.record(PathBuf::from("packages/web/build"));
1630 one_tree.record(PathBuf::from("packages/web/build"));
1631 assert_eq!(one_tree.file_count, 2);
1632 assert_eq!(one_tree.directory_count(), 1);
1633
1634 let mut scattered = ExcludedByPattern::default();
1635 scattered.record(PathBuf::from("packages/a/dist"));
1636 scattered.record(PathBuf::from("packages/b/dist"));
1637 assert_eq!(scattered.directory_count(), 2);
1638 }
1639
1640 #[test]
1644 fn the_anchor_is_the_largest_group_with_ties_broken_by_path() {
1645 let mut tally = ExcludedByPattern::default();
1646 for _ in 0..3 {
1647 tally.record(PathBuf::from("packages/web/build"));
1648 }
1649 tally.record(PathBuf::from("packages/api/build"));
1650 assert_eq!(tally.file_count, 4);
1651 assert_eq!(tally.anchor(), PathBuf::from("packages/web/build"));
1652
1653 let mut tied = ExcludedByPattern::default();
1654 tied.record(PathBuf::from("z/build"));
1655 tied.record(PathBuf::from("a/build"));
1656 assert_eq!(tied.anchor(), PathBuf::from("a/build"));
1657 }
1658
1659 #[test]
1662 fn merging_two_thread_tallies_keeps_the_count_exact() {
1663 let mut left = ExcludedByPattern::default();
1664 left.record(PathBuf::from("dist"));
1665 left.record(PathBuf::from("dist"));
1666 let mut right = ExcludedByPattern::default();
1667 right.record(PathBuf::from("dist"));
1668 right.record(PathBuf::from("packages/ui/dist"));
1669
1670 left.merge(right);
1671 assert_eq!(left.file_count, 4);
1672 assert_eq!(left.scopes.get(Path::new("dist")), Some(&3));
1673 assert_eq!(left.anchor(), PathBuf::from("dist"));
1674 }
1675
1676 #[test]
1677 fn skipped_dotdirs_note_names_the_directory_when_there_is_one() {
1678 let root = Path::new("/repo");
1679 let only = PathBuf::from("/repo/.tooling");
1680 let note = build_skipped_dotdirs_note(root, &[&only], false);
1681 assert!(note.contains("skipped 1 hidden directory that contains source files"));
1682 assert!(note.contains("add it to entry, ignoreExports or ignoreDependencies"));
1683 assert!(note.contains("fallow --root .tooling analyzes it on its own"));
1684 assert!(note.contains("does not fix this run"));
1685 assert!(note.contains("add '.tooling/**' to"));
1686 assert!(note.contains("add '!.tooling/**' to ignorePatterns to analyze it"));
1687 assert!(
1688 !note.contains("<dir>"),
1689 "the single-directory remedy must be copy-pasteable: {note}"
1690 );
1691 }
1692
1693 #[test]
1694 fn skipped_dotdirs_note_pluralizes_and_keeps_the_placeholder() {
1695 let root = Path::new("/repo");
1696 let a = PathBuf::from("/repo/.a");
1697 let b = PathBuf::from("/repo/.b");
1698 let note = build_skipped_dotdirs_note(root, &[&a, &b], false);
1699 assert!(note.contains("skipped 2 hidden directories that contain source files"));
1700 assert!(note.contains("fallow --root <dir> analyzes one on its own"));
1701 }
1702
1703 #[test]
1704 fn skipped_dotdirs_note_drops_the_tail_count_when_truncated() {
1705 let root = Path::new("/repo");
1706 let owned: Vec<PathBuf> = (0..8)
1707 .map(|i| PathBuf::from(format!("/repo/.d{i}")))
1708 .collect();
1709 let reportable: Vec<&PathBuf> = owned.iter().collect();
1710
1711 let bounded = build_skipped_dotdirs_note(root, &reportable, true);
1712 assert!(bounded.contains("skipped at least 8 hidden directories"));
1713 assert!(
1714 bounded.contains("and more") && !bounded.contains("and 3 more"),
1715 "an inexact total must not carry an exact remainder: {bounded}"
1716 );
1717
1718 let complete = build_skipped_dotdirs_note(root, &reportable, false);
1719 assert!(!complete.contains("at least"));
1720 assert!(complete.contains("and 3 more"));
1721 }
1722
1723 #[test]
1724 fn dotdir_noise_path_components_stay_sorted_and_lowercase() {
1725 let mut sorted = DOTDIR_NOISE_PATH_COMPONENTS.to_vec();
1726 sorted.sort_unstable();
1727 assert_eq!(sorted, DOTDIR_NOISE_PATH_COMPONENTS);
1728 for component in DOTDIR_NOISE_PATH_COMPONENTS {
1729 assert!(!component.starts_with('.'), "'{component}' is not hidden");
1730 assert_eq!(
1731 *component,
1732 component.to_lowercase(),
1733 "'{component}' is matched verbatim against a path component"
1734 );
1735 }
1736 }
1737
1738 #[test]
1739 fn script_scope_denylist_stays_disjoint_and_sorted() {
1740 let mut sorted = SCRIPT_SCOPE_DENYLIST.to_vec();
1741 sorted.sort_unstable();
1742 assert_eq!(
1743 sorted, SCRIPT_SCOPE_DENYLIST,
1744 "keep the list sorted so additions stay reviewable"
1745 );
1746 for dir in SCRIPT_SCOPE_DENYLIST {
1747 assert!(dir.starts_with('.'), "'{dir}' is not a hidden directory");
1748 assert!(
1749 !ALLOWED_HIDDEN_DIRS.contains(dir),
1750 "'{dir}' is traversed, so it can never be a skipped candidate"
1751 );
1752 }
1753 }
1754
1755 #[test]
1756 fn dotdir_module_extensions_are_a_subset_of_source_extensions() {
1757 for ext in DOTDIR_MODULE_EXTENSIONS {
1758 assert!(
1759 SOURCE_EXTENSIONS.contains(ext),
1760 "'{ext}' is not discovered as source, so it cannot be a trigger"
1761 );
1762 }
1763 for ext in ["css", "scss", "sass", "less", "html", "graphql", "gql"] {
1764 assert!(
1765 !DOTDIR_MODULE_EXTENSIONS.contains(&ext),
1766 "'{ext}' carries no imports or exports for the message to be about"
1767 );
1768 }
1769 }
1770
1771 fn assign_file_ids(mut raw: Vec<(std::path::PathBuf, u64)>) -> Vec<DiscoveredFile> {
1774 raw.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1775 raw.into_iter()
1776 .enumerate()
1777 .map(|(idx, (path, size_bytes))| DiscoveredFile {
1778 id: FileId(idx as u32),
1779 path,
1780 size_bytes,
1781 })
1782 .collect()
1783 }
1784
1785 #[test]
1791 fn file_id_assignment_is_deterministic_for_identical_file_set() {
1792 let paths = [
1793 "/project/src/z.ts",
1794 "/project/src/a.ts",
1795 "/project/src/components/Button.tsx",
1796 "/project/src/components/Button.module.css",
1797 "/project/index.ts",
1798 ];
1799
1800 let walk_one: Vec<(std::path::PathBuf, u64)> = paths
1802 .iter()
1803 .map(|p| (std::path::PathBuf::from(p), 10))
1804 .collect();
1805 let mut walk_two = walk_one.clone();
1806 walk_two.reverse();
1807
1808 let files_one = assign_file_ids(walk_one);
1809 let files_two = assign_file_ids(walk_two);
1810
1811 assert_eq!(files_one.len(), files_two.len());
1813 for (a, b) in files_one.iter().zip(files_two.iter()) {
1814 assert_eq!(a.id, b.id);
1815 assert_eq!(a.path, b.path);
1816 }
1817
1818 for (idx, file) in files_one.iter().enumerate() {
1821 assert_eq!(file.id, FileId(idx as u32));
1822 }
1823 assert_eq!(
1824 files_one[0].path,
1825 std::path::PathBuf::from("/project/index.ts")
1826 );
1827 }
1828
1829 #[test]
1830 fn file_id_assignment_recomputes_after_rename_or_delete() {
1831 let before = assign_file_ids(vec![
1832 (std::path::PathBuf::from("/project/src/a.ts"), 10),
1833 (std::path::PathBuf::from("/project/src/b.ts"), 10),
1834 (std::path::PathBuf::from("/project/src/c.ts"), 10),
1835 ]);
1836 let after_delete = assign_file_ids(vec![
1837 (std::path::PathBuf::from("/project/src/a.ts"), 10),
1838 (std::path::PathBuf::from("/project/src/c.ts"), 10),
1839 ]);
1840 let after_rename = assign_file_ids(vec![
1841 (std::path::PathBuf::from("/project/src/a.ts"), 10),
1842 (std::path::PathBuf::from("/project/src/c.ts"), 10),
1843 (std::path::PathBuf::from("/project/src/d.ts"), 10),
1844 ]);
1845
1846 assert_eq!(before[0].id, FileId(0));
1847 assert_eq!(before[1].id, FileId(1));
1848 assert_eq!(before[2].id, FileId(2));
1849 assert_eq!(after_delete[0].id, FileId(0));
1850 assert_eq!(after_delete[1].id, FileId(1));
1851 assert_eq!(
1852 after_delete[1].path,
1853 std::path::PathBuf::from("/project/src/c.ts")
1854 );
1855 assert_eq!(after_rename[0].id, FileId(0));
1856 assert_eq!(after_rename[1].id, FileId(1));
1857 assert_eq!(
1858 after_rename[1].path,
1859 std::path::PathBuf::from("/project/src/c.ts")
1860 );
1861 assert_eq!(after_rename[2].id, FileId(2));
1862 assert_eq!(
1863 after_rename[2].path,
1864 std::path::PathBuf::from("/project/src/d.ts")
1865 );
1866 }
1867
1868 #[test]
1869 fn allowed_hidden_dirs() {
1870 assert!(is_allowed_hidden_dir(OsStr::new(".storybook")));
1871 assert!(is_allowed_hidden_dir(OsStr::new(".vitepress")));
1872 assert!(is_allowed_hidden_dir(OsStr::new(".well-known")));
1873 assert!(is_allowed_hidden_dir(OsStr::new(".changeset")));
1874 assert!(is_allowed_hidden_dir(OsStr::new(".github")));
1875 }
1876
1877 #[test]
1878 fn disallowed_hidden_dirs() {
1879 assert!(!is_allowed_hidden_dir(OsStr::new(".git")));
1880 assert!(!is_allowed_hidden_dir(OsStr::new(".cache")));
1881 assert!(!is_allowed_hidden_dir(OsStr::new(".vscode")));
1882 assert!(!is_allowed_hidden_dir(OsStr::new(".fallow")));
1883 assert!(!is_allowed_hidden_dir(OsStr::new(".next")));
1884 }
1885
1886 #[test]
1887 fn non_hidden_dirs_not_in_allowlist() {
1888 assert!(!is_allowed_hidden_dir(OsStr::new("src")));
1889 assert!(!is_allowed_hidden_dir(OsStr::new("node_modules")));
1890 }
1891
1892 #[test]
1893 fn walk_types_match_every_supported_source_extension() {
1894 for capture_config in [false, true] {
1895 let types = build_walk_types(capture_config);
1896 for extension in SOURCE_EXTENSIONS {
1897 let path = format!("packages/ui/src/nested/component.{extension}");
1898 assert!(
1899 types.matched(&path, false).is_whitelist(),
1900 "expected source match for {path} with capture_config={capture_config}"
1901 );
1902 }
1903 }
1904 }
1905
1906 #[test]
1907 fn walk_types_match_typescript_declaration_files() {
1908 let types = build_walk_types(true);
1909 for path in [
1910 "src/env.d.ts",
1911 "packages/app/types/generated.d.mts",
1912 "packages/app/types/compat.d.cts",
1913 ] {
1914 assert!(
1915 types.matched(path, false).is_whitelist(),
1916 "expected declaration source match for {path}"
1917 );
1918 }
1919 }
1920
1921 #[test]
1922 fn walk_types_reject_source_extension_near_misses() {
1923 for capture_config in [false, true] {
1924 let types = build_walk_types(capture_config);
1925 for path in [
1926 "src/component.tsx.bak",
1927 "src/component.tsxmap",
1928 "src/component.TS",
1929 "src/component.gqlx",
1930 "src/component.htm",
1931 "src/component",
1932 "assets/component.png",
1933 ] {
1934 assert!(
1935 types.matched(path, false).is_ignore(),
1936 "expected non-source rejection for {path} with capture_config={capture_config}"
1937 );
1938 }
1939 }
1940 }
1941
1942 #[test]
1943 fn walk_types_keep_config_candidate_selection_separate() {
1944 assert!(
1945 build_walk_types(true)
1946 .matched("packages/app/tsconfig.json", false)
1947 .is_whitelist()
1948 );
1949 assert!(
1950 build_walk_types(false)
1951 .matched("packages/app/tsconfig.json", false)
1952 .is_ignore()
1953 );
1954 }
1955
1956 #[test]
1957 fn source_extensions_are_exactly_the_supported_set() {
1958 let mut actual = SOURCE_EXTENSIONS.to_vec();
1959 actual.sort_unstable();
1960 let mut expected = vec![
1961 "ts", "tsx", "mts", "cts", "gts", "js", "jsx", "mjs", "cjs", "gjs", "vue", "svelte",
1962 "astro", "mdx", "css", "scss", "sass", "less", "html", "graphql", "gql",
1963 ];
1964 expected.sort_unstable();
1965 assert_eq!(actual, expected);
1966 }
1967
1968 fn production_excludes() -> globset::GlobSet {
1970 let config = fallow_config::FallowConfig {
1971 production: true.into(),
1972 ..Default::default()
1973 }
1974 .resolve(
1975 std::path::PathBuf::from("/project"),
1976 fallow_config::OutputFormat::Human,
1977 1,
1978 true,
1979 true,
1980 None,
1981 );
1982 super::super::production_excludes::build_production_excludes(&config)
1983 .expect("production mode builds an exclude set")
1984 }
1985
1986 #[test]
1987 fn production_excludes_test_files() {
1988 let set = production_excludes();
1989 assert!(set.is_match("src/Button.test.ts"));
1990 assert!(set.is_match("src/utils.spec.tsx"));
1991 assert!(set.is_match("src/__tests__/helper.ts"));
1992 assert!(!set.is_match("src/Button.ts"));
1993 assert!(!set.is_match("src/utils.tsx"));
1994 }
1995
1996 #[test]
1997 fn production_excludes_story_files() {
1998 let set = production_excludes();
1999 assert!(set.is_match("src/Button.stories.tsx"));
2000 assert!(set.is_match("src/Card.story.ts"));
2001 assert!(!set.is_match("src/Button.tsx"));
2002 }
2003
2004 #[test]
2005 fn production_excludes_config_files_at_root_only() {
2006 let set = production_excludes();
2007 assert!(set.is_match("vitest.config.ts"));
2008 assert!(set.is_match("jest.config.js"));
2009 assert!(!set.is_match("src/app/app.config.ts"));
2010 assert!(!set.is_match("src/app/app.config.server.ts"));
2011 assert!(!set.is_match("packages/foo/vitest.config.ts"));
2012 assert!(!set.is_match("src/config.ts"));
2013 }
2014
2015 #[test]
2016 fn disallowed_hidden_dirs_idea() {
2017 assert!(!is_allowed_hidden_dir(OsStr::new(".idea")));
2018 }
2019
2020 #[test]
2021 fn is_declaration_file_matches_dts_variants() {
2022 assert!(is_declaration_file(Path::new("env.d.ts")));
2023 assert!(is_declaration_file(Path::new("src/auto-imports.d.ts")));
2024 assert!(is_declaration_file(Path::new("mod.d.mts")));
2025 assert!(is_declaration_file(Path::new("compat.d.cts")));
2026 assert!(!is_declaration_file(Path::new("index.ts")));
2027 assert!(!is_declaration_file(Path::new("component.tsx")));
2028 assert!(!is_declaration_file(Path::new("notes.d.txt")));
2029 }
2030
2031 #[test]
2032 fn format_size_mb_renders_one_decimal() {
2033 assert_eq!(format_size_mb(5 * 1024 * 1024), "5.0 MB");
2034 assert_eq!(format_size_mb(1024 * 1024 + 512 * 1024), "1.5 MB");
2035 assert_eq!(format_size_mb(0), "0.0 MB");
2036 }
2037
2038 #[test]
2039 fn partition_by_size_no_limit_keeps_all() {
2040 let raw = vec![(PathBuf::from("a.ts"), 10), (PathBuf::from("b.ts"), 10_000)];
2041 let (kept, skipped) = partition_by_size(raw, None);
2042 assert_eq!(kept.len(), 2);
2043 assert!(skipped.is_empty());
2044 }
2045
2046 #[test]
2047 fn partition_by_size_skips_strictly_over_limit() {
2048 let raw = vec![
2049 (PathBuf::from("under.ts"), 99),
2050 (PathBuf::from("exact.ts"), 100),
2051 (PathBuf::from("over.ts"), 101),
2052 ];
2053 let (kept, skipped) = partition_by_size(raw, Some(100));
2054 let kept_has = |name: &str| kept.iter().any(|(p, _)| p.as_path() == Path::new(name));
2055 assert!(kept_has("under.ts"));
2056 assert!(
2057 kept_has("exact.ts"),
2058 "a file exactly at the limit is kept (skip is strictly-greater)"
2059 );
2060 assert_eq!(skipped.len(), 1);
2061 assert_eq!(skipped[0].0, PathBuf::from("over.ts"));
2062 }
2063
2064 #[test]
2065 fn partition_by_size_exempts_declaration_files() {
2066 let raw = vec![
2067 (PathBuf::from("huge.ts"), 10_000),
2068 (PathBuf::from("auto-imports.d.ts"), 10_000),
2069 ];
2070 let (kept, skipped) = partition_by_size(raw, Some(100));
2071 assert!(
2072 kept.iter()
2073 .any(|(p, _)| p.as_path() == Path::new("auto-imports.d.ts")),
2074 "declaration files are exempt from the size skip regardless of size"
2075 );
2076 assert_eq!(skipped.len(), 1);
2077 assert_eq!(skipped[0].0, PathBuf::from("huge.ts"));
2078 }
2079
2080 fn disco(path: &str, size_bytes: u64) -> DiscoveredFile {
2081 DiscoveredFile {
2082 id: FileId(0),
2083 path: PathBuf::from(path),
2084 size_bytes,
2085 }
2086 }
2087
2088 #[test]
2089 fn largest_files_note_below_threshold_is_none() {
2090 let files = [disco("a.ts", 100), disco("b.ts", 200)];
2091 assert!(build_largest_files_note(Path::new("/p"), &files).is_none());
2092 }
2093
2094 #[test]
2095 fn largest_files_note_single_file_uses_singular() {
2096 let files = [disco("big.ts", 5 * 1024 * 1024)];
2097 let note = build_largest_files_note(Path::new("/p"), &files).expect("note fires");
2098 assert!(
2099 note.contains("discovered 1 file;"),
2100 "singular noun on the single-big-file path (issue #1086 regression): {note}"
2101 );
2102 assert!(!note.contains("discovered 1 files"));
2103 assert!(note.contains("big.ts (5.0 MB)"));
2104 }
2105
2106 #[test]
2107 fn largest_files_note_filters_sub_floor_files() {
2108 let files = [disco("big.ts", 5 * 1024 * 1024), disco("tiny.ts", 10)];
2109 let note = build_largest_files_note(Path::new("/p"), &files).expect("note fires");
2110 assert!(note.contains("discovered 2 files;"));
2111 assert!(note.contains("big.ts (5.0 MB)"));
2112 assert!(
2113 !note.contains("tiny.ts"),
2114 "sub-floor files are not listed as `0.0 MB` chaff: {note}"
2115 );
2116 }
2117
2118 #[test]
2119 fn largest_files_note_large_set_no_big_file_omits_list() {
2120 let files: Vec<DiscoveredFile> = (0..=LARGE_SET_THRESHOLD)
2121 .map(|i| disco(&format!("f{i}.ts"), 100))
2122 .collect();
2123 let note = build_largest_files_note(Path::new("/p"), &files).expect("large set fires");
2124 assert!(note.contains(&format!("discovered {} files", LARGE_SET_THRESHOLD + 1)));
2125 assert!(
2126 !note.contains("largest:"),
2127 "no sub-floor `largest:` list when no file clears the floor: {note}"
2128 );
2129 }
2130
2131 mod discover_files_integration {
2132 use std::path::PathBuf;
2133
2134 use fallow_config::{
2135 DuplicatesConfig, FallowConfig, FlagsConfig, HealthConfig, OutputFormat, ResolveConfig,
2136 RulesConfig,
2137 };
2138
2139 use super::*;
2140
2141 fn make_config(root: PathBuf, production: bool) -> ResolvedConfig {
2143 FallowConfig {
2144 production: production.into(),
2145 ..Default::default()
2146 }
2147 .resolve(root, OutputFormat::Human, 1, true, true, None)
2148 }
2149
2150 fn file_names(files: &[DiscoveredFile], root: &std::path::Path) -> Vec<String> {
2153 files
2154 .iter()
2155 .map(|f| {
2156 f.path
2157 .strip_prefix(root)
2158 .unwrap_or(&f.path)
2159 .to_string_lossy()
2160 .replace('\\', "/")
2161 })
2162 .collect()
2163 }
2164
2165 #[cfg(unix)]
2166 fn symlink_file(target: &Path, link: &Path) {
2167 std::os::unix::fs::symlink(target, link).expect("create file symlink");
2168 }
2169
2170 #[cfg(windows)]
2171 fn symlink_file(target: &Path, link: &Path) {
2172 std::os::windows::fs::symlink_file(target, link).expect("create file symlink");
2173 }
2174
2175 #[cfg(unix)]
2176 fn symlink_dir(target: &Path, link: &Path) {
2177 std::os::unix::fs::symlink(target, link).expect("create directory symlink");
2178 }
2179
2180 #[cfg(windows)]
2181 fn symlink_dir(target: &Path, link: &Path) {
2182 std::os::windows::fs::symlink_dir(target, link).expect("create directory symlink");
2183 }
2184
2185 #[test]
2186 fn source_symlinks_must_target_regular_files_inside_root() {
2187 let dir = tempfile::tempdir().expect("create project");
2188 let outside = tempfile::tempdir().expect("create outside dir");
2189 let src = dir.path().join("src");
2190 std::fs::create_dir_all(&src).unwrap();
2191 std::fs::write(src.join("regular.ts"), "export const regular = 1;").unwrap();
2192 std::fs::write(src.join("inside-target.ts"), "export const inside = 1;").unwrap();
2193 std::fs::write(
2194 outside.path().join("outside-target.ts"),
2195 "export const outside = 1;",
2196 )
2197 .unwrap();
2198 std::fs::create_dir_all(src.join("directory-target")).unwrap();
2199
2200 symlink_file(&src.join("inside-target.ts"), &src.join("inside-link.ts"));
2201 symlink_file(
2202 &outside.path().join("outside-target.ts"),
2203 &src.join("outside-link.ts"),
2204 );
2205 symlink_file(&src.join("missing-target.ts"), &src.join("broken-link.ts"));
2206 symlink_dir(
2207 &src.join("directory-target"),
2208 &src.join("directory-link.ts"),
2209 );
2210
2211 let config = make_config(dir.path().to_path_buf(), false);
2212 let names = file_names(&discover_files(&config), dir.path());
2213
2214 assert!(names.contains(&"src/regular.ts".to_string()));
2215 assert!(names.contains(&"src/inside-target.ts".to_string()));
2216 assert!(names.contains(&"src/inside-link.ts".to_string()));
2217 assert!(!names.contains(&"src/outside-link.ts".to_string()));
2218 assert!(!names.contains(&"src/broken-link.ts".to_string()));
2219 assert!(!names.contains(&"src/directory-link.ts".to_string()));
2220 }
2221
2222 #[test]
2226 fn skips_yarn_pnp_generated_files() {
2227 let dir = tempfile::tempdir().expect("create temp dir");
2228 std::fs::write(dir.path().join(".pnp.cjs"), "module.exports = {};").unwrap();
2229 std::fs::write(dir.path().join(".pnp.loader.mjs"), "export {};").unwrap();
2230 std::fs::write(dir.path().join("index.ts"), "export const a = 1;").unwrap();
2231
2232 let config = make_config(dir.path().to_path_buf(), false);
2233 let names = file_names(&discover_files(&config), dir.path());
2234
2235 assert_eq!(names, vec!["index.ts".to_string()]);
2236 }
2237
2238 #[test]
2239 fn discovers_source_files_with_valid_extensions() {
2240 let dir = tempfile::tempdir().expect("create temp dir");
2241 let src = dir.path().join("src");
2242 std::fs::create_dir_all(&src).unwrap();
2243
2244 std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
2245 std::fs::write(src.join("component.tsx"), "export default () => {};").unwrap();
2246 std::fs::write(src.join("utils.js"), "module.exports = {};").unwrap();
2247 std::fs::write(src.join("helper.jsx"), "export const h = 1;").unwrap();
2248 std::fs::write(src.join("config.mjs"), "export default {};").unwrap();
2249 std::fs::write(src.join("legacy.cjs"), "module.exports = {};").unwrap();
2250 std::fs::write(src.join("types.mts"), "export type T = string;").unwrap();
2251 std::fs::write(src.join("compat.cts"), "module.exports = {};").unwrap();
2252
2253 let config = make_config(dir.path().to_path_buf(), false);
2254 let files = discover_files(&config);
2255 let names = file_names(&files, dir.path());
2256
2257 assert!(names.contains(&"src/app.ts".to_string()));
2258 assert!(names.contains(&"src/component.tsx".to_string()));
2259 assert!(names.contains(&"src/utils.js".to_string()));
2260 assert!(names.contains(&"src/helper.jsx".to_string()));
2261 assert!(names.contains(&"src/config.mjs".to_string()));
2262 assert!(names.contains(&"src/legacy.cjs".to_string()));
2263 assert!(names.contains(&"src/types.mts".to_string()));
2264 assert!(names.contains(&"src/compat.cts".to_string()));
2265 }
2266
2267 #[test]
2268 fn compact_source_glob_preserves_discovered_file_inventory() {
2269 let dir = tempfile::tempdir().expect("create temp dir");
2270 let nested = dir.path().join("packages/ui/src/nested");
2271 std::fs::create_dir_all(&nested).unwrap();
2272
2273 let mut expected = Vec::new();
2274 for (index, extension) in SOURCE_EXTENSIONS.iter().enumerate() {
2275 let relative = format!("packages/ui/src/nested/source-{index}.{extension}");
2276 std::fs::write(dir.path().join(&relative), "export const value = 1;").unwrap();
2277 expected.push(relative);
2278 }
2279 for relative in [
2280 "packages/ui/src/nested/env.d.ts",
2281 "packages/ui/src/nested/generated.d.mts",
2282 "packages/ui/src/nested/compat.d.cts",
2283 ] {
2284 std::fs::write(dir.path().join(relative), "export type Value = string;").unwrap();
2285 expected.push(relative.to_string());
2286 }
2287 let rejected = [
2288 "packages/ui/src/nested/component.tsx.bak",
2289 "packages/ui/src/nested/component.tsxmap",
2290 "packages/ui/src/nested/component.TS",
2291 "packages/ui/src/nested/component.gqlx",
2292 "packages/ui/src/nested/component.htm",
2293 "packages/ui/src/nested/component",
2294 "packages/ui/src/nested/component.png",
2295 ];
2296 for relative in rejected {
2297 std::fs::write(dir.path().join(relative), "not source").unwrap();
2298 }
2299
2300 let config = make_config(dir.path().to_path_buf(), false);
2301 let names = file_names(&discover_files(&config), dir.path());
2302
2303 for relative in expected {
2304 assert!(
2305 names.contains(&relative),
2306 "missing supported source {relative}"
2307 );
2308 }
2309 for relative in rejected {
2310 assert!(
2311 !names.iter().any(|name| name == relative),
2312 "unexpected near-miss source {relative}"
2313 );
2314 }
2315 }
2316
2317 #[test]
2318 fn excludes_non_source_extensions() {
2319 let dir = tempfile::tempdir().expect("create temp dir");
2320 let src = dir.path().join("src");
2321 std::fs::create_dir_all(&src).unwrap();
2322
2323 std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
2324
2325 std::fs::write(src.join("data.json"), "{}").unwrap();
2326 std::fs::write(src.join("readme.md"), "# Hello").unwrap();
2327 std::fs::write(src.join("notes.txt"), "notes").unwrap();
2328 std::fs::write(src.join("logo.png"), [0u8; 8]).unwrap();
2329
2330 let config = make_config(dir.path().to_path_buf(), false);
2331 let files = discover_files(&config);
2332 let names = file_names(&files, dir.path());
2333
2334 assert_eq!(names.len(), 1, "only the .ts file should be discovered");
2335 assert!(names.contains(&"src/app.ts".to_string()));
2336 }
2337
2338 #[test]
2339 fn excludes_disallowed_hidden_directories() {
2340 let dir = tempfile::tempdir().expect("create temp dir");
2341
2342 let git_dir = dir.path().join(".git");
2343 std::fs::create_dir_all(&git_dir).unwrap();
2344 std::fs::write(git_dir.join("hooks.ts"), "// git hook").unwrap();
2345
2346 let idea_dir = dir.path().join(".idea");
2347 std::fs::create_dir_all(&idea_dir).unwrap();
2348 std::fs::write(idea_dir.join("workspace.ts"), "// idea").unwrap();
2349
2350 let cache_dir = dir.path().join(".cache");
2351 std::fs::create_dir_all(&cache_dir).unwrap();
2352 std::fs::write(cache_dir.join("cached.js"), "// cached").unwrap();
2353
2354 let src = dir.path().join("src");
2355 std::fs::create_dir_all(&src).unwrap();
2356 std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
2357
2358 let config = make_config(dir.path().to_path_buf(), false);
2359 let files = discover_files(&config);
2360 let names = file_names(&files, dir.path());
2361
2362 assert_eq!(names.len(), 1, "only src/app.ts should be discovered");
2363 assert!(names.contains(&"src/app.ts".to_string()));
2364 }
2365
2366 #[test]
2367 fn includes_allowed_hidden_directories() {
2368 let dir = tempfile::tempdir().expect("create temp dir");
2369
2370 let storybook = dir.path().join(".storybook");
2371 std::fs::create_dir_all(&storybook).unwrap();
2372 std::fs::write(storybook.join("main.ts"), "export default {};").unwrap();
2373
2374 let github = dir.path().join(".github");
2375 std::fs::create_dir_all(&github).unwrap();
2376 std::fs::write(github.join("actions.js"), "module.exports = {};").unwrap();
2377
2378 let changeset = dir.path().join(".changeset");
2379 std::fs::create_dir_all(&changeset).unwrap();
2380 std::fs::write(changeset.join("config.js"), "module.exports = {};").unwrap();
2381
2382 let config = make_config(dir.path().to_path_buf(), false);
2383 let files = discover_files(&config);
2384 let names = file_names(&files, dir.path());
2385
2386 assert!(
2387 names.contains(&".storybook/main.ts".to_string()),
2388 "files in .storybook should be discovered"
2389 );
2390 assert!(
2391 names.contains(&".github/actions.js".to_string()),
2392 "files in .github should be discovered"
2393 );
2394 assert!(
2395 names.contains(&".changeset/config.js".to_string()),
2396 "files in .changeset should be discovered"
2397 );
2398 }
2399
2400 #[test]
2401 fn default_discovery_excludes_client_and_server_hidden_directories() {
2402 let dir = tempfile::tempdir().expect("create temp dir");
2403 let app = dir.path().join("app");
2404 std::fs::create_dir_all(app.join(".client")).unwrap();
2405 std::fs::create_dir_all(app.join(".server")).unwrap();
2406 std::fs::write(app.join(".client/analytics.ts"), "export const a = 1;").unwrap();
2407 std::fs::write(app.join(".server/db.ts"), "export const db = {};").unwrap();
2408 std::fs::write(app.join("root.tsx"), "export default function Root() {}").unwrap();
2409
2410 let config = make_config(dir.path().to_path_buf(), false);
2411 let files = discover_files(&config);
2412 let names = file_names(&files, dir.path());
2413
2414 assert!(names.contains(&"app/root.tsx".to_string()));
2415 assert!(!names.contains(&"app/.client/analytics.ts".to_string()));
2416 assert!(!names.contains(&"app/.server/db.ts".to_string()));
2417 }
2418
2419 #[test]
2420 fn scoped_hidden_dirs_include_client_and_server_under_package_root() {
2421 let dir = tempfile::tempdir().expect("create temp dir");
2422 let package = dir.path().join("packages/app");
2423 std::fs::create_dir_all(package.join("app/.client")).unwrap();
2424 std::fs::create_dir_all(package.join("app/.server")).unwrap();
2425 std::fs::write(
2426 package.join("app/.client/analytics.ts"),
2427 "export const track = () => {};",
2428 )
2429 .unwrap();
2430 std::fs::write(package.join("app/.server/db.ts"), "export const db = {};").unwrap();
2431
2432 let config = make_config(dir.path().to_path_buf(), false);
2433 let scopes = [HiddenDirScope::new(
2434 package,
2435 vec![".client".to_string(), ".server".to_string()],
2436 )];
2437 let files = discover_files_with_additional_hidden_dirs(&config, &scopes);
2438 let names = file_names(&files, dir.path());
2439
2440 assert!(names.contains(&"packages/app/app/.client/analytics.ts".to_string()));
2441 assert!(names.contains(&"packages/app/app/.server/db.ts".to_string()));
2442 }
2443
2444 #[test]
2445 fn scoped_hidden_dirs_do_not_include_unscoped_packages() {
2446 let dir = tempfile::tempdir().expect("create temp dir");
2447 let active = dir.path().join("packages/active");
2448 let inactive = dir.path().join("packages/inactive");
2449 std::fs::create_dir_all(active.join("app/.server")).unwrap();
2450 std::fs::create_dir_all(inactive.join("app/.server")).unwrap();
2451 std::fs::write(active.join("app/.server/db.ts"), "export const db = {};").unwrap();
2452 std::fs::write(inactive.join("app/.server/db.ts"), "export const db = {};").unwrap();
2453
2454 let config = make_config(dir.path().to_path_buf(), false);
2455 let scopes = [HiddenDirScope::new(active, vec![".server".to_string()])];
2456 let files = discover_files_with_additional_hidden_dirs(&config, &scopes);
2457 let names = file_names(&files, dir.path());
2458
2459 assert!(names.contains(&"packages/active/app/.server/db.ts".to_string()));
2460 assert!(!names.contains(&"packages/inactive/app/.server/db.ts".to_string()));
2461 }
2462
2463 #[test]
2464 fn exact_path_scope_does_not_admit_the_same_name_elsewhere() {
2465 let dir = tempfile::tempdir().expect("create temp dir");
2469 std::fs::create_dir_all(dir.path().join(".a/.b")).unwrap();
2470 std::fs::create_dir_all(dir.path().join("elsewhere/.b")).unwrap();
2471 std::fs::create_dir_all(dir.path().join("unrelated/.a")).unwrap();
2472 std::fs::write(dir.path().join(".a/.b/deep.mjs"), "export const a = 1;").unwrap();
2473 std::fs::write(dir.path().join("elsewhere/.b/y.mjs"), "export const b = 1;").unwrap();
2474 std::fs::write(dir.path().join("unrelated/.a/u.mjs"), "export const c = 1;").unwrap();
2475
2476 let config = make_config(dir.path().to_path_buf(), false);
2477 let scopes = [HiddenDirScope::new_exact_paths(
2478 dir.path().to_path_buf(),
2479 vec![".a".to_string(), format!(".a{MAIN_SEPARATOR}.b")],
2480 )];
2481 let files = discover_files_with_additional_hidden_dirs(&config, &scopes);
2482 let names = file_names(&files, dir.path());
2483
2484 assert!(names.contains(&".a/.b/deep.mjs".to_string()));
2485 assert!(!names.contains(&"elsewhere/.b/y.mjs".to_string()));
2486 assert!(!names.contains(&"unrelated/.a/u.mjs".to_string()));
2487 }
2488
2489 #[test]
2490 fn exact_path_scope_admits_a_hidden_dir_under_a_visible_parent() {
2491 let dir = tempfile::tempdir().expect("create temp dir");
2492 std::fs::create_dir_all(dir.path().join("tools/.config")).unwrap();
2493 std::fs::create_dir_all(dir.path().join("other/.config")).unwrap();
2494 std::fs::write(
2495 dir.path().join("tools/.config/eslint.config.js"),
2496 "export default [];",
2497 )
2498 .unwrap();
2499 std::fs::write(
2500 dir.path().join("other/.config/eslint.config.js"),
2501 "export default [];",
2502 )
2503 .unwrap();
2504
2505 let config = make_config(dir.path().to_path_buf(), false);
2506 let scopes = [HiddenDirScope::new_exact_paths(
2507 dir.path().to_path_buf(),
2508 vec![format!("tools{MAIN_SEPARATOR}.config")],
2509 )];
2510 let files = discover_files_with_additional_hidden_dirs(&config, &scopes);
2511 let names = file_names(&files, dir.path());
2512
2513 assert!(names.contains(&"tools/.config/eslint.config.js".to_string()));
2514 assert!(!names.contains(&"other/.config/eslint.config.js".to_string()));
2515 }
2516
2517 #[test]
2518 fn any_depth_scope_keeps_matching_by_name_for_plugins() {
2519 let dir = tempfile::tempdir().expect("create temp dir");
2523 std::fs::create_dir_all(dir.path().join("app/routes/deep/.server")).unwrap();
2524 std::fs::write(
2525 dir.path().join("app/routes/deep/.server/db.ts"),
2526 "export const db = {};",
2527 )
2528 .unwrap();
2529
2530 let config = make_config(dir.path().to_path_buf(), false);
2531 let scopes = [HiddenDirScope::new(
2532 dir.path().to_path_buf(),
2533 vec![".server".to_string()],
2534 )];
2535 let files = discover_files_with_additional_hidden_dirs(&config, &scopes);
2536 let names = file_names(&files, dir.path());
2537
2538 assert!(names.contains(&"app/routes/deep/.server/db.ts".to_string()));
2539 }
2540
2541 #[test]
2542 fn excludes_root_build_directory() {
2543 let dir = tempfile::tempdir().expect("create temp dir");
2544
2545 std::fs::write(dir.path().join(".ignore"), "/build/\n").unwrap();
2546
2547 let build_dir = dir.path().join("build");
2548 std::fs::create_dir_all(&build_dir).unwrap();
2549 std::fs::write(build_dir.join("output.js"), "// build output").unwrap();
2550
2551 let src = dir.path().join("src");
2552 std::fs::create_dir_all(&src).unwrap();
2553 std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
2554
2555 let config = make_config(dir.path().to_path_buf(), false);
2556 let files = discover_files(&config);
2557 let names = file_names(&files, dir.path());
2558
2559 assert_eq!(names.len(), 1, "root build/ should be excluded via .ignore");
2560 assert!(names.contains(&"src/app.ts".to_string()));
2561 }
2562
2563 #[test]
2564 fn excludes_nested_build_directory() {
2565 let dir = tempfile::tempdir().expect("create temp dir");
2566
2567 let nested_build = dir.path().join("src").join("build");
2568 std::fs::create_dir_all(&nested_build).unwrap();
2569 std::fs::write(nested_build.join("helper.ts"), "export const h = 1;").unwrap();
2570
2571 let config = make_config(dir.path().to_path_buf(), false);
2572 let files = discover_files(&config);
2573 let names = file_names(&files, dir.path());
2574
2575 assert!(
2576 !names.contains(&"src/build/helper.ts".to_string()),
2577 "build/ is treated as generated output at any depth: {names:?}"
2578 );
2579 }
2580
2581 #[test]
2582 #[expect(
2583 clippy::cast_possible_truncation,
2584 reason = "test file counts are trivially small"
2585 )]
2586 fn file_ids_are_sequential_after_sorting() {
2587 let dir = tempfile::tempdir().expect("create temp dir");
2588 let src = dir.path().join("src");
2589 std::fs::create_dir_all(&src).unwrap();
2590
2591 std::fs::write(src.join("z_last.ts"), "export const z = 1;").unwrap();
2592 std::fs::write(src.join("a_first.ts"), "export const a = 1;").unwrap();
2593 std::fs::write(src.join("m_middle.ts"), "export const m = 1;").unwrap();
2594
2595 let config = make_config(dir.path().to_path_buf(), false);
2596 let files = discover_files(&config);
2597
2598 for (idx, file) in files.iter().enumerate() {
2599 assert_eq!(file.id, FileId(idx as u32), "FileId should be sequential");
2600 }
2601
2602 for pair in files.windows(2) {
2603 assert!(
2604 pair[0].path < pair[1].path,
2605 "files should be sorted by path"
2606 );
2607 }
2608 }
2609
2610 #[test]
2611 fn production_mode_excludes_test_files() {
2612 let dir = tempfile::tempdir().expect("create temp dir");
2613 let src = dir.path().join("src");
2614 std::fs::create_dir_all(&src).unwrap();
2615
2616 std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
2617 std::fs::write(src.join("app.test.ts"), "test('a', () => {});").unwrap();
2618 std::fs::write(src.join("app.spec.ts"), "describe('a', () => {});").unwrap();
2619 std::fs::write(src.join("app.stories.tsx"), "export default {};").unwrap();
2620
2621 let config = make_config(dir.path().to_path_buf(), true);
2622 let files = discover_files(&config);
2623 let names = file_names(&files, dir.path());
2624
2625 assert!(
2626 names.contains(&"src/app.ts".to_string()),
2627 "source files should be included in production mode"
2628 );
2629 assert!(
2630 !names.contains(&"src/app.test.ts".to_string()),
2631 "test files should be excluded in production mode"
2632 );
2633 assert!(
2634 !names.contains(&"src/app.spec.ts".to_string()),
2635 "spec files should be excluded in production mode"
2636 );
2637 assert!(
2638 !names.contains(&"src/app.stories.tsx".to_string()),
2639 "story files should be excluded in production mode"
2640 );
2641 }
2642
2643 #[test]
2644 fn non_production_mode_includes_test_files() {
2645 let dir = tempfile::tempdir().expect("create temp dir");
2646 let src = dir.path().join("src");
2647 std::fs::create_dir_all(&src).unwrap();
2648
2649 std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
2650 std::fs::write(src.join("app.test.ts"), "test('a', () => {});").unwrap();
2651
2652 let config = make_config(dir.path().to_path_buf(), false);
2653 let files = discover_files(&config);
2654 let names = file_names(&files, dir.path());
2655
2656 assert!(names.contains(&"src/app.ts".to_string()));
2657 assert!(
2658 names.contains(&"src/app.test.ts".to_string()),
2659 "test files should be included in non-production mode"
2660 );
2661 }
2662
2663 #[test]
2664 fn empty_directory_returns_no_files() {
2665 let dir = tempfile::tempdir().expect("create temp dir");
2666 let config = make_config(dir.path().to_path_buf(), false);
2667 let files = discover_files(&config);
2668 assert!(files.is_empty(), "empty project should discover no files");
2669 }
2670
2671 #[test]
2672 fn hidden_files_not_discovered_as_source() {
2673 let dir = tempfile::tempdir().expect("create temp dir");
2674
2675 std::fs::write(dir.path().join(".env"), "SECRET=abc").unwrap();
2676 std::fs::write(dir.path().join(".gitignore"), "node_modules").unwrap();
2677 std::fs::write(dir.path().join(".eslintrc.js"), "module.exports = {};").unwrap();
2678
2679 let src = dir.path().join("src");
2680 std::fs::create_dir_all(&src).unwrap();
2681 std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
2682
2683 let config = make_config(dir.path().to_path_buf(), false);
2684 let files = discover_files(&config);
2685 let names = file_names(&files, dir.path());
2686
2687 assert!(
2688 !names.contains(&".env".to_string()),
2689 ".env should not be discovered"
2690 );
2691 assert!(
2692 !names.contains(&".gitignore".to_string()),
2693 ".gitignore should not be discovered"
2694 );
2695 }
2696
2697 fn make_config_with_ignores(root: PathBuf, ignores: Vec<String>) -> ResolvedConfig {
2699 FallowConfig {
2700 type_aware: fallow_config::TypeAwareConfig::default(),
2701 schema: None,
2702 minimum_version: None,
2703 extends: vec![],
2704 entry: vec![],
2705 ignore_patterns: ignores,
2706 ignore_findings: vec![],
2707 framework: vec![],
2708 workspaces: None,
2709 ignore_dependencies: vec![],
2710 ignore_command_entries: vec![],
2711 ignore_unresolved_imports: vec![],
2712 ignore_exports: vec![],
2713 ignore_catalog_references: vec![],
2714 ignore_dependency_overrides: vec![],
2715 ignore_exports_used_in_file: fallow_config::IgnoreExportsUsedInFileConfig::default(
2716 ),
2717 used_class_members: vec![],
2718 ignore_decorators: vec![],
2719 unused_component_props: fallow_config::UnusedComponentPropsConfig::default(),
2720 circular_dependencies: fallow_config::CircularDependenciesConfig::default(),
2721 duplicates: DuplicatesConfig::default(),
2722 similar_code: fallow_config::SimilarCodeConfig::default(),
2723 mutation: fallow_config::MutationConfig::default(),
2724 health: HealthConfig::default(),
2725 rules: RulesConfig::default(),
2726 boundaries: fallow_config::BoundaryConfig::default(),
2727 production: false.into(),
2728 plugins: vec![],
2729 rule_packs: vec![],
2730 overrides: vec![],
2731 regression: None,
2732 audit: fallow_config::AuditConfig::default(),
2733 codeowners: None,
2734 public_packages: vec![],
2735 flags: FlagsConfig::default(),
2736 security: fallow_config::SecurityConfig::default(),
2737 fix: fallow_config::FixConfig::default(),
2738 resolve: ResolveConfig::default(),
2739 sealed: false,
2740 include_entry_exports: false,
2741 show_cascade: false,
2742 auto_imports: false,
2743 fail_on_parse_error: false,
2744 cache: fallow_config::CacheConfig::default(),
2745 ..Default::default()
2746 }
2747 .resolve(root, OutputFormat::Human, 1, true, true, None)
2748 }
2749
2750 #[test]
2751 fn custom_ignore_patterns_exclude_matching_files() {
2752 let dir = tempfile::tempdir().expect("create temp dir");
2753
2754 let generated = dir.path().join("src").join("api").join("generated");
2755 std::fs::create_dir_all(&generated).unwrap();
2756 std::fs::write(generated.join("client.ts"), "export const api = {};").unwrap();
2757
2758 let client = dir.path().join("src").join("api").join("client");
2759 std::fs::create_dir_all(&client).unwrap();
2760 std::fs::write(client.join("fetch.ts"), "export const fetch = {};").unwrap();
2761
2762 let src = dir.path().join("src");
2763 std::fs::write(src.join("index.ts"), "export const x = 1;").unwrap();
2764
2765 let config = make_config_with_ignores(
2766 dir.path().to_path_buf(),
2767 vec![
2768 "src/api/generated/**".to_string(),
2769 "src/api/client/**".to_string(),
2770 ],
2771 );
2772 let files = discover_files(&config);
2773 let names = file_names(&files, dir.path());
2774
2775 assert_eq!(names.len(), 1, "only non-ignored files: {names:?}");
2776 assert!(names.contains(&"src/index.ts".to_string()));
2777 }
2778
2779 #[test]
2780 fn leading_dot_ignore_patterns_exclude_matching_files() {
2781 let dir = tempfile::tempdir().expect("create temp dir");
2782
2783 let generated = dir.path().join("src").join("generated");
2784 std::fs::create_dir_all(&generated).unwrap();
2785 std::fs::write(generated.join("client.ts"), "export const api = {};").unwrap();
2786
2787 let src = dir.path().join("src");
2788 std::fs::write(src.join("index.ts"), "export const x = 1;").unwrap();
2789
2790 let config = make_config_with_ignores(
2791 dir.path().to_path_buf(),
2792 vec!["./src/generated/**".to_string()],
2793 );
2794 let files = discover_files(&config);
2795 let names = file_names(&files, dir.path());
2796
2797 assert_eq!(names, vec!["src/index.ts"]);
2798 }
2799
2800 #[test]
2801 fn default_ignore_patterns_exclude_node_modules_and_dist() {
2802 let dir = tempfile::tempdir().expect("create temp dir");
2803
2804 let nm = dir.path().join("node_modules").join("lodash");
2805 std::fs::create_dir_all(&nm).unwrap();
2806 std::fs::write(nm.join("lodash.js"), "module.exports = {};").unwrap();
2807
2808 let dist = dir.path().join("dist");
2809 std::fs::create_dir_all(&dist).unwrap();
2810 std::fs::write(dist.join("bundle.js"), "// bundled").unwrap();
2811
2812 let src = dir.path().join("src");
2813 std::fs::create_dir_all(&src).unwrap();
2814 std::fs::write(src.join("index.ts"), "export const x = 1;").unwrap();
2815
2816 let config = make_config(dir.path().to_path_buf(), false);
2817 let files = discover_files(&config);
2818 let names = file_names(&files, dir.path());
2819
2820 assert_eq!(names.len(), 1);
2821 assert!(names.contains(&"src/index.ts".to_string()));
2822 }
2823
2824 #[test]
2825 fn default_ignore_patterns_exclude_build_at_any_depth() {
2826 let dir = tempfile::tempdir().expect("create temp dir");
2827
2828 let build = dir.path().join("build");
2829 std::fs::create_dir_all(&build).unwrap();
2830 std::fs::write(build.join("output.js"), "// built").unwrap();
2831
2832 let nested_build = dir.path().join("src").join("build");
2833 std::fs::create_dir_all(&nested_build).unwrap();
2834 std::fs::write(nested_build.join("helper.ts"), "export const h = 1;").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(dir.path().to_path_buf(), false);
2840 let files = discover_files(&config);
2841 let names = file_names(&files, dir.path());
2842
2843 assert_eq!(names, vec!["src/index.ts".to_string()]);
2844 }
2845
2846 #[test]
2849 fn default_ignore_patterns_exclude_nested_build() {
2850 let dir = tempfile::tempdir().expect("create temp dir");
2851
2852 let build = dir.path().join("build");
2853 std::fs::create_dir_all(&build).unwrap();
2854 std::fs::write(build.join("output.js"), "// built").unwrap();
2855
2856 let package_build = dir.path().join("projects").join("app").join("build");
2857 std::fs::create_dir_all(&package_build).unwrap();
2858 std::fs::write(package_build.join("index.js"), "// built").unwrap();
2859
2860 let src = dir.path().join("src");
2861 std::fs::create_dir_all(&src).unwrap();
2862 std::fs::write(src.join("index.ts"), "export const x = 1;").unwrap();
2863
2864 let config = make_config(dir.path().to_path_buf(), false);
2865 let files = discover_files(&config);
2866 let names = file_names(&files, dir.path());
2867
2868 assert_eq!(names, vec!["src/index.ts".to_string()]);
2869 }
2870
2871 #[test]
2873 fn default_ignore_patterns_keep_paths_that_merely_contain_build() {
2874 let dir = tempfile::tempdir().expect("create temp dir");
2875
2876 let src = dir.path().join("src");
2877 std::fs::create_dir_all(src.join("rebuild")).unwrap();
2878 std::fs::create_dir_all(src.join("buildings")).unwrap();
2879 std::fs::write(src.join("build.ts"), "export const a = 1;").unwrap();
2880 std::fs::write(src.join("rebuild").join("helper.ts"), "export const b = 1;").unwrap();
2881 std::fs::write(src.join("buildings").join("a.ts"), "export const c = 1;").unwrap();
2882
2883 let config = make_config(dir.path().to_path_buf(), false);
2884 let files = discover_files(&config);
2885 let mut names = file_names(&files, dir.path());
2886 names.sort();
2887
2888 assert_eq!(
2889 names,
2890 vec![
2891 "src/build.ts".to_string(),
2892 "src/buildings/a.ts".to_string(),
2893 "src/rebuild/helper.ts".to_string(),
2894 ]
2895 );
2896 }
2897
2898 fn make_config_with_max_file_size(
2900 root: PathBuf,
2901 max_file_size_bytes: Option<u64>,
2902 ) -> ResolvedConfig {
2903 let mut config = make_config(root, false);
2904 config.max_file_size_bytes = max_file_size_bytes;
2905 config
2906 }
2907
2908 #[test]
2909 fn skips_files_over_max_file_size() {
2910 let dir = tempfile::tempdir().expect("create temp dir");
2911 let src = dir.path().join("src");
2912 std::fs::create_dir_all(&src).unwrap();
2913 std::fs::write(src.join("small.ts"), "export const a = 1;").unwrap();
2914 std::fs::write(src.join("huge.ts"), "x".repeat(5_000)).unwrap();
2915
2916 let config = make_config_with_max_file_size(dir.path().to_path_buf(), Some(1_000));
2917 let files = discover_files(&config);
2918 let names = file_names(&files, dir.path());
2919
2920 assert!(names.contains(&"src/small.ts".to_string()));
2921 assert!(
2922 !names.contains(&"src/huge.ts".to_string()),
2923 "a file over the size limit must not be discovered"
2924 );
2925 }
2926
2927 #[test]
2928 fn declaration_files_exempt_from_size_skip() {
2929 let dir = tempfile::tempdir().expect("create temp dir");
2930 let src = dir.path().join("src");
2931 std::fs::create_dir_all(&src).unwrap();
2932 std::fs::write(src.join("auto-imports.d.ts"), "x".repeat(5_000)).unwrap();
2933 std::fs::write(src.join("huge.ts"), "x".repeat(5_000)).unwrap();
2934
2935 let config = make_config_with_max_file_size(dir.path().to_path_buf(), Some(1_000));
2936 let files = discover_files(&config);
2937 let names = file_names(&files, dir.path());
2938
2939 assert!(
2940 names.contains(&"src/auto-imports.d.ts".to_string()),
2941 "a large .d.ts is exempt from the skip (reachability root for global types)"
2942 );
2943 assert!(!names.contains(&"src/huge.ts".to_string()));
2944 }
2945
2946 #[test]
2947 fn unlimited_size_keeps_large_files() {
2948 let dir = tempfile::tempdir().expect("create temp dir");
2949 let src = dir.path().join("src");
2950 std::fs::create_dir_all(&src).unwrap();
2951 std::fs::write(src.join("huge.ts"), "x".repeat(5_000)).unwrap();
2952
2953 let config = make_config_with_max_file_size(dir.path().to_path_buf(), None);
2954 let files = discover_files(&config);
2955 let names = file_names(&files, dir.path());
2956
2957 assert!(
2958 names.contains(&"src/huge.ts".to_string()),
2959 "no limit keeps every file"
2960 );
2961 }
2962
2963 #[test]
2964 fn skipped_file_recorded_in_workspace_diagnostics() {
2965 let dir = tempfile::tempdir().expect("create temp dir");
2966 let src = dir.path().join("src");
2967 std::fs::create_dir_all(&src).unwrap();
2968 std::fs::write(src.join("huge.ts"), "x".repeat(5_000)).unwrap();
2969
2970 let config = make_config_with_max_file_size(dir.path().to_path_buf(), Some(1_000));
2971 let _ = discover_files(&config);
2972
2973 let diagnostics = fallow_config::workspace_diagnostics_for(dir.path());
2974 let skipped: Vec<_> = diagnostics
2975 .iter()
2976 .filter(|d| {
2977 matches!(
2978 d.kind,
2979 fallow_config::WorkspaceDiagnosticKind::SkippedLargeFile { .. }
2980 )
2981 })
2982 .collect();
2983 assert_eq!(
2984 skipped.len(),
2985 1,
2986 "the skipped file is recorded in workspace diagnostics for JSON output"
2987 );
2988 assert!(skipped[0].path.ends_with("src/huge.ts"));
2989 assert!(
2990 matches!(
2991 skipped[0].kind,
2992 fallow_config::WorkspaceDiagnosticKind::SkippedLargeFile { size_bytes }
2993 if size_bytes == 5_000
2994 ),
2995 "the recorded diagnostic carries the on-disk byte size"
2996 );
2997 }
2998
2999 fn dotdir_diagnostics(root: &Path) -> Vec<fallow_config::WorkspaceDiagnostic> {
3001 fallow_config::workspace_diagnostics_for(root)
3002 .into_iter()
3003 .filter(|d| {
3004 matches!(
3005 d.kind,
3006 fallow_config::WorkspaceDiagnosticKind::SkippedSourceDotdir
3007 )
3008 })
3009 .collect()
3010 }
3011
3012 fn write_at(root: &Path, relative: &str, contents: &str) {
3013 let path = root.join(relative);
3014 std::fs::create_dir_all(path.parent().expect("has a parent")).unwrap();
3015 std::fs::write(path, contents).unwrap();
3016 }
3017
3018 #[test]
3019 fn skipped_source_dotdir_recorded_in_workspace_diagnostics() {
3020 let dir = tempfile::tempdir().expect("create temp dir");
3021 write_at(
3022 dir.path(),
3023 ".claude/hooks/probe.mjs",
3024 "export const a = 1;\n",
3025 );
3026 write_at(dir.path(), "src/app.ts", "export const b = 2;\n");
3027
3028 let config = make_config(dir.path().to_path_buf(), false);
3029 let files = discover_files(&config);
3030 let names = file_names(&files, dir.path());
3031
3032 let reported = dotdir_diagnostics(dir.path());
3033 assert_eq!(reported.len(), 1, "one skipped dotdir holds source files");
3034 assert!(reported[0].path.ends_with(".claude"));
3035 assert_eq!(reported[0].kind.id(), "skipped-source-dotdir");
3036 assert!(
3037 reported[0].message.contains("--root"),
3038 "message names the real remedy: {}",
3039 reported[0].message
3040 );
3041 assert!(
3042 names.contains(&"src/app.ts".to_string()),
3043 "traversal is unchanged for ordinary directories"
3044 );
3045 assert!(
3046 !names.contains(&".claude/hooks/probe.mjs".to_string()),
3047 "the diagnostic reports the skip, it does not change traversal"
3048 );
3049 }
3050
3051 #[test]
3052 fn allowlisted_dotdir_is_not_reported() {
3053 let dir = tempfile::tempdir().expect("create temp dir");
3054 write_at(dir.path(), ".storybook/main.ts", "export const a = 1;\n");
3055
3056 let config = make_config(dir.path().to_path_buf(), false);
3057 let files = discover_files(&config);
3058 let names = file_names(&files, dir.path());
3059
3060 assert!(dotdir_diagnostics(dir.path()).is_empty());
3061 assert!(
3062 names.contains(&".storybook/main.ts".to_string()),
3063 "an allowlisted dotdir is still traversed"
3064 );
3065 }
3066
3067 #[test]
3068 fn denylisted_dotdir_is_not_reported() {
3069 let dir = tempfile::tempdir().expect("create temp dir");
3070 write_at(dir.path(), ".idea/workspace.ts", "export const a = 1;\n");
3071 write_at(dir.path(), ".husky/hook.js", "export const b = 2;\n");
3072 write_at(dir.path(), ".next/page.js", "export const c = 3;\n");
3073 write_at(dir.path(), ".pnpm/x.js", "export const d = 4;\n");
3074
3075 let config = make_config(dir.path().to_path_buf(), false);
3076 let _ = discover_files(&config);
3077
3078 assert!(
3079 dotdir_diagnostics(dir.path()).is_empty(),
3080 "build caches, VCS and package-manager state never advise"
3081 );
3082 }
3083
3084 #[test]
3085 fn scoped_dotdir_is_traversed_and_not_reported() {
3086 let dir = tempfile::tempdir().expect("create temp dir");
3087 write_at(
3088 dir.path(),
3089 ".claude/hooks/probe.mjs",
3090 "export const a = 1;\n",
3091 );
3092
3093 let config = make_config(dir.path().to_path_buf(), false);
3094 let scopes = [HiddenDirScope::new(
3095 dir.path().to_path_buf(),
3096 vec![".claude".to_owned()],
3097 )];
3098 let files = discover_files_with_additional_hidden_dirs(&config, &scopes);
3099 let names = file_names(&files, dir.path());
3100
3101 assert!(
3102 dotdir_diagnostics(dir.path()).is_empty(),
3103 "a plugin- or script-contributed scope is admitted, so nothing was skipped"
3104 );
3105 assert!(names.contains(&".claude/hooks/probe.mjs".to_string()));
3106 }
3107
3108 #[test]
3109 fn ignore_patterns_silence_the_skipped_source_dotdir() {
3110 let dir = tempfile::tempdir().expect("create temp dir");
3111 write_at(
3112 dir.path(),
3113 ".claude/hooks/probe.mjs",
3114 "export const a = 1;\n",
3115 );
3116
3117 let config =
3118 make_config_with_ignores(dir.path().to_path_buf(), vec![".claude/**".to_owned()]);
3119 let _ = discover_files(&config);
3120
3121 assert!(
3122 dotdir_diagnostics(dir.path()).is_empty(),
3123 "the documented silencing route works"
3124 );
3125 }
3126
3127 #[test]
3128 fn dotdir_without_source_files_is_not_reported() {
3129 let dir = tempfile::tempdir().expect("create temp dir");
3130 write_at(dir.path(), ".claude/settings.json", "{}\n");
3131 write_at(dir.path(), ".claude/README.md", "# notes\n");
3132
3133 let config = make_config(dir.path().to_path_buf(), false);
3134 let _ = discover_files(&config);
3135
3136 assert!(dotdir_diagnostics(dir.path()).is_empty());
3137 }
3138
3139 #[test]
3140 fn dotdir_source_at_scan_depth_limit_is_reported() {
3141 let dir = tempfile::tempdir().expect("create temp dir");
3142 write_at(dir.path(), ".claude/a/b/deep.ts", "export const a = 1;\n");
3143
3144 let config = make_config(dir.path().to_path_buf(), false);
3145 let _ = discover_files(&config);
3146
3147 assert_eq!(dotdir_diagnostics(dir.path()).len(), 1);
3148 }
3149
3150 #[test]
3151 fn dotdir_source_below_scan_depth_limit_is_not_reported() {
3152 let dir = tempfile::tempdir().expect("create temp dir");
3153 write_at(
3154 dir.path(),
3155 ".claude/a/b/c/deeper.ts",
3156 "export const a = 1;\n",
3157 );
3158
3159 let config = make_config(dir.path().to_path_buf(), false);
3160 let _ = discover_files(&config);
3161
3162 assert!(
3163 dotdir_diagnostics(dir.path()).is_empty(),
3164 "the depth cap is real, so widening it stays a deliberate act"
3165 );
3166 }
3167
3168 fn mark_as_git_repo(root: &Path) {
3172 std::fs::create_dir_all(root.join(".git")).expect("create .git marker");
3173 }
3174
3175 #[test]
3176 fn gitignored_dotdir_contents_are_not_reported() {
3177 for pattern in [".tooling/**", ".tooling/*", "**/.tooling/**", "*.ts"] {
3181 let dir = tempfile::tempdir().expect("create temp dir");
3182 mark_as_git_repo(dir.path());
3183 write_at(dir.path(), ".gitignore", &format!("{pattern}\n"));
3184 write_at(dir.path(), ".tooling/mod.ts", "export const a = 1;\n");
3185
3186 let config = make_config(dir.path().to_path_buf(), false);
3187 let _ = discover_files(&config);
3188
3189 assert!(
3190 dotdir_diagnostics(dir.path()).is_empty(),
3191 "gitignore pattern '{pattern}' excludes the contents, so neither \
3192 advertised remedy would find anything there"
3193 );
3194 }
3195 }
3196
3197 #[test]
3198 fn self_ignoring_dotdir_is_not_reported() {
3199 let dir = tempfile::tempdir().expect("create temp dir");
3200 mark_as_git_repo(dir.path());
3201 write_at(dir.path(), ".toolcache/.gitignore", "*\n");
3202 write_at(dir.path(), ".toolcache/mod.ts", "export const a = 1;\n");
3203
3204 let config = make_config(dir.path().to_path_buf(), false);
3205 let _ = discover_files(&config);
3206
3207 assert!(
3208 dotdir_diagnostics(dir.path()).is_empty(),
3209 "a cache directory that ignores itself has excluded its own contents"
3210 );
3211 }
3212
3213 #[test]
3214 fn ungitignored_dotdir_in_a_git_repo_is_still_reported() {
3215 let dir = tempfile::tempdir().expect("create temp dir");
3216 mark_as_git_repo(dir.path());
3217 write_at(dir.path(), ".gitignore", "dist/\n");
3218 write_at(dir.path(), ".tooling/mod.ts", "export const a = 1;\n");
3219
3220 let config = make_config(dir.path().to_path_buf(), false);
3221 let _ = discover_files(&config);
3222
3223 assert_eq!(
3224 dotdir_diagnostics(dir.path()).len(),
3225 1,
3226 "the gitignore check must not swallow the case the diagnostic exists for"
3227 );
3228 }
3229
3230 #[test]
3231 fn production_run_does_not_report_a_test_only_dotdir() {
3232 let dir = tempfile::tempdir().expect("create temp dir");
3233 write_at(dir.path(), ".qa/thing.test.ts", "export const a = 1;\n");
3234 write_at(dir.path(), ".qa/thing.stories.tsx", "export const b = 2;\n");
3235
3236 let config = make_config(dir.path().to_path_buf(), true);
3237 let _ = discover_files(&config);
3238
3239 assert!(
3240 dotdir_diagnostics(dir.path()).is_empty(),
3241 "a --production run would analyze none of those files, so the \
3242 --root remedy would return nothing"
3243 );
3244 }
3245
3246 #[test]
3247 fn production_run_still_reports_a_dotdir_with_production_source() {
3248 let dir = tempfile::tempdir().expect("create temp dir");
3249 write_at(dir.path(), ".qa/thing.test.ts", "export const a = 1;\n");
3250 write_at(dir.path(), ".qa/helper.ts", "export const b = 2;\n");
3251
3252 let config = make_config(dir.path().to_path_buf(), true);
3253 let _ = discover_files(&config);
3254
3255 assert_eq!(dotdir_diagnostics(dir.path()).len(), 1);
3256 }
3257
3258 #[test]
3259 fn dotdir_with_only_generated_markup_is_not_reported() {
3260 let dir = tempfile::tempdir().expect("create temp dir");
3261 write_at(dir.path(), ".lighthouseci/lhr-1.html", "<html></html>\n");
3262 write_at(dir.path(), ".styles/theme.css", ":root { color: red; }\n");
3263 write_at(dir.path(), ".gql/schema.graphql", "type Query { a: Int }\n");
3264
3265 let config = make_config(dir.path().to_path_buf(), false);
3266 let _ = discover_files(&config);
3267
3268 assert!(
3269 dotdir_diagnostics(dir.path()).is_empty(),
3270 "the message claims imports and exports are lost, and these have none"
3271 );
3272 }
3273
3274 #[test]
3275 fn generated_tool_and_foreign_vcs_dotdirs_are_not_reported() {
3276 let dir = tempfile::tempdir().expect("create temp dir");
3277 write_at(dir.path(), ".astro/types.d.ts", "export {};\n");
3278 write_at(dir.path(), ".wxt/types/imports.d.ts", "export {};\n");
3279 write_at(dir.path(), ".yalc/pkg/index.js", "export const a = 1;\n");
3280 write_at(dir.path(), ".jj/repo/config.js", "export const b = 2;\n");
3281 write_at(dir.path(), ".svn/pristine/y.js", "export const c = 3;\n");
3282
3283 let config = make_config(dir.path().to_path_buf(), false);
3284 let _ = discover_files(&config);
3285
3286 assert!(
3287 dotdir_diagnostics(dir.path()).is_empty(),
3288 "generated output and foreign VCS metadata are not first-party source"
3289 );
3290 }
3291
3292 #[test]
3293 fn denylisted_dotdirs_do_not_consume_the_candidate_ceiling() {
3294 let dir = tempfile::tempdir().expect("create temp dir");
3295 for index in 0..(DOTDIR_SCAN_MAX_CANDIDATES + 8) {
3298 write_at(
3299 dir.path(),
3300 &format!("packages/pkg{index:03}/.turbo/blob.js"),
3301 "export const a = 1;\n",
3302 );
3303 }
3304 write_at(dir.path(), "zz/.tooling/mod.ts", "export const b = 2;\n");
3305
3306 let config = make_config(dir.path().to_path_buf(), false);
3307 let _ = discover_files(&config);
3308
3309 let reported = dotdir_diagnostics(dir.path());
3310 assert_eq!(reported.len(), 1, "{reported:?}");
3311 assert!(reported[0].path.ends_with(".tooling"));
3312 }
3313
3314 #[test]
3315 fn one_pathological_dotdir_cannot_starve_the_rest() {
3316 let dir = tempfile::tempdir().expect("create temp dir");
3317 for index in 0..(DOTDIR_SCAN_MAX_ENTRIES * 2) {
3319 write_at(dir.path(), &format!(".aaa-noise/f{index}.bin"), "x");
3320 }
3321 write_at(dir.path(), ".zzz-real/mod.ts", "export const a = 1;\n");
3322
3323 let config = make_config(dir.path().to_path_buf(), false);
3324 let _ = discover_files(&config);
3325
3326 let reported = dotdir_diagnostics(dir.path());
3327 assert_eq!(reported.len(), 1, "{reported:?}");
3328 assert!(reported[0].path.ends_with(".zzz-real"));
3329 }
3330
3331 #[test]
3332 fn repeat_walks_do_not_stack_skipped_source_dotdirs() {
3333 let dir = tempfile::tempdir().expect("create temp dir");
3334 write_at(
3335 dir.path(),
3336 ".claude/hooks/probe.mjs",
3337 "export const a = 1;\n",
3338 );
3339
3340 let config = make_config(dir.path().to_path_buf(), false);
3341 let _ = discover_files(&config);
3342 let _ = discover_files(&config);
3343
3344 assert_eq!(
3345 dotdir_diagnostics(dir.path()).len(),
3346 1,
3347 "each walk replaces its own root's source-discovery set"
3348 );
3349 }
3350
3351 #[test]
3352 fn skips_large_one_line_js_as_minified_generated_output() {
3353 let dir = tempfile::tempdir().expect("create temp dir");
3354 let src = dir.path().join("src");
3355 std::fs::create_dir_all(&src).unwrap();
3356 let asset = src.join("index-abc123.js");
3357 std::fs::write(&asset, "x".repeat(MINIFIED_FILE_SKIP_BYTES as usize + 1)).unwrap();
3358
3359 let config = make_config(dir.path().to_path_buf(), false);
3360 let files = discover_files(&config);
3361 let names = file_names(&files, dir.path());
3362
3363 assert!(
3364 !names.contains(&"src/index-abc123.js".to_string()),
3365 "large one-line JS assets should be skipped before parsing"
3366 );
3367
3368 let diagnostics = fallow_config::workspace_diagnostics_for(dir.path());
3369 assert!(
3370 diagnostics.iter().any(|diag| {
3371 diag.path.ends_with("src/index-abc123.js")
3372 && matches!(
3373 diag.kind,
3374 fallow_config::WorkspaceDiagnosticKind::SkippedMinifiedFile { .. }
3375 )
3376 }),
3377 "the skipped minified asset is recorded for JSON output: {diagnostics:?}"
3378 );
3379 }
3380
3381 #[test]
3382 fn unlimited_size_keeps_large_one_line_js() {
3383 let dir = tempfile::tempdir().expect("create temp dir");
3384 let src = dir.path().join("src");
3385 std::fs::create_dir_all(&src).unwrap();
3386 let asset = src.join("index-abc123.js");
3387 std::fs::write(&asset, "x".repeat(MINIFIED_FILE_SKIP_BYTES as usize + 1)).unwrap();
3388
3389 let config = make_config_with_max_file_size(dir.path().to_path_buf(), None);
3390 let files = discover_files(&config);
3391 let names = file_names(&files, dir.path());
3392
3393 assert!(
3394 names.contains(&"src/index-abc123.js".to_string()),
3395 "--max-file-size 0 should opt out of generated JS skipping"
3396 );
3397 }
3398
3399 #[test]
3400 fn keeps_large_multiline_js() {
3401 let dir = tempfile::tempdir().expect("create temp dir");
3402 let src = dir.path().join("src");
3403 std::fs::create_dir_all(&src).unwrap();
3404 let asset = src.join("handwritten.js");
3405 let mut content = String::new();
3406 while content.len() <= MINIFIED_FILE_SKIP_BYTES as usize + 1 {
3407 content.push_str("export const value = 1;\n");
3408 }
3409 std::fs::write(&asset, content).unwrap();
3410
3411 let config = make_config(dir.path().to_path_buf(), false);
3412 let files = discover_files(&config);
3413 let names = file_names(&files, dir.path());
3414
3415 assert!(
3416 names.contains(&"src/handwritten.js".to_string()),
3417 "large multiline JS should not be treated as a generated minified asset"
3418 );
3419 }
3420 }
3421}