Skip to main content

fallow_engine/
error_severity.rs

1//! The error-severity rule: whether a dead-code result holds a finding whose
2//! effective severity is `error`.
3//!
4//! This rule decides the exit code of `dead-code` and `check`, the
5//! `error-severity-findings` gate entry, the combined verdict and the audit
6//! summary. Every caller reads it from here, so a finding cannot fail one
7//! command and pass another.
8
9use fallow_config::{ResolvedConfig, RulesConfig, Severity};
10
11use crate::effective_severity::{
12    SeveritySource, any_finding_with_severity, count_findings_with_severity,
13};
14pub use crate::effective_severity::{promote_warns_to_errors, strict_rules};
15
16/// Check whether any issue type with `Severity::Error` has remaining issues.
17///
18/// The severity of each finding comes from the rule table in
19/// `crate::effective_severity`, the same table that writes the
20/// `effective_severity` of each finding for the CI formats and that the audit
21/// ledger reads. When overrides are configured, file-scoped findings resolve
22/// the rules for their own path. Circular dependencies resolve against every
23/// file in the cycle. Project-level findings read `rules`.
24///
25/// `promote_warns` mirrors `--fail-on-issues`: `rules` is expected to arrive
26/// already promoted, and the per-file override path promotes each resolved
27/// severity after override resolution so an explicit per-path `warn` fails
28/// the run just like the base rules would.
29pub fn has_error_severity_issues(
30    results: &crate::dead_code::AnalysisResults,
31    rules: &RulesConfig,
32    config: Option<&ResolvedConfig>,
33    promote_warns: bool,
34) -> bool {
35    let source = SeveritySource::new(rules, config, promote_warns);
36    any_finding_with_severity(results, &source, Severity::Error)
37}
38
39/// The number of findings that [`has_error_severity_issues`] reads as
40/// `error`, with the same arguments and the same rule table.
41///
42/// The `error-severity-findings` gate publishes this number as `observed`.
43/// The count is zero exactly when [`has_error_severity_issues`] returns
44/// false.
45pub fn count_error_severity_issues(
46    results: &crate::dead_code::AnalysisResults,
47    rules: &RulesConfig,
48    config: Option<&ResolvedConfig>,
49    promote_warns: bool,
50) -> usize {
51    let source = SeveritySource::new(rules, config, promote_warns);
52    count_findings_with_severity(results, &source, Severity::Error)
53}
54
55/// Promote per-finding `warn` policy-violation severities to `error` for a
56/// strict (fail-on-issues) run. Policy findings carry their effective
57/// severity baked by the evaluator, so the rule-level promotion in
58/// [`promote_warns_to_errors`] alone would not flip findings whose rule
59/// explicitly opted down to `warn`; under strict mode every warning fails.
60pub fn promote_policy_finding_warns(results: &mut crate::dead_code::AnalysisResults) {
61    use fallow_types::results::PolicyViolationSeverity;
62    for finding in &mut results.policy_violations {
63        if finding.violation.severity == PolicyViolationSeverity::Warn {
64            finding.violation.severity = PolicyViolationSeverity::Error;
65        }
66    }
67}
68
69#[cfg(test)]
70mod tests {
71    use std::path::PathBuf;
72
73    use fallow_config::{ConfigOverride, FallowConfig, PartialRulesConfig, RulesConfig, Severity};
74    use fallow_types::output_dead_code::{
75        EmptyCatalogGroupFinding, MisconfiguredDependencyOverrideFinding,
76        UnusedDependencyOverrideFinding,
77    };
78    use fallow_types::results::{
79        DependencyOverrideMisconfigReason, DependencyOverrideSource, EmptyCatalogGroup,
80        MisconfiguredDependencyOverride, UnusedDependencyOverride,
81    };
82
83    use super::{count_error_severity_issues, has_error_severity_issues};
84    use crate::dead_code::AnalysisResults;
85
86    /// One finding of each manifest-level kind that per-file `overrides` can
87    /// change: an unused and a misconfigured dependency override in
88    /// `package.json`, and an empty catalog group in `pnpm-workspace.yaml`.
89    fn manifest_findings() -> [(&'static str, AnalysisResults); 3] {
90        let mut unused = AnalysisResults::default();
91        unused
92            .unused_dependency_overrides
93            .push(UnusedDependencyOverrideFinding::with_actions(
94                UnusedDependencyOverride {
95                    raw_key: "old-dep".to_string(),
96                    target_package: "old-dep".to_string(),
97                    parent_package: None,
98                    version_constraint: None,
99                    version_range: "^1.0.0".to_string(),
100                    source: DependencyOverrideSource::PnpmPackageJson,
101                    path: PathBuf::from("/project/package.json"),
102                    line: 7,
103                    hint: None,
104                },
105            ));
106        let mut misconfigured = AnalysisResults::default();
107        misconfigured.misconfigured_dependency_overrides.push(
108            MisconfiguredDependencyOverrideFinding::with_actions(MisconfiguredDependencyOverride {
109                raw_key: "bad>".to_string(),
110                target_package: None,
111                raw_value: "1.0.0".to_string(),
112                reason: DependencyOverrideMisconfigReason::UnparsableKey,
113                source: DependencyOverrideSource::PnpmPackageJson,
114                path: PathBuf::from("/project/package.json"),
115                line: 4,
116            }),
117        );
118        let mut empty_group = AnalysisResults::default();
119        empty_group
120            .empty_catalog_groups
121            .push(EmptyCatalogGroupFinding::with_actions(EmptyCatalogGroup {
122                catalog_name: "legacy".to_string(),
123                path: PathBuf::from("/project/pnpm-workspace.yaml"),
124                line: 3,
125            }));
126        [
127            ("unused-dependency-overrides", unused),
128            ("misconfigured-dependency-overrides", misconfigured),
129            ("empty-catalog-groups", empty_group),
130        ]
131    }
132
133    fn config_with_manifest_override(
134        base: Severity,
135        manifest: Severity,
136    ) -> fallow_config::ResolvedConfig {
137        FallowConfig {
138            rules: RulesConfig {
139                unused_dependency_overrides: base,
140                misconfigured_dependency_overrides: base,
141                empty_catalog_groups: base,
142                ..RulesConfig::default()
143            },
144            overrides: vec![ConfigOverride {
145                files: vec![
146                    "package.json".to_string(),
147                    "pnpm-workspace.yaml".to_string(),
148                ],
149                rules: PartialRulesConfig {
150                    unused_dependency_overrides: Some(manifest),
151                    misconfigured_dependency_overrides: Some(manifest),
152                    empty_catalog_groups: Some(manifest),
153                    ..PartialRulesConfig::default()
154                },
155            }],
156            ..FallowConfig::default()
157        }
158        .resolve(
159            PathBuf::from("/project"),
160            fallow_config::OutputFormat::Human,
161            1,
162            true,
163            true,
164            None,
165        )
166    }
167
168    #[test]
169    fn a_manifest_override_to_warn_clears_a_base_error() {
170        let config = config_with_manifest_override(Severity::Error, Severity::Warn);
171        for (kind, results) in manifest_findings() {
172            assert!(
173                !has_error_severity_issues(&results, &config.rules, Some(&config), false),
174                "the `warn` override for the manifest must win over the base `error` for {kind}"
175            );
176        }
177    }
178
179    #[test]
180    fn a_manifest_override_to_error_raises_a_base_warn() {
181        let config = config_with_manifest_override(Severity::Warn, Severity::Error);
182        for (kind, results) in manifest_findings() {
183            assert!(
184                has_error_severity_issues(&results, &config.rules, Some(&config), false),
185                "the `error` override for the manifest must win over the base `warn` for {kind}"
186            );
187        }
188    }
189
190    /// The count agrees with the yes or no answer, and per-file overrides
191    /// count each finding with its own severity.
192    #[test]
193    fn the_count_holds_each_finding_at_its_own_severity() {
194        let config = config_with_manifest_override(Severity::Error, Severity::Error);
195        let mut all = AnalysisResults::default();
196        for (_, results) in manifest_findings() {
197            all.unused_dependency_overrides
198                .extend(results.unused_dependency_overrides);
199            all.misconfigured_dependency_overrides
200                .extend(results.misconfigured_dependency_overrides);
201            all.empty_catalog_groups
202                .extend(results.empty_catalog_groups);
203        }
204        assert_eq!(
205            count_error_severity_issues(&all, &config.rules, Some(&config), false),
206            3
207        );
208
209        let mixed = config_with_manifest_override(Severity::Error, Severity::Warn);
210        assert_eq!(
211            count_error_severity_issues(&all, &mixed.rules, Some(&mixed), false),
212            0
213        );
214        assert_eq!(
215            count_error_severity_issues(&all, &mixed.rules, Some(&mixed), true),
216            3,
217            "--fail-on-issues promotes the per-file `warn`"
218        );
219        assert_eq!(
220            count_error_severity_issues(&AnalysisResults::default(), &config.rules, None, false),
221            0
222        );
223    }
224}