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 if self.should_skip(ctx) {
269 return Ok(ctx.content.to_string());
270 }
271 let warnings = self.check(ctx)?;
272 if warnings.is_empty() {
273 return Ok(ctx.content.to_string());
274 }
275 let warnings =
276 crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
277 crate::utils::fix_utils::apply_warning_fixes(ctx.content, &warnings)
278 .map_err(crate::rule::LintError::InvalidInput)
279 }
280
281 fn as_any(&self) -> &dyn std::any::Any {
282 self
283 }
284
285 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
286 ctx.content.is_empty() || !ctx.likely_has_code()
288 }
289
290 fn default_config_section(&self) -> Option<(String, toml::Value)> {
291 let default_config = MD014Config::default();
292 let json_value = serde_json::to_value(&default_config).ok()?;
293 let toml_value = crate::rule_config_serde::json_to_toml_value(&json_value)?;
294
295 if let toml::Value::Table(table) = toml_value {
296 if !table.is_empty() {
297 Some((MD014Config::RULE_NAME.to_string(), toml::Value::Table(table)))
298 } else {
299 None
300 }
301 } else {
302 None
303 }
304 }
305
306 fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
307 where
308 Self: Sized,
309 {
310 let rule_config = crate::rule_config_serde::load_rule_config::<MD014Config>(config);
311 Box::new(Self::from_config_struct(rule_config))
312 }
313}
314
315#[cfg(test)]
316mod tests {
317 use super::*;
318 use crate::lint_context::LintContext;
319
320 #[test]
321 fn test_is_command_line() {
322 let rule = MD014CommandsShowOutput::new();
323 assert!(rule.is_command_line("$ echo test"));
324 assert!(rule.is_command_line(" $ ls -la"));
325 assert!(rule.is_command_line("> pwd"));
326 assert!(rule.is_command_line(" > cd /home"));
327 assert!(!rule.is_command_line("echo test"));
328 assert!(!rule.is_command_line("# comment"));
329 assert!(!rule.is_command_line("output line"));
330 }
331
332 #[test]
333 fn test_is_shell_language() {
334 let rule = MD014CommandsShowOutput::new();
335 assert!(rule.is_shell_language("bash"));
336 assert!(rule.is_shell_language("BASH"));
337 assert!(rule.is_shell_language("sh"));
338 assert!(rule.is_shell_language("shell"));
339 assert!(rule.is_shell_language("Shell"));
340 assert!(rule.is_shell_language("console"));
341 assert!(rule.is_shell_language("CONSOLE"));
342 assert!(rule.is_shell_language("terminal"));
343 assert!(rule.is_shell_language("Terminal"));
344 assert!(!rule.is_shell_language("python"));
345 assert!(!rule.is_shell_language("javascript"));
346 assert!(!rule.is_shell_language(""));
347 }
348
349 #[test]
350 fn test_is_output_line() {
351 let rule = MD014CommandsShowOutput::new();
352 assert!(rule.is_output_line("output text"));
353 assert!(rule.is_output_line(" some output"));
354 assert!(rule.is_output_line("file1 file2"));
355 assert!(!rule.is_output_line(""));
356 assert!(!rule.is_output_line(" "));
357 assert!(!rule.is_output_line("$ command"));
358 assert!(!rule.is_output_line("> prompt"));
359 assert!(!rule.is_output_line("# comment"));
360 }
361
362 #[test]
363 fn test_is_no_output_command() {
364 let rule = MD014CommandsShowOutput::new();
365
366 assert!(rule.is_no_output_command("cd /home"));
368 assert!(rule.is_no_output_command("cd"));
369 assert!(rule.is_no_output_command("mkdir test"));
370 assert!(rule.is_no_output_command("touch file.txt"));
371 assert!(rule.is_no_output_command("rm -rf dir"));
372 assert!(rule.is_no_output_command("mv old new"));
373 assert!(rule.is_no_output_command("cp src dst"));
374 assert!(rule.is_no_output_command("export VAR=value"));
375 assert!(rule.is_no_output_command("set -e"));
376 assert!(rule.is_no_output_command("source ~/.bashrc"));
377 assert!(rule.is_no_output_command(". ~/.profile"));
378 assert!(rule.is_no_output_command("alias ll='ls -la'"));
379 assert!(rule.is_no_output_command("unset VAR"));
380 assert!(rule.is_no_output_command("true"));
381 assert!(rule.is_no_output_command("false"));
382 assert!(rule.is_no_output_command("sleep 5"));
383 assert!(rule.is_no_output_command("pushd /tmp"));
384 assert!(rule.is_no_output_command("popd"));
385
386 assert!(rule.is_no_output_command("CD /HOME"));
388 assert!(rule.is_no_output_command("MKDIR TEST"));
389
390 assert!(rule.is_no_output_command("echo 'test' > file.txt"));
392 assert!(rule.is_no_output_command("cat input.txt > output.txt"));
393 assert!(rule.is_no_output_command("echo 'append' >> log.txt"));
394
395 assert!(rule.is_no_output_command("git add ."));
397 assert!(rule.is_no_output_command("git checkout main"));
398 assert!(rule.is_no_output_command("git stash"));
399 assert!(rule.is_no_output_command("git reset HEAD~1"));
400
401 assert!(!rule.is_no_output_command("ls -la"));
403 assert!(!rule.is_no_output_command("echo test")); assert!(!rule.is_no_output_command("pwd"));
405 assert!(!rule.is_no_output_command("cat file.txt")); assert!(!rule.is_no_output_command("grep pattern file"));
407
408 assert!(!rule.is_no_output_command("pip install requests"));
410 assert!(!rule.is_no_output_command("npm install express"));
411 assert!(!rule.is_no_output_command("cargo install ripgrep"));
412 assert!(!rule.is_no_output_command("brew install git"));
413
414 assert!(!rule.is_no_output_command("cargo build"));
416 assert!(!rule.is_no_output_command("npm run build"));
417 assert!(!rule.is_no_output_command("make"));
418
419 assert!(!rule.is_no_output_command("docker ps"));
421 assert!(!rule.is_no_output_command("docker compose up"));
422 assert!(!rule.is_no_output_command("docker run myimage"));
423
424 assert!(!rule.is_no_output_command("git status"));
426 assert!(!rule.is_no_output_command("git log"));
427 assert!(!rule.is_no_output_command("git diff"));
428 }
429
430 #[test]
431 fn test_fix_command_block() {
432 let rule = MD014CommandsShowOutput::new();
433 let block = vec!["$ echo test", "$ ls -la"];
434 assert_eq!(rule.fix_command_block(&block), "echo test\nls -la");
435
436 let indented = vec![" $ echo test", " $ pwd"];
437 assert_eq!(rule.fix_command_block(&indented), " echo test\n pwd");
438
439 let mixed = vec!["> cd /home", "$ mkdir test"];
440 assert_eq!(rule.fix_command_block(&mixed), "cd /home\nmkdir test");
441 }
442
443 #[test]
444 fn test_get_code_block_language() {
445 assert_eq!(MD014CommandsShowOutput::get_code_block_language("```bash"), "bash");
446 assert_eq!(MD014CommandsShowOutput::get_code_block_language("```shell"), "shell");
447 assert_eq!(
448 MD014CommandsShowOutput::get_code_block_language(" ```console"),
449 "console"
450 );
451 assert_eq!(
452 MD014CommandsShowOutput::get_code_block_language("```bash {.line-numbers}"),
453 "bash"
454 );
455 assert_eq!(MD014CommandsShowOutput::get_code_block_language("```"), "");
456 }
457
458 #[test]
459 fn test_find_all_command_lines() {
460 let rule = MD014CommandsShowOutput::new();
461 let block = vec!["# comment", "$ echo test", "output"];
462 let result = rule.find_all_command_lines(&block);
463 assert_eq!(result, vec![(1, "$ echo test")]);
464
465 let no_commands = vec!["output1", "output2"];
466 assert!(rule.find_all_command_lines(&no_commands).is_empty());
467
468 let multiple = vec!["$ echo one", "$ echo two", "$ cd /tmp"];
469 let result = rule.find_all_command_lines(&multiple);
470 assert_eq!(result, vec![(0, "$ echo one"), (1, "$ echo two")]);
472 }
473
474 #[test]
475 fn test_is_command_without_output() {
476 let rule = MD014CommandsShowOutput::with_show_output(true);
477
478 let block1 = vec!["$ echo test"];
480 assert!(rule.is_command_without_output(&block1, "bash"));
481
482 let block2 = vec!["$ echo test", "test"];
484 assert!(!rule.is_command_without_output(&block2, "bash"));
485
486 let block3 = vec!["$ cd /home"];
488 assert!(!rule.is_command_without_output(&block3, "bash"));
489
490 let rule_disabled = MD014CommandsShowOutput::with_show_output(false);
492 assert!(!rule_disabled.is_command_without_output(&block1, "bash"));
493
494 assert!(!rule.is_command_without_output(&block1, "python"));
496 }
497
498 #[test]
499 fn test_edge_cases() {
500 let rule = MD014CommandsShowOutput::new();
501 let content = "```bash\n$ \n```";
503 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
504 let result = rule.check(&ctx).unwrap();
505 assert!(
506 result.is_empty(),
507 "Bare $ with only space doesn't match command pattern"
508 );
509
510 let empty_content = "```bash\n```";
512 let ctx2 = LintContext::new(empty_content, crate::config::MarkdownFlavor::Standard, None);
513 let result2 = rule.check(&ctx2).unwrap();
514 assert!(result2.is_empty(), "Empty code block should not be flagged");
515
516 let minimal = "```bash\n$ a\n```";
518 let ctx3 = LintContext::new(minimal, crate::config::MarkdownFlavor::Standard, None);
519 let result3 = rule.check(&ctx3).unwrap();
520 assert_eq!(result3.len(), 1, "Minimal command should be flagged");
521 }
522
523 #[test]
524 fn test_mixed_silent_and_output_commands() {
525 let rule = MD014CommandsShowOutput::new();
526
527 let silent_only = "```bash\n$ cd /home\n$ mkdir test\n```";
529 let ctx1 = LintContext::new(silent_only, crate::config::MarkdownFlavor::Standard, None);
530 let result1 = rule.check(&ctx1).unwrap();
531 assert!(
532 result1.is_empty(),
533 "Block with only silent commands should not be flagged"
534 );
535
536 let mixed_silent_first = "```bash\n$ cd /home\n$ ls -la\n```";
539 let ctx2 = LintContext::new(mixed_silent_first, crate::config::MarkdownFlavor::Standard, None);
540 let result2 = rule.check(&ctx2).unwrap();
541 assert_eq!(result2.len(), 1, "Only output-producing commands should be flagged");
542 assert!(
543 result2[0].message.contains("ls -la"),
544 "Message should mention 'ls -la', not 'cd /home'. Got: {}",
545 result2[0].message
546 );
547
548 let mixed_mkdir_cat = "```bash\n$ mkdir test\n$ cat file.txt\n```";
550 let ctx3 = LintContext::new(mixed_mkdir_cat, crate::config::MarkdownFlavor::Standard, None);
551 let result3 = rule.check(&ctx3).unwrap();
552 assert_eq!(result3.len(), 1, "Only output-producing commands should be flagged");
553 assert!(
554 result3[0].message.contains("cat file.txt"),
555 "Message should mention 'cat file.txt', not 'mkdir'. Got: {}",
556 result3[0].message
557 );
558
559 let mkdir_pip = "```bash\n$ mkdir test\n$ pip install something\n```";
561 let ctx3b = LintContext::new(mkdir_pip, crate::config::MarkdownFlavor::Standard, None);
562 let result3b = rule.check(&ctx3b).unwrap();
563 assert_eq!(result3b.len(), 1, "Block with pip install should be flagged");
564 assert!(
565 result3b[0].message.contains("pip install"),
566 "Message should mention 'pip install'. Got: {}",
567 result3b[0].message
568 );
569
570 let mixed_output_first = "```bash\n$ echo hello\n$ cd /home\n```";
572 let ctx4 = LintContext::new(mixed_output_first, crate::config::MarkdownFlavor::Standard, None);
573 let result4 = rule.check(&ctx4).unwrap();
574 assert_eq!(result4.len(), 1, "Only output-producing commands should be flagged");
575 assert!(
576 result4[0].message.contains("echo hello"),
577 "Message should mention 'echo hello'. Got: {}",
578 result4[0].message
579 );
580 }
581
582 #[test]
583 fn test_multiple_commands_without_output_all_flagged() {
584 let rule = MD014CommandsShowOutput::new();
585
586 let content = "```shell\n# First invocation\n$ my_command\n\n# Second invocation\n$ my_command\n```";
588 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
589 let result = rule.check(&ctx).unwrap();
590 assert_eq!(result.len(), 2, "Both commands should be flagged. Got: {result:?}");
591 assert!(result[0].message.contains("my_command"));
592 assert!(result[1].message.contains("my_command"));
593 assert_ne!(result[0].line, result[1].line, "Warnings should be on different lines");
595
596 let content2 = "```bash\n$ echo hello\n$ ls -la\n$ pwd\n```";
598 let ctx2 = LintContext::new(content2, crate::config::MarkdownFlavor::Standard, None);
599 let result2 = rule.check(&ctx2).unwrap();
600 assert_eq!(
601 result2.len(),
602 3,
603 "All three commands should be flagged. Got: {result2:?}"
604 );
605 assert!(result2[0].message.contains("echo hello"));
606 assert!(result2[1].message.contains("ls -la"));
607 assert!(result2[2].message.contains("pwd"));
608
609 let content3 = "```bash\n$ echo hello\n$ cd /tmp\n$ ls -la\n```";
611 let ctx3 = LintContext::new(content3, crate::config::MarkdownFlavor::Standard, None);
612 let result3 = rule.check(&ctx3).unwrap();
613 assert_eq!(
614 result3.len(),
615 2,
616 "Only output-producing commands should be flagged. Got: {result3:?}"
617 );
618 assert!(result3[0].message.contains("echo hello"));
619 assert!(result3[1].message.contains("ls -la"));
620 }
621
622 #[test]
623 fn test_issue_516_exact_case() {
624 let rule = MD014CommandsShowOutput::new();
625
626 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";
628 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
629 let result = rule.check(&ctx).unwrap();
630 assert_eq!(
631 result.len(),
632 2,
633 "Both $ my_command lines should be flagged. Got: {result:?}"
634 );
635 assert_eq!(result[0].line, 9, "First warning should be on line 9");
636 assert_eq!(result[1].line, 12, "Second warning should be on line 12");
637 }
638
639 #[test]
640 fn test_default_config_section() {
641 let rule = MD014CommandsShowOutput::new();
642 let config_section = rule.default_config_section();
643 assert!(config_section.is_some());
644 let (name, _value) = config_section.unwrap();
645 assert_eq!(name, "MD014");
646 }
647}