rumdl 0.0.12

A fast Markdown linter written in Rust (Ru(st) MarkDown Linter)
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
use clap::{Parser, Subcommand};
use colored::*;
use rumdl::rule::{Rule, LintWarning};
use rumdl::rules::*;
use rumdl::md046_code_block_style::CodeBlockStyle;
use rumdl::md048_code_fence_style::CodeFenceStyle;
use rumdl::md049_emphasis_style::EmphasisStyle;
use rumdl::md050_strong_style::StrongStyle;
use std::fs;
use std::path::Path;
use std::process;
use walkdir::WalkDir;
use ignore;
use glob;

mod config;

#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
    /// Files or directories to lint
    #[arg(required = false)]
    paths: Vec<String>,

    /// Configuration file path
    #[arg(short, long)]
    config: Option<String>,

    /// Fix issues automatically where possible
    #[arg(short, long)]
    fix: bool,

    /// List all available rules
    #[arg(short, long)]
    list_rules: bool,

    /// Disable specific rules (comma-separated)
    #[arg(short, long)]
    disable: Option<String>,

    /// Enable only specific rules (comma-separated)
    #[arg(short, long)]
    enable: Option<String>,
    
    /// Exclude specific files or directories (comma-separated glob patterns)
    #[arg(long)]
    exclude: Option<String>,

    /// Respect .gitignore files when scanning directories
    #[arg(long)]
    respect_gitignore: bool,

    /// Debug gitignore patterns for a specific file
    #[arg(long)]
    debug_gitignore: bool,

    /// Show detailed output
    #[arg(short, long)]
    verbose: bool,
    
    /// Command to run
    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Initialize a new configuration file
    Init,
}

fn get_rules(opts: &Cli) -> Vec<Box<dyn Rule>> {
    let mut rules: Vec<Box<dyn Rule>> = Vec::new();

    // Load configuration file if provided
    let config_result = match &opts.config {
        Some(path) => config::load_config(Some(path)),
        None => config::load_config(None),
    };

    // Log any configuration errors but continue with defaults
    let config = match config_result {
        Ok(config) => config,
        Err(err) => {
            eprintln!("{}: {}", "Configuration error".yellow().bold(), err);
            config::Config::default()
        }
    };

    // Add implemented rules
    rules.push(Box::new(MD001HeadingIncrement::default()));
    rules.push(Box::new(MD002FirstHeadingH1::default()));
    rules.push(Box::new(MD003HeadingStyle::default()));
    rules.push(Box::new(MD004UnorderedListStyle::default()));
    rules.push(Box::new(MD005ListIndent::default()));
    rules.push(Box::new(MD006StartBullets::default()));
    rules.push(Box::new(MD007ULIndent::default()));
    
    // Configure MD008 from config if available
    let md008 = if let Some(style) = config::get_rule_config_value::<char>(&config, "MD008", "style") {
        Box::new(MD008ULStyle::new(style))
    } else {
        Box::new(MD008ULStyle::default())
    };
    rules.push(md008);
    
    rules.push(Box::new(MD009TrailingSpaces::default()));
    rules.push(Box::new(MD010NoHardTabs::default()));
    rules.push(Box::new(MD011ReversedLink::default()));
    rules.push(Box::new(MD012NoMultipleBlanks::default()));
    
    // Configure MD013 from config if available
    let md013 = {
        let line_length = config::get_rule_config_value::<usize>(&config, "MD013", "line_length")
            .unwrap_or(80);
        let code_blocks = config::get_rule_config_value::<bool>(&config, "MD013", "code_blocks")
            .unwrap_or(true);
        let tables = config::get_rule_config_value::<bool>(&config, "MD013", "tables")
            .unwrap_or(false);
        let headings = config::get_rule_config_value::<bool>(&config, "MD013", "headings")
            .unwrap_or(true);
        let strict = config::get_rule_config_value::<bool>(&config, "MD013", "strict")
            .unwrap_or(false);
        
        Box::new(MD013LineLength::new(line_length, code_blocks, tables, headings, strict))
    };
    rules.push(md013);
    
    rules.push(Box::new(MD014CommandsShowOutput::default()));
    rules.push(Box::new(MD015NoMissingSpaceAfterListMarker::default()));
    rules.push(Box::new(MD016NoMultipleSpaceAfterListMarker::default()));
    rules.push(Box::new(MD017NoEmphasisAsHeading::default()));
    rules.push(Box::new(MD018NoMissingSpaceAtx::default()));
    rules.push(Box::new(MD019NoMultipleSpaceAtx::default()));
    rules.push(Box::new(MD020NoMissingSpaceClosedAtx::default()));
    rules.push(Box::new(MD021NoMultipleSpaceClosedAtx::default()));
    rules.push(Box::new(MD022BlanksAroundHeadings::default()));
    rules.push(Box::new(MD023HeadingStartLeft::default()));
    rules.push(Box::new(MD024MultipleHeadings::default()));
    rules.push(Box::new(MD025SingleTitle::default()));
    rules.push(Box::new(MD026NoTrailingPunctuation::default()));
    rules.push(Box::new(MD027MultipleSpacesBlockquote::default()));
    rules.push(Box::new(MD028NoBlanksBlockquote::default()));
    rules.push(Box::new(MD029OrderedListPrefix::default()));
    rules.push(Box::new(MD030ListMarkerSpace::default()));
    rules.push(Box::new(MD031BlanksAroundFences::default()));
    rules.push(Box::new(MD032BlanksAroundLists::default()));
    rules.push(Box::new(MD033NoInlineHtml::default()));
    rules.push(Box::new(MD034NoBareUrls::default()));
    rules.push(Box::new(MD035HRStyle::default()));
    rules.push(Box::new(MD036NoEmphasisOnlyFirst::default()));
    rules.push(Box::new(MD037SpacesAroundEmphasis::default()));
    rules.push(Box::new(MD038NoSpaceInCode::default()));
    rules.push(Box::new(MD039NoSpaceInLinks::default()));
    rules.push(Box::new(MD040FencedCodeLanguage::default()));
    rules.push(Box::new(MD041FirstLineHeading::default()));
    rules.push(Box::new(MD042NoEmptyLinks::new()));
    rules.push(Box::new(MD043RequiredHeadings::new(Vec::new())));
    rules.push(Box::new(MD044ProperNames::new(Vec::new(), true)));
    rules.push(Box::new(MD045NoAltText::new()));
    
    // Configure MD046 from config if available
    let md046 = {
        let style_str = config::get_rule_config_value::<String>(&config, "MD046", "style")
            .unwrap_or_else(|| "consistent".to_string());
        
        let style = match style_str.to_lowercase().as_str() {
            "fenced" => CodeBlockStyle::Fenced,
            "indented" => CodeBlockStyle::Indented,
            _ => CodeBlockStyle::Consistent,
        };
        
        Box::new(MD046CodeBlockStyle::new(style))
    };
    rules.push(md046);
    
    rules.push(Box::new(MD047FileEndNewline::default()));
    
    // Configure MD048 from config if available
    let md048 = {
        let style_str = config::get_rule_config_value::<String>(&config, "MD048", "style")
            .unwrap_or_else(|| "consistent".to_string());
        
        let style = match style_str.to_lowercase().as_str() {
            "backtick" => CodeFenceStyle::Backtick,
            "tilde" => CodeFenceStyle::Tilde,
            _ => CodeFenceStyle::Consistent,
        };
        
        Box::new(MD048CodeFenceStyle::new(style))
    };
    rules.push(md048);
    
    // Configure MD049 from config if available
    let md049 = {
        let style_str = config::get_rule_config_value::<String>(&config, "MD049", "style")
            .unwrap_or_else(|| "consistent".to_string());
        
        let style = match style_str.to_lowercase().as_str() {
            "asterisk" => EmphasisStyle::Asterisk,
            "underscore" => EmphasisStyle::Underscore,
            _ => EmphasisStyle::Consistent,
        };
        
        Box::new(MD049EmphasisStyle::new(style))
    };
    rules.push(md049);
    
    // Configure MD050 from config if available
    let md050 = {
        let style_str = config::get_rule_config_value::<String>(&config, "MD050", "style")
            .unwrap_or_else(|| "consistent".to_string());
        
        let style = match style_str.to_lowercase().as_str() {
            "asterisk" => StrongStyle::Asterisk,
            "underscore" => StrongStyle::Underscore,
            _ => StrongStyle::Consistent,
        };
        
        Box::new(MD050StrongStyle::new(style))
    };
    rules.push(md050);
    
    rules.push(Box::new(MD051LinkFragments::new()));
    rules.push(Box::new(MD052ReferenceLinkImages::new()));
    rules.push(Box::new(MD053LinkImageReferenceDefinitions::default()));
    
    // Use default implementation for MD054
    rules.push(Box::new(MD054LinkImageStyle::default()));
    
    rules.push(Box::new(MD055TablePipeStyle::default()));
    rules.push(Box::new(MD056TableColumnCount));
    rules.push(Box::new(MD058BlanksAroundTables));

    // Filter rules based on configuration and command-line options
    // Priority: command-line options override config file settings
    let disable_rules: Vec<String> = match &opts.disable {
        Some(disable_str) => disable_str.split(',').map(String::from).collect(),
        None => config.global.disable.clone(),
    };

    let enable_rules: Vec<String> = match &opts.enable {
        Some(enable_str) => enable_str.split(',').map(String::from).collect(),
        None => config.global.enable.clone(),
    };

    // Apply the filters
    if !enable_rules.is_empty() {
        rules.retain(|rule| enable_rules.iter().any(|r| r == rule.name()));
    } else if !disable_rules.is_empty() {
        rules.retain(|rule| !disable_rules.iter().any(|r| r == rule.name()));
    }

    rules
}

fn list_available_rules() {
    println!("Available rules:");
    
    // Create a temporary instance of all rules to get their names and descriptions
    let rules = get_rules(&Cli {
        paths: Vec::new(),
        config: None,
        fix: false,
        list_rules: true,
        disable: None,
        enable: None,
        exclude: None,
        respect_gitignore: false,
        debug_gitignore: false,
        verbose: false,
        command: None,
    });
    
    // Sort rules by name
    let mut rule_info: Vec<(&str, &str)> = rules.iter()
        .map(|rule| (rule.name(), rule.description()))
        .collect();
    rule_info.sort_by(|a, b| a.0.cmp(b.0));
    
    // Print rule names and descriptions
    for (name, description) in rule_info {
        println!("{} - {}", name, description);
    }
}

fn process_file(path: &str, rules: &[Box<dyn Rule>], fix: bool, verbose: bool) -> (bool, usize, usize) {
    let content = match fs::read_to_string(path) {
        Ok(content) => content,
        Err(err) => {
            eprintln!("{}: {}", "Error reading file".red().bold(), format!("{}: {}", path, err));
            return (false, 0, 0);
        }
    };
    
    let mut has_warnings = false;
    let mut total_warnings = 0;
    let mut total_fixed = 0;
    let mut all_warnings = Vec::new();
    
    // Collect all warnings first
    for rule in rules {
        match rule.check(&content) {
            Ok(warnings) => {
                if !warnings.is_empty() {
                    // Filter out warnings for lines where the rule is disabled
                    let filtered_warnings: Vec<LintWarning> = warnings.into_iter()
                        .filter(|warning| !rumdl::rule::is_rule_disabled_at_line(&content, rule.name(), warning.line - 1))
                        .collect();
                    
                    if !filtered_warnings.is_empty() {
                        has_warnings = true;
                        total_warnings += filtered_warnings.len();
                        
                        for warning in filtered_warnings {
                            all_warnings.push((rule.name(), rule, warning));
                        }
                    }
                }
            }
            Err(err) => {
                eprintln!("{}: {} on file {}: {}", 
                    "Error".red().bold(), 
                    rule.name().yellow(), 
                    path.blue().underline(), 
                    err);
            }
        }
    }
    
    // Sort warnings by line and column
    all_warnings.sort_by(|a, b| {
        let line_cmp = a.2.line.cmp(&b.2.line);
        if line_cmp == std::cmp::Ordering::Equal {
            a.2.column.cmp(&b.2.column)
        } else {
            line_cmp
        }
    });
    
    // Display warnings in a clean format
    if !all_warnings.is_empty() {
        for (rule_name, _, warning) in &all_warnings {
            let fixable = warning.fix.is_some();
            let fix_indicator = if fixable && fix { "[fixed]".green() } else if fixable { "[*]".green() } else { "".normal() };
            
            println!("{}:{}:{}: {} {} {}", 
                path.blue().underline(),
                warning.line.to_string().cyan(),
                warning.column.to_string().cyan(),
                format!("[{}]", rule_name).yellow(),
                warning.message,
                fix_indicator);
        }
    } else {
        if verbose {
            println!("{} No issues found in {}", "".green(), path.blue().underline());
        }
    }
    
    // Apply fixes in a single pass if requested
    if fix && has_warnings {
        let mut fixed_content = content.clone();
        let mut fixed_warnings = 0;
        
        // Group all warnings by rule, then apply each rule's fixes in a single operation
        let mut rule_to_warnings: std::collections::HashMap<&'static str, Vec<&LintWarning>> = std::collections::HashMap::new();
        
        for (rule_name, _, warning) in &all_warnings {
            if warning.fix.is_some() {
                rule_to_warnings.entry(rule_name).or_insert_with(Vec::new).push(warning);
            }
        }
        
        // Apply fixes for each rule
        for (rule_name, warnings) in rule_to_warnings {
            // Find the rule by name
            if let Some(rule) = rules.iter().find(|r| r.name() == rule_name) {
                match rule.fix(&fixed_content) {
                    Ok(new_content) => {
                        fixed_warnings += warnings.len();
                        fixed_content = new_content;
                    }
                    Err(err) => {
                        eprintln!("  {} {}: {}", 
                            "Error fixing issues with".red().bold(), 
                            rule_name.yellow(), 
                            err);
                    }
                }
            }
        }
        
        // Write fixed content back to file
        if fixed_warnings > 0 {
            total_fixed = fixed_warnings;
            match fs::write(path, fixed_content) {
                Ok(_) => {}
                Err(err) => {
                    eprintln!("{} {}: {}", 
                        "Error writing fixed content to".red().bold(), 
                        path.blue().underline(), 
                        err);
                }
            }
        }
    }
    
    // Return whether there were warnings, total warnings, and total fixed
    (has_warnings, total_warnings, total_fixed)
}

// Helper function to test if a file would be ignored by .gitignore
fn debug_gitignore_test(path: &str, verbose: bool) {
    use ignore::WalkBuilder;
    use std::path::Path;
    use std::fs;

    let file_path = Path::new(path);
    
    println!("Testing gitignore patterns for: {}", path);
    
    // First, check if the file exists
    if !file_path.exists() {
        println!("File does not exist: {}", path);
        return;
    }
    
    // Read the .gitignore file if it exists
    let mut gitignore_patterns = Vec::new();
    if let Ok(content) = fs::read_to_string(".gitignore") {
        println!("\nFound .gitignore file with the following patterns:");
        for line in content.lines() {
            let trimmed = line.trim();
            if !trimmed.is_empty() && !trimmed.starts_with('#') {
                println!("  - {}", trimmed);
                gitignore_patterns.push(trimmed.to_string());
            }
        }
    } else {
        println!("No .gitignore file found in the current directory.");
    }
    
    // Create a walker that respects .gitignore files
    let walker = WalkBuilder::new(".")
        .hidden(true)
        .git_global(true)
        .git_ignore(true)
        .git_exclude(true)
        .add_custom_ignore_filename(".gitignore")
        .build();
    
    // Check if the file is in the walker's output
    let mut found_in_walker = false;
    let canonical_path = file_path.canonicalize().unwrap_or_else(|_| file_path.to_path_buf());
    
    for entry_result in walker {
        if let Ok(entry) = entry_result {
            let entry_canonical = entry.path().canonicalize().unwrap_or_else(|_| entry.path().to_path_buf());
            if entry_canonical == canonical_path {
                found_in_walker = true;
                break;
            }
        }
    }
    
    if found_in_walker {
        println!("\nFile would NOT be ignored by gitignore");
    } else {
        println!("\nFile would be IGNORED by gitignore");
        
        // Try to determine which pattern is causing the file to be ignored
        for pattern in &gitignore_patterns {
            if pattern.contains('*') {
                // For glob patterns, use the glob crate
                if let Ok(glob_pattern) = glob::Pattern::new(pattern) {
                    if glob_pattern.matches(path) {
                        println!("  - Matched by pattern: {}", pattern);
                    }
                }
            } else {
                // For simple patterns, check if the path contains the pattern
                if path.contains(pattern) {
                    println!("  - Matched by pattern: {}", pattern);
                }
            }
        }
    }
    
    if verbose {
        println!("\nSample of files that would be processed (not ignored):");
        
        // Create a new walker to list some files that would be processed
        let walker = WalkBuilder::new(".")
            .hidden(true)
            .git_global(true)
            .git_ignore(true)
            .git_exclude(true)
            .add_custom_ignore_filename(".gitignore")
            .build();
            
        let mut count = 0;
        for entry_result in walker {
            if let Ok(entry) = entry_result {
                if entry.file_type().map_or(false, |ft| ft.is_file()) {
                    println!("  - {}", entry.path().display());
                    count += 1;
                    if count >= 10 {
                        println!("  ... and more");
                        break;
                    }
                }
            }
        }
    }
    
    println!();
}

fn main() {
    let cli = Cli::parse();
    
    if cli.list_rules {
        list_available_rules();
        return;
    }
    
    // Handle init command to create a default configuration file
    if let Some(Commands::Init) = cli.command {
        let config_path = ".rumdl.toml";
        match config::create_default_config(config_path) {
            Ok(_) => {
                println!("{}: Created default configuration file at {}", "Success".green().bold(), config_path);
                println!("You can now customize the configuration to suit your needs.");
                return;
            }
            Err(err) => {
                eprintln!("{}: Failed to create configuration file: {}", "Error".red().bold(), err);
                process::exit(1);
            }
        }
    }
    
    // Only require paths if we're not running a subcommand
    if cli.paths.is_empty() && cli.command.is_none() {
        eprintln!("{}: No paths provided. Please specify at least one file or directory to lint.", "Error".red().bold());
        process::exit(1);
    }
    
    // If debug_gitignore is enabled, test gitignore patterns for the specified files
    if cli.debug_gitignore {
        for path in &cli.paths {
            debug_gitignore_test(path, cli.verbose);
        }
        return;
    }
    
    let rules = get_rules(&cli);
    if rules.is_empty() {
        eprintln!("{}: No rules selected to run.", "Error".red().bold());
        process::exit(1);
    }
    
    let mut has_issues = false;
    let mut files_with_issues = 0;
    let mut total_files_processed = 0;
    let mut total_issues_found = 0;
    let mut total_issues_fixed = 0;
    
    // Process exclude patterns from CLI and config
    let mut exclude_patterns = Vec::new();
    let mut respect_gitignore = cli.respect_gitignore;
    
    // Add exclude patterns from config
    if let Ok(config) = config::load_config(cli.config.as_deref()) {
        exclude_patterns.extend(config.global.exclude.clone());
        
        // Check if respect_gitignore is set in config (and not overridden in CLI)
        if config.global.respect_gitignore && !cli.respect_gitignore {
            respect_gitignore = true;
        }
    }
    
    // Add exclude patterns from CLI (overrides config)
    if let Some(exclude_str) = &cli.exclude {
        exclude_patterns.extend(exclude_str.split(',').map(|s| s.trim().to_string()));
    }
    
    // Remove duplicates from exclude_patterns
    exclude_patterns.sort();
    exclude_patterns.dedup();
    
    if cli.verbose && !exclude_patterns.is_empty() {
        println!("Excluding the following patterns:");
        for pattern in &exclude_patterns {
            println!("  - {}", pattern);
        }
        println!();
    }
    
    for path_str in &cli.paths {
        let path = Path::new(path_str);
        
        if !path.exists() {
            eprintln!("{}: Path does not exist: {}", "Error".red().bold(), path_str);
            has_issues = true;
            continue;
        }
        
        if path.is_file() {
            // Check if file is excluded based on patterns
            let excluded = rumdl::should_exclude(path_str, &exclude_patterns);
            
            if excluded {
                if cli.verbose {
                    println!("Skipping excluded file: {}", path_str);
                }
                continue;
            }
            
            // Check if file should be ignored by gitignore when respect_gitignore is enabled
            if respect_gitignore {
                use ignore::WalkBuilder;
                
                let file_path = Path::new(path_str);
                let canonical_path = file_path.canonicalize().unwrap_or_else(|_| file_path.to_path_buf());
                
                // Create a walker that respects .gitignore files
                let walker = WalkBuilder::new(".")
                    .hidden(true)
                    .git_global(true)
                    .git_ignore(true)
                    .git_exclude(true)
                    .add_custom_ignore_filename(".gitignore")
                    .build();
                
                // Check if the file is in the walker's output
                let mut found_in_walker = false;
                
                for entry_result in walker {
                    if let Ok(entry) = entry_result {
                        let entry_canonical = entry.path().canonicalize().unwrap_or_else(|_| entry.path().to_path_buf());
                        if entry_canonical == canonical_path {
                            found_in_walker = true;
                            break;
                        }
                    }
                }
                
                if !found_in_walker {
                    if cli.verbose {
                        println!("Skipping file ignored by gitignore: {}", path_str);
                    }
                    continue;
                }
            }
            
            total_files_processed += 1;
            let (file_has_issues, issues_found, issues_fixed) = process_file(path_str, &rules, cli.fix, cli.verbose);
            if file_has_issues {
                has_issues = true;
                files_with_issues += 1;
                total_issues_found += issues_found;
                total_issues_fixed += issues_fixed;
            }
        } else if path.is_dir() {
            // Process directory recursively
            // If respect_gitignore is enabled, use the ignore crate's WalkBuilder
            if respect_gitignore {
                use ignore::WalkBuilder;
                
                // Create a walker that respects .gitignore files
                let walker = WalkBuilder::new(path)
                    .hidden(true)
                    .git_global(true)
                    .git_ignore(true)
                    .git_exclude(true)
                    .add_custom_ignore_filename(".gitignore")
                    .build();
                
                for entry_result in walker {
                    if let Ok(entry) = entry_result {
                        // Only process Markdown files
                        if entry.file_type().map_or(false, |ft| ft.is_file()) 
                            && entry.path().extension().map_or(false, |ext| ext == "md") {
                            
                            let file_path = entry.path().to_string_lossy().to_string();
                            
                            // Check if file is excluded based on patterns
                            let excluded = rumdl::should_exclude(&file_path, &exclude_patterns);
                            
                            if excluded {
                                if cli.verbose {
                                    println!("Skipping excluded file: {}", file_path);
                                }
                                continue;
                            }
                            
                            total_files_processed += 1;
                            let (file_has_issues, issues_found, issues_fixed) = process_file(&file_path, &rules, cli.fix, cli.verbose);
                            if file_has_issues {
                                has_issues = true;
                                files_with_issues += 1;
                                total_issues_found += issues_found;
                                total_issues_fixed += issues_fixed;
                            }
                        }
                    }
                }
            } else {
                // Use walkdir if respect_gitignore is disabled
                match WalkDir::new(path)
                    .follow_links(true)
                    .into_iter()
                    .filter_map(|e| e.ok())
                    .filter(|e| e.file_type().is_file() && e.path().extension().map_or(false, |ext| ext == "md"))
                {
                    dir_iter => {
                        for entry in dir_iter {
                            let file_path = entry.path().to_string_lossy().to_string();
                            
                            // Check if file is excluded based on patterns
                            let excluded = rumdl::should_exclude(&file_path, &exclude_patterns);
                            
                            if excluded {
                                if cli.verbose {
                                    println!("Skipping excluded file: {}", file_path);
                                }
                                continue;
                            }
                            
                            total_files_processed += 1;
                            let (file_has_issues, issues_found, issues_fixed) = process_file(&file_path, &rules, cli.fix, cli.verbose);
                            if file_has_issues {
                                has_issues = true;
                                files_with_issues += 1;
                                total_issues_found += issues_found;
                                total_issues_fixed += issues_fixed;
                            }
                        }
                    }
                }
            }
        }
    }
    
    // Print a single, concise Ruff-like summary
    if has_issues {
        if cli.fix {
            println!("\nFixed {} {} in {} {}", 
                total_issues_fixed,
                if total_issues_fixed == 1 { "issue" } else { "issues" },
                files_with_issues, 
                if files_with_issues == 1 { "file" } else { "files" });
        } else {
            println!("\nFound {} {} in {} {} ({} {} checked)", 
                total_issues_found,
                if total_issues_found == 1 { "issue" } else { "issues" },
                files_with_issues, 
                if files_with_issues == 1 { "file" } else { "files" },
                total_files_processed,
                if total_files_processed == 1 { "file" } else { "files" });
            println!("Run with `--fix` to automatically fix issues");
        }
        
        process::exit(1);
    } else {
        println!("{} No issues found", "".green().bold());
    }
}