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