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 explain_examples;
57mod explain_guides;
58mod explain_rationale;
59pub mod grouped_output;
60pub mod health_codeclimate;
61mod health_groups_markdown;
62pub mod json_output;
63pub mod list_output;
64mod list_runtime;
65pub mod markdown_output;
68pub mod mutation;
69mod next_steps;
70pub mod output_contracts;
71pub mod ownership;
72mod release_signature;
73pub mod review_deltas;
74pub mod routing;
75pub mod run;
76pub mod runtime;
77mod runtime_json;
78mod runtime_output;
79pub mod sarif_output;
80pub mod schemas;
83pub mod security_output;
84pub mod similar_code;
86mod threshold_override_output;
87mod type_aware;
88pub use analysis_context::{ProgrammaticAnalysisContext, resolve_programmatic_analysis_context};
89pub use audit_output::{
90 AuditAttribution, AuditCodeClimateOutputInput, AuditJsonHeaderInput, AuditJsonOutputInput,
91 AuditSarifOutputInput, AuditSummary, AuditVerdict, attach_audit_diff_risk_attribution,
92 attach_audit_duplication_demotion_attribution, attach_audit_styling_attribution,
93 attach_audit_wire_attribution, audit_run_notices, build_audit_codeclimate,
94 build_audit_codeclimate_issues, build_audit_header_json, build_audit_header_map,
95 build_audit_sarif, build_diff_risk_codeclimate, build_review_brief_header,
96 serialize_audit_json,
97};
98pub use combined_output::{
99 CombinedCheckJsonSection, CombinedJsonOutputInput, serialize_combined_dupes_json,
100 serialize_combined_health_json, serialize_combined_json,
101};
102pub use compact_output::{
103 build_compact_lines, build_diff_risk_compact_lines, build_duplication_compact_lines,
104 build_grouped_compact_lines, build_health_compact_lines,
105};
106pub use coverage::{
107 CoverageInputError, CoverageInputSource, CoverageInputs, resolve_coverage_inputs,
108};
109pub use dead_code_codeclimate::build_codeclimate;
110pub use dead_code_sarif::build_sarif;
111pub use doctor::{DoctorOptions, run_doctor, run_doctor_with_cache_dir};
112pub use dupes_output::{
113 AttributedCloneGroup, AttributedCloneGroupFinding, AttributedInstance, CloneDemotionReason,
114 CloneFamilyFinding, CloneGroupFinding, CombinedDupesSection, DupesReportPayload,
115 DuplicationGroup, DuplicationGrouping, build_duplication_codeclimate,
116 set_duplication_audit_attribution,
117};
118pub use editor::{
119 ChangedFilesError, EditorAnalysisOutput, EditorAnalysisResults, EditorAnalysisSession,
120 EditorCloneFamily, EditorCloneFingerprintSet, EditorCloneGroup, EditorCloneInstance,
121 EditorDeadCodeAnalysisOutput, EditorDuplicationReport, EditorDuplicationStats,
122 EditorInlineComplexityExceeded, EditorInlineComplexityFinding, EditorMirroredDirectory,
123 EditorProjectAnalysisOutput, EditorRefactoringKind, EditorRefactoringSuggestion,
124 EditorSessionParseCounts, collect_inline_complexity, editor_duplicates, editor_extract,
125 editor_results, editor_security, editor_suppress, filter_inline_complexity_by_change_scope,
126 filter_inline_complexity_by_changed_files, resolve_git_toplevel,
127 try_get_changed_files_with_toplevel,
128};
129pub use explain::{
130 AUDIT_RULES, CHECK_RULES, DUPES_RULES, FLAGS_RULES, HEALTH_RULES, MUTATION_RULES, RuleDef,
131 RuleGuide, SECURITY_RULES, all_rules, bare_rule_id, coverage_analyze_meta, coverage_setup_meta,
132 explain_issue_type, rule_by_id, rule_by_token, rule_command, rule_config_key, rule_docs_url,
133 rule_guide, rule_has_guide, rule_rationale, rule_severity_key, security_meta,
134 serialize_explain_programmatic_json, unknown_explain_error,
135};
136pub use explain_examples::{ExampleFile, RuleExample, rule_example, rule_examples};
137pub use fallow_config::levenshtein::closest_match;
138pub use fallow_config::{
139 AuditGate, AuditWorsened, HealthConfig, ProductionAnalysis, ProductionEnv, TypeAwareRequire,
140};
141pub use fallow_engine::change_scope::{
144 ChangeScope, ChangeScopeOwner, ChangeScopeRequest, first_package_baselines,
145 package_baseline_statuses,
146};
147#[cfg(any(test, feature = "testing"))]
150pub use fallow_engine::git_fixture;
151pub use fallow_engine::package_baselines::{PackageBaselineError, PackageChangeScope};
153pub use fallow_engine::source_edits;
156pub use fallow_engine::thread_pool::{WORKER_STACK_SIZE, register_thread_stack};
163pub use fallow_engine::warm_parse;
169pub use fallow_output::PackageBaselineStatus;
171pub use fallow_output::serialize_similar_code_json_output;
172pub use fallow_types::trace::{
173 CloneTrace, DependencyTrace, ExportReference, ExportTrace, FileTrace, ReExportChain,
174 TracedCloneGroup, TracedExport, TracedReExport,
175};
176pub use fallow_types::trace_usage::{
177 DependencyUsage, DependencyUsageQuery, SitePageRequest, UsageQueryError,
178};
179pub use grouped_output::{
180 ResultGroup, UNOWNED_GROUP_LABEL, build_duplication_grouping_with, group_analysis_results_with,
181 health_signal_header_part, largest_clone_group_owner_with,
182};
183pub use health_codeclimate::build_health_codeclimate;
184pub use health_groups_markdown::build_health_groups_markdown;
185pub use json_output::{
186 CheckJsonExtraOutputs, CheckJsonOutputInput, CheckJsonPayloadInput, DuplicationJsonOutputInput,
187 GroupedCheckJsonOutputInput, GroupedDuplicationJsonOutputInput, serialize_check_json,
188 serialize_check_json_payload, serialize_duplication_json, serialize_grouped_check_json,
189 serialize_grouped_duplication_json,
190};
191pub use list_output::{
192 ListJsonEnvelope, ListJsonOutputInput, build_list_json_output, serialize_list_json_output,
193};
194pub use list_runtime::{
195 BoundaryData, ListBoundariesOptions, ListBoundariesProgrammaticOutput, LogicalGroupInfo,
196 ProjectInfoOptions, ProjectInfoProgrammaticOutput, RuleInfo, ZoneInfo, boundary_data_to_output,
197 compute_boundary_data, run_list_boundaries, run_project_info,
198 serialize_list_boundaries_programmatic_json, serialize_project_info_programmatic_json,
199};
200pub use markdown_output::{
201 ComplexityListing, build_diff_risk_markdown, build_duplication_markdown,
202 build_grouped_markdown, build_health_markdown, build_markdown, build_walkthrough_markdown,
203};
204pub use mutation::{
205 MutationProgress, MutationProgressSink, MutationReplayOptions, MutationRunOptions,
206 MutationRunScope, apply_mutation_verdicts, validate_mutation_verdicts,
207};
208pub use output_contracts::{
209 AuditOutput, BoundariesListLogicalGroup, BoundariesListRule, BoundariesListZone,
210 BoundariesListing, CombinedOutput, FallowOutput, ImpactOutput, ListBoundariesOutput,
211 ListEntryPointOutput, ListOutput, ListPluginOutput, ReviewBriefWireOutput, SecurityGate,
212 SecurityOutput, SecurityOutputConfig, SecuritySummaryOutput, SimilarCodeCandidateSnapshot,
213 SimilarCodeOutput, TraceOutput, WorkspacesOutput,
214};
215pub use runtime::TYPE_AWARE_CONFIG_UNSUPPORTED;
216pub use runtime::{
217 AUDIT_CONFIG_BASELINE_UNSUPPORTED, ArchitectureOutput, ArchitectureProgrammaticOutput,
218 AuditProgrammaticKeySnapshot, AuditProgrammaticOutput, BoundaryViolationsOutput,
219 BoundaryViolationsProgrammaticOutput, CircularDependenciesOutput,
220 CircularDependenciesProgrammaticOutput, CombinedProgrammaticOutput, DeadCodeOutput,
221 DeadCodeProgrammaticOutput, DecisionSurfaceProgrammaticOutput, DuplicationOutput,
222 DuplicationProgrammaticOutput, EngineHealthRunner, FeatureFlagsOutput,
223 FeatureFlagsProgrammaticOutput, HealthJsonReportInput, HealthProgrammaticOutput,
224 ProgrammaticHealthAnalysis, ProgrammaticHealthNextStepFacts, ProgrammaticHealthRun,
225 ProgrammaticHealthRunner, TraceClassMemberOutput, TraceCloneBenchmarkResult, TraceCloneOutput,
226 TraceCloneProgrammaticOutput, TraceDependencyOutput, TraceDependencyProgrammaticOutput,
227 TraceErrorOutput, TraceErrorProgrammaticOutput, TraceExportOutput,
228 TraceExportProgrammaticOutput, TraceExportTargetOutput, TraceFileOutput,
229 TraceFileProgrammaticOutput, TraceImportPathOutput, TraceImportPathProgrammaticOutput,
230 benchmark_trace_clone_compact_json, benchmark_trace_graph_family_compact_json,
231 inspect_similar_code, load_health_config, parse_similar_code_candidate_snapshot, plan_mutation,
232 replay_mutation, review_similar_code, run_architecture, run_audit, run_boundary_violations,
233 run_circular_dependencies, run_combined, run_complexity_with_runner, run_dead_code,
234 run_dead_code_with_baseline, run_decision_surface, run_duplication, run_feature_flags,
235 run_health, run_health_with_runner, run_mutation, run_mutation_with_progress, run_similar_code,
236 run_trace_clone, run_trace_dependency, run_trace_error, run_trace_export, run_trace_file,
237 run_trace_import_path, select_similar_code_candidate_snapshot, serialize_health_report_json,
238};
239pub use runtime_json::{
240 serialize_architecture_programmatic_json, serialize_audit_programmatic_json,
241 serialize_boundary_violations_programmatic_json,
242 serialize_circular_dependencies_programmatic_json, serialize_combined_programmatic_json,
243 serialize_dead_code_programmatic_json, serialize_decision_surface_programmatic_json,
244 serialize_duplication_programmatic_json, serialize_feature_flags_programmatic_json,
245 serialize_health_programmatic_json, serialize_trace_clone_programmatic_json,
246 serialize_trace_dependency_programmatic_json, serialize_trace_error_programmatic_json,
247 serialize_trace_export_programmatic_json, serialize_trace_file_programmatic_json,
248 serialize_trace_import_path_programmatic_json,
249};
250pub use sarif_output::{
251 annotate_sarif_results, build_duplication_sarif, build_grouped_duplication_sarif,
252 build_health_sarif,
253};
254pub use security_output::SecurityGateMode;
255pub use type_aware::{
256 DEFAULT_BACKEND_FAMILY as DEFAULT_TYPE_AWARE_BACKEND_FAMILY, SemanticCouplingOutcome,
257 SemanticDeadCodeOutcome, SemanticInspectOutcome, TypeAwareError, TypeAwareFileChanges,
258 TypeAwareOutcome, TypeAwareSession, TypeAwareStatus, discard_unverified_semantic_candidates,
259 inspect_symbol as inspect_type_aware_symbol, merge_type_aware_meta,
260 refine_configured_dead_code_results as refine_type_aware_results_with_config,
261 shutdown_type_aware_sidecars, status as type_aware_status,
262 symbol_impact as run_type_aware_symbol_impact, symbol_impact as type_aware_symbol_impact,
263 terminate_active_type_aware_sidecars, trace_symbol as run_type_aware_symbol_trace,
264 trace_symbol as trace_type_aware_symbol, type_coupling as analyze_type_coupling,
265};
266
267pub use type_aware::setup_store as type_aware_setup;
270
271pub const COMMON_ANALYSIS_OPTION_FLAGS: &[&str] = &[
278 "root",
279 "config",
280 "no-cache",
281 "threads",
282 "changed-since",
283 "diff-file",
284 "production",
285 "workspace",
286 "changed-workspaces",
287 "explain",
288 "allow-remote-extends",
289];
290
291#[derive(Debug, Clone, Serialize)]
293pub struct ProgrammaticError {
294 pub message: String,
296 pub exit_code: u8,
298 pub code: Option<String>,
300 pub help: Option<String>,
302 pub context: Option<String>,
304}
305
306impl ProgrammaticError {
307 #[must_use]
310 pub fn new(message: impl Into<String>, exit_code: u8) -> Self {
311 Self {
312 message: message.into(),
313 exit_code,
314 code: None,
315 help: None,
316 context: None,
317 }
318 }
319
320 #[must_use]
322 pub fn with_help(mut self, help: impl Into<String>) -> Self {
323 self.help = Some(help.into());
324 self
325 }
326
327 #[must_use]
330 pub fn with_code(mut self, code: impl Into<String>) -> Self {
331 self.code = Some(code.into());
332 self
333 }
334
335 #[must_use]
338 pub fn with_context(mut self, context: impl Into<String>) -> Self {
339 self.context = Some(context.into());
340 self
341 }
342}
343
344impl std::fmt::Display for ProgrammaticError {
345 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
346 write!(f, "{}", self.message)
347 }
348}
349
350impl std::error::Error for ProgrammaticError {}
351
352#[derive(Debug, Clone, Default)]
354pub struct AnalysisOptions {
355 pub root: Option<PathBuf>,
358 pub config_path: Option<PathBuf>,
360 pub allow_remote_extends: bool,
362 pub no_cache: bool,
364 pub threads: Option<usize>,
366 pub diff_file: Option<PathBuf>,
378 pub ambient_diff_file: Option<PathBuf>,
386 pub production: bool,
389 pub production_override: Option<bool>,
392 pub changed_since: Option<String>,
397 pub ambient_changed_since: Option<String>,
405 pub no_package_baselines: bool,
409 pub workspace: Option<Vec<String>>,
411 pub changed_workspaces: Option<String>,
413 pub explain: bool,
415 pub type_aware: TypeAwareOptions,
418 pub cancellation: Option<Arc<AtomicBool>>,
448 pub host: Option<run::HostInputs>,
454}
455
456#[derive(Debug, Clone, Default, PartialEq, Eq)]
458pub struct TypeAwareOptions {
459 pub enabled: Option<bool>,
466 pub projects: Vec<PathBuf>,
469 pub require: fallow_config::TypeAwareRequire,
471}
472
473impl TypeAwareOptions {
474 #[must_use]
476 pub const fn requested(&self) -> bool {
477 matches!(self.enabled, Some(true))
478 }
479}
480
481#[derive(Debug, Clone, Default, PartialEq, Eq)]
486pub struct DeadCodeFilters {
487 pub shared_state: bool,
489 pub unused_files: bool,
491 pub unused_exports: bool,
493 pub unused_deps: bool,
495 pub unused_types: bool,
497 pub private_type_leaks: bool,
499 pub deprecated_exports_in_use: bool,
501 pub unused_enum_members: bool,
503 pub unused_class_members: bool,
505 pub unused_namespace_members: bool,
507 pub unused_protected_class_members: bool,
509 pub unused_store_members: bool,
511 pub unprovided_injects: bool,
513 pub unrendered_components: bool,
515 pub unused_component_props: bool,
517 pub absent_component_props: bool,
519 pub constant_parameters: bool,
521 pub unused_component_emits: bool,
523 pub unused_component_inputs: bool,
525 pub unused_component_outputs: bool,
527 pub unused_svelte_events: bool,
529 pub unused_effect_layers: bool,
531 pub unused_tagged_errors: bool,
533 pub unproduced_catch_tags: bool,
535 pub unused_server_actions: bool,
537 pub unused_load_data_keys: bool,
539 pub unresolved_imports: bool,
541 pub unlisted_deps: bool,
543 pub unlisted_binaries: bool,
545 pub duplicate_exports: bool,
547 pub duplicate_export_aliases: bool,
549 pub circular_deps: bool,
551 pub re_export_cycles: bool,
553 pub package_cycles: bool,
555 pub boundary_violations: bool,
557 pub policy_violations: bool,
559 pub stale_suppressions: bool,
561 pub unused_catalog_entries: bool,
563 pub empty_catalog_groups: bool,
565 pub unresolved_catalog_references: bool,
567 pub unused_dependency_overrides: bool,
569 pub misconfigured_dependency_overrides: bool,
571}
572
573impl DeadCodeFilters {
574 pub(crate) fn reports_dependency_findings(&self) -> bool {
578 !self.any_active() || self.unused_deps || self.unlisted_deps
579 }
580
581 fn any_active(&self) -> bool {
582 self.shared_state
583 || self.unused_files
584 || self.unused_exports
585 || self.unused_deps
586 || self.unused_types
587 || self.private_type_leaks
588 || self.deprecated_exports_in_use
589 || self.unused_enum_members
590 || self.unused_class_members
591 || self.unused_namespace_members
592 || self.unused_protected_class_members
593 || self.unused_store_members
594 || self.unprovided_injects
595 || self.unrendered_components
596 || self.unused_component_props
597 || self.absent_component_props
598 || self.constant_parameters
599 || self.unused_component_emits
600 || self.unused_component_inputs
601 || self.unused_component_outputs
602 || self.unused_svelte_events
603 || self.unused_effect_layers
604 || self.unused_tagged_errors
605 || self.unproduced_catch_tags
606 || self.unused_server_actions
607 || self.unused_load_data_keys
608 || self.unresolved_imports
609 || self.unlisted_deps
610 || self.unlisted_binaries
611 || self.duplicate_exports
612 || self.duplicate_export_aliases
613 || self.circular_deps
614 || self.re_export_cycles
615 || self.package_cycles
616 || self.boundary_violations
617 || self.policy_violations
618 || self.stale_suppressions
619 || self.unused_catalog_entries
620 || self.empty_catalog_groups
621 || self.unresolved_catalog_references
622 || self.unused_dependency_overrides
623 || self.misconfigured_dependency_overrides
624 }
625
626 pub fn enable_registry_selector(&mut self, selector: &str) -> bool {
632 let Some(flag) = fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS
633 .iter()
634 .find_map(|&(name, flag)| (name == selector).then_some(flag))
635 else {
636 return false;
637 };
638 self.enable_cli_filter_flag(flag);
639 true
640 }
641
642 pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
644 fallow_engine::requested_rule_off::explicit_filter_flags(|flag| {
645 let mut enabled = self.clone();
646 enabled.enable_cli_filter_flag(flag);
647 enabled == *self
648 })
649 }
650
651 fn enable_cli_filter_flag(&mut self, flag: &str) {
652 match flag {
653 "--unused-files" => self.unused_files = true,
654 "--unused-exports" => self.unused_exports = true,
655 "--unused-types" => self.unused_types = true,
656 "--private-type-leaks" => self.private_type_leaks = true,
657 "--deprecated-exports-in-use" => self.deprecated_exports_in_use = true,
658 "--unused-deps" => self.unused_deps = true,
659 "--unused-enum-members" => self.unused_enum_members = true,
660 "--unused-class-members" => self.unused_class_members = true,
661 "--unused-namespace-members" => self.unused_namespace_members = true,
662 "--unused-protected-class-members" => self.unused_protected_class_members = true,
663 "--unused-store-members" => self.unused_store_members = true,
664 "--unprovided-injects" => self.unprovided_injects = true,
665 "--unrendered-components" => self.unrendered_components = true,
666 "--unused-component-props" => self.unused_component_props = true,
667 "--absent-component-props" => self.absent_component_props = true,
668 "--constant-parameters" => self.constant_parameters = true,
669 "--unused-component-emits" => self.unused_component_emits = true,
670 "--unused-component-inputs" => self.unused_component_inputs = true,
671 "--unused-component-outputs" => self.unused_component_outputs = true,
672 "--unused-svelte-events" => self.unused_svelte_events = true,
673 "--unused-effect-layers" => self.unused_effect_layers = true,
674 "--unused-tagged-errors" => self.unused_tagged_errors = true,
675 "--unproduced-catch-tags" => self.unproduced_catch_tags = true,
676 "--unused-server-actions" => self.unused_server_actions = true,
677 "--unused-load-data-keys" => self.unused_load_data_keys = true,
678 "--unresolved-imports" => self.unresolved_imports = true,
679 "--unlisted-deps" => self.unlisted_deps = true,
680 "--unlisted-binaries" => self.unlisted_binaries = true,
681 "--duplicate-exports" => self.duplicate_exports = true,
682 "--duplicate-export-aliases" => self.duplicate_export_aliases = true,
683 "--circular-deps" => self.circular_deps = true,
684 "--re-export-cycles" => self.re_export_cycles = true,
685 "--package-cycles" => self.package_cycles = true,
686 "--boundary-violations" => self.boundary_violations = true,
687 "--policy-violations" => self.policy_violations = true,
688 "--stale-suppressions" => self.stale_suppressions = true,
689 "--unused-catalog-entries" => self.unused_catalog_entries = true,
690 "--empty-catalog-groups" => self.empty_catalog_groups = true,
691 "--unresolved-catalog-references" => self.unresolved_catalog_references = true,
692 "--unused-dependency-overrides" => self.unused_dependency_overrides = true,
693 "--misconfigured-dependency-overrides" => {
694 self.misconfigured_dependency_overrides = true;
695 }
696 _ => unreachable!("registry emitted unsupported dead-code filter flag: {flag}"),
697 }
698 }
699}
700
701#[derive(Debug, Clone, Default)]
703pub struct DeadCodeOptions {
704 pub analysis: AnalysisOptions,
706 pub filters: DeadCodeFilters,
708 pub files: Vec<PathBuf>,
710 pub include_entry_exports: bool,
712 pub show_cascade: bool,
714 pub finding_ids: Vec<String>,
719}
720
721#[derive(Debug, Clone, Default)]
727pub struct ArchitectureOptions {
728 pub shared_state: bool,
730 pub analysis: AnalysisOptions,
732 pub files: Vec<PathBuf>,
734 pub cycles: bool,
737 pub boundaries: bool,
739 pub policy: bool,
741}
742
743impl ArchitectureOptions {
744 #[must_use]
746 pub fn dead_code_filters(&self) -> DeadCodeFilters {
747 let all = !(self.cycles || self.boundaries || self.policy || self.shared_state);
748 DeadCodeFilters {
749 shared_state: self.shared_state,
750 circular_deps: self.cycles || all,
751 re_export_cycles: self.cycles || all,
752 package_cycles: self.cycles || all,
753 boundary_violations: self.boundaries || all,
754 policy_violations: self.policy || all,
755 ..DeadCodeFilters::default()
756 }
757 }
758
759 pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
762 fallow_engine::requested_rule_off::architecture_requested_flags(
763 self.cycles,
764 self.boundaries,
765 self.policy,
766 )
767 }
768
769 #[must_use]
771 pub fn dead_code_options(&self) -> DeadCodeOptions {
772 DeadCodeOptions {
773 analysis: self.analysis.clone(),
774 filters: self.dead_code_filters(),
775 files: self.files.clone(),
776 include_entry_exports: false,
777 show_cascade: false,
778 finding_ids: Vec::new(),
779 }
780 }
781}
782
783#[derive(Debug, Clone, Default)]
785pub struct AuditOptions {
786 pub analysis: AnalysisOptions,
788 pub base: Option<String>,
791 pub production: bool,
793 pub production_dead_code: Option<bool>,
795 pub production_health: Option<bool>,
797 pub production_dupes: Option<bool>,
800 pub dead_code: Option<bool>,
804 pub health: Option<bool>,
807 pub duplication: Option<bool>,
810 pub css: Option<bool>,
813 pub css_deep: Option<bool>,
816 pub gate: Option<fallow_config::AuditGate>,
819 pub worsened: Option<fallow_config::AuditWorsened>,
822 pub max_crap: Option<f64>,
824 pub coverage: Option<PathBuf>,
826 pub coverage_root: Option<PathBuf>,
828 pub include_entry_exports: bool,
830 pub show_cascade: bool,
832 pub runtime_coverage: Option<PathBuf>,
834 pub min_invocations_hot: u64,
836}
837
838#[derive(Debug, Clone)]
840pub struct CombinedOptions {
841 pub analysis: AnalysisOptions,
843 pub production_dead_code: Option<bool>,
847 pub production_health: Option<bool>,
849 pub production_dupes: Option<bool>,
852 pub dead_code: bool,
854 pub duplication: bool,
856 pub health: bool,
858 pub include_entry_exports: bool,
860 pub show_cascade: bool,
862 pub duplication_options: DuplicationOptions,
864 pub health_options: ComplexityOptions,
866}
867
868impl Default for CombinedOptions {
869 fn default() -> Self {
870 Self {
871 analysis: AnalysisOptions::default(),
872 production_dead_code: None,
873 production_health: None,
874 production_dupes: None,
875 dead_code: true,
876 duplication: true,
877 health: true,
878 include_entry_exports: false,
879 show_cascade: false,
880 duplication_options: DuplicationOptions::default(),
881 health_options: ComplexityOptions::default(),
882 }
883 }
884}
885
886#[derive(Debug, Clone, Default)]
888pub struct DecisionSurfaceOptions {
889 pub analysis: AnalysisOptions,
891 pub base: Option<String>,
894 pub max_decisions: Option<usize>,
896}
897
898#[derive(Debug, Clone, Default)]
900pub struct FeatureFlagsOptions {
901 pub analysis: AnalysisOptions,
903 pub top: Option<usize>,
906 pub retirement: Option<FeatureFlagsRetirementOptions>,
908}
909
910#[derive(Debug, Clone, Default)]
913pub struct FeatureFlagsRetirementOptions {
914 pub flag_age: fallow_types::flag_retirement::FlagAgeMode,
916 pub flag_state: Option<std::path::PathBuf>,
918 pub reasons: Vec<fallow_types::flag_retirement::RetirementReason>,
920 pub sort: fallow_engine::flag_retirement::RetirementSort,
922 pub min_age_days: Option<u64>,
924 pub max_flag_age: Option<u64>,
926}
927
928#[derive(Debug, Clone, Copy, Default)]
930pub enum DuplicationMode {
931 Strict,
934 #[default]
936 Mild,
937 Weak,
939 Semantic,
942}
943
944#[derive(Debug, Clone, Default)]
946pub struct DuplicationOptions {
947 pub analysis: AnalysisOptions,
949 pub mode: Option<DuplicationMode>,
951 pub near: Option<bool>,
954 pub min_tokens: Option<usize>,
956 pub min_lines: Option<usize>,
958 pub min_occurrences: Option<usize>,
961 pub threshold: Option<f64>,
964 pub skip_local: Option<bool>,
967 pub ignore_symlinks: Option<bool>,
970 pub cross_language: Option<bool>,
972 pub ignore_imports: Option<bool>,
975 pub top: Option<usize>,
977 pub include_fragments: Option<bool>,
981}
982
983#[derive(Debug, Clone, Default)]
985pub struct SimilarCodeOptions {
986 pub analysis: AnalysisOptions,
988 pub threshold: Option<f64>,
990 pub min_lines: Option<usize>,
993 pub top: Option<usize>,
995 pub files: Vec<PathBuf>,
999 #[doc(hidden)]
1004 pub adapter_provider_path: Option<PathBuf>,
1005}
1006
1007#[derive(Debug, Clone)]
1009pub struct SimilarCodeInspectOptions {
1010 pub analysis: AnalysisOptions,
1013 pub snapshot: fallow_output::SimilarCodeCandidateSnapshot,
1015}
1016
1017#[derive(Debug, Clone, Default)]
1019pub struct TraceExportOptions {
1020 pub analysis: AnalysisOptions,
1022 pub file: String,
1024 pub export_name: String,
1026}
1027
1028#[derive(Debug, Clone, Default)]
1030pub struct TraceFileOptions {
1031 pub analysis: AnalysisOptions,
1033 pub file: String,
1035}
1036
1037#[derive(Debug, Clone, Default)]
1039pub struct TraceImportPathOptions {
1040 pub analysis: AnalysisOptions,
1042 pub from: String,
1044 pub to: String,
1046 pub eager_only: bool,
1049}
1050
1051#[derive(Debug, Clone, Default)]
1053pub struct TraceErrorOptions {
1054 pub analysis: AnalysisOptions,
1056 pub trace: String,
1058 pub source: String,
1060}
1061
1062#[derive(Debug, Clone, Default)]
1064pub struct TraceDependencyOptions {
1065 pub analysis: AnalysisOptions,
1067 pub package_name: String,
1069 pub usage: Option<DependencyUsageQuery>,
1072}
1073
1074#[derive(Debug, Clone, PartialEq, Eq)]
1076pub enum TraceCloneTarget {
1077 Location {
1079 file: String,
1081 line: usize,
1083 },
1084 Fingerprint(String),
1086}
1087
1088#[derive(Debug, Clone)]
1090pub struct TraceCloneOptions {
1091 pub duplication: DuplicationOptions,
1093 pub target: TraceCloneTarget,
1095}
1096
1097#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1099pub enum ComplexitySort {
1100 #[default]
1102 Cyclomatic,
1103 Cognitive,
1105 Lines,
1107 Severity,
1109}
1110
1111#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1113pub enum OwnershipEmailMode {
1114 Raw,
1116 #[default]
1118 Handle,
1119 Anonymized,
1121 Hash,
1123}
1124
1125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1127pub enum TargetEffort {
1128 Low,
1130 Medium,
1132 High,
1134}
1135
1136#[derive(Debug, Clone, Default)]
1138pub struct ComplexityOptions {
1139 pub analysis: AnalysisOptions,
1141 pub max_cyclomatic: Option<u16>,
1143 pub max_cognitive: Option<u16>,
1145 pub max_crap: Option<f64>,
1147 pub max_file_lines: Option<u32>,
1150 pub top: Option<usize>,
1152 pub sort: ComplexitySort,
1154 pub complexity_breakdown: bool,
1156 pub complexity: bool,
1158 pub file_scores: bool,
1160 pub coverage_gaps: bool,
1162 pub config_activates_coverage_gaps: bool,
1167 pub hotspots: bool,
1169 pub ownership: bool,
1171 pub ownership_emails: Option<OwnershipEmailMode>,
1173 pub targets: bool,
1175 pub css: bool,
1177 pub css_deep: bool,
1179 pub effort: Option<TargetEffort>,
1182 pub score: bool,
1184 pub since: Option<String>,
1186 pub min_commits: Option<u32>,
1188 pub coverage: Option<PathBuf>,
1190 pub coverage_root: Option<PathBuf>,
1192 pub coverage_relocated: bool,
1197}
1198
1199#[derive(Debug, Clone, Copy, Default, PartialEq)]
1201pub struct ComplexityThresholdOverrides {
1202 pub max_cyclomatic: Option<u16>,
1204 pub max_cognitive: Option<u16>,
1206 pub max_crap: Option<f64>,
1208 pub max_file_lines: Option<u32>,
1210}
1211
1212#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1214pub struct ComplexityCoverageInputs<'a> {
1215 pub coverage: Option<&'a Path>,
1217 pub coverage_root: Option<&'a Path>,
1219 pub coverage_relocated: bool,
1222}
1223
1224#[derive(Debug, Clone)]
1226pub struct HealthSectionOptions {
1227 pub output: fallow_types::output_format::OutputFormat,
1229 pub complexity: bool,
1231 pub file_scores: bool,
1233 pub coverage_gaps: bool,
1235 pub hotspots: bool,
1237 pub targets: bool,
1239 pub css: bool,
1241 pub score: bool,
1243 pub score_gate: bool,
1245 pub snapshot_requested: bool,
1247 pub trend: bool,
1249}
1250
1251#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1253pub struct DerivedHealthSections {
1254 pub any_section: bool,
1256 pub complexity: bool,
1258 pub file_scores: bool,
1260 pub coverage_gaps: bool,
1262 pub hotspots: bool,
1264 pub targets: bool,
1266 pub css: bool,
1268 pub score: bool,
1270 pub force_full: bool,
1272 pub score_only_output: bool,
1274}
1275
1276#[derive(Debug, Clone)]
1278pub struct ComplexitySectionOptions {
1279 pub complexity: bool,
1281 pub file_scores: bool,
1283 pub coverage_gaps: bool,
1285 pub hotspots: bool,
1287 pub ownership: bool,
1289 pub targets: bool,
1291 pub css: bool,
1293 pub score: bool,
1295}
1296
1297#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1299pub struct DerivedComplexityOptions {
1300 pub any_section: bool,
1302 pub complexity: bool,
1304 pub file_scores: bool,
1306 pub coverage_gaps: bool,
1308 pub hotspots: bool,
1310 pub ownership: bool,
1312 pub targets: bool,
1314 pub force_full: bool,
1316 pub score_only_output: bool,
1318 pub score: bool,
1320}
1321
1322#[derive(Debug, Clone, PartialEq)]
1324pub struct ComplexityRunOptions<'a> {
1325 pub thresholds: ComplexityThresholdOverrides,
1327 pub top: Option<usize>,
1329 pub sort: ComplexitySort,
1331 pub complexity_breakdown: bool,
1333 pub sections: DerivedComplexityOptions,
1335 pub ownership_emails: Option<OwnershipEmailMode>,
1337 pub effort: Option<TargetEffort>,
1339 pub css: bool,
1341 pub css_deep: bool,
1343 pub since: Option<&'a str>,
1345 pub min_commits: Option<u32>,
1347 pub coverage_inputs: ComplexityCoverageInputs<'a>,
1349}
1350
1351pub fn configure_global_analysis_pool(threads: usize) -> bool {
1360 fallow_engine::thread_pool::worker_pool_builder(threads)
1361 .build_global()
1362 .is_ok()
1363}
1364
1365#[must_use]
1367pub fn derive_health_sections(options: &HealthSectionOptions) -> DerivedHealthSections {
1368 let score = options.score
1369 || options.score_gate
1370 || options.trend
1371 || matches!(
1372 options.output,
1373 fallow_types::output_format::OutputFormat::Badge
1374 );
1375 let any_section = options.complexity
1376 || options.file_scores
1377 || options.coverage_gaps
1378 || options.hotspots
1379 || options.targets
1380 || score;
1381 let effective_score = if any_section { score } else { true } || options.snapshot_requested;
1382 let force_full = options.snapshot_requested || effective_score;
1383
1384 DerivedHealthSections {
1385 any_section,
1386 complexity: if any_section {
1387 options.complexity
1388 } else {
1389 true
1390 },
1391 file_scores: if any_section {
1392 options.file_scores
1393 } else {
1394 true
1395 } || force_full,
1396 coverage_gaps: if any_section {
1397 options.coverage_gaps
1398 } else {
1399 false
1400 },
1401 hotspots: if any_section { options.hotspots } else { true }
1402 || options.snapshot_requested
1403 || options.trend,
1404 targets: if any_section { options.targets } else { true },
1405 css: options.css,
1406 score: effective_score,
1407 force_full,
1408 score_only_output: is_health_score_only_output(options, score),
1409 }
1410}
1411
1412#[must_use]
1414pub fn derive_complexity_sections(options: &ComplexitySectionOptions) -> DerivedComplexityOptions {
1415 let requested_hotspots = options.hotspots || options.ownership;
1416 let sections = derive_health_sections(&HealthSectionOptions {
1417 output: fallow_types::output_format::OutputFormat::Human,
1418 complexity: options.complexity,
1419 file_scores: options.file_scores,
1420 coverage_gaps: options.coverage_gaps,
1421 hotspots: requested_hotspots,
1422 targets: options.targets,
1423 css: options.css,
1424 score: options.score,
1425 score_gate: false,
1426 snapshot_requested: false,
1427 trend: false,
1428 });
1429
1430 DerivedComplexityOptions {
1431 any_section: sections.any_section,
1432 complexity: sections.complexity,
1433 file_scores: sections.file_scores,
1434 coverage_gaps: sections.coverage_gaps,
1435 hotspots: sections.hotspots,
1436 ownership: options.ownership && sections.hotspots,
1437 targets: sections.targets,
1438 force_full: sections.force_full,
1439 score_only_output: sections.score_only_output,
1440 score: sections.score,
1441 }
1442}
1443
1444#[must_use]
1446pub fn derive_complexity_options(options: &ComplexityOptions) -> DerivedComplexityOptions {
1447 derive_complexity_sections(&complexity_section_options(options))
1448}
1449
1450#[must_use]
1452pub fn derive_complexity_run_options(options: &ComplexityOptions) -> ComplexityRunOptions<'_> {
1453 ComplexityRunOptions {
1454 thresholds: ComplexityThresholdOverrides {
1455 max_cyclomatic: options.max_cyclomatic,
1456 max_cognitive: options.max_cognitive,
1457 max_crap: options.max_crap,
1458 max_file_lines: options.max_file_lines,
1459 },
1460 top: options.top,
1461 sort: options.sort,
1462 complexity_breakdown: options.complexity_breakdown,
1463 sections: derive_complexity_options(options),
1464 ownership_emails: options.ownership_emails,
1465 effort: options.effort,
1466 css: options.css,
1467 css_deep: options.css_deep,
1468 since: options.since.as_deref(),
1469 min_commits: options.min_commits,
1470 coverage_inputs: ComplexityCoverageInputs {
1471 coverage: options.coverage.as_deref(),
1472 coverage_root: options.coverage_root.as_deref(),
1473 coverage_relocated: options.coverage_relocated,
1474 },
1475 }
1476}
1477
1478pub fn validate_complexity_options(options: &ComplexityOptions) -> Result<(), ProgrammaticError> {
1501 if let Some(path) = &options.coverage {
1502 let resolved = fallow_engine::health::scoring::resolve_relative_to_root(
1503 path,
1504 options.analysis.root.as_deref(),
1505 );
1506 if !resolved.exists() {
1507 return Err(ProgrammaticError::new(
1508 format!("coverage path does not exist: {}", resolved.display()),
1509 2,
1510 )
1511 .with_code("FALLOW_INVALID_COVERAGE_PATH")
1512 .with_context("health.coverage"));
1513 }
1514 }
1515 if let Err(message) =
1516 fallow_engine::health::validate_coverage_root_absolute(options.coverage_root.as_deref())
1517 {
1518 return Err(ProgrammaticError::new(message, 2)
1519 .with_code("FALLOW_INVALID_COVERAGE_ROOT")
1520 .with_context("health.coverage_root"));
1521 }
1522
1523 Ok(())
1524}
1525
1526fn complexity_section_options(options: &ComplexityOptions) -> ComplexitySectionOptions {
1527 let ownership = options.ownership || options.ownership_emails.is_some();
1528 let requested_targets = options.targets || options.effort.is_some();
1529 ComplexitySectionOptions {
1530 complexity: options.complexity,
1531 file_scores: options.file_scores,
1532 coverage_gaps: options.coverage_gaps,
1533 hotspots: options.hotspots,
1534 ownership,
1535 targets: requested_targets,
1536 css: options.css,
1537 score: options.score,
1538 }
1539}
1540
1541fn is_health_score_only_output(options: &HealthSectionOptions, score: bool) -> bool {
1542 score
1543 && !options.complexity
1544 && !options.file_scores
1545 && !options.coverage_gaps
1546 && !options.hotspots
1547 && !options.targets
1548 && !options.trend
1549}
1550
1551const fn thresholds_to_engine(
1552 thresholds: ComplexityThresholdOverrides,
1553) -> fallow_engine::health::HealthThresholdOverrides {
1554 fallow_engine::health::HealthThresholdOverrides {
1555 max_cyclomatic: thresholds.max_cyclomatic,
1556 max_cognitive: thresholds.max_cognitive,
1557 max_crap: thresholds.max_crap,
1558 max_file_lines: thresholds.max_file_lines,
1559 }
1560}
1561
1562const fn complexity_sort_to_engine(sort: ComplexitySort) -> fallow_engine::health::HealthSort {
1563 match sort {
1564 ComplexitySort::Severity => fallow_engine::health::HealthSort::Severity,
1565 ComplexitySort::Cyclomatic => fallow_engine::health::HealthSort::Cyclomatic,
1566 ComplexitySort::Cognitive => fallow_engine::health::HealthSort::Cognitive,
1567 ComplexitySort::Lines => fallow_engine::health::HealthSort::Lines,
1568 }
1569}
1570
1571const fn coverage_inputs_to_engine(
1572 coverage_inputs: ComplexityCoverageInputs<'_>,
1573) -> fallow_engine::health::HealthCoverageInputs<'_> {
1574 fallow_engine::health::HealthCoverageInputs {
1575 coverage: coverage_inputs.coverage,
1576 coverage_root: coverage_inputs.coverage_root,
1577 coverage_relocated: coverage_inputs.coverage_relocated,
1578 }
1579}
1580
1581const fn ownership_email_mode_to_config(mode: OwnershipEmailMode) -> EmailMode {
1582 match mode {
1583 OwnershipEmailMode::Raw => EmailMode::Raw,
1584 OwnershipEmailMode::Handle => EmailMode::Handle,
1585 OwnershipEmailMode::Anonymized => EmailMode::Anonymized,
1586 OwnershipEmailMode::Hash => EmailMode::Hash,
1587 }
1588}
1589
1590const fn target_effort_to_output(effort: TargetEffort) -> EffortEstimate {
1591 match effort {
1592 TargetEffort::Low => EffortEstimate::Low,
1593 TargetEffort::Medium => EffortEstimate::Medium,
1594 TargetEffort::High => EffortEstimate::High,
1595 }
1596}
1597
1598#[cfg(test)]
1599mod tests {
1600 use super::*;
1601
1602 #[test]
1603 fn duplication_defaults_match_cli_contract() {
1604 let options = DuplicationOptions::default();
1605 assert!(options.mode.is_none());
1606 assert!(options.min_tokens.is_none());
1607 assert!(options.min_lines.is_none());
1608 assert!(options.min_occurrences.is_none());
1609 }
1610
1611 #[test]
1612 fn programmatic_error_builder_keeps_optional_fields() {
1613 let error = ProgrammaticError::new("boom", 2)
1614 .with_code("FALLOW_TEST")
1615 .with_help("Try again")
1616 .with_context("analysis.root");
1617
1618 assert_eq!(error.message, "boom");
1619 assert_eq!(error.exit_code, 2);
1620 assert_eq!(error.code.as_deref(), Some("FALLOW_TEST"));
1621 assert_eq!(error.help.as_deref(), Some("Try again"));
1622 assert_eq!(error.context.as_deref(), Some("analysis.root"));
1623 }
1624
1625 #[test]
1626 fn dead_code_filters_accept_shared_registry_selectors() {
1627 for (selector, _) in fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS.iter() {
1628 let mut filters = DeadCodeFilters::default();
1629 assert!(
1630 filters.enable_registry_selector(selector),
1631 "{selector} should be accepted"
1632 );
1633 }
1634
1635 let mut filters = DeadCodeFilters::default();
1636 assert!(filters.enable_registry_selector("unused-files"));
1637 assert!(filters.unused_files);
1638 assert!(filters.enable_registry_selector("boundary-violations"));
1639 assert!(filters.boundary_violations);
1640 assert!(!filters.enable_registry_selector("not-a-real-selector"));
1641 }
1642
1643 #[test]
1644 fn default_complexity_options_match_programmatic_health_defaults() {
1645 let derived = derive_complexity_options(&ComplexityOptions::default());
1646
1647 assert!(!derived.any_section);
1648 assert!(derived.complexity);
1649 assert!(derived.file_scores);
1650 assert!(!derived.coverage_gaps);
1651 assert!(derived.hotspots);
1652 assert!(!derived.ownership);
1653 assert!(derived.targets);
1654 assert!(derived.force_full);
1655 assert!(!derived.score_only_output);
1656 assert!(derived.score);
1657 }
1658
1659 #[test]
1660 fn score_only_complexity_options_request_score_only_output() {
1661 let derived = derive_complexity_options(&ComplexityOptions {
1662 score: true,
1663 ..ComplexityOptions::default()
1664 });
1665
1666 assert!(derived.any_section);
1667 assert!(!derived.complexity);
1668 assert!(derived.file_scores);
1669 assert!(!derived.hotspots);
1670 assert!(!derived.targets);
1671 assert!(derived.force_full);
1672 assert!(derived.score_only_output);
1673 assert!(derived.score);
1674 }
1675
1676 #[test]
1677 fn ownership_implies_hotspots_when_requested() {
1678 let derived = derive_complexity_options(&ComplexityOptions {
1679 ownership: true,
1680 ..ComplexityOptions::default()
1681 });
1682
1683 assert!(derived.any_section);
1684 assert!(derived.hotspots);
1685 assert!(derived.ownership);
1686 assert!(!derived.targets);
1687 }
1688
1689 #[test]
1690 fn complexity_run_options_normalize_public_api_options() {
1691 let options = ComplexityOptions {
1692 max_cyclomatic: Some(42),
1693 max_cognitive: Some(21),
1694 max_crap: Some(18.5),
1695 top: Some(7),
1696 sort: ComplexitySort::Severity,
1697 complexity_breakdown: true,
1698 ownership_emails: Some(OwnershipEmailMode::Hash),
1699 effort: Some(TargetEffort::High),
1700 coverage: Some(PathBuf::from("coverage/coverage-final.json")),
1701 coverage_root: Some(PathBuf::from("/ci/workspace")),
1702 since: Some("30d".to_string()),
1703 min_commits: Some(4),
1704 ..ComplexityOptions::default()
1705 };
1706
1707 let run = derive_complexity_run_options(&options);
1708
1709 assert_eq!(run.thresholds.max_cyclomatic, Some(42));
1710 assert_eq!(run.thresholds.max_cognitive, Some(21));
1711 assert_eq!(run.thresholds.max_crap, Some(18.5));
1712 assert_eq!(run.top, Some(7));
1713 assert!(matches!(run.sort, ComplexitySort::Severity));
1714 assert!(run.complexity_breakdown);
1715 assert!(run.sections.hotspots);
1716 assert!(run.sections.ownership);
1717 assert!(run.sections.targets);
1718 assert!(matches!(
1719 run.ownership_emails,
1720 Some(OwnershipEmailMode::Hash)
1721 ));
1722 assert!(matches!(run.effort, Some(TargetEffort::High)));
1723 assert_eq!(run.since, Some("30d"));
1724 assert_eq!(run.min_commits, Some(4));
1725 assert_eq!(run.coverage_inputs.coverage, options.coverage.as_deref());
1726 assert_eq!(
1727 run.coverage_inputs.coverage_root,
1728 options.coverage_root.as_deref()
1729 );
1730 }
1731
1732 #[test]
1733 fn complexity_options_validation_accepts_existing_coverage_path_and_absolute_root() {
1734 let dir = tempfile::tempdir().expect("tempdir");
1735 let coverage = dir.path().join("coverage-final.json");
1736 std::fs::write(&coverage, "{}").expect("coverage fixture");
1737
1738 let result = validate_complexity_options(&ComplexityOptions {
1739 coverage: Some(coverage),
1740 coverage_root: Some(PathBuf::from("/ci/workspace")),
1741 ..ComplexityOptions::default()
1742 });
1743
1744 assert!(result.is_ok());
1745 }
1746
1747 #[test]
1748 fn complexity_options_validation_keeps_missing_coverage_error_contract() {
1749 let err = validate_complexity_options(&ComplexityOptions {
1750 coverage: Some(PathBuf::from("/missing/coverage-final.json")),
1751 ..ComplexityOptions::default()
1752 })
1753 .expect_err("missing coverage path should fail");
1754
1755 assert_eq!(err.exit_code, 2);
1756 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1757 assert_eq!(err.context.as_deref(), Some("health.coverage"));
1758 }
1759
1760 #[test]
1761 fn complexity_options_validation_keeps_relative_coverage_root_error_contract() {
1762 let err = validate_complexity_options(&ComplexityOptions {
1763 coverage_root: Some(PathBuf::from("coverage")),
1764 ..ComplexityOptions::default()
1765 })
1766 .expect_err("relative coverage root should fail");
1767
1768 assert_eq!(err.exit_code, 2);
1769 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_ROOT"));
1770 assert_eq!(err.context.as_deref(), Some("health.coverage_root"));
1771 }
1772
1773 #[test]
1777 fn complexity_options_validation_resolves_relative_coverage_against_root() {
1778 let dir = tempfile::tempdir().expect("tempdir");
1779 std::fs::create_dir_all(dir.path().join("artifacts")).expect("artifacts dir");
1780 std::fs::write(dir.path().join("artifacts/coverage-final.json"), "{}")
1781 .expect("coverage fixture");
1782 let relative = PathBuf::from("artifacts/coverage-final.json");
1783 assert!(
1784 !relative.exists(),
1785 "the fixture must not also exist under the test cwd"
1786 );
1787
1788 let result = validate_complexity_options(&ComplexityOptions {
1789 analysis: AnalysisOptions {
1790 root: Some(dir.path().to_path_buf()),
1791 ..AnalysisOptions::default()
1792 },
1793 coverage: Some(relative.clone()),
1794 ..ComplexityOptions::default()
1795 });
1796 assert!(result.is_ok(), "{result:?}");
1797
1798 let err = validate_complexity_options(&ComplexityOptions {
1799 analysis: AnalysisOptions {
1800 root: Some(dir.path().join("elsewhere")),
1801 ..AnalysisOptions::default()
1802 },
1803 coverage: Some(relative),
1804 ..ComplexityOptions::default()
1805 })
1806 .expect_err("the path does not exist under the other root");
1807 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1808 assert!(
1809 err.message.contains("elsewhere"),
1810 "the message names the resolved path: {}",
1811 err.message
1812 );
1813 }
1814
1815 #[test]
1816 fn default_health_sections_match_full_health_output() {
1817 let derived = derive_health_sections(&HealthSectionOptions {
1818 output: fallow_types::output_format::OutputFormat::Human,
1819 complexity: false,
1820 file_scores: false,
1821 coverage_gaps: false,
1822 hotspots: false,
1823 targets: false,
1824 css: false,
1825 score: false,
1826 score_gate: false,
1827 snapshot_requested: false,
1828 trend: false,
1829 });
1830
1831 assert!(!derived.any_section);
1832 assert!(derived.complexity);
1833 assert!(derived.file_scores);
1834 assert!(!derived.coverage_gaps);
1835 assert!(derived.hotspots);
1836 assert!(derived.targets);
1837 assert!(derived.score);
1838 assert!(derived.force_full);
1839 assert!(!derived.score_only_output);
1840 }
1841
1842 #[test]
1843 fn health_score_gate_requests_score_only_output() {
1844 let derived = derive_health_sections(&HealthSectionOptions {
1845 output: fallow_types::output_format::OutputFormat::Human,
1846 complexity: false,
1847 file_scores: false,
1848 coverage_gaps: false,
1849 hotspots: false,
1850 targets: false,
1851 css: false,
1852 score: false,
1853 score_gate: true,
1854 snapshot_requested: false,
1855 trend: false,
1856 });
1857
1858 assert!(derived.any_section);
1859 assert!(!derived.complexity);
1860 assert!(derived.file_scores);
1861 assert!(!derived.hotspots);
1862 assert!(!derived.targets);
1863 assert!(derived.score);
1864 assert!(derived.force_full);
1865 assert!(derived.score_only_output);
1866 }
1867
1868 #[test]
1869 fn health_snapshot_keeps_full_hidden_inputs_without_section_request() {
1870 let derived = derive_health_sections(&HealthSectionOptions {
1871 output: fallow_types::output_format::OutputFormat::Human,
1872 complexity: false,
1873 file_scores: false,
1874 coverage_gaps: false,
1875 hotspots: false,
1876 targets: false,
1877 css: true,
1878 score: false,
1879 score_gate: false,
1880 snapshot_requested: true,
1881 trend: false,
1882 });
1883
1884 assert!(!derived.any_section);
1885 assert!(derived.css);
1886 assert!(derived.file_scores);
1887 assert!(derived.hotspots);
1888 assert!(derived.score);
1889 assert!(derived.force_full);
1890 }
1891}
1892
1893mod shared_state_explain;