1#![warn(missing_docs)]
10#![cfg_attr(
11 test,
12 allow(
13 clippy::expect_used,
14 reason = "tests use expect to keep fixture setup concise"
15 )
16)]
17
18use std::path::{Path, PathBuf};
19use std::sync::Arc;
20use std::sync::atomic::AtomicBool;
21
22use fallow_config::EmailMode;
23use fallow_output::EffortEstimate;
24use serde::Serialize;
25
26mod analysis_context;
27mod audit_complexity;
28pub mod audit_keys;
32pub mod audit_output;
33pub mod audit_run;
34pub mod combined_output;
35pub mod compact_output;
38pub mod coverage;
39pub mod dead_code_codeclimate;
40pub mod dead_code_sarif;
41pub mod decision_surface;
42pub mod dependency_deltas;
43pub mod diff_risk;
44pub mod doctor;
45pub mod dupes_output;
46pub mod editor;
47pub mod explain;
48pub mod grouped_output;
49pub mod health_codeclimate;
50mod health_groups_markdown;
51pub mod json_output;
52pub mod list_output;
53mod list_runtime;
54pub mod markdown_output;
57pub mod mutation;
58mod next_steps;
59pub mod output_contracts;
60pub mod ownership;
61pub mod review_deltas;
62pub mod routing;
63pub mod runtime;
64mod runtime_json;
65mod runtime_output;
66pub mod sarif_output;
67pub mod schemas;
70pub mod security_output;
71pub mod similar_code;
73mod type_aware;
74pub use analysis_context::{ProgrammaticAnalysisContext, resolve_programmatic_analysis_context};
75pub use audit_output::{
76 AuditAttribution, AuditCodeClimateOutputInput, AuditJsonHeaderInput, AuditJsonOutputInput,
77 AuditSarifOutputInput, AuditSummary, AuditVerdict, attach_audit_diff_risk_attribution,
78 attach_audit_duplication_demotion_attribution, attach_audit_styling_attribution,
79 attach_audit_wire_attribution, build_audit_codeclimate, build_audit_codeclimate_issues,
80 build_audit_header_json, build_audit_header_map, build_audit_sarif,
81 build_diff_risk_codeclimate, build_review_brief_header, serialize_audit_json,
82};
83pub use combined_output::{
84 CombinedCheckJsonSection, CombinedJsonOutputInput, serialize_combined_dupes_json,
85 serialize_combined_health_json, serialize_combined_json,
86};
87pub use compact_output::{
88 build_compact_lines, build_diff_risk_compact_lines, build_duplication_compact_lines,
89 build_grouped_compact_lines, build_health_compact_lines,
90};
91pub use coverage::{
92 CoverageInputError, CoverageInputSource, CoverageInputs, resolve_coverage_inputs,
93};
94pub use dead_code_codeclimate::build_codeclimate;
95pub use dead_code_sarif::build_sarif;
96pub use doctor::{DoctorOptions, run_doctor, run_doctor_with_cache_dir};
97pub use dupes_output::{
98 AttributedCloneGroup, AttributedCloneGroupFinding, AttributedInstance, CloneDemotionReason,
99 CloneFamilyFinding, CloneGroupFinding, CombinedDupesSection, DupesReportPayload,
100 DuplicationGroup, DuplicationGrouping, build_duplication_codeclimate,
101 set_duplication_audit_attribution,
102};
103pub use editor::{
104 ChangedFilesError, EditorAnalysisOutput, EditorAnalysisResults, EditorAnalysisSession,
105 EditorCloneFamily, EditorCloneFingerprintSet, EditorCloneGroup, EditorCloneInstance,
106 EditorDeadCodeAnalysisOutput, EditorDuplicationReport, EditorDuplicationStats,
107 EditorInlineComplexityExceeded, EditorInlineComplexityFinding, EditorMirroredDirectory,
108 EditorProjectAnalysisOutput, EditorRefactoringKind, EditorRefactoringSuggestion,
109 EditorSessionParseCounts, collect_inline_complexity, editor_duplicates, editor_extract,
110 editor_results, editor_security, editor_suppress, filter_inline_complexity_by_change_scope,
111 filter_inline_complexity_by_changed_files, resolve_git_toplevel,
112 try_get_changed_files_with_toplevel,
113};
114pub use explain::{
115 AUDIT_RULES, CHECK_RULES, DUPES_RULES, FLAGS_RULES, HEALTH_RULES, RuleDef, RuleGuide,
116 SECURITY_RULES, all_rules, bare_rule_id, coverage_analyze_meta, coverage_setup_meta,
117 explain_issue_type, rule_by_id, rule_by_token, rule_command, rule_docs_url, rule_guide,
118 rule_severity_key, security_meta, serialize_explain_programmatic_json, unknown_explain_error,
119};
120pub use fallow_config::levenshtein::closest_match;
121pub use fallow_config::{AuditGate, AuditWorsened, HealthConfig, TypeAwareRequire};
122pub use fallow_engine::change_scope::{
125 ChangeScope, ChangeScopeOwner, ChangeScopeRequest, first_package_baselines,
126 package_baseline_statuses,
127};
128pub use fallow_engine::package_baselines::{PackageBaselineError, PackageChangeScope};
130pub use fallow_engine::thread_pool::{WORKER_STACK_SIZE, register_thread_stack};
137pub use fallow_engine::warm_parse;
143pub use fallow_output::PackageBaselineStatus;
145pub use fallow_output::serialize_similar_code_json_output;
146pub use fallow_types::trace::{
147 CloneTrace, DependencyTrace, ExportReference, ExportTrace, FileTrace, ReExportChain,
148 TracedCloneGroup, TracedExport, TracedReExport,
149};
150pub use fallow_types::trace_usage::{
151 DependencyUsage, DependencyUsageQuery, SitePageRequest, UsageQueryError,
152};
153pub use grouped_output::{
154 ResultGroup, UNOWNED_GROUP_LABEL, build_duplication_grouping_with, group_analysis_results_with,
155 health_signal_header_part, largest_clone_group_owner_with,
156};
157pub use health_codeclimate::build_health_codeclimate;
158pub use health_groups_markdown::build_health_groups_markdown;
159pub use json_output::{
160 CheckJsonExtraOutputs, CheckJsonOutputInput, CheckJsonPayloadInput, DuplicationJsonOutputInput,
161 GroupedCheckJsonOutputInput, GroupedDuplicationJsonOutputInput, serialize_check_json,
162 serialize_check_json_payload, serialize_duplication_json, serialize_grouped_check_json,
163 serialize_grouped_duplication_json,
164};
165pub use list_output::{
166 ListJsonEnvelope, ListJsonOutputInput, build_list_json_output, serialize_list_json_output,
167};
168pub use list_runtime::{
169 BoundaryData, ListBoundariesOptions, ListBoundariesProgrammaticOutput, LogicalGroupInfo,
170 ProjectInfoOptions, ProjectInfoProgrammaticOutput, RuleInfo, ZoneInfo, boundary_data_to_output,
171 compute_boundary_data, run_list_boundaries, run_project_info,
172 serialize_list_boundaries_programmatic_json, serialize_project_info_programmatic_json,
173};
174pub use markdown_output::{
175 ComplexityListing, build_diff_risk_markdown, build_duplication_markdown,
176 build_grouped_markdown, build_health_markdown, build_markdown, build_walkthrough_markdown,
177};
178pub use mutation::{
179 MutationProgress, MutationProgressSink, MutationRunOptions, MutationRunScope,
180 apply_mutation_verdicts, validate_mutation_verdicts,
181};
182pub use output_contracts::{
183 AuditOutput, BoundariesListLogicalGroup, BoundariesListRule, BoundariesListZone,
184 BoundariesListing, CombinedOutput, FallowOutput, ImpactOutput, ListBoundariesOutput,
185 ListEntryPointOutput, ListOutput, ListPluginOutput, ReviewBriefWireOutput, SecurityGate,
186 SecurityOutput, SecurityOutputConfig, SecuritySummaryOutput, SimilarCodeCandidateSnapshot,
187 SimilarCodeOutput, TraceOutput, WorkspacesOutput,
188};
189pub use runtime::TYPE_AWARE_CONFIG_UNSUPPORTED;
190pub use runtime::{
191 AUDIT_CONFIG_BASELINE_UNSUPPORTED, ArchitectureOutput, ArchitectureProgrammaticOutput,
192 AuditProgrammaticKeySnapshot, AuditProgrammaticOutput, BoundaryViolationsOutput,
193 BoundaryViolationsProgrammaticOutput, CircularDependenciesOutput,
194 CircularDependenciesProgrammaticOutput, CombinedProgrammaticOutput, DeadCodeOutput,
195 DeadCodeProgrammaticOutput, DecisionSurfaceProgrammaticOutput, DuplicationOutput,
196 DuplicationProgrammaticOutput, EngineHealthRunner, FeatureFlagsOutput,
197 FeatureFlagsProgrammaticOutput, HealthJsonReportInput, HealthProgrammaticOutput,
198 ProgrammaticHealthAnalysis, ProgrammaticHealthNextStepFacts, ProgrammaticHealthRun,
199 ProgrammaticHealthRunner, TraceClassMemberOutput, TraceCloneBenchmarkResult, TraceCloneOutput,
200 TraceCloneProgrammaticOutput, TraceDependencyOutput, TraceDependencyProgrammaticOutput,
201 TraceErrorOutput, TraceErrorProgrammaticOutput, TraceExportOutput,
202 TraceExportProgrammaticOutput, TraceExportTargetOutput, TraceFileOutput,
203 TraceFileProgrammaticOutput, TraceImportPathOutput, TraceImportPathProgrammaticOutput,
204 benchmark_trace_clone_compact_json, benchmark_trace_graph_family_compact_json,
205 inspect_similar_code, load_health_config, parse_similar_code_candidate_snapshot, plan_mutation,
206 review_similar_code, run_architecture, run_audit, run_boundary_violations,
207 run_circular_dependencies, run_combined, run_complexity_with_runner, run_dead_code,
208 run_dead_code_with_baseline, run_decision_surface, run_duplication, run_feature_flags,
209 run_health, run_health_with_runner, run_mutation, run_mutation_with_progress, run_similar_code,
210 run_trace_clone, run_trace_dependency, run_trace_error, run_trace_export, run_trace_file,
211 run_trace_import_path, select_similar_code_candidate_snapshot, serialize_health_report_json,
212};
213pub use runtime_json::{
214 serialize_architecture_programmatic_json, serialize_audit_programmatic_json,
215 serialize_boundary_violations_programmatic_json,
216 serialize_circular_dependencies_programmatic_json, serialize_combined_programmatic_json,
217 serialize_dead_code_programmatic_json, serialize_decision_surface_programmatic_json,
218 serialize_duplication_programmatic_json, serialize_feature_flags_programmatic_json,
219 serialize_health_programmatic_json, serialize_trace_clone_programmatic_json,
220 serialize_trace_dependency_programmatic_json, serialize_trace_error_programmatic_json,
221 serialize_trace_export_programmatic_json, serialize_trace_file_programmatic_json,
222 serialize_trace_import_path_programmatic_json,
223};
224pub use sarif_output::{
225 annotate_sarif_results, build_duplication_sarif, build_grouped_duplication_sarif,
226 build_health_sarif,
227};
228pub use security_output::SecurityGateMode;
229pub use type_aware::{
230 DEFAULT_BACKEND_FAMILY as DEFAULT_TYPE_AWARE_BACKEND_FAMILY, SemanticCouplingOutcome,
231 SemanticDeadCodeOutcome, SemanticInspectOutcome, TypeAwareError, TypeAwareFileChanges,
232 TypeAwareOutcome, TypeAwareSession, TypeAwareStatus, discard_unverified_semantic_candidates,
233 inspect_symbol as inspect_type_aware_symbol, merge_type_aware_meta,
234 refine_configured_dead_code_results as refine_type_aware_results_with_config,
235 shutdown_type_aware_sidecars, status as type_aware_status,
236 symbol_impact as run_type_aware_symbol_impact, symbol_impact as type_aware_symbol_impact,
237 terminate_active_type_aware_sidecars, trace_symbol as run_type_aware_symbol_trace,
238 trace_symbol as trace_type_aware_symbol, type_coupling as analyze_type_coupling,
239};
240
241pub const COMMON_ANALYSIS_OPTION_FLAGS: &[&str] = &[
248 "root",
249 "config",
250 "no-cache",
251 "threads",
252 "changed-since",
253 "diff-file",
254 "production",
255 "workspace",
256 "changed-workspaces",
257 "explain",
258 "allow-remote-extends",
259];
260
261#[derive(Debug, Clone, Serialize)]
263pub struct ProgrammaticError {
264 pub message: String,
266 pub exit_code: u8,
268 pub code: Option<String>,
270 pub help: Option<String>,
272 pub context: Option<String>,
274}
275
276impl ProgrammaticError {
277 #[must_use]
280 pub fn new(message: impl Into<String>, exit_code: u8) -> Self {
281 Self {
282 message: message.into(),
283 exit_code,
284 code: None,
285 help: None,
286 context: None,
287 }
288 }
289
290 #[must_use]
292 pub fn with_help(mut self, help: impl Into<String>) -> Self {
293 self.help = Some(help.into());
294 self
295 }
296
297 #[must_use]
300 pub fn with_code(mut self, code: impl Into<String>) -> Self {
301 self.code = Some(code.into());
302 self
303 }
304
305 #[must_use]
308 pub fn with_context(mut self, context: impl Into<String>) -> Self {
309 self.context = Some(context.into());
310 self
311 }
312}
313
314impl std::fmt::Display for ProgrammaticError {
315 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
316 write!(f, "{}", self.message)
317 }
318}
319
320impl std::error::Error for ProgrammaticError {}
321
322#[derive(Debug, Clone, Default)]
324pub struct AnalysisOptions {
325 pub root: Option<PathBuf>,
328 pub config_path: Option<PathBuf>,
330 pub allow_remote_extends: bool,
332 pub no_cache: bool,
334 pub threads: Option<usize>,
336 pub diff_file: Option<PathBuf>,
348 pub ambient_diff_file: Option<PathBuf>,
356 pub production: bool,
359 pub production_override: Option<bool>,
362 pub changed_since: Option<String>,
367 pub ambient_changed_since: Option<String>,
375 pub no_package_baselines: bool,
379 pub workspace: Option<Vec<String>>,
381 pub changed_workspaces: Option<String>,
383 pub explain: bool,
385 pub type_aware: TypeAwareOptions,
388 pub cancellation: Option<Arc<AtomicBool>>,
418}
419
420#[derive(Debug, Clone, Default, PartialEq, Eq)]
422pub struct TypeAwareOptions {
423 pub enabled: Option<bool>,
430 pub projects: Vec<PathBuf>,
433 pub require: fallow_config::TypeAwareRequire,
435}
436
437impl TypeAwareOptions {
438 #[must_use]
440 pub const fn requested(&self) -> bool {
441 matches!(self.enabled, Some(true))
442 }
443}
444
445#[derive(Debug, Clone, Default, PartialEq, Eq)]
450pub struct DeadCodeFilters {
451 pub unused_files: bool,
453 pub unused_exports: bool,
455 pub unused_deps: bool,
457 pub unused_types: bool,
459 pub private_type_leaks: bool,
461 pub deprecated_exports_in_use: bool,
463 pub unused_enum_members: bool,
465 pub unused_class_members: bool,
467 pub unused_namespace_members: bool,
469 pub unused_store_members: bool,
471 pub unprovided_injects: bool,
473 pub unrendered_components: bool,
475 pub unused_component_props: bool,
477 pub absent_component_props: bool,
479 pub unused_component_emits: bool,
481 pub unused_component_inputs: bool,
483 pub unused_component_outputs: bool,
485 pub unused_svelte_events: bool,
487 pub unused_effect_layers: bool,
489 pub unused_tagged_errors: bool,
491 pub unproduced_catch_tags: bool,
493 pub unused_server_actions: bool,
495 pub unused_load_data_keys: bool,
497 pub unresolved_imports: bool,
499 pub unlisted_deps: bool,
501 pub unlisted_binaries: bool,
503 pub duplicate_exports: bool,
505 pub duplicate_export_aliases: bool,
507 pub circular_deps: bool,
509 pub re_export_cycles: bool,
511 pub package_cycles: bool,
513 pub boundary_violations: bool,
515 pub policy_violations: bool,
517 pub stale_suppressions: bool,
519 pub unused_catalog_entries: bool,
521 pub empty_catalog_groups: bool,
523 pub unresolved_catalog_references: bool,
525 pub unused_dependency_overrides: bool,
527 pub misconfigured_dependency_overrides: bool,
529}
530
531impl DeadCodeFilters {
532 pub(crate) fn reports_dependency_findings(&self) -> bool {
536 !self.any_active() || self.unused_deps || self.unlisted_deps
537 }
538
539 fn any_active(&self) -> bool {
540 self.unused_files
541 || self.unused_exports
542 || self.unused_deps
543 || self.unused_types
544 || self.private_type_leaks
545 || self.deprecated_exports_in_use
546 || self.unused_enum_members
547 || self.unused_class_members
548 || self.unused_namespace_members
549 || self.unused_store_members
550 || self.unprovided_injects
551 || self.unrendered_components
552 || self.unused_component_props
553 || self.absent_component_props
554 || self.unused_component_emits
555 || self.unused_component_inputs
556 || self.unused_component_outputs
557 || self.unused_svelte_events
558 || self.unused_effect_layers
559 || self.unused_tagged_errors
560 || self.unproduced_catch_tags
561 || self.unused_server_actions
562 || self.unused_load_data_keys
563 || self.unresolved_imports
564 || self.unlisted_deps
565 || self.unlisted_binaries
566 || self.duplicate_exports
567 || self.duplicate_export_aliases
568 || self.circular_deps
569 || self.re_export_cycles
570 || self.package_cycles
571 || self.boundary_violations
572 || self.policy_violations
573 || self.stale_suppressions
574 || self.unused_catalog_entries
575 || self.empty_catalog_groups
576 || self.unresolved_catalog_references
577 || self.unused_dependency_overrides
578 || self.misconfigured_dependency_overrides
579 }
580
581 pub fn enable_registry_selector(&mut self, selector: &str) -> bool {
587 let Some(flag) = fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS
588 .iter()
589 .find_map(|&(name, flag)| (name == selector).then_some(flag))
590 else {
591 return false;
592 };
593 self.enable_cli_filter_flag(flag);
594 true
595 }
596
597 pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
599 fallow_engine::requested_rule_off::explicit_filter_flags(|flag| {
600 let mut enabled = self.clone();
601 enabled.enable_cli_filter_flag(flag);
602 enabled == *self
603 })
604 }
605
606 fn enable_cli_filter_flag(&mut self, flag: &str) {
607 match flag {
608 "--unused-files" => self.unused_files = true,
609 "--unused-exports" => self.unused_exports = true,
610 "--unused-types" => self.unused_types = true,
611 "--private-type-leaks" => self.private_type_leaks = true,
612 "--deprecated-exports-in-use" => self.deprecated_exports_in_use = true,
613 "--unused-deps" => self.unused_deps = true,
614 "--unused-enum-members" => self.unused_enum_members = true,
615 "--unused-class-members" => self.unused_class_members = true,
616 "--unused-namespace-members" => self.unused_namespace_members = true,
617 "--unused-store-members" => self.unused_store_members = true,
618 "--unprovided-injects" => self.unprovided_injects = true,
619 "--unrendered-components" => self.unrendered_components = true,
620 "--unused-component-props" => self.unused_component_props = true,
621 "--absent-component-props" => self.absent_component_props = true,
622 "--unused-component-emits" => self.unused_component_emits = true,
623 "--unused-component-inputs" => self.unused_component_inputs = true,
624 "--unused-component-outputs" => self.unused_component_outputs = true,
625 "--unused-svelte-events" => self.unused_svelte_events = true,
626 "--unused-effect-layers" => self.unused_effect_layers = true,
627 "--unused-tagged-errors" => self.unused_tagged_errors = true,
628 "--unproduced-catch-tags" => self.unproduced_catch_tags = true,
629 "--unused-server-actions" => self.unused_server_actions = true,
630 "--unused-load-data-keys" => self.unused_load_data_keys = true,
631 "--unresolved-imports" => self.unresolved_imports = true,
632 "--unlisted-deps" => self.unlisted_deps = true,
633 "--unlisted-binaries" => self.unlisted_binaries = true,
634 "--duplicate-exports" => self.duplicate_exports = true,
635 "--duplicate-export-aliases" => self.duplicate_export_aliases = true,
636 "--circular-deps" => self.circular_deps = true,
637 "--re-export-cycles" => self.re_export_cycles = true,
638 "--package-cycles" => self.package_cycles = true,
639 "--boundary-violations" => self.boundary_violations = true,
640 "--policy-violations" => self.policy_violations = true,
641 "--stale-suppressions" => self.stale_suppressions = true,
642 "--unused-catalog-entries" => self.unused_catalog_entries = true,
643 "--empty-catalog-groups" => self.empty_catalog_groups = true,
644 "--unresolved-catalog-references" => self.unresolved_catalog_references = true,
645 "--unused-dependency-overrides" => self.unused_dependency_overrides = true,
646 "--misconfigured-dependency-overrides" => {
647 self.misconfigured_dependency_overrides = true;
648 }
649 _ => unreachable!("registry emitted unsupported dead-code filter flag: {flag}"),
650 }
651 }
652}
653
654#[derive(Debug, Clone, Default)]
656pub struct DeadCodeOptions {
657 pub analysis: AnalysisOptions,
659 pub filters: DeadCodeFilters,
661 pub files: Vec<PathBuf>,
663 pub include_entry_exports: bool,
665 pub show_cascade: bool,
667 pub finding_ids: Vec<String>,
672}
673
674#[derive(Debug, Clone, Default)]
680pub struct ArchitectureOptions {
681 pub analysis: AnalysisOptions,
683 pub files: Vec<PathBuf>,
685 pub cycles: bool,
688 pub boundaries: bool,
690 pub policy: bool,
692}
693
694impl ArchitectureOptions {
695 #[must_use]
697 pub fn dead_code_filters(&self) -> DeadCodeFilters {
698 let all = !(self.cycles || self.boundaries || self.policy);
699 DeadCodeFilters {
700 circular_deps: self.cycles || all,
701 re_export_cycles: self.cycles || all,
702 package_cycles: self.cycles || all,
703 boundary_violations: self.boundaries || all,
704 policy_violations: self.policy || all,
705 ..DeadCodeFilters::default()
706 }
707 }
708
709 pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
712 fallow_engine::requested_rule_off::architecture_requested_flags(
713 self.cycles,
714 self.boundaries,
715 self.policy,
716 )
717 }
718
719 #[must_use]
721 pub fn dead_code_options(&self) -> DeadCodeOptions {
722 DeadCodeOptions {
723 analysis: self.analysis.clone(),
724 filters: self.dead_code_filters(),
725 files: self.files.clone(),
726 include_entry_exports: false,
727 show_cascade: false,
728 finding_ids: Vec::new(),
729 }
730 }
731}
732
733#[derive(Debug, Clone, Default)]
735pub struct AuditOptions {
736 pub analysis: AnalysisOptions,
738 pub base: Option<String>,
741 pub production: bool,
743 pub production_dead_code: Option<bool>,
745 pub production_health: Option<bool>,
747 pub production_dupes: Option<bool>,
750 pub dead_code: Option<bool>,
754 pub health: Option<bool>,
757 pub duplication: Option<bool>,
760 pub css: Option<bool>,
763 pub css_deep: Option<bool>,
766 pub gate: Option<fallow_config::AuditGate>,
769 pub worsened: Option<fallow_config::AuditWorsened>,
772 pub max_crap: Option<f64>,
774 pub coverage: Option<PathBuf>,
776 pub coverage_root: Option<PathBuf>,
778 pub include_entry_exports: bool,
780 pub show_cascade: bool,
782 pub runtime_coverage: Option<PathBuf>,
784 pub min_invocations_hot: u64,
786}
787
788#[derive(Debug, Clone)]
790pub struct CombinedOptions {
791 pub analysis: AnalysisOptions,
793 pub dead_code: bool,
795 pub duplication: bool,
797 pub health: bool,
799 pub include_entry_exports: bool,
801 pub show_cascade: bool,
803 pub duplication_options: DuplicationOptions,
805 pub health_options: ComplexityOptions,
807}
808
809impl Default for CombinedOptions {
810 fn default() -> Self {
811 Self {
812 analysis: AnalysisOptions::default(),
813 dead_code: true,
814 duplication: true,
815 health: true,
816 include_entry_exports: false,
817 show_cascade: false,
818 duplication_options: DuplicationOptions::default(),
819 health_options: ComplexityOptions::default(),
820 }
821 }
822}
823
824#[derive(Debug, Clone, Default)]
826pub struct DecisionSurfaceOptions {
827 pub analysis: AnalysisOptions,
829 pub base: Option<String>,
832 pub max_decisions: Option<usize>,
834}
835
836#[derive(Debug, Clone, Default)]
838pub struct FeatureFlagsOptions {
839 pub analysis: AnalysisOptions,
841 pub top: Option<usize>,
844 pub retirement: Option<FeatureFlagsRetirementOptions>,
846}
847
848#[derive(Debug, Clone, Default)]
851pub struct FeatureFlagsRetirementOptions {
852 pub flag_age: fallow_types::flag_retirement::FlagAgeMode,
854 pub flag_state: Option<std::path::PathBuf>,
856 pub reasons: Vec<fallow_types::flag_retirement::RetirementReason>,
858 pub sort: fallow_engine::flag_retirement::RetirementSort,
860 pub min_age_days: Option<u64>,
862 pub max_flag_age: Option<u64>,
864}
865
866#[derive(Debug, Clone, Copy, Default)]
868pub enum DuplicationMode {
869 Strict,
872 #[default]
874 Mild,
875 Weak,
877 Semantic,
880}
881
882#[derive(Debug, Clone, Default)]
884pub struct DuplicationOptions {
885 pub analysis: AnalysisOptions,
887 pub mode: Option<DuplicationMode>,
889 pub near: Option<bool>,
892 pub min_tokens: Option<usize>,
894 pub min_lines: Option<usize>,
896 pub min_occurrences: Option<usize>,
899 pub threshold: Option<f64>,
902 pub skip_local: Option<bool>,
905 pub ignore_symlinks: Option<bool>,
908 pub cross_language: Option<bool>,
910 pub ignore_imports: Option<bool>,
913 pub top: Option<usize>,
915 pub include_fragments: Option<bool>,
919}
920
921#[derive(Debug, Clone, Default)]
923pub struct SimilarCodeOptions {
924 pub analysis: AnalysisOptions,
926 pub threshold: Option<f64>,
928 pub min_lines: Option<usize>,
931 pub top: Option<usize>,
933 pub files: Vec<PathBuf>,
937 #[doc(hidden)]
942 pub adapter_provider_path: Option<PathBuf>,
943}
944
945#[derive(Debug, Clone)]
947pub struct SimilarCodeInspectOptions {
948 pub analysis: AnalysisOptions,
951 pub snapshot: fallow_output::SimilarCodeCandidateSnapshot,
953}
954
955#[derive(Debug, Clone, Default)]
957pub struct TraceExportOptions {
958 pub analysis: AnalysisOptions,
960 pub file: String,
962 pub export_name: String,
964}
965
966#[derive(Debug, Clone, Default)]
968pub struct TraceFileOptions {
969 pub analysis: AnalysisOptions,
971 pub file: String,
973}
974
975#[derive(Debug, Clone, Default)]
977pub struct TraceImportPathOptions {
978 pub analysis: AnalysisOptions,
980 pub from: String,
982 pub to: String,
984 pub eager_only: bool,
987}
988
989#[derive(Debug, Clone, Default)]
991pub struct TraceErrorOptions {
992 pub analysis: AnalysisOptions,
994 pub trace: String,
996 pub source: String,
998}
999
1000#[derive(Debug, Clone, Default)]
1002pub struct TraceDependencyOptions {
1003 pub analysis: AnalysisOptions,
1005 pub package_name: String,
1007 pub usage: Option<DependencyUsageQuery>,
1010}
1011
1012#[derive(Debug, Clone, PartialEq, Eq)]
1014pub enum TraceCloneTarget {
1015 Location {
1017 file: String,
1019 line: usize,
1021 },
1022 Fingerprint(String),
1024}
1025
1026#[derive(Debug, Clone)]
1028pub struct TraceCloneOptions {
1029 pub duplication: DuplicationOptions,
1031 pub target: TraceCloneTarget,
1033}
1034
1035#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1037pub enum ComplexitySort {
1038 #[default]
1040 Cyclomatic,
1041 Cognitive,
1043 Lines,
1045 Severity,
1047}
1048
1049#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1051pub enum OwnershipEmailMode {
1052 Raw,
1054 #[default]
1056 Handle,
1057 Anonymized,
1059 Hash,
1061}
1062
1063#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1065pub enum TargetEffort {
1066 Low,
1068 Medium,
1070 High,
1072}
1073
1074#[derive(Debug, Clone, Default)]
1076pub struct ComplexityOptions {
1077 pub analysis: AnalysisOptions,
1079 pub max_cyclomatic: Option<u16>,
1081 pub max_cognitive: Option<u16>,
1083 pub max_crap: Option<f64>,
1085 pub max_file_lines: Option<u32>,
1088 pub top: Option<usize>,
1090 pub sort: ComplexitySort,
1092 pub complexity_breakdown: bool,
1094 pub complexity: bool,
1096 pub file_scores: bool,
1098 pub coverage_gaps: bool,
1100 pub hotspots: bool,
1102 pub ownership: bool,
1104 pub ownership_emails: Option<OwnershipEmailMode>,
1106 pub targets: bool,
1108 pub css: bool,
1110 pub css_deep: bool,
1112 pub effort: Option<TargetEffort>,
1115 pub score: bool,
1117 pub since: Option<String>,
1119 pub min_commits: Option<u32>,
1121 pub coverage: Option<PathBuf>,
1123 pub coverage_root: Option<PathBuf>,
1125 pub coverage_relocated: bool,
1130}
1131
1132#[derive(Debug, Clone, Copy, Default, PartialEq)]
1134pub struct ComplexityThresholdOverrides {
1135 pub max_cyclomatic: Option<u16>,
1137 pub max_cognitive: Option<u16>,
1139 pub max_crap: Option<f64>,
1141 pub max_file_lines: Option<u32>,
1143}
1144
1145#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1147pub struct ComplexityCoverageInputs<'a> {
1148 pub coverage: Option<&'a Path>,
1150 pub coverage_root: Option<&'a Path>,
1152 pub coverage_relocated: bool,
1155}
1156
1157#[derive(Debug, Clone)]
1159pub struct HealthSectionOptions {
1160 pub output: fallow_types::output_format::OutputFormat,
1162 pub complexity: bool,
1164 pub file_scores: bool,
1166 pub coverage_gaps: bool,
1168 pub hotspots: bool,
1170 pub targets: bool,
1172 pub css: bool,
1174 pub score: bool,
1176 pub score_gate: bool,
1178 pub snapshot_requested: bool,
1180 pub trend: bool,
1182}
1183
1184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1186pub struct DerivedHealthSections {
1187 pub any_section: bool,
1189 pub complexity: bool,
1191 pub file_scores: bool,
1193 pub coverage_gaps: bool,
1195 pub hotspots: bool,
1197 pub targets: bool,
1199 pub css: bool,
1201 pub score: bool,
1203 pub force_full: bool,
1205 pub score_only_output: bool,
1207}
1208
1209#[derive(Debug, Clone)]
1211pub struct ComplexitySectionOptions {
1212 pub complexity: bool,
1214 pub file_scores: bool,
1216 pub coverage_gaps: bool,
1218 pub hotspots: bool,
1220 pub ownership: bool,
1222 pub targets: bool,
1224 pub css: bool,
1226 pub score: bool,
1228}
1229
1230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1232pub struct DerivedComplexityOptions {
1233 pub any_section: bool,
1235 pub complexity: bool,
1237 pub file_scores: bool,
1239 pub coverage_gaps: bool,
1241 pub hotspots: bool,
1243 pub ownership: bool,
1245 pub targets: bool,
1247 pub force_full: bool,
1249 pub score_only_output: bool,
1251 pub score: bool,
1253}
1254
1255#[derive(Debug, Clone, PartialEq)]
1257pub struct ComplexityRunOptions<'a> {
1258 pub thresholds: ComplexityThresholdOverrides,
1260 pub top: Option<usize>,
1262 pub sort: ComplexitySort,
1264 pub complexity_breakdown: bool,
1266 pub sections: DerivedComplexityOptions,
1268 pub ownership_emails: Option<OwnershipEmailMode>,
1270 pub effort: Option<TargetEffort>,
1272 pub css: bool,
1274 pub css_deep: bool,
1276 pub since: Option<&'a str>,
1278 pub min_commits: Option<u32>,
1280 pub coverage_inputs: ComplexityCoverageInputs<'a>,
1282}
1283
1284pub fn configure_global_analysis_pool(threads: usize) -> bool {
1293 fallow_engine::thread_pool::worker_pool_builder(threads)
1294 .build_global()
1295 .is_ok()
1296}
1297
1298#[must_use]
1300pub fn derive_health_sections(options: &HealthSectionOptions) -> DerivedHealthSections {
1301 let score = options.score
1302 || options.score_gate
1303 || options.trend
1304 || matches!(
1305 options.output,
1306 fallow_types::output_format::OutputFormat::Badge
1307 );
1308 let any_section = options.complexity
1309 || options.file_scores
1310 || options.coverage_gaps
1311 || options.hotspots
1312 || options.targets
1313 || score;
1314 let effective_score = if any_section { score } else { true } || options.snapshot_requested;
1315 let force_full = options.snapshot_requested || effective_score;
1316
1317 DerivedHealthSections {
1318 any_section,
1319 complexity: if any_section {
1320 options.complexity
1321 } else {
1322 true
1323 },
1324 file_scores: if any_section {
1325 options.file_scores
1326 } else {
1327 true
1328 } || force_full,
1329 coverage_gaps: if any_section {
1330 options.coverage_gaps
1331 } else {
1332 false
1333 },
1334 hotspots: if any_section { options.hotspots } else { true }
1335 || options.snapshot_requested
1336 || options.trend,
1337 targets: if any_section { options.targets } else { true },
1338 css: options.css,
1339 score: effective_score,
1340 force_full,
1341 score_only_output: is_health_score_only_output(options, score),
1342 }
1343}
1344
1345#[must_use]
1347pub fn derive_complexity_sections(options: &ComplexitySectionOptions) -> DerivedComplexityOptions {
1348 let requested_hotspots = options.hotspots || options.ownership;
1349 let sections = derive_health_sections(&HealthSectionOptions {
1350 output: fallow_types::output_format::OutputFormat::Human,
1351 complexity: options.complexity,
1352 file_scores: options.file_scores,
1353 coverage_gaps: options.coverage_gaps,
1354 hotspots: requested_hotspots,
1355 targets: options.targets,
1356 css: options.css,
1357 score: options.score,
1358 score_gate: false,
1359 snapshot_requested: false,
1360 trend: false,
1361 });
1362
1363 DerivedComplexityOptions {
1364 any_section: sections.any_section,
1365 complexity: sections.complexity,
1366 file_scores: sections.file_scores,
1367 coverage_gaps: sections.coverage_gaps,
1368 hotspots: sections.hotspots,
1369 ownership: options.ownership && sections.hotspots,
1370 targets: sections.targets,
1371 force_full: sections.force_full,
1372 score_only_output: sections.score_only_output,
1373 score: sections.score,
1374 }
1375}
1376
1377#[must_use]
1379pub fn derive_complexity_options(options: &ComplexityOptions) -> DerivedComplexityOptions {
1380 derive_complexity_sections(&complexity_section_options(options))
1381}
1382
1383#[must_use]
1385pub fn derive_complexity_run_options(options: &ComplexityOptions) -> ComplexityRunOptions<'_> {
1386 ComplexityRunOptions {
1387 thresholds: ComplexityThresholdOverrides {
1388 max_cyclomatic: options.max_cyclomatic,
1389 max_cognitive: options.max_cognitive,
1390 max_crap: options.max_crap,
1391 max_file_lines: options.max_file_lines,
1392 },
1393 top: options.top,
1394 sort: options.sort,
1395 complexity_breakdown: options.complexity_breakdown,
1396 sections: derive_complexity_options(options),
1397 ownership_emails: options.ownership_emails,
1398 effort: options.effort,
1399 css: options.css,
1400 css_deep: options.css_deep,
1401 since: options.since.as_deref(),
1402 min_commits: options.min_commits,
1403 coverage_inputs: ComplexityCoverageInputs {
1404 coverage: options.coverage.as_deref(),
1405 coverage_root: options.coverage_root.as_deref(),
1406 coverage_relocated: options.coverage_relocated,
1407 },
1408 }
1409}
1410
1411pub fn validate_complexity_options(options: &ComplexityOptions) -> Result<(), ProgrammaticError> {
1434 if let Some(path) = &options.coverage {
1435 let resolved = fallow_engine::health::scoring::resolve_relative_to_root(
1436 path,
1437 options.analysis.root.as_deref(),
1438 );
1439 if !resolved.exists() {
1440 return Err(ProgrammaticError::new(
1441 format!("coverage path does not exist: {}", resolved.display()),
1442 2,
1443 )
1444 .with_code("FALLOW_INVALID_COVERAGE_PATH")
1445 .with_context("health.coverage"));
1446 }
1447 }
1448 if let Err(message) =
1449 fallow_engine::health::validate_coverage_root_absolute(options.coverage_root.as_deref())
1450 {
1451 return Err(ProgrammaticError::new(message, 2)
1452 .with_code("FALLOW_INVALID_COVERAGE_ROOT")
1453 .with_context("health.coverage_root"));
1454 }
1455
1456 Ok(())
1457}
1458
1459fn complexity_section_options(options: &ComplexityOptions) -> ComplexitySectionOptions {
1460 let ownership = options.ownership || options.ownership_emails.is_some();
1461 let requested_targets = options.targets || options.effort.is_some();
1462 ComplexitySectionOptions {
1463 complexity: options.complexity,
1464 file_scores: options.file_scores,
1465 coverage_gaps: options.coverage_gaps,
1466 hotspots: options.hotspots,
1467 ownership,
1468 targets: requested_targets,
1469 css: options.css,
1470 score: options.score,
1471 }
1472}
1473
1474fn is_health_score_only_output(options: &HealthSectionOptions, score: bool) -> bool {
1475 score
1476 && !options.complexity
1477 && !options.file_scores
1478 && !options.coverage_gaps
1479 && !options.hotspots
1480 && !options.targets
1481 && !options.trend
1482}
1483
1484const fn thresholds_to_engine(
1485 thresholds: ComplexityThresholdOverrides,
1486) -> fallow_engine::health::HealthThresholdOverrides {
1487 fallow_engine::health::HealthThresholdOverrides {
1488 max_cyclomatic: thresholds.max_cyclomatic,
1489 max_cognitive: thresholds.max_cognitive,
1490 max_crap: thresholds.max_crap,
1491 max_file_lines: thresholds.max_file_lines,
1492 }
1493}
1494
1495const fn complexity_sort_to_engine(sort: ComplexitySort) -> fallow_engine::health::HealthSort {
1496 match sort {
1497 ComplexitySort::Severity => fallow_engine::health::HealthSort::Severity,
1498 ComplexitySort::Cyclomatic => fallow_engine::health::HealthSort::Cyclomatic,
1499 ComplexitySort::Cognitive => fallow_engine::health::HealthSort::Cognitive,
1500 ComplexitySort::Lines => fallow_engine::health::HealthSort::Lines,
1501 }
1502}
1503
1504const fn coverage_inputs_to_engine(
1505 coverage_inputs: ComplexityCoverageInputs<'_>,
1506) -> fallow_engine::health::HealthCoverageInputs<'_> {
1507 fallow_engine::health::HealthCoverageInputs {
1508 coverage: coverage_inputs.coverage,
1509 coverage_root: coverage_inputs.coverage_root,
1510 coverage_relocated: coverage_inputs.coverage_relocated,
1511 }
1512}
1513
1514const fn ownership_email_mode_to_config(mode: OwnershipEmailMode) -> EmailMode {
1515 match mode {
1516 OwnershipEmailMode::Raw => EmailMode::Raw,
1517 OwnershipEmailMode::Handle => EmailMode::Handle,
1518 OwnershipEmailMode::Anonymized => EmailMode::Anonymized,
1519 OwnershipEmailMode::Hash => EmailMode::Hash,
1520 }
1521}
1522
1523const fn target_effort_to_output(effort: TargetEffort) -> EffortEstimate {
1524 match effort {
1525 TargetEffort::Low => EffortEstimate::Low,
1526 TargetEffort::Medium => EffortEstimate::Medium,
1527 TargetEffort::High => EffortEstimate::High,
1528 }
1529}
1530
1531#[cfg(test)]
1532mod tests {
1533 use super::*;
1534
1535 #[test]
1536 fn duplication_defaults_match_cli_contract() {
1537 let options = DuplicationOptions::default();
1538 assert!(options.mode.is_none());
1539 assert!(options.min_tokens.is_none());
1540 assert!(options.min_lines.is_none());
1541 assert!(options.min_occurrences.is_none());
1542 }
1543
1544 #[test]
1545 fn programmatic_error_builder_keeps_optional_fields() {
1546 let error = ProgrammaticError::new("boom", 2)
1547 .with_code("FALLOW_TEST")
1548 .with_help("Try again")
1549 .with_context("analysis.root");
1550
1551 assert_eq!(error.message, "boom");
1552 assert_eq!(error.exit_code, 2);
1553 assert_eq!(error.code.as_deref(), Some("FALLOW_TEST"));
1554 assert_eq!(error.help.as_deref(), Some("Try again"));
1555 assert_eq!(error.context.as_deref(), Some("analysis.root"));
1556 }
1557
1558 #[test]
1559 fn dead_code_filters_accept_shared_registry_selectors() {
1560 for (selector, _) in fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS.iter() {
1561 let mut filters = DeadCodeFilters::default();
1562 assert!(
1563 filters.enable_registry_selector(selector),
1564 "{selector} should be accepted"
1565 );
1566 }
1567
1568 let mut filters = DeadCodeFilters::default();
1569 assert!(filters.enable_registry_selector("unused-files"));
1570 assert!(filters.unused_files);
1571 assert!(filters.enable_registry_selector("boundary-violations"));
1572 assert!(filters.boundary_violations);
1573 assert!(!filters.enable_registry_selector("not-a-real-selector"));
1574 }
1575
1576 #[test]
1577 fn default_complexity_options_match_programmatic_health_defaults() {
1578 let derived = derive_complexity_options(&ComplexityOptions::default());
1579
1580 assert!(!derived.any_section);
1581 assert!(derived.complexity);
1582 assert!(derived.file_scores);
1583 assert!(!derived.coverage_gaps);
1584 assert!(derived.hotspots);
1585 assert!(!derived.ownership);
1586 assert!(derived.targets);
1587 assert!(derived.force_full);
1588 assert!(!derived.score_only_output);
1589 assert!(derived.score);
1590 }
1591
1592 #[test]
1593 fn score_only_complexity_options_request_score_only_output() {
1594 let derived = derive_complexity_options(&ComplexityOptions {
1595 score: true,
1596 ..ComplexityOptions::default()
1597 });
1598
1599 assert!(derived.any_section);
1600 assert!(!derived.complexity);
1601 assert!(derived.file_scores);
1602 assert!(!derived.hotspots);
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 ownership_implies_hotspots_when_requested() {
1611 let derived = derive_complexity_options(&ComplexityOptions {
1612 ownership: true,
1613 ..ComplexityOptions::default()
1614 });
1615
1616 assert!(derived.any_section);
1617 assert!(derived.hotspots);
1618 assert!(derived.ownership);
1619 assert!(!derived.targets);
1620 }
1621
1622 #[test]
1623 fn complexity_run_options_normalize_public_api_options() {
1624 let options = ComplexityOptions {
1625 max_cyclomatic: Some(42),
1626 max_cognitive: Some(21),
1627 max_crap: Some(18.5),
1628 top: Some(7),
1629 sort: ComplexitySort::Severity,
1630 complexity_breakdown: true,
1631 ownership_emails: Some(OwnershipEmailMode::Hash),
1632 effort: Some(TargetEffort::High),
1633 coverage: Some(PathBuf::from("coverage/coverage-final.json")),
1634 coverage_root: Some(PathBuf::from("/ci/workspace")),
1635 since: Some("30d".to_string()),
1636 min_commits: Some(4),
1637 ..ComplexityOptions::default()
1638 };
1639
1640 let run = derive_complexity_run_options(&options);
1641
1642 assert_eq!(run.thresholds.max_cyclomatic, Some(42));
1643 assert_eq!(run.thresholds.max_cognitive, Some(21));
1644 assert_eq!(run.thresholds.max_crap, Some(18.5));
1645 assert_eq!(run.top, Some(7));
1646 assert!(matches!(run.sort, ComplexitySort::Severity));
1647 assert!(run.complexity_breakdown);
1648 assert!(run.sections.hotspots);
1649 assert!(run.sections.ownership);
1650 assert!(run.sections.targets);
1651 assert!(matches!(
1652 run.ownership_emails,
1653 Some(OwnershipEmailMode::Hash)
1654 ));
1655 assert!(matches!(run.effort, Some(TargetEffort::High)));
1656 assert_eq!(run.since, Some("30d"));
1657 assert_eq!(run.min_commits, Some(4));
1658 assert_eq!(run.coverage_inputs.coverage, options.coverage.as_deref());
1659 assert_eq!(
1660 run.coverage_inputs.coverage_root,
1661 options.coverage_root.as_deref()
1662 );
1663 }
1664
1665 #[test]
1666 fn complexity_options_validation_accepts_existing_coverage_path_and_absolute_root() {
1667 let dir = tempfile::tempdir().expect("tempdir");
1668 let coverage = dir.path().join("coverage-final.json");
1669 std::fs::write(&coverage, "{}").expect("coverage fixture");
1670
1671 let result = validate_complexity_options(&ComplexityOptions {
1672 coverage: Some(coverage),
1673 coverage_root: Some(PathBuf::from("/ci/workspace")),
1674 ..ComplexityOptions::default()
1675 });
1676
1677 assert!(result.is_ok());
1678 }
1679
1680 #[test]
1681 fn complexity_options_validation_keeps_missing_coverage_error_contract() {
1682 let err = validate_complexity_options(&ComplexityOptions {
1683 coverage: Some(PathBuf::from("/missing/coverage-final.json")),
1684 ..ComplexityOptions::default()
1685 })
1686 .expect_err("missing coverage path should fail");
1687
1688 assert_eq!(err.exit_code, 2);
1689 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1690 assert_eq!(err.context.as_deref(), Some("health.coverage"));
1691 }
1692
1693 #[test]
1694 fn complexity_options_validation_keeps_relative_coverage_root_error_contract() {
1695 let err = validate_complexity_options(&ComplexityOptions {
1696 coverage_root: Some(PathBuf::from("coverage")),
1697 ..ComplexityOptions::default()
1698 })
1699 .expect_err("relative coverage root should fail");
1700
1701 assert_eq!(err.exit_code, 2);
1702 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_ROOT"));
1703 assert_eq!(err.context.as_deref(), Some("health.coverage_root"));
1704 }
1705
1706 #[test]
1710 fn complexity_options_validation_resolves_relative_coverage_against_root() {
1711 let dir = tempfile::tempdir().expect("tempdir");
1712 std::fs::create_dir_all(dir.path().join("artifacts")).expect("artifacts dir");
1713 std::fs::write(dir.path().join("artifacts/coverage-final.json"), "{}")
1714 .expect("coverage fixture");
1715 let relative = PathBuf::from("artifacts/coverage-final.json");
1716 assert!(
1717 !relative.exists(),
1718 "the fixture must not also exist under the test cwd"
1719 );
1720
1721 let result = validate_complexity_options(&ComplexityOptions {
1722 analysis: AnalysisOptions {
1723 root: Some(dir.path().to_path_buf()),
1724 ..AnalysisOptions::default()
1725 },
1726 coverage: Some(relative.clone()),
1727 ..ComplexityOptions::default()
1728 });
1729 assert!(result.is_ok(), "{result:?}");
1730
1731 let err = validate_complexity_options(&ComplexityOptions {
1732 analysis: AnalysisOptions {
1733 root: Some(dir.path().join("elsewhere")),
1734 ..AnalysisOptions::default()
1735 },
1736 coverage: Some(relative),
1737 ..ComplexityOptions::default()
1738 })
1739 .expect_err("the path does not exist under the other root");
1740 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1741 assert!(
1742 err.message.contains("elsewhere"),
1743 "the message names the resolved path: {}",
1744 err.message
1745 );
1746 }
1747
1748 #[test]
1749 fn default_health_sections_match_full_health_output() {
1750 let derived = derive_health_sections(&HealthSectionOptions {
1751 output: fallow_types::output_format::OutputFormat::Human,
1752 complexity: false,
1753 file_scores: false,
1754 coverage_gaps: false,
1755 hotspots: false,
1756 targets: false,
1757 css: false,
1758 score: false,
1759 score_gate: false,
1760 snapshot_requested: false,
1761 trend: false,
1762 });
1763
1764 assert!(!derived.any_section);
1765 assert!(derived.complexity);
1766 assert!(derived.file_scores);
1767 assert!(!derived.coverage_gaps);
1768 assert!(derived.hotspots);
1769 assert!(derived.targets);
1770 assert!(derived.score);
1771 assert!(derived.force_full);
1772 assert!(!derived.score_only_output);
1773 }
1774
1775 #[test]
1776 fn health_score_gate_requests_score_only_output() {
1777 let derived = derive_health_sections(&HealthSectionOptions {
1778 output: fallow_types::output_format::OutputFormat::Human,
1779 complexity: false,
1780 file_scores: false,
1781 coverage_gaps: false,
1782 hotspots: false,
1783 targets: false,
1784 css: false,
1785 score: false,
1786 score_gate: true,
1787 snapshot_requested: false,
1788 trend: false,
1789 });
1790
1791 assert!(derived.any_section);
1792 assert!(!derived.complexity);
1793 assert!(derived.file_scores);
1794 assert!(!derived.hotspots);
1795 assert!(!derived.targets);
1796 assert!(derived.score);
1797 assert!(derived.force_full);
1798 assert!(derived.score_only_output);
1799 }
1800
1801 #[test]
1802 fn health_snapshot_keeps_full_hidden_inputs_without_section_request() {
1803 let derived = derive_health_sections(&HealthSectionOptions {
1804 output: fallow_types::output_format::OutputFormat::Human,
1805 complexity: false,
1806 file_scores: false,
1807 coverage_gaps: false,
1808 hotspots: false,
1809 targets: false,
1810 css: true,
1811 score: false,
1812 score_gate: false,
1813 snapshot_requested: true,
1814 trend: false,
1815 });
1816
1817 assert!(!derived.any_section);
1818 assert!(derived.css);
1819 assert!(derived.file_scores);
1820 assert!(derived.hotspots);
1821 assert!(derived.score);
1822 assert!(derived.force_full);
1823 }
1824}