mdbook-lint-rulesets 0.16.1

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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! CONTENT001: TODO/FIXME/XXX comment detection
//!
//! Detects TODO, FIXME, XXX, and other common work-in-progress markers
//! that shouldn't appear in production documentation.

use mdbook_lint_core::Document;
use mdbook_lint_core::rule::{Rule, RuleCategory, RuleMetadata};
use mdbook_lint_core::violation::{Severity, Violation};
use regex::Regex;
use std::sync::LazyLock;

/// Default markers to detect (these are matched as whole words)
const DEFAULT_MARKERS: &[&str] = &["TODO", "FIXME", "XXX", "HACK", "WIP"];

/// Markers that require comment-style context to avoid false positives in prose
/// e.g., "BUG:" or "BUG(" but not "this bug" or "bug fix"
/// Note: These are handled separately via CONTEXTUAL_MARKER_REGEX
#[allow(dead_code)]
const CONTEXTUAL_MARKERS: &[&str] = &["BUG"];

/// Regex pattern for matching standard markers (case-insensitive, word boundary)
static MARKER_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    // Match markers as whole words
    Regex::new(r"(?i)\b(TODO|FIXME|XXX|HACK|WIP)\b").unwrap()
});

/// Regex pattern for markers that need comment-style context
/// Matches BUG only when followed by :, (, or at start of line/after comment markers
static CONTEXTUAL_MARKER_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    // Match BUG only in comment-like contexts:
    // - BUG: or BUG( (followed by colon or paren)
    // - // BUG or /* BUG (after code comment markers)
    // - Start of line with optional whitespace
    Regex::new(r"(?i)(?:^|\s|//|/\*|#)\s*(BUG)\s*[:(\[]|(?i)\bBUG\s*[:(\[]").unwrap()
});

/// CONTENT001: Detects TODO/FIXME/XXX comments
///
/// This rule flags common work-in-progress markers that indicate
/// incomplete documentation. These should be resolved before publishing.
pub struct CONTENT001 {
    /// Custom markers to detect (in addition to or instead of defaults)
    markers: Vec<String>,
    /// Whether to include default markers
    include_defaults: bool,
    /// Whether to check inside code blocks
    check_code_blocks: bool,
}

impl Default for CONTENT001 {
    fn default() -> Self {
        Self {
            markers: Vec::new(),
            include_defaults: true,
            check_code_blocks: false,
        }
    }
}

impl CONTENT001 {
    /// Create with custom markers
    #[allow(dead_code)]
    pub fn with_markers(markers: Vec<String>) -> Self {
        Self {
            markers,
            include_defaults: false,
            check_code_blocks: false,
        }
    }

    /// Set whether to check inside code blocks
    #[allow(dead_code)]
    pub fn check_code_blocks(mut self, check: bool) -> Self {
        self.check_code_blocks = check;
        self
    }

    /// Create an instance from rule configuration.
    ///
    /// Recognized keys (both `snake_case` and `kebab-case` accepted):
    /// - `markers`: array of custom marker strings to detect.
    /// - `include_defaults`: also check the built-in markers (default true).
    /// - `check_code_blocks`: scan inside code blocks (default false).
    pub fn from_config(config: &toml::Value) -> Self {
        let mut rule = Self::default();

        if let Some(markers) = config.get("markers").and_then(|v| v.as_array()) {
            rule.markers = markers
                .iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect();
        }
        if let Some(b) = config
            .get("include_defaults")
            .or_else(|| config.get("include-defaults"))
            .and_then(|v| v.as_bool())
        {
            rule.include_defaults = b;
        }
        if let Some(b) = config
            .get("check_code_blocks")
            .or_else(|| config.get("check-code-blocks"))
            .and_then(|v| v.as_bool())
        {
            rule.check_code_blocks = b;
        }
        rule
    }

    /// Get all markers to check
    fn get_markers(&self) -> Vec<&str> {
        let mut markers: Vec<&str> = Vec::new();

        if self.include_defaults {
            markers.extend(DEFAULT_MARKERS.iter().copied());
        }

        for marker in &self.markers {
            markers.push(marker.as_str());
        }

        markers
    }

    /// Build regex pattern for current markers
    fn build_pattern(&self) -> Regex {
        let markers = self.get_markers();
        if markers.is_empty() {
            return MARKER_REGEX.clone();
        }

        let pattern = format!(r"(?i)\b({})\b", markers.join("|"));
        Regex::new(&pattern).unwrap_or_else(|_| MARKER_REGEX.clone())
    }

    /// Check if a position is inside a code block
    fn is_in_code_block(&self, lines: &[String], line_idx: usize) -> bool {
        let mut in_fenced_block = false;

        for (idx, line) in lines.iter().enumerate() {
            let trimmed = line.trim();

            // Check for fenced code block markers
            if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
                in_fenced_block = !in_fenced_block;
            }

            if idx == line_idx {
                return in_fenced_block;
            }
        }

        false
    }

    /// Check if a position is inside inline code
    fn is_in_inline_code(&self, line: &str, col: usize) -> bool {
        let before = &line[..col.min(line.len())];

        // Count backticks before the position
        let backtick_count = before.chars().filter(|&c| c == '`').count();

        // Odd number of backticks means we're inside inline code
        backtick_count % 2 == 1
    }

    /// Check if a match is inside an HTML comment
    fn is_in_html_comment(&self, line: &str, col: usize) -> bool {
        // Simple check: look for <!-- before and --> after
        let before = &line[..col.min(line.len())];
        let after = &line[col.min(line.len())..];

        before.contains("<!--") && !before.contains("-->") && after.contains("-->")
    }
}

impl Rule for CONTENT001 {
    fn id(&self) -> &'static str {
        "CONTENT001"
    }

    fn name(&self) -> &'static str {
        "no-todo-comments"
    }

    fn description(&self) -> &'static str {
        "TODO/FIXME/XXX comments should be resolved before publishing"
    }

    fn metadata(&self) -> RuleMetadata {
        RuleMetadata::stable(RuleCategory::Content).introduced_in("mdbook-lint v0.11.0")
    }

    fn check_with_ast<'a>(
        &self,
        document: &Document,
        _ast: Option<&'a comrak::nodes::AstNode<'a>>,
    ) -> mdbook_lint_core::error::Result<Vec<Violation>> {
        let mut violations = Vec::new();
        let pattern = self.build_pattern();

        for (line_idx, line) in document.lines.iter().enumerate() {
            let line_num = line_idx + 1; // 1-based

            // Skip code blocks unless configured to check them
            if !self.check_code_blocks && self.is_in_code_block(&document.lines, line_idx) {
                continue;
            }

            // Find all matches for standard markers in this line
            for mat in pattern.find_iter(line) {
                let col = mat.start() + 1; // 1-based

                // Skip if inside inline code (unless checking code blocks)
                if !self.check_code_blocks && self.is_in_inline_code(line, mat.start()) {
                    continue;
                }

                // Always report HTML comments - they're often used for TODOs
                let in_comment = self.is_in_html_comment(line, mat.start());

                let marker = mat.as_str().to_uppercase();
                let context = if in_comment {
                    format!("{} comment found in HTML comment", marker)
                } else {
                    format!("{} comment found - resolve before publishing", marker)
                };

                violations.push(self.create_violation(context, line_num, col, Severity::Warning));
            }

            // Check for contextual markers (BUG) that need comment-style context
            for cap in CONTEXTUAL_MARKER_REGEX.captures_iter(line) {
                // Get the position of the BUG marker itself
                if let Some(mat) = cap.get(1) {
                    let col = mat.start() + 1; // 1-based

                    // Skip if inside inline code (unless checking code blocks)
                    if !self.check_code_blocks && self.is_in_inline_code(line, mat.start()) {
                        continue;
                    }

                    let in_comment = self.is_in_html_comment(line, mat.start());

                    let marker = mat.as_str().to_uppercase();
                    let context = if in_comment {
                        format!("{} comment found in HTML comment", marker)
                    } else {
                        format!("{} comment found - resolve before publishing", marker)
                    };

                    violations.push(self.create_violation(
                        context,
                        line_num,
                        col,
                        Severity::Warning,
                    ));
                }
            }
        }

        Ok(violations)
    }
}

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

    fn create_test_document(content: &str) -> Document {
        Document::new(content.to_string(), PathBuf::from("test.md")).unwrap()
    }

    #[test]
    fn test_from_config() {
        let cfg: toml::Value = toml::from_str(
            "markers = [\"REVIEW\"]\ninclude_defaults = false\ncheck_code_blocks = true",
        )
        .unwrap();
        let rule = CONTENT001::from_config(&cfg);
        assert_eq!(rule.markers, vec!["REVIEW".to_string()]);
        assert!(!rule.include_defaults);
        assert!(rule.check_code_blocks);

        // Empty config matches default().
        let empty: toml::Value = toml::from_str("").unwrap();
        let d = CONTENT001::from_config(&empty);
        assert!(d.markers.is_empty());
        assert!(d.include_defaults);
        assert!(!d.check_code_blocks);
    }

    #[test]
    fn test_no_markers() {
        let content = "# Title\n\nThis is clean documentation.";
        let doc = create_test_document(content);
        let rule = CONTENT001::default();
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_todo_detected() {
        let content = "# Title\n\nTODO: Add more content here.";
        let doc = create_test_document(content);
        let rule = CONTENT001::default();
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("TODO"));
    }

    #[test]
    fn test_fixme_detected() {
        let content = "# Title\n\nFIXME: This section needs work.";
        let doc = create_test_document(content);
        let rule = CONTENT001::default();
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("FIXME"));
    }

    #[test]
    fn test_xxx_detected() {
        let content = "# Title\n\nXXX: Review this section.";
        let doc = create_test_document(content);
        let rule = CONTENT001::default();
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("XXX"));
    }

    #[test]
    fn test_case_insensitive() {
        let content = "# Title\n\ntodo: lowercase\nFixMe: mixed case";
        let doc = create_test_document(content);
        let rule = CONTENT001::default();
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 2);
    }

    #[test]
    fn test_multiple_markers() {
        let content = "# Title\n\nTODO: First thing\nFIXME: Second thing\nHACK: Third thing";
        let doc = create_test_document(content);
        let rule = CONTENT001::default();
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 3);
    }

    #[test]
    fn test_skip_code_blocks_by_default() {
        let content = "# Title\n\n```rust\n// TODO: This is in code\n```\n\nTODO: This is not";
        let doc = create_test_document(content);
        let rule = CONTENT001::default();
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].line, 7);
    }

    #[test]
    fn test_check_code_blocks_when_enabled() {
        let content = "# Title\n\n```rust\n// TODO: This is in code\n```";
        let doc = create_test_document(content);
        let rule = CONTENT001::default().check_code_blocks(true);
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 1);
    }

    #[test]
    fn test_skip_inline_code() {
        let content = "# Title\n\nUse `TODO` as a marker.\n\nTODO: Real marker";
        let doc = create_test_document(content);
        let rule = CONTENT001::default();
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].line, 5);
    }

    #[test]
    fn test_html_comment() {
        let content = "# Title\n\n<!-- TODO: Add content -->\n\nParagraph.";
        let doc = create_test_document(content);
        let rule = CONTENT001::default();
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("HTML comment"));
    }

    #[test]
    fn test_word_boundary() {
        let content = "# Title\n\nTODONOT a marker\nMYTODO not a marker";
        let doc = create_test_document(content);
        let rule = CONTENT001::default();
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 0, "Should not match partial words");
    }

    #[test]
    fn test_wip_detected() {
        let content = "# Title\n\nWIP: Work in progress section.";
        let doc = create_test_document(content);
        let rule = CONTENT001::default();
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("WIP"));
    }

    #[test]
    fn test_custom_markers() {
        let content = "# Title\n\nNEEDSREVIEW: Check this.";
        let doc = create_test_document(content);
        let rule = CONTENT001::with_markers(vec!["NEEDSREVIEW".to_string()]);
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 1);
    }

    #[test]
    fn test_marker_with_colon() {
        let content = "# Title\n\nTODO: With colon\nFIXME - With dash";
        let doc = create_test_document(content);
        let rule = CONTENT001::default();
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 2);
    }

    #[test]
    fn test_marker_in_parentheses() {
        let content = "# Title\n\n(TODO) In parens\n(FIXME) Also in parens";
        let doc = create_test_document(content);
        let rule = CONTENT001::default();
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 2);
    }

    #[test]
    fn test_bug_in_prose_not_detected() {
        // "bug" in normal prose should NOT be flagged
        let content = r#"# Title

This kind of bug can be difficult to track down.
The bug fix was released yesterday.
We found a bug in the code.
"#;
        let doc = create_test_document(content);
        let rule = CONTENT001::default();
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 0, "BUG in prose should not be flagged");
    }

    #[test]
    fn test_bug_comment_style_detected() {
        // BUG with comment-style context SHOULD be flagged
        let content = r#"# Title

BUG: This needs to be fixed.
BUG(123): Tracked issue.
// BUG: In a code comment style
"#;
        let doc = create_test_document(content);
        let rule = CONTENT001::default();
        let violations = rule.check(&doc).unwrap();
        assert!(
            violations.len() >= 2,
            "BUG: style comments should be flagged, got {}",
            violations.len()
        );
    }

    #[test]
    fn test_bug_in_html_comment() {
        let content = "# Title\n\n<!-- BUG: Fix this -->\n\nParagraph.";
        let doc = create_test_document(content);
        let rule = CONTENT001::default();
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("BUG"));
    }
}