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;
38pub mod audit_output;
39pub mod audit_run;
40pub mod combined_output;
41pub mod compact_output;
44mod companion_install;
45pub mod coverage;
46pub mod dead_code_codeclimate;
47pub mod dead_code_sarif;
48pub mod decision_surface;
49pub mod dependency_deltas;
50pub mod diff_risk;
51pub mod doctor;
52pub mod dupes_output;
53pub mod editor;
54pub mod explain;
55pub mod grouped_output;
56pub mod health_codeclimate;
57mod health_groups_markdown;
58pub mod json_output;
59pub mod list_output;
60mod list_runtime;
61pub mod markdown_output;
64pub mod mutation;
65mod next_steps;
66pub mod output_contracts;
67pub mod ownership;
68pub mod review_deltas;
69pub mod routing;
70pub mod runtime;
71mod runtime_json;
72mod runtime_output;
73pub mod sarif_output;
74pub mod schemas;
77pub mod security_output;
78pub mod similar_code;
80mod type_aware;
81pub use analysis_context::{ProgrammaticAnalysisContext, resolve_programmatic_analysis_context};
82pub use audit_output::{
83 AuditAttribution, AuditCodeClimateOutputInput, AuditJsonHeaderInput, AuditJsonOutputInput,
84 AuditSarifOutputInput, AuditSummary, AuditVerdict, attach_audit_diff_risk_attribution,
85 attach_audit_duplication_demotion_attribution, attach_audit_styling_attribution,
86 attach_audit_wire_attribution, build_audit_codeclimate, build_audit_codeclimate_issues,
87 build_audit_header_json, build_audit_header_map, build_audit_sarif,
88 build_diff_risk_codeclimate, build_review_brief_header, serialize_audit_json,
89};
90pub use combined_output::{
91 CombinedCheckJsonSection, CombinedJsonOutputInput, serialize_combined_dupes_json,
92 serialize_combined_health_json, serialize_combined_json,
93};
94pub use compact_output::{
95 build_compact_lines, build_diff_risk_compact_lines, build_duplication_compact_lines,
96 build_grouped_compact_lines, build_health_compact_lines,
97};
98pub use coverage::{
99 CoverageInputError, CoverageInputSource, CoverageInputs, resolve_coverage_inputs,
100};
101pub use dead_code_codeclimate::build_codeclimate;
102pub use dead_code_sarif::build_sarif;
103pub use doctor::{DoctorOptions, run_doctor, run_doctor_with_cache_dir};
104pub use dupes_output::{
105 AttributedCloneGroup, AttributedCloneGroupFinding, AttributedInstance, CloneDemotionReason,
106 CloneFamilyFinding, CloneGroupFinding, CombinedDupesSection, DupesReportPayload,
107 DuplicationGroup, DuplicationGrouping, build_duplication_codeclimate,
108 set_duplication_audit_attribution,
109};
110pub use editor::{
111 ChangedFilesError, EditorAnalysisOutput, EditorAnalysisResults, EditorAnalysisSession,
112 EditorCloneFamily, EditorCloneFingerprintSet, EditorCloneGroup, EditorCloneInstance,
113 EditorDeadCodeAnalysisOutput, EditorDuplicationReport, EditorDuplicationStats,
114 EditorInlineComplexityExceeded, EditorInlineComplexityFinding, EditorMirroredDirectory,
115 EditorProjectAnalysisOutput, EditorRefactoringKind, EditorRefactoringSuggestion,
116 EditorSessionParseCounts, collect_inline_complexity, editor_duplicates, editor_extract,
117 editor_results, editor_security, editor_suppress, filter_inline_complexity_by_change_scope,
118 filter_inline_complexity_by_changed_files, resolve_git_toplevel,
119 try_get_changed_files_with_toplevel,
120};
121pub use explain::{
122 AUDIT_RULES, CHECK_RULES, DUPES_RULES, FLAGS_RULES, HEALTH_RULES, MUTATION_RULES, RuleDef,
123 RuleGuide, SECURITY_RULES, all_rules, bare_rule_id, coverage_analyze_meta, coverage_setup_meta,
124 explain_issue_type, rule_by_id, rule_by_token, rule_command, rule_docs_url, rule_guide,
125 rule_severity_key, security_meta, serialize_explain_programmatic_json, unknown_explain_error,
126};
127pub use fallow_config::levenshtein::closest_match;
128pub use fallow_config::{AuditGate, AuditWorsened, HealthConfig, TypeAwareRequire};
129pub use fallow_engine::change_scope::{
132 ChangeScope, ChangeScopeOwner, ChangeScopeRequest, first_package_baselines,
133 package_baseline_statuses,
134};
135pub use fallow_engine::package_baselines::{PackageBaselineError, PackageChangeScope};
137pub use fallow_engine::thread_pool::{WORKER_STACK_SIZE, register_thread_stack};
144pub use fallow_engine::warm_parse;
150pub use fallow_output::PackageBaselineStatus;
152pub use fallow_output::serialize_similar_code_json_output;
153pub use fallow_types::trace::{
154 CloneTrace, DependencyTrace, ExportReference, ExportTrace, FileTrace, ReExportChain,
155 TracedCloneGroup, TracedExport, TracedReExport,
156};
157pub use fallow_types::trace_usage::{
158 DependencyUsage, DependencyUsageQuery, SitePageRequest, UsageQueryError,
159};
160pub use grouped_output::{
161 ResultGroup, UNOWNED_GROUP_LABEL, build_duplication_grouping_with, group_analysis_results_with,
162 health_signal_header_part, largest_clone_group_owner_with,
163};
164pub use health_codeclimate::build_health_codeclimate;
165pub use health_groups_markdown::build_health_groups_markdown;
166pub use json_output::{
167 CheckJsonExtraOutputs, CheckJsonOutputInput, CheckJsonPayloadInput, DuplicationJsonOutputInput,
168 GroupedCheckJsonOutputInput, GroupedDuplicationJsonOutputInput, serialize_check_json,
169 serialize_check_json_payload, serialize_duplication_json, serialize_grouped_check_json,
170 serialize_grouped_duplication_json,
171};
172pub use list_output::{
173 ListJsonEnvelope, ListJsonOutputInput, build_list_json_output, serialize_list_json_output,
174};
175pub use list_runtime::{
176 BoundaryData, ListBoundariesOptions, ListBoundariesProgrammaticOutput, LogicalGroupInfo,
177 ProjectInfoOptions, ProjectInfoProgrammaticOutput, RuleInfo, ZoneInfo, boundary_data_to_output,
178 compute_boundary_data, run_list_boundaries, run_project_info,
179 serialize_list_boundaries_programmatic_json, serialize_project_info_programmatic_json,
180};
181pub use markdown_output::{
182 ComplexityListing, build_diff_risk_markdown, build_duplication_markdown,
183 build_grouped_markdown, build_health_markdown, build_markdown, build_walkthrough_markdown,
184};
185pub use mutation::{
186 MutationProgress, MutationProgressSink, MutationReplayOptions, MutationRunOptions,
187 MutationRunScope, apply_mutation_verdicts, validate_mutation_verdicts,
188};
189pub use output_contracts::{
190 AuditOutput, BoundariesListLogicalGroup, BoundariesListRule, BoundariesListZone,
191 BoundariesListing, CombinedOutput, FallowOutput, ImpactOutput, ListBoundariesOutput,
192 ListEntryPointOutput, ListOutput, ListPluginOutput, ReviewBriefWireOutput, SecurityGate,
193 SecurityOutput, SecurityOutputConfig, SecuritySummaryOutput, SimilarCodeCandidateSnapshot,
194 SimilarCodeOutput, TraceOutput, WorkspacesOutput,
195};
196pub use runtime::TYPE_AWARE_CONFIG_UNSUPPORTED;
197pub use runtime::{
198 AUDIT_CONFIG_BASELINE_UNSUPPORTED, ArchitectureOutput, ArchitectureProgrammaticOutput,
199 AuditProgrammaticKeySnapshot, AuditProgrammaticOutput, BoundaryViolationsOutput,
200 BoundaryViolationsProgrammaticOutput, CircularDependenciesOutput,
201 CircularDependenciesProgrammaticOutput, CombinedProgrammaticOutput, DeadCodeOutput,
202 DeadCodeProgrammaticOutput, DecisionSurfaceProgrammaticOutput, DuplicationOutput,
203 DuplicationProgrammaticOutput, EngineHealthRunner, FeatureFlagsOutput,
204 FeatureFlagsProgrammaticOutput, HealthJsonReportInput, HealthProgrammaticOutput,
205 ProgrammaticHealthAnalysis, ProgrammaticHealthNextStepFacts, ProgrammaticHealthRun,
206 ProgrammaticHealthRunner, TraceClassMemberOutput, TraceCloneBenchmarkResult, TraceCloneOutput,
207 TraceCloneProgrammaticOutput, TraceDependencyOutput, TraceDependencyProgrammaticOutput,
208 TraceErrorOutput, TraceErrorProgrammaticOutput, TraceExportOutput,
209 TraceExportProgrammaticOutput, TraceExportTargetOutput, TraceFileOutput,
210 TraceFileProgrammaticOutput, TraceImportPathOutput, TraceImportPathProgrammaticOutput,
211 benchmark_trace_clone_compact_json, benchmark_trace_graph_family_compact_json,
212 inspect_similar_code, load_health_config, parse_similar_code_candidate_snapshot, plan_mutation,
213 replay_mutation, review_similar_code, run_architecture, run_audit, run_boundary_violations,
214 run_circular_dependencies, run_combined, run_complexity_with_runner, run_dead_code,
215 run_dead_code_with_baseline, run_decision_surface, run_duplication, run_feature_flags,
216 run_health, run_health_with_runner, run_mutation, run_mutation_with_progress, run_similar_code,
217 run_trace_clone, run_trace_dependency, run_trace_error, run_trace_export, run_trace_file,
218 run_trace_import_path, select_similar_code_candidate_snapshot, serialize_health_report_json,
219};
220pub use runtime_json::{
221 serialize_architecture_programmatic_json, serialize_audit_programmatic_json,
222 serialize_boundary_violations_programmatic_json,
223 serialize_circular_dependencies_programmatic_json, serialize_combined_programmatic_json,
224 serialize_dead_code_programmatic_json, serialize_decision_surface_programmatic_json,
225 serialize_duplication_programmatic_json, serialize_feature_flags_programmatic_json,
226 serialize_health_programmatic_json, serialize_trace_clone_programmatic_json,
227 serialize_trace_dependency_programmatic_json, serialize_trace_error_programmatic_json,
228 serialize_trace_export_programmatic_json, serialize_trace_file_programmatic_json,
229 serialize_trace_import_path_programmatic_json,
230};
231pub use sarif_output::{
232 annotate_sarif_results, build_duplication_sarif, build_grouped_duplication_sarif,
233 build_health_sarif,
234};
235pub use security_output::SecurityGateMode;
236pub use type_aware::{
237 DEFAULT_BACKEND_FAMILY as DEFAULT_TYPE_AWARE_BACKEND_FAMILY, SemanticCouplingOutcome,
238 SemanticDeadCodeOutcome, SemanticInspectOutcome, TypeAwareError, TypeAwareFileChanges,
239 TypeAwareOutcome, TypeAwareSession, TypeAwareStatus, discard_unverified_semantic_candidates,
240 inspect_symbol as inspect_type_aware_symbol, merge_type_aware_meta,
241 refine_configured_dead_code_results as refine_type_aware_results_with_config,
242 shutdown_type_aware_sidecars, status as type_aware_status,
243 symbol_impact as run_type_aware_symbol_impact, symbol_impact as type_aware_symbol_impact,
244 terminate_active_type_aware_sidecars, trace_symbol as run_type_aware_symbol_trace,
245 trace_symbol as trace_type_aware_symbol, type_coupling as analyze_type_coupling,
246};
247
248pub const COMMON_ANALYSIS_OPTION_FLAGS: &[&str] = &[
255 "root",
256 "config",
257 "no-cache",
258 "threads",
259 "changed-since",
260 "diff-file",
261 "production",
262 "workspace",
263 "changed-workspaces",
264 "explain",
265 "allow-remote-extends",
266];
267
268#[derive(Debug, Clone, Serialize)]
270pub struct ProgrammaticError {
271 pub message: String,
273 pub exit_code: u8,
275 pub code: Option<String>,
277 pub help: Option<String>,
279 pub context: Option<String>,
281}
282
283impl ProgrammaticError {
284 #[must_use]
287 pub fn new(message: impl Into<String>, exit_code: u8) -> Self {
288 Self {
289 message: message.into(),
290 exit_code,
291 code: None,
292 help: None,
293 context: None,
294 }
295 }
296
297 #[must_use]
299 pub fn with_help(mut self, help: impl Into<String>) -> Self {
300 self.help = Some(help.into());
301 self
302 }
303
304 #[must_use]
307 pub fn with_code(mut self, code: impl Into<String>) -> Self {
308 self.code = Some(code.into());
309 self
310 }
311
312 #[must_use]
315 pub fn with_context(mut self, context: impl Into<String>) -> Self {
316 self.context = Some(context.into());
317 self
318 }
319}
320
321impl std::fmt::Display for ProgrammaticError {
322 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
323 write!(f, "{}", self.message)
324 }
325}
326
327impl std::error::Error for ProgrammaticError {}
328
329#[derive(Debug, Clone, Default)]
331pub struct AnalysisOptions {
332 pub root: Option<PathBuf>,
335 pub config_path: Option<PathBuf>,
337 pub allow_remote_extends: bool,
339 pub no_cache: bool,
341 pub threads: Option<usize>,
343 pub diff_file: Option<PathBuf>,
355 pub ambient_diff_file: Option<PathBuf>,
363 pub production: bool,
366 pub production_override: Option<bool>,
369 pub changed_since: Option<String>,
374 pub ambient_changed_since: Option<String>,
382 pub no_package_baselines: bool,
386 pub workspace: Option<Vec<String>>,
388 pub changed_workspaces: Option<String>,
390 pub explain: bool,
392 pub type_aware: TypeAwareOptions,
395 pub cancellation: Option<Arc<AtomicBool>>,
425}
426
427#[derive(Debug, Clone, Default, PartialEq, Eq)]
429pub struct TypeAwareOptions {
430 pub enabled: Option<bool>,
437 pub projects: Vec<PathBuf>,
440 pub require: fallow_config::TypeAwareRequire,
442}
443
444impl TypeAwareOptions {
445 #[must_use]
447 pub const fn requested(&self) -> bool {
448 matches!(self.enabled, Some(true))
449 }
450}
451
452#[derive(Debug, Clone, Default, PartialEq, Eq)]
457pub struct DeadCodeFilters {
458 pub shared_state: bool,
460 pub unused_files: bool,
462 pub unused_exports: bool,
464 pub unused_deps: bool,
466 pub unused_types: bool,
468 pub private_type_leaks: bool,
470 pub deprecated_exports_in_use: bool,
472 pub unused_enum_members: bool,
474 pub unused_class_members: bool,
476 pub unused_namespace_members: bool,
478 pub unused_store_members: bool,
480 pub unprovided_injects: bool,
482 pub unrendered_components: bool,
484 pub unused_component_props: bool,
486 pub absent_component_props: bool,
488 pub constant_parameters: bool,
490 pub unused_component_emits: bool,
492 pub unused_component_inputs: bool,
494 pub unused_component_outputs: bool,
496 pub unused_svelte_events: bool,
498 pub unused_effect_layers: bool,
500 pub unused_tagged_errors: bool,
502 pub unproduced_catch_tags: bool,
504 pub unused_server_actions: bool,
506 pub unused_load_data_keys: bool,
508 pub unresolved_imports: bool,
510 pub unlisted_deps: bool,
512 pub unlisted_binaries: bool,
514 pub duplicate_exports: bool,
516 pub duplicate_export_aliases: bool,
518 pub circular_deps: bool,
520 pub re_export_cycles: bool,
522 pub package_cycles: bool,
524 pub boundary_violations: bool,
526 pub policy_violations: bool,
528 pub stale_suppressions: bool,
530 pub unused_catalog_entries: bool,
532 pub empty_catalog_groups: bool,
534 pub unresolved_catalog_references: bool,
536 pub unused_dependency_overrides: bool,
538 pub misconfigured_dependency_overrides: bool,
540}
541
542impl DeadCodeFilters {
543 pub(crate) fn reports_dependency_findings(&self) -> bool {
547 !self.any_active() || self.unused_deps || self.unlisted_deps
548 }
549
550 fn any_active(&self) -> bool {
551 self.shared_state
552 || self.unused_files
553 || self.unused_exports
554 || self.unused_deps
555 || self.unused_types
556 || self.private_type_leaks
557 || self.deprecated_exports_in_use
558 || self.unused_enum_members
559 || self.unused_class_members
560 || self.unused_namespace_members
561 || self.unused_store_members
562 || self.unprovided_injects
563 || self.unrendered_components
564 || self.unused_component_props
565 || self.absent_component_props
566 || self.constant_parameters
567 || self.unused_component_emits
568 || self.unused_component_inputs
569 || self.unused_component_outputs
570 || self.unused_svelte_events
571 || self.unused_effect_layers
572 || self.unused_tagged_errors
573 || self.unproduced_catch_tags
574 || self.unused_server_actions
575 || self.unused_load_data_keys
576 || self.unresolved_imports
577 || self.unlisted_deps
578 || self.unlisted_binaries
579 || self.duplicate_exports
580 || self.duplicate_export_aliases
581 || self.circular_deps
582 || self.re_export_cycles
583 || self.package_cycles
584 || self.boundary_violations
585 || self.policy_violations
586 || self.stale_suppressions
587 || self.unused_catalog_entries
588 || self.empty_catalog_groups
589 || self.unresolved_catalog_references
590 || self.unused_dependency_overrides
591 || self.misconfigured_dependency_overrides
592 }
593
594 pub fn enable_registry_selector(&mut self, selector: &str) -> bool {
600 let Some(flag) = fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS
601 .iter()
602 .find_map(|&(name, flag)| (name == selector).then_some(flag))
603 else {
604 return false;
605 };
606 self.enable_cli_filter_flag(flag);
607 true
608 }
609
610 pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
612 fallow_engine::requested_rule_off::explicit_filter_flags(|flag| {
613 let mut enabled = self.clone();
614 enabled.enable_cli_filter_flag(flag);
615 enabled == *self
616 })
617 }
618
619 fn enable_cli_filter_flag(&mut self, flag: &str) {
620 match flag {
621 "--unused-files" => self.unused_files = true,
622 "--unused-exports" => self.unused_exports = true,
623 "--unused-types" => self.unused_types = true,
624 "--private-type-leaks" => self.private_type_leaks = true,
625 "--deprecated-exports-in-use" => self.deprecated_exports_in_use = true,
626 "--unused-deps" => self.unused_deps = true,
627 "--unused-enum-members" => self.unused_enum_members = true,
628 "--unused-class-members" => self.unused_class_members = true,
629 "--unused-namespace-members" => self.unused_namespace_members = true,
630 "--unused-store-members" => self.unused_store_members = true,
631 "--unprovided-injects" => self.unprovided_injects = true,
632 "--unrendered-components" => self.unrendered_components = true,
633 "--unused-component-props" => self.unused_component_props = true,
634 "--absent-component-props" => self.absent_component_props = true,
635 "--constant-parameters" => self.constant_parameters = true,
636 "--unused-component-emits" => self.unused_component_emits = true,
637 "--unused-component-inputs" => self.unused_component_inputs = true,
638 "--unused-component-outputs" => self.unused_component_outputs = true,
639 "--unused-svelte-events" => self.unused_svelte_events = true,
640 "--unused-effect-layers" => self.unused_effect_layers = true,
641 "--unused-tagged-errors" => self.unused_tagged_errors = true,
642 "--unproduced-catch-tags" => self.unproduced_catch_tags = true,
643 "--unused-server-actions" => self.unused_server_actions = true,
644 "--unused-load-data-keys" => self.unused_load_data_keys = true,
645 "--unresolved-imports" => self.unresolved_imports = true,
646 "--unlisted-deps" => self.unlisted_deps = true,
647 "--unlisted-binaries" => self.unlisted_binaries = true,
648 "--duplicate-exports" => self.duplicate_exports = true,
649 "--duplicate-export-aliases" => self.duplicate_export_aliases = true,
650 "--circular-deps" => self.circular_deps = true,
651 "--re-export-cycles" => self.re_export_cycles = true,
652 "--package-cycles" => self.package_cycles = true,
653 "--boundary-violations" => self.boundary_violations = true,
654 "--policy-violations" => self.policy_violations = true,
655 "--stale-suppressions" => self.stale_suppressions = true,
656 "--unused-catalog-entries" => self.unused_catalog_entries = true,
657 "--empty-catalog-groups" => self.empty_catalog_groups = true,
658 "--unresolved-catalog-references" => self.unresolved_catalog_references = true,
659 "--unused-dependency-overrides" => self.unused_dependency_overrides = true,
660 "--misconfigured-dependency-overrides" => {
661 self.misconfigured_dependency_overrides = true;
662 }
663 _ => unreachable!("registry emitted unsupported dead-code filter flag: {flag}"),
664 }
665 }
666}
667
668#[derive(Debug, Clone, Default)]
670pub struct DeadCodeOptions {
671 pub analysis: AnalysisOptions,
673 pub filters: DeadCodeFilters,
675 pub files: Vec<PathBuf>,
677 pub include_entry_exports: bool,
679 pub show_cascade: bool,
681 pub finding_ids: Vec<String>,
686}
687
688#[derive(Debug, Clone, Default)]
694pub struct ArchitectureOptions {
695 pub shared_state: bool,
697 pub analysis: AnalysisOptions,
699 pub files: Vec<PathBuf>,
701 pub cycles: bool,
704 pub boundaries: bool,
706 pub policy: bool,
708}
709
710impl ArchitectureOptions {
711 #[must_use]
713 pub fn dead_code_filters(&self) -> DeadCodeFilters {
714 let all = !(self.cycles || self.boundaries || self.policy || self.shared_state);
715 DeadCodeFilters {
716 shared_state: self.shared_state,
717 circular_deps: self.cycles || all,
718 re_export_cycles: self.cycles || all,
719 package_cycles: self.cycles || all,
720 boundary_violations: self.boundaries || all,
721 policy_violations: self.policy || all,
722 ..DeadCodeFilters::default()
723 }
724 }
725
726 pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
729 fallow_engine::requested_rule_off::architecture_requested_flags(
730 self.cycles,
731 self.boundaries,
732 self.policy,
733 )
734 }
735
736 #[must_use]
738 pub fn dead_code_options(&self) -> DeadCodeOptions {
739 DeadCodeOptions {
740 analysis: self.analysis.clone(),
741 filters: self.dead_code_filters(),
742 files: self.files.clone(),
743 include_entry_exports: false,
744 show_cascade: false,
745 finding_ids: Vec::new(),
746 }
747 }
748}
749
750#[derive(Debug, Clone, Default)]
752pub struct AuditOptions {
753 pub analysis: AnalysisOptions,
755 pub base: Option<String>,
758 pub production: bool,
760 pub production_dead_code: Option<bool>,
762 pub production_health: Option<bool>,
764 pub production_dupes: Option<bool>,
767 pub dead_code: Option<bool>,
771 pub health: Option<bool>,
774 pub duplication: Option<bool>,
777 pub css: Option<bool>,
780 pub css_deep: Option<bool>,
783 pub gate: Option<fallow_config::AuditGate>,
786 pub worsened: Option<fallow_config::AuditWorsened>,
789 pub max_crap: Option<f64>,
791 pub coverage: Option<PathBuf>,
793 pub coverage_root: Option<PathBuf>,
795 pub include_entry_exports: bool,
797 pub show_cascade: bool,
799 pub runtime_coverage: Option<PathBuf>,
801 pub min_invocations_hot: u64,
803}
804
805#[derive(Debug, Clone)]
807pub struct CombinedOptions {
808 pub analysis: AnalysisOptions,
810 pub dead_code: bool,
812 pub duplication: bool,
814 pub health: bool,
816 pub include_entry_exports: bool,
818 pub show_cascade: bool,
820 pub duplication_options: DuplicationOptions,
822 pub health_options: ComplexityOptions,
824}
825
826impl Default for CombinedOptions {
827 fn default() -> Self {
828 Self {
829 analysis: AnalysisOptions::default(),
830 dead_code: true,
831 duplication: true,
832 health: true,
833 include_entry_exports: false,
834 show_cascade: false,
835 duplication_options: DuplicationOptions::default(),
836 health_options: ComplexityOptions::default(),
837 }
838 }
839}
840
841#[derive(Debug, Clone, Default)]
843pub struct DecisionSurfaceOptions {
844 pub analysis: AnalysisOptions,
846 pub base: Option<String>,
849 pub max_decisions: Option<usize>,
851}
852
853#[derive(Debug, Clone, Default)]
855pub struct FeatureFlagsOptions {
856 pub analysis: AnalysisOptions,
858 pub top: Option<usize>,
861 pub retirement: Option<FeatureFlagsRetirementOptions>,
863}
864
865#[derive(Debug, Clone, Default)]
868pub struct FeatureFlagsRetirementOptions {
869 pub flag_age: fallow_types::flag_retirement::FlagAgeMode,
871 pub flag_state: Option<std::path::PathBuf>,
873 pub reasons: Vec<fallow_types::flag_retirement::RetirementReason>,
875 pub sort: fallow_engine::flag_retirement::RetirementSort,
877 pub min_age_days: Option<u64>,
879 pub max_flag_age: Option<u64>,
881}
882
883#[derive(Debug, Clone, Copy, Default)]
885pub enum DuplicationMode {
886 Strict,
889 #[default]
891 Mild,
892 Weak,
894 Semantic,
897}
898
899#[derive(Debug, Clone, Default)]
901pub struct DuplicationOptions {
902 pub analysis: AnalysisOptions,
904 pub mode: Option<DuplicationMode>,
906 pub near: Option<bool>,
909 pub min_tokens: Option<usize>,
911 pub min_lines: Option<usize>,
913 pub min_occurrences: Option<usize>,
916 pub threshold: Option<f64>,
919 pub skip_local: Option<bool>,
922 pub ignore_symlinks: Option<bool>,
925 pub cross_language: Option<bool>,
927 pub ignore_imports: Option<bool>,
930 pub top: Option<usize>,
932 pub include_fragments: Option<bool>,
936}
937
938#[derive(Debug, Clone, Default)]
940pub struct SimilarCodeOptions {
941 pub analysis: AnalysisOptions,
943 pub threshold: Option<f64>,
945 pub min_lines: Option<usize>,
948 pub top: Option<usize>,
950 pub files: Vec<PathBuf>,
954 #[doc(hidden)]
959 pub adapter_provider_path: Option<PathBuf>,
960}
961
962#[derive(Debug, Clone)]
964pub struct SimilarCodeInspectOptions {
965 pub analysis: AnalysisOptions,
968 pub snapshot: fallow_output::SimilarCodeCandidateSnapshot,
970}
971
972#[derive(Debug, Clone, Default)]
974pub struct TraceExportOptions {
975 pub analysis: AnalysisOptions,
977 pub file: String,
979 pub export_name: String,
981}
982
983#[derive(Debug, Clone, Default)]
985pub struct TraceFileOptions {
986 pub analysis: AnalysisOptions,
988 pub file: String,
990}
991
992#[derive(Debug, Clone, Default)]
994pub struct TraceImportPathOptions {
995 pub analysis: AnalysisOptions,
997 pub from: String,
999 pub to: String,
1001 pub eager_only: bool,
1004}
1005
1006#[derive(Debug, Clone, Default)]
1008pub struct TraceErrorOptions {
1009 pub analysis: AnalysisOptions,
1011 pub trace: String,
1013 pub source: String,
1015}
1016
1017#[derive(Debug, Clone, Default)]
1019pub struct TraceDependencyOptions {
1020 pub analysis: AnalysisOptions,
1022 pub package_name: String,
1024 pub usage: Option<DependencyUsageQuery>,
1027}
1028
1029#[derive(Debug, Clone, PartialEq, Eq)]
1031pub enum TraceCloneTarget {
1032 Location {
1034 file: String,
1036 line: usize,
1038 },
1039 Fingerprint(String),
1041}
1042
1043#[derive(Debug, Clone)]
1045pub struct TraceCloneOptions {
1046 pub duplication: DuplicationOptions,
1048 pub target: TraceCloneTarget,
1050}
1051
1052#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1054pub enum ComplexitySort {
1055 #[default]
1057 Cyclomatic,
1058 Cognitive,
1060 Lines,
1062 Severity,
1064}
1065
1066#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1068pub enum OwnershipEmailMode {
1069 Raw,
1071 #[default]
1073 Handle,
1074 Anonymized,
1076 Hash,
1078}
1079
1080#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1082pub enum TargetEffort {
1083 Low,
1085 Medium,
1087 High,
1089}
1090
1091#[derive(Debug, Clone, Default)]
1093pub struct ComplexityOptions {
1094 pub analysis: AnalysisOptions,
1096 pub max_cyclomatic: Option<u16>,
1098 pub max_cognitive: Option<u16>,
1100 pub max_crap: Option<f64>,
1102 pub max_file_lines: Option<u32>,
1105 pub top: Option<usize>,
1107 pub sort: ComplexitySort,
1109 pub complexity_breakdown: bool,
1111 pub complexity: bool,
1113 pub file_scores: bool,
1115 pub coverage_gaps: bool,
1117 pub hotspots: bool,
1119 pub ownership: bool,
1121 pub ownership_emails: Option<OwnershipEmailMode>,
1123 pub targets: bool,
1125 pub css: bool,
1127 pub css_deep: bool,
1129 pub effort: Option<TargetEffort>,
1132 pub score: bool,
1134 pub since: Option<String>,
1136 pub min_commits: Option<u32>,
1138 pub coverage: Option<PathBuf>,
1140 pub coverage_root: Option<PathBuf>,
1142 pub coverage_relocated: bool,
1147}
1148
1149#[derive(Debug, Clone, Copy, Default, PartialEq)]
1151pub struct ComplexityThresholdOverrides {
1152 pub max_cyclomatic: Option<u16>,
1154 pub max_cognitive: Option<u16>,
1156 pub max_crap: Option<f64>,
1158 pub max_file_lines: Option<u32>,
1160}
1161
1162#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1164pub struct ComplexityCoverageInputs<'a> {
1165 pub coverage: Option<&'a Path>,
1167 pub coverage_root: Option<&'a Path>,
1169 pub coverage_relocated: bool,
1172}
1173
1174#[derive(Debug, Clone)]
1176pub struct HealthSectionOptions {
1177 pub output: fallow_types::output_format::OutputFormat,
1179 pub complexity: bool,
1181 pub file_scores: bool,
1183 pub coverage_gaps: bool,
1185 pub hotspots: bool,
1187 pub targets: bool,
1189 pub css: bool,
1191 pub score: bool,
1193 pub score_gate: bool,
1195 pub snapshot_requested: bool,
1197 pub trend: bool,
1199}
1200
1201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1203pub struct DerivedHealthSections {
1204 pub any_section: bool,
1206 pub complexity: bool,
1208 pub file_scores: bool,
1210 pub coverage_gaps: bool,
1212 pub hotspots: bool,
1214 pub targets: bool,
1216 pub css: bool,
1218 pub score: bool,
1220 pub force_full: bool,
1222 pub score_only_output: bool,
1224}
1225
1226#[derive(Debug, Clone)]
1228pub struct ComplexitySectionOptions {
1229 pub complexity: bool,
1231 pub file_scores: bool,
1233 pub coverage_gaps: bool,
1235 pub hotspots: bool,
1237 pub ownership: bool,
1239 pub targets: bool,
1241 pub css: bool,
1243 pub score: bool,
1245}
1246
1247#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1249pub struct DerivedComplexityOptions {
1250 pub any_section: bool,
1252 pub complexity: bool,
1254 pub file_scores: bool,
1256 pub coverage_gaps: bool,
1258 pub hotspots: bool,
1260 pub ownership: bool,
1262 pub targets: bool,
1264 pub force_full: bool,
1266 pub score_only_output: bool,
1268 pub score: bool,
1270}
1271
1272#[derive(Debug, Clone, PartialEq)]
1274pub struct ComplexityRunOptions<'a> {
1275 pub thresholds: ComplexityThresholdOverrides,
1277 pub top: Option<usize>,
1279 pub sort: ComplexitySort,
1281 pub complexity_breakdown: bool,
1283 pub sections: DerivedComplexityOptions,
1285 pub ownership_emails: Option<OwnershipEmailMode>,
1287 pub effort: Option<TargetEffort>,
1289 pub css: bool,
1291 pub css_deep: bool,
1293 pub since: Option<&'a str>,
1295 pub min_commits: Option<u32>,
1297 pub coverage_inputs: ComplexityCoverageInputs<'a>,
1299}
1300
1301pub fn configure_global_analysis_pool(threads: usize) -> bool {
1310 fallow_engine::thread_pool::worker_pool_builder(threads)
1311 .build_global()
1312 .is_ok()
1313}
1314
1315#[must_use]
1317pub fn derive_health_sections(options: &HealthSectionOptions) -> DerivedHealthSections {
1318 let score = options.score
1319 || options.score_gate
1320 || options.trend
1321 || matches!(
1322 options.output,
1323 fallow_types::output_format::OutputFormat::Badge
1324 );
1325 let any_section = options.complexity
1326 || options.file_scores
1327 || options.coverage_gaps
1328 || options.hotspots
1329 || options.targets
1330 || score;
1331 let effective_score = if any_section { score } else { true } || options.snapshot_requested;
1332 let force_full = options.snapshot_requested || effective_score;
1333
1334 DerivedHealthSections {
1335 any_section,
1336 complexity: if any_section {
1337 options.complexity
1338 } else {
1339 true
1340 },
1341 file_scores: if any_section {
1342 options.file_scores
1343 } else {
1344 true
1345 } || force_full,
1346 coverage_gaps: if any_section {
1347 options.coverage_gaps
1348 } else {
1349 false
1350 },
1351 hotspots: if any_section { options.hotspots } else { true }
1352 || options.snapshot_requested
1353 || options.trend,
1354 targets: if any_section { options.targets } else { true },
1355 css: options.css,
1356 score: effective_score,
1357 force_full,
1358 score_only_output: is_health_score_only_output(options, score),
1359 }
1360}
1361
1362#[must_use]
1364pub fn derive_complexity_sections(options: &ComplexitySectionOptions) -> DerivedComplexityOptions {
1365 let requested_hotspots = options.hotspots || options.ownership;
1366 let sections = derive_health_sections(&HealthSectionOptions {
1367 output: fallow_types::output_format::OutputFormat::Human,
1368 complexity: options.complexity,
1369 file_scores: options.file_scores,
1370 coverage_gaps: options.coverage_gaps,
1371 hotspots: requested_hotspots,
1372 targets: options.targets,
1373 css: options.css,
1374 score: options.score,
1375 score_gate: false,
1376 snapshot_requested: false,
1377 trend: false,
1378 });
1379
1380 DerivedComplexityOptions {
1381 any_section: sections.any_section,
1382 complexity: sections.complexity,
1383 file_scores: sections.file_scores,
1384 coverage_gaps: sections.coverage_gaps,
1385 hotspots: sections.hotspots,
1386 ownership: options.ownership && sections.hotspots,
1387 targets: sections.targets,
1388 force_full: sections.force_full,
1389 score_only_output: sections.score_only_output,
1390 score: sections.score,
1391 }
1392}
1393
1394#[must_use]
1396pub fn derive_complexity_options(options: &ComplexityOptions) -> DerivedComplexityOptions {
1397 derive_complexity_sections(&complexity_section_options(options))
1398}
1399
1400#[must_use]
1402pub fn derive_complexity_run_options(options: &ComplexityOptions) -> ComplexityRunOptions<'_> {
1403 ComplexityRunOptions {
1404 thresholds: ComplexityThresholdOverrides {
1405 max_cyclomatic: options.max_cyclomatic,
1406 max_cognitive: options.max_cognitive,
1407 max_crap: options.max_crap,
1408 max_file_lines: options.max_file_lines,
1409 },
1410 top: options.top,
1411 sort: options.sort,
1412 complexity_breakdown: options.complexity_breakdown,
1413 sections: derive_complexity_options(options),
1414 ownership_emails: options.ownership_emails,
1415 effort: options.effort,
1416 css: options.css,
1417 css_deep: options.css_deep,
1418 since: options.since.as_deref(),
1419 min_commits: options.min_commits,
1420 coverage_inputs: ComplexityCoverageInputs {
1421 coverage: options.coverage.as_deref(),
1422 coverage_root: options.coverage_root.as_deref(),
1423 coverage_relocated: options.coverage_relocated,
1424 },
1425 }
1426}
1427
1428pub fn validate_complexity_options(options: &ComplexityOptions) -> Result<(), ProgrammaticError> {
1451 if let Some(path) = &options.coverage {
1452 let resolved = fallow_engine::health::scoring::resolve_relative_to_root(
1453 path,
1454 options.analysis.root.as_deref(),
1455 );
1456 if !resolved.exists() {
1457 return Err(ProgrammaticError::new(
1458 format!("coverage path does not exist: {}", resolved.display()),
1459 2,
1460 )
1461 .with_code("FALLOW_INVALID_COVERAGE_PATH")
1462 .with_context("health.coverage"));
1463 }
1464 }
1465 if let Err(message) =
1466 fallow_engine::health::validate_coverage_root_absolute(options.coverage_root.as_deref())
1467 {
1468 return Err(ProgrammaticError::new(message, 2)
1469 .with_code("FALLOW_INVALID_COVERAGE_ROOT")
1470 .with_context("health.coverage_root"));
1471 }
1472
1473 Ok(())
1474}
1475
1476fn complexity_section_options(options: &ComplexityOptions) -> ComplexitySectionOptions {
1477 let ownership = options.ownership || options.ownership_emails.is_some();
1478 let requested_targets = options.targets || options.effort.is_some();
1479 ComplexitySectionOptions {
1480 complexity: options.complexity,
1481 file_scores: options.file_scores,
1482 coverage_gaps: options.coverage_gaps,
1483 hotspots: options.hotspots,
1484 ownership,
1485 targets: requested_targets,
1486 css: options.css,
1487 score: options.score,
1488 }
1489}
1490
1491fn is_health_score_only_output(options: &HealthSectionOptions, score: bool) -> bool {
1492 score
1493 && !options.complexity
1494 && !options.file_scores
1495 && !options.coverage_gaps
1496 && !options.hotspots
1497 && !options.targets
1498 && !options.trend
1499}
1500
1501const fn thresholds_to_engine(
1502 thresholds: ComplexityThresholdOverrides,
1503) -> fallow_engine::health::HealthThresholdOverrides {
1504 fallow_engine::health::HealthThresholdOverrides {
1505 max_cyclomatic: thresholds.max_cyclomatic,
1506 max_cognitive: thresholds.max_cognitive,
1507 max_crap: thresholds.max_crap,
1508 max_file_lines: thresholds.max_file_lines,
1509 }
1510}
1511
1512const fn complexity_sort_to_engine(sort: ComplexitySort) -> fallow_engine::health::HealthSort {
1513 match sort {
1514 ComplexitySort::Severity => fallow_engine::health::HealthSort::Severity,
1515 ComplexitySort::Cyclomatic => fallow_engine::health::HealthSort::Cyclomatic,
1516 ComplexitySort::Cognitive => fallow_engine::health::HealthSort::Cognitive,
1517 ComplexitySort::Lines => fallow_engine::health::HealthSort::Lines,
1518 }
1519}
1520
1521const fn coverage_inputs_to_engine(
1522 coverage_inputs: ComplexityCoverageInputs<'_>,
1523) -> fallow_engine::health::HealthCoverageInputs<'_> {
1524 fallow_engine::health::HealthCoverageInputs {
1525 coverage: coverage_inputs.coverage,
1526 coverage_root: coverage_inputs.coverage_root,
1527 coverage_relocated: coverage_inputs.coverage_relocated,
1528 }
1529}
1530
1531const fn ownership_email_mode_to_config(mode: OwnershipEmailMode) -> EmailMode {
1532 match mode {
1533 OwnershipEmailMode::Raw => EmailMode::Raw,
1534 OwnershipEmailMode::Handle => EmailMode::Handle,
1535 OwnershipEmailMode::Anonymized => EmailMode::Anonymized,
1536 OwnershipEmailMode::Hash => EmailMode::Hash,
1537 }
1538}
1539
1540const fn target_effort_to_output(effort: TargetEffort) -> EffortEstimate {
1541 match effort {
1542 TargetEffort::Low => EffortEstimate::Low,
1543 TargetEffort::Medium => EffortEstimate::Medium,
1544 TargetEffort::High => EffortEstimate::High,
1545 }
1546}
1547
1548#[cfg(test)]
1549mod tests {
1550 use super::*;
1551
1552 #[test]
1553 fn duplication_defaults_match_cli_contract() {
1554 let options = DuplicationOptions::default();
1555 assert!(options.mode.is_none());
1556 assert!(options.min_tokens.is_none());
1557 assert!(options.min_lines.is_none());
1558 assert!(options.min_occurrences.is_none());
1559 }
1560
1561 #[test]
1562 fn programmatic_error_builder_keeps_optional_fields() {
1563 let error = ProgrammaticError::new("boom", 2)
1564 .with_code("FALLOW_TEST")
1565 .with_help("Try again")
1566 .with_context("analysis.root");
1567
1568 assert_eq!(error.message, "boom");
1569 assert_eq!(error.exit_code, 2);
1570 assert_eq!(error.code.as_deref(), Some("FALLOW_TEST"));
1571 assert_eq!(error.help.as_deref(), Some("Try again"));
1572 assert_eq!(error.context.as_deref(), Some("analysis.root"));
1573 }
1574
1575 #[test]
1576 fn dead_code_filters_accept_shared_registry_selectors() {
1577 for (selector, _) in fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS.iter() {
1578 let mut filters = DeadCodeFilters::default();
1579 assert!(
1580 filters.enable_registry_selector(selector),
1581 "{selector} should be accepted"
1582 );
1583 }
1584
1585 let mut filters = DeadCodeFilters::default();
1586 assert!(filters.enable_registry_selector("unused-files"));
1587 assert!(filters.unused_files);
1588 assert!(filters.enable_registry_selector("boundary-violations"));
1589 assert!(filters.boundary_violations);
1590 assert!(!filters.enable_registry_selector("not-a-real-selector"));
1591 }
1592
1593 #[test]
1594 fn default_complexity_options_match_programmatic_health_defaults() {
1595 let derived = derive_complexity_options(&ComplexityOptions::default());
1596
1597 assert!(!derived.any_section);
1598 assert!(derived.complexity);
1599 assert!(derived.file_scores);
1600 assert!(!derived.coverage_gaps);
1601 assert!(derived.hotspots);
1602 assert!(!derived.ownership);
1603 assert!(derived.targets);
1604 assert!(derived.force_full);
1605 assert!(!derived.score_only_output);
1606 assert!(derived.score);
1607 }
1608
1609 #[test]
1610 fn score_only_complexity_options_request_score_only_output() {
1611 let derived = derive_complexity_options(&ComplexityOptions {
1612 score: true,
1613 ..ComplexityOptions::default()
1614 });
1615
1616 assert!(derived.any_section);
1617 assert!(!derived.complexity);
1618 assert!(derived.file_scores);
1619 assert!(!derived.hotspots);
1620 assert!(!derived.targets);
1621 assert!(derived.force_full);
1622 assert!(derived.score_only_output);
1623 assert!(derived.score);
1624 }
1625
1626 #[test]
1627 fn ownership_implies_hotspots_when_requested() {
1628 let derived = derive_complexity_options(&ComplexityOptions {
1629 ownership: true,
1630 ..ComplexityOptions::default()
1631 });
1632
1633 assert!(derived.any_section);
1634 assert!(derived.hotspots);
1635 assert!(derived.ownership);
1636 assert!(!derived.targets);
1637 }
1638
1639 #[test]
1640 fn complexity_run_options_normalize_public_api_options() {
1641 let options = ComplexityOptions {
1642 max_cyclomatic: Some(42),
1643 max_cognitive: Some(21),
1644 max_crap: Some(18.5),
1645 top: Some(7),
1646 sort: ComplexitySort::Severity,
1647 complexity_breakdown: true,
1648 ownership_emails: Some(OwnershipEmailMode::Hash),
1649 effort: Some(TargetEffort::High),
1650 coverage: Some(PathBuf::from("coverage/coverage-final.json")),
1651 coverage_root: Some(PathBuf::from("/ci/workspace")),
1652 since: Some("30d".to_string()),
1653 min_commits: Some(4),
1654 ..ComplexityOptions::default()
1655 };
1656
1657 let run = derive_complexity_run_options(&options);
1658
1659 assert_eq!(run.thresholds.max_cyclomatic, Some(42));
1660 assert_eq!(run.thresholds.max_cognitive, Some(21));
1661 assert_eq!(run.thresholds.max_crap, Some(18.5));
1662 assert_eq!(run.top, Some(7));
1663 assert!(matches!(run.sort, ComplexitySort::Severity));
1664 assert!(run.complexity_breakdown);
1665 assert!(run.sections.hotspots);
1666 assert!(run.sections.ownership);
1667 assert!(run.sections.targets);
1668 assert!(matches!(
1669 run.ownership_emails,
1670 Some(OwnershipEmailMode::Hash)
1671 ));
1672 assert!(matches!(run.effort, Some(TargetEffort::High)));
1673 assert_eq!(run.since, Some("30d"));
1674 assert_eq!(run.min_commits, Some(4));
1675 assert_eq!(run.coverage_inputs.coverage, options.coverage.as_deref());
1676 assert_eq!(
1677 run.coverage_inputs.coverage_root,
1678 options.coverage_root.as_deref()
1679 );
1680 }
1681
1682 #[test]
1683 fn complexity_options_validation_accepts_existing_coverage_path_and_absolute_root() {
1684 let dir = tempfile::tempdir().expect("tempdir");
1685 let coverage = dir.path().join("coverage-final.json");
1686 std::fs::write(&coverage, "{}").expect("coverage fixture");
1687
1688 let result = validate_complexity_options(&ComplexityOptions {
1689 coverage: Some(coverage),
1690 coverage_root: Some(PathBuf::from("/ci/workspace")),
1691 ..ComplexityOptions::default()
1692 });
1693
1694 assert!(result.is_ok());
1695 }
1696
1697 #[test]
1698 fn complexity_options_validation_keeps_missing_coverage_error_contract() {
1699 let err = validate_complexity_options(&ComplexityOptions {
1700 coverage: Some(PathBuf::from("/missing/coverage-final.json")),
1701 ..ComplexityOptions::default()
1702 })
1703 .expect_err("missing coverage path should fail");
1704
1705 assert_eq!(err.exit_code, 2);
1706 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1707 assert_eq!(err.context.as_deref(), Some("health.coverage"));
1708 }
1709
1710 #[test]
1711 fn complexity_options_validation_keeps_relative_coverage_root_error_contract() {
1712 let err = validate_complexity_options(&ComplexityOptions {
1713 coverage_root: Some(PathBuf::from("coverage")),
1714 ..ComplexityOptions::default()
1715 })
1716 .expect_err("relative coverage root should fail");
1717
1718 assert_eq!(err.exit_code, 2);
1719 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_ROOT"));
1720 assert_eq!(err.context.as_deref(), Some("health.coverage_root"));
1721 }
1722
1723 #[test]
1727 fn complexity_options_validation_resolves_relative_coverage_against_root() {
1728 let dir = tempfile::tempdir().expect("tempdir");
1729 std::fs::create_dir_all(dir.path().join("artifacts")).expect("artifacts dir");
1730 std::fs::write(dir.path().join("artifacts/coverage-final.json"), "{}")
1731 .expect("coverage fixture");
1732 let relative = PathBuf::from("artifacts/coverage-final.json");
1733 assert!(
1734 !relative.exists(),
1735 "the fixture must not also exist under the test cwd"
1736 );
1737
1738 let result = validate_complexity_options(&ComplexityOptions {
1739 analysis: AnalysisOptions {
1740 root: Some(dir.path().to_path_buf()),
1741 ..AnalysisOptions::default()
1742 },
1743 coverage: Some(relative.clone()),
1744 ..ComplexityOptions::default()
1745 });
1746 assert!(result.is_ok(), "{result:?}");
1747
1748 let err = validate_complexity_options(&ComplexityOptions {
1749 analysis: AnalysisOptions {
1750 root: Some(dir.path().join("elsewhere")),
1751 ..AnalysisOptions::default()
1752 },
1753 coverage: Some(relative),
1754 ..ComplexityOptions::default()
1755 })
1756 .expect_err("the path does not exist under the other root");
1757 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1758 assert!(
1759 err.message.contains("elsewhere"),
1760 "the message names the resolved path: {}",
1761 err.message
1762 );
1763 }
1764
1765 #[test]
1766 fn default_health_sections_match_full_health_output() {
1767 let derived = derive_health_sections(&HealthSectionOptions {
1768 output: fallow_types::output_format::OutputFormat::Human,
1769 complexity: false,
1770 file_scores: false,
1771 coverage_gaps: false,
1772 hotspots: false,
1773 targets: false,
1774 css: false,
1775 score: false,
1776 score_gate: false,
1777 snapshot_requested: false,
1778 trend: false,
1779 });
1780
1781 assert!(!derived.any_section);
1782 assert!(derived.complexity);
1783 assert!(derived.file_scores);
1784 assert!(!derived.coverage_gaps);
1785 assert!(derived.hotspots);
1786 assert!(derived.targets);
1787 assert!(derived.score);
1788 assert!(derived.force_full);
1789 assert!(!derived.score_only_output);
1790 }
1791
1792 #[test]
1793 fn health_score_gate_requests_score_only_output() {
1794 let derived = derive_health_sections(&HealthSectionOptions {
1795 output: fallow_types::output_format::OutputFormat::Human,
1796 complexity: false,
1797 file_scores: false,
1798 coverage_gaps: false,
1799 hotspots: false,
1800 targets: false,
1801 css: false,
1802 score: false,
1803 score_gate: true,
1804 snapshot_requested: false,
1805 trend: false,
1806 });
1807
1808 assert!(derived.any_section);
1809 assert!(!derived.complexity);
1810 assert!(derived.file_scores);
1811 assert!(!derived.hotspots);
1812 assert!(!derived.targets);
1813 assert!(derived.score);
1814 assert!(derived.force_full);
1815 assert!(derived.score_only_output);
1816 }
1817
1818 #[test]
1819 fn health_snapshot_keeps_full_hidden_inputs_without_section_request() {
1820 let derived = derive_health_sections(&HealthSectionOptions {
1821 output: fallow_types::output_format::OutputFormat::Human,
1822 complexity: false,
1823 file_scores: false,
1824 coverage_gaps: false,
1825 hotspots: false,
1826 targets: false,
1827 css: true,
1828 score: false,
1829 score_gate: false,
1830 snapshot_requested: true,
1831 trend: false,
1832 });
1833
1834 assert!(!derived.any_section);
1835 assert!(derived.css);
1836 assert!(derived.file_scores);
1837 assert!(derived.hotspots);
1838 assert!(derived.score);
1839 assert!(derived.force_full);
1840 }
1841}
1842
1843mod shared_state_explain;