1use std::path::{Path, PathBuf};
2
3use fallow_config::{EmailMode, OutputFormat};
4use fallow_core::results::AnalysisResults;
5use serde::Serialize;
6
7use crate::check::{CheckOptions, IssueFilters, TraceOptions};
8use crate::dupes::{DupesMode, DupesOptions};
9use crate::health::{HealthOptions, SortBy};
10use crate::health_types::EffortEstimate;
11use crate::report::{build_duplication_json, build_health_json, build_json};
12
13#[derive(Debug, Clone, Serialize)]
15pub struct ProgrammaticError {
16 pub message: String,
17 pub exit_code: u8,
18 pub code: Option<String>,
19 pub help: Option<String>,
20 pub context: Option<String>,
21}
22
23impl ProgrammaticError {
24 #[must_use]
25 pub fn new(message: impl Into<String>, exit_code: u8) -> Self {
26 Self {
27 message: message.into(),
28 exit_code,
29 code: None,
30 help: None,
31 context: None,
32 }
33 }
34
35 #[must_use]
36 pub fn with_help(mut self, help: impl Into<String>) -> Self {
37 self.help = Some(help.into());
38 self
39 }
40
41 #[must_use]
42 pub fn with_code(mut self, code: impl Into<String>) -> Self {
43 self.code = Some(code.into());
44 self
45 }
46
47 #[must_use]
48 pub fn with_context(mut self, context: impl Into<String>) -> Self {
49 self.context = Some(context.into());
50 self
51 }
52}
53
54impl std::fmt::Display for ProgrammaticError {
55 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56 write!(f, "{}", self.message)
57 }
58}
59
60impl std::error::Error for ProgrammaticError {}
61
62type ProgrammaticResult<T> = Result<T, ProgrammaticError>;
63
64#[derive(Debug, Clone, Default)]
66pub struct AnalysisOptions {
67 pub root: Option<PathBuf>,
68 pub config_path: Option<PathBuf>,
69 pub no_cache: bool,
70 pub threads: Option<usize>,
71 pub production: bool,
74 pub production_override: Option<bool>,
77 pub changed_since: Option<String>,
78 pub workspace: Option<Vec<String>>,
79 pub changed_workspaces: Option<String>,
80 pub explain: bool,
81}
82
83#[derive(Debug, Clone, Default)]
85pub struct DeadCodeFilters {
86 pub unused_files: bool,
87 pub unused_exports: bool,
88 pub unused_deps: bool,
89 pub unused_types: bool,
90 pub private_type_leaks: bool,
91 pub unused_enum_members: bool,
92 pub unused_class_members: bool,
93 pub unresolved_imports: bool,
94 pub unlisted_deps: bool,
95 pub duplicate_exports: bool,
96 pub circular_deps: bool,
97 pub boundary_violations: bool,
98 pub stale_suppressions: bool,
99}
100
101#[derive(Debug, Clone, Default)]
103pub struct DeadCodeOptions {
104 pub analysis: AnalysisOptions,
105 pub filters: DeadCodeFilters,
106 pub files: Vec<PathBuf>,
107 pub include_entry_exports: bool,
108}
109
110#[derive(Debug, Clone, Copy, Default)]
112pub enum DuplicationMode {
113 Strict,
114 #[default]
115 Mild,
116 Weak,
117 Semantic,
118}
119
120impl DuplicationMode {
121 const fn to_cli(self) -> DupesMode {
122 match self {
123 Self::Strict => DupesMode::Strict,
124 Self::Mild => DupesMode::Mild,
125 Self::Weak => DupesMode::Weak,
126 Self::Semantic => DupesMode::Semantic,
127 }
128 }
129}
130
131#[derive(Debug, Clone)]
133pub struct DuplicationOptions {
134 pub analysis: AnalysisOptions,
135 pub mode: DuplicationMode,
136 pub min_tokens: usize,
137 pub min_lines: usize,
138 pub threshold: f64,
139 pub skip_local: bool,
140 pub cross_language: bool,
141 pub ignore_imports: bool,
142 pub top: Option<usize>,
143}
144
145impl Default for DuplicationOptions {
146 fn default() -> Self {
147 Self {
148 analysis: AnalysisOptions::default(),
149 mode: DuplicationMode::Mild,
150 min_tokens: 50,
151 min_lines: 5,
152 threshold: 0.0,
153 skip_local: false,
154 cross_language: false,
155 ignore_imports: false,
156 top: None,
157 }
158 }
159}
160
161#[derive(Debug, Clone, Copy, Default)]
163pub enum ComplexitySort {
164 #[default]
165 Cyclomatic,
166 Cognitive,
167 Lines,
168 Severity,
169}
170
171impl ComplexitySort {
172 const fn to_cli(self) -> SortBy {
173 match self {
174 Self::Severity => SortBy::Severity,
175 Self::Cyclomatic => SortBy::Cyclomatic,
176 Self::Cognitive => SortBy::Cognitive,
177 Self::Lines => SortBy::Lines,
178 }
179 }
180}
181
182#[derive(Debug, Clone, Copy, Default)]
184pub enum OwnershipEmailMode {
185 Raw,
186 #[default]
187 Handle,
188 Hash,
189}
190
191impl OwnershipEmailMode {
192 const fn to_config(self) -> EmailMode {
193 match self {
194 Self::Raw => EmailMode::Raw,
195 Self::Handle => EmailMode::Handle,
196 Self::Hash => EmailMode::Hash,
197 }
198 }
199}
200
201#[derive(Debug, Clone, Copy)]
203pub enum TargetEffort {
204 Low,
205 Medium,
206 High,
207}
208
209impl TargetEffort {
210 const fn to_cli(self) -> EffortEstimate {
211 match self {
212 Self::Low => EffortEstimate::Low,
213 Self::Medium => EffortEstimate::Medium,
214 Self::High => EffortEstimate::High,
215 }
216 }
217}
218
219#[derive(Debug, Clone, Default)]
221pub struct ComplexityOptions {
222 pub analysis: AnalysisOptions,
223 pub max_cyclomatic: Option<u16>,
224 pub max_cognitive: Option<u16>,
225 pub max_crap: Option<f64>,
226 pub top: Option<usize>,
227 pub sort: ComplexitySort,
228 pub complexity: bool,
229 pub file_scores: bool,
230 pub coverage_gaps: bool,
231 pub hotspots: bool,
232 pub ownership: bool,
233 pub ownership_emails: Option<OwnershipEmailMode>,
234 pub targets: bool,
235 pub effort: Option<TargetEffort>,
236 pub score: bool,
237 pub since: Option<String>,
238 pub min_commits: Option<u32>,
239 pub coverage: Option<PathBuf>,
240 pub coverage_root: Option<PathBuf>,
241}
242
243#[derive(Debug, Clone)]
244struct ResolvedAnalysisOptions {
245 root: PathBuf,
246 config_path: Option<PathBuf>,
247 no_cache: bool,
248 threads: usize,
249 production_override: Option<bool>,
250 changed_since: Option<String>,
251 workspace: Option<Vec<String>>,
252 changed_workspaces: Option<String>,
253 explain: bool,
254}
255
256impl AnalysisOptions {
257 fn resolve(&self) -> ProgrammaticResult<ResolvedAnalysisOptions> {
258 if self.threads == Some(0) {
259 return Err(
260 ProgrammaticError::new("`threads` must be greater than 0", 2)
261 .with_code("FALLOW_INVALID_THREADS")
262 .with_context("analysis.threads"),
263 );
264 }
265 if self.workspace.is_some() && self.changed_workspaces.is_some() {
266 return Err(ProgrammaticError::new(
267 "`workspace` and `changed_workspaces` are mutually exclusive",
268 2,
269 )
270 .with_code("FALLOW_MUTUALLY_EXCLUSIVE_OPTIONS")
271 .with_context("analysis.workspace"));
272 }
273
274 let root = if let Some(root) = &self.root {
275 root.clone()
276 } else {
277 std::env::current_dir().map_err(|err| {
278 ProgrammaticError::new(
279 format!("failed to resolve current working directory: {err}"),
280 2,
281 )
282 .with_code("FALLOW_CWD_UNAVAILABLE")
283 .with_context("analysis.root")
284 })?
285 };
286
287 if !root.exists() {
288 return Err(ProgrammaticError::new(
289 format!("analysis root does not exist: {}", root.display()),
290 2,
291 )
292 .with_code("FALLOW_INVALID_ROOT")
293 .with_context("analysis.root"));
294 }
295 if !root.is_dir() {
296 return Err(ProgrammaticError::new(
297 format!("analysis root is not a directory: {}", root.display()),
298 2,
299 )
300 .with_code("FALLOW_INVALID_ROOT")
301 .with_context("analysis.root"));
302 }
303
304 if let Some(config_path) = &self.config_path
305 && !config_path.exists()
306 {
307 return Err(ProgrammaticError::new(
308 format!("config file does not exist: {}", config_path.display()),
309 2,
310 )
311 .with_code("FALLOW_INVALID_CONFIG_PATH")
312 .with_context("analysis.configPath"));
313 }
314
315 let threads = self.threads.unwrap_or_else(default_threads);
316 let production_override = self
317 .production_override
318 .or_else(|| self.production.then_some(true));
319
320 Ok(ResolvedAnalysisOptions {
321 root,
322 config_path: self.config_path.clone(),
323 no_cache: self.no_cache,
324 threads,
325 production_override,
326 changed_since: self.changed_since.clone(),
327 workspace: self.workspace.clone(),
328 changed_workspaces: self.changed_workspaces.clone(),
329 explain: self.explain,
330 })
331 }
332}
333
334fn default_threads() -> usize {
335 std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get)
336}
337
338fn insert_meta(output: &mut serde_json::Value, meta: serde_json::Value) {
339 if let serde_json::Value::Object(map) = output {
340 map.insert("_meta".to_string(), meta);
341 }
342}
343
344fn build_dead_code_json(
345 results: &AnalysisResults,
346 root: &Path,
347 elapsed: std::time::Duration,
348 explain: bool,
349) -> ProgrammaticResult<serde_json::Value> {
350 let mut output = build_json(results, root, elapsed).map_err(|err| {
351 ProgrammaticError::new(format!("failed to serialize dead-code report: {err}"), 2)
352 .with_code("FALLOW_SERIALIZE_DEAD_CODE_REPORT")
353 .with_context("dead-code")
354 })?;
355 if explain {
356 insert_meta(&mut output, crate::explain::check_meta());
357 }
358 Ok(output)
359}
360
361fn to_issue_filters(filters: &DeadCodeFilters) -> IssueFilters {
362 IssueFilters {
363 unused_files: filters.unused_files,
364 unused_exports: filters.unused_exports,
365 unused_deps: filters.unused_deps,
366 unused_types: filters.unused_types,
367 private_type_leaks: filters.private_type_leaks,
368 unused_enum_members: filters.unused_enum_members,
369 unused_class_members: filters.unused_class_members,
370 unresolved_imports: filters.unresolved_imports,
371 unlisted_deps: filters.unlisted_deps,
372 duplicate_exports: filters.duplicate_exports,
373 circular_deps: filters.circular_deps,
374 boundary_violations: filters.boundary_violations,
375 stale_suppressions: filters.stale_suppressions,
376 }
377}
378
379fn generic_analysis_error(command: &str) -> ProgrammaticError {
380 let code = format!(
381 "FALLOW_{}_FAILED",
382 command.replace('-', "_").to_ascii_uppercase()
383 );
384 ProgrammaticError::new(format!("{command} failed"), 2)
385 .with_code(code)
386 .with_context(format!("fallow {command}"))
387 .with_help(format!(
388 "Re-run `fallow {command} --format json --quiet` in the target project for CLI diagnostics"
389 ))
390}
391
392fn build_check_options<'a>(
393 resolved: &'a ResolvedAnalysisOptions,
394 options: &'a DeadCodeOptions,
395 filters: &'a IssueFilters,
396 trace_opts: &'a TraceOptions,
397) -> CheckOptions<'a> {
398 CheckOptions {
399 root: &resolved.root,
400 config_path: &resolved.config_path,
401 output: OutputFormat::Human,
402 no_cache: resolved.no_cache,
403 threads: resolved.threads,
404 quiet: true,
405 fail_on_issues: false,
406 filters,
407 changed_since: resolved.changed_since.as_deref(),
408 baseline: None,
409 save_baseline: None,
410 sarif_file: None,
411 production: resolved.production_override.unwrap_or(false),
412 production_override: resolved.production_override,
413 workspace: resolved.workspace.as_deref(),
414 changed_workspaces: resolved.changed_workspaces.as_deref(),
415 group_by: None,
416 include_dupes: false,
417 trace_opts,
418 explain: resolved.explain,
419 top: None,
420 file: &options.files,
421 include_entry_exports: options.include_entry_exports,
422 summary: false,
423 regression_opts: crate::regression::RegressionOpts {
424 fail_on_regression: false,
425 tolerance: crate::regression::Tolerance::Absolute(0),
426 regression_baseline_file: None,
427 save_target: crate::regression::SaveRegressionTarget::None,
428 scoped: false,
429 quiet: true,
430 },
431 retain_modules_for_health: false,
432 }
433}
434
435fn filter_for_circular_dependencies(results: &AnalysisResults) -> AnalysisResults {
436 let mut filtered = results.clone();
437 filtered.unused_files.clear();
438 filtered.unused_exports.clear();
439 filtered.unused_types.clear();
440 filtered.private_type_leaks.clear();
441 filtered.unused_dependencies.clear();
442 filtered.unused_dev_dependencies.clear();
443 filtered.unused_optional_dependencies.clear();
444 filtered.unused_enum_members.clear();
445 filtered.unused_class_members.clear();
446 filtered.unresolved_imports.clear();
447 filtered.unlisted_dependencies.clear();
448 filtered.duplicate_exports.clear();
449 filtered.type_only_dependencies.clear();
450 filtered.test_only_dependencies.clear();
451 filtered.boundary_violations.clear();
452 filtered.stale_suppressions.clear();
453 filtered
454}
455
456fn filter_for_boundary_violations(results: &AnalysisResults) -> AnalysisResults {
457 let mut filtered = results.clone();
458 filtered.unused_files.clear();
459 filtered.unused_exports.clear();
460 filtered.unused_types.clear();
461 filtered.private_type_leaks.clear();
462 filtered.unused_dependencies.clear();
463 filtered.unused_dev_dependencies.clear();
464 filtered.unused_optional_dependencies.clear();
465 filtered.unused_enum_members.clear();
466 filtered.unused_class_members.clear();
467 filtered.unresolved_imports.clear();
468 filtered.unlisted_dependencies.clear();
469 filtered.duplicate_exports.clear();
470 filtered.type_only_dependencies.clear();
471 filtered.test_only_dependencies.clear();
472 filtered.circular_dependencies.clear();
473 filtered.stale_suppressions.clear();
474 filtered
475}
476
477pub fn detect_dead_code(options: &DeadCodeOptions) -> ProgrammaticResult<serde_json::Value> {
479 let resolved = options.analysis.resolve()?;
480 let filters = to_issue_filters(&options.filters);
481 let trace_opts = TraceOptions {
482 trace_export: None,
483 trace_file: None,
484 trace_dependency: None,
485 performance: false,
486 };
487 let check_options = build_check_options(&resolved, options, &filters, &trace_opts);
488 let result = crate::check::execute_check(&check_options)
489 .map_err(|_| generic_analysis_error("dead-code"))?;
490 build_dead_code_json(
491 &result.results,
492 &result.config.root,
493 result.elapsed,
494 resolved.explain,
495 )
496}
497
498pub fn detect_circular_dependencies(
501 options: &DeadCodeOptions,
502) -> ProgrammaticResult<serde_json::Value> {
503 let resolved = options.analysis.resolve()?;
504 let filters = to_issue_filters(&options.filters);
505 let trace_opts = TraceOptions {
506 trace_export: None,
507 trace_file: None,
508 trace_dependency: None,
509 performance: false,
510 };
511 let check_options = build_check_options(&resolved, options, &filters, &trace_opts);
512 let result = crate::check::execute_check(&check_options)
513 .map_err(|_| generic_analysis_error("dead-code"))?;
514 let filtered = filter_for_circular_dependencies(&result.results);
515 build_dead_code_json(
516 &filtered,
517 &result.config.root,
518 result.elapsed,
519 resolved.explain,
520 )
521}
522
523pub fn detect_boundary_violations(
526 options: &DeadCodeOptions,
527) -> ProgrammaticResult<serde_json::Value> {
528 let resolved = options.analysis.resolve()?;
529 let filters = to_issue_filters(&options.filters);
530 let trace_opts = TraceOptions {
531 trace_export: None,
532 trace_file: None,
533 trace_dependency: None,
534 performance: false,
535 };
536 let check_options = build_check_options(&resolved, options, &filters, &trace_opts);
537 let result = crate::check::execute_check(&check_options)
538 .map_err(|_| generic_analysis_error("dead-code"))?;
539 let filtered = filter_for_boundary_violations(&result.results);
540 build_dead_code_json(
541 &filtered,
542 &result.config.root,
543 result.elapsed,
544 resolved.explain,
545 )
546}
547
548pub fn detect_duplication(options: &DuplicationOptions) -> ProgrammaticResult<serde_json::Value> {
550 let resolved = options.analysis.resolve()?;
551 let dupes_options = DupesOptions {
552 root: &resolved.root,
553 config_path: &resolved.config_path,
554 output: OutputFormat::Human,
555 no_cache: resolved.no_cache,
556 threads: resolved.threads,
557 quiet: true,
558 mode: options.mode.to_cli(),
559 min_tokens: options.min_tokens,
560 min_lines: options.min_lines,
561 threshold: options.threshold,
562 skip_local: options.skip_local,
563 cross_language: options.cross_language,
564 ignore_imports: options.ignore_imports,
565 top: options.top,
566 baseline_path: None,
567 save_baseline_path: None,
568 production: resolved.production_override.unwrap_or(false),
569 production_override: resolved.production_override,
570 trace: None,
571 changed_since: resolved.changed_since.as_deref(),
572 workspace: resolved.workspace.as_deref(),
573 changed_workspaces: resolved.changed_workspaces.as_deref(),
574 explain: resolved.explain,
575 summary: false,
576 group_by: None,
577 };
578 let result =
579 crate::dupes::execute_dupes(&dupes_options).map_err(|_| generic_analysis_error("dupes"))?;
580 build_duplication_json(
581 &result.report,
582 &result.config.root,
583 result.elapsed,
584 resolved.explain,
585 )
586 .map_err(|err| {
587 ProgrammaticError::new(format!("failed to serialize duplication report: {err}"), 2)
588 .with_code("FALLOW_SERIALIZE_DUPLICATION_REPORT")
589 .with_context("dupes")
590 })
591}
592
593fn build_complexity_options<'a>(
594 resolved: &'a ResolvedAnalysisOptions,
595 options: &'a ComplexityOptions,
596) -> HealthOptions<'a> {
597 let ownership = options.ownership || options.ownership_emails.is_some();
598 let hotspots = options.hotspots || ownership;
599 let targets = options.targets || options.effort.is_some();
600 let any_section = options.complexity
601 || options.file_scores
602 || options.coverage_gaps
603 || hotspots
604 || targets
605 || options.score;
606 let eff_score = if any_section { options.score } else { true };
607 let force_full = eff_score;
608 let score_only_output = options.score
609 && !options.complexity
610 && !options.file_scores
611 && !options.coverage_gaps
612 && !hotspots
613 && !targets;
614 let eff_file_scores = if any_section {
615 options.file_scores
616 } else {
617 true
618 } || force_full;
619 let eff_hotspots = if any_section { hotspots } else { true };
620 let eff_complexity = if any_section {
621 options.complexity
622 } else {
623 true
624 };
625 let eff_targets = if any_section { targets } else { true };
626 let eff_coverage_gaps = if any_section {
627 options.coverage_gaps
628 } else {
629 false
630 };
631
632 HealthOptions {
633 root: &resolved.root,
634 config_path: &resolved.config_path,
635 output: OutputFormat::Human,
636 no_cache: resolved.no_cache,
637 threads: resolved.threads,
638 quiet: true,
639 max_cyclomatic: options.max_cyclomatic,
640 max_cognitive: options.max_cognitive,
641 max_crap: options.max_crap,
642 top: options.top,
643 sort: options.sort.to_cli(),
644 production: resolved.production_override.unwrap_or(false),
645 production_override: resolved.production_override,
646 changed_since: resolved.changed_since.as_deref(),
647 workspace: resolved.workspace.as_deref(),
648 changed_workspaces: resolved.changed_workspaces.as_deref(),
649 baseline: None,
650 save_baseline: None,
651 complexity: eff_complexity,
652 file_scores: eff_file_scores,
653 coverage_gaps: eff_coverage_gaps,
654 config_activates_coverage_gaps: !any_section,
655 hotspots: eff_hotspots,
656 ownership: ownership && eff_hotspots,
657 ownership_emails: options.ownership_emails.map(OwnershipEmailMode::to_config),
658 targets: eff_targets,
659 force_full,
660 score_only_output,
661 enforce_coverage_gap_gate: true,
662 effort: options.effort.map(TargetEffort::to_cli),
663 score: eff_score,
664 min_score: None,
665 since: options.since.as_deref(),
666 min_commits: options.min_commits,
667 explain: resolved.explain,
668 summary: false,
669 save_snapshot: None,
670 trend: false,
671 group_by: None,
672 coverage: options.coverage.as_deref(),
673 coverage_root: options.coverage_root.as_deref(),
674 performance: false,
675 min_severity: None,
676 runtime_coverage: None,
677 }
678}
679
680pub fn compute_complexity(options: &ComplexityOptions) -> ProgrammaticResult<serde_json::Value> {
682 let resolved = options.analysis.resolve()?;
683 if let Some(path) = &options.coverage
684 && !path.exists()
685 {
686 return Err(ProgrammaticError::new(
687 format!("coverage path does not exist: {}", path.display()),
688 2,
689 )
690 .with_code("FALLOW_INVALID_COVERAGE_PATH")
691 .with_context("health.coverage"));
692 }
693
694 let health_options = build_complexity_options(&resolved, options);
695 let result = crate::health::execute_health(&health_options)
696 .map_err(|_| generic_analysis_error("health"))?;
697 let action_opts = crate::health::health_action_opts(&result);
698 build_health_json(
699 &result.report,
700 &result.config.root,
701 result.elapsed,
702 resolved.explain,
703 action_opts,
704 )
705 .map_err(|err| {
706 ProgrammaticError::new(format!("failed to serialize health report: {err}"), 2)
707 .with_code("FALLOW_SERIALIZE_HEALTH_REPORT")
708 .with_context("health")
709 })
710}
711
712pub fn compute_health(options: &ComplexityOptions) -> ProgrammaticResult<serde_json::Value> {
714 compute_complexity(options)
715}
716
717#[cfg(test)]
718mod tests {
719 use super::*;
720 use crate::report::test_helpers::sample_results;
721
722 #[test]
723 fn circular_dependency_filter_clears_other_issue_types() {
724 let root = PathBuf::from("/project");
725 let results = sample_results(&root);
726 let filtered = filter_for_circular_dependencies(&results);
727 let json = build_dead_code_json(&filtered, &root, std::time::Duration::ZERO, false)
728 .expect("should serialize");
729
730 assert_eq!(json["circular_dependencies"].as_array().unwrap().len(), 1);
731 assert_eq!(json["boundary_violations"].as_array().unwrap().len(), 0);
732 assert_eq!(json["unused_files"].as_array().unwrap().len(), 0);
733 assert_eq!(json["summary"]["total_issues"], serde_json::Value::from(1));
734 }
735
736 #[test]
737 fn boundary_violation_filter_clears_other_issue_types() {
738 let root = PathBuf::from("/project");
739 let results = sample_results(&root);
740 let filtered = filter_for_boundary_violations(&results);
741 let json = build_dead_code_json(&filtered, &root, std::time::Duration::ZERO, false)
742 .expect("should serialize");
743
744 assert_eq!(json["boundary_violations"].as_array().unwrap().len(), 1);
745 assert_eq!(json["circular_dependencies"].as_array().unwrap().len(), 0);
746 assert_eq!(json["unused_exports"].as_array().unwrap().len(), 0);
747 assert_eq!(json["summary"]["total_issues"], serde_json::Value::from(1));
748 }
749
750 #[test]
751 fn dead_code_without_production_override_uses_per_analysis_config() {
752 let dir = tempfile::tempdir().expect("temp dir");
753 let root = dir.path();
754 std::fs::create_dir_all(root.join("src")).unwrap();
755 std::fs::write(
756 root.join("package.json"),
757 r#"{"name":"programmatic-production","main":"src/index.ts"}"#,
758 )
759 .unwrap();
760 std::fs::write(root.join("src/index.ts"), "export const ok = 1;\n").unwrap();
761 std::fs::write(root.join("src/utils.test.ts"), "export const dead = 1;\n").unwrap();
762 std::fs::write(
763 root.join(".fallowrc.json"),
764 r#"{"production":{"deadCode":true,"health":false,"dupes":false}}"#,
765 )
766 .unwrap();
767
768 let options = DeadCodeOptions {
769 analysis: AnalysisOptions {
770 root: Some(root.to_path_buf()),
771 ..AnalysisOptions::default()
772 },
773 ..DeadCodeOptions::default()
774 };
775 let json = detect_dead_code(&options).expect("analysis should succeed");
776 let paths = unused_file_paths(&json);
777
778 assert!(
779 !paths.iter().any(|path| path.ends_with("utils.test.ts")),
780 "omitted production option should defer to production.deadCode=true config: {paths:?}"
781 );
782 }
783
784 #[test]
785 fn dead_code_explicit_production_false_overrides_config() {
786 let dir = tempfile::tempdir().expect("temp dir");
787 let root = dir.path();
788 std::fs::create_dir_all(root.join("src")).unwrap();
789 std::fs::write(
790 root.join("package.json"),
791 r#"{"name":"programmatic-production","main":"src/index.ts"}"#,
792 )
793 .unwrap();
794 std::fs::write(root.join("src/index.ts"), "export const ok = 1;\n").unwrap();
795 std::fs::write(root.join("src/utils.test.ts"), "export const dead = 1;\n").unwrap();
796 std::fs::write(
797 root.join(".fallowrc.json"),
798 r#"{"production":{"deadCode":true,"health":false,"dupes":false}}"#,
799 )
800 .unwrap();
801
802 let options = DeadCodeOptions {
803 analysis: AnalysisOptions {
804 root: Some(root.to_path_buf()),
805 production_override: Some(false),
806 ..AnalysisOptions::default()
807 },
808 ..DeadCodeOptions::default()
809 };
810 let json = detect_dead_code(&options).expect("analysis should succeed");
811 let paths = unused_file_paths(&json);
812
813 assert!(
814 paths.iter().any(|path| path.ends_with("utils.test.ts")),
815 "explicit production=false should include test files despite config: {paths:?}"
816 );
817 }
818
819 fn unused_file_paths(json: &serde_json::Value) -> Vec<String> {
820 json["unused_files"]
821 .as_array()
822 .unwrap()
823 .iter()
824 .filter_map(|file| file["path"].as_str())
825 .map(str::to_owned)
826 .collect()
827 }
828}