mdbook-lint 0.16.0

A fast markdown linter and preprocessor for mdBook
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
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
457
458
459
460
461
462
463
464
465
466
467
//! SARIF v2.1.0 report generation.
//!
//! The CI documentation and the companion GitHub Action have advertised SARIF
//! output for some time (issue #471). This module implements it against the
//! OASIS SARIF 2.1.0 schema, deriving rule descriptors from `RuleMetadata` so
//! the report stays consistent with the registry.

use mdbook_lint_core::{LintEngine, Severity, Violation};
use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::path::Path;

/// Schema URL emitted in the report.
const SARIF_SCHEMA: &str = "https://json.schemastore.org/sarif-2.1.0.json";

/// SARIF specification version this report conforms to.
const SARIF_VERSION: &str = "2.1.0";

/// Tool home page, reported as the driver's `informationUri`.
const INFORMATION_URI: &str = "https://github.com/joshrotenberg/mdbook-lint";

/// Base URL of the published rule reference.
const DOCS_BASE_URI: &str = "https://joshrotenberg.github.io/mdbook-lint/rules";

/// Map a violation severity onto a SARIF result level.
///
/// SARIF defines `none`, `note`, `warning`, and `error`. Info maps to `note`,
/// which is how code-scanning surfaces advisory results.
fn sarif_level(severity: Severity) -> &'static str {
    match severity {
        Severity::Error => "error",
        Severity::Warning => "warning",
        Severity::Info => "note",
    }
}

/// Documentation sub-path for a rule ID.
///
/// `MDBOOK` is checked before `MD`, since the former also starts with `MD`.
fn docs_subdir(rule_id: &str) -> Option<&'static str> {
    if rule_id.starts_with("MDBOOK") {
        Some("mdbook")
    } else if rule_id.starts_with("CONTENT") {
        Some("content")
    } else if rule_id.starts_with("ADR") {
        Some("adr")
    } else if rule_id.starts_with("MD") {
        Some("standard")
    } else {
        None
    }
}

/// Published documentation URL for a rule, when its ruleset is recognized.
fn help_uri(rule_id: &str) -> Option<String> {
    let subdir = docs_subdir(rule_id)?;
    Some(format!(
        "{DOCS_BASE_URI}/{subdir}/{}.html",
        rule_id.to_lowercase()
    ))
}

/// Normalize a file path into a SARIF `artifactLocation` URI.
///
/// SARIF consumers, GitHub code scanning in particular, expect paths relative
/// to the repository root with forward slashes. Absolute paths under the
/// working directory are made relative; anything else is passed through with
/// separators normalized.
fn artifact_uri(path: &str) -> String {
    let path = Path::new(path);

    let relative = std::env::current_dir()
        .ok()
        .and_then(|cwd| path.strip_prefix(&cwd).ok().map(Path::to_path_buf))
        .unwrap_or_else(|| path.to_path_buf());

    relative
        .to_string_lossy()
        .replace('\\', "/")
        .trim_start_matches("./")
        .to_string()
}

/// Build a rule descriptor for the driver's `rules` array.
///
/// Metadata comes from the registry where the rule is known. A violation always
/// carries an ID, name, and message, so a descriptor can still be produced for
/// a rule the registry cannot resolve.
fn rule_descriptor(rule_id: &str, rule_name: &str, engine: &LintEngine) -> Value {
    let mut descriptor = json!({
        "id": rule_id,
        "name": rule_name,
    });

    if let Some(uri) = help_uri(rule_id) {
        descriptor["helpUri"] = json!(uri);
    }

    // Document rules and collection rules live in separate registry lists.
    let registry = engine.registry();
    let resolved = registry
        .get_rule(rule_id)
        .map(|r| (r.description().to_string(), r.metadata()))
        .or_else(|| {
            registry
                .get_collection_rule(rule_id)
                .map(|r| (r.description().to_string(), r.metadata()))
        });

    if let Some((description, metadata)) = resolved {
        descriptor["shortDescription"] = json!({ "text": description });

        let mut properties = json!({
            "category": format!("{:?}", metadata.category),
            "stability": format!("{:?}", metadata.stability),
            "runsByDefault": metadata.runs_by_default(),
        });
        if let Some(version) = metadata.introduced_in {
            properties["introducedIn"] = json!(version);
        }
        if metadata.deprecated {
            properties["deprecated"] = json!(true);
            if let Some(reason) = metadata.deprecated_reason {
                properties["deprecatedReason"] = json!(reason);
            }
        }
        descriptor["properties"] = properties;
    }

    descriptor
}

/// Build a complete SARIF v2.1.0 report for the given violations.
///
/// Rule descriptors are emitted for the rules that actually produced results,
/// and each result references its descriptor by `ruleIndex`.
pub fn build_report(violations_by_file: &[(String, Vec<Violation>)], engine: &LintEngine) -> Value {
    // Stable descriptor ordering, so repeated runs over the same input produce
    // byte-identical reports.
    let mut rule_names: BTreeMap<&str, &str> = BTreeMap::new();
    for (_, violations) in violations_by_file {
        for violation in violations {
            rule_names
                .entry(violation.rule_id.as_str())
                .or_insert(violation.rule_name.as_str());
        }
    }

    let rule_index: BTreeMap<&str, usize> = rule_names
        .keys()
        .enumerate()
        .map(|(index, id)| (*id, index))
        .collect();

    let rules: Vec<Value> = rule_names
        .iter()
        .map(|(id, name)| rule_descriptor(id, name, engine))
        .collect();

    // Results are sorted by location and then rule ID. The engine does not
    // guarantee an order for violations reported at the same position, so two
    // runs over identical input could otherwise emit results in different
    // orders, producing spurious diffs and defeating caching.
    let mut ordered: Vec<(String, usize, usize, &str, Value)> = violations_by_file
        .iter()
        .flat_map(|(file_path, violations)| {
            let uri = artifact_uri(file_path);
            let rule_index = &rule_index;
            violations.iter().map(move |violation| {
                let mut region = json!({ "startLine": violation.line.max(1) });
                if violation.column > 0 {
                    region["startColumn"] = json!(violation.column);
                }

                let mut result = json!({
                    "ruleId": violation.rule_id,
                    "level": sarif_level(violation.severity),
                    "message": { "text": violation.message },
                    "locations": [{
                        "physicalLocation": {
                            "artifactLocation": { "uri": uri },
                            "region": region,
                        }
                    }],
                });

                if let Some(index) = rule_index.get(violation.rule_id.as_str()) {
                    result["ruleIndex"] = json!(index);
                }

                (
                    uri.clone(),
                    violation.line,
                    violation.column,
                    violation.rule_id.as_str(),
                    result,
                )
            })
        })
        .collect();

    ordered.sort_by(|a, b| {
        (&a.0, a.1, a.2, a.3)
            .cmp(&(&b.0, b.1, b.2, b.3))
            .then_with(|| a.4.to_string().cmp(&b.4.to_string()))
    });

    let results: Vec<Value> = ordered
        .into_iter()
        .map(|(_, _, _, _, value)| value)
        .collect();

    json!({
        "$schema": SARIF_SCHEMA,
        "version": SARIF_VERSION,
        "runs": [{
            "tool": {
                "driver": {
                    "name": "mdbook-lint",
                    "version": env!("CARGO_PKG_VERSION"),
                    "semanticVersion": env!("CARGO_PKG_VERSION"),
                    "informationUri": INFORMATION_URI,
                    "rules": rules,
                }
            },
            "results": results,
        }]
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use mdbook_lint_core::PluginRegistry;
    use mdbook_lint_rulesets::{MdBookRuleProvider, StandardRuleProvider};

    fn test_engine() -> LintEngine {
        let mut registry = PluginRegistry::new();
        registry
            .register_provider(Box::new(StandardRuleProvider))
            .unwrap();
        registry
            .register_provider(Box::new(MdBookRuleProvider))
            .unwrap();
        registry.create_engine().unwrap()
    }

    fn violation(rule_id: &str, rule_name: &str, line: usize, column: usize) -> Violation {
        Violation {
            rule_id: rule_id.to_string(),
            rule_name: rule_name.to_string(),
            message: format!("{rule_id} fired"),
            line,
            column,
            severity: Severity::Warning,
            fix: None,
        }
    }

    #[test]
    fn test_report_has_required_sarif_envelope() {
        let report = build_report(&[], &test_engine());

        assert_eq!(report["version"], SARIF_VERSION);
        assert_eq!(report["$schema"], SARIF_SCHEMA);

        let driver = &report["runs"][0]["tool"]["driver"];
        assert_eq!(driver["name"], "mdbook-lint");
        assert_eq!(driver["informationUri"], INFORMATION_URI);
        assert!(!driver["version"].as_str().unwrap().is_empty());

        // An empty run is still a valid report with an empty results array.
        assert_eq!(report["runs"][0]["results"].as_array().unwrap().len(), 0);
    }

    #[test]
    fn test_severity_maps_to_sarif_levels() {
        assert_eq!(sarif_level(Severity::Error), "error");
        assert_eq!(sarif_level(Severity::Warning), "warning");
        assert_eq!(sarif_level(Severity::Info), "note");
    }

    #[test]
    fn test_results_carry_location_and_rule_index() {
        let violations = vec![(
            "docs/guide.md".to_string(),
            vec![violation("MD001", "heading-increment", 4, 2)],
        )];
        let report = build_report(&violations, &test_engine());

        let result = &report["runs"][0]["results"][0];
        assert_eq!(result["ruleId"], "MD001");
        assert_eq!(result["level"], "warning");
        assert_eq!(result["message"]["text"], "MD001 fired");

        let location = &result["locations"][0]["physicalLocation"];
        assert_eq!(location["artifactLocation"]["uri"], "docs/guide.md");
        assert_eq!(location["region"]["startLine"], 4);
        assert_eq!(location["region"]["startColumn"], 2);

        // ruleIndex must point at the matching descriptor.
        let index = result["ruleIndex"].as_u64().unwrap() as usize;
        let rules = report["runs"][0]["tool"]["driver"]["rules"]
            .as_array()
            .unwrap();
        assert_eq!(rules[index]["id"], "MD001");
    }

    #[test]
    fn test_rule_descriptors_are_deduplicated_and_sourced_from_metadata() {
        let violations = vec![
            (
                "a.md".to_string(),
                vec![
                    violation("MD001", "heading-increment", 1, 1),
                    violation("MD001", "heading-increment", 9, 1),
                ],
            ),
            (
                "b.md".to_string(),
                vec![violation("MD009", "no-trailing-spaces", 2, 1)],
            ),
        ];
        let report = build_report(&violations, &test_engine());

        let rules = report["runs"][0]["tool"]["driver"]["rules"]
            .as_array()
            .unwrap();
        assert_eq!(rules.len(), 2, "one descriptor per distinct rule");

        let md001 = rules.iter().find(|r| r["id"] == "MD001").unwrap();
        assert_eq!(md001["name"], "heading-increment");
        // Description and properties come from the registry, not the violation.
        assert!(
            md001["shortDescription"]["text"]
                .as_str()
                .is_some_and(|s| !s.is_empty())
        );
        assert_eq!(md001["properties"]["category"], "Structure");
        assert_eq!(md001["properties"]["stability"], "Stable");
        assert_eq!(
            md001["helpUri"],
            "https://joshrotenberg.github.io/mdbook-lint/rules/standard/md001.html"
        );

        assert_eq!(report["runs"][0]["results"].as_array().unwrap().len(), 3);
    }

    #[test]
    fn test_unknown_rule_still_produces_a_descriptor() {
        // A violation from a rule the registry cannot resolve must not be dropped.
        let violations = vec![(
            "a.md".to_string(),
            vec![violation("ZZZ999", "mystery", 1, 1)],
        )];
        let report = build_report(&violations, &test_engine());

        let rules = report["runs"][0]["tool"]["driver"]["rules"]
            .as_array()
            .unwrap();
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0]["id"], "ZZZ999");
        assert!(rules[0]["shortDescription"].is_null());
        assert!(
            rules[0]["helpUri"].is_null(),
            "no docs path for unknown prefix"
        );
        assert_eq!(report["runs"][0]["results"][0]["ruleId"], "ZZZ999");
    }

    #[test]
    fn test_help_uri_routes_by_ruleset() {
        assert!(help_uri("MD001").unwrap().contains("/standard/md001.html"));
        assert!(
            help_uri("MDBOOK005")
                .unwrap()
                .contains("/mdbook/mdbook005.html"),
            "MDBOOK must not be treated as MD"
        );
        assert!(help_uri("CONTENT004").unwrap().contains("/content/"));
        assert!(help_uri("ADR001").unwrap().contains("/adr/"));
        assert!(help_uri("ZZZ999").is_none());
    }

    #[test]
    fn test_artifact_uri_normalizes_separators() {
        assert_eq!(artifact_uri("docs/guide.md"), "docs/guide.md");
        assert_eq!(artifact_uri("./docs/guide.md"), "docs/guide.md");
        assert_eq!(artifact_uri(r"docs\guide.md"), "docs/guide.md");
    }

    #[test]
    fn test_results_are_sorted_by_location_then_rule() {
        // The engine does not order violations reported at the same position, so
        // the report imposes its own order. Without this, two runs over identical
        // input could emit results in different orders.
        let violations = vec![
            (
                "b.md".to_string(),
                vec![violation("MD009", "no-trailing-spaces", 5, 1)],
            ),
            (
                "a.md".to_string(),
                vec![
                    violation("MD060", "z-rule", 3, 1),
                    violation("MD001", "heading-increment", 3, 1),
                    violation("MD001", "heading-increment", 1, 1),
                ],
            ),
        ];
        let report = build_report(&violations, &test_engine());
        let results = report["runs"][0]["results"].as_array().unwrap();

        let order: Vec<(String, u64, String)> = results
            .iter()
            .map(|r| {
                (
                    r["locations"][0]["physicalLocation"]["artifactLocation"]["uri"]
                        .as_str()
                        .unwrap()
                        .to_string(),
                    r["locations"][0]["physicalLocation"]["region"]["startLine"]
                        .as_u64()
                        .unwrap(),
                    r["ruleId"].as_str().unwrap().to_string(),
                )
            })
            .collect();

        assert_eq!(
            order,
            vec![
                ("a.md".to_string(), 1, "MD001".to_string()),
                ("a.md".to_string(), 3, "MD001".to_string()),
                ("a.md".to_string(), 3, "MD060".to_string()),
                ("b.md".to_string(), 5, "MD009".to_string()),
            ]
        );
    }

    #[test]
    fn test_report_is_deterministic() {
        let violations = vec![(
            "a.md".to_string(),
            vec![
                violation("MD009", "no-trailing-spaces", 1, 1),
                violation("MD001", "heading-increment", 2, 1),
            ],
        )];
        let engine = test_engine();

        let first = serde_json::to_string(&build_report(&violations, &engine)).unwrap();
        let second = serde_json::to_string(&build_report(&violations, &engine)).unwrap();
        assert_eq!(first, second);
    }

    #[test]
    fn test_zero_column_is_omitted_rather_than_emitted_as_zero() {
        // SARIF columns are 1-based; 0 is not a legal startColumn.
        let violations = vec![("a.md".to_string(), vec![violation("MD001", "x", 3, 0)])];
        let report = build_report(&violations, &test_engine());

        let region = &report["runs"][0]["results"][0]["locations"][0]["physicalLocation"]["region"];
        assert_eq!(region["startLine"], 3);
        assert!(region["startColumn"].is_null());
    }
}