mdbook-lint 0.2.0

A fast markdown linter 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
//! MD014: Dollar signs used before commands without showing output
//!
//! This rule checks that shell commands in code blocks don't include dollar signs
//! as part of the command, which makes them harder to copy and paste.

use crate::error::Result;
use crate::rule::{AstRule, RuleCategory, RuleMetadata};
use crate::{
    Document,
    violation::{Severity, Violation},
};
use comrak::nodes::{AstNode, NodeValue};

/// Rule to check that shell commands don't include dollar signs
pub struct MD014;

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

    fn name(&self) -> &'static str {
        "no-dollar-signs"
    }

    fn description(&self) -> &'static str {
        "Dollar signs used before commands without showing output"
    }

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

    fn check_ast<'a>(&self, document: &Document, ast: &'a AstNode<'a>) -> Result<Vec<Violation>> {
        let mut violations = Vec::new();

        // Find all code block nodes
        for node in ast.descendants() {
            if let NodeValue::CodeBlock(code_block) = &node.data.borrow().value {
                let info = code_block.info.trim().to_lowercase();

                // Check if this is a shell-related code block
                if is_shell_language(&info) {
                    let content = &code_block.literal;
                    let lines: Vec<&str> = content.lines().collect();

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

                        // Skip empty lines and comments
                        if trimmed.is_empty() || trimmed.starts_with('#') {
                            continue;
                        }

                        // Check if line starts with $ (potentially with whitespace)
                        if trimmed.starts_with('$') {
                            // Make sure it's not just a variable or other valid use
                            if is_command_prompt_dollar(trimmed) {
                                if let Some((base_line, _)) = document.node_position(node) {
                                    let actual_line = base_line + line_idx + 1; // +1 because code block content starts on next line
                                    violations.push(self.create_violation(
                                        format!("Shell command should not include dollar sign prompt: '{trimmed}'"),
                                        actual_line,
                                        1,
                                        Severity::Warning,
                                    ));
                                }
                            }
                        }
                    }
                }
            }
        }

        Ok(violations)
    }
}

/// Check if the language info indicates a shell-related code block
fn is_shell_language(info: &str) -> bool {
    let shell_languages = [
        "sh",
        "bash",
        "shell",
        "zsh",
        "fish",
        "csh",
        "tcsh",
        "ksh",
        "console",
        "terminal",
        "cmd",
        "powershell",
        "ps1",
    ];

    // Check if the info string starts with any shell language
    // (handles cases like "bash,no_run" or "sh copy")
    for lang in &shell_languages {
        if info == *lang
            || info.starts_with(&format!("{lang},"))
            || info.starts_with(&format!("{lang} "))
        {
            return true;
        }
    }

    false
}

/// Check if a dollar sign is being used as a command prompt
fn is_command_prompt_dollar(line: &str) -> bool {
    let trimmed = line.trim();

    // Must start with $
    if !trimmed.starts_with('$') {
        return false;
    }

    // Get the part after the $
    let after_dollar = &trimmed[1..];

    // If there's a space after $, it's likely a command prompt
    if after_dollar.starts_with(' ') {
        return true;
    }

    // If it's just $ followed by nothing, it's likely a prompt
    if after_dollar.is_empty() {
        return true;
    }

    // Don't flag common shell variable patterns
    // Like $VAR, $(command), ${var}, $((math))
    if after_dollar.starts_with('(')
        || after_dollar.starts_with('{')
        || after_dollar
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_uppercase() || c == '_')
    {
        return false;
    }

    // Don't flag multiple dollar signs ($$, $$$, etc.) - these are less likely to be prompts
    if after_dollar.starts_with('$') {
        return false;
    }

    // For anything else that looks like a command (lowercase letter after $), flag it
    // This catches cases like "$echo" or "$cd"
    if let Some(first_char) = after_dollar.chars().next() {
        first_char.is_ascii_lowercase()
    } else {
        false
    }
}

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

    #[test]
    fn test_md014_no_violations() {
        let content = r#"# Valid Shell Commands

These shell commands should not trigger violations:

```bash
echo "Hello, world!"
ls -la
cd /home/user
```

```sh
grep "pattern" file.txt
find . -name "*.rs"
```

Variables and substitutions are fine:

```bash
echo $HOME
echo $(date)
echo ${USER}
result=$((2 + 3))
```

Non-shell code blocks are ignored:

```rust
let x = "$not_a_shell_command";
```

```python
print("$this is fine")
```
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD014;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md014_dollar_sign_violations() {
        let content = r#"# Shell Commands with Dollar Signs

These should trigger violations:

```bash
$ echo "Hello, world!"
$ ls -la
```

```sh
$ cd /home/user
$ grep "pattern" file.txt
```
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD014;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 4);
        assert!(
            violations[0]
                .message
                .contains("Shell command should not include dollar sign prompt")
        );
        assert!(violations[0].message.contains("$ echo \"Hello, world!\""));
    }

    #[test]
    fn test_md014_mixed_valid_invalid() {
        let content = r#"# Mixed Valid and Invalid

```bash
# This is a comment
echo "This is fine"
$ echo "This is not fine"
ls -la
$ cd /home
export VAR="value"
$ grep "pattern" file.txt
```
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD014;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 3);
    }

    #[test]
    fn test_md014_different_shell_languages() {
        let content = r#"# Different Shell Languages

```console
$ echo "console command"
```

```terminal
$ ls -la
```

```zsh
$ cd /home
```

```fish
$ grep "pattern" file.txt
```

```powershell
$ Get-Process
```
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD014;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 5);
    }

    #[test]
    fn test_md014_variables_not_flagged() {
        let content = r#"# Variable Usage

```bash
echo $HOME
echo $USER
echo ${HOME}/bin
echo $(date)
result=$((2 + 3))
$VAR="something"
$_PRIVATE_VAR="value"
```

These should not be flagged as they are valid shell syntax.
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD014;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md014_empty_lines_and_comments() {
        let content = r#"# Empty Lines and Comments

```bash
# This is a comment
$ echo "This should be flagged"

# Another comment

$ ls -la
echo "This is fine"
# Final comment
```
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD014;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 2);
    }

    #[test]
    fn test_md014_non_shell_languages_ignored() {
        let content = r#"# Non-Shell Languages

```javascript
console.log("$ this is fine");
```

```python
print("$ also fine")
```

```rust
println!("$ still fine");
```

```markdown
$ This is in markdown, should be ignored
```

```
$ This has no language specified, should be ignored
```
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD014;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md014_indented_dollar_signs() {
        let content = r#"# Indented Dollar Signs

```bash
    $ echo "indented command"
  $ echo "also indented"
$ echo "not indented"
```
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD014;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 3);
    }

    #[test]
    fn test_md014_edge_cases() {
        let content = r#"# Edge Cases

```bash
$
$
$echo_no_space
$ echo "with space"
$$
$$$multiple
```
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD014;
        let violations = rule.check(&document).unwrap();

        // Should flag: $, $ , $echo_no_space, $ echo "with space"
        // Should not flag: $$, $$$multiple (these are less likely to be prompts)
        assert_eq!(violations.len(), 4);
    }

    #[test]
    fn test_shell_language_detection() {
        assert!(is_shell_language("bash"));
        assert!(is_shell_language("sh"));
        assert!(is_shell_language("shell"));
        assert!(is_shell_language("console"));
        assert!(is_shell_language("bash,no_run"));
        assert!(is_shell_language("sh copy"));

        assert!(!is_shell_language("rust"));
        assert!(!is_shell_language("python"));
        assert!(!is_shell_language("javascript"));
        assert!(!is_shell_language(""));
    }

    #[test]
    fn test_command_prompt_dollar_detection() {
        assert!(is_command_prompt_dollar("$ echo hello"));
        assert!(is_command_prompt_dollar("$"));
        assert!(is_command_prompt_dollar("$ "));
        assert!(is_command_prompt_dollar("$command"));

        assert!(!is_command_prompt_dollar("$VAR"));
        assert!(!is_command_prompt_dollar("$HOME"));
        assert!(!is_command_prompt_dollar("$(command)"));
        assert!(!is_command_prompt_dollar("${var}"));
        assert!(!is_command_prompt_dollar("$((math))"));
        assert!(!is_command_prompt_dollar("$_PRIVATE"));
    }
}