Skip to main content

lanekeep_core/
severity.rs

1//! How much a violation matters.
2
3use std::fmt;
4use std::str::FromStr;
5
6use serde::{Deserialize, Serialize};
7use thiserror::Error;
8
9/// A rule's configured severity.
10///
11/// `Off` exists as a severity rather than as a separate "disabled rules" list so that a
12/// project turning a rule off, and a preset turning it back on, are the same kind of
13/// operation. Config merge then has one rule to follow instead of two that can disagree.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
15#[serde(rename_all = "lowercase")]
16pub enum Severity {
17    /// Reported, and does not affect the exit code.
18    Warn,
19    /// Reported, and makes the run exit non-zero.
20    Error,
21    /// Not evaluated at all. The rule is skipped before its gates are considered.
22    Off,
23}
24
25impl Severity {
26    /// Whether a violation at this severity should fail the run.
27    #[must_use]
28    pub const fn is_failing(self) -> bool {
29        matches!(self, Self::Error)
30    }
31
32    /// Whether the rule runs at all.
33    #[must_use]
34    pub const fn is_enabled(self) -> bool {
35        !matches!(self, Self::Off)
36    }
37
38    /// The severity as it appears in config and output.
39    #[must_use]
40    pub const fn as_str(self) -> &'static str {
41        match self {
42            Self::Warn => "warn",
43            Self::Error => "error",
44            Self::Off => "off",
45        }
46    }
47}
48
49impl fmt::Display for Severity {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        f.write_str(self.as_str())
52    }
53}
54
55/// The string was not a severity lanekeep recognizes.
56#[derive(Debug, Clone, PartialEq, Eq, Error)]
57#[error("unknown severity `{0}`: expected `error`, `warn` or `off`")]
58pub struct ParseSeverityError(pub String);
59
60impl FromStr for Severity {
61    type Err = ParseSeverityError;
62
63    fn from_str(s: &str) -> Result<Self, Self::Err> {
64        match s {
65            "warn" => Ok(Self::Warn),
66            "error" => Ok(Self::Error),
67            "off" => Ok(Self::Off),
68            other => Err(ParseSeverityError(other.to_owned())),
69        }
70    }
71}
72
73#[cfg(test)]
74mod tests {
75    use super::*;
76
77    #[test]
78    fn parses_every_variant() {
79        assert_eq!("warn".parse(), Ok(Severity::Warn));
80        assert_eq!("error".parse(), Ok(Severity::Error));
81        assert_eq!("off".parse(), Ok(Severity::Off));
82    }
83
84    #[test]
85    fn rejects_anything_else() {
86        // Notably case-sensitive. `Error` in a config file is a typo, and accepting it
87        // would mean two spellings of one value that a reader has to know are the same.
88        for bad in ["Error", "ERROR", "warning", "none", "", " warn"] {
89            assert!(
90                bad.parse::<Severity>().is_err(),
91                "should have rejected {bad:?}"
92            );
93        }
94    }
95
96    #[test]
97    fn round_trips_through_display() {
98        for severity in [Severity::Warn, Severity::Error, Severity::Off] {
99            assert_eq!(severity.to_string().parse(), Ok(severity));
100        }
101    }
102
103    #[test]
104    fn only_error_fails_the_run() {
105        assert!(Severity::Error.is_failing());
106        assert!(!Severity::Warn.is_failing());
107        assert!(!Severity::Off.is_failing());
108    }
109
110    #[test]
111    fn only_off_disables_the_rule() {
112        assert!(Severity::Error.is_enabled());
113        assert!(Severity::Warn.is_enabled());
114        assert!(!Severity::Off.is_enabled());
115    }
116
117    #[test]
118    fn serde_uses_the_same_spelling_as_config() {
119        // The JSON reporter and the config loader must agree, or a severity read from
120        // config would serialize as something config cannot read back.
121        assert_eq!(
122            serde_json::to_string(&Severity::Error).expect("ok"),
123            "\"error\""
124        );
125        assert_eq!(
126            serde_json::to_string(&Severity::Warn).expect("ok"),
127            "\"warn\""
128        );
129        assert_eq!(
130            serde_json::to_string(&Severity::Off).expect("ok"),
131            "\"off\""
132        );
133
134        let parsed: Severity = serde_json::from_str("\"warn\"").expect("ok");
135        assert_eq!(parsed, Severity::Warn);
136    }
137}