easement 0.3.0

Architecture quality gate for polyglot codebases
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
use anstyle::{AnsiColor, Style};
use serde::Serialize;
use serde_json::json;

use crate::baseline::Verdict;
use crate::check::{Key, RuleId, Stats, Violation};
use crate::diff::Changes;

#[derive(Serialize)]
struct JsonReport<'a> {
    passed: bool,
    violations: &'a [Violation],
    stale: &'a [Key],
    legalized: usize,
    /// `full`, or `partial` when `passed` rests on code the check could not read.
    confidence: &'static str,
    confidence_reasons: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    diff: Option<DiffInfo<'a>>,
    stats: &'a Stats,
}

#[derive(Serialize)]
struct DiffInfo<'a> {
    base: &'a str,
    merge_base: &'a str,
}

/// Why a verdict is only as good as the code the check could read.
fn confidence_reasons(stats: &Stats, changes: Option<&Changes>) -> Vec<String> {
    let mut reasons = Vec::new();
    if let Some(changes) = changes {
        reasons.push(format!(
            "only violations on lines changed since {} were judged, the rest of the project was not",
            changes.base
        ));
    }
    if !stats.limited_to.is_empty() {
        reasons.push(format!(
            "the report is limited to {}, the rest of the project was not judged",
            stats.limited_to.join(", ")
        ));
    }
    if !stats.uncovered.is_empty() {
        reasons.push(format!(
            "{} source files were not covered by an indexer, so imports in or of them were not checked",
            stats.uncovered.len()
        ));
    }
    reasons
}

pub fn json(verdict: &Verdict, stats: &Stats, changes: Option<&Changes>) -> String {
    let reasons = confidence_reasons(stats, changes);
    let report = JsonReport {
        passed: verdict.passed(),
        violations: &verdict.new,
        stale: &verdict.stale,
        legalized: verdict.legalized,
        confidence: if reasons.is_empty() {
            "full"
        } else {
            "partial"
        },
        confidence_reasons: reasons,
        diff: changes.map(|c| DiffInfo {
            base: &c.base,
            merge_base: &c.merge_base,
        }),
        stats,
    };
    serde_json::to_string_pretty(&report).expect("report serializes")
}

/// How many uncovered files the text report names before it counts the rest.
const UNCOVERED_SHOWN: usize = 20;

const BOLD: Style = Style::new().bold();
const DIM: Style = Style::new().dimmed();
const RED: Style = AnsiColor::Red.on_default().bold();
const GREEN: Style = AnsiColor::Green.on_default().bold();
const YELLOW: Style = AnsiColor::Yellow.on_default();

/// `text` wrapped in the escape codes of `style`, or as it is when `color` is off.
fn paint(color: bool, style: Style, text: &str) -> String {
    if color {
        format!("{style}{text}{style:#}")
    } else {
        text.to_string()
    }
}

/// The plain text report.
pub fn text(verdict: &Verdict, stats: &Stats, changes: Option<&Changes>) -> String {
    render(verdict, stats, changes, false)
}

/// The text report with ANSI styles; the caller strips them where the output
/// is not a terminal.
pub fn colored(verdict: &Verdict, stats: &Stats, changes: Option<&Changes>) -> String {
    render(verdict, stats, changes, true)
}

fn render(verdict: &Verdict, stats: &Stats, changes: Option<&Changes>, color: bool) -> String {
    let mut out = String::new();
    if let Some(c) = changes {
        let short = &c.merge_base[..c.merge_base.len().min(12)];
        out.push_str(&format!(
            "Checking lines changed since {} (merge-base {short})\n\n",
            c.base
        ));
    }
    for v in &verdict.new {
        out.push_str(&format!(
            "{}: {} {}\n",
            paint(color, BOLD, &format!("{}:{}", v.file, v.line)),
            v.message,
            paint(color, RED, &format!("[{}]", v.rule.as_str()))
        ));
        if let Some(because) = &v.because {
            out.push_str(&paint(color, DIM, &format!("  because: {because}")));
            out.push('\n');
        }
    }
    if !verdict.stale.is_empty() {
        if !out.is_empty() {
            out.push('\n');
        }
        out.push_str(&paint(
            color,
            YELLOW,
            "Stale baseline entries (fixed, run `easement baseline` to shrink it):",
        ));
        out.push('\n');
        for k in &verdict.stale {
            let what = stale_description(k);
            out.push_str(&format!("  [{}] {what}\n", k.rule.as_str()));
        }
    }
    if !stats.new_dependencies.is_empty() {
        if !out.is_empty() {
            out.push('\n');
        }
        out.push_str("New dependencies between components in this change:\n");
        for d in &stats.new_dependencies {
            out.push_str(&format!("  {d}\n"));
        }
    }
    if !stats.uncovered.is_empty() {
        if !out.is_empty() {
            out.push('\n');
        }
        out.push_str(&paint(
            color,
            YELLOW,
            "Not covered by an indexer (imports in or of these files were not checked; add them to a project the indexer reads, `exclude` them, or accept them in `uncovered_ok`):",
        ));
        out.push('\n');
        for file in stats.uncovered.iter().take(UNCOVERED_SHOWN) {
            out.push_str(&format!("  {file}\n"));
        }
        if stats.uncovered.len() > UNCOVERED_SHOWN {
            out.push_str(&format!(
                "  … and {} more (all of them in `--format json`, `stats.uncovered`)\n",
                stats.uncovered.len() - UNCOVERED_SHOWN
            ));
        }
    }
    if !out.is_empty() {
        out.push('\n');
    }
    let status = if verdict.passed() {
        paint(color, GREEN, "passed")
    } else {
        paint(color, RED, "failed")
    };
    out.push_str(&format!(
        "easement {status}: {} violation(s), {} stale, {} legalized; {} files, {} internal deps",
        verdict.new.len(),
        verdict.stale.len(),
        verdict.legalized,
        stats.files,
        stats.internal_deps,
    ));
    if !stats.limited_to.is_empty() {
        out.push_str(&format!(", limited to {}", stats.limited_to.join(", ")));
    }
    if stats.suppressed > 0 {
        out.push_str(&format!(", {} suppressed", stats.suppressed));
    }
    if !stats.uncovered.is_empty() {
        out.push_str(&format!(
            ", {} files not covered by an indexer",
            stats.uncovered.len()
        ));
    }
    if stats.unmapped_files > 0 {
        out.push_str(&format!(
            ", {} files outside components",
            stats.unmapped_files
        ));
    }
    out.push('\n');
    out
}

fn stale_description(k: &Key) -> String {
    match k.rule {
        RuleId::Cycle => format!("cycle among {}", k.from),
        RuleId::Metric => format!("{} exceeds {}", k.from, k.target),
        RuleId::External => format!("{}: {} -> external {}", k.file, k.from, k.target),
        RuleId::Dependency | RuleId::Privacy => {
            format!("{}: {} -> {} ({})", k.file, k.from, k.to, k.target)
        }
        _ => format!("{}: {}", k.file, k.target),
    }
}

fn stale_message(k: &Key) -> String {
    format!(
        "stale baseline entry, fixed debt: {} (run `easement baseline` to shrink it)",
        stale_description(k)
    )
}

/// SARIF 2.1.0, the format GitHub Code Scanning ingests.
pub fn sarif(verdict: &Verdict) -> String {
    let mut ids: Vec<&str> = verdict.new.iter().map(|v| v.rule.as_str()).collect();
    if !verdict.stale.is_empty() {
        ids.push(STALE);
    }
    ids.sort_unstable();
    ids.dedup();
    let rules: Vec<_> = ids
        .iter()
        .map(|id| json!({ "id": id, "shortDescription": { "text": format!("easement {id}") } }))
        .collect();
    let mut results: Vec<_> = verdict
        .new
        .iter()
        .map(|v| {
            let text = match &v.because {
                Some(because) => format!("{} (because: {because})", v.message),
                None => v.message.clone(),
            };
            json!({
                "ruleId": v.rule.as_str(),
                "level": "error",
                "message": { "text": text },
                "locations": [{
                    "physicalLocation": {
                        "artifactLocation": { "uri": v.file },
                        "region": { "startLine": v.line },
                    },
                }],
            })
        })
        .collect();
    results.extend(verdict.stale.iter().map(|k| {
        json!({
            "ruleId": STALE,
            "level": "error",
            "message": { "text": stale_message(k) },
        })
    }));
    let report = json!({
        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
        "version": "2.1.0",
        "runs": [{
            "tool": { "driver": {
                "name": "easement",
                "version": env!("CARGO_PKG_VERSION"),
                "informationUri": env!("CARGO_PKG_HOMEPAGE"),
                "rules": rules,
            } },
            "results": results,
        }],
    });
    serde_json::to_string_pretty(&report).expect("report serializes")
}

fn escape_command(text: &str) -> String {
    text.replace('%', "%25")
        .replace('\r', "%0D")
        .replace('\n', "%0A")
}

fn escape_property(text: &str) -> String {
    escape_command(text).replace(':', "%3A").replace(',', "%2C")
}

/// GitHub Actions workflow commands: annotations on the changed files.
pub fn github(verdict: &Verdict, stats: &Stats) -> String {
    let mut out = String::new();
    for v in &verdict.new {
        let text = match &v.because {
            Some(because) => format!("{} (because: {because})", v.message),
            None => v.message.clone(),
        };
        out.push_str(&format!(
            "::error file={},line={},title={}::{}\n",
            escape_property(&v.file),
            v.line,
            escape_property(&format!("easement {}", v.rule.as_str())),
            escape_command(&text)
        ));
    }
    for k in &verdict.stale {
        out.push_str(&format!(
            "::error title={}::{}\n",
            escape_property(&format!("easement {STALE}")),
            escape_command(&stale_message(k))
        ));
    }
    if !stats.new_dependencies.is_empty() {
        out.push_str(&format!(
            "::notice title={}::{}\n",
            escape_property("easement graph"),
            escape_command(&format!(
                "New component dependencies in this change: {}",
                stats.new_dependencies.join(", ")
            ))
        ));
    }
    out.push_str(
        &text(verdict, stats, None)
            .lines()
            .last()
            .map_or_else(String::new, |l| format!("{l}\n")),
    );
    out
}

fn escape_xml(text: &str) -> String {
    text.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

/// JUnit XML: one failed test case per violation, so CI shows them as test failures.
pub fn junit(verdict: &Verdict) -> String {
    let failures = verdict.new.len() + verdict.stale.len();
    let mut out = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    out.push_str(&format!(
        "<testsuite name=\"easement\" tests=\"{}\" failures=\"{failures}\">\n",
        failures.max(1)
    ));
    if failures == 0 {
        out.push_str("  <testcase classname=\"easement\" name=\"architecture\"/>\n");
    }
    for v in &verdict.new {
        let name = format!("{}:{}", v.file, v.line);
        let mut body = v.message.clone();
        if let Some(because) = &v.because {
            body.push_str(&format!("\nbecause: {because}"));
        }
        out.push_str(&format!(
            "  <testcase classname=\"easement.{}\" name=\"{}\"><failure message=\"{}\" type=\"{}\">{}</failure></testcase>\n",
            v.rule.as_str(),
            escape_xml(&name),
            escape_xml(&v.message),
            v.rule.as_str(),
            escape_xml(&body)
        ));
    }
    for k in &verdict.stale {
        let message = stale_message(k);
        out.push_str(&format!(
            "  <testcase classname=\"easement.{STALE}\" name=\"{}\"><failure message=\"{}\" type=\"{STALE}\">{}</failure></testcase>\n",
            escape_xml(&stale_description(k)),
            escape_xml(&message),
            escape_xml(&message)
        ));
    }
    out.push_str("</testsuite>\n");
    out
}

const STALE: &str = "stale-baseline";

#[cfg(test)]
mod tests {
    use super::*;
    use crate::baseline::Verdict;

    fn verdict() -> Verdict {
        Verdict {
            new: vec![Violation {
                rule: RuleId::Dependency,
                file: "src/a.ts".into(),
                line: 3,
                message: "a -> b is not allowed <x> 100%".into(),
                because: Some("layers".into()),
                from: "a".into(),
                to: "b".into(),
                target: "src/b.ts".into(),
                specifier: "../b".into(),
                evidence: Vec::new(),
            }],
            stale: vec![Key {
                rule: RuleId::Metric,
                file: "f".into(),
                target: "max_fan_out".into(),
                from: "core".into(),
                to: String::new(),
            }],
            legalized: 0,
        }
    }

    #[test]
    fn sarif_has_located_results() {
        let report: serde_json::Value = serde_json::from_str(&sarif(&verdict())).unwrap();
        assert_eq!(report["version"], "2.1.0");
        let results = report["runs"][0]["results"].as_array().unwrap();
        assert_eq!(results.len(), 2);
        assert_eq!(results[0]["ruleId"], "dependency");
        assert_eq!(
            results[0]["locations"][0]["physicalLocation"]["region"]["startLine"],
            3
        );
        assert_eq!(results[1]["ruleId"], "stale-baseline");
        assert_eq!(
            report["runs"][0]["tool"]["driver"]["rules"]
                .as_array()
                .unwrap()
                .len(),
            2
        );
    }

    #[test]
    fn github_annotations_are_escaped() {
        let out = github(&verdict(), &Stats::default());
        assert!(out.starts_with(
            "::error file=src/a.ts,line=3,title=easement dependency::a -> b is not allowed <x> 100%25 (because: layers)\n"
        ));
        assert!(out.contains("::error title=easement stale-baseline::"));
        assert!(out.contains("easement failed"));
    }

    #[test]
    fn junit_counts_failures_and_escapes() {
        let xml = junit(&verdict());
        assert!(xml.contains("tests=\"2\" failures=\"2\""));
        assert!(xml.contains("&lt;x&gt;"));
        let clean = junit(&Verdict {
            new: vec![],
            stale: vec![],
            legalized: 0,
        });
        assert!(clean.contains("tests=\"1\" failures=\"0\""));
        assert!(clean.contains("name=\"architecture\"/>"));
    }
}