mdbook-lint-rulesets 0.16.0

Modular rulesets for mdbook-lint - standard and mdBook-specific linting rules
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
//! ADR format detection utilities
//!
//! Provides functionality to detect whether an ADR follows the Nygard format
//! or the MADR 4.0 format.

use regex::Regex;
use std::sync::LazyLock;

/// The format of an Architecture Decision Record
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AdrFormat {
    /// Nygard format: Plain markdown with "Date:" line and sections like Status, Context, Decision
    Nygard,
    /// MADR 4.0 format: YAML frontmatter with status/date fields
    Madr4,
    /// Auto-detect format based on content
    #[default]
    Auto,
}

impl std::fmt::Display for AdrFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AdrFormat::Nygard => write!(f, "nygard"),
            AdrFormat::Madr4 => write!(f, "madr"),
            AdrFormat::Auto => write!(f, "auto"),
        }
    }
}

impl std::str::FromStr for AdrFormat {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "nygard" => Ok(AdrFormat::Nygard),
            "madr" | "madr4" => Ok(AdrFormat::Madr4),
            "auto" => Ok(AdrFormat::Auto),
            _ => Err(format!("Unknown ADR format: {}", s)),
        }
    }
}

/// Regex for detecting Nygard-style title: "# N. Title" or "# N - Title"
static NYGARD_TITLE_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^#\s+(\d+)[.\-\s]+\s*(.+)$").expect("Invalid regex"));

/// Detect the ADR format based on content
///
/// MADR 4.0 uses YAML frontmatter, but the `adrs` tool's "ng" mode also emits
/// YAML frontmatter while keeping Nygard-style section headings, so the mere
/// presence of frontmatter is not enough to tell the two apart. When
/// frontmatter is present we disambiguate by the section headings actually used:
///
/// - MADR headings (`## Context and Problem Statement`, `## Decision Outcome`)
///   -> [`AdrFormat::Madr4`]
/// - Nygard headings (`## Consequences`, or both `## Context` and `## Decision`)
///   without MADR headings -> [`AdrFormat::Nygard`]
/// - frontmatter with neither signature -> [`AdrFormat::Madr4`] (frontmatter is
///   MADR's defining feature)
///
/// Without frontmatter the document is treated as Nygard.
pub fn detect_format(content: &str) -> AdrFormat {
    let trimmed = content.trim_start();

    if trimmed.starts_with("---") {
        let headings = section_headings(content);
        let has_madr = headings
            .iter()
            .any(|h| h == "context and problem statement" || h == "decision outcome");
        let has_nygard = headings.iter().any(|h| h == "consequences")
            || (headings.iter().any(|h| h == "context")
                && headings.iter().any(|h| h == "decision"));

        if has_nygard && !has_madr {
            return AdrFormat::Nygard;
        }
        return AdrFormat::Madr4;
    }

    // Default to Nygard format for plain markdown
    AdrFormat::Nygard
}

/// Collect the (lowercased, trimmed) text of all level-2+ ATX headings.
fn section_headings(content: &str) -> Vec<String> {
    content
        .lines()
        .filter_map(|line| {
            let trimmed = line.trim_start();
            if trimmed.starts_with("##") {
                let title = trimmed.trim_start_matches('#').trim().to_lowercase();
                if title.is_empty() { None } else { Some(title) }
            } else {
                None
            }
        })
        .collect()
}

/// Check if a document looks like an ADR based on content or path
///
/// Returns true if the document appears to be an Architecture Decision Record:
/// - Has YAML frontmatter with a `status` field (MADR)
/// - Has a numbered title like "# 1. Title" (Nygard)
/// - Has a path containing "adr" or "adrs" directory
pub fn is_adr_document(content: &str, file_path: Option<&std::path::Path>) -> bool {
    // Check if the file lives in a known ADR directory
    if let Some(path) = file_path
        && path_in_adr_dir(path)
    {
        return true;
    }

    // Check for MADR frontmatter with status field
    let trimmed = content.trim_start();
    if let Some(after_open) = trimmed.strip_prefix("---")
        && let Some(end) = after_open.find("---")
    {
        let frontmatter = &after_open[..end];
        if frontmatter.lines().any(|line| {
            let line = line.trim();
            line.starts_with("status:") || line.starts_with("status :")
        }) {
            return true;
        }
    }

    // Check for a Nygard-style numbered title near the top, skipping leading
    // blank lines and license/SPDX HTML comment headers (REUSE compliance) that
    // can push the title past the first few lines.
    has_nygard_title_near_top(content)
}

/// Known directory names that indicate a document is an ADR.
const ADR_DIRECTORY_NAMES: &[&str] = &["adr", "adrs", "decisions", "architecture-decisions"];

/// Check whether any path segment is a known ADR directory.
///
/// The path is normalized to forward slashes so it matches on every platform
/// (e.g. a `docs\decisions\0001.md` string on Linux still matches `decisions`).
fn path_in_adr_dir(path: &std::path::Path) -> bool {
    let normalized = path.to_string_lossy().replace('\\', "/").to_lowercase();
    normalized
        .split('/')
        .any(|segment| ADR_DIRECTORY_NAMES.contains(&segment))
}

/// Look for a Nygard-style numbered title in the first portion of the document,
/// skipping blank lines and HTML comment blocks so that license/SPDX headers
/// before the title do not hide it.
fn has_nygard_title_near_top(content: &str) -> bool {
    let mut in_comment = false;

    for line in content.lines().take(30) {
        let trimmed = line.trim();

        if in_comment {
            if trimmed.contains("-->") {
                in_comment = false;
            }
            continue;
        }
        if trimmed.starts_with("<!--") {
            // A single-line comment closes on the same line.
            if !trimmed.contains("-->") {
                in_comment = true;
            }
            continue;
        }
        if trimmed.is_empty() {
            continue;
        }
        if is_nygard_title(trimmed) {
            return true;
        }
    }

    false
}

/// Extract the ADR number from a Nygard-style title
///
/// Nygard titles follow the pattern "# N. Title" or "# N - Title"
pub fn extract_nygard_number(title_line: &str) -> Option<u32> {
    NYGARD_TITLE_REGEX
        .captures(title_line)
        .and_then(|caps| caps.get(1))
        .and_then(|m| m.as_str().parse().ok())
}

/// Extract the title text from a Nygard-style title line
///
/// Returns the title without the number prefix
pub fn extract_nygard_title(title_line: &str) -> Option<&str> {
    NYGARD_TITLE_REGEX
        .captures(title_line)
        .and_then(|caps| caps.get(2))
        .map(|m| m.as_str().trim())
}

/// Check if a line matches the Nygard title format
pub fn is_nygard_title(line: &str) -> bool {
    NYGARD_TITLE_REGEX.is_match(line)
}

/// Extract the ADR number from MADR frontmatter
///
/// Returns the value of the `number:` field if present in the YAML frontmatter.
pub fn extract_madr_number(content: &str) -> Option<u32> {
    let trimmed = content.trim_start();
    let after_open = trimmed.strip_prefix("---")?;
    let end = after_open.find("---")?;
    let frontmatter = &after_open[..end];

    for line in frontmatter.lines() {
        let line = line.trim();
        if let Some(rest) = line.strip_prefix("number:")
            && let Ok(n) = rest.trim().parse::<u32>()
        {
            return Some(n);
        }
    }
    None
}

/// Parsed information from an ADR document
#[derive(Debug, Clone)]
pub struct ParsedAdr {
    /// Detected format
    pub format: AdrFormat,
    /// ADR number (if extractable from title or filename)
    pub number: Option<u32>,
    /// Title text (without number prefix for Nygard)
    pub title: Option<String>,
    /// Status value
    pub status: Option<String>,
    /// Date value
    pub date: Option<String>,
    /// Line number where the H1 title is found (1-indexed)
    pub title_line: Option<usize>,
    /// Line number where status section/field is found (1-indexed)
    pub status_line: Option<usize>,
    /// Line number where date is found (1-indexed)
    pub date_line: Option<usize>,
}

impl ParsedAdr {
    /// Create a new empty ParsedAdr
    pub fn new(format: AdrFormat) -> Self {
        Self {
            format,
            number: None,
            title: None,
            status: None,
            date: None,
            title_line: None,
            status_line: None,
            date_line: None,
        }
    }
}

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

    #[test]
    fn test_detect_format_madr() {
        let content = r#"---
status: accepted
date: 2024-01-15
---

# Use PostgreSQL
"#;
        assert_eq!(detect_format(content), AdrFormat::Madr4);
    }

    #[test]
    fn test_detect_format_nygard() {
        let content = r#"# 1. Use Rust for implementation

Date: 2024-01-15

## Status

Accepted
"#;
        assert_eq!(detect_format(content), AdrFormat::Nygard);
    }

    #[test]
    fn test_detect_format_with_leading_whitespace() {
        // Leading whitespace should be ignored
        let content = "   \n\n---\nstatus: accepted\n---\n";
        assert_eq!(detect_format(content), AdrFormat::Madr4);
    }

    #[test]
    fn test_detect_format_ng_nygard() {
        // #408: frontmatter + Nygard sections (adrs "ng" mode) is Nygard, not MADR.
        let content = r#"---
status: accepted
date: 2024-01-15
---

# 1. Use PostgreSQL

## Context

We need a database.

## Decision

Use PostgreSQL.

## Consequences

It works.
"#;
        assert_eq!(detect_format(content), AdrFormat::Nygard);
    }

    #[test]
    fn test_detect_format_madr_sections() {
        // Frontmatter + MADR sections stays MADR.
        let content = r#"---
status: accepted
---

# Use PostgreSQL

## Context and Problem Statement

We need a database.

## Decision Outcome

Chosen option: PostgreSQL.
"#;
        assert_eq!(detect_format(content), AdrFormat::Madr4);
    }

    #[test]
    fn test_detect_format_frontmatter_without_known_sections() {
        // Frontmatter but no recognizable Nygard/MADR sections defaults to MADR.
        let content = "---\nstatus: accepted\n---\n\n# Use PostgreSQL\n";
        assert_eq!(detect_format(content), AdrFormat::Madr4);
    }

    #[test]
    fn test_is_adr_document_decisions_dir() {
        // #409: docs/decisions/ is a recognized ADR directory.
        let path = std::path::PathBuf::from("docs/decisions/0001-use-postgres.md");
        assert!(is_adr_document("# Use PostgreSQL\n", Some(&path)));

        let arch = std::path::PathBuf::from("docs/architecture-decisions/0001.md");
        assert!(is_adr_document("# Anything\n", Some(&arch)));
    }

    #[test]
    fn test_is_adr_document_title_after_comment_header() {
        // #409: a REUSE/SPDX comment header before the title must not hide it.
        let content = r#"<!--
SPDX-FileCopyrightText: 2024 Example
SPDX-License-Identifier: CC0-1.0
-->

# 1. Record architecture decisions

## Status

Accepted
"#;
        assert!(is_adr_document(content, None));
    }

    #[test]
    fn test_is_adr_document_non_adr() {
        // A plain doc with no ADR directory, no status frontmatter, and no
        // numbered title is not treated as an ADR.
        let content = "# Just a Guide\n\nSome prose about a topic.\n";
        let path = std::path::PathBuf::from("docs/guide.md");
        assert!(!is_adr_document(content, Some(&path)));
    }

    #[test]
    fn test_extract_nygard_number() {
        assert_eq!(extract_nygard_number("# 1. Use Rust"), Some(1));
        assert_eq!(extract_nygard_number("# 42. Some Decision"), Some(42));
        assert_eq!(extract_nygard_number("# 1 - Use Rust"), Some(1));
        assert_eq!(extract_nygard_number("# Use Rust"), None);
        assert_eq!(extract_nygard_number("## 1. Section"), None);
    }

    #[test]
    fn test_extract_nygard_title() {
        assert_eq!(extract_nygard_title("# 1. Use Rust"), Some("Use Rust"));
        assert_eq!(
            extract_nygard_title("# 42. Some Decision"),
            Some("Some Decision")
        );
        assert_eq!(extract_nygard_title("# 1 - Use Rust"), Some("Use Rust"));
        assert_eq!(extract_nygard_title("# Use Rust"), None);
    }

    #[test]
    fn test_is_nygard_title() {
        assert!(is_nygard_title("# 1. Use Rust"));
        assert!(is_nygard_title("# 42. Some Decision"));
        assert!(is_nygard_title("# 1 - Use Rust"));
        assert!(!is_nygard_title("# Use Rust"));
        assert!(!is_nygard_title("## 1. Section"));
    }

    #[test]
    fn test_format_from_str() {
        assert_eq!("nygard".parse::<AdrFormat>().unwrap(), AdrFormat::Nygard);
        assert_eq!("madr".parse::<AdrFormat>().unwrap(), AdrFormat::Madr4);
        assert_eq!("madr4".parse::<AdrFormat>().unwrap(), AdrFormat::Madr4);
        assert_eq!("auto".parse::<AdrFormat>().unwrap(), AdrFormat::Auto);
        assert_eq!("NYGARD".parse::<AdrFormat>().unwrap(), AdrFormat::Nygard);
        assert!("unknown".parse::<AdrFormat>().is_err());
    }

    #[test]
    fn test_format_display() {
        assert_eq!(format!("{}", AdrFormat::Nygard), "nygard");
        assert_eq!(format!("{}", AdrFormat::Madr4), "madr");
        assert_eq!(format!("{}", AdrFormat::Auto), "auto");
    }

    #[test]
    fn test_extract_madr_number_with_number() {
        let content =
            "---\nnumber: 1\nstatus: accepted\ndate: 2024-01-15\n---\n\n# Use PostgreSQL\n";
        assert_eq!(extract_madr_number(content), Some(1));
    }

    #[test]
    fn test_extract_madr_number_without_number() {
        let content = "---\nstatus: accepted\ndate: 2024-01-15\n---\n\n# Use PostgreSQL\n";
        assert_eq!(extract_madr_number(content), None);
    }

    #[test]
    fn test_extract_madr_number_large_value() {
        let content = "---\nnumber: 42\nstatus: accepted\n---\n\n# Use Kubernetes\n";
        assert_eq!(extract_madr_number(content), Some(42));
    }

    #[test]
    fn test_extract_madr_number_non_madr_content() {
        let content = "# 1. Use Rust\n\nDate: 2024-01-15\n\n## Status\n\nAccepted\n";
        assert_eq!(extract_madr_number(content), None);
    }
}