1#![cfg_attr(not(test), deny(clippy::disallowed_methods))]
14#![cfg_attr(
15 test,
16 allow(
17 clippy::unwrap_used,
18 clippy::expect_used,
19 reason = "tests use unwrap and expect to keep fixture setup concise"
20 )
21)]
22
23pub mod analyze;
24pub mod cache;
25pub mod changed_files;
26pub mod churn;
27pub mod cross_reference;
28pub mod discover;
29pub mod duplicates;
30pub(crate) mod errors;
31mod external_style_usage;
32pub mod extract;
33pub mod git_env;
34mod package_assets;
35pub mod plugins;
36pub(crate) mod progress;
37pub mod results;
38pub(crate) mod scripts;
39pub(crate) mod spawn;
40pub mod suppress;
41pub mod trace;
42
43pub use fallow_graph::graph;
44pub use fallow_graph::project;
45pub use fallow_graph::resolve;
46
47use std::path::{Path, PathBuf};
48use std::time::Instant;
49
50use errors::FallowError;
51use fallow_config::{
52 EntryPointRole, PackageJson, ResolvedConfig, discover_workspaces,
53 find_undeclared_workspaces_with_ignores,
54};
55use rayon::prelude::*;
56use results::AnalysisResults;
57use rustc_hash::FxHashSet;
58use trace::PipelineTimings;
59
60const UNDECLARED_WORKSPACE_WARNING_PREVIEW: usize = 5;
61type LoadedWorkspacePackage<'a> = (&'a fallow_config::WorkspaceInfo, PackageJson);
62
63fn record_graph_package_usage(
64 graph: &mut graph::ModuleGraph,
65 package_name: &str,
66 file_id: discover::FileId,
67 is_type_only: bool,
68) {
69 graph
70 .package_usage
71 .entry(package_name.to_owned())
72 .or_default()
73 .push(file_id);
74 if is_type_only {
75 graph
76 .type_only_package_usage
77 .entry(package_name.to_owned())
78 .or_default()
79 .push(file_id);
80 }
81}
82
83fn workspace_package_name<'a>(
84 source: &str,
85 workspace_names: &'a FxHashSet<&str>,
86) -> Option<&'a str> {
87 if !resolve::is_bare_specifier(source) {
88 return None;
89 }
90 let package_name = resolve::extract_package_name(source);
91 workspace_names.get(package_name.as_str()).copied()
92}
93
94fn credit_workspace_package_usage(
95 graph: &mut graph::ModuleGraph,
96 resolved: &[resolve::ResolvedModule],
97 workspaces: &[fallow_config::WorkspaceInfo],
98) {
99 if workspaces.is_empty() {
100 return;
101 }
102
103 let workspace_names: FxHashSet<&str> = workspaces.iter().map(|ws| ws.name.as_str()).collect();
104 for module in resolved {
105 for import in module.all_resolved_imports() {
106 if matches!(import.target, resolve::ResolveResult::InternalModule(_))
107 && let Some(package_name) =
108 workspace_package_name(&import.info.source, &workspace_names)
109 {
110 record_graph_package_usage(
111 graph,
112 package_name,
113 module.file_id,
114 import.info.is_type_only,
115 );
116 }
117 }
118
119 for re_export in &module.re_exports {
120 if matches!(re_export.target, resolve::ResolveResult::InternalModule(_))
121 && let Some(package_name) =
122 workspace_package_name(&re_export.info.source, &workspace_names)
123 {
124 record_graph_package_usage(
125 graph,
126 package_name,
127 module.file_id,
128 re_export.info.is_type_only,
129 );
130 }
131 }
132 }
133}
134
135fn credit_package_path_references(graph: &mut graph::ModuleGraph, modules: &[extract::ModuleInfo]) {
136 for module in modules {
137 for package_name in &module.package_path_references {
138 record_graph_package_usage(graph, package_name, module.file_id, false);
139 }
140 }
141}
142
143pub struct AnalysisOutput {
145 pub results: AnalysisResults,
146 pub timings: Option<PipelineTimings>,
147 pub graph: Option<graph::ModuleGraph>,
148 pub modules: Option<Vec<extract::ModuleInfo>>,
152 pub files: Option<Vec<discover::DiscoveredFile>>,
154 pub script_used_packages: rustc_hash::FxHashSet<String>,
159 pub file_hashes: rustc_hash::FxHashMap<std::path::PathBuf, u64>,
168}
169
170fn update_cache(
172 store: &mut cache::CacheStore,
173 modules: &[extract::ModuleInfo],
174 files: &[discover::DiscoveredFile],
175) {
176 for module in modules {
177 if let Some(file) = files.get(module.file_id.0 as usize) {
178 let (mt, sz) = file_mtime_and_size(&file.path);
179 if let Some(cached) = store.get_by_path_only(&file.path)
180 && cached.content_hash == module.content_hash
181 {
182 if cached.mtime_secs != mt || cached.file_size != sz {
183 let preserved_last_access = cached.last_access_secs;
184 let mut refreshed = cache::module_to_cached(module, mt, sz);
185 refreshed.last_access_secs = preserved_last_access;
186 store.insert(&file.path, refreshed);
187 }
188 continue;
189 }
190 store.insert(&file.path, cache::module_to_cached(module, mt, sz));
191 }
192 }
193 store.retain_paths(files);
194}
195
196#[must_use]
204pub fn resolve_cache_max_size_bytes(config: &ResolvedConfig) -> usize {
205 config
206 .cache_max_size_mb
207 .map_or(cache::DEFAULT_CACHE_MAX_SIZE, |mb| {
208 (mb as usize).saturating_mul(1024 * 1024)
209 })
210}
211
212fn file_mtime_and_size(path: &std::path::Path) -> (u64, u64) {
214 std::fs::metadata(path).map_or((0, 0), |m| {
215 let mt = m
216 .modified()
217 .ok()
218 .and_then(|t| t.duration_since(std::time::SystemTime::UNIX_EPOCH).ok())
219 .map_or(0, |d| d.as_secs());
220 (mt, m.len())
221 })
222}
223
224fn format_undeclared_workspace_warning(
225 root: &Path,
226 undeclared: &[fallow_config::WorkspaceDiagnostic],
227) -> Option<String> {
228 if undeclared.is_empty() {
229 return None;
230 }
231
232 let preview = undeclared
233 .iter()
234 .take(UNDECLARED_WORKSPACE_WARNING_PREVIEW)
235 .map(|diag| {
236 diag.path
237 .strip_prefix(root)
238 .unwrap_or(&diag.path)
239 .display()
240 .to_string()
241 .replace('\\', "/")
242 })
243 .collect::<Vec<_>>();
244 let remaining = undeclared
245 .len()
246 .saturating_sub(UNDECLARED_WORKSPACE_WARNING_PREVIEW);
247 let tail = if remaining > 0 {
248 format!(" (and {remaining} more)")
249 } else {
250 String::new()
251 };
252 let noun = if undeclared.len() == 1 {
253 "directory with package.json is"
254 } else {
255 "directories with package.json are"
256 };
257 let guidance = if undeclared.len() == 1 {
258 "Add that path to package.json workspaces or pnpm-workspace.yaml if it should be analyzed as a workspace."
259 } else {
260 "Add those paths to package.json workspaces or pnpm-workspace.yaml if they should be analyzed as workspaces."
261 };
262
263 Some(format!(
264 "{} {} not declared as {}: {}{}. {}",
265 undeclared.len(),
266 noun,
267 if undeclared.len() == 1 {
268 "a workspace"
269 } else {
270 "workspaces"
271 },
272 preview.join(", "),
273 tail,
274 guidance
275 ))
276}
277
278fn warn_undeclared_workspaces(
279 root: &Path,
280 workspaces_vec: &[fallow_config::WorkspaceInfo],
281 ignore_patterns: &globset::GlobSet,
282 quiet: bool,
283) {
284 let undeclared = find_undeclared_workspaces_with_ignores(root, workspaces_vec, ignore_patterns);
285 if undeclared.is_empty() {
286 return;
287 }
288
289 let existing = fallow_config::workspace_diagnostics_for(root);
290 let already_flagged: rustc_hash::FxHashSet<PathBuf> = existing
291 .iter()
292 .map(|d| dunce::canonicalize(&d.path).unwrap_or_else(|_| d.path.clone()))
293 .collect();
294 let undeclared: Vec<_> = undeclared
295 .into_iter()
296 .filter(|diag| {
297 let canonical = dunce::canonicalize(&diag.path).unwrap_or_else(|_| diag.path.clone());
298 !already_flagged.contains(&canonical)
299 })
300 .collect();
301 if undeclared.is_empty() {
302 return;
303 }
304
305 fallow_config::append_workspace_diagnostics(root, undeclared.clone());
306
307 if !quiet && let Some(message) = format_undeclared_workspace_warning(root, &undeclared) {
308 tracing::warn!("{message}");
309 }
310}
311
312#[deprecated(
318 since = "2.76.0",
319 note = "fallow_core is internal; use fallow_cli::programmatic::detect_dead_code instead. NOTE: replacement returns serde_json::Value, not typed AnalysisResults. See docs/fallow-core-migration.md and ADR-008."
320)]
321pub fn analyze(config: &ResolvedConfig) -> Result<AnalysisResults, FallowError> {
322 let output = analyze_full(config, false, false, false, false)?;
323 Ok(output.results)
324}
325
326#[deprecated(
332 since = "2.76.0",
333 note = "fallow_core is internal; use fallow_cli::programmatic::detect_dead_code instead. NOTE: export-usage collection is not exposed in the programmatic surface today. See docs/fallow-core-migration.md and ADR-008."
334)]
335pub fn analyze_with_usages(config: &ResolvedConfig) -> Result<AnalysisResults, FallowError> {
336 let output = analyze_full(config, false, true, false, false)?;
337 Ok(output.results)
338}
339
340#[deprecated(
351 since = "2.90.0",
352 note = "fallow_core is internal; use fallow_cli::programmatic::detect_dead_code and `compute_complexity` instead. NOTE: this combined LSP-only typed surface is not exposed externally. See docs/fallow-core-migration.md and ADR-008."
353)]
354pub fn analyze_with_usages_and_complexity(
355 config: &ResolvedConfig,
356) -> Result<AnalysisOutput, FallowError> {
357 analyze_full(config, false, true, true, true)
358}
359
360#[deprecated(
366 since = "2.76.0",
367 note = "fallow_core is internal; use fallow_cli::programmatic::detect_dead_code instead. NOTE: trace timings are not exposed in the programmatic surface today; use `fallow dead-code --performance` for CLI-side timings. See docs/fallow-core-migration.md and ADR-008."
368)]
369pub fn analyze_with_trace(config: &ResolvedConfig) -> Result<AnalysisOutput, FallowError> {
370 analyze_full(config, true, false, false, false)
371}
372
373#[deprecated(
382 since = "2.76.0",
383 note = "fallow_core is internal; the CLI fix command uses this via the workspace path dependency. External embedders should use fallow_cli::programmatic::detect_dead_code. See docs/fallow-core-migration.md and ADR-008."
384)]
385pub fn analyze_with_file_hashes(config: &ResolvedConfig) -> Result<AnalysisOutput, FallowError> {
386 analyze_full(config, false, false, false, false)
387}
388
389#[deprecated(
399 since = "2.76.0",
400 note = "fallow_core is internal; use fallow_cli::programmatic::detect_dead_code instead. NOTE: combined-mode module retention is not exposed in the programmatic surface today. See docs/fallow-core-migration.md and ADR-008."
401)]
402pub fn analyze_retaining_modules(
403 config: &ResolvedConfig,
404 need_complexity: bool,
405 retain_graph: bool,
406) -> Result<AnalysisOutput, FallowError> {
407 analyze_full(config, retain_graph, false, need_complexity, true)
408}
409
410fn new_analysis_progress(config: &ResolvedConfig) -> progress::AnalysisProgress {
411 let show_progress = !config.quiet
412 && std::io::IsTerminal::is_terminal(&std::io::stderr())
413 && matches!(
414 config.output,
415 fallow_config::OutputFormat::Human
416 | fallow_config::OutputFormat::Compact
417 | fallow_config::OutputFormat::Markdown
418 );
419 progress::AnalysisProgress::new(show_progress)
420}
421
422fn warn_missing_node_modules(config: &ResolvedConfig) {
423 if config.root.join("node_modules").is_dir() {
424 return;
425 }
426
427 tracing::warn!(
428 "node_modules directory not found. Run `npm install` / `pnpm install` first for accurate results."
429 );
430}
431
432fn discover_analysis_workspaces(
433 config: &ResolvedConfig,
434) -> (Vec<fallow_config::WorkspaceInfo>, f64) {
435 let t = Instant::now();
436 let workspaces = discover_workspaces(&config.root);
437 let workspaces_ms = t.elapsed().as_secs_f64() * 1000.0;
438 if !workspaces.is_empty() {
439 tracing::info!(count = workspaces.len(), "workspaces discovered");
440 }
441
442 warn_undeclared_workspaces(
443 &config.root,
444 &workspaces,
445 &config.ignore_patterns,
446 config.quiet,
447 );
448
449 (workspaces, workspaces_ms)
450}
451
452#[allow(
464 clippy::too_many_lines,
465 reason = "pipeline orchestration stays easier to audit in one place"
466)]
467#[deprecated(
468 since = "2.76.0",
469 note = "fallow_core is internal; use fallow_cli::programmatic::detect_dead_code instead. NOTE: pre-parsed module reuse is not exposed in the programmatic surface today. See docs/fallow-core-migration.md and ADR-008."
470)]
471pub fn analyze_with_parse_result(
472 config: &ResolvedConfig,
473 modules: &[extract::ModuleInfo],
474) -> Result<AnalysisOutput, FallowError> {
475 let _span = tracing::info_span!("fallow_analyze_with_parse_result").entered();
476 let pipeline_start = Instant::now();
477
478 let progress = new_analysis_progress(config);
479 warn_missing_node_modules(config);
480
481 let (workspaces_vec, workspaces_ms) = discover_analysis_workspaces(config);
482 let root_pkg = load_root_package_json(config);
483 let discovery_hidden_dir_scopes =
484 discover::collect_hidden_dir_scopes(config, root_pkg.as_ref(), &workspaces_vec);
485
486 let t = Instant::now();
487 progress.set_stage("discovering files...");
488 let discovered_files =
489 discover::discover_files_with_additional_hidden_dirs(config, &discovery_hidden_dir_scopes);
490 let discover_ms = t.elapsed().as_secs_f64() * 1000.0;
491
492 let project = project::ProjectState::new(discovered_files, workspaces_vec);
493 let files = project.files();
494 let workspaces = project.workspaces();
495 let workspace_pkgs = load_workspace_packages(workspaces);
496
497 let t = Instant::now();
498 progress.set_stage("detecting plugins...");
499 let mut plugin_result = run_plugins(
500 config,
501 files,
502 workspaces,
503 root_pkg.as_ref(),
504 &workspace_pkgs,
505 )?;
506 let plugins_ms = t.elapsed().as_secs_f64() * 1000.0;
507
508 let t = Instant::now();
509 analyze_all_scripts(
510 config,
511 workspaces,
512 root_pkg.as_ref(),
513 &workspace_pkgs,
514 &mut plugin_result,
515 );
516 let scripts_ms = t.elapsed().as_secs_f64() * 1000.0;
517
518 let t = Instant::now();
519 let entry_points = discover_all_entry_points(
520 config,
521 files,
522 workspaces,
523 root_pkg.as_ref(),
524 &workspace_pkgs,
525 &plugin_result,
526 );
527 let entry_points_ms = t.elapsed().as_secs_f64() * 1000.0;
528
529 let ep_summary = summarize_entry_points(&entry_points.all);
530
531 let t = Instant::now();
532 progress.set_stage("resolving imports...");
533 let resolved = resolve_analysis_imports(modules, files, workspaces, &plugin_result, config);
534 let resolve_ms = t.elapsed().as_secs_f64() * 1000.0;
535
536 let t = Instant::now();
537 progress.set_stage("building module graph...");
538 let graph = build_analysis_graph(&resolved, &entry_points, files, modules, workspaces);
539 let graph_ms = t.elapsed().as_secs_f64() * 1000.0;
540
541 let t = Instant::now();
542 progress.set_stage("analyzing...");
543 #[expect(
544 deprecated,
545 reason = "ADR-008 keeps workspace path-dependency calls while warning external fallow-core consumers"
546 )]
547 let mut result = analyze::find_dead_code_full(
548 &graph,
549 config,
550 &resolved,
551 Some(&plugin_result),
552 workspaces,
553 modules,
554 false,
555 );
556 let analyze_ms = t.elapsed().as_secs_f64() * 1000.0;
557 progress.finish();
558
559 result.entry_point_summary = Some(ep_summary);
560
561 let total_ms = pipeline_start.elapsed().as_secs_f64() * 1000.0;
562
563 tracing::debug!(
564 "\n┌─ Pipeline Profile (reuse) ─────────────────────\n\
565 │ discover files: {:>8.1}ms ({} files)\n\
566 │ workspaces: {:>8.1}ms\n\
567 │ plugins: {:>8.1}ms\n\
568 │ script analysis: {:>8.1}ms\n\
569 │ parse/extract: SKIPPED (reused {} modules)\n\
570 │ entry points: {:>8.1}ms ({} entries)\n\
571 │ resolve imports: {:>8.1}ms\n\
572 │ build graph: {:>8.1}ms\n\
573 │ analyze: {:>8.1}ms\n\
574 │ ────────────────────────────────────────────\n\
575 │ TOTAL: {:>8.1}ms\n\
576 └─────────────────────────────────────────────────",
577 discover_ms,
578 files.len(),
579 workspaces_ms,
580 plugins_ms,
581 scripts_ms,
582 modules.len(),
583 entry_points_ms,
584 entry_points.all.len(),
585 resolve_ms,
586 graph_ms,
587 analyze_ms,
588 total_ms,
589 );
590
591 let timings = Some(PipelineTimings {
592 discover_files_ms: discover_ms,
593 file_count: files.len(),
594 workspaces_ms,
595 workspace_count: workspaces.len(),
596 plugins_ms,
597 script_analysis_ms: scripts_ms,
598 parse_extract_ms: 0.0, parse_cpu_ms: 0.0, module_count: modules.len(),
601 cache_hits: 0,
602 cache_misses: 0,
603 cache_update_ms: 0.0,
604 entry_points_ms,
605 entry_point_count: entry_points.all.len(),
606 resolve_imports_ms: resolve_ms,
607 build_graph_ms: graph_ms,
608 analyze_ms,
609 duplication_ms: None,
610 total_ms,
611 });
612
613 let file_hashes = collect_file_hashes(modules, files);
614
615 Ok(AnalysisOutput {
616 results: result,
617 timings,
618 graph: Some(graph),
619 modules: None,
620 files: None,
621 script_used_packages: plugin_result.script_used_packages.clone(),
622 file_hashes,
623 })
624}
625
626#[expect(
627 clippy::too_many_lines,
628 reason = "main pipeline function; sequential phases are held together for clarity"
629)]
630fn analyze_full(
631 config: &ResolvedConfig,
632 retain: bool,
633 collect_usages: bool,
634 need_complexity: bool,
635 retain_modules: bool,
636) -> Result<AnalysisOutput, FallowError> {
637 let _span = tracing::info_span!("fallow_analyze").entered();
638 let pipeline_start = Instant::now();
639
640 let progress = new_analysis_progress(config);
641 warn_missing_node_modules(config);
642
643 let (workspaces_vec, workspaces_ms) = discover_analysis_workspaces(config);
644 let root_pkg = load_root_package_json(config);
645 let discovery_hidden_dir_scopes =
646 discover::collect_hidden_dir_scopes(config, root_pkg.as_ref(), &workspaces_vec);
647
648 let t = Instant::now();
649 progress.set_stage("discovering files...");
650 let discovered_files =
651 discover::discover_files_with_additional_hidden_dirs(config, &discovery_hidden_dir_scopes);
652 let discover_ms = t.elapsed().as_secs_f64() * 1000.0;
653
654 let project = project::ProjectState::new(discovered_files, workspaces_vec);
655 let files = project.files();
656 let workspaces = project.workspaces();
657 let workspace_pkgs = load_workspace_packages(workspaces);
658
659 let t = Instant::now();
660 progress.set_stage("detecting plugins...");
661 let mut plugin_result = run_plugins(
662 config,
663 files,
664 workspaces,
665 root_pkg.as_ref(),
666 &workspace_pkgs,
667 )?;
668 let plugins_ms = t.elapsed().as_secs_f64() * 1000.0;
669
670 let t = Instant::now();
671 analyze_all_scripts(
672 config,
673 workspaces,
674 root_pkg.as_ref(),
675 &workspace_pkgs,
676 &mut plugin_result,
677 );
678 let scripts_ms = t.elapsed().as_secs_f64() * 1000.0;
679
680 let t = Instant::now();
681 progress.set_stage(&format!("parsing {} files...", files.len()));
682 let cache_max_size_bytes = resolve_cache_max_size_bytes(config);
683 let mut cache_store = if config.no_cache {
684 None
685 } else {
686 cache::CacheStore::load(
687 &config.cache_dir,
688 config.cache_config_hash,
689 cache_max_size_bytes,
690 )
691 };
692
693 let parse_result = extract::parse_all_files(files, cache_store.as_ref(), need_complexity);
694 let mut modules = parse_result.modules;
695 let cache_hits = parse_result.cache_hits;
696 let cache_misses = parse_result.cache_misses;
697 let parse_cpu_ms = parse_result.parse_cpu_ms;
698 let parse_ms = t.elapsed().as_secs_f64() * 1000.0;
699
700 let cache_ms = update_parse_cache_if_enabled(
701 config,
702 &mut cache_store,
703 &modules,
704 files,
705 cache_max_size_bytes,
706 );
707
708 let t = Instant::now();
709 let entry_points = discover_all_entry_points(
710 config,
711 files,
712 workspaces,
713 root_pkg.as_ref(),
714 &workspace_pkgs,
715 &plugin_result,
716 );
717 let entry_points_ms = t.elapsed().as_secs_f64() * 1000.0;
718
719 let t = Instant::now();
720 progress.set_stage("resolving imports...");
721 let resolved = resolve_analysis_imports(&modules, files, workspaces, &plugin_result, config);
722 let resolve_ms = t.elapsed().as_secs_f64() * 1000.0;
723
724 let t = Instant::now();
725 progress.set_stage("building module graph...");
726 let graph = build_analysis_graph(&resolved, &entry_points, files, &modules, workspaces);
727 for module in &mut modules {
728 module.release_resolution_payload();
729 }
730 let graph_ms = t.elapsed().as_secs_f64() * 1000.0;
731
732 let ep_summary = summarize_entry_points(&entry_points.all);
733
734 let t = Instant::now();
735 progress.set_stage("analyzing...");
736 #[expect(
737 deprecated,
738 reason = "ADR-008 keeps workspace path-dependency calls while warning external fallow-core consumers"
739 )]
740 let mut result = analyze::find_dead_code_full(
741 &graph,
742 config,
743 &resolved,
744 Some(&plugin_result),
745 workspaces,
746 &modules,
747 collect_usages,
748 );
749 let analyze_ms = t.elapsed().as_secs_f64() * 1000.0;
750 progress.finish();
751
752 result.entry_point_summary = Some(ep_summary);
753
754 let total_ms = pipeline_start.elapsed().as_secs_f64() * 1000.0;
755
756 trace_pipeline_profile(&PipelineProfile {
757 discover_ms,
758 workspaces_ms,
759 plugins_ms,
760 scripts_ms,
761 parse_ms,
762 cache_ms,
763 entry_points_ms,
764 resolve_ms,
765 graph_ms,
766 analyze_ms,
767 total_ms,
768 file_count: files.len(),
769 module_count: modules.len(),
770 entry_point_count: entry_points.all.len(),
771 cache_hits,
772 cache_misses,
773 });
774
775 let timings = if retain {
776 Some(PipelineTimings {
777 discover_files_ms: discover_ms,
778 file_count: files.len(),
779 workspaces_ms,
780 workspace_count: workspaces.len(),
781 plugins_ms,
782 script_analysis_ms: scripts_ms,
783 parse_extract_ms: parse_ms,
784 parse_cpu_ms,
785 module_count: modules.len(),
786 cache_hits,
787 cache_misses,
788 cache_update_ms: cache_ms,
789 entry_points_ms,
790 entry_point_count: entry_points.all.len(),
791 resolve_imports_ms: resolve_ms,
792 build_graph_ms: graph_ms,
793 analyze_ms,
794 duplication_ms: None,
795 total_ms,
796 })
797 } else {
798 None
799 };
800
801 let file_hashes = collect_file_hashes(&modules, files);
802
803 Ok(AnalysisOutput {
804 results: result,
805 timings,
806 graph: if retain { Some(graph) } else { None },
807 modules: if retain_modules { Some(modules) } else { None },
808 files: if retain_modules {
809 Some(files.to_vec())
810 } else {
811 None
812 },
813 script_used_packages: plugin_result.script_used_packages,
814 file_hashes,
815 })
816}
817
818#[derive(Clone, Copy)]
819struct PipelineProfile {
820 discover_ms: f64,
821 workspaces_ms: f64,
822 plugins_ms: f64,
823 scripts_ms: f64,
824 parse_ms: f64,
825 cache_ms: f64,
826 entry_points_ms: f64,
827 resolve_ms: f64,
828 graph_ms: f64,
829 analyze_ms: f64,
830 total_ms: f64,
831 file_count: usize,
832 module_count: usize,
833 entry_point_count: usize,
834 cache_hits: usize,
835 cache_misses: usize,
836}
837
838fn update_parse_cache_if_enabled(
839 config: &ResolvedConfig,
840 cache_store: &mut Option<cache::CacheStore>,
841 modules: &[extract::ModuleInfo],
842 files: &[discover::DiscoveredFile],
843 cache_max_size_bytes: usize,
844) -> f64 {
845 let t = Instant::now();
846 if !config.no_cache {
847 let store = cache_store.get_or_insert_with(cache::CacheStore::new);
848 update_cache(store, modules, files);
849 if let Err(error) = store.save(
850 &config.cache_dir,
851 config.cache_config_hash,
852 cache_max_size_bytes,
853 ) {
854 tracing::warn!("Failed to save cache: {error}");
855 }
856 }
857 t.elapsed().as_secs_f64() * 1000.0
858}
859
860fn resolve_analysis_imports(
861 modules: &[extract::ModuleInfo],
862 files: &[discover::DiscoveredFile],
863 workspaces: &[fallow_config::WorkspaceInfo],
864 plugin_result: &plugins::AggregatedPluginResult,
865 config: &ResolvedConfig,
866) -> Vec<resolve::ResolvedModule> {
867 let mut resolved = resolve::resolve_all_imports(
868 modules,
869 files,
870 workspaces,
871 &plugin_result.active_plugins,
872 &plugin_result.path_aliases,
873 &plugin_result.auto_imports,
874 &plugin_result.scss_include_paths,
875 &plugin_result.static_dir_mappings,
876 &config.root,
877 &config.resolve.conditions,
878 );
879 external_style_usage::augment_external_style_package_usage(
880 &mut resolved,
881 config,
882 workspaces,
883 plugin_result,
884 );
885 resolved
886}
887
888fn build_analysis_graph(
889 resolved: &[resolve::ResolvedModule],
890 entry_points: &discover::CategorizedEntryPoints,
891 files: &[discover::DiscoveredFile],
892 modules: &[extract::ModuleInfo],
893 workspaces: &[fallow_config::WorkspaceInfo],
894) -> graph::ModuleGraph {
895 let mut graph = graph::ModuleGraph::build_with_reachability_roots(
896 resolved,
897 &entry_points.all,
898 &entry_points.runtime,
899 &entry_points.test,
900 files,
901 );
902 credit_package_path_references(&mut graph, modules);
903 credit_workspace_package_usage(&mut graph, resolved, workspaces);
904 graph
905}
906
907fn collect_file_hashes(
908 modules: &[extract::ModuleInfo],
909 files: &[discover::DiscoveredFile],
910) -> rustc_hash::FxHashMap<std::path::PathBuf, u64> {
911 modules
912 .iter()
913 .filter_map(|module| {
914 files
915 .get(module.file_id.0 as usize)
916 .map(|file| (file.path.clone(), module.content_hash))
917 })
918 .collect()
919}
920
921fn trace_pipeline_profile(profile: &PipelineProfile) {
922 let PipelineProfile {
923 discover_ms,
924 workspaces_ms,
925 plugins_ms,
926 scripts_ms,
927 parse_ms,
928 cache_ms,
929 entry_points_ms,
930 resolve_ms,
931 graph_ms,
932 analyze_ms,
933 total_ms,
934 file_count,
935 module_count,
936 entry_point_count,
937 cache_hits,
938 cache_misses,
939 } = *profile;
940 let cache_summary = if cache_hits > 0 {
941 format!(" ({cache_hits} cached, {cache_misses} parsed)")
942 } else {
943 String::new()
944 };
945
946 tracing::debug!(
947 "\n┌─ Pipeline Profile ─────────────────────────────\n\
948 │ discover files: {:>8.1}ms ({} files)\n\
949 │ workspaces: {:>8.1}ms\n\
950 │ plugins: {:>8.1}ms\n\
951 │ script analysis: {:>8.1}ms\n\
952 │ parse/extract: {:>8.1}ms ({} modules{})\n\
953 │ cache update: {:>8.1}ms\n\
954 │ entry points: {:>8.1}ms ({} entries)\n\
955 │ resolve imports: {:>8.1}ms\n\
956 │ build graph: {:>8.1}ms\n\
957 │ analyze: {:>8.1}ms\n\
958 │ ────────────────────────────────────────────\n\
959 │ TOTAL: {:>8.1}ms\n\
960 └─────────────────────────────────────────────────",
961 discover_ms,
962 file_count,
963 workspaces_ms,
964 plugins_ms,
965 scripts_ms,
966 parse_ms,
967 module_count,
968 cache_summary,
969 cache_ms,
970 entry_points_ms,
971 entry_point_count,
972 resolve_ms,
973 graph_ms,
974 analyze_ms,
975 total_ms,
976 );
977}
978
979fn load_root_package_json(config: &ResolvedConfig) -> Option<PackageJson> {
984 PackageJson::load(&config.root.join("package.json")).ok()
985}
986
987fn load_workspace_packages(
988 workspaces: &[fallow_config::WorkspaceInfo],
989) -> Vec<LoadedWorkspacePackage<'_>> {
990 workspaces
991 .iter()
992 .filter_map(|ws| {
993 PackageJson::load(&ws.root.join("package.json"))
994 .ok()
995 .map(|pkg| (ws, pkg))
996 })
997 .collect()
998}
999
1000fn analyze_all_scripts(
1001 config: &ResolvedConfig,
1002 workspaces: &[fallow_config::WorkspaceInfo],
1003 root_pkg: Option<&PackageJson>,
1004 workspace_pkgs: &[LoadedWorkspacePackage<'_>],
1005 plugin_result: &mut plugins::AggregatedPluginResult,
1006) {
1007 let mut all_dep_names: Vec<String> = Vec::new();
1008 if let Some(pkg) = root_pkg {
1009 all_dep_names.extend(pkg.all_dependency_names());
1010 }
1011 for (_, ws_pkg) in workspace_pkgs {
1012 all_dep_names.extend(ws_pkg.all_dependency_names());
1013 }
1014 all_dep_names.sort_unstable();
1015 all_dep_names.dedup();
1016 let all_dep_set: FxHashSet<String> = all_dep_names.iter().cloned().collect();
1017 let mut all_script_names: FxHashSet<String> = FxHashSet::default();
1018 if let Some(pkg) = root_pkg
1019 && let Some(ref pkg_scripts) = pkg.scripts
1020 {
1021 all_script_names.extend(pkg_scripts.keys().cloned());
1022 }
1023 for (_, ws_pkg) in workspace_pkgs {
1024 if let Some(ref ws_scripts) = ws_pkg.scripts {
1025 all_script_names.extend(ws_scripts.keys().cloned());
1026 }
1027 }
1028
1029 let mut nm_roots: Vec<&std::path::Path> = Vec::new();
1030 if config.root.join("node_modules").is_dir() {
1031 nm_roots.push(&config.root);
1032 }
1033 for ws in workspaces {
1034 if ws.root.join("node_modules").is_dir() {
1035 nm_roots.push(&ws.root);
1036 }
1037 }
1038 let bin_map = scripts::build_bin_to_package_map(&nm_roots, &all_dep_names);
1039
1040 if let Some(pkg) = root_pkg
1041 && let Some(ref pkg_scripts) = pkg.scripts
1042 {
1043 let scripts_to_analyze = if config.production {
1044 scripts::filter_production_scripts(pkg_scripts)
1045 } else {
1046 pkg_scripts.clone()
1047 };
1048 let script_names: FxHashSet<String> = pkg_scripts.keys().cloned().collect();
1049 let script_analysis = scripts::analyze_scripts_with_dependency_context(
1050 &scripts_to_analyze,
1051 &config.root,
1052 &bin_map,
1053 &all_dep_set,
1054 &script_names,
1055 );
1056 plugin_result.script_used_packages = script_analysis.used_packages;
1057
1058 for config_file in &script_analysis.config_files {
1059 plugin_result
1060 .discovered_always_used
1061 .push((config_file.clone(), "scripts".to_string()));
1062 }
1063 for entry in &script_analysis.entry_files {
1064 if let Some(pat) = scripts::normalize_script_entry_pattern("", entry) {
1065 plugin_result
1066 .entry_patterns
1067 .push((plugins::PathRule::new(pat), "scripts".to_string()));
1068 }
1069 }
1070 }
1071 use rayon::prelude::*;
1072 type WsScriptOut = (
1073 Vec<String>,
1074 Vec<(String, String)>,
1075 Vec<(plugins::PathRule, String)>,
1076 );
1077 let ws_results: Vec<WsScriptOut> = workspace_pkgs
1078 .par_iter()
1079 .map(|(ws, ws_pkg)| {
1080 let mut used_packages = Vec::new();
1081 let mut discovered_always_used: Vec<(String, String)> = Vec::new();
1082 let mut entry_patterns: Vec<(plugins::PathRule, String)> = Vec::new();
1083 if let Some(ref ws_scripts) = ws_pkg.scripts {
1084 let scripts_to_analyze = if config.production {
1085 scripts::filter_production_scripts(ws_scripts)
1086 } else {
1087 ws_scripts.clone()
1088 };
1089 let script_names: FxHashSet<String> = ws_scripts.keys().cloned().collect();
1090 let ws_analysis = scripts::analyze_scripts_with_dependency_context(
1091 &scripts_to_analyze,
1092 &ws.root,
1093 &bin_map,
1094 &all_dep_set,
1095 &script_names,
1096 );
1097 used_packages.extend(ws_analysis.used_packages);
1098
1099 let ws_prefix = ws
1100 .root
1101 .strip_prefix(&config.root)
1102 .unwrap_or(&ws.root)
1103 .to_string_lossy();
1104 for config_file in &ws_analysis.config_files {
1105 discovered_always_used
1106 .push((format!("{ws_prefix}/{config_file}"), "scripts".to_string()));
1107 }
1108 for entry in &ws_analysis.entry_files {
1109 if let Some(pat) = scripts::normalize_script_entry_pattern(&ws_prefix, entry) {
1110 entry_patterns.push((plugins::PathRule::new(pat), "scripts".to_string()));
1111 }
1112 }
1113 }
1114 (used_packages, discovered_always_used, entry_patterns)
1115 })
1116 .collect();
1117 for (used_packages, discovered_always_used, entry_patterns) in ws_results {
1118 plugin_result.script_used_packages.extend(used_packages);
1119 plugin_result
1120 .discovered_always_used
1121 .extend(discovered_always_used);
1122 plugin_result.entry_patterns.extend(entry_patterns);
1123 }
1124
1125 let ci_analysis =
1126 scripts::ci::analyze_ci_files(&config.root, &bin_map, &all_dep_set, &all_script_names);
1127 plugin_result
1128 .script_used_packages
1129 .extend(ci_analysis.used_packages);
1130 for entry in &ci_analysis.entry_files {
1131 if let Some(pat) = scripts::normalize_script_entry_pattern("", entry) {
1132 plugin_result
1133 .entry_patterns
1134 .push((plugins::PathRule::new(pat), "scripts".to_string()));
1135 }
1136 }
1137 plugin_result
1138 .entry_point_roles
1139 .entry("scripts".to_string())
1140 .or_insert(EntryPointRole::Support);
1141}
1142
1143fn discover_all_entry_points(
1145 config: &ResolvedConfig,
1146 files: &[discover::DiscoveredFile],
1147 workspaces: &[fallow_config::WorkspaceInfo],
1148 root_pkg: Option<&PackageJson>,
1149 workspace_pkgs: &[LoadedWorkspacePackage<'_>],
1150 plugin_result: &plugins::AggregatedPluginResult,
1151) -> discover::CategorizedEntryPoints {
1152 let mut entry_points = discover::CategorizedEntryPoints::default();
1153 let root_discovery = discover::discover_entry_points_with_warnings_from_pkg(
1154 config,
1155 files,
1156 root_pkg,
1157 workspaces.is_empty(),
1158 );
1159
1160 let workspace_pkg_by_root: rustc_hash::FxHashMap<std::path::PathBuf, &PackageJson> =
1161 workspace_pkgs
1162 .iter()
1163 .map(|(ws, pkg)| (ws.root.clone(), pkg))
1164 .collect();
1165
1166 let workspace_discovery: Vec<discover::EntryPointDiscovery> = workspaces
1167 .par_iter()
1168 .map(|ws| {
1169 let pkg = workspace_pkg_by_root.get(&ws.root).copied();
1170 discover::discover_workspace_entry_points_with_warnings_from_pkg(&ws.root, files, pkg)
1171 })
1172 .collect();
1173 let mut skipped_entries = rustc_hash::FxHashMap::default();
1174 entry_points.extend_runtime(root_discovery.entries);
1175 for (path, count) in root_discovery.skipped_entries {
1176 *skipped_entries.entry(path).or_insert(0) += count;
1177 }
1178 let mut ws_entries = Vec::new();
1179 for workspace in workspace_discovery {
1180 ws_entries.extend(workspace.entries);
1181 for (path, count) in workspace.skipped_entries {
1182 *skipped_entries.entry(path).or_insert(0) += count;
1183 }
1184 }
1185 discover::warn_skipped_entry_summary(&skipped_entries);
1186 entry_points.extend_runtime(ws_entries);
1187
1188 let plugin_entries = discover::discover_plugin_entry_point_sets(plugin_result, config, files);
1189 entry_points.extend(plugin_entries);
1190
1191 let infra_entries = discover::discover_infrastructure_entry_points(&config.root);
1192 entry_points.extend_runtime(infra_entries);
1193
1194 if !config.dynamically_loaded.is_empty() {
1195 let dynamic_entries = discover::discover_dynamically_loaded_entry_points(config, files);
1196 entry_points.extend_runtime(dynamic_entries);
1197 }
1198
1199 entry_points.dedup()
1200}
1201
1202fn summarize_entry_points(entry_points: &[discover::EntryPoint]) -> results::EntryPointSummary {
1204 let mut counts: rustc_hash::FxHashMap<String, usize> = rustc_hash::FxHashMap::default();
1205 for ep in entry_points {
1206 let category = match &ep.source {
1207 discover::EntryPointSource::PackageJsonMain
1208 | discover::EntryPointSource::PackageJsonModule
1209 | discover::EntryPointSource::PackageJsonExports
1210 | discover::EntryPointSource::PackageJsonBin
1211 | discover::EntryPointSource::PackageJsonScript => "package.json",
1212 discover::EntryPointSource::Plugin { .. } => "plugin",
1213 discover::EntryPointSource::TestFile => "test file",
1214 discover::EntryPointSource::DefaultIndex => "default index",
1215 discover::EntryPointSource::ManualEntry => "manual entry",
1216 discover::EntryPointSource::InfrastructureConfig => "config",
1217 discover::EntryPointSource::DynamicallyLoaded => "dynamically loaded",
1218 };
1219 *counts.entry(category.to_string()).or_insert(0) += 1;
1220 }
1221 let mut by_source: Vec<(String, usize)> = counts.into_iter().collect();
1222 by_source.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
1223 results::EntryPointSummary {
1224 total: entry_points.len(),
1225 by_source,
1226 }
1227}
1228
1229fn append_package_file_asset_patterns(
1230 result: &mut plugins::AggregatedPluginResult,
1231 prefix: &str,
1232 pkg: &PackageJson,
1233) {
1234 let prefix = prefix.trim_matches('/');
1235 for pattern in package_assets::scaffold_template_asset_patterns(pkg) {
1236 let pattern = if prefix.is_empty() {
1237 pattern
1238 } else {
1239 format!("{prefix}/{pattern}")
1240 };
1241 result
1242 .discovered_always_used
1243 .push((pattern, package_assets::PACKAGE_FILES_SOURCE.to_string()));
1244 }
1245}
1246
1247fn append_workspace_package_file_asset_patterns(
1248 result: &mut plugins::AggregatedPluginResult,
1249 config: &ResolvedConfig,
1250 workspace_pkgs: &[LoadedWorkspacePackage<'_>],
1251) {
1252 for (ws, ws_pkg) in workspace_pkgs {
1253 let ws_prefix = ws
1254 .root
1255 .strip_prefix(&config.root)
1256 .unwrap_or(&ws.root)
1257 .to_string_lossy()
1258 .replace('\\', "/");
1259 append_package_file_asset_patterns(result, &ws_prefix, ws_pkg);
1260 }
1261}
1262
1263fn run_plugins(
1265 config: &ResolvedConfig,
1266 files: &[discover::DiscoveredFile],
1267 workspaces: &[fallow_config::WorkspaceInfo],
1268 root_pkg: Option<&PackageJson>,
1269 workspace_pkgs: &[LoadedWorkspacePackage<'_>],
1270) -> Result<plugins::AggregatedPluginResult, FallowError> {
1271 let registry = plugins::PluginRegistry::new(config.external_plugins.clone());
1272 let file_paths: Vec<std::path::PathBuf> = files.iter().map(|f| f.path.clone()).collect();
1273 let root_config_search_roots = collect_config_search_roots(&config.root, &file_paths);
1274 let root_config_search_root_refs: Vec<&Path> = root_config_search_roots
1275 .iter()
1276 .map(std::path::PathBuf::as_path)
1277 .collect();
1278
1279 let mut result = if let Some(pkg) = root_pkg {
1280 registry
1281 .try_run_with_search_roots(
1282 pkg,
1283 &config.root,
1284 &file_paths,
1285 &root_config_search_root_refs,
1286 config.production,
1287 )
1288 .map_err(|errors| {
1289 FallowError::config(plugins::registry::format_plugin_regex_errors(&errors))
1290 })?
1291 } else {
1292 plugins::AggregatedPluginResult::default()
1293 };
1294 if let Some(pkg) = root_pkg {
1295 append_package_file_asset_patterns(&mut result, "", pkg);
1296 }
1297
1298 if workspaces.is_empty() {
1299 gate_auto_import_entry_patterns(&mut result, config, workspaces);
1300 return Ok(result);
1301 }
1302
1303 append_workspace_package_file_asset_patterns(&mut result, config, workspace_pkgs);
1304
1305 let root_active_plugins: rustc_hash::FxHashSet<&str> =
1306 result.active_plugins.iter().map(String::as_str).collect();
1307
1308 let precompiled_matchers = registry.precompile_config_matchers();
1309 let workspace_relative_files = bucket_files_by_workspace(workspace_pkgs, &file_paths);
1310
1311 let ws_results: Vec<_> = workspace_pkgs
1312 .par_iter()
1313 .zip(workspace_relative_files.par_iter())
1314 .filter_map(|((ws, ws_pkg), relative_files)| {
1315 let ws_result = match registry.try_run_workspace_fast(
1316 ws_pkg,
1317 &ws.root,
1318 &config.root,
1319 &precompiled_matchers,
1320 relative_files,
1321 &root_active_plugins,
1322 config.production,
1323 ) {
1324 Ok(result) => result,
1325 Err(errors) => return Some(Err(errors)),
1326 };
1327 if ws_result.active_plugins.is_empty() {
1328 return None;
1329 }
1330 let ws_prefix = ws
1331 .root
1332 .strip_prefix(&config.root)
1333 .unwrap_or(&ws.root)
1334 .to_string_lossy()
1335 .into_owned();
1336 Some(Ok((ws_result, ws_prefix)))
1337 })
1338 .collect::<Vec<_>>();
1339
1340 let mut regex_errors = Vec::new();
1341 for ws_result in ws_results {
1342 match ws_result {
1343 Ok((mut ws_result, ws_prefix)) => {
1344 ws_result.apply_workspace_prefix(&ws_prefix);
1345 ws_result.config_patterns.clear();
1346 ws_result.script_used_packages.clear();
1347 result.merge_into(ws_result);
1348 }
1349 Err(mut errors) => regex_errors.append(&mut errors),
1350 }
1351 }
1352 if !regex_errors.is_empty() {
1353 return Err(FallowError::config(
1354 plugins::registry::format_plugin_regex_errors(®ex_errors),
1355 ));
1356 }
1357
1358 gate_auto_import_entry_patterns(&mut result, config, workspaces);
1359
1360 Ok(result)
1361}
1362
1363fn gate_auto_import_entry_patterns(
1369 result: &mut plugins::AggregatedPluginResult,
1370 config: &ResolvedConfig,
1371 workspaces: &[fallow_config::WorkspaceInfo],
1372) {
1373 if !config.auto_imports {
1374 return;
1375 }
1376 if !result.active_plugins.iter().any(|name| name == "nuxt") {
1377 return;
1378 }
1379 let components_custom = plugins::nuxt::config_declares_components(&config.root)
1380 || workspaces
1381 .iter()
1382 .any(|ws| plugins::nuxt::config_declares_components(&ws.root));
1383 let imports_custom = plugins::nuxt::config_declares_imports(&config.root)
1384 || workspaces
1385 .iter()
1386 .any(|ws| plugins::nuxt::config_declares_imports(&ws.root));
1387 result.entry_patterns.retain(|(rule, plugin)| {
1388 if plugin != "nuxt" {
1389 return true;
1390 }
1391 if !components_custom && plugins::nuxt::is_component_entry_pattern(&rule.pattern) {
1392 return false;
1393 }
1394 if !imports_custom && plugins::nuxt::is_script_auto_import_entry_pattern(&rule.pattern) {
1395 return false;
1396 }
1397 true
1398 });
1399}
1400
1401fn bucket_files_by_workspace(
1402 workspace_pkgs: &[LoadedWorkspacePackage<'_>],
1403 file_paths: &[std::path::PathBuf],
1404) -> Vec<Vec<(std::path::PathBuf, String)>> {
1405 let mut buckets = vec![Vec::new(); workspace_pkgs.len()];
1406
1407 for file_path in file_paths {
1408 for (idx, (ws, _)) in workspace_pkgs.iter().enumerate() {
1409 if let Ok(relative) = file_path.strip_prefix(&ws.root) {
1410 buckets[idx].push((file_path.clone(), relative.to_string_lossy().into_owned()));
1411 break;
1412 }
1413 }
1414 }
1415
1416 buckets
1417}
1418
1419fn collect_config_search_roots(
1420 root: &Path,
1421 file_paths: &[std::path::PathBuf],
1422) -> Vec<std::path::PathBuf> {
1423 let mut roots: rustc_hash::FxHashSet<std::path::PathBuf> = rustc_hash::FxHashSet::default();
1424 roots.insert(root.to_path_buf());
1425
1426 for file_path in file_paths {
1427 let mut current = file_path.parent();
1428 while let Some(dir) = current {
1429 if !dir.starts_with(root) {
1430 break;
1431 }
1432 roots.insert(dir.to_path_buf());
1433 if dir == root {
1434 break;
1435 }
1436 current = dir.parent();
1437 }
1438 }
1439
1440 let mut roots_vec: Vec<_> = roots.into_iter().collect();
1441 roots_vec.sort();
1442 roots_vec
1443}
1444
1445#[deprecated(
1451 since = "2.76.0",
1452 note = "fallow_core is internal; use fallow_cli::programmatic::detect_dead_code instead (build a `DeadCodeOptions { analysis: AnalysisOptions { root, ..default() }, ..default() }`). See docs/fallow-core-migration.md and ADR-008."
1453)]
1454pub fn analyze_project(root: &Path) -> Result<AnalysisResults, FallowError> {
1455 let config = default_config(root);
1456 #[expect(
1457 deprecated,
1458 reason = "ADR-008: thin wrapper, internal call into the same deprecated surface"
1459 )]
1460 analyze_with_usages(&config)
1461}
1462
1463pub fn config_for_project(
1471 root: &Path,
1472 config_path: Option<&Path>,
1473) -> Result<(ResolvedConfig, Option<std::path::PathBuf>), FallowError> {
1474 let user_config = if let Some(path) = config_path {
1475 Some((
1476 fallow_config::FallowConfig::load(path)
1477 .map_err(|e| FallowError::config(format!("{e:#}")))?,
1478 path.to_path_buf(),
1479 ))
1480 } else {
1481 fallow_config::FallowConfig::find_and_load(root).map_err(FallowError::config)?
1482 };
1483
1484 let config = match user_config {
1485 Some((mut config, path)) => {
1486 let dead_code_production = config
1487 .production
1488 .for_analysis(fallow_config::ProductionAnalysis::DeadCode);
1489 config.production = dead_code_production.into();
1490 config
1491 .validate_resolved_boundaries(root)
1492 .map_err(|errors| {
1493 let joined = errors
1494 .iter()
1495 .map(ToString::to_string)
1496 .collect::<Vec<_>>()
1497 .join("\n - ");
1498 FallowError::config(format!("invalid boundary configuration:\n - {joined}"))
1499 })?;
1500 fallow_config::load_rule_packs(root, &config.rule_packs).map_err(|errors| {
1501 let joined = errors
1502 .iter()
1503 .map(ToString::to_string)
1504 .collect::<Vec<_>>()
1505 .join("\n - ");
1506 FallowError::config(format!("invalid rule pack:\n - {joined}"))
1507 })?;
1508 (
1509 config.resolve(
1510 root.to_path_buf(),
1511 fallow_config::OutputFormat::Human,
1512 num_cpus(),
1513 false,
1514 true, None, ),
1517 Some(path),
1518 )
1519 }
1520 None => (
1521 fallow_config::FallowConfig::default().resolve(
1522 root.to_path_buf(),
1523 fallow_config::OutputFormat::Human,
1524 num_cpus(),
1525 false,
1526 true,
1527 None,
1528 ),
1529 None,
1530 ),
1531 };
1532
1533 Ok(config)
1534}
1535
1536pub(crate) fn default_config(root: &Path) -> ResolvedConfig {
1547 config_for_project(root, None).map_or_else(
1548 |_| {
1549 fallow_config::FallowConfig::default().resolve(
1550 root.to_path_buf(),
1551 fallow_config::OutputFormat::Human,
1552 num_cpus(),
1553 false,
1554 true,
1555 None,
1556 )
1557 },
1558 |(config, _)| config,
1559 )
1560}
1561
1562fn num_cpus() -> usize {
1563 std::thread::available_parallelism().map_or(4, std::num::NonZeroUsize::get)
1564}
1565
1566#[cfg(test)]
1567mod tests {
1568 use super::{
1569 bucket_files_by_workspace, collect_config_search_roots,
1570 format_undeclared_workspace_warning, warn_undeclared_workspaces,
1571 };
1572 use std::path::{Path, PathBuf};
1573
1574 use fallow_config::{WorkspaceDiagnostic, WorkspaceDiagnosticKind};
1575
1576 fn diag(root: &Path, relative: &str) -> WorkspaceDiagnostic {
1577 WorkspaceDiagnostic::new(
1578 root,
1579 root.join(relative),
1580 WorkspaceDiagnosticKind::UndeclaredWorkspace,
1581 )
1582 }
1583
1584 #[test]
1585 fn undeclared_workspace_warning_is_singular_for_one_path() {
1586 let root = Path::new("/repo");
1587 let warning = format_undeclared_workspace_warning(root, &[diag(root, "packages/api")])
1588 .expect("warning should be rendered");
1589
1590 assert_eq!(
1591 warning,
1592 "1 directory with package.json is not declared as a workspace: packages/api. Add that path to package.json workspaces or pnpm-workspace.yaml if it should be analyzed as a workspace."
1593 );
1594 }
1595
1596 #[test]
1597 fn undeclared_workspace_warning_summarizes_many_paths() {
1598 let root = PathBuf::from("/repo");
1599 let diagnostics = [
1600 "examples/a",
1601 "examples/b",
1602 "examples/c",
1603 "examples/d",
1604 "examples/e",
1605 "examples/f",
1606 ]
1607 .into_iter()
1608 .map(|path| diag(&root, path))
1609 .collect::<Vec<_>>();
1610
1611 let warning = format_undeclared_workspace_warning(&root, &diagnostics)
1612 .expect("warning should be rendered");
1613
1614 assert_eq!(
1615 warning,
1616 "6 directories with package.json are not declared as workspaces: examples/a, examples/b, examples/c, examples/d, examples/e (and 1 more). Add those paths to package.json workspaces or pnpm-workspace.yaml if they should be analyzed as workspaces."
1617 );
1618 }
1619
1620 #[test]
1621 fn collect_config_search_roots_includes_file_ancestors_once() {
1622 let root = PathBuf::from("/repo");
1623 let search_roots = collect_config_search_roots(
1624 &root,
1625 &[
1626 root.join("apps/query/src/main.ts"),
1627 root.join("packages/shared/lib/index.ts"),
1628 ],
1629 );
1630
1631 assert_eq!(
1632 search_roots,
1633 vec![
1634 root.clone(),
1635 root.join("apps"),
1636 root.join("apps/query"),
1637 root.join("apps/query/src"),
1638 root.join("packages"),
1639 root.join("packages/shared"),
1640 root.join("packages/shared/lib"),
1641 ]
1642 );
1643 }
1644
1645 #[test]
1646 fn bucket_files_by_workspace_uses_workspace_relative_paths() {
1647 let root = PathBuf::from("/repo");
1648 let ui = fallow_config::WorkspaceInfo {
1649 root: root.join("apps/ui"),
1650 name: "ui".to_string(),
1651 is_internal_dependency: false,
1652 };
1653 let api = fallow_config::WorkspaceInfo {
1654 root: root.join("apps/api"),
1655 name: "api".to_string(),
1656 is_internal_dependency: false,
1657 };
1658 let workspace_pkgs = vec![
1659 (
1660 &ui,
1661 fallow_config::PackageJson {
1662 name: Some("ui".to_string()),
1663 ..Default::default()
1664 },
1665 ),
1666 (
1667 &api,
1668 fallow_config::PackageJson {
1669 name: Some("api".to_string()),
1670 ..Default::default()
1671 },
1672 ),
1673 ];
1674 let files = vec![
1675 root.join("apps/ui/vite.config.ts"),
1676 root.join("apps/ui/src/main.ts"),
1677 root.join("apps/api/src/server.ts"),
1678 root.join("tools/build.ts"),
1679 ];
1680
1681 let buckets = bucket_files_by_workspace(&workspace_pkgs, &files);
1682
1683 assert_eq!(
1684 buckets[0],
1685 vec![
1686 (
1687 root.join("apps/ui/vite.config.ts"),
1688 "vite.config.ts".to_string()
1689 ),
1690 (root.join("apps/ui/src/main.ts"), "src/main.ts".to_string()),
1691 ]
1692 );
1693 assert_eq!(
1694 buckets[1],
1695 vec![(
1696 root.join("apps/api/src/server.ts"),
1697 "src/server.ts".to_string()
1698 )]
1699 );
1700 }
1701
1702 #[test]
1703 fn warn_undeclared_workspaces_suppresses_paths_already_flagged_as_malformed() {
1704 let dir = tempfile::tempdir().expect("create temp dir");
1705 let pkg_good = dir.path().join("packages").join("good");
1706 let pkg_bad = dir.path().join("packages").join("bad");
1707 std::fs::create_dir_all(&pkg_good).unwrap();
1708 std::fs::create_dir_all(&pkg_bad).unwrap();
1709 std::fs::write(
1710 dir.path().join("package.json"),
1711 r#"{"workspaces": ["packages/*"]}"#,
1712 )
1713 .unwrap();
1714 std::fs::write(pkg_good.join("package.json"), r#"{"name": "good"}"#).unwrap();
1715 std::fs::write(pkg_bad.join("package.json"), r"{,").unwrap();
1716
1717 let (workspaces, diagnostics) = fallow_config::discover_workspaces_with_diagnostics(
1718 dir.path(),
1719 &globset::GlobSet::empty(),
1720 )
1721 .expect("root package.json is valid");
1722 assert_eq!(workspaces.len(), 1, "only the valid workspace discovers");
1723 fallow_config::stash_workspace_diagnostics(dir.path(), diagnostics);
1724
1725 warn_undeclared_workspaces(dir.path(), &workspaces, &globset::GlobSet::empty(), false);
1726
1727 let diagnostics = fallow_config::workspace_diagnostics_for(dir.path());
1728 let mut malformed = 0;
1729 let mut undeclared_for_bad = 0;
1730 for diag in &diagnostics {
1731 if matches!(
1732 diag.kind,
1733 WorkspaceDiagnosticKind::MalformedPackageJson { .. }
1734 ) && diag.path.ends_with("bad")
1735 {
1736 malformed += 1;
1737 }
1738 if matches!(diag.kind, WorkspaceDiagnosticKind::UndeclaredWorkspace)
1739 && diag.path.ends_with("bad")
1740 {
1741 undeclared_for_bad += 1;
1742 }
1743 }
1744 assert_eq!(
1745 malformed, 1,
1746 "expected one MalformedPackageJson for packages/bad: {diagnostics:?}"
1747 );
1748 assert_eq!(
1749 undeclared_for_bad, 0,
1750 "warn_undeclared_workspaces must NOT re-flag a path that already \
1751 carries MalformedPackageJson; got duplicates: {diagnostics:?}"
1752 );
1753 }
1754}