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