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;
44pub mod coverage;
45pub mod dead_code_codeclimate;
46pub mod dead_code_sarif;
47pub mod decision_surface;
48pub mod dependency_deltas;
49pub mod diff_risk;
50pub mod doctor;
51pub mod dupes_output;
52pub mod editor;
53pub mod explain;
54pub mod grouped_output;
55pub mod health_codeclimate;
56mod health_groups_markdown;
57pub mod json_output;
58pub mod list_output;
59mod list_runtime;
60pub mod markdown_output;
63pub mod mutation;
64mod next_steps;
65pub mod output_contracts;
66pub mod ownership;
67pub mod review_deltas;
68pub mod routing;
69pub mod runtime;
70mod runtime_json;
71mod runtime_output;
72pub mod sarif_output;
73pub mod schemas;
76pub mod security_output;
77pub mod similar_code;
79mod type_aware;
80pub use analysis_context::{ProgrammaticAnalysisContext, resolve_programmatic_analysis_context};
81pub use audit_output::{
82 AuditAttribution, AuditCodeClimateOutputInput, AuditJsonHeaderInput, AuditJsonOutputInput,
83 AuditSarifOutputInput, AuditSummary, AuditVerdict, attach_audit_diff_risk_attribution,
84 attach_audit_duplication_demotion_attribution, attach_audit_styling_attribution,
85 attach_audit_wire_attribution, build_audit_codeclimate, build_audit_codeclimate_issues,
86 build_audit_header_json, build_audit_header_map, build_audit_sarif,
87 build_diff_risk_codeclimate, build_review_brief_header, serialize_audit_json,
88};
89pub use combined_output::{
90 CombinedCheckJsonSection, CombinedJsonOutputInput, serialize_combined_dupes_json,
91 serialize_combined_health_json, serialize_combined_json,
92};
93pub use compact_output::{
94 build_compact_lines, build_diff_risk_compact_lines, build_duplication_compact_lines,
95 build_grouped_compact_lines, build_health_compact_lines,
96};
97pub use coverage::{
98 CoverageInputError, CoverageInputSource, CoverageInputs, resolve_coverage_inputs,
99};
100pub use dead_code_codeclimate::build_codeclimate;
101pub use dead_code_sarif::build_sarif;
102pub use doctor::{DoctorOptions, run_doctor, run_doctor_with_cache_dir};
103pub use dupes_output::{
104 AttributedCloneGroup, AttributedCloneGroupFinding, AttributedInstance, CloneDemotionReason,
105 CloneFamilyFinding, CloneGroupFinding, CombinedDupesSection, DupesReportPayload,
106 DuplicationGroup, DuplicationGrouping, build_duplication_codeclimate,
107 set_duplication_audit_attribution,
108};
109pub use editor::{
110 ChangedFilesError, EditorAnalysisOutput, EditorAnalysisResults, EditorAnalysisSession,
111 EditorCloneFamily, EditorCloneFingerprintSet, EditorCloneGroup, EditorCloneInstance,
112 EditorDeadCodeAnalysisOutput, EditorDuplicationReport, EditorDuplicationStats,
113 EditorInlineComplexityExceeded, EditorInlineComplexityFinding, EditorMirroredDirectory,
114 EditorProjectAnalysisOutput, EditorRefactoringKind, EditorRefactoringSuggestion,
115 EditorSessionParseCounts, collect_inline_complexity, editor_duplicates, editor_extract,
116 editor_results, editor_security, editor_suppress, filter_inline_complexity_by_change_scope,
117 filter_inline_complexity_by_changed_files, resolve_git_toplevel,
118 try_get_changed_files_with_toplevel,
119};
120pub use explain::{
121 AUDIT_RULES, CHECK_RULES, DUPES_RULES, FLAGS_RULES, HEALTH_RULES, MUTATION_RULES, RuleDef,
122 RuleGuide, SECURITY_RULES, all_rules, bare_rule_id, coverage_analyze_meta, coverage_setup_meta,
123 explain_issue_type, rule_by_id, rule_by_token, rule_command, rule_docs_url, rule_guide,
124 rule_severity_key, security_meta, serialize_explain_programmatic_json, unknown_explain_error,
125};
126pub use fallow_config::levenshtein::closest_match;
127pub use fallow_config::{AuditGate, AuditWorsened, HealthConfig, TypeAwareRequire};
128pub use fallow_engine::change_scope::{
131 ChangeScope, ChangeScopeOwner, ChangeScopeRequest, first_package_baselines,
132 package_baseline_statuses,
133};
134pub use fallow_engine::package_baselines::{PackageBaselineError, PackageChangeScope};
136pub use fallow_engine::thread_pool::{WORKER_STACK_SIZE, register_thread_stack};
143pub use fallow_engine::warm_parse;
149pub use fallow_output::PackageBaselineStatus;
151pub use fallow_output::serialize_similar_code_json_output;
152pub use fallow_types::trace::{
153 CloneTrace, DependencyTrace, ExportReference, ExportTrace, FileTrace, ReExportChain,
154 TracedCloneGroup, TracedExport, TracedReExport,
155};
156pub use fallow_types::trace_usage::{
157 DependencyUsage, DependencyUsageQuery, SitePageRequest, UsageQueryError,
158};
159pub use grouped_output::{
160 ResultGroup, UNOWNED_GROUP_LABEL, build_duplication_grouping_with, group_analysis_results_with,
161 health_signal_header_part, largest_clone_group_owner_with,
162};
163pub use health_codeclimate::build_health_codeclimate;
164pub use health_groups_markdown::build_health_groups_markdown;
165pub use json_output::{
166 CheckJsonExtraOutputs, CheckJsonOutputInput, CheckJsonPayloadInput, DuplicationJsonOutputInput,
167 GroupedCheckJsonOutputInput, GroupedDuplicationJsonOutputInput, serialize_check_json,
168 serialize_check_json_payload, serialize_duplication_json, serialize_grouped_check_json,
169 serialize_grouped_duplication_json,
170};
171pub use list_output::{
172 ListJsonEnvelope, ListJsonOutputInput, build_list_json_output, serialize_list_json_output,
173};
174pub use list_runtime::{
175 BoundaryData, ListBoundariesOptions, ListBoundariesProgrammaticOutput, LogicalGroupInfo,
176 ProjectInfoOptions, ProjectInfoProgrammaticOutput, RuleInfo, ZoneInfo, boundary_data_to_output,
177 compute_boundary_data, run_list_boundaries, run_project_info,
178 serialize_list_boundaries_programmatic_json, serialize_project_info_programmatic_json,
179};
180pub use markdown_output::{
181 ComplexityListing, build_diff_risk_markdown, build_duplication_markdown,
182 build_grouped_markdown, build_health_markdown, build_markdown, build_walkthrough_markdown,
183};
184pub use mutation::{
185 MutationProgress, MutationProgressSink, MutationReplayOptions, MutationRunOptions,
186 MutationRunScope, apply_mutation_verdicts, validate_mutation_verdicts,
187};
188pub use output_contracts::{
189 AuditOutput, BoundariesListLogicalGroup, BoundariesListRule, BoundariesListZone,
190 BoundariesListing, CombinedOutput, FallowOutput, ImpactOutput, ListBoundariesOutput,
191 ListEntryPointOutput, ListOutput, ListPluginOutput, ReviewBriefWireOutput, SecurityGate,
192 SecurityOutput, SecurityOutputConfig, SecuritySummaryOutput, SimilarCodeCandidateSnapshot,
193 SimilarCodeOutput, TraceOutput, WorkspacesOutput,
194};
195pub use runtime::TYPE_AWARE_CONFIG_UNSUPPORTED;
196pub use runtime::{
197 AUDIT_CONFIG_BASELINE_UNSUPPORTED, ArchitectureOutput, ArchitectureProgrammaticOutput,
198 AuditProgrammaticKeySnapshot, AuditProgrammaticOutput, BoundaryViolationsOutput,
199 BoundaryViolationsProgrammaticOutput, CircularDependenciesOutput,
200 CircularDependenciesProgrammaticOutput, CombinedProgrammaticOutput, DeadCodeOutput,
201 DeadCodeProgrammaticOutput, DecisionSurfaceProgrammaticOutput, DuplicationOutput,
202 DuplicationProgrammaticOutput, EngineHealthRunner, FeatureFlagsOutput,
203 FeatureFlagsProgrammaticOutput, HealthJsonReportInput, HealthProgrammaticOutput,
204 ProgrammaticHealthAnalysis, ProgrammaticHealthNextStepFacts, ProgrammaticHealthRun,
205 ProgrammaticHealthRunner, TraceClassMemberOutput, TraceCloneBenchmarkResult, TraceCloneOutput,
206 TraceCloneProgrammaticOutput, TraceDependencyOutput, TraceDependencyProgrammaticOutput,
207 TraceErrorOutput, TraceErrorProgrammaticOutput, TraceExportOutput,
208 TraceExportProgrammaticOutput, TraceExportTargetOutput, TraceFileOutput,
209 TraceFileProgrammaticOutput, TraceImportPathOutput, TraceImportPathProgrammaticOutput,
210 benchmark_trace_clone_compact_json, benchmark_trace_graph_family_compact_json,
211 inspect_similar_code, load_health_config, parse_similar_code_candidate_snapshot, plan_mutation,
212 replay_mutation, review_similar_code, run_architecture, run_audit, run_boundary_violations,
213 run_circular_dependencies, run_combined, run_complexity_with_runner, run_dead_code,
214 run_dead_code_with_baseline, run_decision_surface, run_duplication, run_feature_flags,
215 run_health, run_health_with_runner, run_mutation, run_mutation_with_progress, run_similar_code,
216 run_trace_clone, run_trace_dependency, run_trace_error, run_trace_export, run_trace_file,
217 run_trace_import_path, select_similar_code_candidate_snapshot, serialize_health_report_json,
218};
219pub use runtime_json::{
220 serialize_architecture_programmatic_json, serialize_audit_programmatic_json,
221 serialize_boundary_violations_programmatic_json,
222 serialize_circular_dependencies_programmatic_json, serialize_combined_programmatic_json,
223 serialize_dead_code_programmatic_json, serialize_decision_surface_programmatic_json,
224 serialize_duplication_programmatic_json, serialize_feature_flags_programmatic_json,
225 serialize_health_programmatic_json, serialize_trace_clone_programmatic_json,
226 serialize_trace_dependency_programmatic_json, serialize_trace_error_programmatic_json,
227 serialize_trace_export_programmatic_json, serialize_trace_file_programmatic_json,
228 serialize_trace_import_path_programmatic_json,
229};
230pub use sarif_output::{
231 annotate_sarif_results, build_duplication_sarif, build_grouped_duplication_sarif,
232 build_health_sarif,
233};
234pub use security_output::SecurityGateMode;
235pub use type_aware::{
236 DEFAULT_BACKEND_FAMILY as DEFAULT_TYPE_AWARE_BACKEND_FAMILY, SemanticCouplingOutcome,
237 SemanticDeadCodeOutcome, SemanticInspectOutcome, TypeAwareError, TypeAwareFileChanges,
238 TypeAwareOutcome, TypeAwareSession, TypeAwareStatus, discard_unverified_semantic_candidates,
239 inspect_symbol as inspect_type_aware_symbol, merge_type_aware_meta,
240 refine_configured_dead_code_results as refine_type_aware_results_with_config,
241 shutdown_type_aware_sidecars, status as type_aware_status,
242 symbol_impact as run_type_aware_symbol_impact, symbol_impact as type_aware_symbol_impact,
243 terminate_active_type_aware_sidecars, trace_symbol as run_type_aware_symbol_trace,
244 trace_symbol as trace_type_aware_symbol, type_coupling as analyze_type_coupling,
245};
246
247pub const COMMON_ANALYSIS_OPTION_FLAGS: &[&str] = &[
254 "root",
255 "config",
256 "no-cache",
257 "threads",
258 "changed-since",
259 "diff-file",
260 "production",
261 "workspace",
262 "changed-workspaces",
263 "explain",
264 "allow-remote-extends",
265];
266
267#[derive(Debug, Clone, Serialize)]
269pub struct ProgrammaticError {
270 pub message: String,
272 pub exit_code: u8,
274 pub code: Option<String>,
276 pub help: Option<String>,
278 pub context: Option<String>,
280}
281
282impl ProgrammaticError {
283 #[must_use]
286 pub fn new(message: impl Into<String>, exit_code: u8) -> Self {
287 Self {
288 message: message.into(),
289 exit_code,
290 code: None,
291 help: None,
292 context: None,
293 }
294 }
295
296 #[must_use]
298 pub fn with_help(mut self, help: impl Into<String>) -> Self {
299 self.help = Some(help.into());
300 self
301 }
302
303 #[must_use]
306 pub fn with_code(mut self, code: impl Into<String>) -> Self {
307 self.code = Some(code.into());
308 self
309 }
310
311 #[must_use]
314 pub fn with_context(mut self, context: impl Into<String>) -> Self {
315 self.context = Some(context.into());
316 self
317 }
318}
319
320impl std::fmt::Display for ProgrammaticError {
321 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
322 write!(f, "{}", self.message)
323 }
324}
325
326impl std::error::Error for ProgrammaticError {}
327
328#[derive(Debug, Clone, Default)]
330pub struct AnalysisOptions {
331 pub root: Option<PathBuf>,
334 pub config_path: Option<PathBuf>,
336 pub allow_remote_extends: bool,
338 pub no_cache: bool,
340 pub threads: Option<usize>,
342 pub diff_file: Option<PathBuf>,
354 pub ambient_diff_file: Option<PathBuf>,
362 pub production: bool,
365 pub production_override: Option<bool>,
368 pub changed_since: Option<String>,
373 pub ambient_changed_since: Option<String>,
381 pub no_package_baselines: bool,
385 pub workspace: Option<Vec<String>>,
387 pub changed_workspaces: Option<String>,
389 pub explain: bool,
391 pub type_aware: TypeAwareOptions,
394 pub cancellation: Option<Arc<AtomicBool>>,
424}
425
426#[derive(Debug, Clone, Default, PartialEq, Eq)]
428pub struct TypeAwareOptions {
429 pub enabled: Option<bool>,
436 pub projects: Vec<PathBuf>,
439 pub require: fallow_config::TypeAwareRequire,
441}
442
443impl TypeAwareOptions {
444 #[must_use]
446 pub const fn requested(&self) -> bool {
447 matches!(self.enabled, Some(true))
448 }
449}
450
451#[derive(Debug, Clone, Default, PartialEq, Eq)]
456pub struct DeadCodeFilters {
457 pub shared_state: bool,
459 pub unused_files: bool,
461 pub unused_exports: bool,
463 pub unused_deps: bool,
465 pub unused_types: bool,
467 pub private_type_leaks: bool,
469 pub deprecated_exports_in_use: bool,
471 pub unused_enum_members: bool,
473 pub unused_class_members: bool,
475 pub unused_namespace_members: bool,
477 pub unused_store_members: bool,
479 pub unprovided_injects: bool,
481 pub unrendered_components: bool,
483 pub unused_component_props: bool,
485 pub absent_component_props: bool,
487 pub constant_parameters: bool,
489 pub unused_component_emits: bool,
491 pub unused_component_inputs: bool,
493 pub unused_component_outputs: bool,
495 pub unused_svelte_events: bool,
497 pub unused_effect_layers: bool,
499 pub unused_tagged_errors: bool,
501 pub unproduced_catch_tags: bool,
503 pub unused_server_actions: bool,
505 pub unused_load_data_keys: bool,
507 pub unresolved_imports: bool,
509 pub unlisted_deps: bool,
511 pub unlisted_binaries: bool,
513 pub duplicate_exports: bool,
515 pub duplicate_export_aliases: bool,
517 pub circular_deps: bool,
519 pub re_export_cycles: bool,
521 pub package_cycles: bool,
523 pub boundary_violations: bool,
525 pub policy_violations: bool,
527 pub stale_suppressions: bool,
529 pub unused_catalog_entries: bool,
531 pub empty_catalog_groups: bool,
533 pub unresolved_catalog_references: bool,
535 pub unused_dependency_overrides: bool,
537 pub misconfigured_dependency_overrides: bool,
539}
540
541impl DeadCodeFilters {
542 pub(crate) fn reports_dependency_findings(&self) -> bool {
546 !self.any_active() || self.unused_deps || self.unlisted_deps
547 }
548
549 fn any_active(&self) -> bool {
550 self.shared_state
551 || self.unused_files
552 || self.unused_exports
553 || self.unused_deps
554 || self.unused_types
555 || self.private_type_leaks
556 || self.deprecated_exports_in_use
557 || self.unused_enum_members
558 || self.unused_class_members
559 || self.unused_namespace_members
560 || self.unused_store_members
561 || self.unprovided_injects
562 || self.unrendered_components
563 || self.unused_component_props
564 || self.absent_component_props
565 || self.constant_parameters
566 || self.unused_component_emits
567 || self.unused_component_inputs
568 || self.unused_component_outputs
569 || self.unused_svelte_events
570 || self.unused_effect_layers
571 || self.unused_tagged_errors
572 || self.unproduced_catch_tags
573 || self.unused_server_actions
574 || self.unused_load_data_keys
575 || self.unresolved_imports
576 || self.unlisted_deps
577 || self.unlisted_binaries
578 || self.duplicate_exports
579 || self.duplicate_export_aliases
580 || self.circular_deps
581 || self.re_export_cycles
582 || self.package_cycles
583 || self.boundary_violations
584 || self.policy_violations
585 || self.stale_suppressions
586 || self.unused_catalog_entries
587 || self.empty_catalog_groups
588 || self.unresolved_catalog_references
589 || self.unused_dependency_overrides
590 || self.misconfigured_dependency_overrides
591 }
592
593 pub fn enable_registry_selector(&mut self, selector: &str) -> bool {
599 let Some(flag) = fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS
600 .iter()
601 .find_map(|&(name, flag)| (name == selector).then_some(flag))
602 else {
603 return false;
604 };
605 self.enable_cli_filter_flag(flag);
606 true
607 }
608
609 pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
611 fallow_engine::requested_rule_off::explicit_filter_flags(|flag| {
612 let mut enabled = self.clone();
613 enabled.enable_cli_filter_flag(flag);
614 enabled == *self
615 })
616 }
617
618 fn enable_cli_filter_flag(&mut self, flag: &str) {
619 match flag {
620 "--unused-files" => self.unused_files = true,
621 "--unused-exports" => self.unused_exports = true,
622 "--unused-types" => self.unused_types = true,
623 "--private-type-leaks" => self.private_type_leaks = true,
624 "--deprecated-exports-in-use" => self.deprecated_exports_in_use = true,
625 "--unused-deps" => self.unused_deps = true,
626 "--unused-enum-members" => self.unused_enum_members = true,
627 "--unused-class-members" => self.unused_class_members = true,
628 "--unused-namespace-members" => self.unused_namespace_members = true,
629 "--unused-store-members" => self.unused_store_members = true,
630 "--unprovided-injects" => self.unprovided_injects = true,
631 "--unrendered-components" => self.unrendered_components = true,
632 "--unused-component-props" => self.unused_component_props = true,
633 "--absent-component-props" => self.absent_component_props = true,
634 "--constant-parameters" => self.constant_parameters = true,
635 "--unused-component-emits" => self.unused_component_emits = true,
636 "--unused-component-inputs" => self.unused_component_inputs = true,
637 "--unused-component-outputs" => self.unused_component_outputs = true,
638 "--unused-svelte-events" => self.unused_svelte_events = true,
639 "--unused-effect-layers" => self.unused_effect_layers = true,
640 "--unused-tagged-errors" => self.unused_tagged_errors = true,
641 "--unproduced-catch-tags" => self.unproduced_catch_tags = true,
642 "--unused-server-actions" => self.unused_server_actions = true,
643 "--unused-load-data-keys" => self.unused_load_data_keys = true,
644 "--unresolved-imports" => self.unresolved_imports = true,
645 "--unlisted-deps" => self.unlisted_deps = true,
646 "--unlisted-binaries" => self.unlisted_binaries = true,
647 "--duplicate-exports" => self.duplicate_exports = true,
648 "--duplicate-export-aliases" => self.duplicate_export_aliases = true,
649 "--circular-deps" => self.circular_deps = true,
650 "--re-export-cycles" => self.re_export_cycles = true,
651 "--package-cycles" => self.package_cycles = true,
652 "--boundary-violations" => self.boundary_violations = true,
653 "--policy-violations" => self.policy_violations = true,
654 "--stale-suppressions" => self.stale_suppressions = true,
655 "--unused-catalog-entries" => self.unused_catalog_entries = true,
656 "--empty-catalog-groups" => self.empty_catalog_groups = true,
657 "--unresolved-catalog-references" => self.unresolved_catalog_references = true,
658 "--unused-dependency-overrides" => self.unused_dependency_overrides = true,
659 "--misconfigured-dependency-overrides" => {
660 self.misconfigured_dependency_overrides = true;
661 }
662 _ => unreachable!("registry emitted unsupported dead-code filter flag: {flag}"),
663 }
664 }
665}
666
667#[derive(Debug, Clone, Default)]
669pub struct DeadCodeOptions {
670 pub analysis: AnalysisOptions,
672 pub filters: DeadCodeFilters,
674 pub files: Vec<PathBuf>,
676 pub include_entry_exports: bool,
678 pub show_cascade: bool,
680 pub finding_ids: Vec<String>,
685}
686
687#[derive(Debug, Clone, Default)]
693pub struct ArchitectureOptions {
694 pub shared_state: bool,
696 pub analysis: AnalysisOptions,
698 pub files: Vec<PathBuf>,
700 pub cycles: bool,
703 pub boundaries: bool,
705 pub policy: bool,
707}
708
709impl ArchitectureOptions {
710 #[must_use]
712 pub fn dead_code_filters(&self) -> DeadCodeFilters {
713 let all = !(self.cycles || self.boundaries || self.policy || self.shared_state);
714 DeadCodeFilters {
715 shared_state: self.shared_state,
716 circular_deps: self.cycles || all,
717 re_export_cycles: self.cycles || all,
718 package_cycles: self.cycles || all,
719 boundary_violations: self.boundaries || all,
720 policy_violations: self.policy || all,
721 ..DeadCodeFilters::default()
722 }
723 }
724
725 pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
728 fallow_engine::requested_rule_off::architecture_requested_flags(
729 self.cycles,
730 self.boundaries,
731 self.policy,
732 )
733 }
734
735 #[must_use]
737 pub fn dead_code_options(&self) -> DeadCodeOptions {
738 DeadCodeOptions {
739 analysis: self.analysis.clone(),
740 filters: self.dead_code_filters(),
741 files: self.files.clone(),
742 include_entry_exports: false,
743 show_cascade: false,
744 finding_ids: Vec::new(),
745 }
746 }
747}
748
749#[derive(Debug, Clone, Default)]
751pub struct AuditOptions {
752 pub analysis: AnalysisOptions,
754 pub base: Option<String>,
757 pub production: bool,
759 pub production_dead_code: Option<bool>,
761 pub production_health: Option<bool>,
763 pub production_dupes: Option<bool>,
766 pub dead_code: Option<bool>,
770 pub health: Option<bool>,
773 pub duplication: Option<bool>,
776 pub css: Option<bool>,
779 pub css_deep: Option<bool>,
782 pub gate: Option<fallow_config::AuditGate>,
785 pub worsened: Option<fallow_config::AuditWorsened>,
788 pub max_crap: Option<f64>,
790 pub coverage: Option<PathBuf>,
792 pub coverage_root: Option<PathBuf>,
794 pub include_entry_exports: bool,
796 pub show_cascade: bool,
798 pub runtime_coverage: Option<PathBuf>,
800 pub min_invocations_hot: u64,
802}
803
804#[derive(Debug, Clone)]
806pub struct CombinedOptions {
807 pub analysis: AnalysisOptions,
809 pub dead_code: bool,
811 pub duplication: bool,
813 pub health: bool,
815 pub include_entry_exports: bool,
817 pub show_cascade: bool,
819 pub duplication_options: DuplicationOptions,
821 pub health_options: ComplexityOptions,
823}
824
825impl Default for CombinedOptions {
826 fn default() -> Self {
827 Self {
828 analysis: AnalysisOptions::default(),
829 dead_code: true,
830 duplication: true,
831 health: true,
832 include_entry_exports: false,
833 show_cascade: false,
834 duplication_options: DuplicationOptions::default(),
835 health_options: ComplexityOptions::default(),
836 }
837 }
838}
839
840#[derive(Debug, Clone, Default)]
842pub struct DecisionSurfaceOptions {
843 pub analysis: AnalysisOptions,
845 pub base: Option<String>,
848 pub max_decisions: Option<usize>,
850}
851
852#[derive(Debug, Clone, Default)]
854pub struct FeatureFlagsOptions {
855 pub analysis: AnalysisOptions,
857 pub top: Option<usize>,
860 pub retirement: Option<FeatureFlagsRetirementOptions>,
862}
863
864#[derive(Debug, Clone, Default)]
867pub struct FeatureFlagsRetirementOptions {
868 pub flag_age: fallow_types::flag_retirement::FlagAgeMode,
870 pub flag_state: Option<std::path::PathBuf>,
872 pub reasons: Vec<fallow_types::flag_retirement::RetirementReason>,
874 pub sort: fallow_engine::flag_retirement::RetirementSort,
876 pub min_age_days: Option<u64>,
878 pub max_flag_age: Option<u64>,
880}
881
882#[derive(Debug, Clone, Copy, Default)]
884pub enum DuplicationMode {
885 Strict,
888 #[default]
890 Mild,
891 Weak,
893 Semantic,
896}
897
898#[derive(Debug, Clone, Default)]
900pub struct DuplicationOptions {
901 pub analysis: AnalysisOptions,
903 pub mode: Option<DuplicationMode>,
905 pub near: Option<bool>,
908 pub min_tokens: Option<usize>,
910 pub min_lines: Option<usize>,
912 pub min_occurrences: Option<usize>,
915 pub threshold: Option<f64>,
918 pub skip_local: Option<bool>,
921 pub ignore_symlinks: Option<bool>,
924 pub cross_language: Option<bool>,
926 pub ignore_imports: Option<bool>,
929 pub top: Option<usize>,
931 pub include_fragments: Option<bool>,
935}
936
937#[derive(Debug, Clone, Default)]
939pub struct SimilarCodeOptions {
940 pub analysis: AnalysisOptions,
942 pub threshold: Option<f64>,
944 pub min_lines: Option<usize>,
947 pub top: Option<usize>,
949 pub files: Vec<PathBuf>,
953 #[doc(hidden)]
958 pub adapter_provider_path: Option<PathBuf>,
959}
960
961#[derive(Debug, Clone)]
963pub struct SimilarCodeInspectOptions {
964 pub analysis: AnalysisOptions,
967 pub snapshot: fallow_output::SimilarCodeCandidateSnapshot,
969}
970
971#[derive(Debug, Clone, Default)]
973pub struct TraceExportOptions {
974 pub analysis: AnalysisOptions,
976 pub file: String,
978 pub export_name: String,
980}
981
982#[derive(Debug, Clone, Default)]
984pub struct TraceFileOptions {
985 pub analysis: AnalysisOptions,
987 pub file: String,
989}
990
991#[derive(Debug, Clone, Default)]
993pub struct TraceImportPathOptions {
994 pub analysis: AnalysisOptions,
996 pub from: String,
998 pub to: String,
1000 pub eager_only: bool,
1003}
1004
1005#[derive(Debug, Clone, Default)]
1007pub struct TraceErrorOptions {
1008 pub analysis: AnalysisOptions,
1010 pub trace: String,
1012 pub source: String,
1014}
1015
1016#[derive(Debug, Clone, Default)]
1018pub struct TraceDependencyOptions {
1019 pub analysis: AnalysisOptions,
1021 pub package_name: String,
1023 pub usage: Option<DependencyUsageQuery>,
1026}
1027
1028#[derive(Debug, Clone, PartialEq, Eq)]
1030pub enum TraceCloneTarget {
1031 Location {
1033 file: String,
1035 line: usize,
1037 },
1038 Fingerprint(String),
1040}
1041
1042#[derive(Debug, Clone)]
1044pub struct TraceCloneOptions {
1045 pub duplication: DuplicationOptions,
1047 pub target: TraceCloneTarget,
1049}
1050
1051#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1053pub enum ComplexitySort {
1054 #[default]
1056 Cyclomatic,
1057 Cognitive,
1059 Lines,
1061 Severity,
1063}
1064
1065#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1067pub enum OwnershipEmailMode {
1068 Raw,
1070 #[default]
1072 Handle,
1073 Anonymized,
1075 Hash,
1077}
1078
1079#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1081pub enum TargetEffort {
1082 Low,
1084 Medium,
1086 High,
1088}
1089
1090#[derive(Debug, Clone, Default)]
1092pub struct ComplexityOptions {
1093 pub analysis: AnalysisOptions,
1095 pub max_cyclomatic: Option<u16>,
1097 pub max_cognitive: Option<u16>,
1099 pub max_crap: Option<f64>,
1101 pub max_file_lines: Option<u32>,
1104 pub top: Option<usize>,
1106 pub sort: ComplexitySort,
1108 pub complexity_breakdown: bool,
1110 pub complexity: bool,
1112 pub file_scores: bool,
1114 pub coverage_gaps: bool,
1116 pub hotspots: bool,
1118 pub ownership: bool,
1120 pub ownership_emails: Option<OwnershipEmailMode>,
1122 pub targets: bool,
1124 pub css: bool,
1126 pub css_deep: bool,
1128 pub effort: Option<TargetEffort>,
1131 pub score: bool,
1133 pub since: Option<String>,
1135 pub min_commits: Option<u32>,
1137 pub coverage: Option<PathBuf>,
1139 pub coverage_root: Option<PathBuf>,
1141 pub coverage_relocated: bool,
1146}
1147
1148#[derive(Debug, Clone, Copy, Default, PartialEq)]
1150pub struct ComplexityThresholdOverrides {
1151 pub max_cyclomatic: Option<u16>,
1153 pub max_cognitive: Option<u16>,
1155 pub max_crap: Option<f64>,
1157 pub max_file_lines: Option<u32>,
1159}
1160
1161#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1163pub struct ComplexityCoverageInputs<'a> {
1164 pub coverage: Option<&'a Path>,
1166 pub coverage_root: Option<&'a Path>,
1168 pub coverage_relocated: bool,
1171}
1172
1173#[derive(Debug, Clone)]
1175pub struct HealthSectionOptions {
1176 pub output: fallow_types::output_format::OutputFormat,
1178 pub complexity: bool,
1180 pub file_scores: bool,
1182 pub coverage_gaps: bool,
1184 pub hotspots: bool,
1186 pub targets: bool,
1188 pub css: bool,
1190 pub score: bool,
1192 pub score_gate: bool,
1194 pub snapshot_requested: bool,
1196 pub trend: bool,
1198}
1199
1200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1202pub struct DerivedHealthSections {
1203 pub any_section: bool,
1205 pub complexity: bool,
1207 pub file_scores: bool,
1209 pub coverage_gaps: bool,
1211 pub hotspots: bool,
1213 pub targets: bool,
1215 pub css: bool,
1217 pub score: bool,
1219 pub force_full: bool,
1221 pub score_only_output: bool,
1223}
1224
1225#[derive(Debug, Clone)]
1227pub struct ComplexitySectionOptions {
1228 pub complexity: bool,
1230 pub file_scores: bool,
1232 pub coverage_gaps: bool,
1234 pub hotspots: bool,
1236 pub ownership: bool,
1238 pub targets: bool,
1240 pub css: bool,
1242 pub score: bool,
1244}
1245
1246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1248pub struct DerivedComplexityOptions {
1249 pub any_section: bool,
1251 pub complexity: bool,
1253 pub file_scores: bool,
1255 pub coverage_gaps: bool,
1257 pub hotspots: bool,
1259 pub ownership: bool,
1261 pub targets: bool,
1263 pub force_full: bool,
1265 pub score_only_output: bool,
1267 pub score: bool,
1269}
1270
1271#[derive(Debug, Clone, PartialEq)]
1273pub struct ComplexityRunOptions<'a> {
1274 pub thresholds: ComplexityThresholdOverrides,
1276 pub top: Option<usize>,
1278 pub sort: ComplexitySort,
1280 pub complexity_breakdown: bool,
1282 pub sections: DerivedComplexityOptions,
1284 pub ownership_emails: Option<OwnershipEmailMode>,
1286 pub effort: Option<TargetEffort>,
1288 pub css: bool,
1290 pub css_deep: bool,
1292 pub since: Option<&'a str>,
1294 pub min_commits: Option<u32>,
1296 pub coverage_inputs: ComplexityCoverageInputs<'a>,
1298}
1299
1300pub fn configure_global_analysis_pool(threads: usize) -> bool {
1309 fallow_engine::thread_pool::worker_pool_builder(threads)
1310 .build_global()
1311 .is_ok()
1312}
1313
1314#[must_use]
1316pub fn derive_health_sections(options: &HealthSectionOptions) -> DerivedHealthSections {
1317 let score = options.score
1318 || options.score_gate
1319 || options.trend
1320 || matches!(
1321 options.output,
1322 fallow_types::output_format::OutputFormat::Badge
1323 );
1324 let any_section = options.complexity
1325 || options.file_scores
1326 || options.coverage_gaps
1327 || options.hotspots
1328 || options.targets
1329 || score;
1330 let effective_score = if any_section { score } else { true } || options.snapshot_requested;
1331 let force_full = options.snapshot_requested || effective_score;
1332
1333 DerivedHealthSections {
1334 any_section,
1335 complexity: if any_section {
1336 options.complexity
1337 } else {
1338 true
1339 },
1340 file_scores: if any_section {
1341 options.file_scores
1342 } else {
1343 true
1344 } || force_full,
1345 coverage_gaps: if any_section {
1346 options.coverage_gaps
1347 } else {
1348 false
1349 },
1350 hotspots: if any_section { options.hotspots } else { true }
1351 || options.snapshot_requested
1352 || options.trend,
1353 targets: if any_section { options.targets } else { true },
1354 css: options.css,
1355 score: effective_score,
1356 force_full,
1357 score_only_output: is_health_score_only_output(options, score),
1358 }
1359}
1360
1361#[must_use]
1363pub fn derive_complexity_sections(options: &ComplexitySectionOptions) -> DerivedComplexityOptions {
1364 let requested_hotspots = options.hotspots || options.ownership;
1365 let sections = derive_health_sections(&HealthSectionOptions {
1366 output: fallow_types::output_format::OutputFormat::Human,
1367 complexity: options.complexity,
1368 file_scores: options.file_scores,
1369 coverage_gaps: options.coverage_gaps,
1370 hotspots: requested_hotspots,
1371 targets: options.targets,
1372 css: options.css,
1373 score: options.score,
1374 score_gate: false,
1375 snapshot_requested: false,
1376 trend: false,
1377 });
1378
1379 DerivedComplexityOptions {
1380 any_section: sections.any_section,
1381 complexity: sections.complexity,
1382 file_scores: sections.file_scores,
1383 coverage_gaps: sections.coverage_gaps,
1384 hotspots: sections.hotspots,
1385 ownership: options.ownership && sections.hotspots,
1386 targets: sections.targets,
1387 force_full: sections.force_full,
1388 score_only_output: sections.score_only_output,
1389 score: sections.score,
1390 }
1391}
1392
1393#[must_use]
1395pub fn derive_complexity_options(options: &ComplexityOptions) -> DerivedComplexityOptions {
1396 derive_complexity_sections(&complexity_section_options(options))
1397}
1398
1399#[must_use]
1401pub fn derive_complexity_run_options(options: &ComplexityOptions) -> ComplexityRunOptions<'_> {
1402 ComplexityRunOptions {
1403 thresholds: ComplexityThresholdOverrides {
1404 max_cyclomatic: options.max_cyclomatic,
1405 max_cognitive: options.max_cognitive,
1406 max_crap: options.max_crap,
1407 max_file_lines: options.max_file_lines,
1408 },
1409 top: options.top,
1410 sort: options.sort,
1411 complexity_breakdown: options.complexity_breakdown,
1412 sections: derive_complexity_options(options),
1413 ownership_emails: options.ownership_emails,
1414 effort: options.effort,
1415 css: options.css,
1416 css_deep: options.css_deep,
1417 since: options.since.as_deref(),
1418 min_commits: options.min_commits,
1419 coverage_inputs: ComplexityCoverageInputs {
1420 coverage: options.coverage.as_deref(),
1421 coverage_root: options.coverage_root.as_deref(),
1422 coverage_relocated: options.coverage_relocated,
1423 },
1424 }
1425}
1426
1427pub fn validate_complexity_options(options: &ComplexityOptions) -> Result<(), ProgrammaticError> {
1450 if let Some(path) = &options.coverage {
1451 let resolved = fallow_engine::health::scoring::resolve_relative_to_root(
1452 path,
1453 options.analysis.root.as_deref(),
1454 );
1455 if !resolved.exists() {
1456 return Err(ProgrammaticError::new(
1457 format!("coverage path does not exist: {}", resolved.display()),
1458 2,
1459 )
1460 .with_code("FALLOW_INVALID_COVERAGE_PATH")
1461 .with_context("health.coverage"));
1462 }
1463 }
1464 if let Err(message) =
1465 fallow_engine::health::validate_coverage_root_absolute(options.coverage_root.as_deref())
1466 {
1467 return Err(ProgrammaticError::new(message, 2)
1468 .with_code("FALLOW_INVALID_COVERAGE_ROOT")
1469 .with_context("health.coverage_root"));
1470 }
1471
1472 Ok(())
1473}
1474
1475fn complexity_section_options(options: &ComplexityOptions) -> ComplexitySectionOptions {
1476 let ownership = options.ownership || options.ownership_emails.is_some();
1477 let requested_targets = options.targets || options.effort.is_some();
1478 ComplexitySectionOptions {
1479 complexity: options.complexity,
1480 file_scores: options.file_scores,
1481 coverage_gaps: options.coverage_gaps,
1482 hotspots: options.hotspots,
1483 ownership,
1484 targets: requested_targets,
1485 css: options.css,
1486 score: options.score,
1487 }
1488}
1489
1490fn is_health_score_only_output(options: &HealthSectionOptions, score: bool) -> bool {
1491 score
1492 && !options.complexity
1493 && !options.file_scores
1494 && !options.coverage_gaps
1495 && !options.hotspots
1496 && !options.targets
1497 && !options.trend
1498}
1499
1500const fn thresholds_to_engine(
1501 thresholds: ComplexityThresholdOverrides,
1502) -> fallow_engine::health::HealthThresholdOverrides {
1503 fallow_engine::health::HealthThresholdOverrides {
1504 max_cyclomatic: thresholds.max_cyclomatic,
1505 max_cognitive: thresholds.max_cognitive,
1506 max_crap: thresholds.max_crap,
1507 max_file_lines: thresholds.max_file_lines,
1508 }
1509}
1510
1511const fn complexity_sort_to_engine(sort: ComplexitySort) -> fallow_engine::health::HealthSort {
1512 match sort {
1513 ComplexitySort::Severity => fallow_engine::health::HealthSort::Severity,
1514 ComplexitySort::Cyclomatic => fallow_engine::health::HealthSort::Cyclomatic,
1515 ComplexitySort::Cognitive => fallow_engine::health::HealthSort::Cognitive,
1516 ComplexitySort::Lines => fallow_engine::health::HealthSort::Lines,
1517 }
1518}
1519
1520const fn coverage_inputs_to_engine(
1521 coverage_inputs: ComplexityCoverageInputs<'_>,
1522) -> fallow_engine::health::HealthCoverageInputs<'_> {
1523 fallow_engine::health::HealthCoverageInputs {
1524 coverage: coverage_inputs.coverage,
1525 coverage_root: coverage_inputs.coverage_root,
1526 coverage_relocated: coverage_inputs.coverage_relocated,
1527 }
1528}
1529
1530const fn ownership_email_mode_to_config(mode: OwnershipEmailMode) -> EmailMode {
1531 match mode {
1532 OwnershipEmailMode::Raw => EmailMode::Raw,
1533 OwnershipEmailMode::Handle => EmailMode::Handle,
1534 OwnershipEmailMode::Anonymized => EmailMode::Anonymized,
1535 OwnershipEmailMode::Hash => EmailMode::Hash,
1536 }
1537}
1538
1539const fn target_effort_to_output(effort: TargetEffort) -> EffortEstimate {
1540 match effort {
1541 TargetEffort::Low => EffortEstimate::Low,
1542 TargetEffort::Medium => EffortEstimate::Medium,
1543 TargetEffort::High => EffortEstimate::High,
1544 }
1545}
1546
1547#[cfg(test)]
1548mod tests {
1549 use super::*;
1550
1551 #[test]
1552 fn duplication_defaults_match_cli_contract() {
1553 let options = DuplicationOptions::default();
1554 assert!(options.mode.is_none());
1555 assert!(options.min_tokens.is_none());
1556 assert!(options.min_lines.is_none());
1557 assert!(options.min_occurrences.is_none());
1558 }
1559
1560 #[test]
1561 fn programmatic_error_builder_keeps_optional_fields() {
1562 let error = ProgrammaticError::new("boom", 2)
1563 .with_code("FALLOW_TEST")
1564 .with_help("Try again")
1565 .with_context("analysis.root");
1566
1567 assert_eq!(error.message, "boom");
1568 assert_eq!(error.exit_code, 2);
1569 assert_eq!(error.code.as_deref(), Some("FALLOW_TEST"));
1570 assert_eq!(error.help.as_deref(), Some("Try again"));
1571 assert_eq!(error.context.as_deref(), Some("analysis.root"));
1572 }
1573
1574 #[test]
1575 fn dead_code_filters_accept_shared_registry_selectors() {
1576 for (selector, _) in fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS.iter() {
1577 let mut filters = DeadCodeFilters::default();
1578 assert!(
1579 filters.enable_registry_selector(selector),
1580 "{selector} should be accepted"
1581 );
1582 }
1583
1584 let mut filters = DeadCodeFilters::default();
1585 assert!(filters.enable_registry_selector("unused-files"));
1586 assert!(filters.unused_files);
1587 assert!(filters.enable_registry_selector("boundary-violations"));
1588 assert!(filters.boundary_violations);
1589 assert!(!filters.enable_registry_selector("not-a-real-selector"));
1590 }
1591
1592 #[test]
1593 fn default_complexity_options_match_programmatic_health_defaults() {
1594 let derived = derive_complexity_options(&ComplexityOptions::default());
1595
1596 assert!(!derived.any_section);
1597 assert!(derived.complexity);
1598 assert!(derived.file_scores);
1599 assert!(!derived.coverage_gaps);
1600 assert!(derived.hotspots);
1601 assert!(!derived.ownership);
1602 assert!(derived.targets);
1603 assert!(derived.force_full);
1604 assert!(!derived.score_only_output);
1605 assert!(derived.score);
1606 }
1607
1608 #[test]
1609 fn score_only_complexity_options_request_score_only_output() {
1610 let derived = derive_complexity_options(&ComplexityOptions {
1611 score: true,
1612 ..ComplexityOptions::default()
1613 });
1614
1615 assert!(derived.any_section);
1616 assert!(!derived.complexity);
1617 assert!(derived.file_scores);
1618 assert!(!derived.hotspots);
1619 assert!(!derived.targets);
1620 assert!(derived.force_full);
1621 assert!(derived.score_only_output);
1622 assert!(derived.score);
1623 }
1624
1625 #[test]
1626 fn ownership_implies_hotspots_when_requested() {
1627 let derived = derive_complexity_options(&ComplexityOptions {
1628 ownership: true,
1629 ..ComplexityOptions::default()
1630 });
1631
1632 assert!(derived.any_section);
1633 assert!(derived.hotspots);
1634 assert!(derived.ownership);
1635 assert!(!derived.targets);
1636 }
1637
1638 #[test]
1639 fn complexity_run_options_normalize_public_api_options() {
1640 let options = ComplexityOptions {
1641 max_cyclomatic: Some(42),
1642 max_cognitive: Some(21),
1643 max_crap: Some(18.5),
1644 top: Some(7),
1645 sort: ComplexitySort::Severity,
1646 complexity_breakdown: true,
1647 ownership_emails: Some(OwnershipEmailMode::Hash),
1648 effort: Some(TargetEffort::High),
1649 coverage: Some(PathBuf::from("coverage/coverage-final.json")),
1650 coverage_root: Some(PathBuf::from("/ci/workspace")),
1651 since: Some("30d".to_string()),
1652 min_commits: Some(4),
1653 ..ComplexityOptions::default()
1654 };
1655
1656 let run = derive_complexity_run_options(&options);
1657
1658 assert_eq!(run.thresholds.max_cyclomatic, Some(42));
1659 assert_eq!(run.thresholds.max_cognitive, Some(21));
1660 assert_eq!(run.thresholds.max_crap, Some(18.5));
1661 assert_eq!(run.top, Some(7));
1662 assert!(matches!(run.sort, ComplexitySort::Severity));
1663 assert!(run.complexity_breakdown);
1664 assert!(run.sections.hotspots);
1665 assert!(run.sections.ownership);
1666 assert!(run.sections.targets);
1667 assert!(matches!(
1668 run.ownership_emails,
1669 Some(OwnershipEmailMode::Hash)
1670 ));
1671 assert!(matches!(run.effort, Some(TargetEffort::High)));
1672 assert_eq!(run.since, Some("30d"));
1673 assert_eq!(run.min_commits, Some(4));
1674 assert_eq!(run.coverage_inputs.coverage, options.coverage.as_deref());
1675 assert_eq!(
1676 run.coverage_inputs.coverage_root,
1677 options.coverage_root.as_deref()
1678 );
1679 }
1680
1681 #[test]
1682 fn complexity_options_validation_accepts_existing_coverage_path_and_absolute_root() {
1683 let dir = tempfile::tempdir().expect("tempdir");
1684 let coverage = dir.path().join("coverage-final.json");
1685 std::fs::write(&coverage, "{}").expect("coverage fixture");
1686
1687 let result = validate_complexity_options(&ComplexityOptions {
1688 coverage: Some(coverage),
1689 coverage_root: Some(PathBuf::from("/ci/workspace")),
1690 ..ComplexityOptions::default()
1691 });
1692
1693 assert!(result.is_ok());
1694 }
1695
1696 #[test]
1697 fn complexity_options_validation_keeps_missing_coverage_error_contract() {
1698 let err = validate_complexity_options(&ComplexityOptions {
1699 coverage: Some(PathBuf::from("/missing/coverage-final.json")),
1700 ..ComplexityOptions::default()
1701 })
1702 .expect_err("missing coverage path should fail");
1703
1704 assert_eq!(err.exit_code, 2);
1705 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1706 assert_eq!(err.context.as_deref(), Some("health.coverage"));
1707 }
1708
1709 #[test]
1710 fn complexity_options_validation_keeps_relative_coverage_root_error_contract() {
1711 let err = validate_complexity_options(&ComplexityOptions {
1712 coverage_root: Some(PathBuf::from("coverage")),
1713 ..ComplexityOptions::default()
1714 })
1715 .expect_err("relative coverage root should fail");
1716
1717 assert_eq!(err.exit_code, 2);
1718 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_ROOT"));
1719 assert_eq!(err.context.as_deref(), Some("health.coverage_root"));
1720 }
1721
1722 #[test]
1726 fn complexity_options_validation_resolves_relative_coverage_against_root() {
1727 let dir = tempfile::tempdir().expect("tempdir");
1728 std::fs::create_dir_all(dir.path().join("artifacts")).expect("artifacts dir");
1729 std::fs::write(dir.path().join("artifacts/coverage-final.json"), "{}")
1730 .expect("coverage fixture");
1731 let relative = PathBuf::from("artifacts/coverage-final.json");
1732 assert!(
1733 !relative.exists(),
1734 "the fixture must not also exist under the test cwd"
1735 );
1736
1737 let result = validate_complexity_options(&ComplexityOptions {
1738 analysis: AnalysisOptions {
1739 root: Some(dir.path().to_path_buf()),
1740 ..AnalysisOptions::default()
1741 },
1742 coverage: Some(relative.clone()),
1743 ..ComplexityOptions::default()
1744 });
1745 assert!(result.is_ok(), "{result:?}");
1746
1747 let err = validate_complexity_options(&ComplexityOptions {
1748 analysis: AnalysisOptions {
1749 root: Some(dir.path().join("elsewhere")),
1750 ..AnalysisOptions::default()
1751 },
1752 coverage: Some(relative),
1753 ..ComplexityOptions::default()
1754 })
1755 .expect_err("the path does not exist under the other root");
1756 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1757 assert!(
1758 err.message.contains("elsewhere"),
1759 "the message names the resolved path: {}",
1760 err.message
1761 );
1762 }
1763
1764 #[test]
1765 fn default_health_sections_match_full_health_output() {
1766 let derived = derive_health_sections(&HealthSectionOptions {
1767 output: fallow_types::output_format::OutputFormat::Human,
1768 complexity: false,
1769 file_scores: false,
1770 coverage_gaps: false,
1771 hotspots: false,
1772 targets: false,
1773 css: false,
1774 score: false,
1775 score_gate: false,
1776 snapshot_requested: false,
1777 trend: false,
1778 });
1779
1780 assert!(!derived.any_section);
1781 assert!(derived.complexity);
1782 assert!(derived.file_scores);
1783 assert!(!derived.coverage_gaps);
1784 assert!(derived.hotspots);
1785 assert!(derived.targets);
1786 assert!(derived.score);
1787 assert!(derived.force_full);
1788 assert!(!derived.score_only_output);
1789 }
1790
1791 #[test]
1792 fn health_score_gate_requests_score_only_output() {
1793 let derived = derive_health_sections(&HealthSectionOptions {
1794 output: fallow_types::output_format::OutputFormat::Human,
1795 complexity: false,
1796 file_scores: false,
1797 coverage_gaps: false,
1798 hotspots: false,
1799 targets: false,
1800 css: false,
1801 score: false,
1802 score_gate: true,
1803 snapshot_requested: false,
1804 trend: false,
1805 });
1806
1807 assert!(derived.any_section);
1808 assert!(!derived.complexity);
1809 assert!(derived.file_scores);
1810 assert!(!derived.hotspots);
1811 assert!(!derived.targets);
1812 assert!(derived.score);
1813 assert!(derived.force_full);
1814 assert!(derived.score_only_output);
1815 }
1816
1817 #[test]
1818 fn health_snapshot_keeps_full_hidden_inputs_without_section_request() {
1819 let derived = derive_health_sections(&HealthSectionOptions {
1820 output: fallow_types::output_format::OutputFormat::Human,
1821 complexity: false,
1822 file_scores: false,
1823 coverage_gaps: false,
1824 hotspots: false,
1825 targets: false,
1826 css: true,
1827 score: false,
1828 score_gate: false,
1829 snapshot_requested: true,
1830 trend: false,
1831 });
1832
1833 assert!(!derived.any_section);
1834 assert!(derived.css);
1835 assert!(derived.file_scores);
1836 assert!(derived.hotspots);
1837 assert!(derived.score);
1838 assert!(derived.force_full);
1839 }
1840}
1841
1842mod shared_state_explain;