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. Only the advisory shallow directories section of
76    /// health output produces it.
77    Info,
78    /// Minor finding.
79    Minor,
80    /// Major finding.
81    Major,
82    /// Critical finding.
83    Critical,
84    /// Blocker (highest severity). Reserved for future severity
85    /// mappings; not produced by the current runtime path.
86    Blocker,
87}
88
89/// Location block inside [`CodeClimateIssue::location`].
90#[derive(Debug, Clone, Serialize)]
91#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
92pub struct CodeClimateLocation {
93    /// File path relative to the analysed root.
94    pub path: String,
95    /// Wrapper carrying the line range so the schema lines up with
96    /// CodeClimate's spec.
97    pub lines: CodeClimateLines,
98}
99
100/// Inclusive line range for [`CodeClimateLocation`].
101#[derive(Debug, Clone, Copy, Serialize)]
102#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
103pub struct CodeClimateLines {
104    /// 1-based start line.
105    pub begin: u32,
106    /// Inclusive 1-based end line. Omitted for point findings.
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub end: Option<u32>,
109}
110
111/// Fields needed to build one CodeClimate issue.
112///
113/// Callers decide what should be reported. This crate owns how that decision is
114/// shaped into the stable CodeClimate / GitLab Code Quality wire contract.
115#[derive(Debug, Clone, Copy)]
116pub struct CodeClimateIssueInput<'a> {
117    /// Fallow rule identifier for the issue's `check_name`.
118    pub check_name: &'a str,
119    /// Human-readable finding description.
120    pub description: &'a str,
121    /// CodeClimate severity to report.
122    pub severity: CodeClimateSeverity,
123    /// Single CodeClimate category label; wrapped into `categories`.
124    pub category: &'a str,
125    /// File path relative to the analysed root.
126    pub path: &'a str,
127    /// 1-based begin line; defaults to line 1 when absent.
128    pub begin_line: Option<u32>,
129    /// Stable finding fingerprint.
130    pub fingerprint: &'a str,
131}
132
133/// Optional grouped CodeClimate annotation field.
134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
135pub enum CodeClimateAnnotationField {
136    /// Dead-code grouped output uses the top-level `owner` property.
137    Owner,
138    /// Health and duplication grouped output use the top-level `group`
139    /// property.
140    Group,
141}
142
143/// Compute a deterministic fingerprint hash from key fields.
144///
145/// Delegates to [`fallow_types::identity::fnv1a64_parts`], the one FNV-1a 64
146/// implementation that fingerprints and finding ids share.
147#[must_use]
148pub fn codeclimate_fingerprint_hash(parts: &[&str]) -> String {
149    fallow_types::identity::fnv1a64_parts(parts)
150}
151
152/// Build a single CodeClimate issue from a stable contract descriptor.
153#[must_use]
154pub fn build_codeclimate_issue(input: CodeClimateIssueInput<'_>) -> CodeClimateIssue {
155    CodeClimateIssue {
156        kind: CodeClimateIssueKind::Issue,
157        check_name: input.check_name.to_string(),
158        description: input.description.to_string(),
159        categories: vec![input.category.to_string()],
160        severity: input.severity,
161        fingerprint: input.fingerprint.to_string(),
162        location: CodeClimateLocation {
163            path: input.path.to_string(),
164            lines: CodeClimateLines {
165                begin: input.begin_line.unwrap_or(1),
166                end: None,
167            },
168        },
169        other_locations: Vec::new(),
170        owner: None,
171        group: None,
172        legacy_fingerprint: None,
173        audit: None,
174    }
175}
176
177/// Serialize typed CodeClimate issues to the wire-shape JSON array.
178///
179/// Infallible: `CodeClimateIssue` contains only strings, integers, arrays, and
180/// enums serialized as fixed strings.
181///
182/// # Panics
183///
184/// Does not panic in practice: every `CodeClimateIssue` field serializes
185/// infallibly.
186#[must_use]
187#[expect(
188    clippy::expect_used,
189    reason = "CodeClimateIssue contains only infallibly serializable fields"
190)]
191pub fn codeclimate_issues_to_value(issues: &[CodeClimateIssue]) -> Value {
192    serde_json::to_value(issues).expect("CodeClimateIssue serializes infallibly")
193}
194
195/// Add a top-level grouped property to each typed CodeClimate issue.
196///
197/// Grouped CLI outputs use this to attach `owner` or `group` while keeping the
198/// issue array shape and path lookup contract in `fallow-output`.
199pub fn annotate_codeclimate_issues(
200    issues: &mut [CodeClimateIssue],
201    field: CodeClimateAnnotationField,
202    mut value_for_path: impl FnMut(&str) -> String,
203) {
204    for issue in issues {
205        let value = value_for_path(&issue.location.path);
206        match field {
207            CodeClimateAnnotationField::Owner => issue.owner = Some(value),
208            CodeClimateAnnotationField::Group => issue.group = Some(value),
209        }
210    }
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    #[test]
218    fn codeclimate_issue_serializes_spec_shape() {
219        let issue = build_codeclimate_issue(CodeClimateIssueInput {
220            check_name: "fallow/test",
221            description: "description",
222            category: "Bug Risk",
223            severity: CodeClimateSeverity::Major,
224            fingerprint: "abc123",
225            path: "src/app.ts",
226            begin_line: Some(7),
227        });
228
229        let value = serde_json::to_value(issue).expect("CodeClimate issue serializes");
230        assert_eq!(value["type"], "issue");
231        assert_eq!(value["severity"], "major");
232        assert_eq!(value["location"]["lines"]["begin"], 7);
233        assert!(value["location"]["lines"].get("end").is_none());
234        assert!(value.get("other_locations").is_none());
235    }
236
237    #[test]
238    fn output_serializes_as_bare_array() {
239        let output = CodeClimateOutput(Vec::new());
240        let value = serde_json::to_value(output).expect("CodeClimate output serializes");
241        assert!(value.is_array());
242    }
243
244    #[test]
245    fn codeclimate_issues_to_value_serializes_bare_array() {
246        let value = codeclimate_issues_to_value(&[]);
247        assert!(value.is_array());
248    }
249
250    #[test]
251    fn build_codeclimate_issue_defaults_missing_line_to_one() {
252        let issue = build_codeclimate_issue(CodeClimateIssueInput {
253            check_name: "fallow/test",
254            description: "description",
255            category: "Bug Risk",
256            severity: CodeClimateSeverity::Minor,
257            fingerprint: "abc123",
258            path: "src/app.ts",
259            begin_line: None,
260        });
261
262        assert_eq!(issue.location.lines.begin, 1);
263    }
264
265    #[test]
266    fn codeclimate_fingerprint_hash_is_deterministic_16_hex() {
267        let a = codeclimate_fingerprint_hash(&["src/index.ts", "FEATURE_X", "3"]);
268        let b = codeclimate_fingerprint_hash(&["src/index.ts", "FEATURE_X", "3"]);
269        assert_eq!(a, b);
270        assert_eq!(a.len(), 16);
271        assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
272        // Per-part separation means reordering parts changes the digest.
273        assert_ne!(
274            a,
275            codeclimate_fingerprint_hash(&["FEATURE_X", "src/index.ts", "3"])
276        );
277    }
278
279    /// Pins exact digests. CI review threads and CodeClimate consumers match on
280    /// these values, so a change to the hash breaks every saved fingerprint.
281    /// The expected values come from an independent FNV-1a 64 script.
282    #[test]
283    fn codeclimate_fingerprint_hash_golden_values() {
284        assert_eq!(
285            codeclimate_fingerprint_hash(&["src/index.ts", "FEATURE_X", "3"]),
286            "2278c9d9bd9d2dd2"
287        );
288        assert_eq!(
289            codeclimate_fingerprint_hash(&["fallow/unused-file", "src/orphan.ts"]),
290            "c03b925ddb7d871a"
291        );
292        assert_eq!(codeclimate_fingerprint_hash(&[]), "cbf29ce484222325");
293    }
294
295    #[test]
296    fn codeclimate_fingerprint_parts_are_separated() {
297        assert_ne!(
298            codeclimate_fingerprint_hash(&["ab", "c"]),
299            codeclimate_fingerprint_hash(&["a", "bc"])
300        );
301    }
302
303    #[test]
304    fn annotate_codeclimate_issues_adds_owner_from_location_path() {
305        let mut issues = vec![build_codeclimate_issue(CodeClimateIssueInput {
306            check_name: "fallow/test",
307            description: "description",
308            category: "Bug Risk",
309            severity: CodeClimateSeverity::Minor,
310            fingerprint: "abc123",
311            path: "src/app.ts",
312            begin_line: Some(3),
313        })];
314
315        annotate_codeclimate_issues(&mut issues, CodeClimateAnnotationField::Owner, |path| {
316            format!("team:{path}")
317        });
318        let value = codeclimate_issues_to_value(&issues);
319
320        assert_eq!(value[0]["owner"], "team:src/app.ts");
321    }
322
323    #[test]
324    fn annotate_codeclimate_issues_adds_group_from_location_path() {
325        let mut issues = vec![build_codeclimate_issue(CodeClimateIssueInput {
326            check_name: "fallow/test",
327            description: "description",
328            category: "Bug Risk",
329            severity: CodeClimateSeverity::Minor,
330            fingerprint: "abc123",
331            path: "src/app.ts",
332            begin_line: Some(3),
333        })];
334
335        annotate_codeclimate_issues(&mut issues, CodeClimateAnnotationField::Group, |path| {
336            format!("group:{path}")
337        });
338        let value = codeclimate_issues_to_value(&issues);
339
340        assert_eq!(value[0]["group"], "group:src/app.ts");
341        assert!(value[0].get("owner").is_none());
342    }
343}