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 let profile = PipelineProfile {
564 discover_ms,
565 workspaces_ms,
566 plugins_ms,
567 scripts_ms,
568 parse_ms: 0.0,
569 cache_ms: 0.0,
570 entry_points_ms,
571 resolve_ms,
572 graph_ms,
573 analyze_ms,
574 total_ms,
575 file_count: files.len(),
576 workspace_count: workspaces.len(),
577 module_count: modules.len(),
578 entry_point_count: entry_points.all.len(),
579 cache_hits: 0,
580 cache_misses: 0,
581 parse_cpu_ms: 0.0,
582 };
583 trace_reused_pipeline_profile(&profile);
584
585 let timings = retained_pipeline_timings(true, &profile);
586
587 let file_hashes = collect_file_hashes(modules, files);
588
589 Ok(AnalysisOutput {
590 results: result,
591 timings,
592 graph: Some(graph),
593 modules: None,
594 files: None,
595 script_used_packages: plugin_result.script_used_packages.clone(),
596 file_hashes,
597 })
598}
599
600fn analyze_full(
601 config: &ResolvedConfig,
602 retain: bool,
603 collect_usages: bool,
604 need_complexity: bool,
605 retain_modules: bool,
606) -> Result<AnalysisOutput, FallowError> {
607 let _span = tracing::info_span!("fallow_analyze").entered();
608 let pipeline_start = Instant::now();
609
610 let progress = new_analysis_progress(config);
611 warn_missing_node_modules(config);
612
613 let (workspaces_vec, workspaces_ms) = discover_analysis_workspaces(config);
614 let root_pkg = load_root_package_json(config);
615 let discovery_hidden_dir_scopes =
616 discover::collect_hidden_dir_scopes(config, root_pkg.as_ref(), &workspaces_vec);
617
618 let t = Instant::now();
619 progress.set_stage("discovering files...");
620 let discovered_files =
621 discover::discover_files_with_additional_hidden_dirs(config, &discovery_hidden_dir_scopes);
622 let discover_ms = t.elapsed().as_secs_f64() * 1000.0;
623
624 let project = project::ProjectState::new(discovered_files, workspaces_vec);
625 let files = project.files();
626 let workspaces = project.workspaces();
627 let workspace_pkgs = load_workspace_packages(workspaces);
628
629 let t = Instant::now();
630 progress.set_stage("detecting plugins...");
631 let mut plugin_result = run_plugins(
632 config,
633 files,
634 workspaces,
635 root_pkg.as_ref(),
636 &workspace_pkgs,
637 )?;
638 let plugins_ms = t.elapsed().as_secs_f64() * 1000.0;
639
640 let t = Instant::now();
641 analyze_all_scripts(
642 config,
643 workspaces,
644 root_pkg.as_ref(),
645 &workspace_pkgs,
646 &mut plugin_result,
647 );
648 let scripts_ms = t.elapsed().as_secs_f64() * 1000.0;
649
650 let t = Instant::now();
651 progress.set_stage(&format!("parsing {} files...", files.len()));
652 let AnalysisParseOutput {
653 mut modules,
654 parse_ms,
655 cache_ms,
656 cache_hits,
657 cache_misses,
658 parse_cpu_ms,
659 } = parse_analysis_modules(config, files, need_complexity, t);
660
661 let t = Instant::now();
662 let entry_points = discover_all_entry_points(
663 config,
664 files,
665 workspaces,
666 root_pkg.as_ref(),
667 &workspace_pkgs,
668 &plugin_result,
669 );
670 let entry_points_ms = t.elapsed().as_secs_f64() * 1000.0;
671
672 let t = Instant::now();
673 progress.set_stage("resolving imports...");
674 let resolved = resolve_analysis_imports(&modules, files, workspaces, &plugin_result, config);
675 let resolve_ms = t.elapsed().as_secs_f64() * 1000.0;
676
677 let t = Instant::now();
678 progress.set_stage("building module graph...");
679 let graph = build_analysis_graph(&resolved, &entry_points, files, &modules, workspaces);
680 for module in &mut modules {
681 module.release_resolution_payload();
682 }
683 let graph_ms = t.elapsed().as_secs_f64() * 1000.0;
684
685 let ep_summary = summarize_entry_points(&entry_points.all);
686
687 let t = Instant::now();
688 progress.set_stage("analyzing...");
689 #[expect(
690 deprecated,
691 reason = "ADR-008 keeps workspace path-dependency calls while warning external fallow-core consumers"
692 )]
693 let mut result = analyze::find_dead_code_full(
694 &graph,
695 config,
696 &resolved,
697 Some(&plugin_result),
698 workspaces,
699 &modules,
700 collect_usages,
701 );
702 let analyze_ms = t.elapsed().as_secs_f64() * 1000.0;
703 progress.finish();
704
705 result.entry_point_summary = Some(ep_summary);
706
707 let total_ms = pipeline_start.elapsed().as_secs_f64() * 1000.0;
708
709 let profile = PipelineProfile {
710 discover_ms,
711 workspaces_ms,
712 plugins_ms,
713 scripts_ms,
714 parse_ms,
715 cache_ms,
716 entry_points_ms,
717 resolve_ms,
718 graph_ms,
719 analyze_ms,
720 total_ms,
721 file_count: files.len(),
722 workspace_count: workspaces.len(),
723 module_count: modules.len(),
724 entry_point_count: entry_points.all.len(),
725 cache_hits,
726 cache_misses,
727 parse_cpu_ms,
728 };
729 trace_pipeline_profile(&profile);
730
731 let timings = retained_pipeline_timings(retain, &profile);
732
733 let file_hashes = collect_file_hashes(&modules, files);
734
735 Ok(AnalysisOutput {
736 results: result,
737 timings,
738 graph: if retain { Some(graph) } else { None },
739 modules: if retain_modules { Some(modules) } else { None },
740 files: if retain_modules {
741 Some(files.to_vec())
742 } else {
743 None
744 },
745 script_used_packages: plugin_result.script_used_packages,
746 file_hashes,
747 })
748}
749
750#[derive(Clone, Copy)]
751struct PipelineProfile {
752 discover_ms: f64,
753 workspaces_ms: f64,
754 plugins_ms: f64,
755 scripts_ms: f64,
756 parse_ms: f64,
757 cache_ms: f64,
758 entry_points_ms: f64,
759 resolve_ms: f64,
760 graph_ms: f64,
761 analyze_ms: f64,
762 total_ms: f64,
763 file_count: usize,
764 workspace_count: usize,
765 module_count: usize,
766 entry_point_count: usize,
767 cache_hits: usize,
768 cache_misses: usize,
769 parse_cpu_ms: f64,
770}
771
772struct AnalysisParseOutput {
773 modules: Vec<extract::ModuleInfo>,
774 parse_ms: f64,
775 cache_ms: f64,
776 cache_hits: usize,
777 cache_misses: usize,
778 parse_cpu_ms: f64,
779}
780
781fn parse_analysis_modules(
782 config: &ResolvedConfig,
783 files: &[discover::DiscoveredFile],
784 need_complexity: bool,
785 start: Instant,
786) -> AnalysisParseOutput {
787 let cache_max_size_bytes = resolve_cache_max_size_bytes(config);
788 let mut cache_store = if config.no_cache {
789 None
790 } else {
791 cache::CacheStore::load(
792 &config.cache_dir,
793 config.cache_config_hash,
794 cache_max_size_bytes,
795 )
796 };
797
798 let parse_result = extract::parse_all_files(files, cache_store.as_ref(), need_complexity);
799 let modules = parse_result.modules;
800 let parse_ms = start.elapsed().as_secs_f64() * 1000.0;
801 let cache_ms = update_parse_cache_if_enabled(
802 config,
803 &mut cache_store,
804 &modules,
805 files,
806 cache_max_size_bytes,
807 );
808
809 AnalysisParseOutput {
810 modules,
811 parse_ms,
812 cache_ms,
813 cache_hits: parse_result.cache_hits,
814 cache_misses: parse_result.cache_misses,
815 parse_cpu_ms: parse_result.parse_cpu_ms,
816 }
817}
818
819fn retained_pipeline_timings(retain: bool, profile: &PipelineProfile) -> Option<PipelineTimings> {
820 retain.then_some(PipelineTimings {
821 discover_files_ms: profile.discover_ms,
822 file_count: profile.file_count,
823 workspaces_ms: profile.workspaces_ms,
824 workspace_count: profile.workspace_count,
825 plugins_ms: profile.plugins_ms,
826 script_analysis_ms: profile.scripts_ms,
827 parse_extract_ms: profile.parse_ms,
828 parse_cpu_ms: profile.parse_cpu_ms,
829 module_count: profile.module_count,
830 cache_hits: profile.cache_hits,
831 cache_misses: profile.cache_misses,
832 cache_update_ms: profile.cache_ms,
833 entry_points_ms: profile.entry_points_ms,
834 entry_point_count: profile.entry_point_count,
835 resolve_imports_ms: profile.resolve_ms,
836 build_graph_ms: profile.graph_ms,
837 analyze_ms: profile.analyze_ms,
838 duplication_ms: None,
839 total_ms: profile.total_ms,
840 })
841}
842
843fn trace_reused_pipeline_profile(profile: &PipelineProfile) {
844 tracing::debug!(
845 "\n┌─ Pipeline Profile (reuse) ─────────────────────\n\
846 │ discover files: {:>8.1}ms ({} files)\n\
847 │ workspaces: {:>8.1}ms\n\
848 │ plugins: {:>8.1}ms\n\
849 │ script analysis: {:>8.1}ms\n\
850 │ parse/extract: SKIPPED (reused {} modules)\n\
851 │ entry points: {:>8.1}ms ({} entries)\n\
852 │ resolve imports: {:>8.1}ms\n\
853 │ build graph: {:>8.1}ms\n\
854 │ analyze: {:>8.1}ms\n\
855 │ ────────────────────────────────────────────\n\
856 │ TOTAL: {:>8.1}ms\n\
857 └─────────────────────────────────────────────────",
858 profile.discover_ms,
859 profile.file_count,
860 profile.workspaces_ms,
861 profile.plugins_ms,
862 profile.scripts_ms,
863 profile.module_count,
864 profile.entry_points_ms,
865 profile.entry_point_count,
866 profile.resolve_ms,
867 profile.graph_ms,
868 profile.analyze_ms,
869 profile.total_ms,
870 );
871}
872
873fn update_parse_cache_if_enabled(
874 config: &ResolvedConfig,
875 cache_store: &mut Option<cache::CacheStore>,
876 modules: &[extract::ModuleInfo],
877 files: &[discover::DiscoveredFile],
878 cache_max_size_bytes: usize,
879) -> f64 {
880 let t = Instant::now();
881 if !config.no_cache {
882 let store = cache_store.get_or_insert_with(cache::CacheStore::new);
883 update_cache(store, modules, files);
884 if let Err(error) = store.save(
885 &config.cache_dir,
886 config.cache_config_hash,
887 cache_max_size_bytes,
888 ) {
889 tracing::warn!("Failed to save cache: {error}");
890 }
891 }
892 t.elapsed().as_secs_f64() * 1000.0
893}
894
895fn resolve_analysis_imports(
896 modules: &[extract::ModuleInfo],
897 files: &[discover::DiscoveredFile],
898 workspaces: &[fallow_config::WorkspaceInfo],
899 plugin_result: &plugins::AggregatedPluginResult,
900 config: &ResolvedConfig,
901) -> Vec<resolve::ResolvedModule> {
902 let mut resolved = resolve::resolve_all_imports(
903 modules,
904 files,
905 workspaces,
906 &plugin_result.active_plugins,
907 &plugin_result.path_aliases,
908 &plugin_result.auto_imports,
909 &plugin_result.scss_include_paths,
910 &plugin_result.static_dir_mappings,
911 &config.root,
912 &config.resolve.conditions,
913 );
914 external_style_usage::augment_external_style_package_usage(
915 &mut resolved,
916 config,
917 workspaces,
918 plugin_result,
919 );
920 resolved
921}
922
923fn build_analysis_graph(
924 resolved: &[resolve::ResolvedModule],
925 entry_points: &discover::CategorizedEntryPoints,
926 files: &[discover::DiscoveredFile],
927 modules: &[extract::ModuleInfo],
928 workspaces: &[fallow_config::WorkspaceInfo],
929) -> graph::ModuleGraph {
930 let mut graph = graph::ModuleGraph::build_with_reachability_roots(
931 resolved,
932 &entry_points.all,
933 &entry_points.runtime,
934 &entry_points.test,
935 files,
936 );
937 credit_package_path_references(&mut graph, modules);
938 credit_workspace_package_usage(&mut graph, resolved, workspaces);
939 graph
940}
941
942fn collect_file_hashes(
943 modules: &[extract::ModuleInfo],
944 files: &[discover::DiscoveredFile],
945) -> rustc_hash::FxHashMap<std::path::PathBuf, u64> {
946 modules
947 .iter()
948 .filter_map(|module| {
949 files
950 .get(module.file_id.0 as usize)
951 .map(|file| (file.path.clone(), module.content_hash))
952 })
953 .collect()
954}
955
956fn trace_pipeline_profile(profile: &PipelineProfile) {
957 let PipelineProfile {
958 discover_ms,
959 workspaces_ms,
960 plugins_ms,
961 scripts_ms,
962 parse_ms,
963 cache_ms,
964 entry_points_ms,
965 resolve_ms,
966 graph_ms,
967 analyze_ms,
968 total_ms,
969 file_count,
970 module_count,
971 entry_point_count,
972 cache_hits,
973 cache_misses,
974 ..
975 } = *profile;
976 let cache_summary = if cache_hits > 0 {
977 format!(" ({cache_hits} cached, {cache_misses} parsed)")
978 } else {
979 String::new()
980 };
981
982 tracing::debug!(
983 "\n┌─ Pipeline Profile ─────────────────────────────\n\
984 │ discover files: {:>8.1}ms ({} files)\n\
985 │ workspaces: {:>8.1}ms\n\
986 │ plugins: {:>8.1}ms\n\
987 │ script analysis: {:>8.1}ms\n\
988 │ parse/extract: {:>8.1}ms ({} modules{})\n\
989 │ cache update: {:>8.1}ms\n\
990 │ entry points: {:>8.1}ms ({} entries)\n\
991 │ resolve imports: {:>8.1}ms\n\
992 │ build graph: {:>8.1}ms\n\
993 │ analyze: {:>8.1}ms\n\
994 │ ────────────────────────────────────────────\n\
995 │ TOTAL: {:>8.1}ms\n\
996 └─────────────────────────────────────────────────",
997 discover_ms,
998 file_count,
999 workspaces_ms,
1000 plugins_ms,
1001 scripts_ms,
1002 parse_ms,
1003 module_count,
1004 cache_summary,
1005 cache_ms,
1006 entry_points_ms,
1007 entry_point_count,
1008 resolve_ms,
1009 graph_ms,
1010 analyze_ms,
1011 total_ms,
1012 );
1013}
1014
1015fn load_root_package_json(config: &ResolvedConfig) -> Option<PackageJson> {
1020 PackageJson::load(&config.root.join("package.json")).ok()
1021}
1022
1023fn load_workspace_packages(
1024 workspaces: &[fallow_config::WorkspaceInfo],
1025) -> Vec<LoadedWorkspacePackage<'_>> {
1026 workspaces
1027 .iter()
1028 .filter_map(|ws| {
1029 PackageJson::load(&ws.root.join("package.json"))
1030 .ok()
1031 .map(|pkg| (ws, pkg))
1032 })
1033 .collect()
1034}
1035
1036fn analyze_all_scripts(
1037 config: &ResolvedConfig,
1038 workspaces: &[fallow_config::WorkspaceInfo],
1039 root_pkg: Option<&PackageJson>,
1040 workspace_pkgs: &[LoadedWorkspacePackage<'_>],
1041 plugin_result: &mut plugins::AggregatedPluginResult,
1042) {
1043 let mut all_dep_names: Vec<String> = Vec::new();
1044 if let Some(pkg) = root_pkg {
1045 all_dep_names.extend(pkg.all_dependency_names());
1046 }
1047 for (_, ws_pkg) in workspace_pkgs {
1048 all_dep_names.extend(ws_pkg.all_dependency_names());
1049 }
1050 all_dep_names.sort_unstable();
1051 all_dep_names.dedup();
1052 let all_dep_set: FxHashSet<String> = all_dep_names.iter().cloned().collect();
1053 let mut all_script_names: FxHashSet<String> = FxHashSet::default();
1054 if let Some(pkg) = root_pkg
1055 && let Some(ref pkg_scripts) = pkg.scripts
1056 {
1057 all_script_names.extend(pkg_scripts.keys().cloned());
1058 }
1059 for (_, ws_pkg) in workspace_pkgs {
1060 if let Some(ref ws_scripts) = ws_pkg.scripts {
1061 all_script_names.extend(ws_scripts.keys().cloned());
1062 }
1063 }
1064
1065 let mut nm_roots: Vec<&std::path::Path> = Vec::new();
1066 if config.root.join("node_modules").is_dir() {
1067 nm_roots.push(&config.root);
1068 }
1069 for ws in workspaces {
1070 if ws.root.join("node_modules").is_dir() {
1071 nm_roots.push(&ws.root);
1072 }
1073 }
1074 let bin_map = scripts::build_bin_to_package_map(&nm_roots, &all_dep_names);
1075
1076 if let Some(pkg) = root_pkg
1077 && let Some(ref pkg_scripts) = pkg.scripts
1078 {
1079 let scripts_to_analyze = if config.production {
1080 scripts::filter_production_scripts(pkg_scripts)
1081 } else {
1082 pkg_scripts.clone()
1083 };
1084 let script_names: FxHashSet<String> = pkg_scripts.keys().cloned().collect();
1085 let script_analysis = scripts::analyze_scripts_with_dependency_context(
1086 &scripts_to_analyze,
1087 &config.root,
1088 &bin_map,
1089 &all_dep_set,
1090 &script_names,
1091 );
1092 plugin_result.script_used_packages = script_analysis.used_packages;
1093
1094 for config_file in &script_analysis.config_files {
1095 plugin_result
1096 .discovered_always_used
1097 .push((config_file.clone(), "scripts".to_string()));
1098 }
1099 for entry in &script_analysis.entry_files {
1100 if let Some(pat) = scripts::normalize_script_entry_pattern("", entry) {
1101 plugin_result
1102 .entry_patterns
1103 .push((plugins::PathRule::new(pat), "scripts".to_string()));
1104 }
1105 }
1106 }
1107 use rayon::prelude::*;
1108 type WsScriptOut = (
1109 Vec<String>,
1110 Vec<(String, String)>,
1111 Vec<(plugins::PathRule, String)>,
1112 );
1113 let ws_results: Vec<WsScriptOut> = workspace_pkgs
1114 .par_iter()
1115 .map(|(ws, ws_pkg)| {
1116 let mut used_packages = Vec::new();
1117 let mut discovered_always_used: Vec<(String, String)> = Vec::new();
1118 let mut entry_patterns: Vec<(plugins::PathRule, String)> = Vec::new();
1119 if let Some(ref ws_scripts) = ws_pkg.scripts {
1120 let scripts_to_analyze = if config.production {
1121 scripts::filter_production_scripts(ws_scripts)
1122 } else {
1123 ws_scripts.clone()
1124 };
1125 let script_names: FxHashSet<String> = ws_scripts.keys().cloned().collect();
1126 let ws_analysis = scripts::analyze_scripts_with_dependency_context(
1127 &scripts_to_analyze,
1128 &ws.root,
1129 &bin_map,
1130 &all_dep_set,
1131 &script_names,
1132 );
1133 used_packages.extend(ws_analysis.used_packages);
1134
1135 let ws_prefix = ws
1136 .root
1137 .strip_prefix(&config.root)
1138 .unwrap_or(&ws.root)
1139 .to_string_lossy();
1140 for config_file in &ws_analysis.config_files {
1141 discovered_always_used
1142 .push((format!("{ws_prefix}/{config_file}"), "scripts".to_string()));
1143 }
1144 for entry in &ws_analysis.entry_files {
1145 if let Some(pat) = scripts::normalize_script_entry_pattern(&ws_prefix, entry) {
1146 entry_patterns.push((plugins::PathRule::new(pat), "scripts".to_string()));
1147 }
1148 }
1149 }
1150 (used_packages, discovered_always_used, entry_patterns)
1151 })
1152 .collect();
1153 for (used_packages, discovered_always_used, entry_patterns) in ws_results {
1154 plugin_result.script_used_packages.extend(used_packages);
1155 plugin_result
1156 .discovered_always_used
1157 .extend(discovered_always_used);
1158 plugin_result.entry_patterns.extend(entry_patterns);
1159 }
1160
1161 let ci_analysis =
1162 scripts::ci::analyze_ci_files(&config.root, &bin_map, &all_dep_set, &all_script_names);
1163 plugin_result
1164 .script_used_packages
1165 .extend(ci_analysis.used_packages);
1166 for entry in &ci_analysis.entry_files {
1167 if let Some(pat) = scripts::normalize_script_entry_pattern("", entry) {
1168 plugin_result
1169 .entry_patterns
1170 .push((plugins::PathRule::new(pat), "scripts".to_string()));
1171 }
1172 }
1173 plugin_result
1174 .entry_point_roles
1175 .entry("scripts".to_string())
1176 .or_insert(EntryPointRole::Support);
1177}
1178
1179fn discover_all_entry_points(
1181 config: &ResolvedConfig,
1182 files: &[discover::DiscoveredFile],
1183 workspaces: &[fallow_config::WorkspaceInfo],
1184 root_pkg: Option<&PackageJson>,
1185 workspace_pkgs: &[LoadedWorkspacePackage<'_>],
1186 plugin_result: &plugins::AggregatedPluginResult,
1187) -> discover::CategorizedEntryPoints {
1188 let mut entry_points = discover::CategorizedEntryPoints::default();
1189 let root_discovery = discover::discover_entry_points_with_warnings_from_pkg(
1190 config,
1191 files,
1192 root_pkg,
1193 workspaces.is_empty(),
1194 );
1195
1196 let workspace_pkg_by_root: rustc_hash::FxHashMap<std::path::PathBuf, &PackageJson> =
1197 workspace_pkgs
1198 .iter()
1199 .map(|(ws, pkg)| (ws.root.clone(), pkg))
1200 .collect();
1201
1202 let workspace_discovery: Vec<discover::EntryPointDiscovery> = workspaces
1203 .par_iter()
1204 .map(|ws| {
1205 let pkg = workspace_pkg_by_root.get(&ws.root).copied();
1206 discover::discover_workspace_entry_points_with_warnings_from_pkg(&ws.root, files, pkg)
1207 })
1208 .collect();
1209 let mut skipped_entries = rustc_hash::FxHashMap::default();
1210 entry_points.extend_runtime(root_discovery.entries);
1211 for (path, count) in root_discovery.skipped_entries {
1212 *skipped_entries.entry(path).or_insert(0) += count;
1213 }
1214 let mut ws_entries = Vec::new();
1215 for workspace in workspace_discovery {
1216 ws_entries.extend(workspace.entries);
1217 for (path, count) in workspace.skipped_entries {
1218 *skipped_entries.entry(path).or_insert(0) += count;
1219 }
1220 }
1221 discover::warn_skipped_entry_summary(&skipped_entries);
1222 entry_points.extend_runtime(ws_entries);
1223
1224 let plugin_entries = discover::discover_plugin_entry_point_sets(plugin_result, config, files);
1225 entry_points.extend(plugin_entries);
1226
1227 let infra_entries = discover::discover_infrastructure_entry_points(&config.root);
1228 entry_points.extend_runtime(infra_entries);
1229
1230 if !config.dynamically_loaded.is_empty() {
1231 let dynamic_entries = discover::discover_dynamically_loaded_entry_points(config, files);
1232 entry_points.extend_runtime(dynamic_entries);
1233 }
1234
1235 entry_points.dedup()
1236}
1237
1238fn summarize_entry_points(entry_points: &[discover::EntryPoint]) -> results::EntryPointSummary {
1240 let mut counts: rustc_hash::FxHashMap<String, usize> = rustc_hash::FxHashMap::default();
1241 for ep in entry_points {
1242 let category = match &ep.source {
1243 discover::EntryPointSource::PackageJsonMain
1244 | discover::EntryPointSource::PackageJsonModule
1245 | discover::EntryPointSource::PackageJsonExports
1246 | discover::EntryPointSource::PackageJsonBin
1247 | discover::EntryPointSource::PackageJsonScript => "package.json",
1248 discover::EntryPointSource::Plugin { .. } => "plugin",
1249 discover::EntryPointSource::TestFile => "test file",
1250 discover::EntryPointSource::DefaultIndex => "default index",
1251 discover::EntryPointSource::ManualEntry => "manual entry",
1252 discover::EntryPointSource::InfrastructureConfig => "config",
1253 discover::EntryPointSource::DynamicallyLoaded => "dynamically loaded",
1254 };
1255 *counts.entry(category.to_string()).or_insert(0) += 1;
1256 }
1257 let mut by_source: Vec<(String, usize)> = counts.into_iter().collect();
1258 by_source.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
1259 results::EntryPointSummary {
1260 total: entry_points.len(),
1261 by_source,
1262 }
1263}
1264
1265fn append_package_file_asset_patterns(
1266 result: &mut plugins::AggregatedPluginResult,
1267 prefix: &str,
1268 pkg: &PackageJson,
1269) {
1270 let prefix = prefix.trim_matches('/');
1271 for pattern in package_assets::scaffold_template_asset_patterns(pkg) {
1272 let pattern = if prefix.is_empty() {
1273 pattern
1274 } else {
1275 format!("{prefix}/{pattern}")
1276 };
1277 result
1278 .discovered_always_used
1279 .push((pattern, package_assets::PACKAGE_FILES_SOURCE.to_string()));
1280 }
1281}
1282
1283fn append_workspace_package_file_asset_patterns(
1284 result: &mut plugins::AggregatedPluginResult,
1285 config: &ResolvedConfig,
1286 workspace_pkgs: &[LoadedWorkspacePackage<'_>],
1287) {
1288 for (ws, ws_pkg) in workspace_pkgs {
1289 let ws_prefix = ws
1290 .root
1291 .strip_prefix(&config.root)
1292 .unwrap_or(&ws.root)
1293 .to_string_lossy()
1294 .replace('\\', "/");
1295 append_package_file_asset_patterns(result, &ws_prefix, ws_pkg);
1296 }
1297}
1298
1299fn run_plugins(
1301 config: &ResolvedConfig,
1302 files: &[discover::DiscoveredFile],
1303 workspaces: &[fallow_config::WorkspaceInfo],
1304 root_pkg: Option<&PackageJson>,
1305 workspace_pkgs: &[LoadedWorkspacePackage<'_>],
1306) -> Result<plugins::AggregatedPluginResult, FallowError> {
1307 let registry = plugins::PluginRegistry::new(config.external_plugins.clone());
1308 let file_paths: Vec<std::path::PathBuf> = files.iter().map(|f| f.path.clone()).collect();
1309 let root_config_search_roots = collect_config_search_roots(&config.root, &file_paths);
1310 let root_config_search_root_refs: Vec<&Path> = root_config_search_roots
1311 .iter()
1312 .map(std::path::PathBuf::as_path)
1313 .collect();
1314
1315 let mut result = if let Some(pkg) = root_pkg {
1316 registry
1317 .try_run_with_search_roots(
1318 pkg,
1319 &config.root,
1320 &file_paths,
1321 &root_config_search_root_refs,
1322 config.production,
1323 )
1324 .map_err(|errors| {
1325 FallowError::config(plugins::registry::format_plugin_regex_errors(&errors))
1326 })?
1327 } else {
1328 plugins::AggregatedPluginResult::default()
1329 };
1330 if let Some(pkg) = root_pkg {
1331 append_package_file_asset_patterns(&mut result, "", pkg);
1332 }
1333
1334 if workspaces.is_empty() {
1335 gate_auto_import_entry_patterns(&mut result, config, workspaces);
1336 return Ok(result);
1337 }
1338
1339 append_workspace_package_file_asset_patterns(&mut result, config, workspace_pkgs);
1340
1341 let root_active_plugins: rustc_hash::FxHashSet<&str> =
1342 result.active_plugins.iter().map(String::as_str).collect();
1343
1344 let precompiled_matchers = registry.precompile_config_matchers();
1345 let workspace_relative_files = bucket_files_by_workspace(workspace_pkgs, &file_paths);
1346
1347 let ws_results: Vec<_> = workspace_pkgs
1348 .par_iter()
1349 .zip(workspace_relative_files.par_iter())
1350 .filter_map(|((ws, ws_pkg), relative_files)| {
1351 let ws_result = match registry.try_run_workspace_fast(
1352 ws_pkg,
1353 &ws.root,
1354 &config.root,
1355 &precompiled_matchers,
1356 relative_files,
1357 &root_active_plugins,
1358 config.production,
1359 ) {
1360 Ok(result) => result,
1361 Err(errors) => return Some(Err(errors)),
1362 };
1363 if ws_result.active_plugins.is_empty() {
1364 return None;
1365 }
1366 let ws_prefix = ws
1367 .root
1368 .strip_prefix(&config.root)
1369 .unwrap_or(&ws.root)
1370 .to_string_lossy()
1371 .into_owned();
1372 Some(Ok((ws_result, ws_prefix)))
1373 })
1374 .collect::<Vec<_>>();
1375
1376 let mut regex_errors = Vec::new();
1377 for ws_result in ws_results {
1378 match ws_result {
1379 Ok((mut ws_result, ws_prefix)) => {
1380 ws_result.apply_workspace_prefix(&ws_prefix);
1381 ws_result.config_patterns.clear();
1382 ws_result.script_used_packages.clear();
1383 result.merge_into(ws_result);
1384 }
1385 Err(mut errors) => regex_errors.append(&mut errors),
1386 }
1387 }
1388 if !regex_errors.is_empty() {
1389 return Err(FallowError::config(
1390 plugins::registry::format_plugin_regex_errors(®ex_errors),
1391 ));
1392 }
1393
1394 gate_auto_import_entry_patterns(&mut result, config, workspaces);
1395
1396 Ok(result)
1397}
1398
1399fn gate_auto_import_entry_patterns(
1405 result: &mut plugins::AggregatedPluginResult,
1406 config: &ResolvedConfig,
1407 workspaces: &[fallow_config::WorkspaceInfo],
1408) {
1409 if !config.auto_imports {
1410 return;
1411 }
1412 if !result.active_plugins.iter().any(|name| name == "nuxt") {
1413 return;
1414 }
1415 let components_custom = plugins::nuxt::config_declares_components(&config.root)
1416 || workspaces
1417 .iter()
1418 .any(|ws| plugins::nuxt::config_declares_components(&ws.root));
1419 let imports_custom = plugins::nuxt::config_declares_imports(&config.root)
1420 || workspaces
1421 .iter()
1422 .any(|ws| plugins::nuxt::config_declares_imports(&ws.root));
1423 result.entry_patterns.retain(|(rule, plugin)| {
1424 if plugin != "nuxt" {
1425 return true;
1426 }
1427 if !components_custom && plugins::nuxt::is_component_entry_pattern(&rule.pattern) {
1428 return false;
1429 }
1430 if !imports_custom && plugins::nuxt::is_script_auto_import_entry_pattern(&rule.pattern) {
1431 return false;
1432 }
1433 true
1434 });
1435}
1436
1437fn bucket_files_by_workspace(
1438 workspace_pkgs: &[LoadedWorkspacePackage<'_>],
1439 file_paths: &[std::path::PathBuf],
1440) -> Vec<Vec<(std::path::PathBuf, String)>> {
1441 let mut buckets = vec![Vec::new(); workspace_pkgs.len()];
1442
1443 for file_path in file_paths {
1444 for (idx, (ws, _)) in workspace_pkgs.iter().enumerate() {
1445 if let Ok(relative) = file_path.strip_prefix(&ws.root) {
1446 buckets[idx].push((file_path.clone(), relative.to_string_lossy().into_owned()));
1447 break;
1448 }
1449 }
1450 }
1451
1452 buckets
1453}
1454
1455fn collect_config_search_roots(
1456 root: &Path,
1457 file_paths: &[std::path::PathBuf],
1458) -> Vec<std::path::PathBuf> {
1459 let mut roots: rustc_hash::FxHashSet<std::path::PathBuf> = rustc_hash::FxHashSet::default();
1460 roots.insert(root.to_path_buf());
1461
1462 for file_path in file_paths {
1463 let mut current = file_path.parent();
1464 while let Some(dir) = current {
1465 if !dir.starts_with(root) {
1466 break;
1467 }
1468 roots.insert(dir.to_path_buf());
1469 if dir == root {
1470 break;
1471 }
1472 current = dir.parent();
1473 }
1474 }
1475
1476 let mut roots_vec: Vec<_> = roots.into_iter().collect();
1477 roots_vec.sort();
1478 roots_vec
1479}
1480
1481#[deprecated(
1487 since = "2.76.0",
1488 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."
1489)]
1490pub fn analyze_project(root: &Path) -> Result<AnalysisResults, FallowError> {
1491 let config = default_config(root);
1492 #[expect(
1493 deprecated,
1494 reason = "ADR-008: thin wrapper, internal call into the same deprecated surface"
1495 )]
1496 analyze_with_usages(&config)
1497}
1498
1499pub fn config_for_project(
1507 root: &Path,
1508 config_path: Option<&Path>,
1509) -> Result<(ResolvedConfig, Option<std::path::PathBuf>), FallowError> {
1510 let user_config = if let Some(path) = config_path {
1511 Some((
1512 fallow_config::FallowConfig::load(path)
1513 .map_err(|e| FallowError::config(format!("{e:#}")))?,
1514 path.to_path_buf(),
1515 ))
1516 } else {
1517 fallow_config::FallowConfig::find_and_load(root).map_err(FallowError::config)?
1518 };
1519
1520 let config = match user_config {
1521 Some((mut config, path)) => {
1522 let dead_code_production = config
1523 .production
1524 .for_analysis(fallow_config::ProductionAnalysis::DeadCode);
1525 config.production = dead_code_production.into();
1526 config
1527 .validate_resolved_boundaries(root)
1528 .map_err(|errors| {
1529 let joined = errors
1530 .iter()
1531 .map(ToString::to_string)
1532 .collect::<Vec<_>>()
1533 .join("\n - ");
1534 FallowError::config(format!("invalid boundary configuration:\n - {joined}"))
1535 })?;
1536 fallow_config::load_rule_packs(root, &config.rule_packs).map_err(|errors| {
1537 let joined = errors
1538 .iter()
1539 .map(ToString::to_string)
1540 .collect::<Vec<_>>()
1541 .join("\n - ");
1542 FallowError::config(format!("invalid rule pack:\n - {joined}"))
1543 })?;
1544 (
1545 config.resolve(
1546 root.to_path_buf(),
1547 fallow_config::OutputFormat::Human,
1548 num_cpus(),
1549 false,
1550 true, None, ),
1553 Some(path),
1554 )
1555 }
1556 None => (
1557 fallow_config::FallowConfig::default().resolve(
1558 root.to_path_buf(),
1559 fallow_config::OutputFormat::Human,
1560 num_cpus(),
1561 false,
1562 true,
1563 None,
1564 ),
1565 None,
1566 ),
1567 };
1568
1569 Ok(config)
1570}
1571
1572pub(crate) fn default_config(root: &Path) -> ResolvedConfig {
1583 config_for_project(root, None).map_or_else(
1584 |_| {
1585 fallow_config::FallowConfig::default().resolve(
1586 root.to_path_buf(),
1587 fallow_config::OutputFormat::Human,
1588 num_cpus(),
1589 false,
1590 true,
1591 None,
1592 )
1593 },
1594 |(config, _)| config,
1595 )
1596}
1597
1598fn num_cpus() -> usize {
1599 std::thread::available_parallelism().map_or(4, std::num::NonZeroUsize::get)
1600}
1601
1602#[cfg(test)]
1603mod tests {
1604 use super::{
1605 bucket_files_by_workspace, collect_config_search_roots,
1606 format_undeclared_workspace_warning, warn_undeclared_workspaces,
1607 };
1608 use std::path::{Path, PathBuf};
1609
1610 use fallow_config::{WorkspaceDiagnostic, WorkspaceDiagnosticKind};
1611
1612 fn diag(root: &Path, relative: &str) -> WorkspaceDiagnostic {
1613 WorkspaceDiagnostic::new(
1614 root,
1615 root.join(relative),
1616 WorkspaceDiagnosticKind::UndeclaredWorkspace,
1617 )
1618 }
1619
1620 #[test]
1621 fn undeclared_workspace_warning_is_singular_for_one_path() {
1622 let root = Path::new("/repo");
1623 let warning = format_undeclared_workspace_warning(root, &[diag(root, "packages/api")])
1624 .expect("warning should be rendered");
1625
1626 assert_eq!(
1627 warning,
1628 "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."
1629 );
1630 }
1631
1632 #[test]
1633 fn undeclared_workspace_warning_summarizes_many_paths() {
1634 let root = PathBuf::from("/repo");
1635 let diagnostics = [
1636 "examples/a",
1637 "examples/b",
1638 "examples/c",
1639 "examples/d",
1640 "examples/e",
1641 "examples/f",
1642 ]
1643 .into_iter()
1644 .map(|path| diag(&root, path))
1645 .collect::<Vec<_>>();
1646
1647 let warning = format_undeclared_workspace_warning(&root, &diagnostics)
1648 .expect("warning should be rendered");
1649
1650 assert_eq!(
1651 warning,
1652 "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."
1653 );
1654 }
1655
1656 #[test]
1657 fn collect_config_search_roots_includes_file_ancestors_once() {
1658 let root = PathBuf::from("/repo");
1659 let search_roots = collect_config_search_roots(
1660 &root,
1661 &[
1662 root.join("apps/query/src/main.ts"),
1663 root.join("packages/shared/lib/index.ts"),
1664 ],
1665 );
1666
1667 assert_eq!(
1668 search_roots,
1669 vec![
1670 root.clone(),
1671 root.join("apps"),
1672 root.join("apps/query"),
1673 root.join("apps/query/src"),
1674 root.join("packages"),
1675 root.join("packages/shared"),
1676 root.join("packages/shared/lib"),
1677 ]
1678 );
1679 }
1680
1681 #[test]
1682 fn bucket_files_by_workspace_uses_workspace_relative_paths() {
1683 let root = PathBuf::from("/repo");
1684 let ui = fallow_config::WorkspaceInfo {
1685 root: root.join("apps/ui"),
1686 name: "ui".to_string(),
1687 is_internal_dependency: false,
1688 };
1689 let api = fallow_config::WorkspaceInfo {
1690 root: root.join("apps/api"),
1691 name: "api".to_string(),
1692 is_internal_dependency: false,
1693 };
1694 let workspace_pkgs = vec![
1695 (
1696 &ui,
1697 fallow_config::PackageJson {
1698 name: Some("ui".to_string()),
1699 ..Default::default()
1700 },
1701 ),
1702 (
1703 &api,
1704 fallow_config::PackageJson {
1705 name: Some("api".to_string()),
1706 ..Default::default()
1707 },
1708 ),
1709 ];
1710 let files = vec![
1711 root.join("apps/ui/vite.config.ts"),
1712 root.join("apps/ui/src/main.ts"),
1713 root.join("apps/api/src/server.ts"),
1714 root.join("tools/build.ts"),
1715 ];
1716
1717 let buckets = bucket_files_by_workspace(&workspace_pkgs, &files);
1718
1719 assert_eq!(
1720 buckets[0],
1721 vec![
1722 (
1723 root.join("apps/ui/vite.config.ts"),
1724 "vite.config.ts".to_string()
1725 ),
1726 (root.join("apps/ui/src/main.ts"), "src/main.ts".to_string()),
1727 ]
1728 );
1729 assert_eq!(
1730 buckets[1],
1731 vec![(
1732 root.join("apps/api/src/server.ts"),
1733 "src/server.ts".to_string()
1734 )]
1735 );
1736 }
1737
1738 #[test]
1739 fn warn_undeclared_workspaces_suppresses_paths_already_flagged_as_malformed() {
1740 let dir = tempfile::tempdir().expect("create temp dir");
1741 let pkg_good = dir.path().join("packages").join("good");
1742 let pkg_bad = dir.path().join("packages").join("bad");
1743 std::fs::create_dir_all(&pkg_good).unwrap();
1744 std::fs::create_dir_all(&pkg_bad).unwrap();
1745 std::fs::write(
1746 dir.path().join("package.json"),
1747 r#"{"workspaces": ["packages/*"]}"#,
1748 )
1749 .unwrap();
1750 std::fs::write(pkg_good.join("package.json"), r#"{"name": "good"}"#).unwrap();
1751 std::fs::write(pkg_bad.join("package.json"), r"{,").unwrap();
1752
1753 let (workspaces, diagnostics) = fallow_config::discover_workspaces_with_diagnostics(
1754 dir.path(),
1755 &globset::GlobSet::empty(),
1756 )
1757 .expect("root package.json is valid");
1758 assert_eq!(workspaces.len(), 1, "only the valid workspace discovers");
1759 fallow_config::stash_workspace_diagnostics(dir.path(), diagnostics);
1760
1761 warn_undeclared_workspaces(dir.path(), &workspaces, &globset::GlobSet::empty(), false);
1762
1763 let diagnostics = fallow_config::workspace_diagnostics_for(dir.path());
1764 let mut malformed = 0;
1765 let mut undeclared_for_bad = 0;
1766 for diag in &diagnostics {
1767 if matches!(
1768 diag.kind,
1769 WorkspaceDiagnosticKind::MalformedPackageJson { .. }
1770 ) && diag.path.ends_with("bad")
1771 {
1772 malformed += 1;
1773 }
1774 if matches!(diag.kind, WorkspaceDiagnosticKind::UndeclaredWorkspace)
1775 && diag.path.ends_with("bad")
1776 {
1777 undeclared_for_bad += 1;
1778 }
1779 }
1780 assert_eq!(
1781 malformed, 1,
1782 "expected one MalformedPackageJson for packages/bad: {diagnostics:?}"
1783 );
1784 assert_eq!(
1785 undeclared_for_bad, 0,
1786 "warn_undeclared_workspaces must NOT re-flag a path that already \
1787 carries MalformedPackageJson; got duplicates: {diagnostics:?}"
1788 );
1789 }
1790}