Skip to main content

snapper_fmt/
output.rs

1use serde_json::{Value, json};
2
3/// Summary of a file that needs reformatting, used by `--check` output modes.
4pub struct CheckResult {
5    pub file: String,
6    pub original_lines: usize,
7    pub formatted_lines: usize,
8}
9
10/// Output check results in JSON format.
11pub fn output_json(results: &[CheckResult]) {
12    let arr: Vec<Value> = results
13        .iter()
14        .map(|r| {
15            json!({
16                "file": r.file,
17                "original_lines": r.original_lines,
18                "formatted_lines": r.formatted_lines,
19            })
20        })
21        .collect();
22    println!("{}", serde_json::to_string_pretty(&arr).unwrap_or_default());
23}
24
25/// Output check results in SARIF v2.1.0 format for GitHub Code Scanning.
26pub fn output_sarif(results: &[CheckResult]) {
27    let sarif_results: Vec<Value> = results
28        .iter()
29        .map(|r| {
30            json!({
31                "ruleId": "snapper/needs-reformat",
32                "level": "warning",
33                "message": {
34                    "text": format!(
35                        "File needs semantic line break formatting ({} -> {} lines)",
36                        r.original_lines, r.formatted_lines
37                    )
38                },
39                "locations": [{
40                    "physicalLocation": {
41                        "artifactLocation": {
42                            "uri": r.file
43                        }
44                    }
45                }]
46            })
47        })
48        .collect();
49
50    let sarif = json!({
51        "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json",
52        "version": "2.1.0",
53        "runs": [{
54            "tool": {
55                "driver": {
56                    "name": "snapper",
57                    "informationUri": "https://snapper.turtletech.us",
58                    "rules": [{
59                        "id": "snapper/needs-reformat",
60                        "shortDescription": {
61                            "text": "File needs semantic line break formatting"
62                        }
63                    }]
64                }
65            },
66            "results": sarif_results
67        }]
68    });
69
70    println!(
71        "{}",
72        serde_json::to_string_pretty(&sarif).unwrap_or_default()
73    );
74}