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