1use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
7use crate::rule_config_serde::RuleConfig;
8use crate::utils::range_utils::calculate_match_range;
9use crate::utils::regex_cache::get_cached_regex;
10use toml;
11
12mod md014_config;
13use md014_config::MD014Config;
14
15const COMMAND_PATTERN: &str = r"^\s*[$>]\s+\S+";
17const SHELL_LANG_PATTERN: &str = r"^(?i)(bash|sh|shell|console|terminal)";
18const DOLLAR_PROMPT_PATTERN: &str = r"^\s*([$>])";
19
20#[derive(Clone, Default)]
21pub struct MD014CommandsShowOutput {
22 config: MD014Config,
23}
24
25impl MD014CommandsShowOutput {
26 pub fn new() -> Self {
27 Self::default()
28 }
29
30 pub fn with_show_output(show_output: bool) -> Self {
31 Self {
32 config: MD014Config { show_output },
33 }
34 }
35
36 pub fn from_config_struct(config: MD014Config) -> Self {
37 Self { config }
38 }
39
40 fn is_command_line(&self, line: &str) -> bool {
41 get_cached_regex(COMMAND_PATTERN)
42 .map(|re| re.is_match(line))
43 .unwrap_or(false)
44 }
45
46 fn is_shell_language(&self, lang: &str) -> bool {
47 get_cached_regex(SHELL_LANG_PATTERN)
48 .map(|re| re.is_match(lang))
49 .unwrap_or(false)
50 }
51
52 fn is_output_line(&self, line: &str) -> bool {
53 let trimmed = line.trim();
54 !trimmed.is_empty() && !trimmed.starts_with('$') && !trimmed.starts_with('>') && !trimmed.starts_with('#')
55 }
56
57 fn is_no_output_command(&self, cmd: &str) -> bool {
58 let cmd = cmd.trim().to_lowercase();
59
60 cmd.starts_with("cd ")
66 || cmd == "cd"
67 || cmd.starts_with("mkdir ")
68 || cmd.starts_with("touch ")
69 || cmd.starts_with("rm ")
70 || cmd.starts_with("mv ")
71 || cmd.starts_with("cp ")
72 || cmd.starts_with("export ")
73 || cmd.starts_with("set ")
74 || cmd.starts_with("alias ")
75 || cmd.starts_with("unset ")
76 || cmd.starts_with("source ")
77 || cmd.starts_with(". ")
78 || cmd == "true"
79 || cmd == "false"
80 || cmd.starts_with("sleep ")
81 || cmd.starts_with("wait ")
82 || cmd.starts_with("pushd ")
83 || cmd.starts_with("popd")
84
85 || cmd.contains(" > ")
87 || cmd.contains(" >> ")
88
89 || cmd.starts_with("git add ")
91 || cmd.starts_with("git checkout ")
92 || cmd.starts_with("git stash")
93 || cmd.starts_with("git reset ")
94 }
95
96 fn is_command_without_output(&self, block: &[&str], lang: &str) -> bool {
97 if !self.config.show_output || !self.is_shell_language(lang) {
98 return false;
99 }
100
101 let has_output = block.iter().any(|line| self.is_output_line(line));
103 if has_output {
104 return false; }
106
107 self.get_first_output_command(block).is_some()
109 }
110
111 fn get_first_output_command(&self, block: &[&str]) -> Option<(usize, String)> {
114 for (i, line) in block.iter().enumerate() {
115 if self.is_command_line(line) {
116 let cmd = line.trim()[1..].trim().to_string();
117 if !self.is_no_output_command(&cmd) {
118 return Some((i, cmd));
119 }
120 }
121 }
122 None }
124
125 fn fix_command_block(&self, block: &[&str]) -> String {
126 block
127 .iter()
128 .map(|line| {
129 let trimmed = line.trim_start();
130 if self.is_command_line(line) {
131 let spaces = line.len() - line.trim_start().len();
132 let cmd = trimmed.chars().skip(1).collect::<String>().trim_start().to_string();
133 format!("{}{}", " ".repeat(spaces), cmd)
134 } else {
135 line.to_string()
136 }
137 })
138 .collect::<Vec<_>>()
139 .join("\n")
140 }
141
142 fn get_code_block_language(block_start: &str) -> String {
143 block_start
144 .trim_start()
145 .trim_start_matches("```")
146 .split_whitespace()
147 .next()
148 .unwrap_or("")
149 .to_string()
150 }
151
152 fn find_all_command_lines<'a>(&self, block: &[&'a str]) -> Vec<(usize, &'a str)> {
155 let mut results = Vec::new();
156 for (i, line) in block.iter().enumerate() {
157 if self.is_command_line(line) {
158 let cmd = line.trim()[1..].trim();
159 if !self.is_no_output_command(cmd) {
160 results.push((i, *line));
161 }
162 }
163 }
164 results
165 }
166}
167
168impl Rule for MD014CommandsShowOutput {
169 fn name(&self) -> &'static str {
170 "MD014"
171 }
172
173 fn description(&self) -> &'static str {
174 "Commands in code blocks should show output"
175 }
176
177 fn category(&self) -> RuleCategory {
178 RuleCategory::CodeBlock
179 }
180
181 fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
182 let content = ctx.content;
183 let _line_index = &ctx.line_index;
184
185 let mut warnings = Vec::new();
186
187 let mut current_block = Vec::new();
188
189 let mut in_code_block = false;
190
191 let mut block_start_line = 0;
192
193 let mut current_lang = String::new();
194
195 for (line_num, line) in content.lines().enumerate() {
196 if line.trim_start().starts_with("```") {
197 if in_code_block {
198 if self.is_command_without_output(¤t_block, ¤t_lang) {
200 let command_lines = self.find_all_command_lines(¤t_block);
202 let fix = Fix {
203 range: {
204 let content_start_line = block_start_line + 1; let content_end_line = line_num - 1; let start_byte = _line_index.get_line_start_byte(content_start_line + 1).unwrap_or(0); let end_byte = _line_index
211 .get_line_start_byte(content_end_line + 2)
212 .unwrap_or(start_byte); start_byte..end_byte
214 },
215 replacement: format!("{}\n", self.fix_command_block(¤t_block)),
216 };
217
218 for (cmd_line_idx, cmd_line) in &command_lines {
219 let cmd_line_num = block_start_line + 1 + cmd_line_idx + 1; if let Ok(re) = get_cached_regex(DOLLAR_PROMPT_PATTERN)
223 && let Some(cap) = re.captures(cmd_line)
224 {
225 let match_obj = cap.get(1).unwrap(); let (start_line, start_col, end_line, end_col) =
227 calculate_match_range(cmd_line_num, cmd_line, match_obj.start(), match_obj.len());
228
229 let cmd_text = cmd_line.trim()[1..].trim().to_string();
231 let message = if cmd_text.is_empty() {
232 "Command should show output (add example output or remove $ prompt)".to_string()
233 } else {
234 format!(
235 "Command '{cmd_text}' should show output (add example output or remove $ prompt)"
236 )
237 };
238
239 warnings.push(LintWarning {
240 rule_name: Some(self.name().to_string()),
241 line: start_line,
242 column: start_col,
243 end_line,
244 end_column: end_col,
245 message,
246 severity: Severity::Warning,
247 fix: Some(fix.clone()),
248 });
249 }
250 }
251 }
252 current_block.clear();
253 } else {
254 block_start_line = line_num;
256 current_lang = Self::get_code_block_language(line);
257 }
258 in_code_block = !in_code_block;
259 } else if in_code_block {
260 current_block.push(line);
261 }
262 }
263
264 Ok(warnings)
265 }
266
267 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
268 let content = ctx.content;
269 let _line_index = &ctx.line_index;
270
271 let mut result = String::new();
272
273 let mut current_block = Vec::new();
274
275 let mut in_code_block = false;
276
277 let mut current_lang = String::new();
278
279 let mut block_start_line_num = 0usize;
280
281 for (line_num_0, line) in content.lines().enumerate() {
282 let line_num = line_num_0 + 1;
283 if line.trim_start().starts_with("```") {
284 if in_code_block {
285 let block_disabled = (0..current_block.len()).any(|j| {
288 let block_line_num = block_start_line_num + 1 + j;
289 ctx.inline_config().is_rule_disabled(self.name(), block_line_num)
290 });
291 if !block_disabled && self.is_command_without_output(¤t_block, ¤t_lang) {
292 result.push_str(&self.fix_command_block(¤t_block));
293 result.push('\n');
294 } else {
295 for block_line in ¤t_block {
296 result.push_str(block_line);
297 result.push('\n');
298 }
299 }
300 current_block.clear();
301 } else {
302 current_lang = Self::get_code_block_language(line);
303 block_start_line_num = line_num;
304 }
305 in_code_block = !in_code_block;
306 result.push_str(line);
307 result.push('\n');
308 } else if in_code_block {
309 current_block.push(line);
310 } else {
311 result.push_str(line);
312 result.push('\n');
313 }
314 }
315
316 if !content.ends_with('\n') && result.ends_with('\n') {
318 result.pop();
319 }
320
321 Ok(result)
322 }
323
324 fn as_any(&self) -> &dyn std::any::Any {
325 self
326 }
327
328 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
329 ctx.content.is_empty() || !ctx.likely_has_code()
331 }
332
333 fn default_config_section(&self) -> Option<(String, toml::Value)> {
334 let default_config = MD014Config::default();
335 let json_value = serde_json::to_value(&default_config).ok()?;
336 let toml_value = crate::rule_config_serde::json_to_toml_value(&json_value)?;
337
338 if let toml::Value::Table(table) = toml_value {
339 if !table.is_empty() {
340 Some((MD014Config::RULE_NAME.to_string(), toml::Value::Table(table)))
341 } else {
342 None
343 }
344 } else {
345 None
346 }
347 }
348
349 fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
350 where
351 Self: Sized,
352 {
353 let rule_config = crate::rule_config_serde::load_rule_config::<MD014Config>(config);
354 Box::new(Self::from_config_struct(rule_config))
355 }
356}
357
358#[cfg(test)]
359mod tests {
360 use super::*;
361 use crate::lint_context::LintContext;
362
363 #[test]
364 fn test_is_command_line() {
365 let rule = MD014CommandsShowOutput::new();
366 assert!(rule.is_command_line("$ echo test"));
367 assert!(rule.is_command_line(" $ ls -la"));
368 assert!(rule.is_command_line("> pwd"));
369 assert!(rule.is_command_line(" > cd /home"));
370 assert!(!rule.is_command_line("echo test"));
371 assert!(!rule.is_command_line("# comment"));
372 assert!(!rule.is_command_line("output line"));
373 }
374
375 #[test]
376 fn test_is_shell_language() {
377 let rule = MD014CommandsShowOutput::new();
378 assert!(rule.is_shell_language("bash"));
379 assert!(rule.is_shell_language("BASH"));
380 assert!(rule.is_shell_language("sh"));
381 assert!(rule.is_shell_language("shell"));
382 assert!(rule.is_shell_language("Shell"));
383 assert!(rule.is_shell_language("console"));
384 assert!(rule.is_shell_language("CONSOLE"));
385 assert!(rule.is_shell_language("terminal"));
386 assert!(rule.is_shell_language("Terminal"));
387 assert!(!rule.is_shell_language("python"));
388 assert!(!rule.is_shell_language("javascript"));
389 assert!(!rule.is_shell_language(""));
390 }
391
392 #[test]
393 fn test_is_output_line() {
394 let rule = MD014CommandsShowOutput::new();
395 assert!(rule.is_output_line("output text"));
396 assert!(rule.is_output_line(" some output"));
397 assert!(rule.is_output_line("file1 file2"));
398 assert!(!rule.is_output_line(""));
399 assert!(!rule.is_output_line(" "));
400 assert!(!rule.is_output_line("$ command"));
401 assert!(!rule.is_output_line("> prompt"));
402 assert!(!rule.is_output_line("# comment"));
403 }
404
405 #[test]
406 fn test_is_no_output_command() {
407 let rule = MD014CommandsShowOutput::new();
408
409 assert!(rule.is_no_output_command("cd /home"));
411 assert!(rule.is_no_output_command("cd"));
412 assert!(rule.is_no_output_command("mkdir test"));
413 assert!(rule.is_no_output_command("touch file.txt"));
414 assert!(rule.is_no_output_command("rm -rf dir"));
415 assert!(rule.is_no_output_command("mv old new"));
416 assert!(rule.is_no_output_command("cp src dst"));
417 assert!(rule.is_no_output_command("export VAR=value"));
418 assert!(rule.is_no_output_command("set -e"));
419 assert!(rule.is_no_output_command("source ~/.bashrc"));
420 assert!(rule.is_no_output_command(". ~/.profile"));
421 assert!(rule.is_no_output_command("alias ll='ls -la'"));
422 assert!(rule.is_no_output_command("unset VAR"));
423 assert!(rule.is_no_output_command("true"));
424 assert!(rule.is_no_output_command("false"));
425 assert!(rule.is_no_output_command("sleep 5"));
426 assert!(rule.is_no_output_command("pushd /tmp"));
427 assert!(rule.is_no_output_command("popd"));
428
429 assert!(rule.is_no_output_command("CD /HOME"));
431 assert!(rule.is_no_output_command("MKDIR TEST"));
432
433 assert!(rule.is_no_output_command("echo 'test' > file.txt"));
435 assert!(rule.is_no_output_command("cat input.txt > output.txt"));
436 assert!(rule.is_no_output_command("echo 'append' >> log.txt"));
437
438 assert!(rule.is_no_output_command("git add ."));
440 assert!(rule.is_no_output_command("git checkout main"));
441 assert!(rule.is_no_output_command("git stash"));
442 assert!(rule.is_no_output_command("git reset HEAD~1"));
443
444 assert!(!rule.is_no_output_command("ls -la"));
446 assert!(!rule.is_no_output_command("echo test")); assert!(!rule.is_no_output_command("pwd"));
448 assert!(!rule.is_no_output_command("cat file.txt")); assert!(!rule.is_no_output_command("grep pattern file"));
450
451 assert!(!rule.is_no_output_command("pip install requests"));
453 assert!(!rule.is_no_output_command("npm install express"));
454 assert!(!rule.is_no_output_command("cargo install ripgrep"));
455 assert!(!rule.is_no_output_command("brew install git"));
456
457 assert!(!rule.is_no_output_command("cargo build"));
459 assert!(!rule.is_no_output_command("npm run build"));
460 assert!(!rule.is_no_output_command("make"));
461
462 assert!(!rule.is_no_output_command("docker ps"));
464 assert!(!rule.is_no_output_command("docker compose up"));
465 assert!(!rule.is_no_output_command("docker run myimage"));
466
467 assert!(!rule.is_no_output_command("git status"));
469 assert!(!rule.is_no_output_command("git log"));
470 assert!(!rule.is_no_output_command("git diff"));
471 }
472
473 #[test]
474 fn test_fix_command_block() {
475 let rule = MD014CommandsShowOutput::new();
476 let block = vec!["$ echo test", "$ ls -la"];
477 assert_eq!(rule.fix_command_block(&block), "echo test\nls -la");
478
479 let indented = vec![" $ echo test", " $ pwd"];
480 assert_eq!(rule.fix_command_block(&indented), " echo test\n pwd");
481
482 let mixed = vec!["> cd /home", "$ mkdir test"];
483 assert_eq!(rule.fix_command_block(&mixed), "cd /home\nmkdir test");
484 }
485
486 #[test]
487 fn test_get_code_block_language() {
488 assert_eq!(MD014CommandsShowOutput::get_code_block_language("```bash"), "bash");
489 assert_eq!(MD014CommandsShowOutput::get_code_block_language("```shell"), "shell");
490 assert_eq!(
491 MD014CommandsShowOutput::get_code_block_language(" ```console"),
492 "console"
493 );
494 assert_eq!(
495 MD014CommandsShowOutput::get_code_block_language("```bash {.line-numbers}"),
496 "bash"
497 );
498 assert_eq!(MD014CommandsShowOutput::get_code_block_language("```"), "");
499 }
500
501 #[test]
502 fn test_find_all_command_lines() {
503 let rule = MD014CommandsShowOutput::new();
504 let block = vec!["# comment", "$ echo test", "output"];
505 let result = rule.find_all_command_lines(&block);
506 assert_eq!(result, vec![(1, "$ echo test")]);
507
508 let no_commands = vec!["output1", "output2"];
509 assert!(rule.find_all_command_lines(&no_commands).is_empty());
510
511 let multiple = vec!["$ echo one", "$ echo two", "$ cd /tmp"];
512 let result = rule.find_all_command_lines(&multiple);
513 assert_eq!(result, vec![(0, "$ echo one"), (1, "$ echo two")]);
515 }
516
517 #[test]
518 fn test_is_command_without_output() {
519 let rule = MD014CommandsShowOutput::with_show_output(true);
520
521 let block1 = vec!["$ echo test"];
523 assert!(rule.is_command_without_output(&block1, "bash"));
524
525 let block2 = vec!["$ echo test", "test"];
527 assert!(!rule.is_command_without_output(&block2, "bash"));
528
529 let block3 = vec!["$ cd /home"];
531 assert!(!rule.is_command_without_output(&block3, "bash"));
532
533 let rule_disabled = MD014CommandsShowOutput::with_show_output(false);
535 assert!(!rule_disabled.is_command_without_output(&block1, "bash"));
536
537 assert!(!rule.is_command_without_output(&block1, "python"));
539 }
540
541 #[test]
542 fn test_edge_cases() {
543 let rule = MD014CommandsShowOutput::new();
544 let content = "```bash\n$ \n```";
546 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
547 let result = rule.check(&ctx).unwrap();
548 assert!(
549 result.is_empty(),
550 "Bare $ with only space doesn't match command pattern"
551 );
552
553 let empty_content = "```bash\n```";
555 let ctx2 = LintContext::new(empty_content, crate::config::MarkdownFlavor::Standard, None);
556 let result2 = rule.check(&ctx2).unwrap();
557 assert!(result2.is_empty(), "Empty code block should not be flagged");
558
559 let minimal = "```bash\n$ a\n```";
561 let ctx3 = LintContext::new(minimal, crate::config::MarkdownFlavor::Standard, None);
562 let result3 = rule.check(&ctx3).unwrap();
563 assert_eq!(result3.len(), 1, "Minimal command should be flagged");
564 }
565
566 #[test]
567 fn test_mixed_silent_and_output_commands() {
568 let rule = MD014CommandsShowOutput::new();
569
570 let silent_only = "```bash\n$ cd /home\n$ mkdir test\n```";
572 let ctx1 = LintContext::new(silent_only, crate::config::MarkdownFlavor::Standard, None);
573 let result1 = rule.check(&ctx1).unwrap();
574 assert!(
575 result1.is_empty(),
576 "Block with only silent commands should not be flagged"
577 );
578
579 let mixed_silent_first = "```bash\n$ cd /home\n$ ls -la\n```";
582 let ctx2 = LintContext::new(mixed_silent_first, crate::config::MarkdownFlavor::Standard, None);
583 let result2 = rule.check(&ctx2).unwrap();
584 assert_eq!(result2.len(), 1, "Only output-producing commands should be flagged");
585 assert!(
586 result2[0].message.contains("ls -la"),
587 "Message should mention 'ls -la', not 'cd /home'. Got: {}",
588 result2[0].message
589 );
590
591 let mixed_mkdir_cat = "```bash\n$ mkdir test\n$ cat file.txt\n```";
593 let ctx3 = LintContext::new(mixed_mkdir_cat, crate::config::MarkdownFlavor::Standard, None);
594 let result3 = rule.check(&ctx3).unwrap();
595 assert_eq!(result3.len(), 1, "Only output-producing commands should be flagged");
596 assert!(
597 result3[0].message.contains("cat file.txt"),
598 "Message should mention 'cat file.txt', not 'mkdir'. Got: {}",
599 result3[0].message
600 );
601
602 let mkdir_pip = "```bash\n$ mkdir test\n$ pip install something\n```";
604 let ctx3b = LintContext::new(mkdir_pip, crate::config::MarkdownFlavor::Standard, None);
605 let result3b = rule.check(&ctx3b).unwrap();
606 assert_eq!(result3b.len(), 1, "Block with pip install should be flagged");
607 assert!(
608 result3b[0].message.contains("pip install"),
609 "Message should mention 'pip install'. Got: {}",
610 result3b[0].message
611 );
612
613 let mixed_output_first = "```bash\n$ echo hello\n$ cd /home\n```";
615 let ctx4 = LintContext::new(mixed_output_first, crate::config::MarkdownFlavor::Standard, None);
616 let result4 = rule.check(&ctx4).unwrap();
617 assert_eq!(result4.len(), 1, "Only output-producing commands should be flagged");
618 assert!(
619 result4[0].message.contains("echo hello"),
620 "Message should mention 'echo hello'. Got: {}",
621 result4[0].message
622 );
623 }
624
625 #[test]
626 fn test_multiple_commands_without_output_all_flagged() {
627 let rule = MD014CommandsShowOutput::new();
628
629 let content = "```shell\n# First invocation\n$ my_command\n\n# Second invocation\n$ my_command\n```";
631 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
632 let result = rule.check(&ctx).unwrap();
633 assert_eq!(result.len(), 2, "Both commands should be flagged. Got: {result:?}");
634 assert!(result[0].message.contains("my_command"));
635 assert!(result[1].message.contains("my_command"));
636 assert_ne!(result[0].line, result[1].line, "Warnings should be on different lines");
638
639 let content2 = "```bash\n$ echo hello\n$ ls -la\n$ pwd\n```";
641 let ctx2 = LintContext::new(content2, crate::config::MarkdownFlavor::Standard, None);
642 let result2 = rule.check(&ctx2).unwrap();
643 assert_eq!(
644 result2.len(),
645 3,
646 "All three commands should be flagged. Got: {result2:?}"
647 );
648 assert!(result2[0].message.contains("echo hello"));
649 assert!(result2[1].message.contains("ls -la"));
650 assert!(result2[2].message.contains("pwd"));
651
652 let content3 = "```bash\n$ echo hello\n$ cd /tmp\n$ ls -la\n```";
654 let ctx3 = LintContext::new(content3, crate::config::MarkdownFlavor::Standard, None);
655 let result3 = rule.check(&ctx3).unwrap();
656 assert_eq!(
657 result3.len(),
658 2,
659 "Only output-producing commands should be flagged. Got: {result3:?}"
660 );
661 assert!(result3[0].message.contains("echo hello"));
662 assert!(result3[1].message.contains("ls -la"));
663 }
664
665 #[test]
666 fn test_issue_516_exact_case() {
667 let rule = MD014CommandsShowOutput::new();
668
669 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";
671 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
672 let result = rule.check(&ctx).unwrap();
673 assert_eq!(
674 result.len(),
675 2,
676 "Both $ my_command lines should be flagged. Got: {result:?}"
677 );
678 assert_eq!(result[0].line, 9, "First warning should be on line 9");
679 assert_eq!(result[1].line, 12, "Second warning should be on line 12");
680 }
681
682 #[test]
683 fn test_default_config_section() {
684 let rule = MD014CommandsShowOutput::new();
685 let config_section = rule.default_config_section();
686 assert!(config_section.is_some());
687 let (name, _value) = config_section.unwrap();
688 assert_eq!(name, "MD014");
689 }
690}