Skip to main content

fallow_output/
codeclimate.rs

1use serde::Serialize;
2use serde_json::Value;
3
4/// Envelope emitted by `fallow --format codeclimate` and
5/// `fallow --format gitlab-codequality`. GitLab Code Quality consumes the
6/// same shape. The wire form is a bare JSON array, not an object.
7#[derive(Debug, Clone, Serialize)]
8#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
9#[cfg_attr(
10    feature = "schema",
11    schemars(title = "fallow --format codeclimate / gitlab-codequality")
12)]
13#[serde(transparent)]
14pub struct CodeClimateOutput(pub Vec<CodeClimateIssue>);
15
16/// Single CodeClimate-compatible issue inside [`CodeClimateOutput`].
17#[derive(Debug, Clone, Serialize)]
18#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
19pub struct CodeClimateIssue {
20    /// CodeClimate `type` discriminator; always `issue`.
21    #[serde(rename = "type")]
22    pub kind: CodeClimateIssueKind,
23    /// Fallow rule identifier, e.g. `fallow/unused-file`.
24    pub check_name: String,
25    /// Human-readable finding description.
26    pub description: String,
27    /// CodeClimate category labels, e.g. `Clarity` or `Duplication`.
28    pub categories: Vec<String>,
29    /// CodeClimate severity mapped from the configured rule severity.
30    pub severity: CodeClimateSeverity,
31    /// Stable finding fingerprint GitLab uses to track issues across pushes.
32    pub fingerprint: String,
33    /// File and inclusive line range of the finding.
34    pub location: CodeClimateLocation,
35    /// Other source locations that provide evidence for the finding. GitLab's
36    /// Code Quality widget ignores this standard CodeClimate field, but Fallow
37    /// preserves it for review-comment rendering.
38    #[serde(default, skip_serializing_if = "Vec::is_empty")]
39    pub other_locations: Vec<CodeClimateLocation>,
40    /// Optional owner attribution used by grouped dead-code output.
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub owner: Option<String>,
43    /// Optional grouping attribution used by grouped health and duplication
44    /// output.
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub group: Option<String>,
47    /// The fingerprint an older Fallow version gave this issue, when it is
48    /// different from `fingerprint`. Never serialized: the CodeClimate wire
49    /// shape does not change. The review layer uses it for one release to
50    /// match review threads that carry the older marker.
51    #[serde(skip)]
52    #[cfg_attr(feature = "schema", schemars(skip))]
53    pub legacy_fingerprint: Option<String>,
54    /// Audit facts that an inline review comment shows. Never serialized:
55    /// the CodeClimate wire shape does not change.
56    #[serde(skip)]
57    #[cfg_attr(feature = "schema", schemars(skip))]
58    pub audit: Option<crate::AuditReviewContext>,
59}
60
61/// Discriminator value for [`CodeClimateIssue::kind`].
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
63#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
64#[serde(rename_all = "lowercase")]
65pub enum CodeClimateIssueKind {
66    /// The only valid CodeClimate type today.
67    Issue,
68}
69
70/// CodeClimate severity scale.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
72#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
73#[serde(rename_all = "lowercase")]
74pub enum CodeClimateSeverity {
75    /// Informational. Reserved for future severity mappings; not produced
76    /// by the current runtime path (which only emits Minor / Major /
77    /// Critical via `severity_to_codeclimate` and the health / runtime-
78    /// coverage match arms).
79    Info,
80    /// Minor finding.
81    Minor,
82    /// Major finding.
83    Major,
84    /// Critical finding.
85    Critical,
86    /// Blocker (highest severity). Reserved for future severity
87    /// mappings; not produced by the current runtime path.
88    Blocker,
89}
90
91/// Location block inside [`CodeClimateIssue::location`].
92#[derive(Debug, Clone, Serialize)]
93#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
94pub struct CodeClimateLocation {
95    /// File path relative to the analysed root.
96    pub path: String,
97    /// Wrapper carrying the line range so the schema lines up with
98    /// CodeClimate's spec.
99    pub lines: CodeClimateLines,
100}
101
102/// Inclusive line range for [`CodeClimateLocation`].
103#[derive(Debug, Clone, Copy, Serialize)]
104#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
105pub struct CodeClimateLines {
106    /// 1-based start line.
107    pub begin: u32,
108    /// Inclusive 1-based end line. Omitted for point findings.
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub end: Option<u32>,
111}
112
113/// Fields needed to build one CodeClimate issue.
114///
115/// Callers decide what should be reported. This crate owns how that decision is
116/// shaped into the stable CodeClimate / GitLab Code Quality wire contract.
117#[derive(Debug, Clone, Copy)]
118pub struct CodeClimateIssueInput<'a> {
119    /// Fallow rule identifier for the issue's `check_name`.
120    pub check_name: &'a str,
121    /// Human-readable finding description.
122    pub description: &'a str,
123    /// CodeClimate severity to report.
124    pub severity: CodeClimateSeverity,
125    /// Single CodeClimate category label; wrapped into `categories`.
126    pub category: &'a str,
127    /// File path relative to the analysed root.
128    pub path: &'a str,
129    /// 1-based begin line; defaults to line 1 when absent.
130    pub begin_line: Option<u32>,
131    /// Stable finding fingerprint.
132    pub fingerprint: &'a str,
133}
134
135/// Optional grouped CodeClimate annotation field.
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137pub enum CodeClimateAnnotationField {
138    /// Dead-code grouped output uses the top-level `owner` property.
139    Owner,
140    /// Health and duplication grouped output use the top-level `group`
141    /// property.
142    Group,
143}
144
145/// Compute a deterministic fingerprint hash from key fields.
146///
147/// Delegates to [`fallow_types::identity::fnv1a64_parts`], the one FNV-1a 64
148/// implementation that fingerprints and finding ids share.
149#[must_use]
150pub fn codeclimate_fingerprint_hash(parts: &[&str]) -> String {
151    fallow_types::identity::fnv1a64_parts(parts)
152}
153
154/// Build a single CodeClimate issue from a stable contract descriptor.
155#[must_use]
156pub fn build_codeclimate_issue(input: CodeClimateIssueInput<'_>) -> CodeClimateIssue {
157    CodeClimateIssue {
158        kind: CodeClimateIssueKind::Issue,
159        check_name: input.check_name.to_string(),
160        description: input.description.to_string(),
161        categories: vec![input.category.to_string()],
162        severity: input.severity,
163        fingerprint: input.fingerprint.to_string(),
164        location: CodeClimateLocation {
165            path: input.path.to_string(),
166            lines: CodeClimateLines {
167                begin: input.begin_line.unwrap_or(1),
168                end: None,
169            },
170        },
171        other_locations: Vec::new(),
172        owner: None,
173        group: None,
174        legacy_fingerprint: None,
175        audit: None,
176    }
177}
178
179/// Serialize typed CodeClimate issues to the wire-shape JSON array.
180///
181/// Infallible: `CodeClimateIssue` contains only strings, integers, arrays, and
182/// enums serialized as fixed strings.
183///
184/// # Panics
185///
186/// Does not panic in practice: every `CodeClimateIssue` field serializes
187/// infallibly.
188#[must_use]
189#[expect(
190    clippy::expect_used,
191    reason = "CodeClimateIssue contains only infallibly serializable fields"
192)]
193pub fn codeclimate_issues_to_value(issues: &[CodeClimateIssue]) -> Value {
194    serde_json::to_value(issues).expect("CodeClimateIssue serializes infallibly")
195}
196
197/// Add a top-level grouped property to each typed CodeClimate issue.
198///
199/// Grouped CLI outputs use this to attach `owner` or `group` while keeping the
200/// issue array shape and path lookup contract in `fallow-output`.
201pub fn annotate_codeclimate_issues(
202    issues: &mut [CodeClimateIssue],
203    field: CodeClimateAnnotationField,
204    mut value_for_path: impl FnMut(&str) -> String,
205) {
206    for issue in issues {
207        let value = value_for_path(&issue.location.path);
208        match field {
209            CodeClimateAnnotationField::Owner => issue.owner = Some(value),
210            CodeClimateAnnotationField::Group => issue.group = Some(value),
211        }
212    }
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218
219    #[test]
220    fn codeclimate_issue_serializes_spec_shape() {
221        let issue = build_codeclimate_issue(CodeClimateIssueInput {
222            check_name: "fallow/test",
223            description: "description",
224            category: "Bug Risk",
225            severity: CodeClimateSeverity::Major,
226            fingerprint: "abc123",
227            path: "src/app.ts",
228            begin_line: Some(7),
229        });
230
231        let value = serde_json::to_value(issue).expect("CodeClimate issue serializes");
232        assert_eq!(value["type"], "issue");
233        assert_eq!(value["severity"], "major");
234        assert_eq!(value["location"]["lines"]["begin"], 7);
235        assert!(value["location"]["lines"].get("end").is_none());
236        assert!(value.get("other_locations").is_none());
237    }
238
239    #[test]
240    fn output_serializes_as_bare_array() {
241        let output = CodeClimateOutput(Vec::new());
242        let value = serde_json::to_value(output).expect("CodeClimate output serializes");
243        assert!(value.is_array());
244    }
245
246    #[test]
247    fn codeclimate_issues_to_value_serializes_bare_array() {
248        let value = codeclimate_issues_to_value(&[]);
249        assert!(value.is_array());
250    }
251
252    #[test]
253    fn build_codeclimate_issue_defaults_missing_line_to_one() {
254        let issue = build_codeclimate_issue(CodeClimateIssueInput {
255            check_name: "fallow/test",
256            description: "description",
257            category: "Bug Risk",
258            severity: CodeClimateSeverity::Minor,
259            fingerprint: "abc123",
260            path: "src/app.ts",
261            begin_line: None,
262        });
263
264        assert_eq!(issue.location.lines.begin, 1);
265    }
266
267    #[test]
268    fn codeclimate_fingerprint_hash_is_deterministic_16_hex() {
269        let a = codeclimate_fingerprint_hash(&["src/index.ts", "FEATURE_X", "3"]);
270        let b = codeclimate_fingerprint_hash(&["src/index.ts", "FEATURE_X", "3"]);
271        assert_eq!(a, b);
272        assert_eq!(a.len(), 16);
273        assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
274        // Per-part separation means reordering parts changes the digest.
275        assert_ne!(
276            a,
277            codeclimate_fingerprint_hash(&["FEATURE_X", "src/index.ts", "3"])
278        );
279    }
280
281    /// Pins exact digests. CI review threads and CodeClimate consumers match on
282    /// these values, so a change to the hash breaks every saved fingerprint.
283    /// The expected values come from an independent FNV-1a 64 script.
284    #[test]
285    fn codeclimate_fingerprint_hash_golden_values() {
286        assert_eq!(
287            codeclimate_fingerprint_hash(&["src/index.ts", "FEATURE_X", "3"]),
288            "2278c9d9bd9d2dd2"
289        );
290        assert_eq!(
291            codeclimate_fingerprint_hash(&["fallow/unused-file", "src/orphan.ts"]),
292            "c03b925ddb7d871a"
293        );
294        assert_eq!(codeclimate_fingerprint_hash(&[]), "cbf29ce484222325");
295    }
296
297    #[test]
298    fn codeclimate_fingerprint_parts_are_separated() {
299        assert_ne!(
300            codeclimate_fingerprint_hash(&["ab", "c"]),
301            codeclimate_fingerprint_hash(&["a", "bc"])
302        );
303    }
304
305    #[test]
306    fn annotate_codeclimate_issues_adds_owner_from_location_path() {
307        let mut issues = vec![build_codeclimate_issue(CodeClimateIssueInput {
308            check_name: "fallow/test",
309            description: "description",
310            category: "Bug Risk",
311            severity: CodeClimateSeverity::Minor,
312            fingerprint: "abc123",
313            path: "src/app.ts",
314            begin_line: Some(3),
315        })];
316
317        annotate_codeclimate_issues(&mut issues, CodeClimateAnnotationField::Owner, |path| {
318            format!("team:{path}")
319        });
320        let value = codeclimate_issues_to_value(&issues);
321
322        assert_eq!(value[0]["owner"], "team:src/app.ts");
323    }
324
325    #[test]
326    fn annotate_codeclimate_issues_adds_group_from_location_path() {
327        let mut issues = vec![build_codeclimate_issue(CodeClimateIssueInput {
328            check_name: "fallow/test",
329            description: "description",
330            category: "Bug Risk",
331            severity: CodeClimateSeverity::Minor,
332            fingerprint: "abc123",
333            path: "src/app.ts",
334            begin_line: Some(3),
335        })];
336
337        annotate_codeclimate_issues(&mut issues, CodeClimateAnnotationField::Group, |path| {
338            format!("group:{path}")
339        });
340        let value = codeclimate_issues_to_value(&issues);
341
342        assert_eq!(value[0]["group"], "group:src/app.ts");
343        assert!(value[0].get("owner").is_none());
344    }
345}