dockerfile-roast 1.4.4

A Dockerfile linter with personality — catches bad practices with snarky, funny error messages
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
use crate::rules::{Finding, Severity};
use colored::*;
use serde::Serialize;
use std::collections::HashMap;

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum OutputFormat {
    Terminal,
    Json,
    Github,
    Compact,
    Sarif,
}

impl std::str::FromStr for OutputFormat {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "terminal" | "tty" => Ok(OutputFormat::Terminal),
            "json" => Ok(OutputFormat::Json),
            "github" | "gh" => Ok(OutputFormat::Github),
            "compact" => Ok(OutputFormat::Compact),
            "sarif" => Ok(OutputFormat::Sarif),
            other => Err(format!("unknown format '{}'", other)),
        }
    }
}

#[derive(Serialize)]
struct JsonFinding {
    rule: String,
    severity: String,
    line: usize,
    message: String,
    roast: String,
}

#[derive(Serialize)]
struct JsonOutput {
    file: String,
    total: usize,
    errors: usize,
    warnings: usize,
    infos: usize,
    findings: Vec<JsonFinding>,
}

pub fn print_findings(file: &str, findings: &[Finding], format: OutputFormat, no_roast: bool) {
    match format {
        OutputFormat::Terminal => print_terminal(file, findings, no_roast),
        OutputFormat::Json => print_json(file, findings),
        OutputFormat::Github => print_github(file, findings),
        OutputFormat::Compact => print_compact(file, findings),
        OutputFormat::Sarif => {
            unreachable!("SARIF output is handled via print_sarif, not print_findings")
        }
    }
}

fn severity_color(s: &Severity) -> ColoredString {
    match s {
        Severity::Error => "ERROR".red().bold(),
        Severity::Warning => "WARN ".yellow().bold(),
        Severity::Info => "INFO ".cyan(),
    }
}

fn print_terminal(file: &str, findings: &[Finding], no_roast: bool) {
    if findings.is_empty() {
        println!(
            "\n  {} {}\n",
            "".green().bold(),
            format!("{} passed with no issues. Impressive restraint.", file).green()
        );
        return;
    }

    println!(
        "\n  {} {}\n",
        "🔥".bold(),
        format!("Roasting {}...", file).bold()
    );

    for f in findings {
        let line_info = if f.line > 0 {
            format!("{}:{}", file, f.line).dimmed().to_string()
        } else {
            file.dimmed().to_string()
        };

        println!(
            "  {} [{}]  {}",
            severity_color(&f.severity),
            f.rule.dimmed(),
            f.message.bold()
        );
        println!("  {}      at {}", " ".repeat(5), line_info);
        if !no_roast {
            println!(
                "  {}      {} {}\n",
                " ".repeat(5),
                "💬".dimmed(),
                format!("\"{}\"", f.roast).italic().dimmed()
            );
        } else {
            println!();
        }
    }

    let errors = findings
        .iter()
        .filter(|f| f.severity == Severity::Error)
        .count();
    let warnings = findings
        .iter()
        .filter(|f| f.severity == Severity::Warning)
        .count();
    let infos = findings
        .iter()
        .filter(|f| f.severity == Severity::Info)
        .count();

    println!(
        "  {} {} error(s), {} warning(s), {} info(s)",
        "Summary:".bold(),
        errors.to_string().red().bold(),
        warnings.to_string().yellow().bold(),
        infos.to_string().cyan()
    );

    if errors > 0 {
        println!(
            "\n  {} This Dockerfile is a liability. Fix the errors.",
            "💀".bold()
        );
    } else if warnings > 0 {
        println!(
            "\n  {} Could be worse. Could also be much better.",
            "🤔".bold()
        );
    } else {
        println!(
            "\n  {} Only informational findings. You're almost competent.",
            "📝".bold()
        );
    }
    println!();
}

fn print_json(file: &str, findings: &[Finding]) {
    println!(
        "{}",
        serde_json::to_string_pretty(&json_output(file, findings)).unwrap()
    );
}

fn json_output(file: &str, findings: &[Finding]) -> JsonOutput {
    let errors = findings
        .iter()
        .filter(|f| f.severity == Severity::Error)
        .count();
    let warnings = findings
        .iter()
        .filter(|f| f.severity == Severity::Warning)
        .count();
    let infos = findings
        .iter()
        .filter(|f| f.severity == Severity::Info)
        .count();
    JsonOutput {
        file: file.to_string(),
        total: findings.len(),
        errors,
        warnings,
        infos,
        findings: findings
            .iter()
            .map(|f| JsonFinding {
                rule: f.rule.to_string(),
                severity: f.severity.to_string(),
                line: f.line,
                message: f.message.clone(),
                roast: f.roast.clone(),
            })
            .collect(),
    }
}

/// Emit one valid JSON document for a repository scan while preserving the
/// historical object shape for a single Dockerfile.
pub fn print_json_results(results: &[(&str, &[Finding])]) {
    if let [(file, findings)] = results {
        print_json(file, findings);
        return;
    }
    let output = results
        .iter()
        .map(|(file, findings)| json_output(file, findings))
        .collect::<Vec<_>>();
    println!("{}", serde_json::to_string_pretty(&output).unwrap());
}

fn print_github(file: &str, findings: &[Finding]) {
    for f in findings {
        let level = match f.severity {
            Severity::Error => "error",
            Severity::Warning => "warning",
            Severity::Info => "notice",
        };
        let line_part = if f.line > 0 {
            format!(",line={}", f.line)
        } else {
            String::new()
        };
        println!(
            "::{} file={}{},title=[{}] {}::{}",
            level, file, line_part, f.rule, f.message, f.roast
        );
    }
}

fn print_compact(file: &str, findings: &[Finding]) {
    for f in findings {
        let line_info = if f.line > 0 {
            format!(":{}", f.line)
        } else {
            String::new()
        };
        println!(
            "{}{}:{} [{}] {}",
            file, line_info, f.severity, f.rule, f.message
        );
    }
}

/// Emit a SARIF 2.1.0 document covering all linted files at once.
///
/// SARIF is a document format — all files and findings must be collected
/// before emission. Call this once after linting every file, not per-file.
///
/// Compatible with GitHub Advanced Security (`upload-sarif`), VS Code SARIF
/// Viewer, and any tool that consumes the OASIS SARIF 2.1.0 schema.
pub fn print_sarif(results: &[(&str, &[Finding])]) {
    println!("{}", build_sarif(results));
}

fn build_sarif(results: &[(&str, &[Finding])]) -> String {
    let all_rule_meta = crate::rules::all_rules();
    let rule_desc: HashMap<&str, &str> = all_rule_meta
        .iter()
        .map(|r| (r.id, r.description))
        .collect();
    let rule_categories: HashMap<&str, &[&str]> = all_rule_meta
        .iter()
        .map(|rule| (rule.id, rule.categories()))
        .collect();

    // Collect the ordered, deduplicated set of rule IDs that actually fired.
    // Sorted for deterministic output and so ruleIndex values are stable.
    let mut seen_ids = std::collections::BTreeSet::new();
    for (_, findings) in results {
        for f in *findings {
            seen_ids.insert(f.rule);
        }
    }
    let rule_ids: Vec<&str> = seen_ids.into_iter().collect();

    // ruleId → index in the rules array (ruleIndex in results must match).
    let rule_index: HashMap<&str, usize> = rule_ids
        .iter()
        .enumerate()
        .map(|(i, &id)| (id, i))
        .collect();

    // Highest severity seen per rule — used for defaultConfiguration.level.
    let mut rule_max_sev: HashMap<&str, Severity> = HashMap::new();
    for (_, findings) in results {
        for f in *findings {
            let entry = rule_max_sev.entry(f.rule).or_insert(Severity::Info);
            if f.severity > *entry {
                *entry = f.severity;
            }
        }
    }

    // Build tool.driver.rules
    let sarif_rules: Vec<serde_json::Value> = rule_ids
        .iter()
        .map(|&id| {
            let desc = rule_desc.get(id).copied().unwrap_or(id);
            let level = sarif_level(rule_max_sev.get(id).unwrap_or(&Severity::Info));
            let categories = rule_categories.get(id).copied().unwrap_or_default();
            serde_json::json!({
                "id": id,
                "name": id,
                "shortDescription": { "text": desc },
                "helpUri": "https://github.com/immanuwell/dockerfile-roast",
                "defaultConfiguration": { "level": level },
                "properties": { "tags": categories }
            })
        })
        .collect();

    // Build results array
    let mut sarif_results: Vec<serde_json::Value> = Vec::new();
    for (file, findings) in results {
        let uri = normalize_uri(file);
        for f in *findings {
            let idx = *rule_index.get(f.rule).unwrap_or(&0);
            let mut result = serde_json::json!({
                "ruleId": f.rule,
                "ruleIndex": idx,
                "level": sarif_level(&f.severity),
                "message": { "text": f.message },
                "locations": [{
                    "physicalLocation": {
                        "artifactLocation": {
                            "uri": uri,
                            "uriBaseId": "%SRCROOT%"
                        }
                    }
                }]
            });
            // region is optional in SARIF; only add when we have a real line number.
            if f.line > 0 {
                result["locations"][0]["physicalLocation"]["region"] =
                    serde_json::json!({ "startLine": f.line });
            }
            sarif_results.push(result);
        }
    }

    // Artifacts — the list of scanned files (optional but useful for tooling).
    let artifacts: Vec<serde_json::Value> = results
        .iter()
        .map(|(file, _)| {
            serde_json::json!({
                "location": {
                    "uri": normalize_uri(file),
                    "uriBaseId": "%SRCROOT%"
                }
            })
        })
        .collect();

    let doc = serde_json::json!({
        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
        "version": "2.1.0",
        "runs": [{
            "tool": {
                "driver": {
                    "name": "droast",
                    "version": env!("CARGO_PKG_VERSION"),
                    "informationUri": "https://github.com/immanuwell/dockerfile-roast",
                    "rules": sarif_rules
                }
            },
            "results": sarif_results,
            "artifacts": artifacts
        }]
    });

    serde_json::to_string_pretty(&doc).unwrap()
}

/// Map droast severity to the SARIF level string.
/// SARIF uses "note" for informational findings, not "info".
fn sarif_level(sev: &Severity) -> &'static str {
    match sev {
        Severity::Error => "error",
        Severity::Warning => "warning",
        Severity::Info => "note",
    }
}

/// Convert a file path to a forward-slash URI relative to the repo root.
/// Absolute paths are made relative by stripping the current working directory.
fn normalize_uri(path: &str) -> String {
    let p = std::path::Path::new(path);
    let relative = if p.is_absolute() {
        std::env::current_dir()
            .ok()
            .and_then(|cwd| p.strip_prefix(&cwd).ok().map(|r| r.to_path_buf()))
            .unwrap_or_else(|| p.to_path_buf())
    } else {
        p.to_path_buf()
    };
    relative.to_string_lossy().replace('\\', "/")
}

pub fn print_summary_header() {
    println!(
        "\n{}",
        r#"
  ██████╗ ██████╗  ██████╗  █████╗ ███████╗████████╗
  ██╔══██╗██╔══██╗██╔═══██╗██╔══██╗██╔════╝╚══██╔══╝
  ██║  ██║██████╔╝██║   ██║███████║███████╗   ██║
  ██║  ██║██╔══██╗██║   ██║██╔══██║╚════██║   ██║
  ██████╔╝██║  ██║╚██████╔╝██║  ██║███████║   ██║
  ╚═════╝ ╚═╝  ╚═╝ ╚═════╝ ╚═╝  ╚═╝╚══════╝   ╚═╝
  Dockerfile linter with personality
"#
        .bold()
        .red()
    );
}