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