Skip to main content

logcompact/
lib.rs

1use logcompact_builtins::{Diagnostic, Reduction, Severity, TestFailure};
2use serde_json::{Value, json};
3
4/// Stable presentation formats supported by the standalone adapter.
5#[derive(Clone, Copy, Debug, Eq, PartialEq)]
6pub enum OutputFormat {
7    Human,
8    Json,
9    JsonLines,
10    Sarif,
11    GitHub,
12}
13
14#[must_use]
15pub fn render(reduction: &Reduction, format: OutputFormat) -> String {
16    match format {
17        OutputFormat::Human => render_human(reduction),
18        OutputFormat::Json => serde_json::to_string_pretty(reduction)
19            .expect("the reduction data model is always serializable"),
20        OutputFormat::JsonLines => render_json_lines(reduction),
21        OutputFormat::Sarif => serde_json::to_string_pretty(&sarif(reduction))
22            .expect("the generated SARIF value is always serializable"),
23        OutputFormat::GitHub => render_github(reduction),
24    }
25}
26
27#[must_use]
28pub fn has_severity(reduction: &Reduction, minimum: Severity) -> bool {
29    reduction
30        .diagnostics
31        .iter()
32        .any(|diagnostic| severity_rank(diagnostic.severity) <= severity_rank(minimum))
33        || (minimum == Severity::Error && !reduction.test_failures.is_empty())
34}
35
36fn severity_rank(severity: Severity) -> u8 {
37    match severity {
38        Severity::Error => 0,
39        Severity::Warning => 1,
40        Severity::Note => 2,
41    }
42}
43
44fn render_human(reduction: &Reduction) -> String {
45    let mut output = String::new();
46    for diagnostic in &reduction.diagnostics {
47        let severity = match diagnostic.severity {
48            Severity::Error => "error",
49            Severity::Warning => "warning",
50            Severity::Note => "note",
51        };
52        if let Some(location) = &diagnostic.location {
53            output.push_str(&location.path);
54            if let Some(line) = location.line {
55                output.push(':');
56                output.push_str(&line.to_string());
57            }
58            if let Some(column) = location.column {
59                output.push(':');
60                output.push_str(&column.to_string());
61            }
62            output.push_str(": ");
63        }
64        output.push_str(severity);
65        output.push_str(": ");
66        output.push_str(&diagnostic.message);
67        if diagnostic.repetition_count > 1 {
68            output.push_str(" [repeated ");
69            output.push_str(&diagnostic.repetition_count.to_string());
70            output.push(']');
71        }
72        output.push('\n');
73    }
74    for failure in &reduction.test_failures {
75        output.push_str("test failed: ");
76        output.push_str(&failure.name);
77        output.push_str(": ");
78        output.push_str(&failure.message);
79        output.push('\n');
80    }
81    if reduction.truncated {
82        output.push_str("note: reduction was truncated\n");
83    }
84    output
85}
86
87fn render_json_lines(reduction: &Reduction) -> String {
88    let mut lines = Vec::new();
89    for diagnostic in &reduction.diagnostics {
90        lines.push(
91            serde_json::to_string(&json!({"type": "diagnostic", "value": diagnostic}))
92                .expect("a diagnostic is always serializable"),
93        );
94    }
95    for failure in &reduction.test_failures {
96        lines.push(
97            serde_json::to_string(&json!({"type": "test_failure", "value": failure}))
98                .expect("a test failure is always serializable"),
99        );
100    }
101    lines.push(
102        serde_json::to_string(&json!({
103            "type": "summary",
104            "truncated": reduction.truncated,
105            "omitted_diagnostics": reduction.omitted_diagnostics,
106            "used_bytes": reduction.used_bytes,
107            "stats": reduction.stats,
108        }))
109        .expect("summary accounting is always serializable"),
110    );
111    let mut output = lines.join("\n");
112    output.push('\n');
113    output
114}
115
116fn render_github(reduction: &Reduction) -> String {
117    let mut output = String::new();
118    for diagnostic in &reduction.diagnostics {
119        let command = match diagnostic.severity {
120            Severity::Error => "error",
121            Severity::Warning => "warning",
122            Severity::Note => "notice",
123        };
124        output.push_str("::");
125        output.push_str(command);
126        if let Some(location) = &diagnostic.location {
127            output.push_str(" file=");
128            output.push_str(&escape_property(&location.path));
129            if let Some(line) = location.line {
130                output.push_str(",line=");
131                output.push_str(&line.to_string());
132            }
133            if let Some(column) = location.column {
134                output.push_str(",col=");
135                output.push_str(&column.to_string());
136            }
137            if let Some(end_line) = location.end_line {
138                output.push_str(",endLine=");
139                output.push_str(&end_line.to_string());
140            }
141            if let Some(end_column) = location.end_column {
142                output.push_str(",endColumn=");
143                output.push_str(&end_column.to_string());
144            }
145        }
146        output.push_str("::");
147        output.push_str(&escape_message(&diagnostic.message));
148        output.push('\n');
149    }
150    for failure in &reduction.test_failures {
151        output.push_str("::error title=");
152        output.push_str(&escape_property(&failure.name));
153        output.push_str("::");
154        output.push_str(&escape_message(&failure.message));
155        output.push('\n');
156    }
157    output
158}
159
160fn sarif(reduction: &Reduction) -> Value {
161    let mut rules = Vec::<Value>::new();
162    let mut rule_ids = Vec::<String>::new();
163    let results = reduction
164        .diagnostics
165        .iter()
166        .map(|diagnostic| {
167            let rule_id = diagnostic
168                .code
169                .clone()
170                .unwrap_or_else(|| "logcompact.finding".to_owned());
171            if !rule_ids.contains(&rule_id) {
172                rule_ids.push(rule_id.clone());
173                rules.push(json!({
174                    "id": rule_id,
175                    "shortDescription": {"text": "Reduced log diagnostic"}
176                }));
177            }
178            sarif_result(diagnostic, &rule_id)
179        })
180        .chain(reduction.test_failures.iter().map(sarif_test_failure))
181        .collect::<Vec<_>>();
182    json!({
183        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
184        "version": "2.1.0",
185        "runs": [{
186            "tool": {"driver": {"name": "logcompact", "rules": rules}},
187            "results": results,
188            "properties": {
189                "truncated": reduction.truncated,
190                "omittedDiagnostics": reduction.omitted_diagnostics
191            }
192        }]
193    })
194}
195
196fn sarif_result(diagnostic: &Diagnostic, rule_id: &str) -> Value {
197    let level = match diagnostic.severity {
198        Severity::Error => "error",
199        Severity::Warning => "warning",
200        Severity::Note => "note",
201    };
202    let locations = diagnostic
203        .location
204        .as_ref()
205        .map_or_else(Vec::new, |location| {
206            let mut region = json!({
207                "startLine": location.line.unwrap_or(1),
208                "startColumn": location.column.unwrap_or(1)
209            });
210            if let Some(end_line) = location.end_line {
211                region["endLine"] = json!(end_line);
212            }
213            if let Some(end_column) = location.end_column {
214                region["endColumn"] = json!(end_column);
215            }
216            vec![json!({
217                "physicalLocation": {
218                    "artifactLocation": {"uri": location.path},
219                    "region": region
220                }
221            })]
222        });
223    json!({
224        "ruleId": rule_id,
225        "level": level,
226        "message": {"text": diagnostic.message},
227        "locations": locations,
228        "properties": {
229            "class": diagnostic.class,
230            "quality": diagnostic.quality,
231            "repetitionCount": diagnostic.repetition_count,
232            "provenance": diagnostic.provenance
233        }
234    })
235}
236
237fn sarif_test_failure(failure: &TestFailure) -> Value {
238    let locations = failure.location.as_ref().map_or_else(Vec::new, |location| {
239        vec![json!({
240            "physicalLocation": {
241                "artifactLocation": {"uri": location.path},
242                "region": {"startLine": location.line.unwrap_or(1)}
243            }
244        })]
245    });
246    json!({
247        "ruleId": "test.failure",
248        "level": "error",
249        "message": {"text": failure.message},
250        "locations": locations,
251        "properties": {
252            "testName": failure.name,
253            "framework": failure.framework,
254            "provenance": failure.provenance
255        }
256    })
257}
258
259fn escape_message(value: &str) -> String {
260    value
261        .replace('%', "%25")
262        .replace('\r', "%0D")
263        .replace('\n', "%0A")
264}
265
266fn escape_property(value: &str) -> String {
267    escape_message(value)
268        .replace(':', "%3A")
269        .replace(',', "%2C")
270}
271
272#[cfg(test)]
273mod tests {
274    use logcompact_builtins::{DiagnosticClass, EvidenceQuality, Location, ReductionStats};
275
276    use super::*;
277
278    fn reduction() -> Reduction {
279        Reduction {
280            diagnostics: vec![Diagnostic {
281                severity: Severity::Error,
282                class: DiagnosticClass::Compiler,
283                code: Some("rust.E0308".to_owned()),
284                message: "mismatched types".to_owned(),
285                location: Some(Location {
286                    path: "src/lib.rs".to_owned(),
287                    line: Some(7),
288                    column: Some(5),
289                    end_line: Some(8),
290                    end_column: Some(9),
291                }),
292                provenance: None,
293                quality: EvidenceQuality::Located,
294                repetition_count: 1,
295            }],
296            test_failures: Vec::new(),
297            truncated: false,
298            omitted_diagnostics: 0,
299            used_bytes: 10,
300            stats: ReductionStats::default(),
301        }
302    }
303
304    #[test]
305    fn renders_human_github_and_sarif_locations() {
306        let reduction = reduction();
307        assert!(render(&reduction, OutputFormat::Human).contains("src/lib.rs:7:5"));
308        assert!(render(&reduction, OutputFormat::GitHub).contains("file=src/lib.rs,line=7,col=5"));
309        assert!(render(&reduction, OutputFormat::GitHub).contains("endLine=8,endColumn=9"));
310        let sarif = render(&reduction, OutputFormat::Sarif);
311        assert!(sarif.contains("\"version\": \"2.1.0\""));
312        assert!(sarif.contains("src/lib.rs"));
313        assert!(sarif.contains("\"endLine\": 8"));
314    }
315
316    #[test]
317    fn json_lines_ends_with_summary() {
318        let rendered = render(&reduction(), OutputFormat::JsonLines);
319        assert_eq!(rendered.lines().count(), 2);
320        assert!(rendered.lines().last().unwrap().contains("summary"));
321    }
322}