1use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
7use crate::utils::range_utils::calculate_match_range;
8use crate::utils::regex_cache::get_cached_regex;
9use toml;
10
11mod md014_config;
12use md014_config::MD014Config;
13
14const COMMAND_PATTERN: &str = r"^\s*[$>]\s+\S+";
16const SHELL_LANG_PATTERN: &str = r"^(?i)(bash|sh|shell|console|terminal)";
17const DOLLAR_PROMPT_PATTERN: &str = r"^\s*([$>])";
18
19#[derive(Clone, Default)]
20pub struct MD014CommandsShowOutput {
21 config: MD014Config,
22}
23
24impl MD014CommandsShowOutput {
25 pub fn new() -> Self {
26 Self::default()
27 }
28
29 pub fn with_show_output(show_output: bool) -> Self {
30 Self {
31 config: MD014Config { show_output },
32 }
33 }
34
35 pub fn from_config_struct(config: MD014Config) -> Self {
36 Self { config }
37 }
38
39 fn is_command_line(&self, line: &str) -> bool {
40 get_cached_regex(COMMAND_PATTERN).is_ok_and(|re| re.is_match(line))
41 }
42
43 fn is_shell_language(&self, lang: &str) -> bool {
44 get_cached_regex(SHELL_LANG_PATTERN).is_ok_and(|re| re.is_match(lang))
45 }
46
47 fn is_output_line(&self, line: &str) -> bool {
48 let trimmed = line.trim();
49 !trimmed.is_empty() && !trimmed.starts_with('$') && !trimmed.starts_with('>') && !trimmed.starts_with('#')
50 }
51
52 fn is_no_output_command(&self, cmd: &str) -> bool {
53 let cmd = cmd.trim().to_lowercase();
54
55 cmd.starts_with("cd ")
61 || cmd == "cd"
62 || cmd.starts_with("mkdir ")
63 || cmd.starts_with("touch ")
64 || cmd.starts_with("rm ")
65 || cmd.starts_with("mv ")
66 || cmd.starts_with("cp ")
67 || cmd.starts_with("export ")
68 || cmd.starts_with("set ")
69 || cmd.starts_with("alias ")
70 || cmd.starts_with("unset ")
71 || cmd.starts_with("source ")
72 || cmd.starts_with(". ")
73 || cmd == "true"
74 || cmd == "false"
75 || cmd.starts_with("sleep ")
76 || cmd.starts_with("wait ")
77 || cmd.starts_with("pushd ")
78 || cmd.starts_with("popd")
79
80 || cmd.contains(" > ")
82 || cmd.contains(" >> ")
83
84 || cmd.starts_with("git add ")
86 || cmd.starts_with("git checkout ")
87 || cmd.starts_with("git stash")
88 || cmd.starts_with("git reset ")
89 }
90
91 fn is_command_without_output(&self, block: &[&str], lang: &str) -> bool {
92 if !self.config.show_output || !self.is_shell_language(lang) {
93 return false;
94 }
95
96 let has_output = block.iter().any(|line| self.is_output_line(line));
98 if has_output {
99 return false; }
101
102 self.get_first_output_command(block).is_some()
104 }
105
106 fn get_first_output_command(&self, block: &[&str]) -> Option<(usize, String)> {
109 for (i, line) in block.iter().enumerate() {
110 if self.is_command_line(line) {
111 let cmd = line.trim()[1..].trim().to_string();
112 if !self.is_no_output_command(&cmd) {
113 return Some((i, cmd));
114 }
115 }
116 }
117 None }
119
120 fn fix_command_block(&self, block: &[&str]) -> String {
121 block
122 .iter()
123 .map(|line| {
124 let trimmed = line.trim_start();
125 if self.is_command_line(line) {
126 let spaces = line.len() - line.trim_start().len();
127 let cmd = trimmed.chars().skip(1).collect::<String>().trim_start().to_string();
128 format!("{}{}", " ".repeat(spaces), cmd)
129 } else {
130 line.to_string()
131 }
132 })
133 .collect::<Vec<_>>()
134 .join("\n")
135 }
136
137 fn get_code_block_language(block_start: &str) -> String {
138 block_start
139 .trim_start()
140 .trim_start_matches("```")
141 .split_whitespace()
142 .next()
143 .unwrap_or("")
144 .to_string()
145 }
146
147 fn find_all_command_lines<'a>(&self, block: &[&'a str]) -> Vec<(usize, &'a str)> {
150 let mut results = Vec::new();
151 for (i, line) in block.iter().enumerate() {
152 if self.is_command_line(line) {
153 let cmd = line.trim()[1..].trim();
154 if !self.is_no_output_command(cmd) {
155 results.push((i, *line));
156 }
157 }
158 }
159 results
160 }
161}
162
163impl Rule for MD014CommandsShowOutput {
164 fn name(&self) -> &'static str {
165 "MD014"
166 }
167
168 fn description(&self) -> &'static str {
169 "Commands in code blocks should show output"
170 }
171
172 fn category(&self) -> RuleCategory {
173 RuleCategory::CodeBlock
174 }
175
176 fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
177 let content = ctx.content;
178
179 let mut warnings = Vec::new();
180
181 let mut current_block = Vec::new();
182
183 let mut in_code_block = false;
184
185 let mut block_start_line = 0;
186
187 let mut current_lang = String::new();
188
189 for (line_num, line) in content.lines().enumerate() {
190 if line.trim_start().starts_with("```") {
191 if in_code_block {
192 if self.is_command_without_output(¤t_block, ¤t_lang) {
194 let command_lines = self.find_all_command_lines(¤t_block);
196 let fix = Fix::new(
197 {
198 let content_start_line = block_start_line + 1; let content_end_line = line_num - 1; let start_byte = ctx.line_start_byte(content_start_line + 1).unwrap_or(0); let end_byte = ctx.line_start_byte(content_end_line + 2).unwrap_or(start_byte); start_byte..end_byte
206 },
207 format!("{}\n", self.fix_command_block(¤t_block)),
208 );
209
210 for (cmd_line_idx, cmd_line) in &command_lines {
211 let cmd_line_num = block_start_line + 1 + cmd_line_idx + 1; if let Ok(re) = get_cached_regex(DOLLAR_PROMPT_PATTERN)
215 && let Some(cap) = re.captures(cmd_line)
216 {
217 let match_obj = cap.get(1).unwrap(); let (start_line, start_col, end_line, end_col) =
219 calculate_match_range(cmd_line_num, cmd_line, match_obj.start(), match_obj.len());
220
221 let cmd_text = cmd_line.trim()[1..].trim().to_string();
223 let message = if cmd_text.is_empty() {
224 "Command should show output (add example output or remove $ prompt)".to_string()
225 } else {
226 format!(
227 "Command '{cmd_text}' should show output (add example output or remove $ prompt)"
228 )
229 };
230
231 warnings.push(LintWarning {
232 rule_name: Some(self.name().to_string()),
233 line: start_line,
234 column: start_col,
235 end_line,
236 end_column: end_col,
237 message,
238 severity: Severity::Warning,
239 fix: Some(fix.clone()),
240 });
241 }
242 }
243 }
244 current_block.clear();
245 } else {
246 block_start_line = line_num;
248 current_lang = Self::get_code_block_language(line);
249 }
250 in_code_block = !in_code_block;
251 } else if in_code_block {
252 current_block.push(line);
253 }
254 }
255
256 Ok(warnings)
257 }
258
259 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
260 if self.should_skip(ctx) {
261 return Ok(ctx.content.to_string());
262 }
263 let warnings = self.check(ctx)?;
264 if warnings.is_empty() {
265 return Ok(ctx.content.to_string());
266 }
267 let warnings =
268 crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
269 crate::utils::fix_utils::apply_warning_fixes(ctx.content, &warnings)
270 .map_err(crate::rule::LintError::InvalidInput)
271 }
272
273 fn as_any(&self) -> &dyn std::any::Any {
274 self
275 }
276
277 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
278 ctx.content.is_empty() || !ctx.likely_has_code()
280 }
281
282 crate::impl_rule_config_methods!(MD014Config);
283}
284
285#[cfg(test)]
286mod tests {
287 use super::*;
288 use crate::lint_context::LintContext;
289
290 #[test]
291 fn test_is_command_line() {
292 let rule = MD014CommandsShowOutput::new();
293 assert!(rule.is_command_line("$ echo test"));
294 assert!(rule.is_command_line(" $ ls -la"));
295 assert!(rule.is_command_line("> pwd"));
296 assert!(rule.is_command_line(" > cd /home"));
297 assert!(!rule.is_command_line("echo test"));
298 assert!(!rule.is_command_line("# comment"));
299 assert!(!rule.is_command_line("output line"));
300 }
301
302 #[test]
303 fn test_is_shell_language() {
304 let rule = MD014CommandsShowOutput::new();
305 assert!(rule.is_shell_language("bash"));
306 assert!(rule.is_shell_language("BASH"));
307 assert!(rule.is_shell_language("sh"));
308 assert!(rule.is_shell_language("shell"));
309 assert!(rule.is_shell_language("Shell"));
310 assert!(rule.is_shell_language("console"));
311 assert!(rule.is_shell_language("CONSOLE"));
312 assert!(rule.is_shell_language("terminal"));
313 assert!(rule.is_shell_language("Terminal"));
314 assert!(!rule.is_shell_language("python"));
315 assert!(!rule.is_shell_language("javascript"));
316 assert!(!rule.is_shell_language(""));
317 }
318
319 #[test]
320 fn test_is_output_line() {
321 let rule = MD014CommandsShowOutput::new();
322 assert!(rule.is_output_line("output text"));
323 assert!(rule.is_output_line(" some output"));
324 assert!(rule.is_output_line("file1 file2"));
325 assert!(!rule.is_output_line(""));
326 assert!(!rule.is_output_line(" "));
327 assert!(!rule.is_output_line("$ command"));
328 assert!(!rule.is_output_line("> prompt"));
329 assert!(!rule.is_output_line("# comment"));
330 }
331
332 #[test]
333 fn test_is_no_output_command() {
334 let rule = MD014CommandsShowOutput::new();
335
336 assert!(rule.is_no_output_command("cd /home"));
338 assert!(rule.is_no_output_command("cd"));
339 assert!(rule.is_no_output_command("mkdir test"));
340 assert!(rule.is_no_output_command("touch file.txt"));
341 assert!(rule.is_no_output_command("rm -rf dir"));
342 assert!(rule.is_no_output_command("mv old new"));
343 assert!(rule.is_no_output_command("cp src dst"));
344 assert!(rule.is_no_output_command("export VAR=value"));
345 assert!(rule.is_no_output_command("set -e"));
346 assert!(rule.is_no_output_command("source ~/.bashrc"));
347 assert!(rule.is_no_output_command(". ~/.profile"));
348 assert!(rule.is_no_output_command("alias ll='ls -la'"));
349 assert!(rule.is_no_output_command("unset VAR"));
350 assert!(rule.is_no_output_command("true"));
351 assert!(rule.is_no_output_command("false"));
352 assert!(rule.is_no_output_command("sleep 5"));
353 assert!(rule.is_no_output_command("pushd /tmp"));
354 assert!(rule.is_no_output_command("popd"));
355
356 assert!(rule.is_no_output_command("CD /HOME"));
358 assert!(rule.is_no_output_command("MKDIR TEST"));
359
360 assert!(rule.is_no_output_command("echo 'test' > file.txt"));
362 assert!(rule.is_no_output_command("cat input.txt > output.txt"));
363 assert!(rule.is_no_output_command("echo 'append' >> log.txt"));
364
365 assert!(rule.is_no_output_command("git add ."));
367 assert!(rule.is_no_output_command("git checkout main"));
368 assert!(rule.is_no_output_command("git stash"));
369 assert!(rule.is_no_output_command("git reset HEAD~1"));
370
371 assert!(!rule.is_no_output_command("ls -la"));
373 assert!(!rule.is_no_output_command("echo test")); assert!(!rule.is_no_output_command("pwd"));
375 assert!(!rule.is_no_output_command("cat file.txt")); assert!(!rule.is_no_output_command("grep pattern file"));
377
378 assert!(!rule.is_no_output_command("pip install requests"));
380 assert!(!rule.is_no_output_command("npm install express"));
381 assert!(!rule.is_no_output_command("cargo install ripgrep"));
382 assert!(!rule.is_no_output_command("brew install git"));
383
384 assert!(!rule.is_no_output_command("cargo build"));
386 assert!(!rule.is_no_output_command("npm run build"));
387 assert!(!rule.is_no_output_command("make"));
388
389 assert!(!rule.is_no_output_command("docker ps"));
391 assert!(!rule.is_no_output_command("docker compose up"));
392 assert!(!rule.is_no_output_command("docker run myimage"));
393
394 assert!(!rule.is_no_output_command("git status"));
396 assert!(!rule.is_no_output_command("git log"));
397 assert!(!rule.is_no_output_command("git diff"));
398 }
399
400 #[test]
401 fn test_fix_command_block() {
402 let rule = MD014CommandsShowOutput::new();
403 let block = vec!["$ echo test", "$ ls -la"];
404 assert_eq!(rule.fix_command_block(&block), "echo test\nls -la");
405
406 let indented = vec![" $ echo test", " $ pwd"];
407 assert_eq!(rule.fix_command_block(&indented), " echo test\n pwd");
408
409 let mixed = vec!["> cd /home", "$ mkdir test"];
410 assert_eq!(rule.fix_command_block(&mixed), "cd /home\nmkdir test");
411 }
412
413 #[test]
414 fn test_get_code_block_language() {
415 assert_eq!(MD014CommandsShowOutput::get_code_block_language("```bash"), "bash");
416 assert_eq!(MD014CommandsShowOutput::get_code_block_language("```shell"), "shell");
417 assert_eq!(
418 MD014CommandsShowOutput::get_code_block_language(" ```console"),
419 "console"
420 );
421 assert_eq!(
422 MD014CommandsShowOutput::get_code_block_language("```bash {.line-numbers}"),
423 "bash"
424 );
425 assert_eq!(MD014CommandsShowOutput::get_code_block_language("```"), "");
426 }
427
428 #[test]
429 fn test_find_all_command_lines() {
430 let rule = MD014CommandsShowOutput::new();
431 let block = vec!["# comment", "$ echo test", "output"];
432 let result = rule.find_all_command_lines(&block);
433 assert_eq!(result, vec![(1, "$ echo test")]);
434
435 let no_commands = vec!["output1", "output2"];
436 assert!(rule.find_all_command_lines(&no_commands).is_empty());
437
438 let multiple = vec!["$ echo one", "$ echo two", "$ cd /tmp"];
439 let result = rule.find_all_command_lines(&multiple);
440 assert_eq!(result, vec![(0, "$ echo one"), (1, "$ echo two")]);
442 }
443
444 #[test]
445 fn test_is_command_without_output() {
446 let rule = MD014CommandsShowOutput::with_show_output(true);
447
448 let block1 = vec!["$ echo test"];
450 assert!(rule.is_command_without_output(&block1, "bash"));
451
452 let block2 = vec!["$ echo test", "test"];
454 assert!(!rule.is_command_without_output(&block2, "bash"));
455
456 let block3 = vec!["$ cd /home"];
458 assert!(!rule.is_command_without_output(&block3, "bash"));
459
460 let rule_disabled = MD014CommandsShowOutput::with_show_output(false);
462 assert!(!rule_disabled.is_command_without_output(&block1, "bash"));
463
464 assert!(!rule.is_command_without_output(&block1, "python"));
466 }
467
468 #[test]
469 fn test_edge_cases() {
470 let rule = MD014CommandsShowOutput::new();
471 let content = "```bash\n$ \n```";
473 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
474 let result = rule.check(&ctx).unwrap();
475 assert!(
476 result.is_empty(),
477 "Bare $ with only space doesn't match command pattern"
478 );
479
480 let empty_content = "```bash\n```";
482 let ctx2 = LintContext::new(empty_content, crate::config::MarkdownFlavor::Standard, None);
483 let result2 = rule.check(&ctx2).unwrap();
484 assert!(result2.is_empty(), "Empty code block should not be flagged");
485
486 let minimal = "```bash\n$ a\n```";
488 let ctx3 = LintContext::new(minimal, crate::config::MarkdownFlavor::Standard, None);
489 let result3 = rule.check(&ctx3).unwrap();
490 assert_eq!(result3.len(), 1, "Minimal command should be flagged");
491 }
492
493 #[test]
494 fn test_mixed_silent_and_output_commands() {
495 let rule = MD014CommandsShowOutput::new();
496
497 let silent_only = "```bash\n$ cd /home\n$ mkdir test\n```";
499 let ctx1 = LintContext::new(silent_only, crate::config::MarkdownFlavor::Standard, None);
500 let result1 = rule.check(&ctx1).unwrap();
501 assert!(
502 result1.is_empty(),
503 "Block with only silent commands should not be flagged"
504 );
505
506 let mixed_silent_first = "```bash\n$ cd /home\n$ ls -la\n```";
509 let ctx2 = LintContext::new(mixed_silent_first, crate::config::MarkdownFlavor::Standard, None);
510 let result2 = rule.check(&ctx2).unwrap();
511 assert_eq!(result2.len(), 1, "Only output-producing commands should be flagged");
512 assert!(
513 result2[0].message.contains("ls -la"),
514 "Message should mention 'ls -la', not 'cd /home'. Got: {}",
515 result2[0].message
516 );
517
518 let mixed_mkdir_cat = "```bash\n$ mkdir test\n$ cat file.txt\n```";
520 let ctx3 = LintContext::new(mixed_mkdir_cat, crate::config::MarkdownFlavor::Standard, None);
521 let result3 = rule.check(&ctx3).unwrap();
522 assert_eq!(result3.len(), 1, "Only output-producing commands should be flagged");
523 assert!(
524 result3[0].message.contains("cat file.txt"),
525 "Message should mention 'cat file.txt', not 'mkdir'. Got: {}",
526 result3[0].message
527 );
528
529 let mkdir_pip = "```bash\n$ mkdir test\n$ pip install something\n```";
531 let ctx3b = LintContext::new(mkdir_pip, crate::config::MarkdownFlavor::Standard, None);
532 let result3b = rule.check(&ctx3b).unwrap();
533 assert_eq!(result3b.len(), 1, "Block with pip install should be flagged");
534 assert!(
535 result3b[0].message.contains("pip install"),
536 "Message should mention 'pip install'. Got: {}",
537 result3b[0].message
538 );
539
540 let mixed_output_first = "```bash\n$ echo hello\n$ cd /home\n```";
542 let ctx4 = LintContext::new(mixed_output_first, crate::config::MarkdownFlavor::Standard, None);
543 let result4 = rule.check(&ctx4).unwrap();
544 assert_eq!(result4.len(), 1, "Only output-producing commands should be flagged");
545 assert!(
546 result4[0].message.contains("echo hello"),
547 "Message should mention 'echo hello'. Got: {}",
548 result4[0].message
549 );
550 }
551
552 #[test]
553 fn test_multiple_commands_without_output_all_flagged() {
554 let rule = MD014CommandsShowOutput::new();
555
556 let content = "```shell\n# First invocation\n$ my_command\n\n# Second invocation\n$ my_command\n```";
558 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
559 let result = rule.check(&ctx).unwrap();
560 assert_eq!(result.len(), 2, "Both commands should be flagged. Got: {result:?}");
561 assert!(result[0].message.contains("my_command"));
562 assert!(result[1].message.contains("my_command"));
563 assert_ne!(result[0].line, result[1].line, "Warnings should be on different lines");
565
566 let content2 = "```bash\n$ echo hello\n$ ls -la\n$ pwd\n```";
568 let ctx2 = LintContext::new(content2, crate::config::MarkdownFlavor::Standard, None);
569 let result2 = rule.check(&ctx2).unwrap();
570 assert_eq!(
571 result2.len(),
572 3,
573 "All three commands should be flagged. Got: {result2:?}"
574 );
575 assert!(result2[0].message.contains("echo hello"));
576 assert!(result2[1].message.contains("ls -la"));
577 assert!(result2[2].message.contains("pwd"));
578
579 let content3 = "```bash\n$ echo hello\n$ cd /tmp\n$ ls -la\n```";
581 let ctx3 = LintContext::new(content3, crate::config::MarkdownFlavor::Standard, None);
582 let result3 = rule.check(&ctx3).unwrap();
583 assert_eq!(
584 result3.len(),
585 2,
586 "Only output-producing commands should be flagged. Got: {result3:?}"
587 );
588 assert!(result3[0].message.contains("echo hello"));
589 assert!(result3[1].message.contains("ls -la"));
590 }
591
592 #[test]
593 fn test_issue_516_exact_case() {
594 let rule = MD014CommandsShowOutput::new();
595
596 let content = "---\ntitle: Heading\n---\n\nHere is a fenced code block:\n\n```shell\n# First invocation of my_command\n$ my_command\n\n# Second invocation of my_command\n$ my_command\n```\n";
598 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
599 let result = rule.check(&ctx).unwrap();
600 assert_eq!(
601 result.len(),
602 2,
603 "Both $ my_command lines should be flagged. Got: {result:?}"
604 );
605 assert_eq!(result[0].line, 9, "First warning should be on line 9");
606 assert_eq!(result[1].line, 12, "Second warning should be on line 12");
607 }
608
609 #[test]
610 fn test_default_config_section() {
611 let rule = MD014CommandsShowOutput::new();
612 let config_section = rule.default_config_section();
613 assert!(config_section.is_some());
614 let (name, _value) = config_section.unwrap();
615 assert_eq!(name, "MD014");
616 }
617}