rumdl 0.1.51

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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
//!
//! Rule MD074: MkDocs nav validation
//!
//! See [docs/md074.md](../../docs/md074.md) for full documentation, configuration, and examples.

use crate::rule::{FixCapability, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
use crate::rule_config_serde::RuleConfig;
use crate::utils::mkdocs_config::find_mkdocs_yml;
use serde::Deserialize;
use std::collections::{HashMap, HashSet};
use std::hash::{DefaultHasher, Hash, Hasher};
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex};

mod md074_config;
pub use md074_config::{MD074Config, NavValidation};

/// Cache mapping mkdocs.yml paths to content hashes.
/// Re-validates when file content changes (self-invalidating for LSP mode).
static VALIDATED_PROJECTS: LazyLock<Mutex<HashMap<PathBuf, u64>>> = LazyLock::new(|| Mutex::new(HashMap::new()));

/// Rule MD074: MkDocs nav validation
///
/// Validates that MkDocs nav entries in mkdocs.yml point to existing files.
/// Only active when the markdown flavor is set to "mkdocs".
#[derive(Debug, Clone)]
pub struct MD074MkDocsNav {
    config: MD074Config,
}

impl Default for MD074MkDocsNav {
    fn default() -> Self {
        Self::new()
    }
}

impl MD074MkDocsNav {
    pub fn new() -> Self {
        Self {
            config: MD074Config::default(),
        }
    }

    pub fn from_config_struct(config: MD074Config) -> Self {
        Self { config }
    }

    /// Clear the validation cache.
    #[cfg(test)]
    pub fn clear_cache() {
        if let Ok(mut cache) = VALIDATED_PROJECTS.lock() {
            cache.clear();
        }
    }

    /// Parse mkdocs.yml and extract configuration (reads from disk).
    /// Used by tests that need to parse without going through `check()`.
    #[cfg(test)]
    fn parse_mkdocs_yml(path: &Path) -> Result<MkDocsConfig, String> {
        let content = std::fs::read_to_string(path).map_err(|e| format!("Failed to read {}: {e}", path.display()))?;
        Self::parse_mkdocs_yml_from_str(&content, path)
    }

    /// Parse mkdocs.yml from already-read content
    fn parse_mkdocs_yml_from_str(content: &str, path: &Path) -> Result<MkDocsConfig, String> {
        serde_yml::from_str(content).map_err(|e| format!("Failed to parse {}: {e}", path.display()))
    }

    /// Recursively extract all file paths from nav structure
    /// Returns tuples of (file_path, nav_location_description)
    fn extract_nav_paths(nav: &[NavItem], prefix: &str) -> Vec<(String, String)> {
        let mut paths = Vec::new();

        for item in nav {
            match item {
                NavItem::Path(path) => {
                    let nav_path = if prefix.is_empty() {
                        path.clone()
                    } else {
                        format!("{prefix} > {path}")
                    };
                    paths.push((path.clone(), nav_path));
                }
                NavItem::Section { name, children } => {
                    let new_prefix = if prefix.is_empty() {
                        name.clone()
                    } else {
                        format!("{prefix} > {name}")
                    };
                    paths.extend(Self::extract_nav_paths(children, &new_prefix));
                }
                NavItem::NamedPath { name, path } => {
                    let nav_path = if prefix.is_empty() {
                        name.clone()
                    } else {
                        format!("{prefix} > {name}")
                    };
                    paths.push((path.clone(), nav_path));
                }
            }
        }

        paths
    }

    /// Collect all markdown files in docs_dir recursively
    fn collect_docs_files(docs_dir: &Path) -> HashSet<PathBuf> {
        Self::collect_docs_files_recursive(docs_dir, docs_dir)
    }

    /// Recursive helper that preserves the original docs_dir for relative path calculation
    fn collect_docs_files_recursive(current_dir: &Path, root_docs_dir: &Path) -> HashSet<PathBuf> {
        let mut files = HashSet::new();

        let entries = match std::fs::read_dir(current_dir) {
            Ok(entries) => entries,
            Err(_) => return files,
        };

        for entry in entries.flatten() {
            let path = entry.path();

            // Skip hidden directories and files
            if path.file_name().is_some_and(|n| n.to_string_lossy().starts_with('.')) {
                continue;
            }

            if path.is_dir() {
                files.extend(Self::collect_docs_files_recursive(&path, root_docs_dir));
            } else if path.is_file()
                && let Some(ext) = path.extension()
            {
                let ext_lower = ext.to_string_lossy().to_lowercase();
                if ext_lower == "md" || ext_lower == "markdown" {
                    // Get path relative to docs_dir, normalized with forward slashes
                    if let Ok(relative) = path.strip_prefix(root_docs_dir) {
                        let normalized = Self::normalize_path(relative);
                        files.insert(normalized);
                    }
                }
            }
        }

        files
    }

    /// Normalize a path to use forward slashes (for cross-platform consistency)
    fn normalize_path(path: &Path) -> PathBuf {
        let path_str = path.to_string_lossy();
        PathBuf::from(path_str.replace('\\', "/"))
    }

    /// Normalize a nav path string for comparison
    fn normalize_nav_path(path: &str) -> PathBuf {
        PathBuf::from(path.replace('\\', "/"))
    }

    /// Check if a path looks like an external URL
    fn is_external_url(path: &str) -> bool {
        path.starts_with("http://") || path.starts_with("https://") || path.starts_with("//") || path.contains("://")
    }

    /// Check if a path is absolute (starts with /)
    fn is_absolute_path(path: &str) -> bool {
        path.starts_with('/')
    }

    /// Find the 1-indexed line number in the raw YAML content where a nav path appears.
    /// Checks for the path as a YAML value (after `:` or `- `), not just substring.
    /// Returns None if not found.
    /// Strip surrounding YAML quotes (single or double) from a value
    fn strip_yaml_quotes(s: &str) -> &str {
        if (s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')) {
            &s[1..s.len() - 1]
        } else {
            s
        }
    }

    fn find_nav_line_in_yaml(yaml_content: &str, file_path: &str) -> Option<usize> {
        for (idx, line) in yaml_content.lines().enumerate() {
            let trimmed = line.trim();
            // Skip comments
            if trimmed.starts_with('#') {
                continue;
            }
            // Match "- path.md" or "- 'path.md'" (bare list item)
            if let Some(rest) = trimmed.strip_prefix("- ")
                && Self::strip_yaml_quotes(rest.trim()) == file_path
            {
                return Some(idx + 1);
            }
            // Match "Title: path.md" or "- Title: 'path.md'" (named nav entry)
            if let Some(colon_pos) = trimmed.find(": ") {
                let value = trimmed[colon_pos + 2..].trim();
                if Self::strip_yaml_quotes(value) == file_path {
                    return Some(idx + 1);
                }
            }
        }
        None
    }

    /// Perform the actual validation of mkdocs.yml nav entries
    fn validate_nav(&self, mkdocs_path: &Path, mkdocs_config: &MkDocsConfig, yaml_content: &str) -> Vec<LintWarning> {
        let mut warnings = Vec::new();
        let mkdocs_file = mkdocs_path
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_else(|| "mkdocs.yml".to_string());

        // Get docs_dir relative to mkdocs.yml location
        let mkdocs_dir = mkdocs_path.parent().unwrap_or(Path::new("."));
        let docs_dir = if Path::new(&mkdocs_config.docs_dir).is_absolute() {
            PathBuf::from(&mkdocs_config.docs_dir)
        } else {
            mkdocs_dir.join(&mkdocs_config.docs_dir)
        };

        if !docs_dir.exists() {
            let yaml_line = Self::find_nav_line_in_yaml(yaml_content, &mkdocs_config.docs_dir);
            let line_info = yaml_line.map_or(String::new(), |l| format!(" (line {l})"));
            warnings.push(LintWarning {
                rule_name: Some(self.name().to_string()),
                line: 1,
                column: 1,
                end_line: 1,
                end_column: 1,
                message: format!(
                    "docs_dir '{}' does not exist (from {}{})",
                    mkdocs_config.docs_dir,
                    mkdocs_path.display(),
                    line_info,
                ),
                severity: Severity::Warning,
                fix: None,
            });
            return warnings;
        }

        // Extract all nav paths
        let nav_paths = Self::extract_nav_paths(&mkdocs_config.nav, "");

        // Track referenced files for omitted_files check (normalized paths)
        let mut referenced_files: HashSet<PathBuf> = HashSet::new();

        // Validate each nav entry
        for (file_path, nav_location) in &nav_paths {
            // Skip external URLs
            if Self::is_external_url(file_path) {
                continue;
            }

            // Check for absolute links
            if Self::is_absolute_path(file_path) {
                if self.config.absolute_links == NavValidation::Warn {
                    let yaml_line = Self::find_nav_line_in_yaml(yaml_content, file_path);
                    let line_info = yaml_line.map_or(String::new(), |l| format!(", line {l}"));
                    warnings.push(LintWarning {
                        rule_name: Some(self.name().to_string()),
                        line: 1,
                        column: 1,
                        end_line: 1,
                        end_column: 1,
                        message: format!(
                            "Absolute path in nav '{nav_location}': {file_path} (in {mkdocs_file}{line_info})"
                        ),
                        severity: Severity::Warning,
                        fix: None,
                    });
                }
                continue;
            }

            let normalized_path = Self::normalize_nav_path(file_path);

            // Check if file exists
            if self.config.not_found == NavValidation::Warn {
                let full_path = docs_dir.join(&normalized_path);

                // Handle directory entries (e.g., "api/" -> "api/index.md")
                let (actual_path, is_dir_entry) = if file_path.ends_with('/') || full_path.is_dir() {
                    let index_path = normalized_path.join("index.md");
                    (docs_dir.join(&index_path), true)
                } else {
                    (full_path, false)
                };

                // Track the actual file that would be served
                if is_dir_entry {
                    referenced_files.insert(normalized_path.join("index.md"));
                } else {
                    referenced_files.insert(normalized_path.clone());
                }

                if !actual_path.exists() {
                    let display_path = if is_dir_entry {
                        format!(
                            "{} (resolves to {}/index.md)",
                            file_path,
                            file_path.trim_end_matches('/')
                        )
                    } else {
                        file_path.to_string()
                    };
                    let yaml_line = Self::find_nav_line_in_yaml(yaml_content, file_path);
                    let line_info = yaml_line.map_or(String::new(), |l| format!(", line {l}"));
                    warnings.push(LintWarning {
                        rule_name: Some(self.name().to_string()),
                        line: 1,
                        column: 1,
                        end_line: 1,
                        end_column: 1,
                        message: format!(
                            "Nav entry '{nav_location}' points to non-existent file: {display_path} (in {mkdocs_file}{line_info})"
                        ),
                        severity: Severity::Warning,
                        fix: None,
                    });
                }
            } else {
                // Still track referenced files even if not validating
                if file_path.ends_with('/') {
                    referenced_files.insert(normalized_path.join("index.md"));
                } else {
                    referenced_files.insert(normalized_path);
                }
            }
        }

        // Check for omitted files
        if self.config.omitted_files == NavValidation::Warn {
            let all_docs = Self::collect_docs_files(&docs_dir);

            for doc_file in all_docs {
                if !referenced_files.contains(&doc_file) {
                    // Skip common files that are often intentionally not in nav
                    let file_name = doc_file.file_name().map(|n| n.to_string_lossy());
                    if let Some(name) = &file_name {
                        let name_lower = name.to_lowercase();
                        // Skip index files in root, README files, and other common non-nav files
                        if (doc_file.parent().is_none() || doc_file.parent() == Some(Path::new("")))
                            && (name_lower == "index.md" || name_lower == "readme.md")
                        {
                            continue;
                        }
                    }

                    warnings.push(LintWarning {
                        rule_name: Some(self.name().to_string()),
                        line: 1,
                        column: 1,
                        end_line: 1,
                        end_column: 1,
                        message: format!("File not referenced in nav: {} (in {mkdocs_file})", doc_file.display()),
                        severity: Severity::Info,
                        fix: None,
                    });
                }
            }
        }

        warnings
    }
}

/// MkDocs configuration structure (partial - only fields we need for validation)
#[derive(Debug)]
struct MkDocsConfig {
    /// Documentation directory (default: "docs")
    docs_dir: String,

    /// Navigation structure
    nav: Vec<NavItem>,
}

fn default_docs_dir() -> String {
    "docs".to_string()
}

/// Navigation item in mkdocs.yml
/// MkDocs nav can be:
/// - A simple string: "index.md"
/// - A named path: { "Home": "index.md" }
/// - A section with children: { "Section": [...] }
#[derive(Debug)]
enum NavItem {
    /// Simple path: "index.md"
    Path(String),

    /// Section with children: { "Section Name": [...] }
    Section { name: String, children: Vec<NavItem> },

    /// Named path: { "Page Title": "path/to/page.md" }
    NamedPath { name: String, path: String },
}

impl NavItem {
    /// Parse a NavItem from a serde_yml::Value
    fn from_yaml_value(value: &serde_yml::Value) -> Option<NavItem> {
        match value {
            serde_yml::Value::String(s) => Some(NavItem::Path(s.clone())),
            serde_yml::Value::Mapping(map) => {
                if map.len() != 1 {
                    return None;
                }

                let (key, val) = map.iter().next()?;
                let name = key.as_str()?.to_string();

                match val {
                    serde_yml::Value::String(path) => Some(NavItem::NamedPath {
                        name,
                        path: path.clone(),
                    }),
                    serde_yml::Value::Sequence(seq) => {
                        let children: Vec<NavItem> = seq.iter().filter_map(NavItem::from_yaml_value).collect();
                        Some(NavItem::Section { name, children })
                    }
                    serde_yml::Value::Null => {
                        // Handle case like "- Section:" with no value (treated as empty section)
                        Some(NavItem::Section {
                            name,
                            children: Vec::new(),
                        })
                    }
                    _ => None,
                }
            }
            _ => None,
        }
    }
}

impl<'de> Deserialize<'de> for MkDocsConfig {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::de::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct RawMkDocsConfig {
            #[serde(default = "default_docs_dir")]
            docs_dir: String,
            #[serde(default)]
            nav: Option<serde_yml::Value>,
        }

        let raw = RawMkDocsConfig::deserialize(deserializer)?;

        let nav = match raw.nav {
            Some(serde_yml::Value::Sequence(seq)) => seq.iter().filter_map(NavItem::from_yaml_value).collect(),
            _ => Vec::new(),
        };

        Ok(MkDocsConfig {
            docs_dir: raw.docs_dir,
            nav,
        })
    }
}

impl Rule for MD074MkDocsNav {
    fn name(&self) -> &'static str {
        "MD074"
    }

    fn description(&self) -> &'static str {
        "MkDocs nav entries should point to existing files"
    }

    fn category(&self) -> RuleCategory {
        RuleCategory::Other
    }

    fn fix_capability(&self) -> FixCapability {
        FixCapability::Unfixable
    }

    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
        // Only run for MkDocs flavor
        ctx.flavor != crate::config::MarkdownFlavor::MkDocs
    }

    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
        // Only run for MkDocs flavor
        if ctx.flavor != crate::config::MarkdownFlavor::MkDocs {
            return Ok(Vec::new());
        }

        // Need source file path to find mkdocs.yml
        let Some(source_file) = &ctx.source_file else {
            return Ok(Vec::new());
        };

        // Find mkdocs.yml (returns canonicalized path for consistent caching)
        let Some(mkdocs_path) = find_mkdocs_yml(source_file) else {
            return Ok(Vec::new());
        };

        // Read mkdocs.yml content and compute hash for cache invalidation
        let mkdocs_content = match std::fs::read_to_string(&mkdocs_path) {
            Ok(content) => content,
            Err(e) => {
                return Ok(vec![LintWarning {
                    rule_name: Some(self.name().to_string()),
                    line: 1,
                    column: 1,
                    end_line: 1,
                    end_column: 1,
                    message: format!("Failed to read {}: {e}", mkdocs_path.display()),
                    severity: Severity::Warning,
                    fix: None,
                }]);
            }
        };

        let mut hasher = DefaultHasher::new();
        mkdocs_content.hash(&mut hasher);
        let content_hash = hasher.finish();

        // Check if we've already validated this exact version of mkdocs.yml
        if let Ok(mut cache) = VALIDATED_PROJECTS.lock() {
            if let Some(&cached_hash) = cache.get(&mkdocs_path)
                && cached_hash == content_hash
            {
                return Ok(Vec::new());
            }
            cache.insert(mkdocs_path.clone(), content_hash);
        }
        // If lock is poisoned, continue with validation (just without caching)

        // Parse mkdocs.yml from already-read content
        let mkdocs_config = match Self::parse_mkdocs_yml_from_str(&mkdocs_content, &mkdocs_path) {
            Ok(config) => config,
            Err(e) => {
                return Ok(vec![LintWarning {
                    rule_name: Some(self.name().to_string()),
                    line: 1,
                    column: 1,
                    end_line: 1,
                    end_column: 1,
                    message: e,
                    severity: Severity::Warning,
                    fix: None,
                }]);
            }
        };

        // Perform validation
        Ok(self.validate_nav(&mkdocs_path, &mkdocs_config, &mkdocs_content))
    }

    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
        // This rule doesn't provide automatic fixes
        Ok(ctx.content.to_string())
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn default_config_section(&self) -> Option<(String, toml::Value)> {
        let default_config = MD074Config::default();
        let json_value = serde_json::to_value(&default_config).ok()?;
        let toml_value = crate::rule_config_serde::json_to_toml_value(&json_value)?;

        if let toml::Value::Table(table) = toml_value {
            if !table.is_empty() {
                Some((MD074Config::RULE_NAME.to_string(), toml::Value::Table(table)))
            } else {
                None
            }
        } else {
            None
        }
    }

    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
    where
        Self: Sized,
    {
        let rule_config = crate::rule_config_serde::load_rule_config::<MD074Config>(config);
        Box::new(Self::from_config_struct(rule_config))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    fn setup_test() {
        MD074MkDocsNav::clear_cache();
    }

    #[test]
    fn test_find_mkdocs_yml() {
        setup_test();
        let temp_dir = tempdir().unwrap();
        let mkdocs_path = temp_dir.path().join("mkdocs.yml");
        fs::write(&mkdocs_path, "site_name: Test").unwrap();

        let subdir = temp_dir.path().join("docs");
        fs::create_dir_all(&subdir).unwrap();
        let file_in_subdir = subdir.join("test.md");

        let found = find_mkdocs_yml(&file_in_subdir);
        assert!(found.is_some());
        // Canonicalized paths should match
        assert_eq!(found.unwrap(), mkdocs_path.canonicalize().unwrap());
    }

    #[test]
    fn test_find_mkdocs_yaml_extension() {
        setup_test();
        let temp_dir = tempdir().unwrap();
        let mkdocs_path = temp_dir.path().join("mkdocs.yaml"); // .yaml extension
        fs::write(&mkdocs_path, "site_name: Test").unwrap();

        let docs_dir = temp_dir.path().join("docs");
        fs::create_dir_all(&docs_dir).unwrap();
        let file_in_docs = docs_dir.join("test.md");

        let found = find_mkdocs_yml(&file_in_docs);
        assert!(found.is_some(), "Should find mkdocs.yaml");
        assert_eq!(found.unwrap(), mkdocs_path.canonicalize().unwrap());
    }

    #[test]
    fn test_parse_simple_nav() {
        setup_test();
        let temp_dir = tempdir().unwrap();
        let mkdocs_path = temp_dir.path().join("mkdocs.yml");

        let mkdocs_content = r#"
site_name: Test
docs_dir: docs
nav:
  - Home: index.md
  - Guide: guide.md
  - Section:
    - Page 1: section/page1.md
    - Page 2: section/page2.md
"#;
        fs::write(&mkdocs_path, mkdocs_content).unwrap();

        let config = MD074MkDocsNav::parse_mkdocs_yml(&mkdocs_path).unwrap();
        assert_eq!(config.docs_dir, "docs");
        assert_eq!(config.nav.len(), 3);

        let paths = MD074MkDocsNav::extract_nav_paths(&config.nav, "");
        assert_eq!(paths.len(), 4);

        // Check paths are extracted correctly
        let path_strs: Vec<&str> = paths.iter().map(|(p, _)| p.as_str()).collect();
        assert!(path_strs.contains(&"index.md"));
        assert!(path_strs.contains(&"guide.md"));
        assert!(path_strs.contains(&"section/page1.md"));
        assert!(path_strs.contains(&"section/page2.md"));
    }

    #[test]
    fn test_parse_deeply_nested_nav() {
        setup_test();
        let temp_dir = tempdir().unwrap();
        let mkdocs_path = temp_dir.path().join("mkdocs.yml");

        let mkdocs_content = r#"
site_name: Test
nav:
  - Level 1:
    - Level 2:
      - Level 3:
        - Deep Page: deep/nested/page.md
"#;
        fs::write(&mkdocs_path, mkdocs_content).unwrap();

        let config = MD074MkDocsNav::parse_mkdocs_yml(&mkdocs_path).unwrap();
        let paths = MD074MkDocsNav::extract_nav_paths(&config.nav, "");

        assert_eq!(paths.len(), 1);
        assert_eq!(paths[0].0, "deep/nested/page.md");
        assert!(paths[0].1.contains("Level 1"));
        assert!(paths[0].1.contains("Level 2"));
        assert!(paths[0].1.contains("Level 3"));
    }

    #[test]
    fn test_parse_nav_with_external_urls() {
        setup_test();
        let temp_dir = tempdir().unwrap();
        let mkdocs_path = temp_dir.path().join("mkdocs.yml");

        let mkdocs_content = r#"
site_name: Test
docs_dir: docs
nav:
  - Home: index.md
  - GitHub: https://github.com/example/repo
  - External: http://example.com
  - Protocol Relative: //example.com/path
"#;
        fs::write(&mkdocs_path, mkdocs_content).unwrap();

        let config = MD074MkDocsNav::parse_mkdocs_yml(&mkdocs_path).unwrap();
        let paths = MD074MkDocsNav::extract_nav_paths(&config.nav, "");

        // All 4 entries are extracted
        assert_eq!(paths.len(), 4);

        // Verify external URL detection
        assert!(!MD074MkDocsNav::is_external_url("index.md"));
        assert!(MD074MkDocsNav::is_external_url("https://github.com/example/repo"));
        assert!(MD074MkDocsNav::is_external_url("http://example.com"));
        assert!(MD074MkDocsNav::is_external_url("//example.com/path"));
    }

    #[test]
    fn test_parse_nav_with_empty_section() {
        setup_test();
        let temp_dir = tempdir().unwrap();
        let mkdocs_path = temp_dir.path().join("mkdocs.yml");

        // Empty section (null value)
        let mkdocs_content = r#"
site_name: Test
nav:
  - Empty Section:
  - Home: index.md
"#;
        fs::write(&mkdocs_path, mkdocs_content).unwrap();

        let result = MD074MkDocsNav::parse_mkdocs_yml(&mkdocs_path);
        assert!(result.is_ok(), "Should handle empty sections");
    }

    #[test]
    fn test_nav_not_found_validation() {
        setup_test();
        let temp_dir = tempdir().unwrap();

        // Create mkdocs.yml
        let mkdocs_content = r#"
site_name: Test
docs_dir: docs
nav:
  - Home: index.md
  - Missing: missing.md
"#;
        fs::write(temp_dir.path().join("mkdocs.yml"), mkdocs_content).unwrap();

        // Create docs directory with only index.md
        let docs_dir = temp_dir.path().join("docs");
        fs::create_dir_all(&docs_dir).unwrap();
        fs::write(docs_dir.join("index.md"), "# Home").unwrap();

        // Create a test markdown file
        let test_file = docs_dir.join("test.md");
        fs::write(&test_file, "# Test").unwrap();

        let rule = MD074MkDocsNav::new();
        let ctx =
            crate::lint_context::LintContext::new("# Test", crate::config::MarkdownFlavor::MkDocs, Some(test_file));

        let result = rule.check(&ctx).unwrap();

        // Should have 1 warning for missing.md
        assert_eq!(result.len(), 1, "Should warn about missing nav entry. Got: {result:?}");
        assert!(result[0].message.contains("missing.md"));
    }

    #[test]
    fn test_absolute_links_validation() {
        setup_test();
        let temp_dir = tempdir().unwrap();

        let mkdocs_content = r#"
site_name: Test
docs_dir: docs
nav:
  - Absolute: /absolute/path.md
"#;
        fs::write(temp_dir.path().join("mkdocs.yml"), mkdocs_content).unwrap();

        let docs_dir = temp_dir.path().join("docs");
        fs::create_dir_all(&docs_dir).unwrap();
        let test_file = docs_dir.join("test.md");
        fs::write(&test_file, "# Test").unwrap();

        let config = MD074Config {
            not_found: NavValidation::Ignore,
            omitted_files: NavValidation::Ignore,
            absolute_links: NavValidation::Warn,
        };
        let rule = MD074MkDocsNav::from_config_struct(config);

        let ctx =
            crate::lint_context::LintContext::new("# Test", crate::config::MarkdownFlavor::MkDocs, Some(test_file));

        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 1, "Should warn about absolute path. Got: {result:?}");
        assert!(result[0].message.contains("Absolute path"));
    }

    #[test]
    fn test_omitted_files_validation() {
        setup_test();
        let temp_dir = tempdir().unwrap();

        let mkdocs_content = r#"
site_name: Test
docs_dir: docs
nav:
  - Home: index.md
"#;
        fs::write(temp_dir.path().join("mkdocs.yml"), mkdocs_content).unwrap();

        let docs_dir = temp_dir.path().join("docs");
        fs::create_dir_all(&docs_dir).unwrap();
        fs::write(docs_dir.join("index.md"), "# Home").unwrap();
        fs::write(docs_dir.join("unlisted.md"), "# Unlisted").unwrap();

        // Create subdirectory with file
        let subdir = docs_dir.join("subdir");
        fs::create_dir_all(&subdir).unwrap();
        fs::write(subdir.join("nested.md"), "# Nested").unwrap();

        let test_file = docs_dir.join("test.md");
        fs::write(&test_file, "# Test").unwrap();

        let config = MD074Config {
            not_found: NavValidation::Ignore,
            omitted_files: NavValidation::Warn,
            absolute_links: NavValidation::Ignore,
        };
        let rule = MD074MkDocsNav::from_config_struct(config);

        let ctx =
            crate::lint_context::LintContext::new("# Test", crate::config::MarkdownFlavor::MkDocs, Some(test_file));

        let result = rule.check(&ctx).unwrap();

        // Should warn about unlisted.md, test.md, and subdir/nested.md
        // (index.md in root is skipped)
        assert!(result.len() >= 2, "Should warn about omitted files. Got: {result:?}");

        let messages: Vec<&str> = result.iter().map(|w| w.message.as_str()).collect();
        assert!(
            messages.iter().any(|m| m.contains("unlisted.md")),
            "Should mention unlisted.md"
        );
    }

    #[test]
    fn test_omitted_files_with_subdirectories() {
        setup_test();
        let temp_dir = tempdir().unwrap();

        let mkdocs_content = r#"
site_name: Test
docs_dir: docs
nav:
  - Home: index.md
  - API:
    - Overview: api/overview.md
"#;
        fs::write(temp_dir.path().join("mkdocs.yml"), mkdocs_content).unwrap();

        let docs_dir = temp_dir.path().join("docs");
        fs::create_dir_all(&docs_dir).unwrap();
        fs::write(docs_dir.join("index.md"), "# Home").unwrap();

        let api_dir = docs_dir.join("api");
        fs::create_dir_all(&api_dir).unwrap();
        fs::write(api_dir.join("overview.md"), "# Overview").unwrap();
        fs::write(api_dir.join("unlisted.md"), "# Unlisted API").unwrap();

        let test_file = docs_dir.join("index.md");

        let config = MD074Config {
            not_found: NavValidation::Warn,
            omitted_files: NavValidation::Warn,
            absolute_links: NavValidation::Ignore,
        };
        let rule = MD074MkDocsNav::from_config_struct(config);

        let ctx =
            crate::lint_context::LintContext::new("# Home", crate::config::MarkdownFlavor::MkDocs, Some(test_file));

        let result = rule.check(&ctx).unwrap();

        // Should only warn about api/unlisted.md, not api/overview.md
        let messages: Vec<&str> = result.iter().map(|w| w.message.as_str()).collect();

        // api/overview.md should NOT be reported (it's in nav)
        assert!(
            !messages.iter().any(|m| m.contains("overview.md")),
            "Should NOT warn about api/overview.md (it's in nav). Got: {messages:?}"
        );

        // api/unlisted.md SHOULD be reported
        assert!(
            messages.iter().any(|m| m.contains("unlisted.md")),
            "Should warn about api/unlisted.md. Got: {messages:?}"
        );
    }

    #[test]
    fn test_skips_non_mkdocs_flavor() {
        setup_test();
        let rule = MD074MkDocsNav::new();
        let ctx = crate::lint_context::LintContext::new("# Test", crate::config::MarkdownFlavor::Standard, None);

        let result = rule.check(&ctx).unwrap();
        assert!(result.is_empty(), "Should skip non-MkDocs flavor");
    }

    #[test]
    fn test_skips_external_urls_in_validation() {
        setup_test();
        let temp_dir = tempdir().unwrap();

        let mkdocs_content = r#"
site_name: Test
docs_dir: docs
nav:
  - Home: index.md
  - GitHub: https://github.com/example
  - Docs: http://docs.example.com
"#;
        fs::write(temp_dir.path().join("mkdocs.yml"), mkdocs_content).unwrap();

        let docs_dir = temp_dir.path().join("docs");
        fs::create_dir_all(&docs_dir).unwrap();
        fs::write(docs_dir.join("index.md"), "# Home").unwrap();

        let test_file = docs_dir.join("index.md");

        let rule = MD074MkDocsNav::new();
        let ctx =
            crate::lint_context::LintContext::new("# Home", crate::config::MarkdownFlavor::MkDocs, Some(test_file));

        let result = rule.check(&ctx).unwrap();

        // Should NOT warn about external URLs as missing files
        assert!(
            result.is_empty(),
            "Should not warn about external URLs. Got: {result:?}"
        );
    }

    #[test]
    fn test_cache_prevents_duplicate_validation() {
        setup_test();
        let temp_dir = tempdir().unwrap();

        let mkdocs_content = r#"
site_name: Test
docs_dir: docs
nav:
  - Home: index.md
  - Missing: missing.md
"#;
        fs::write(temp_dir.path().join("mkdocs.yml"), mkdocs_content).unwrap();

        let docs_dir = temp_dir.path().join("docs");
        fs::create_dir_all(&docs_dir).unwrap();
        fs::write(docs_dir.join("index.md"), "# Home").unwrap();
        fs::write(docs_dir.join("other.md"), "# Other").unwrap();

        let rule = MD074MkDocsNav::new();

        // First file check
        let ctx1 = crate::lint_context::LintContext::new(
            "# Home",
            crate::config::MarkdownFlavor::MkDocs,
            Some(docs_dir.join("index.md")),
        );
        let result1 = rule.check(&ctx1).unwrap();
        assert_eq!(result1.len(), 1, "First check should return warnings");

        // Second file check - same project
        let ctx2 = crate::lint_context::LintContext::new(
            "# Other",
            crate::config::MarkdownFlavor::MkDocs,
            Some(docs_dir.join("other.md")),
        );
        let result2 = rule.check(&ctx2).unwrap();
        assert!(result2.is_empty(), "Second check should return no warnings (cached)");
    }

    #[test]
    fn test_cache_invalidates_when_content_changes() {
        setup_test();
        let temp_dir = tempdir().unwrap();

        let mkdocs_content_v1 = r#"
site_name: Test
docs_dir: docs
nav:
  - Home: index.md
"#;
        fs::write(temp_dir.path().join("mkdocs.yml"), mkdocs_content_v1).unwrap();

        let docs_dir = temp_dir.path().join("docs");
        fs::create_dir_all(&docs_dir).unwrap();
        fs::write(docs_dir.join("index.md"), "# Home").unwrap();

        let rule = MD074MkDocsNav::new();

        // First check - valid config, no warnings
        let ctx1 = crate::lint_context::LintContext::new(
            "# Home",
            crate::config::MarkdownFlavor::MkDocs,
            Some(docs_dir.join("index.md")),
        );
        let result1 = rule.check(&ctx1).unwrap();
        assert!(
            result1.is_empty(),
            "First check: valid config should produce no warnings"
        );

        // Now modify mkdocs.yml to add a missing file reference
        let mkdocs_content_v2 = r#"
site_name: Test
docs_dir: docs
nav:
  - Home: index.md
  - Missing: missing.md
"#;
        fs::write(temp_dir.path().join("mkdocs.yml"), mkdocs_content_v2).unwrap();

        // Second check - content changed, cache should invalidate
        let ctx2 = crate::lint_context::LintContext::new(
            "# Home",
            crate::config::MarkdownFlavor::MkDocs,
            Some(docs_dir.join("index.md")),
        );
        let result2 = rule.check(&ctx2).unwrap();
        assert_eq!(
            result2.len(),
            1,
            "Second check: changed mkdocs.yml should re-validate and find missing.md"
        );
        assert!(result2[0].message.contains("missing.md"));
    }

    #[test]
    fn test_invalid_mkdocs_yml_returns_warning() {
        setup_test();
        let temp_dir = tempdir().unwrap();

        // Invalid YAML
        let mkdocs_content = "site_name: Test\nnav: [[[invalid yaml";
        fs::write(temp_dir.path().join("mkdocs.yml"), mkdocs_content).unwrap();

        let docs_dir = temp_dir.path().join("docs");
        fs::create_dir_all(&docs_dir).unwrap();
        let test_file = docs_dir.join("test.md");
        fs::write(&test_file, "# Test").unwrap();

        let rule = MD074MkDocsNav::new();
        let ctx =
            crate::lint_context::LintContext::new("# Test", crate::config::MarkdownFlavor::MkDocs, Some(test_file));

        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 1, "Should return parse error warning");
        assert!(
            result[0].message.contains("Failed to parse"),
            "Should mention parse failure"
        );
    }

    #[test]
    fn test_missing_docs_dir_returns_warning() {
        setup_test();
        let temp_dir = tempdir().unwrap();

        let mkdocs_content = r#"
site_name: Test
docs_dir: nonexistent
nav:
  - Home: index.md
"#;
        fs::write(temp_dir.path().join("mkdocs.yml"), mkdocs_content).unwrap();

        // Create a file but not in the docs_dir
        let other_dir = temp_dir.path().join("other");
        fs::create_dir_all(&other_dir).unwrap();
        let test_file = other_dir.join("test.md");
        fs::write(&test_file, "# Test").unwrap();

        let rule = MD074MkDocsNav::new();
        let ctx =
            crate::lint_context::LintContext::new("# Test", crate::config::MarkdownFlavor::MkDocs, Some(test_file));

        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 1, "Should warn about missing docs_dir");
        assert!(
            result[0].message.contains("does not exist"),
            "Should mention docs_dir doesn't exist"
        );
    }

    #[test]
    fn test_default_docs_dir() {
        setup_test();
        let temp_dir = tempdir().unwrap();

        // mkdocs.yml without docs_dir specified - should default to "docs"
        let mkdocs_content = r#"
site_name: Test
nav:
  - Home: index.md
"#;
        fs::write(temp_dir.path().join("mkdocs.yml"), mkdocs_content).unwrap();

        let config = MD074MkDocsNav::parse_mkdocs_yml(&temp_dir.path().join("mkdocs.yml")).unwrap();
        assert_eq!(config.docs_dir, "docs", "Should default to 'docs'");
    }

    #[test]
    fn test_path_normalization() {
        // Test that paths are normalized consistently
        let path1 = MD074MkDocsNav::normalize_path(Path::new("api/overview.md"));
        let path2 = MD074MkDocsNav::normalize_nav_path("api/overview.md");
        assert_eq!(path1, path2);

        // Windows-style paths should be normalized
        let win_path = MD074MkDocsNav::normalize_nav_path("api\\overview.md");
        assert_eq!(win_path, PathBuf::from("api/overview.md"));
    }

    #[test]
    fn test_skips_hidden_files_and_directories() {
        setup_test();
        let temp_dir = tempdir().unwrap();

        let mkdocs_content = r#"
site_name: Test
docs_dir: docs
nav:
  - Home: index.md
"#;
        fs::write(temp_dir.path().join("mkdocs.yml"), mkdocs_content).unwrap();

        let docs_dir = temp_dir.path().join("docs");
        fs::create_dir_all(&docs_dir).unwrap();
        fs::write(docs_dir.join("index.md"), "# Home").unwrap();

        // Create hidden file and directory
        fs::write(docs_dir.join(".hidden.md"), "# Hidden").unwrap();
        let hidden_dir = docs_dir.join(".hidden_dir");
        fs::create_dir_all(&hidden_dir).unwrap();
        fs::write(hidden_dir.join("secret.md"), "# Secret").unwrap();

        let collected = MD074MkDocsNav::collect_docs_files(&docs_dir);

        assert_eq!(collected.len(), 1, "Should only find index.md");
        assert!(
            !collected.iter().any(|p| p.to_string_lossy().contains("hidden")),
            "Should not include hidden files"
        );
    }

    #[test]
    fn test_is_external_url() {
        assert!(MD074MkDocsNav::is_external_url("https://example.com"));
        assert!(MD074MkDocsNav::is_external_url("http://example.com"));
        assert!(MD074MkDocsNav::is_external_url("//example.com"));
        assert!(MD074MkDocsNav::is_external_url("ftp://files.example.com"));
        assert!(!MD074MkDocsNav::is_external_url("index.md"));
        assert!(!MD074MkDocsNav::is_external_url("path/to/file.md"));
        assert!(!MD074MkDocsNav::is_external_url("/absolute/path.md"));
    }

    #[test]
    fn test_is_absolute_path() {
        assert!(MD074MkDocsNav::is_absolute_path("/absolute/path.md"));
        assert!(MD074MkDocsNav::is_absolute_path("/index.md"));
        assert!(!MD074MkDocsNav::is_absolute_path("relative/path.md"));
        assert!(!MD074MkDocsNav::is_absolute_path("index.md"));
        assert!(!MD074MkDocsNav::is_absolute_path("https://example.com"));
    }

    #[test]
    fn test_directory_nav_entries() {
        setup_test();
        let temp_dir = tempdir().unwrap();

        // Nav with directory entry (trailing slash)
        let mkdocs_content = r#"
site_name: Test
docs_dir: docs
nav:
  - Home: index.md
  - API: api/
"#;
        fs::write(temp_dir.path().join("mkdocs.yml"), mkdocs_content).unwrap();

        let docs_dir = temp_dir.path().join("docs");
        fs::create_dir_all(&docs_dir).unwrap();
        fs::write(docs_dir.join("index.md"), "# Home").unwrap();

        // Create api directory WITHOUT index.md
        let api_dir = docs_dir.join("api");
        fs::create_dir_all(&api_dir).unwrap();

        let test_file = docs_dir.join("index.md");

        let rule = MD074MkDocsNav::new();
        let ctx =
            crate::lint_context::LintContext::new("# Home", crate::config::MarkdownFlavor::MkDocs, Some(test_file));

        let result = rule.check(&ctx).unwrap();

        // Should warn that api/index.md doesn't exist
        assert_eq!(
            result.len(),
            1,
            "Should warn about missing api/index.md. Got: {result:?}"
        );
        assert!(result[0].message.contains("api/"), "Should mention api/ in warning");
        assert!(
            result[0].message.contains("index.md"),
            "Should mention index.md in warning"
        );
    }

    #[test]
    fn test_directory_nav_entries_with_index() {
        setup_test();
        let temp_dir = tempdir().unwrap();

        // Nav with directory entry (trailing slash)
        let mkdocs_content = r#"
site_name: Test
docs_dir: docs
nav:
  - Home: index.md
  - API: api/
"#;
        fs::write(temp_dir.path().join("mkdocs.yml"), mkdocs_content).unwrap();

        let docs_dir = temp_dir.path().join("docs");
        fs::create_dir_all(&docs_dir).unwrap();
        fs::write(docs_dir.join("index.md"), "# Home").unwrap();

        // Create api directory WITH index.md
        let api_dir = docs_dir.join("api");
        fs::create_dir_all(&api_dir).unwrap();
        fs::write(api_dir.join("index.md"), "# API").unwrap();

        let test_file = docs_dir.join("index.md");

        let rule = MD074MkDocsNav::new();
        let ctx =
            crate::lint_context::LintContext::new("# Home", crate::config::MarkdownFlavor::MkDocs, Some(test_file));

        let result = rule.check(&ctx).unwrap();

        // Should not warn - api/index.md exists
        assert!(
            result.is_empty(),
            "Should not warn when api/index.md exists. Got: {result:?}"
        );
    }
}