1#![warn(missing_docs)]
16#![cfg_attr(
17 test,
18 allow(
19 clippy::expect_used,
20 reason = "tests use expect to keep fixture setup concise"
21 )
22)]
23
24use std::path::{Path, PathBuf};
25use std::sync::Arc;
26use std::sync::atomic::AtomicBool;
27
28use fallow_config::EmailMode;
29use fallow_output::EffortEstimate;
30use serde::Serialize;
31
32mod analysis_context;
33mod audit_complexity;
34pub mod audit_keys;
38mod audit_moved;
39pub mod audit_output;
40pub mod audit_run;
41pub mod combined_output;
42pub mod compact_output;
45mod companion_install;
46pub mod coverage;
47pub mod dead_code_codeclimate;
48pub mod dead_code_sarif;
49pub mod decision_surface;
50pub mod dependency_deltas;
51pub mod diff_risk;
52pub mod doctor;
53pub mod dupes_output;
54pub mod editor;
55pub mod explain;
56pub mod grouped_output;
57pub mod health_codeclimate;
58mod health_groups_markdown;
59pub mod json_output;
60pub mod list_output;
61mod list_runtime;
62pub mod markdown_output;
65pub mod mutation;
66mod next_steps;
67pub mod output_contracts;
68pub mod ownership;
69mod release_signature;
70pub mod review_deltas;
71pub mod routing;
72pub mod runtime;
73mod runtime_json;
74mod runtime_output;
75pub mod sarif_output;
76pub mod schemas;
79pub mod security_output;
80pub mod similar_code;
82mod type_aware;
83pub use analysis_context::{ProgrammaticAnalysisContext, resolve_programmatic_analysis_context};
84pub use audit_output::{
85 AuditAttribution, AuditCodeClimateOutputInput, AuditJsonHeaderInput, AuditJsonOutputInput,
86 AuditSarifOutputInput, AuditSummary, AuditVerdict, attach_audit_diff_risk_attribution,
87 attach_audit_duplication_demotion_attribution, attach_audit_styling_attribution,
88 attach_audit_wire_attribution, build_audit_codeclimate, build_audit_codeclimate_issues,
89 build_audit_header_json, build_audit_header_map, build_audit_sarif,
90 build_diff_risk_codeclimate, build_review_brief_header, serialize_audit_json,
91};
92pub use combined_output::{
93 CombinedCheckJsonSection, CombinedJsonOutputInput, serialize_combined_dupes_json,
94 serialize_combined_health_json, serialize_combined_json,
95};
96pub use compact_output::{
97 build_compact_lines, build_diff_risk_compact_lines, build_duplication_compact_lines,
98 build_grouped_compact_lines, build_health_compact_lines,
99};
100pub use coverage::{
101 CoverageInputError, CoverageInputSource, CoverageInputs, resolve_coverage_inputs,
102};
103pub use dead_code_codeclimate::build_codeclimate;
104pub use dead_code_sarif::build_sarif;
105pub use doctor::{DoctorOptions, run_doctor, run_doctor_with_cache_dir};
106pub use dupes_output::{
107 AttributedCloneGroup, AttributedCloneGroupFinding, AttributedInstance, CloneDemotionReason,
108 CloneFamilyFinding, CloneGroupFinding, CombinedDupesSection, DupesReportPayload,
109 DuplicationGroup, DuplicationGrouping, build_duplication_codeclimate,
110 set_duplication_audit_attribution,
111};
112pub use editor::{
113 ChangedFilesError, EditorAnalysisOutput, EditorAnalysisResults, EditorAnalysisSession,
114 EditorCloneFamily, EditorCloneFingerprintSet, EditorCloneGroup, EditorCloneInstance,
115 EditorDeadCodeAnalysisOutput, EditorDuplicationReport, EditorDuplicationStats,
116 EditorInlineComplexityExceeded, EditorInlineComplexityFinding, EditorMirroredDirectory,
117 EditorProjectAnalysisOutput, EditorRefactoringKind, EditorRefactoringSuggestion,
118 EditorSessionParseCounts, collect_inline_complexity, editor_duplicates, editor_extract,
119 editor_results, editor_security, editor_suppress, filter_inline_complexity_by_change_scope,
120 filter_inline_complexity_by_changed_files, resolve_git_toplevel,
121 try_get_changed_files_with_toplevel,
122};
123pub use explain::{
124 AUDIT_RULES, CHECK_RULES, DUPES_RULES, FLAGS_RULES, HEALTH_RULES, MUTATION_RULES, RuleDef,
125 RuleGuide, SECURITY_RULES, all_rules, bare_rule_id, coverage_analyze_meta, coverage_setup_meta,
126 explain_issue_type, rule_by_id, rule_by_token, rule_command, rule_docs_url, rule_guide,
127 rule_severity_key, security_meta, serialize_explain_programmatic_json, unknown_explain_error,
128};
129pub use fallow_config::levenshtein::closest_match;
130pub use fallow_config::{
131 AuditGate, AuditWorsened, HealthConfig, ProductionAnalysis, ProductionEnv, TypeAwareRequire,
132};
133pub use fallow_engine::change_scope::{
136 ChangeScope, ChangeScopeOwner, ChangeScopeRequest, first_package_baselines,
137 package_baseline_statuses,
138};
139pub use fallow_engine::package_baselines::{PackageBaselineError, PackageChangeScope};
141pub use fallow_engine::thread_pool::{WORKER_STACK_SIZE, register_thread_stack};
148pub use fallow_engine::warm_parse;
154pub use fallow_output::PackageBaselineStatus;
156pub use fallow_output::serialize_similar_code_json_output;
157pub use fallow_types::trace::{
158 CloneTrace, DependencyTrace, ExportReference, ExportTrace, FileTrace, ReExportChain,
159 TracedCloneGroup, TracedExport, TracedReExport,
160};
161pub use fallow_types::trace_usage::{
162 DependencyUsage, DependencyUsageQuery, SitePageRequest, UsageQueryError,
163};
164pub use grouped_output::{
165 ResultGroup, UNOWNED_GROUP_LABEL, build_duplication_grouping_with, group_analysis_results_with,
166 health_signal_header_part, largest_clone_group_owner_with,
167};
168pub use health_codeclimate::build_health_codeclimate;
169pub use health_groups_markdown::build_health_groups_markdown;
170pub use json_output::{
171 CheckJsonExtraOutputs, CheckJsonOutputInput, CheckJsonPayloadInput, DuplicationJsonOutputInput,
172 GroupedCheckJsonOutputInput, GroupedDuplicationJsonOutputInput, serialize_check_json,
173 serialize_check_json_payload, serialize_duplication_json, serialize_grouped_check_json,
174 serialize_grouped_duplication_json,
175};
176pub use list_output::{
177 ListJsonEnvelope, ListJsonOutputInput, build_list_json_output, serialize_list_json_output,
178};
179pub use list_runtime::{
180 BoundaryData, ListBoundariesOptions, ListBoundariesProgrammaticOutput, LogicalGroupInfo,
181 ProjectInfoOptions, ProjectInfoProgrammaticOutput, RuleInfo, ZoneInfo, boundary_data_to_output,
182 compute_boundary_data, run_list_boundaries, run_project_info,
183 serialize_list_boundaries_programmatic_json, serialize_project_info_programmatic_json,
184};
185pub use markdown_output::{
186 ComplexityListing, build_diff_risk_markdown, build_duplication_markdown,
187 build_grouped_markdown, build_health_markdown, build_markdown, build_walkthrough_markdown,
188};
189pub use mutation::{
190 MutationProgress, MutationProgressSink, MutationReplayOptions, MutationRunOptions,
191 MutationRunScope, apply_mutation_verdicts, validate_mutation_verdicts,
192};
193pub use output_contracts::{
194 AuditOutput, BoundariesListLogicalGroup, BoundariesListRule, BoundariesListZone,
195 BoundariesListing, CombinedOutput, FallowOutput, ImpactOutput, ListBoundariesOutput,
196 ListEntryPointOutput, ListOutput, ListPluginOutput, ReviewBriefWireOutput, SecurityGate,
197 SecurityOutput, SecurityOutputConfig, SecuritySummaryOutput, SimilarCodeCandidateSnapshot,
198 SimilarCodeOutput, TraceOutput, WorkspacesOutput,
199};
200pub use runtime::TYPE_AWARE_CONFIG_UNSUPPORTED;
201pub use runtime::{
202 AUDIT_CONFIG_BASELINE_UNSUPPORTED, ArchitectureOutput, ArchitectureProgrammaticOutput,
203 AuditProgrammaticKeySnapshot, AuditProgrammaticOutput, BoundaryViolationsOutput,
204 BoundaryViolationsProgrammaticOutput, CircularDependenciesOutput,
205 CircularDependenciesProgrammaticOutput, CombinedProgrammaticOutput, DeadCodeOutput,
206 DeadCodeProgrammaticOutput, DecisionSurfaceProgrammaticOutput, DuplicationOutput,
207 DuplicationProgrammaticOutput, EngineHealthRunner, FeatureFlagsOutput,
208 FeatureFlagsProgrammaticOutput, HealthJsonReportInput, HealthProgrammaticOutput,
209 ProgrammaticHealthAnalysis, ProgrammaticHealthNextStepFacts, ProgrammaticHealthRun,
210 ProgrammaticHealthRunner, TraceClassMemberOutput, TraceCloneBenchmarkResult, TraceCloneOutput,
211 TraceCloneProgrammaticOutput, TraceDependencyOutput, TraceDependencyProgrammaticOutput,
212 TraceErrorOutput, TraceErrorProgrammaticOutput, TraceExportOutput,
213 TraceExportProgrammaticOutput, TraceExportTargetOutput, TraceFileOutput,
214 TraceFileProgrammaticOutput, TraceImportPathOutput, TraceImportPathProgrammaticOutput,
215 benchmark_trace_clone_compact_json, benchmark_trace_graph_family_compact_json,
216 inspect_similar_code, load_health_config, parse_similar_code_candidate_snapshot, plan_mutation,
217 replay_mutation, review_similar_code, run_architecture, run_audit, run_boundary_violations,
218 run_circular_dependencies, run_combined, run_complexity_with_runner, run_dead_code,
219 run_dead_code_with_baseline, run_decision_surface, run_duplication, run_feature_flags,
220 run_health, run_health_with_runner, run_mutation, run_mutation_with_progress, run_similar_code,
221 run_trace_clone, run_trace_dependency, run_trace_error, run_trace_export, run_trace_file,
222 run_trace_import_path, select_similar_code_candidate_snapshot, serialize_health_report_json,
223};
224pub use runtime_json::{
225 serialize_architecture_programmatic_json, serialize_audit_programmatic_json,
226 serialize_boundary_violations_programmatic_json,
227 serialize_circular_dependencies_programmatic_json, serialize_combined_programmatic_json,
228 serialize_dead_code_programmatic_json, serialize_decision_surface_programmatic_json,
229 serialize_duplication_programmatic_json, serialize_feature_flags_programmatic_json,
230 serialize_health_programmatic_json, serialize_trace_clone_programmatic_json,
231 serialize_trace_dependency_programmatic_json, serialize_trace_error_programmatic_json,
232 serialize_trace_export_programmatic_json, serialize_trace_file_programmatic_json,
233 serialize_trace_import_path_programmatic_json,
234};
235pub use sarif_output::{
236 annotate_sarif_results, build_duplication_sarif, build_grouped_duplication_sarif,
237 build_health_sarif,
238};
239pub use security_output::SecurityGateMode;
240pub use type_aware::{
241 DEFAULT_BACKEND_FAMILY as DEFAULT_TYPE_AWARE_BACKEND_FAMILY, SemanticCouplingOutcome,
242 SemanticDeadCodeOutcome, SemanticInspectOutcome, TypeAwareError, TypeAwareFileChanges,
243 TypeAwareOutcome, TypeAwareSession, TypeAwareStatus, discard_unverified_semantic_candidates,
244 inspect_symbol as inspect_type_aware_symbol, merge_type_aware_meta,
245 refine_configured_dead_code_results as refine_type_aware_results_with_config,
246 shutdown_type_aware_sidecars, status as type_aware_status,
247 symbol_impact as run_type_aware_symbol_impact, symbol_impact as type_aware_symbol_impact,
248 terminate_active_type_aware_sidecars, trace_symbol as run_type_aware_symbol_trace,
249 trace_symbol as trace_type_aware_symbol, type_coupling as analyze_type_coupling,
250};
251
252pub use type_aware::setup_store as type_aware_setup;
255
256pub const COMMON_ANALYSIS_OPTION_FLAGS: &[&str] = &[
263 "root",
264 "config",
265 "no-cache",
266 "threads",
267 "changed-since",
268 "diff-file",
269 "production",
270 "workspace",
271 "changed-workspaces",
272 "explain",
273 "allow-remote-extends",
274];
275
276#[derive(Debug, Clone, Serialize)]
278pub struct ProgrammaticError {
279 pub message: String,
281 pub exit_code: u8,
283 pub code: Option<String>,
285 pub help: Option<String>,
287 pub context: Option<String>,
289}
290
291impl ProgrammaticError {
292 #[must_use]
295 pub fn new(message: impl Into<String>, exit_code: u8) -> Self {
296 Self {
297 message: message.into(),
298 exit_code,
299 code: None,
300 help: None,
301 context: None,
302 }
303 }
304
305 #[must_use]
307 pub fn with_help(mut self, help: impl Into<String>) -> Self {
308 self.help = Some(help.into());
309 self
310 }
311
312 #[must_use]
315 pub fn with_code(mut self, code: impl Into<String>) -> Self {
316 self.code = Some(code.into());
317 self
318 }
319
320 #[must_use]
323 pub fn with_context(mut self, context: impl Into<String>) -> Self {
324 self.context = Some(context.into());
325 self
326 }
327}
328
329impl std::fmt::Display for ProgrammaticError {
330 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
331 write!(f, "{}", self.message)
332 }
333}
334
335impl std::error::Error for ProgrammaticError {}
336
337#[derive(Debug, Clone, Default)]
339pub struct AnalysisOptions {
340 pub root: Option<PathBuf>,
343 pub config_path: Option<PathBuf>,
345 pub allow_remote_extends: bool,
347 pub no_cache: bool,
349 pub threads: Option<usize>,
351 pub diff_file: Option<PathBuf>,
363 pub ambient_diff_file: Option<PathBuf>,
371 pub production: bool,
374 pub production_override: Option<bool>,
377 pub changed_since: Option<String>,
382 pub ambient_changed_since: Option<String>,
390 pub no_package_baselines: bool,
394 pub workspace: Option<Vec<String>>,
396 pub changed_workspaces: Option<String>,
398 pub explain: bool,
400 pub type_aware: TypeAwareOptions,
403 pub cancellation: Option<Arc<AtomicBool>>,
433}
434
435#[derive(Debug, Clone, Default, PartialEq, Eq)]
437pub struct TypeAwareOptions {
438 pub enabled: Option<bool>,
445 pub projects: Vec<PathBuf>,
448 pub require: fallow_config::TypeAwareRequire,
450}
451
452impl TypeAwareOptions {
453 #[must_use]
455 pub const fn requested(&self) -> bool {
456 matches!(self.enabled, Some(true))
457 }
458}
459
460#[derive(Debug, Clone, Default, PartialEq, Eq)]
465pub struct DeadCodeFilters {
466 pub shared_state: bool,
468 pub unused_files: bool,
470 pub unused_exports: bool,
472 pub unused_deps: bool,
474 pub unused_types: bool,
476 pub private_type_leaks: bool,
478 pub deprecated_exports_in_use: bool,
480 pub unused_enum_members: bool,
482 pub unused_class_members: bool,
484 pub unused_namespace_members: bool,
486 pub unused_protected_class_members: bool,
488 pub unused_store_members: bool,
490 pub unprovided_injects: bool,
492 pub unrendered_components: bool,
494 pub unused_component_props: bool,
496 pub absent_component_props: bool,
498 pub constant_parameters: bool,
500 pub unused_component_emits: bool,
502 pub unused_component_inputs: bool,
504 pub unused_component_outputs: bool,
506 pub unused_svelte_events: bool,
508 pub unused_effect_layers: bool,
510 pub unused_tagged_errors: bool,
512 pub unproduced_catch_tags: bool,
514 pub unused_server_actions: bool,
516 pub unused_load_data_keys: bool,
518 pub unresolved_imports: bool,
520 pub unlisted_deps: bool,
522 pub unlisted_binaries: bool,
524 pub duplicate_exports: bool,
526 pub duplicate_export_aliases: bool,
528 pub circular_deps: bool,
530 pub re_export_cycles: bool,
532 pub package_cycles: bool,
534 pub boundary_violations: bool,
536 pub policy_violations: bool,
538 pub stale_suppressions: bool,
540 pub unused_catalog_entries: bool,
542 pub empty_catalog_groups: bool,
544 pub unresolved_catalog_references: bool,
546 pub unused_dependency_overrides: bool,
548 pub misconfigured_dependency_overrides: bool,
550}
551
552impl DeadCodeFilters {
553 pub(crate) fn reports_dependency_findings(&self) -> bool {
557 !self.any_active() || self.unused_deps || self.unlisted_deps
558 }
559
560 fn any_active(&self) -> bool {
561 self.shared_state
562 || self.unused_files
563 || self.unused_exports
564 || self.unused_deps
565 || self.unused_types
566 || self.private_type_leaks
567 || self.deprecated_exports_in_use
568 || self.unused_enum_members
569 || self.unused_class_members
570 || self.unused_namespace_members
571 || self.unused_protected_class_members
572 || self.unused_store_members
573 || self.unprovided_injects
574 || self.unrendered_components
575 || self.unused_component_props
576 || self.absent_component_props
577 || self.constant_parameters
578 || self.unused_component_emits
579 || self.unused_component_inputs
580 || self.unused_component_outputs
581 || self.unused_svelte_events
582 || self.unused_effect_layers
583 || self.unused_tagged_errors
584 || self.unproduced_catch_tags
585 || self.unused_server_actions
586 || self.unused_load_data_keys
587 || self.unresolved_imports
588 || self.unlisted_deps
589 || self.unlisted_binaries
590 || self.duplicate_exports
591 || self.duplicate_export_aliases
592 || self.circular_deps
593 || self.re_export_cycles
594 || self.package_cycles
595 || self.boundary_violations
596 || self.policy_violations
597 || self.stale_suppressions
598 || self.unused_catalog_entries
599 || self.empty_catalog_groups
600 || self.unresolved_catalog_references
601 || self.unused_dependency_overrides
602 || self.misconfigured_dependency_overrides
603 }
604
605 pub fn enable_registry_selector(&mut self, selector: &str) -> bool {
611 let Some(flag) = fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS
612 .iter()
613 .find_map(|&(name, flag)| (name == selector).then_some(flag))
614 else {
615 return false;
616 };
617 self.enable_cli_filter_flag(flag);
618 true
619 }
620
621 pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
623 fallow_engine::requested_rule_off::explicit_filter_flags(|flag| {
624 let mut enabled = self.clone();
625 enabled.enable_cli_filter_flag(flag);
626 enabled == *self
627 })
628 }
629
630 fn enable_cli_filter_flag(&mut self, flag: &str) {
631 match flag {
632 "--unused-files" => self.unused_files = true,
633 "--unused-exports" => self.unused_exports = true,
634 "--unused-types" => self.unused_types = true,
635 "--private-type-leaks" => self.private_type_leaks = true,
636 "--deprecated-exports-in-use" => self.deprecated_exports_in_use = true,
637 "--unused-deps" => self.unused_deps = true,
638 "--unused-enum-members" => self.unused_enum_members = true,
639 "--unused-class-members" => self.unused_class_members = true,
640 "--unused-namespace-members" => self.unused_namespace_members = true,
641 "--unused-protected-class-members" => self.unused_protected_class_members = true,
642 "--unused-store-members" => self.unused_store_members = true,
643 "--unprovided-injects" => self.unprovided_injects = true,
644 "--unrendered-components" => self.unrendered_components = true,
645 "--unused-component-props" => self.unused_component_props = true,
646 "--absent-component-props" => self.absent_component_props = true,
647 "--constant-parameters" => self.constant_parameters = true,
648 "--unused-component-emits" => self.unused_component_emits = true,
649 "--unused-component-inputs" => self.unused_component_inputs = true,
650 "--unused-component-outputs" => self.unused_component_outputs = true,
651 "--unused-svelte-events" => self.unused_svelte_events = true,
652 "--unused-effect-layers" => self.unused_effect_layers = true,
653 "--unused-tagged-errors" => self.unused_tagged_errors = true,
654 "--unproduced-catch-tags" => self.unproduced_catch_tags = true,
655 "--unused-server-actions" => self.unused_server_actions = true,
656 "--unused-load-data-keys" => self.unused_load_data_keys = true,
657 "--unresolved-imports" => self.unresolved_imports = true,
658 "--unlisted-deps" => self.unlisted_deps = true,
659 "--unlisted-binaries" => self.unlisted_binaries = true,
660 "--duplicate-exports" => self.duplicate_exports = true,
661 "--duplicate-export-aliases" => self.duplicate_export_aliases = true,
662 "--circular-deps" => self.circular_deps = true,
663 "--re-export-cycles" => self.re_export_cycles = true,
664 "--package-cycles" => self.package_cycles = true,
665 "--boundary-violations" => self.boundary_violations = true,
666 "--policy-violations" => self.policy_violations = true,
667 "--stale-suppressions" => self.stale_suppressions = true,
668 "--unused-catalog-entries" => self.unused_catalog_entries = true,
669 "--empty-catalog-groups" => self.empty_catalog_groups = true,
670 "--unresolved-catalog-references" => self.unresolved_catalog_references = true,
671 "--unused-dependency-overrides" => self.unused_dependency_overrides = true,
672 "--misconfigured-dependency-overrides" => {
673 self.misconfigured_dependency_overrides = true;
674 }
675 _ => unreachable!("registry emitted unsupported dead-code filter flag: {flag}"),
676 }
677 }
678}
679
680#[derive(Debug, Clone, Default)]
682pub struct DeadCodeOptions {
683 pub analysis: AnalysisOptions,
685 pub filters: DeadCodeFilters,
687 pub files: Vec<PathBuf>,
689 pub include_entry_exports: bool,
691 pub show_cascade: bool,
693 pub finding_ids: Vec<String>,
698}
699
700#[derive(Debug, Clone, Default)]
706pub struct ArchitectureOptions {
707 pub shared_state: bool,
709 pub analysis: AnalysisOptions,
711 pub files: Vec<PathBuf>,
713 pub cycles: bool,
716 pub boundaries: bool,
718 pub policy: bool,
720}
721
722impl ArchitectureOptions {
723 #[must_use]
725 pub fn dead_code_filters(&self) -> DeadCodeFilters {
726 let all = !(self.cycles || self.boundaries || self.policy || self.shared_state);
727 DeadCodeFilters {
728 shared_state: self.shared_state,
729 circular_deps: self.cycles || all,
730 re_export_cycles: self.cycles || all,
731 package_cycles: self.cycles || all,
732 boundary_violations: self.boundaries || all,
733 policy_violations: self.policy || all,
734 ..DeadCodeFilters::default()
735 }
736 }
737
738 pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
741 fallow_engine::requested_rule_off::architecture_requested_flags(
742 self.cycles,
743 self.boundaries,
744 self.policy,
745 )
746 }
747
748 #[must_use]
750 pub fn dead_code_options(&self) -> DeadCodeOptions {
751 DeadCodeOptions {
752 analysis: self.analysis.clone(),
753 filters: self.dead_code_filters(),
754 files: self.files.clone(),
755 include_entry_exports: false,
756 show_cascade: false,
757 finding_ids: Vec::new(),
758 }
759 }
760}
761
762#[derive(Debug, Clone, Default)]
764pub struct AuditOptions {
765 pub analysis: AnalysisOptions,
767 pub base: Option<String>,
770 pub production: bool,
772 pub production_dead_code: Option<bool>,
774 pub production_health: Option<bool>,
776 pub production_dupes: Option<bool>,
779 pub dead_code: Option<bool>,
783 pub health: Option<bool>,
786 pub duplication: Option<bool>,
789 pub css: Option<bool>,
792 pub css_deep: Option<bool>,
795 pub gate: Option<fallow_config::AuditGate>,
798 pub worsened: Option<fallow_config::AuditWorsened>,
801 pub max_crap: Option<f64>,
803 pub coverage: Option<PathBuf>,
805 pub coverage_root: Option<PathBuf>,
807 pub include_entry_exports: bool,
809 pub show_cascade: bool,
811 pub runtime_coverage: Option<PathBuf>,
813 pub min_invocations_hot: u64,
815}
816
817#[derive(Debug, Clone)]
819pub struct CombinedOptions {
820 pub analysis: AnalysisOptions,
822 pub production_dead_code: Option<bool>,
826 pub production_health: Option<bool>,
828 pub production_dupes: Option<bool>,
831 pub dead_code: bool,
833 pub duplication: bool,
835 pub health: bool,
837 pub include_entry_exports: bool,
839 pub show_cascade: bool,
841 pub duplication_options: DuplicationOptions,
843 pub health_options: ComplexityOptions,
845}
846
847impl Default for CombinedOptions {
848 fn default() -> Self {
849 Self {
850 analysis: AnalysisOptions::default(),
851 production_dead_code: None,
852 production_health: None,
853 production_dupes: None,
854 dead_code: true,
855 duplication: true,
856 health: true,
857 include_entry_exports: false,
858 show_cascade: false,
859 duplication_options: DuplicationOptions::default(),
860 health_options: ComplexityOptions::default(),
861 }
862 }
863}
864
865#[derive(Debug, Clone, Default)]
867pub struct DecisionSurfaceOptions {
868 pub analysis: AnalysisOptions,
870 pub base: Option<String>,
873 pub max_decisions: Option<usize>,
875}
876
877#[derive(Debug, Clone, Default)]
879pub struct FeatureFlagsOptions {
880 pub analysis: AnalysisOptions,
882 pub top: Option<usize>,
885 pub retirement: Option<FeatureFlagsRetirementOptions>,
887}
888
889#[derive(Debug, Clone, Default)]
892pub struct FeatureFlagsRetirementOptions {
893 pub flag_age: fallow_types::flag_retirement::FlagAgeMode,
895 pub flag_state: Option<std::path::PathBuf>,
897 pub reasons: Vec<fallow_types::flag_retirement::RetirementReason>,
899 pub sort: fallow_engine::flag_retirement::RetirementSort,
901 pub min_age_days: Option<u64>,
903 pub max_flag_age: Option<u64>,
905}
906
907#[derive(Debug, Clone, Copy, Default)]
909pub enum DuplicationMode {
910 Strict,
913 #[default]
915 Mild,
916 Weak,
918 Semantic,
921}
922
923#[derive(Debug, Clone, Default)]
925pub struct DuplicationOptions {
926 pub analysis: AnalysisOptions,
928 pub mode: Option<DuplicationMode>,
930 pub near: Option<bool>,
933 pub min_tokens: Option<usize>,
935 pub min_lines: Option<usize>,
937 pub min_occurrences: Option<usize>,
940 pub threshold: Option<f64>,
943 pub skip_local: Option<bool>,
946 pub ignore_symlinks: Option<bool>,
949 pub cross_language: Option<bool>,
951 pub ignore_imports: Option<bool>,
954 pub top: Option<usize>,
956 pub include_fragments: Option<bool>,
960}
961
962#[derive(Debug, Clone, Default)]
964pub struct SimilarCodeOptions {
965 pub analysis: AnalysisOptions,
967 pub threshold: Option<f64>,
969 pub min_lines: Option<usize>,
972 pub top: Option<usize>,
974 pub files: Vec<PathBuf>,
978 #[doc(hidden)]
983 pub adapter_provider_path: Option<PathBuf>,
984}
985
986#[derive(Debug, Clone)]
988pub struct SimilarCodeInspectOptions {
989 pub analysis: AnalysisOptions,
992 pub snapshot: fallow_output::SimilarCodeCandidateSnapshot,
994}
995
996#[derive(Debug, Clone, Default)]
998pub struct TraceExportOptions {
999 pub analysis: AnalysisOptions,
1001 pub file: String,
1003 pub export_name: String,
1005}
1006
1007#[derive(Debug, Clone, Default)]
1009pub struct TraceFileOptions {
1010 pub analysis: AnalysisOptions,
1012 pub file: String,
1014}
1015
1016#[derive(Debug, Clone, Default)]
1018pub struct TraceImportPathOptions {
1019 pub analysis: AnalysisOptions,
1021 pub from: String,
1023 pub to: String,
1025 pub eager_only: bool,
1028}
1029
1030#[derive(Debug, Clone, Default)]
1032pub struct TraceErrorOptions {
1033 pub analysis: AnalysisOptions,
1035 pub trace: String,
1037 pub source: String,
1039}
1040
1041#[derive(Debug, Clone, Default)]
1043pub struct TraceDependencyOptions {
1044 pub analysis: AnalysisOptions,
1046 pub package_name: String,
1048 pub usage: Option<DependencyUsageQuery>,
1051}
1052
1053#[derive(Debug, Clone, PartialEq, Eq)]
1055pub enum TraceCloneTarget {
1056 Location {
1058 file: String,
1060 line: usize,
1062 },
1063 Fingerprint(String),
1065}
1066
1067#[derive(Debug, Clone)]
1069pub struct TraceCloneOptions {
1070 pub duplication: DuplicationOptions,
1072 pub target: TraceCloneTarget,
1074}
1075
1076#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1078pub enum ComplexitySort {
1079 #[default]
1081 Cyclomatic,
1082 Cognitive,
1084 Lines,
1086 Severity,
1088}
1089
1090#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1092pub enum OwnershipEmailMode {
1093 Raw,
1095 #[default]
1097 Handle,
1098 Anonymized,
1100 Hash,
1102}
1103
1104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1106pub enum TargetEffort {
1107 Low,
1109 Medium,
1111 High,
1113}
1114
1115#[derive(Debug, Clone, Default)]
1117pub struct ComplexityOptions {
1118 pub analysis: AnalysisOptions,
1120 pub max_cyclomatic: Option<u16>,
1122 pub max_cognitive: Option<u16>,
1124 pub max_crap: Option<f64>,
1126 pub max_file_lines: Option<u32>,
1129 pub top: Option<usize>,
1131 pub sort: ComplexitySort,
1133 pub complexity_breakdown: bool,
1135 pub complexity: bool,
1137 pub file_scores: bool,
1139 pub coverage_gaps: bool,
1141 pub config_activates_coverage_gaps: bool,
1146 pub hotspots: bool,
1148 pub ownership: bool,
1150 pub ownership_emails: Option<OwnershipEmailMode>,
1152 pub targets: bool,
1154 pub css: bool,
1156 pub css_deep: bool,
1158 pub effort: Option<TargetEffort>,
1161 pub score: bool,
1163 pub since: Option<String>,
1165 pub min_commits: Option<u32>,
1167 pub coverage: Option<PathBuf>,
1169 pub coverage_root: Option<PathBuf>,
1171 pub coverage_relocated: bool,
1176}
1177
1178#[derive(Debug, Clone, Copy, Default, PartialEq)]
1180pub struct ComplexityThresholdOverrides {
1181 pub max_cyclomatic: Option<u16>,
1183 pub max_cognitive: Option<u16>,
1185 pub max_crap: Option<f64>,
1187 pub max_file_lines: Option<u32>,
1189}
1190
1191#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1193pub struct ComplexityCoverageInputs<'a> {
1194 pub coverage: Option<&'a Path>,
1196 pub coverage_root: Option<&'a Path>,
1198 pub coverage_relocated: bool,
1201}
1202
1203#[derive(Debug, Clone)]
1205pub struct HealthSectionOptions {
1206 pub output: fallow_types::output_format::OutputFormat,
1208 pub complexity: bool,
1210 pub file_scores: bool,
1212 pub coverage_gaps: bool,
1214 pub hotspots: bool,
1216 pub targets: bool,
1218 pub css: bool,
1220 pub score: bool,
1222 pub score_gate: bool,
1224 pub snapshot_requested: bool,
1226 pub trend: bool,
1228}
1229
1230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1232pub struct DerivedHealthSections {
1233 pub any_section: bool,
1235 pub complexity: bool,
1237 pub file_scores: bool,
1239 pub coverage_gaps: bool,
1241 pub hotspots: bool,
1243 pub targets: bool,
1245 pub css: bool,
1247 pub score: bool,
1249 pub force_full: bool,
1251 pub score_only_output: bool,
1253}
1254
1255#[derive(Debug, Clone)]
1257pub struct ComplexitySectionOptions {
1258 pub complexity: bool,
1260 pub file_scores: bool,
1262 pub coverage_gaps: bool,
1264 pub hotspots: bool,
1266 pub ownership: bool,
1268 pub targets: bool,
1270 pub css: bool,
1272 pub score: bool,
1274}
1275
1276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1278pub struct DerivedComplexityOptions {
1279 pub any_section: bool,
1281 pub complexity: bool,
1283 pub file_scores: bool,
1285 pub coverage_gaps: bool,
1287 pub hotspots: bool,
1289 pub ownership: bool,
1291 pub targets: bool,
1293 pub force_full: bool,
1295 pub score_only_output: bool,
1297 pub score: bool,
1299}
1300
1301#[derive(Debug, Clone, PartialEq)]
1303pub struct ComplexityRunOptions<'a> {
1304 pub thresholds: ComplexityThresholdOverrides,
1306 pub top: Option<usize>,
1308 pub sort: ComplexitySort,
1310 pub complexity_breakdown: bool,
1312 pub sections: DerivedComplexityOptions,
1314 pub ownership_emails: Option<OwnershipEmailMode>,
1316 pub effort: Option<TargetEffort>,
1318 pub css: bool,
1320 pub css_deep: bool,
1322 pub since: Option<&'a str>,
1324 pub min_commits: Option<u32>,
1326 pub coverage_inputs: ComplexityCoverageInputs<'a>,
1328}
1329
1330pub fn configure_global_analysis_pool(threads: usize) -> bool {
1339 fallow_engine::thread_pool::worker_pool_builder(threads)
1340 .build_global()
1341 .is_ok()
1342}
1343
1344#[must_use]
1346pub fn derive_health_sections(options: &HealthSectionOptions) -> DerivedHealthSections {
1347 let score = options.score
1348 || options.score_gate
1349 || options.trend
1350 || matches!(
1351 options.output,
1352 fallow_types::output_format::OutputFormat::Badge
1353 );
1354 let any_section = options.complexity
1355 || options.file_scores
1356 || options.coverage_gaps
1357 || options.hotspots
1358 || options.targets
1359 || score;
1360 let effective_score = if any_section { score } else { true } || options.snapshot_requested;
1361 let force_full = options.snapshot_requested || effective_score;
1362
1363 DerivedHealthSections {
1364 any_section,
1365 complexity: if any_section {
1366 options.complexity
1367 } else {
1368 true
1369 },
1370 file_scores: if any_section {
1371 options.file_scores
1372 } else {
1373 true
1374 } || force_full,
1375 coverage_gaps: if any_section {
1376 options.coverage_gaps
1377 } else {
1378 false
1379 },
1380 hotspots: if any_section { options.hotspots } else { true }
1381 || options.snapshot_requested
1382 || options.trend,
1383 targets: if any_section { options.targets } else { true },
1384 css: options.css,
1385 score: effective_score,
1386 force_full,
1387 score_only_output: is_health_score_only_output(options, score),
1388 }
1389}
1390
1391#[must_use]
1393pub fn derive_complexity_sections(options: &ComplexitySectionOptions) -> DerivedComplexityOptions {
1394 let requested_hotspots = options.hotspots || options.ownership;
1395 let sections = derive_health_sections(&HealthSectionOptions {
1396 output: fallow_types::output_format::OutputFormat::Human,
1397 complexity: options.complexity,
1398 file_scores: options.file_scores,
1399 coverage_gaps: options.coverage_gaps,
1400 hotspots: requested_hotspots,
1401 targets: options.targets,
1402 css: options.css,
1403 score: options.score,
1404 score_gate: false,
1405 snapshot_requested: false,
1406 trend: false,
1407 });
1408
1409 DerivedComplexityOptions {
1410 any_section: sections.any_section,
1411 complexity: sections.complexity,
1412 file_scores: sections.file_scores,
1413 coverage_gaps: sections.coverage_gaps,
1414 hotspots: sections.hotspots,
1415 ownership: options.ownership && sections.hotspots,
1416 targets: sections.targets,
1417 force_full: sections.force_full,
1418 score_only_output: sections.score_only_output,
1419 score: sections.score,
1420 }
1421}
1422
1423#[must_use]
1425pub fn derive_complexity_options(options: &ComplexityOptions) -> DerivedComplexityOptions {
1426 derive_complexity_sections(&complexity_section_options(options))
1427}
1428
1429#[must_use]
1431pub fn derive_complexity_run_options(options: &ComplexityOptions) -> ComplexityRunOptions<'_> {
1432 ComplexityRunOptions {
1433 thresholds: ComplexityThresholdOverrides {
1434 max_cyclomatic: options.max_cyclomatic,
1435 max_cognitive: options.max_cognitive,
1436 max_crap: options.max_crap,
1437 max_file_lines: options.max_file_lines,
1438 },
1439 top: options.top,
1440 sort: options.sort,
1441 complexity_breakdown: options.complexity_breakdown,
1442 sections: derive_complexity_options(options),
1443 ownership_emails: options.ownership_emails,
1444 effort: options.effort,
1445 css: options.css,
1446 css_deep: options.css_deep,
1447 since: options.since.as_deref(),
1448 min_commits: options.min_commits,
1449 coverage_inputs: ComplexityCoverageInputs {
1450 coverage: options.coverage.as_deref(),
1451 coverage_root: options.coverage_root.as_deref(),
1452 coverage_relocated: options.coverage_relocated,
1453 },
1454 }
1455}
1456
1457pub fn validate_complexity_options(options: &ComplexityOptions) -> Result<(), ProgrammaticError> {
1480 if let Some(path) = &options.coverage {
1481 let resolved = fallow_engine::health::scoring::resolve_relative_to_root(
1482 path,
1483 options.analysis.root.as_deref(),
1484 );
1485 if !resolved.exists() {
1486 return Err(ProgrammaticError::new(
1487 format!("coverage path does not exist: {}", resolved.display()),
1488 2,
1489 )
1490 .with_code("FALLOW_INVALID_COVERAGE_PATH")
1491 .with_context("health.coverage"));
1492 }
1493 }
1494 if let Err(message) =
1495 fallow_engine::health::validate_coverage_root_absolute(options.coverage_root.as_deref())
1496 {
1497 return Err(ProgrammaticError::new(message, 2)
1498 .with_code("FALLOW_INVALID_COVERAGE_ROOT")
1499 .with_context("health.coverage_root"));
1500 }
1501
1502 Ok(())
1503}
1504
1505fn complexity_section_options(options: &ComplexityOptions) -> ComplexitySectionOptions {
1506 let ownership = options.ownership || options.ownership_emails.is_some();
1507 let requested_targets = options.targets || options.effort.is_some();
1508 ComplexitySectionOptions {
1509 complexity: options.complexity,
1510 file_scores: options.file_scores,
1511 coverage_gaps: options.coverage_gaps,
1512 hotspots: options.hotspots,
1513 ownership,
1514 targets: requested_targets,
1515 css: options.css,
1516 score: options.score,
1517 }
1518}
1519
1520fn is_health_score_only_output(options: &HealthSectionOptions, score: bool) -> bool {
1521 score
1522 && !options.complexity
1523 && !options.file_scores
1524 && !options.coverage_gaps
1525 && !options.hotspots
1526 && !options.targets
1527 && !options.trend
1528}
1529
1530const fn thresholds_to_engine(
1531 thresholds: ComplexityThresholdOverrides,
1532) -> fallow_engine::health::HealthThresholdOverrides {
1533 fallow_engine::health::HealthThresholdOverrides {
1534 max_cyclomatic: thresholds.max_cyclomatic,
1535 max_cognitive: thresholds.max_cognitive,
1536 max_crap: thresholds.max_crap,
1537 max_file_lines: thresholds.max_file_lines,
1538 }
1539}
1540
1541const fn complexity_sort_to_engine(sort: ComplexitySort) -> fallow_engine::health::HealthSort {
1542 match sort {
1543 ComplexitySort::Severity => fallow_engine::health::HealthSort::Severity,
1544 ComplexitySort::Cyclomatic => fallow_engine::health::HealthSort::Cyclomatic,
1545 ComplexitySort::Cognitive => fallow_engine::health::HealthSort::Cognitive,
1546 ComplexitySort::Lines => fallow_engine::health::HealthSort::Lines,
1547 }
1548}
1549
1550const fn coverage_inputs_to_engine(
1551 coverage_inputs: ComplexityCoverageInputs<'_>,
1552) -> fallow_engine::health::HealthCoverageInputs<'_> {
1553 fallow_engine::health::HealthCoverageInputs {
1554 coverage: coverage_inputs.coverage,
1555 coverage_root: coverage_inputs.coverage_root,
1556 coverage_relocated: coverage_inputs.coverage_relocated,
1557 }
1558}
1559
1560const fn ownership_email_mode_to_config(mode: OwnershipEmailMode) -> EmailMode {
1561 match mode {
1562 OwnershipEmailMode::Raw => EmailMode::Raw,
1563 OwnershipEmailMode::Handle => EmailMode::Handle,
1564 OwnershipEmailMode::Anonymized => EmailMode::Anonymized,
1565 OwnershipEmailMode::Hash => EmailMode::Hash,
1566 }
1567}
1568
1569const fn target_effort_to_output(effort: TargetEffort) -> EffortEstimate {
1570 match effort {
1571 TargetEffort::Low => EffortEstimate::Low,
1572 TargetEffort::Medium => EffortEstimate::Medium,
1573 TargetEffort::High => EffortEstimate::High,
1574 }
1575}
1576
1577#[cfg(test)]
1578mod tests {
1579 use super::*;
1580
1581 #[test]
1582 fn duplication_defaults_match_cli_contract() {
1583 let options = DuplicationOptions::default();
1584 assert!(options.mode.is_none());
1585 assert!(options.min_tokens.is_none());
1586 assert!(options.min_lines.is_none());
1587 assert!(options.min_occurrences.is_none());
1588 }
1589
1590 #[test]
1591 fn programmatic_error_builder_keeps_optional_fields() {
1592 let error = ProgrammaticError::new("boom", 2)
1593 .with_code("FALLOW_TEST")
1594 .with_help("Try again")
1595 .with_context("analysis.root");
1596
1597 assert_eq!(error.message, "boom");
1598 assert_eq!(error.exit_code, 2);
1599 assert_eq!(error.code.as_deref(), Some("FALLOW_TEST"));
1600 assert_eq!(error.help.as_deref(), Some("Try again"));
1601 assert_eq!(error.context.as_deref(), Some("analysis.root"));
1602 }
1603
1604 #[test]
1605 fn dead_code_filters_accept_shared_registry_selectors() {
1606 for (selector, _) in fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS.iter() {
1607 let mut filters = DeadCodeFilters::default();
1608 assert!(
1609 filters.enable_registry_selector(selector),
1610 "{selector} should be accepted"
1611 );
1612 }
1613
1614 let mut filters = DeadCodeFilters::default();
1615 assert!(filters.enable_registry_selector("unused-files"));
1616 assert!(filters.unused_files);
1617 assert!(filters.enable_registry_selector("boundary-violations"));
1618 assert!(filters.boundary_violations);
1619 assert!(!filters.enable_registry_selector("not-a-real-selector"));
1620 }
1621
1622 #[test]
1623 fn default_complexity_options_match_programmatic_health_defaults() {
1624 let derived = derive_complexity_options(&ComplexityOptions::default());
1625
1626 assert!(!derived.any_section);
1627 assert!(derived.complexity);
1628 assert!(derived.file_scores);
1629 assert!(!derived.coverage_gaps);
1630 assert!(derived.hotspots);
1631 assert!(!derived.ownership);
1632 assert!(derived.targets);
1633 assert!(derived.force_full);
1634 assert!(!derived.score_only_output);
1635 assert!(derived.score);
1636 }
1637
1638 #[test]
1639 fn score_only_complexity_options_request_score_only_output() {
1640 let derived = derive_complexity_options(&ComplexityOptions {
1641 score: true,
1642 ..ComplexityOptions::default()
1643 });
1644
1645 assert!(derived.any_section);
1646 assert!(!derived.complexity);
1647 assert!(derived.file_scores);
1648 assert!(!derived.hotspots);
1649 assert!(!derived.targets);
1650 assert!(derived.force_full);
1651 assert!(derived.score_only_output);
1652 assert!(derived.score);
1653 }
1654
1655 #[test]
1656 fn ownership_implies_hotspots_when_requested() {
1657 let derived = derive_complexity_options(&ComplexityOptions {
1658 ownership: true,
1659 ..ComplexityOptions::default()
1660 });
1661
1662 assert!(derived.any_section);
1663 assert!(derived.hotspots);
1664 assert!(derived.ownership);
1665 assert!(!derived.targets);
1666 }
1667
1668 #[test]
1669 fn complexity_run_options_normalize_public_api_options() {
1670 let options = ComplexityOptions {
1671 max_cyclomatic: Some(42),
1672 max_cognitive: Some(21),
1673 max_crap: Some(18.5),
1674 top: Some(7),
1675 sort: ComplexitySort::Severity,
1676 complexity_breakdown: true,
1677 ownership_emails: Some(OwnershipEmailMode::Hash),
1678 effort: Some(TargetEffort::High),
1679 coverage: Some(PathBuf::from("coverage/coverage-final.json")),
1680 coverage_root: Some(PathBuf::from("/ci/workspace")),
1681 since: Some("30d".to_string()),
1682 min_commits: Some(4),
1683 ..ComplexityOptions::default()
1684 };
1685
1686 let run = derive_complexity_run_options(&options);
1687
1688 assert_eq!(run.thresholds.max_cyclomatic, Some(42));
1689 assert_eq!(run.thresholds.max_cognitive, Some(21));
1690 assert_eq!(run.thresholds.max_crap, Some(18.5));
1691 assert_eq!(run.top, Some(7));
1692 assert!(matches!(run.sort, ComplexitySort::Severity));
1693 assert!(run.complexity_breakdown);
1694 assert!(run.sections.hotspots);
1695 assert!(run.sections.ownership);
1696 assert!(run.sections.targets);
1697 assert!(matches!(
1698 run.ownership_emails,
1699 Some(OwnershipEmailMode::Hash)
1700 ));
1701 assert!(matches!(run.effort, Some(TargetEffort::High)));
1702 assert_eq!(run.since, Some("30d"));
1703 assert_eq!(run.min_commits, Some(4));
1704 assert_eq!(run.coverage_inputs.coverage, options.coverage.as_deref());
1705 assert_eq!(
1706 run.coverage_inputs.coverage_root,
1707 options.coverage_root.as_deref()
1708 );
1709 }
1710
1711 #[test]
1712 fn complexity_options_validation_accepts_existing_coverage_path_and_absolute_root() {
1713 let dir = tempfile::tempdir().expect("tempdir");
1714 let coverage = dir.path().join("coverage-final.json");
1715 std::fs::write(&coverage, "{}").expect("coverage fixture");
1716
1717 let result = validate_complexity_options(&ComplexityOptions {
1718 coverage: Some(coverage),
1719 coverage_root: Some(PathBuf::from("/ci/workspace")),
1720 ..ComplexityOptions::default()
1721 });
1722
1723 assert!(result.is_ok());
1724 }
1725
1726 #[test]
1727 fn complexity_options_validation_keeps_missing_coverage_error_contract() {
1728 let err = validate_complexity_options(&ComplexityOptions {
1729 coverage: Some(PathBuf::from("/missing/coverage-final.json")),
1730 ..ComplexityOptions::default()
1731 })
1732 .expect_err("missing coverage path should fail");
1733
1734 assert_eq!(err.exit_code, 2);
1735 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1736 assert_eq!(err.context.as_deref(), Some("health.coverage"));
1737 }
1738
1739 #[test]
1740 fn complexity_options_validation_keeps_relative_coverage_root_error_contract() {
1741 let err = validate_complexity_options(&ComplexityOptions {
1742 coverage_root: Some(PathBuf::from("coverage")),
1743 ..ComplexityOptions::default()
1744 })
1745 .expect_err("relative coverage root should fail");
1746
1747 assert_eq!(err.exit_code, 2);
1748 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_ROOT"));
1749 assert_eq!(err.context.as_deref(), Some("health.coverage_root"));
1750 }
1751
1752 #[test]
1756 fn complexity_options_validation_resolves_relative_coverage_against_root() {
1757 let dir = tempfile::tempdir().expect("tempdir");
1758 std::fs::create_dir_all(dir.path().join("artifacts")).expect("artifacts dir");
1759 std::fs::write(dir.path().join("artifacts/coverage-final.json"), "{}")
1760 .expect("coverage fixture");
1761 let relative = PathBuf::from("artifacts/coverage-final.json");
1762 assert!(
1763 !relative.exists(),
1764 "the fixture must not also exist under the test cwd"
1765 );
1766
1767 let result = validate_complexity_options(&ComplexityOptions {
1768 analysis: AnalysisOptions {
1769 root: Some(dir.path().to_path_buf()),
1770 ..AnalysisOptions::default()
1771 },
1772 coverage: Some(relative.clone()),
1773 ..ComplexityOptions::default()
1774 });
1775 assert!(result.is_ok(), "{result:?}");
1776
1777 let err = validate_complexity_options(&ComplexityOptions {
1778 analysis: AnalysisOptions {
1779 root: Some(dir.path().join("elsewhere")),
1780 ..AnalysisOptions::default()
1781 },
1782 coverage: Some(relative),
1783 ..ComplexityOptions::default()
1784 })
1785 .expect_err("the path does not exist under the other root");
1786 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1787 assert!(
1788 err.message.contains("elsewhere"),
1789 "the message names the resolved path: {}",
1790 err.message
1791 );
1792 }
1793
1794 #[test]
1795 fn default_health_sections_match_full_health_output() {
1796 let derived = derive_health_sections(&HealthSectionOptions {
1797 output: fallow_types::output_format::OutputFormat::Human,
1798 complexity: false,
1799 file_scores: false,
1800 coverage_gaps: false,
1801 hotspots: false,
1802 targets: false,
1803 css: false,
1804 score: false,
1805 score_gate: false,
1806 snapshot_requested: false,
1807 trend: false,
1808 });
1809
1810 assert!(!derived.any_section);
1811 assert!(derived.complexity);
1812 assert!(derived.file_scores);
1813 assert!(!derived.coverage_gaps);
1814 assert!(derived.hotspots);
1815 assert!(derived.targets);
1816 assert!(derived.score);
1817 assert!(derived.force_full);
1818 assert!(!derived.score_only_output);
1819 }
1820
1821 #[test]
1822 fn health_score_gate_requests_score_only_output() {
1823 let derived = derive_health_sections(&HealthSectionOptions {
1824 output: fallow_types::output_format::OutputFormat::Human,
1825 complexity: false,
1826 file_scores: false,
1827 coverage_gaps: false,
1828 hotspots: false,
1829 targets: false,
1830 css: false,
1831 score: false,
1832 score_gate: true,
1833 snapshot_requested: false,
1834 trend: false,
1835 });
1836
1837 assert!(derived.any_section);
1838 assert!(!derived.complexity);
1839 assert!(derived.file_scores);
1840 assert!(!derived.hotspots);
1841 assert!(!derived.targets);
1842 assert!(derived.score);
1843 assert!(derived.force_full);
1844 assert!(derived.score_only_output);
1845 }
1846
1847 #[test]
1848 fn health_snapshot_keeps_full_hidden_inputs_without_section_request() {
1849 let derived = derive_health_sections(&HealthSectionOptions {
1850 output: fallow_types::output_format::OutputFormat::Human,
1851 complexity: false,
1852 file_scores: false,
1853 coverage_gaps: false,
1854 hotspots: false,
1855 targets: false,
1856 css: true,
1857 score: false,
1858 score_gate: false,
1859 snapshot_requested: true,
1860 trend: false,
1861 });
1862
1863 assert!(!derived.any_section);
1864 assert!(derived.css);
1865 assert!(derived.file_scores);
1866 assert!(derived.hotspots);
1867 assert!(derived.score);
1868 assert!(derived.force_full);
1869 }
1870}
1871
1872mod shared_state_explain;