1pub const INLINE_THRESHOLD_MARKER: &str = "fallow-override-threshold-next-line";
15
16pub const INLINE_THRESHOLD_KEYS: [&str; 4] =
18 ["maxCyclomatic", "maxCognitive", "maxCrap", "maxUnitSize"];
19
20#[derive(Debug, Clone, PartialEq)]
22pub struct InlineThresholdOverride {
23 pub line: u32,
25 pub comment_line: u32,
27 pub max_cyclomatic: Option<u16>,
29 pub max_cognitive: Option<u16>,
31 pub max_crap: Option<f64>,
33 pub max_unit_size: Option<u32>,
35 pub reason: String,
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
42#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
43#[serde(rename_all = "snake_case")]
44pub enum InlineThresholdProblemKind {
45 MissingReason,
47 MissingThreshold,
49 InvalidKey,
51 InvalidValue,
53 Disabled,
55}
56
57impl InlineThresholdProblemKind {
58 #[must_use]
60 pub const fn to_code(self) -> u8 {
61 match self {
62 Self::MissingReason => 1,
63 Self::MissingThreshold => 2,
64 Self::InvalidKey => 3,
65 Self::InvalidValue => 4,
66 Self::Disabled => 5,
67 }
68 }
69
70 #[must_use]
72 pub const fn from_code(code: u8) -> Option<Self> {
73 match code {
74 1 => Some(Self::MissingReason),
75 2 => Some(Self::MissingThreshold),
76 3 => Some(Self::InvalidKey),
77 4 => Some(Self::InvalidValue),
78 5 => Some(Self::Disabled),
79 _ => None,
80 }
81 }
82
83 #[must_use]
85 pub const fn description(self) -> &'static str {
86 match self {
87 Self::MissingReason => {
88 "the comment has no reason; add ` -- <reason>` after the thresholds"
89 }
90 Self::MissingThreshold => {
91 "the comment sets no threshold; use maxCyclomatic, maxCognitive, maxCrap or maxUnitSize"
92 }
93 Self::InvalidKey => {
94 "unknown or repeated key; write each threshold as key=value (maxCyclomatic, maxCognitive, maxCrap or maxUnitSize), each one time"
95 }
96 Self::InvalidValue => {
97 "the value is not valid; use a whole number (a finite number for maxCrap), as in maxCognitive=40"
98 }
99 Self::Disabled => {
100 "health.inlineThresholdOverrides is false, so the comment has no effect"
101 }
102 }
103 }
104}
105
106#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
108#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
109pub struct InlineThresholdProblem {
110 pub line: u32,
112 #[serde(rename = "problem")]
114 pub kind: InlineThresholdProblemKind,
115 #[serde(default, skip_serializing_if = "Option::is_none")]
117 pub token: Option<String>,
118}
119
120#[derive(Debug, Clone, Default, PartialEq)]
122pub struct InlineThresholdOverrides {
123 pub entries: Vec<InlineThresholdOverride>,
125 pub problems: Vec<InlineThresholdProblem>,
127}
128
129impl InlineThresholdOverrides {
130 #[must_use]
132 pub fn is_empty(&self) -> bool {
133 self.entries.is_empty() && self.problems.is_empty()
134 }
135
136 pub fn drop_comment_lines(&mut self, comment_lines: &[u32]) {
138 self.entries
139 .retain(|entry| !comment_lines.contains(&entry.comment_line));
140 self.problems
141 .retain(|problem| !comment_lines.contains(&problem.line));
142 }
143}
144
145pub fn parse_inline_threshold_override(
153 line: u32,
154 comment_line: u32,
155 targets: &str,
156 reason: Option<String>,
157) -> Result<InlineThresholdOverride, InlineThresholdProblem> {
158 let problem = |kind, token: Option<&str>| InlineThresholdProblem {
159 line: comment_line,
160 kind,
161 token: token.map(str::to_string),
162 };
163 let mut entry = InlineThresholdOverride {
164 line,
165 comment_line,
166 max_cyclomatic: None,
167 max_cognitive: None,
168 max_crap: None,
169 max_unit_size: None,
170 reason: String::new(),
171 };
172 let mut seen: Vec<&str> = Vec::new();
173 for token in targets
174 .split(|c: char| c == ',' || c.is_whitespace())
175 .filter(|token| !token.is_empty())
176 {
177 let Some((key, value)) = token.split_once('=') else {
178 return Err(problem(InlineThresholdProblemKind::InvalidKey, Some(token)));
179 };
180 if !INLINE_THRESHOLD_KEYS.contains(&key) || seen.contains(&key) {
181 return Err(problem(InlineThresholdProblemKind::InvalidKey, Some(token)));
182 }
183 seen.push(key);
184 let invalid = || problem(InlineThresholdProblemKind::InvalidValue, Some(token));
185 match key {
186 "maxCyclomatic" => entry.max_cyclomatic = Some(value.parse().map_err(|_| invalid())?),
187 "maxCognitive" => entry.max_cognitive = Some(value.parse().map_err(|_| invalid())?),
188 "maxUnitSize" => entry.max_unit_size = Some(value.parse().map_err(|_| invalid())?),
189 _ => {
190 let crap: f64 = value.parse().map_err(|_| invalid())?;
191 if !crap.is_finite() || crap < 0.0 {
192 return Err(invalid());
193 }
194 entry.max_crap = Some(crap);
195 }
196 }
197 }
198 if seen.is_empty() {
199 return Err(problem(InlineThresholdProblemKind::MissingThreshold, None));
200 }
201 let Some(reason) = reason else {
202 return Err(problem(InlineThresholdProblemKind::MissingReason, None));
203 };
204 entry.reason = reason;
205 Ok(entry)
206}
207
208#[cfg(test)]
209mod tests {
210 use super::*;
211
212 fn parse(
213 targets: &str,
214 reason: Option<&str>,
215 ) -> Result<InlineThresholdOverride, InlineThresholdProblem> {
216 parse_inline_threshold_override(5, 4, targets, reason.map(str::to_string))
217 }
218
219 #[test]
220 fn parses_every_key() {
221 let entry = parse(
222 "maxCyclomatic=30 maxCognitive=40, maxCrap=45.5 maxUnitSize=120",
223 Some("legacy"),
224 )
225 .unwrap();
226 assert_eq!(entry.line, 5);
227 assert_eq!(entry.comment_line, 4);
228 assert_eq!(entry.max_cyclomatic, Some(30));
229 assert_eq!(entry.max_cognitive, Some(40));
230 assert_eq!(entry.max_crap, Some(45.5));
231 assert_eq!(entry.max_unit_size, Some(120));
232 assert_eq!(entry.reason, "legacy");
233 }
234
235 #[test]
236 fn rejects_a_comment_without_reason() {
237 let problem = parse("maxCognitive=40", None).unwrap_err();
238 assert_eq!(problem.kind, InlineThresholdProblemKind::MissingReason);
239 assert_eq!(problem.line, 4);
240 }
241
242 #[test]
243 fn rejects_a_comment_without_threshold() {
244 let problem = parse("", Some("why")).unwrap_err();
245 assert_eq!(problem.kind, InlineThresholdProblemKind::MissingThreshold);
246 }
247
248 #[test]
249 fn rejects_bad_keys_and_values() {
250 for (targets, kind, token) in [
251 (
252 "maxCognitive:40",
253 InlineThresholdProblemKind::InvalidKey,
254 "maxCognitive:40",
255 ),
256 (
257 "maxFileLines=900",
258 InlineThresholdProblemKind::InvalidKey,
259 "maxFileLines=900",
260 ),
261 (
262 "maxCognitive=40 maxCognitive=50",
263 InlineThresholdProblemKind::InvalidKey,
264 "maxCognitive=50",
265 ),
266 (
267 "maxCognitive=forty",
268 InlineThresholdProblemKind::InvalidValue,
269 "maxCognitive=forty",
270 ),
271 (
272 "maxCyclomatic=-1",
273 InlineThresholdProblemKind::InvalidValue,
274 "maxCyclomatic=-1",
275 ),
276 (
277 "maxCrap=NaN",
278 InlineThresholdProblemKind::InvalidValue,
279 "maxCrap=NaN",
280 ),
281 (
282 "maxCrap=-2",
283 InlineThresholdProblemKind::InvalidValue,
284 "maxCrap=-2",
285 ),
286 ] {
287 let problem = parse(targets, Some("why")).unwrap_err();
288 assert_eq!(problem.kind, kind, "{targets}");
289 assert_eq!(problem.token.as_deref(), Some(token), "{targets}");
290 }
291 }
292
293 #[test]
294 fn problem_codes_round_trip() {
295 for kind in [
296 InlineThresholdProblemKind::MissingReason,
297 InlineThresholdProblemKind::MissingThreshold,
298 InlineThresholdProblemKind::InvalidKey,
299 InlineThresholdProblemKind::InvalidValue,
300 InlineThresholdProblemKind::Disabled,
301 ] {
302 assert_eq!(
303 InlineThresholdProblemKind::from_code(kind.to_code()),
304 Some(kind)
305 );
306 }
307 assert_eq!(InlineThresholdProblemKind::from_code(0), None);
308 }
309}