1use std::ffi::OsStr;
2use std::path::{Path, PathBuf};
3use std::sync::{Mutex, OnceLock};
4
5use fallow_config::{ResolvedConfig, WorkspaceDiagnostic, WorkspaceDiagnosticKind};
6use fallow_types::discover::{DiscoveredFile, FileId};
7use ignore::WalkBuilder;
8use rustc_hash::FxHashSet;
9
10use super::ALLOWED_HIDDEN_DIRS;
11
12fn should_emit_note_once(key: String) -> bool {
18 static EMITTED: OnceLock<Mutex<FxHashSet<String>>> = OnceLock::new();
19 EMITTED
20 .get_or_init(|| Mutex::new(FxHashSet::default()))
21 .lock()
22 .map_or(true, |mut set| set.insert(key))
23}
24
25type SizedFile = (PathBuf, u64);
28
29const NOTE_EXAMPLE_CAP: usize = 5;
33
34const LARGE_SET_THRESHOLD: usize = 20_000;
38
39const LARGE_FILE_NOTE_BYTES: u64 = 4 * 1024 * 1024;
44
45const NOTE_FILE_FLOOR_BYTES: u64 = 256 * 1024;
49
50const MINIFIED_FILE_SKIP_BYTES: u64 = 1024 * 1024;
54
55const MINIFIED_SAMPLE_BYTES: usize = 256 * 1024;
57
58const MINIFIED_LONG_LINE_BYTES: usize = 128 * 1024;
61
62fn is_declaration_file(path: &Path) -> bool {
67 let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
68 name.ends_with(".d.ts") || name.ends_with(".d.mts") || name.ends_with(".d.cts")
69}
70
71fn is_plain_js_file(path: &Path) -> bool {
72 matches!(
73 path.extension().and_then(|ext| ext.to_str()),
74 Some("js" | "mjs" | "cjs")
75 )
76}
77
78fn has_minified_line_shape(path: &Path) -> bool {
79 use std::io::Read;
80
81 let Ok(mut file) = std::fs::File::open(path) else {
82 return false;
83 };
84 let mut sample = vec![0; MINIFIED_SAMPLE_BYTES];
85 let Ok(len) = file.read(&mut sample) else {
86 return false;
87 };
88 sample.truncate(len);
89 if sample.is_empty() {
90 return false;
91 }
92
93 let mut current_line = 0usize;
94 for byte in sample {
95 if byte == b'\n' || byte == b'\r' {
96 current_line = 0;
97 continue;
98 }
99 current_line += 1;
100 if current_line >= MINIFIED_LONG_LINE_BYTES {
101 return true;
102 }
103 }
104 false
105}
106
107fn is_probably_minified_generated_js(path: &Path, size_bytes: u64) -> bool {
108 size_bytes >= MINIFIED_FILE_SKIP_BYTES
109 && is_plain_js_file(path)
110 && !is_declaration_file(path)
111 && has_minified_line_shape(path)
112}
113
114fn format_size_mb(bytes: u64) -> String {
116 #[expect(
117 clippy::cast_precision_loss,
118 reason = "display-only size figure; precision loss past 2^53 bytes is irrelevant"
119 )]
120 let mb = bytes as f64 / (1024.0 * 1024.0);
121 format!("{mb:.1} MB")
122}
123
124fn summarize_examples(root: &Path, examples: &[SizedFile]) -> String {
127 let shown: Vec<String> = examples
128 .iter()
129 .take(NOTE_EXAMPLE_CAP)
130 .map(|(path, size)| {
131 let display = path
132 .strip_prefix(root)
133 .unwrap_or(path)
134 .display()
135 .to_string()
136 .replace('\\', "/");
137 format!("{display} ({})", format_size_mb(*size))
138 })
139 .collect();
140 let remaining = examples.len().saturating_sub(NOTE_EXAMPLE_CAP);
141 if remaining > 0 {
142 format!("{}, and {remaining} more", shown.join(", "))
143 } else {
144 shown.join(", ")
145 }
146}
147
148fn partition_by_size(
151 raw: Vec<SizedFile>,
152 max_file_size_bytes: Option<u64>,
153) -> (Vec<SizedFile>, Vec<SizedFile>) {
154 let Some(limit) = max_file_size_bytes else {
155 return (raw, Vec::new());
156 };
157 raw.into_iter()
158 .partition(|(path, size)| *size <= limit || is_declaration_file(path))
159}
160
161fn partition_minified_generated_js(
164 raw: Vec<SizedFile>,
165 max_file_size_bytes: Option<u64>,
166) -> (Vec<SizedFile>, Vec<SizedFile>) {
167 if max_file_size_bytes.is_none() {
168 return (raw, Vec::new());
169 }
170 raw.into_iter()
171 .partition(|(path, size)| !is_probably_minified_generated_js(path, *size))
172}
173
174fn report_skipped_large_files(config: &ResolvedConfig, skipped: &[SizedFile]) {
179 if skipped.is_empty() {
180 return;
181 }
182 let diagnostics: Vec<WorkspaceDiagnostic> = skipped
183 .iter()
184 .map(|(path, size_bytes)| {
185 WorkspaceDiagnostic::new(
186 &config.root,
187 path.clone(),
188 WorkspaceDiagnosticKind::SkippedLargeFile {
189 size_bytes: *size_bytes,
190 },
191 )
192 })
193 .collect();
194 fallow_config::append_workspace_diagnostics(&config.root, diagnostics);
195
196 let mut sorted: Vec<SizedFile> = skipped.to_vec();
197 sorted.sort_unstable_by_key(|f| std::cmp::Reverse(f.1));
198 let count = skipped.len();
199 if !config.quiet
200 && should_emit_note_once(format!(
201 "skip::{}::{count}::{}",
202 config.root.display(),
203 sorted.first().map_or(0, |f| f.1)
204 ))
205 {
206 let examples = summarize_examples(&config.root, &sorted);
207 let noun = if count == 1 { "file" } else { "files" };
208 tracing::warn!(
209 "fallow: skipped {count} {noun} over the max file size limit ({examples}). \
210 Raise the limit with --max-file-size <MB> (or FALLOW_MAX_FILE_SIZE), or add them to ignorePatterns."
211 );
212 }
213}
214
215fn report_skipped_minified_files(config: &ResolvedConfig, skipped: &[SizedFile]) {
217 if skipped.is_empty() {
218 return;
219 }
220 let diagnostics: Vec<WorkspaceDiagnostic> = skipped
221 .iter()
222 .map(|(path, size_bytes)| {
223 WorkspaceDiagnostic::new(
224 &config.root,
225 path.clone(),
226 WorkspaceDiagnosticKind::SkippedMinifiedFile {
227 size_bytes: *size_bytes,
228 },
229 )
230 })
231 .collect();
232 fallow_config::append_workspace_diagnostics(&config.root, diagnostics);
233
234 let mut sorted: Vec<SizedFile> = skipped.to_vec();
235 sorted.sort_unstable_by_key(|f| std::cmp::Reverse(f.1));
236 let count = skipped.len();
237 if !config.quiet
238 && should_emit_note_once(format!(
239 "minified::{}::{count}::{}",
240 config.root.display(),
241 sorted.first().map_or(0, |f| f.1)
242 ))
243 {
244 let examples = summarize_examples(&config.root, &sorted);
245 let noun = if count == 1 { "file" } else { "files" };
246 let pronoun = if count == 1 { "it" } else { "them" };
247 tracing::warn!(
248 "fallow: skipped {count} minified generated JS {noun} ({examples}). \
249 Add {pronoun} to ignorePatterns, rename {pronoun} with a .min.js suffix, or use --max-file-size 0 to analyze {pronoun}."
250 );
251 }
252}
253
254fn build_largest_files_note(root: &Path, files: &[DiscoveredFile]) -> Option<String> {
259 if files.is_empty() {
260 return None;
261 }
262 let largest = files.iter().map(|f| f.size_bytes).max().unwrap_or(0);
263 if files.len() <= LARGE_SET_THRESHOLD && largest < LARGE_FILE_NOTE_BYTES {
264 return None;
265 }
266 let count = files.len();
267 let noun = if count == 1 { "file" } else { "files" };
268 let mut by_size: Vec<SizedFile> = files
269 .iter()
270 .filter(|f| f.size_bytes >= NOTE_FILE_FLOOR_BYTES)
271 .map(|f| (f.path.clone(), f.size_bytes))
272 .collect();
273 by_size.sort_unstable_by_key(|f| std::cmp::Reverse(f.1));
274 if by_size.is_empty() {
275 return Some(format!(
278 "fallow: discovered {count} {noun}. If analysis stalls or runs out of memory, \
279 exclude large generated files via ignorePatterns or --max-file-size."
280 ));
281 }
282 let examples = summarize_examples(root, &by_size);
283 Some(format!(
284 "fallow: discovered {count} {noun}; largest: {examples}. If analysis stalls or runs out of memory, \
285 exclude large generated files via ignorePatterns or --max-file-size."
286 ))
287}
288
289fn note_largest_files(config: &ResolvedConfig, files: &[DiscoveredFile]) {
294 if config.quiet {
295 return;
296 }
297 if let Some(message) = build_largest_files_note(&config.root, files)
298 && should_emit_note_once(format!("note::{}::{}", config.root.display(), files.len()))
299 {
300 tracing::warn!("{message}");
301 }
302}
303
304#[derive(Debug, Clone, PartialEq, Eq)]
306pub struct HiddenDirScope {
307 root: PathBuf,
308 dirs: Vec<String>,
309}
310
311impl HiddenDirScope {
312 pub fn new(root: PathBuf, dirs: Vec<String>) -> Self {
313 Self { root, dirs }
314 }
315
316 fn allows(&self, path: &Path, name: &OsStr) -> bool {
317 path.starts_with(&self.root) && self.dirs.iter().any(|dir| OsStr::new(dir) == name)
318 }
319}
320
321struct FileVisitor<'a> {
323 root: &'a Path,
324 ignore_patterns: &'a globset::GlobSet,
325 production_excludes: &'a Option<globset::GlobSet>,
326 shared: &'a Mutex<Vec<(std::path::PathBuf, u64)>>,
327 local: Vec<(std::path::PathBuf, u64)>,
328}
329
330impl ignore::ParallelVisitor for FileVisitor<'_> {
331 fn visit(&mut self, result: Result<ignore::DirEntry, ignore::Error>) -> ignore::WalkState {
332 let Ok(entry) = result else {
333 return ignore::WalkState::Continue;
334 };
335 if entry.file_type().is_some_and(|ft| ft.is_dir()) {
336 return ignore::WalkState::Continue;
337 }
338 let relative = entry
339 .path()
340 .strip_prefix(self.root)
341 .unwrap_or_else(|_| entry.path());
342 if self.ignore_patterns.is_match(relative) {
343 return ignore::WalkState::Continue;
344 }
345 if self
346 .production_excludes
347 .as_ref()
348 .is_some_and(|excludes| excludes.is_match(relative))
349 {
350 return ignore::WalkState::Continue;
351 }
352 let size_bytes = entry.metadata().map_or(0, |m| m.len());
353 self.local.push((entry.into_path(), size_bytes));
354 ignore::WalkState::Continue
355 }
356}
357
358impl Drop for FileVisitor<'_> {
359 #[expect(
360 clippy::expect_used,
361 reason = "poisoned walk collector lock means worker state is unrecoverable"
362 )]
363 fn drop(&mut self) {
364 if !self.local.is_empty() {
365 self.shared
366 .lock()
367 .expect("walk collector lock poisoned")
368 .append(&mut self.local);
369 }
370 }
371}
372
373struct FileVisitorBuilder<'a> {
375 root: &'a Path,
376 ignore_patterns: &'a globset::GlobSet,
377 production_excludes: &'a Option<globset::GlobSet>,
378 shared: &'a Mutex<Vec<(std::path::PathBuf, u64)>>,
379}
380
381impl<'s> ignore::ParallelVisitorBuilder<'s> for FileVisitorBuilder<'s> {
382 fn build(&mut self) -> Box<dyn ignore::ParallelVisitor + 's> {
383 Box::new(FileVisitor {
384 root: self.root,
385 ignore_patterns: self.ignore_patterns,
386 production_excludes: self.production_excludes,
387 shared: self.shared,
388 local: Vec::new(),
389 })
390 }
391}
392
393pub const SOURCE_EXTENSIONS: &[&str] = &[
394 "ts", "tsx", "mts", "cts", "gts", "js", "jsx", "mjs", "cjs", "gjs", "vue", "svelte", "astro",
395 "mdx", "css", "scss", "html", "graphql", "gql",
396];
397
398pub const PRODUCTION_EXCLUDE_PATTERNS: &[&str] = &[
400 "**/*.test.*",
401 "**/*.spec.*",
402 "**/*.e2e.*",
403 "**/*.e2e-spec.*",
404 "**/*.bench.*",
405 "**/*.fixture.*",
406 "**/*.stories.*",
407 "**/*.story.*",
408 "**/__tests__/**",
409 "**/__mocks__/**",
410 "**/__snapshots__/**",
411 "**/__fixtures__/**",
412 "**/test/**",
413 "**/tests/**",
414 "*.config.*",
415 "**/.*.js",
416 "**/.*.ts",
417 "**/.*.mjs",
418 "**/.*.cjs",
419];
420
421pub fn is_allowed_hidden_dir(name: &OsStr) -> bool {
423 ALLOWED_HIDDEN_DIRS.iter().any(|&d| OsStr::new(d) == name)
424}
425
426fn is_allowed_scoped_hidden_dir(
427 name: &OsStr,
428 path: &Path,
429 additional_hidden_dir_scopes: &[HiddenDirScope],
430) -> bool {
431 additional_hidden_dir_scopes
432 .iter()
433 .any(|scope| scope.allows(path, name))
434}
435
436fn is_allowed_hidden(entry: &ignore::DirEntry) -> bool {
442 is_allowed_hidden_with_scopes(entry, &[])
443}
444
445fn is_allowed_hidden_with_scopes(
446 entry: &ignore::DirEntry,
447 additional_hidden_dir_scopes: &[HiddenDirScope],
448) -> bool {
449 let name = entry.file_name();
450 let name_str = name.to_string_lossy();
451
452 if !name_str.starts_with('.') {
453 return true;
454 }
455
456 if entry.file_type().is_some_and(|ft| !ft.is_dir()) {
457 return true;
458 }
459
460 is_allowed_hidden_dir(name)
461 || is_allowed_scoped_hidden_dir(name, entry.path(), additional_hidden_dir_scopes)
462}
463
464pub fn discover_files(config: &ResolvedConfig) -> Vec<DiscoveredFile> {
470 discover_files_with_additional_hidden_dirs(config, &[])
471}
472
473#[expect(
479 clippy::cast_possible_truncation,
480 reason = "file count is bounded by project size, well under u32::MAX"
481)]
482#[expect(
483 clippy::expect_used,
484 reason = "source file globs are hard-coded and the collector lock must remain usable"
485)]
486pub fn discover_files_with_additional_hidden_dirs(
487 config: &ResolvedConfig,
488 additional_hidden_dir_scopes: &[HiddenDirScope],
489) -> Vec<DiscoveredFile> {
490 let _span = tracing::info_span!("discover_files").entered();
491
492 let mut types_builder = ignore::types::TypesBuilder::new();
493 for ext in SOURCE_EXTENSIONS {
494 types_builder
495 .add("source", &format!("*.{ext}"))
496 .expect("valid glob");
497 }
498 types_builder.select("source");
499 let types = types_builder.build().expect("valid types");
500
501 let mut walk_builder = WalkBuilder::new(&config.root);
502 walk_builder
503 .hidden(false)
504 .git_ignore(true)
505 .git_global(true)
506 .git_exclude(true)
507 .types(types)
508 .threads(config.threads);
509 if additional_hidden_dir_scopes.is_empty() {
510 walk_builder.filter_entry(is_allowed_hidden);
511 } else {
512 let scopes = additional_hidden_dir_scopes.to_vec();
513 walk_builder.filter_entry(move |entry| is_allowed_hidden_with_scopes(entry, &scopes));
514 }
515
516 let production_excludes = if config.production {
517 let mut builder = globset::GlobSetBuilder::new();
518 for pattern in PRODUCTION_EXCLUDE_PATTERNS {
519 if let Ok(glob) = globset::GlobBuilder::new(pattern)
520 .literal_separator(true)
521 .build()
522 {
523 builder.add(glob);
524 }
525 }
526 builder.build().ok()
527 } else {
528 None
529 };
530
531 let collected: Mutex<Vec<(std::path::PathBuf, u64)>> = Mutex::new(Vec::new());
532 let mut visitor_builder = FileVisitorBuilder {
533 root: &config.root,
534 ignore_patterns: &config.ignore_patterns,
535 production_excludes: &production_excludes,
536 shared: &collected,
537 };
538 walk_builder.build_parallel().visit(&mut visitor_builder);
539
540 let mut raw = collected
541 .into_inner()
542 .expect("walk collector lock poisoned");
543 raw.sort_unstable_by(|a, b| a.0.cmp(&b.0));
544
545 fallow_config::clear_source_discovery_diagnostics(&config.root);
549 let (kept, skipped) = partition_by_size(raw, config.max_file_size_bytes);
550 report_skipped_large_files(config, &skipped);
551 let (kept, skipped_minified) =
552 partition_minified_generated_js(kept, config.max_file_size_bytes);
553 report_skipped_minified_files(config, &skipped_minified);
554
555 let files: Vec<DiscoveredFile> = kept
556 .into_iter()
557 .enumerate()
558 .map(|(idx, (path, size_bytes))| DiscoveredFile {
559 id: FileId(idx as u32),
560 path,
561 size_bytes,
562 })
563 .collect();
564
565 note_largest_files(config, &files);
566
567 files
568}
569
570#[cfg(test)]
571mod tests {
572 use std::ffi::OsStr;
573
574 use super::*;
575
576 #[test]
577 fn allowed_hidden_dirs() {
578 assert!(is_allowed_hidden_dir(OsStr::new(".storybook")));
579 assert!(is_allowed_hidden_dir(OsStr::new(".vitepress")));
580 assert!(is_allowed_hidden_dir(OsStr::new(".well-known")));
581 assert!(is_allowed_hidden_dir(OsStr::new(".changeset")));
582 assert!(is_allowed_hidden_dir(OsStr::new(".github")));
583 }
584
585 #[test]
586 fn disallowed_hidden_dirs() {
587 assert!(!is_allowed_hidden_dir(OsStr::new(".git")));
588 assert!(!is_allowed_hidden_dir(OsStr::new(".cache")));
589 assert!(!is_allowed_hidden_dir(OsStr::new(".vscode")));
590 assert!(!is_allowed_hidden_dir(OsStr::new(".fallow")));
591 assert!(!is_allowed_hidden_dir(OsStr::new(".next")));
592 }
593
594 #[test]
595 fn non_hidden_dirs_not_in_allowlist() {
596 assert!(!is_allowed_hidden_dir(OsStr::new("src")));
597 assert!(!is_allowed_hidden_dir(OsStr::new("node_modules")));
598 }
599
600 #[test]
601 fn source_extensions_include_typescript() {
602 assert!(SOURCE_EXTENSIONS.contains(&"ts"));
603 assert!(SOURCE_EXTENSIONS.contains(&"tsx"));
604 assert!(SOURCE_EXTENSIONS.contains(&"mts"));
605 assert!(SOURCE_EXTENSIONS.contains(&"cts"));
606 assert!(SOURCE_EXTENSIONS.contains(&"gts"));
607 }
608
609 #[test]
610 fn source_extensions_include_javascript() {
611 assert!(SOURCE_EXTENSIONS.contains(&"js"));
612 assert!(SOURCE_EXTENSIONS.contains(&"jsx"));
613 assert!(SOURCE_EXTENSIONS.contains(&"mjs"));
614 assert!(SOURCE_EXTENSIONS.contains(&"cjs"));
615 assert!(SOURCE_EXTENSIONS.contains(&"gjs"));
616 }
617
618 #[test]
619 fn source_extensions_include_sfc_formats() {
620 assert!(SOURCE_EXTENSIONS.contains(&"vue"));
621 assert!(SOURCE_EXTENSIONS.contains(&"svelte"));
622 assert!(SOURCE_EXTENSIONS.contains(&"astro"));
623 }
624
625 #[test]
626 fn source_extensions_include_styles() {
627 assert!(SOURCE_EXTENSIONS.contains(&"css"));
628 assert!(SOURCE_EXTENSIONS.contains(&"scss"));
629 }
630
631 #[test]
632 fn source_extensions_exclude_non_source() {
633 assert!(!SOURCE_EXTENSIONS.contains(&"json"));
634 assert!(!SOURCE_EXTENSIONS.contains(&"yaml"));
635 assert!(!SOURCE_EXTENSIONS.contains(&"md"));
636 assert!(!SOURCE_EXTENSIONS.contains(&"png"));
637 assert!(!SOURCE_EXTENSIONS.contains(&"htm"));
638 }
639
640 #[test]
641 fn source_extensions_include_html() {
642 assert!(SOURCE_EXTENSIONS.contains(&"html"));
643 }
644
645 #[test]
646 fn source_extensions_include_graphql_documents() {
647 assert!(SOURCE_EXTENSIONS.contains(&"graphql"));
648 assert!(SOURCE_EXTENSIONS.contains(&"gql"));
649 }
650
651 fn build_production_glob_set() -> globset::GlobSet {
652 let mut builder = globset::GlobSetBuilder::new();
653 for pattern in PRODUCTION_EXCLUDE_PATTERNS {
654 builder.add(
655 globset::GlobBuilder::new(pattern)
656 .literal_separator(true)
657 .build()
658 .expect("valid glob pattern"),
659 );
660 }
661 builder.build().expect("valid glob set")
662 }
663
664 #[test]
665 fn production_excludes_test_files() {
666 let set = build_production_glob_set();
667 assert!(set.is_match("src/Button.test.ts"));
668 assert!(set.is_match("src/utils.spec.tsx"));
669 assert!(set.is_match("src/__tests__/helper.ts"));
670 assert!(!set.is_match("src/Button.ts"));
671 assert!(!set.is_match("src/utils.tsx"));
672 }
673
674 #[test]
675 fn production_excludes_story_files() {
676 let set = build_production_glob_set();
677 assert!(set.is_match("src/Button.stories.tsx"));
678 assert!(set.is_match("src/Card.story.ts"));
679 assert!(!set.is_match("src/Button.tsx"));
680 }
681
682 #[test]
683 fn production_excludes_config_files_at_root_only() {
684 let set = build_production_glob_set();
685 assert!(set.is_match("vitest.config.ts"));
686 assert!(set.is_match("jest.config.js"));
687 assert!(!set.is_match("src/app/app.config.ts"));
688 assert!(!set.is_match("src/app/app.config.server.ts"));
689 assert!(!set.is_match("packages/foo/vitest.config.ts"));
690 assert!(!set.is_match("src/config.ts"));
691 }
692
693 #[test]
694 fn production_patterns_are_valid_globs() {
695 let _ = build_production_glob_set();
696 }
697
698 #[test]
699 fn disallowed_hidden_dirs_idea() {
700 assert!(!is_allowed_hidden_dir(OsStr::new(".idea")));
701 }
702
703 #[test]
704 fn source_extensions_include_mdx() {
705 assert!(SOURCE_EXTENSIONS.contains(&"mdx"));
706 }
707
708 #[test]
709 fn source_extensions_exclude_image_and_data_formats() {
710 assert!(!SOURCE_EXTENSIONS.contains(&"png"));
711 assert!(!SOURCE_EXTENSIONS.contains(&"jpg"));
712 assert!(!SOURCE_EXTENSIONS.contains(&"svg"));
713 assert!(!SOURCE_EXTENSIONS.contains(&"txt"));
714 assert!(!SOURCE_EXTENSIONS.contains(&"csv"));
715 assert!(!SOURCE_EXTENSIONS.contains(&"wasm"));
716 }
717
718 #[test]
719 fn is_declaration_file_matches_dts_variants() {
720 assert!(is_declaration_file(Path::new("env.d.ts")));
721 assert!(is_declaration_file(Path::new("src/auto-imports.d.ts")));
722 assert!(is_declaration_file(Path::new("mod.d.mts")));
723 assert!(is_declaration_file(Path::new("compat.d.cts")));
724 assert!(!is_declaration_file(Path::new("index.ts")));
725 assert!(!is_declaration_file(Path::new("component.tsx")));
726 assert!(!is_declaration_file(Path::new("notes.d.txt")));
727 }
728
729 #[test]
730 fn format_size_mb_renders_one_decimal() {
731 assert_eq!(format_size_mb(5 * 1024 * 1024), "5.0 MB");
732 assert_eq!(format_size_mb(1024 * 1024 + 512 * 1024), "1.5 MB");
733 assert_eq!(format_size_mb(0), "0.0 MB");
734 }
735
736 #[test]
737 fn partition_by_size_no_limit_keeps_all() {
738 let raw = vec![(PathBuf::from("a.ts"), 10), (PathBuf::from("b.ts"), 10_000)];
739 let (kept, skipped) = partition_by_size(raw, None);
740 assert_eq!(kept.len(), 2);
741 assert!(skipped.is_empty());
742 }
743
744 #[test]
745 fn partition_by_size_skips_strictly_over_limit() {
746 let raw = vec![
747 (PathBuf::from("under.ts"), 99),
748 (PathBuf::from("exact.ts"), 100),
749 (PathBuf::from("over.ts"), 101),
750 ];
751 let (kept, skipped) = partition_by_size(raw, Some(100));
752 let kept_has = |name: &str| kept.iter().any(|(p, _)| p.as_path() == Path::new(name));
753 assert!(kept_has("under.ts"));
754 assert!(
755 kept_has("exact.ts"),
756 "a file exactly at the limit is kept (skip is strictly-greater)"
757 );
758 assert_eq!(skipped.len(), 1);
759 assert_eq!(skipped[0].0, PathBuf::from("over.ts"));
760 }
761
762 #[test]
763 fn partition_by_size_exempts_declaration_files() {
764 let raw = vec![
765 (PathBuf::from("huge.ts"), 10_000),
766 (PathBuf::from("auto-imports.d.ts"), 10_000),
767 ];
768 let (kept, skipped) = partition_by_size(raw, Some(100));
769 assert!(
770 kept.iter()
771 .any(|(p, _)| p.as_path() == Path::new("auto-imports.d.ts")),
772 "declaration files are exempt from the size skip regardless of size"
773 );
774 assert_eq!(skipped.len(), 1);
775 assert_eq!(skipped[0].0, PathBuf::from("huge.ts"));
776 }
777
778 fn disco(path: &str, size_bytes: u64) -> DiscoveredFile {
779 DiscoveredFile {
780 id: FileId(0),
781 path: PathBuf::from(path),
782 size_bytes,
783 }
784 }
785
786 #[test]
787 fn largest_files_note_below_threshold_is_none() {
788 let files = [disco("a.ts", 100), disco("b.ts", 200)];
789 assert!(build_largest_files_note(Path::new("/p"), &files).is_none());
790 }
791
792 #[test]
793 fn largest_files_note_single_file_uses_singular() {
794 let files = [disco("big.ts", 5 * 1024 * 1024)];
795 let note = build_largest_files_note(Path::new("/p"), &files).expect("note fires");
796 assert!(
797 note.contains("discovered 1 file;"),
798 "singular noun on the single-big-file path (issue #1086 regression): {note}"
799 );
800 assert!(!note.contains("discovered 1 files"));
801 assert!(note.contains("big.ts (5.0 MB)"));
802 }
803
804 #[test]
805 fn largest_files_note_filters_sub_floor_files() {
806 let files = [disco("big.ts", 5 * 1024 * 1024), disco("tiny.ts", 10)];
807 let note = build_largest_files_note(Path::new("/p"), &files).expect("note fires");
808 assert!(note.contains("discovered 2 files;"));
809 assert!(note.contains("big.ts (5.0 MB)"));
810 assert!(
811 !note.contains("tiny.ts"),
812 "sub-floor files are not listed as `0.0 MB` chaff: {note}"
813 );
814 }
815
816 #[test]
817 fn largest_files_note_large_set_no_big_file_omits_list() {
818 let files: Vec<DiscoveredFile> = (0..=LARGE_SET_THRESHOLD)
819 .map(|i| disco(&format!("f{i}.ts"), 100))
820 .collect();
821 let note = build_largest_files_note(Path::new("/p"), &files).expect("large set fires");
822 assert!(note.contains(&format!("discovered {} files", LARGE_SET_THRESHOLD + 1)));
823 assert!(
824 !note.contains("largest:"),
825 "no sub-floor `largest:` list when no file clears the floor: {note}"
826 );
827 }
828
829 mod discover_files_integration {
830 use std::path::PathBuf;
831
832 use fallow_config::{
833 DuplicatesConfig, FallowConfig, FlagsConfig, HealthConfig, OutputFormat, ResolveConfig,
834 RulesConfig,
835 };
836
837 use super::*;
838
839 fn make_config(root: PathBuf, production: bool) -> ResolvedConfig {
841 FallowConfig {
842 production: production.into(),
843 ..Default::default()
844 }
845 .resolve(root, OutputFormat::Human, 1, true, true, None)
846 }
847
848 fn file_names(files: &[DiscoveredFile], root: &std::path::Path) -> Vec<String> {
851 files
852 .iter()
853 .map(|f| {
854 f.path
855 .strip_prefix(root)
856 .unwrap_or(&f.path)
857 .to_string_lossy()
858 .replace('\\', "/")
859 })
860 .collect()
861 }
862
863 #[test]
864 fn discovers_source_files_with_valid_extensions() {
865 let dir = tempfile::tempdir().expect("create temp dir");
866 let src = dir.path().join("src");
867 std::fs::create_dir_all(&src).unwrap();
868
869 std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
870 std::fs::write(src.join("component.tsx"), "export default () => {};").unwrap();
871 std::fs::write(src.join("utils.js"), "module.exports = {};").unwrap();
872 std::fs::write(src.join("helper.jsx"), "export const h = 1;").unwrap();
873 std::fs::write(src.join("config.mjs"), "export default {};").unwrap();
874 std::fs::write(src.join("legacy.cjs"), "module.exports = {};").unwrap();
875 std::fs::write(src.join("types.mts"), "export type T = string;").unwrap();
876 std::fs::write(src.join("compat.cts"), "module.exports = {};").unwrap();
877
878 let config = make_config(dir.path().to_path_buf(), false);
879 let files = discover_files(&config);
880 let names = file_names(&files, dir.path());
881
882 assert!(names.contains(&"src/app.ts".to_string()));
883 assert!(names.contains(&"src/component.tsx".to_string()));
884 assert!(names.contains(&"src/utils.js".to_string()));
885 assert!(names.contains(&"src/helper.jsx".to_string()));
886 assert!(names.contains(&"src/config.mjs".to_string()));
887 assert!(names.contains(&"src/legacy.cjs".to_string()));
888 assert!(names.contains(&"src/types.mts".to_string()));
889 assert!(names.contains(&"src/compat.cts".to_string()));
890 }
891
892 #[test]
893 fn excludes_non_source_extensions() {
894 let dir = tempfile::tempdir().expect("create temp dir");
895 let src = dir.path().join("src");
896 std::fs::create_dir_all(&src).unwrap();
897
898 std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
899
900 std::fs::write(src.join("data.json"), "{}").unwrap();
901 std::fs::write(src.join("readme.md"), "# Hello").unwrap();
902 std::fs::write(src.join("notes.txt"), "notes").unwrap();
903 std::fs::write(src.join("logo.png"), [0u8; 8]).unwrap();
904
905 let config = make_config(dir.path().to_path_buf(), false);
906 let files = discover_files(&config);
907 let names = file_names(&files, dir.path());
908
909 assert_eq!(names.len(), 1, "only the .ts file should be discovered");
910 assert!(names.contains(&"src/app.ts".to_string()));
911 }
912
913 #[test]
914 fn excludes_disallowed_hidden_directories() {
915 let dir = tempfile::tempdir().expect("create temp dir");
916
917 let git_dir = dir.path().join(".git");
918 std::fs::create_dir_all(&git_dir).unwrap();
919 std::fs::write(git_dir.join("hooks.ts"), "// git hook").unwrap();
920
921 let idea_dir = dir.path().join(".idea");
922 std::fs::create_dir_all(&idea_dir).unwrap();
923 std::fs::write(idea_dir.join("workspace.ts"), "// idea").unwrap();
924
925 let cache_dir = dir.path().join(".cache");
926 std::fs::create_dir_all(&cache_dir).unwrap();
927 std::fs::write(cache_dir.join("cached.js"), "// cached").unwrap();
928
929 let src = dir.path().join("src");
930 std::fs::create_dir_all(&src).unwrap();
931 std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
932
933 let config = make_config(dir.path().to_path_buf(), false);
934 let files = discover_files(&config);
935 let names = file_names(&files, dir.path());
936
937 assert_eq!(names.len(), 1, "only src/app.ts should be discovered");
938 assert!(names.contains(&"src/app.ts".to_string()));
939 }
940
941 #[test]
942 fn includes_allowed_hidden_directories() {
943 let dir = tempfile::tempdir().expect("create temp dir");
944
945 let storybook = dir.path().join(".storybook");
946 std::fs::create_dir_all(&storybook).unwrap();
947 std::fs::write(storybook.join("main.ts"), "export default {};").unwrap();
948
949 let github = dir.path().join(".github");
950 std::fs::create_dir_all(&github).unwrap();
951 std::fs::write(github.join("actions.js"), "module.exports = {};").unwrap();
952
953 let changeset = dir.path().join(".changeset");
954 std::fs::create_dir_all(&changeset).unwrap();
955 std::fs::write(changeset.join("config.js"), "module.exports = {};").unwrap();
956
957 let config = make_config(dir.path().to_path_buf(), false);
958 let files = discover_files(&config);
959 let names = file_names(&files, dir.path());
960
961 assert!(
962 names.contains(&".storybook/main.ts".to_string()),
963 "files in .storybook should be discovered"
964 );
965 assert!(
966 names.contains(&".github/actions.js".to_string()),
967 "files in .github should be discovered"
968 );
969 assert!(
970 names.contains(&".changeset/config.js".to_string()),
971 "files in .changeset should be discovered"
972 );
973 }
974
975 #[test]
976 fn default_discovery_excludes_client_and_server_hidden_directories() {
977 let dir = tempfile::tempdir().expect("create temp dir");
978 let app = dir.path().join("app");
979 std::fs::create_dir_all(app.join(".client")).unwrap();
980 std::fs::create_dir_all(app.join(".server")).unwrap();
981 std::fs::write(app.join(".client/analytics.ts"), "export const a = 1;").unwrap();
982 std::fs::write(app.join(".server/db.ts"), "export const db = {};").unwrap();
983 std::fs::write(app.join("root.tsx"), "export default function Root() {}").unwrap();
984
985 let config = make_config(dir.path().to_path_buf(), false);
986 let files = discover_files(&config);
987 let names = file_names(&files, dir.path());
988
989 assert!(names.contains(&"app/root.tsx".to_string()));
990 assert!(!names.contains(&"app/.client/analytics.ts".to_string()));
991 assert!(!names.contains(&"app/.server/db.ts".to_string()));
992 }
993
994 #[test]
995 fn scoped_hidden_dirs_include_client_and_server_under_package_root() {
996 let dir = tempfile::tempdir().expect("create temp dir");
997 let package = dir.path().join("packages/app");
998 std::fs::create_dir_all(package.join("app/.client")).unwrap();
999 std::fs::create_dir_all(package.join("app/.server")).unwrap();
1000 std::fs::write(
1001 package.join("app/.client/analytics.ts"),
1002 "export const track = () => {};",
1003 )
1004 .unwrap();
1005 std::fs::write(package.join("app/.server/db.ts"), "export const db = {};").unwrap();
1006
1007 let config = make_config(dir.path().to_path_buf(), false);
1008 let scopes = [HiddenDirScope::new(
1009 package,
1010 vec![".client".to_string(), ".server".to_string()],
1011 )];
1012 let files = discover_files_with_additional_hidden_dirs(&config, &scopes);
1013 let names = file_names(&files, dir.path());
1014
1015 assert!(names.contains(&"packages/app/app/.client/analytics.ts".to_string()));
1016 assert!(names.contains(&"packages/app/app/.server/db.ts".to_string()));
1017 }
1018
1019 #[test]
1020 fn scoped_hidden_dirs_do_not_include_unscoped_packages() {
1021 let dir = tempfile::tempdir().expect("create temp dir");
1022 let active = dir.path().join("packages/active");
1023 let inactive = dir.path().join("packages/inactive");
1024 std::fs::create_dir_all(active.join("app/.server")).unwrap();
1025 std::fs::create_dir_all(inactive.join("app/.server")).unwrap();
1026 std::fs::write(active.join("app/.server/db.ts"), "export const db = {};").unwrap();
1027 std::fs::write(inactive.join("app/.server/db.ts"), "export const db = {};").unwrap();
1028
1029 let config = make_config(dir.path().to_path_buf(), false);
1030 let scopes = [HiddenDirScope::new(active, vec![".server".to_string()])];
1031 let files = discover_files_with_additional_hidden_dirs(&config, &scopes);
1032 let names = file_names(&files, dir.path());
1033
1034 assert!(names.contains(&"packages/active/app/.server/db.ts".to_string()));
1035 assert!(!names.contains(&"packages/inactive/app/.server/db.ts".to_string()));
1036 }
1037
1038 #[test]
1039 fn excludes_root_build_directory() {
1040 let dir = tempfile::tempdir().expect("create temp dir");
1041
1042 std::fs::write(dir.path().join(".ignore"), "/build/\n").unwrap();
1043
1044 let build_dir = dir.path().join("build");
1045 std::fs::create_dir_all(&build_dir).unwrap();
1046 std::fs::write(build_dir.join("output.js"), "// build output").unwrap();
1047
1048 let src = dir.path().join("src");
1049 std::fs::create_dir_all(&src).unwrap();
1050 std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
1051
1052 let config = make_config(dir.path().to_path_buf(), false);
1053 let files = discover_files(&config);
1054 let names = file_names(&files, dir.path());
1055
1056 assert_eq!(names.len(), 1, "root build/ should be excluded via .ignore");
1057 assert!(names.contains(&"src/app.ts".to_string()));
1058 }
1059
1060 #[test]
1061 fn includes_nested_build_directory() {
1062 let dir = tempfile::tempdir().expect("create temp dir");
1063
1064 let nested_build = dir.path().join("src").join("build");
1065 std::fs::create_dir_all(&nested_build).unwrap();
1066 std::fs::write(nested_build.join("helper.ts"), "export const h = 1;").unwrap();
1067
1068 let config = make_config(dir.path().to_path_buf(), false);
1069 let files = discover_files(&config);
1070 let names = file_names(&files, dir.path());
1071
1072 assert!(
1073 names.contains(&"src/build/helper.ts".to_string()),
1074 "nested build/ directories should be included"
1075 );
1076 }
1077
1078 #[test]
1079 #[expect(
1080 clippy::cast_possible_truncation,
1081 reason = "test file counts are trivially small"
1082 )]
1083 fn file_ids_are_sequential_after_sorting() {
1084 let dir = tempfile::tempdir().expect("create temp dir");
1085 let src = dir.path().join("src");
1086 std::fs::create_dir_all(&src).unwrap();
1087
1088 std::fs::write(src.join("z_last.ts"), "export const z = 1;").unwrap();
1089 std::fs::write(src.join("a_first.ts"), "export const a = 1;").unwrap();
1090 std::fs::write(src.join("m_middle.ts"), "export const m = 1;").unwrap();
1091
1092 let config = make_config(dir.path().to_path_buf(), false);
1093 let files = discover_files(&config);
1094
1095 for (idx, file) in files.iter().enumerate() {
1096 assert_eq!(file.id, FileId(idx as u32), "FileId should be sequential");
1097 }
1098
1099 for pair in files.windows(2) {
1100 assert!(
1101 pair[0].path < pair[1].path,
1102 "files should be sorted by path"
1103 );
1104 }
1105 }
1106
1107 #[test]
1108 fn production_mode_excludes_test_files() {
1109 let dir = tempfile::tempdir().expect("create temp dir");
1110 let src = dir.path().join("src");
1111 std::fs::create_dir_all(&src).unwrap();
1112
1113 std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
1114 std::fs::write(src.join("app.test.ts"), "test('a', () => {});").unwrap();
1115 std::fs::write(src.join("app.spec.ts"), "describe('a', () => {});").unwrap();
1116 std::fs::write(src.join("app.stories.tsx"), "export default {};").unwrap();
1117
1118 let config = make_config(dir.path().to_path_buf(), true);
1119 let files = discover_files(&config);
1120 let names = file_names(&files, dir.path());
1121
1122 assert!(
1123 names.contains(&"src/app.ts".to_string()),
1124 "source files should be included in production mode"
1125 );
1126 assert!(
1127 !names.contains(&"src/app.test.ts".to_string()),
1128 "test files should be excluded in production mode"
1129 );
1130 assert!(
1131 !names.contains(&"src/app.spec.ts".to_string()),
1132 "spec files should be excluded in production mode"
1133 );
1134 assert!(
1135 !names.contains(&"src/app.stories.tsx".to_string()),
1136 "story files should be excluded in production mode"
1137 );
1138 }
1139
1140 #[test]
1141 fn non_production_mode_includes_test_files() {
1142 let dir = tempfile::tempdir().expect("create temp dir");
1143 let src = dir.path().join("src");
1144 std::fs::create_dir_all(&src).unwrap();
1145
1146 std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
1147 std::fs::write(src.join("app.test.ts"), "test('a', () => {});").unwrap();
1148
1149 let config = make_config(dir.path().to_path_buf(), false);
1150 let files = discover_files(&config);
1151 let names = file_names(&files, dir.path());
1152
1153 assert!(names.contains(&"src/app.ts".to_string()));
1154 assert!(
1155 names.contains(&"src/app.test.ts".to_string()),
1156 "test files should be included in non-production mode"
1157 );
1158 }
1159
1160 #[test]
1161 fn empty_directory_returns_no_files() {
1162 let dir = tempfile::tempdir().expect("create temp dir");
1163 let config = make_config(dir.path().to_path_buf(), false);
1164 let files = discover_files(&config);
1165 assert!(files.is_empty(), "empty project should discover no files");
1166 }
1167
1168 #[test]
1169 fn hidden_files_not_discovered_as_source() {
1170 let dir = tempfile::tempdir().expect("create temp dir");
1171
1172 std::fs::write(dir.path().join(".env"), "SECRET=abc").unwrap();
1173 std::fs::write(dir.path().join(".gitignore"), "node_modules").unwrap();
1174 std::fs::write(dir.path().join(".eslintrc.js"), "module.exports = {};").unwrap();
1175
1176 let src = dir.path().join("src");
1177 std::fs::create_dir_all(&src).unwrap();
1178 std::fs::write(src.join("app.ts"), "export const a = 1;").unwrap();
1179
1180 let config = make_config(dir.path().to_path_buf(), false);
1181 let files = discover_files(&config);
1182 let names = file_names(&files, dir.path());
1183
1184 assert!(
1185 !names.contains(&".env".to_string()),
1186 ".env should not be discovered"
1187 );
1188 assert!(
1189 !names.contains(&".gitignore".to_string()),
1190 ".gitignore should not be discovered"
1191 );
1192 }
1193
1194 fn make_config_with_ignores(root: PathBuf, ignores: Vec<String>) -> ResolvedConfig {
1196 FallowConfig {
1197 schema: None,
1198 extends: vec![],
1199 entry: vec![],
1200 ignore_patterns: ignores,
1201 framework: vec![],
1202 workspaces: None,
1203 ignore_dependencies: vec![],
1204 ignore_unresolved_imports: vec![],
1205 ignore_exports: vec![],
1206 ignore_catalog_references: vec![],
1207 ignore_dependency_overrides: vec![],
1208 ignore_exports_used_in_file: fallow_config::IgnoreExportsUsedInFileConfig::default(
1209 ),
1210 used_class_members: vec![],
1211 ignore_decorators: vec![],
1212 duplicates: DuplicatesConfig::default(),
1213 health: HealthConfig::default(),
1214 rules: RulesConfig::default(),
1215 boundaries: fallow_config::BoundaryConfig::default(),
1216 production: false.into(),
1217 plugins: vec![],
1218 rule_packs: vec![],
1219 dynamically_loaded: vec![],
1220 overrides: vec![],
1221 regression: None,
1222 audit: fallow_config::AuditConfig::default(),
1223 codeowners: None,
1224 public_packages: vec![],
1225 flags: FlagsConfig::default(),
1226 security: fallow_config::SecurityConfig::default(),
1227 fix: fallow_config::FixConfig::default(),
1228 resolve: ResolveConfig::default(),
1229 sealed: false,
1230 include_entry_exports: false,
1231 auto_imports: false,
1232 cache: fallow_config::CacheConfig::default(),
1233 }
1234 .resolve(root, OutputFormat::Human, 1, true, true, None)
1235 }
1236
1237 #[test]
1238 fn custom_ignore_patterns_exclude_matching_files() {
1239 let dir = tempfile::tempdir().expect("create temp dir");
1240
1241 let generated = dir.path().join("src").join("api").join("generated");
1242 std::fs::create_dir_all(&generated).unwrap();
1243 std::fs::write(generated.join("client.ts"), "export const api = {};").unwrap();
1244
1245 let client = dir.path().join("src").join("api").join("client");
1246 std::fs::create_dir_all(&client).unwrap();
1247 std::fs::write(client.join("fetch.ts"), "export const fetch = {};").unwrap();
1248
1249 let src = dir.path().join("src");
1250 std::fs::write(src.join("index.ts"), "export const x = 1;").unwrap();
1251
1252 let config = make_config_with_ignores(
1253 dir.path().to_path_buf(),
1254 vec![
1255 "src/api/generated/**".to_string(),
1256 "src/api/client/**".to_string(),
1257 ],
1258 );
1259 let files = discover_files(&config);
1260 let names = file_names(&files, dir.path());
1261
1262 assert_eq!(names.len(), 1, "only non-ignored files: {names:?}");
1263 assert!(names.contains(&"src/index.ts".to_string()));
1264 }
1265
1266 #[test]
1267 fn default_ignore_patterns_exclude_node_modules_and_dist() {
1268 let dir = tempfile::tempdir().expect("create temp dir");
1269
1270 let nm = dir.path().join("node_modules").join("lodash");
1271 std::fs::create_dir_all(&nm).unwrap();
1272 std::fs::write(nm.join("lodash.js"), "module.exports = {};").unwrap();
1273
1274 let dist = dir.path().join("dist");
1275 std::fs::create_dir_all(&dist).unwrap();
1276 std::fs::write(dist.join("bundle.js"), "// bundled").unwrap();
1277
1278 let src = dir.path().join("src");
1279 std::fs::create_dir_all(&src).unwrap();
1280 std::fs::write(src.join("index.ts"), "export const x = 1;").unwrap();
1281
1282 let config = make_config(dir.path().to_path_buf(), false);
1283 let files = discover_files(&config);
1284 let names = file_names(&files, dir.path());
1285
1286 assert_eq!(names.len(), 1);
1287 assert!(names.contains(&"src/index.ts".to_string()));
1288 }
1289
1290 #[test]
1291 fn default_ignore_patterns_exclude_root_build() {
1292 let dir = tempfile::tempdir().expect("create temp dir");
1293
1294 let build = dir.path().join("build");
1295 std::fs::create_dir_all(&build).unwrap();
1296 std::fs::write(build.join("output.js"), "// built").unwrap();
1297
1298 let nested_build = dir.path().join("src").join("build");
1299 std::fs::create_dir_all(&nested_build).unwrap();
1300 std::fs::write(nested_build.join("helper.ts"), "export const h = 1;").unwrap();
1301
1302 let src = dir.path().join("src");
1303 std::fs::write(src.join("index.ts"), "export const x = 1;").unwrap();
1304
1305 let config = make_config(dir.path().to_path_buf(), false);
1306 let files = discover_files(&config);
1307 let names = file_names(&files, dir.path());
1308
1309 assert_eq!(
1310 names.len(),
1311 2,
1312 "root build/ excluded, nested kept: {names:?}"
1313 );
1314 assert!(names.contains(&"src/index.ts".to_string()));
1315 assert!(names.contains(&"src/build/helper.ts".to_string()));
1316 }
1317
1318 fn make_config_with_max_file_size(
1320 root: PathBuf,
1321 max_file_size_bytes: Option<u64>,
1322 ) -> ResolvedConfig {
1323 let mut config = make_config(root, false);
1324 config.max_file_size_bytes = max_file_size_bytes;
1325 config
1326 }
1327
1328 #[test]
1329 fn skips_files_over_max_file_size() {
1330 let dir = tempfile::tempdir().expect("create temp dir");
1331 let src = dir.path().join("src");
1332 std::fs::create_dir_all(&src).unwrap();
1333 std::fs::write(src.join("small.ts"), "export const a = 1;").unwrap();
1334 std::fs::write(src.join("huge.ts"), "x".repeat(5_000)).unwrap();
1335
1336 let config = make_config_with_max_file_size(dir.path().to_path_buf(), Some(1_000));
1337 let files = discover_files(&config);
1338 let names = file_names(&files, dir.path());
1339
1340 assert!(names.contains(&"src/small.ts".to_string()));
1341 assert!(
1342 !names.contains(&"src/huge.ts".to_string()),
1343 "a file over the size limit must not be discovered"
1344 );
1345 }
1346
1347 #[test]
1348 fn declaration_files_exempt_from_size_skip() {
1349 let dir = tempfile::tempdir().expect("create temp dir");
1350 let src = dir.path().join("src");
1351 std::fs::create_dir_all(&src).unwrap();
1352 std::fs::write(src.join("auto-imports.d.ts"), "x".repeat(5_000)).unwrap();
1353 std::fs::write(src.join("huge.ts"), "x".repeat(5_000)).unwrap();
1354
1355 let config = make_config_with_max_file_size(dir.path().to_path_buf(), Some(1_000));
1356 let files = discover_files(&config);
1357 let names = file_names(&files, dir.path());
1358
1359 assert!(
1360 names.contains(&"src/auto-imports.d.ts".to_string()),
1361 "a large .d.ts is exempt from the skip (reachability root for global types)"
1362 );
1363 assert!(!names.contains(&"src/huge.ts".to_string()));
1364 }
1365
1366 #[test]
1367 fn unlimited_size_keeps_large_files() {
1368 let dir = tempfile::tempdir().expect("create temp dir");
1369 let src = dir.path().join("src");
1370 std::fs::create_dir_all(&src).unwrap();
1371 std::fs::write(src.join("huge.ts"), "x".repeat(5_000)).unwrap();
1372
1373 let config = make_config_with_max_file_size(dir.path().to_path_buf(), None);
1374 let files = discover_files(&config);
1375 let names = file_names(&files, dir.path());
1376
1377 assert!(
1378 names.contains(&"src/huge.ts".to_string()),
1379 "no limit keeps every file"
1380 );
1381 }
1382
1383 #[test]
1384 fn skipped_file_recorded_in_workspace_diagnostics() {
1385 let dir = tempfile::tempdir().expect("create temp dir");
1386 let src = dir.path().join("src");
1387 std::fs::create_dir_all(&src).unwrap();
1388 std::fs::write(src.join("huge.ts"), "x".repeat(5_000)).unwrap();
1389
1390 let config = make_config_with_max_file_size(dir.path().to_path_buf(), Some(1_000));
1391 let _ = discover_files(&config);
1392
1393 let diagnostics = fallow_config::workspace_diagnostics_for(dir.path());
1394 let skipped: Vec<_> = diagnostics
1395 .iter()
1396 .filter(|d| {
1397 matches!(
1398 d.kind,
1399 fallow_config::WorkspaceDiagnosticKind::SkippedLargeFile { .. }
1400 )
1401 })
1402 .collect();
1403 assert_eq!(
1404 skipped.len(),
1405 1,
1406 "the skipped file is recorded in workspace diagnostics for JSON output"
1407 );
1408 assert!(skipped[0].path.ends_with("src/huge.ts"));
1409 assert!(
1410 matches!(
1411 skipped[0].kind,
1412 fallow_config::WorkspaceDiagnosticKind::SkippedLargeFile { size_bytes }
1413 if size_bytes == 5_000
1414 ),
1415 "the recorded diagnostic carries the on-disk byte size"
1416 );
1417 }
1418
1419 #[test]
1420 fn skips_large_one_line_js_as_minified_generated_output() {
1421 let dir = tempfile::tempdir().expect("create temp dir");
1422 let src = dir.path().join("src");
1423 std::fs::create_dir_all(&src).unwrap();
1424 let asset = src.join("index-abc123.js");
1425 std::fs::write(&asset, "x".repeat(MINIFIED_FILE_SKIP_BYTES as usize + 1)).unwrap();
1426
1427 let config = make_config(dir.path().to_path_buf(), false);
1428 let files = discover_files(&config);
1429 let names = file_names(&files, dir.path());
1430
1431 assert!(
1432 !names.contains(&"src/index-abc123.js".to_string()),
1433 "large one-line JS assets should be skipped before parsing"
1434 );
1435
1436 let diagnostics = fallow_config::workspace_diagnostics_for(dir.path());
1437 assert!(
1438 diagnostics.iter().any(|diag| {
1439 diag.path.ends_with("src/index-abc123.js")
1440 && matches!(
1441 diag.kind,
1442 fallow_config::WorkspaceDiagnosticKind::SkippedMinifiedFile { .. }
1443 )
1444 }),
1445 "the skipped minified asset is recorded for JSON output: {diagnostics:?}"
1446 );
1447 }
1448
1449 #[test]
1450 fn unlimited_size_keeps_large_one_line_js() {
1451 let dir = tempfile::tempdir().expect("create temp dir");
1452 let src = dir.path().join("src");
1453 std::fs::create_dir_all(&src).unwrap();
1454 let asset = src.join("index-abc123.js");
1455 std::fs::write(&asset, "x".repeat(MINIFIED_FILE_SKIP_BYTES as usize + 1)).unwrap();
1456
1457 let config = make_config_with_max_file_size(dir.path().to_path_buf(), None);
1458 let files = discover_files(&config);
1459 let names = file_names(&files, dir.path());
1460
1461 assert!(
1462 names.contains(&"src/index-abc123.js".to_string()),
1463 "--max-file-size 0 should opt out of generated JS skipping"
1464 );
1465 }
1466
1467 #[test]
1468 fn keeps_large_multiline_js() {
1469 let dir = tempfile::tempdir().expect("create temp dir");
1470 let src = dir.path().join("src");
1471 std::fs::create_dir_all(&src).unwrap();
1472 let asset = src.join("handwritten.js");
1473 let mut content = String::new();
1474 while content.len() <= MINIFIED_FILE_SKIP_BYTES as usize + 1 {
1475 content.push_str("export const value = 1;\n");
1476 }
1477 std::fs::write(&asset, content).unwrap();
1478
1479 let config = make_config(dir.path().to_path_buf(), false);
1480 let files = discover_files(&config);
1481 let names = file_names(&files, dir.path());
1482
1483 assert!(
1484 names.contains(&"src/handwritten.js".to_string()),
1485 "large multiline JS should not be treated as a generated minified asset"
1486 );
1487 }
1488 }
1489}