1use crate::rule::Rule;
6use crate::rules;
7use crate::types::LineLength;
8use log;
9use serde::{Deserialize, Serialize};
10use std::collections::BTreeMap;
11use std::collections::{HashMap, HashSet};
12use std::fmt;
13use std::fs;
14use std::io;
15use std::marker::PhantomData;
16use std::path::Path;
17use std::str::FromStr;
18use toml_edit::DocumentMut;
19
20#[derive(Debug, Clone, Copy, Default)]
27pub struct ConfigLoaded;
28
29#[derive(Debug, Clone, Copy, Default)]
32pub struct ConfigValidated;
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, schemars::JsonSchema)]
36#[serde(rename_all = "lowercase")]
37pub enum MarkdownFlavor {
38 #[serde(rename = "standard", alias = "none", alias = "")]
40 #[default]
41 Standard,
42 #[serde(rename = "mkdocs")]
44 MkDocs,
45 #[serde(rename = "mdx")]
47 MDX,
48 #[serde(rename = "quarto")]
50 Quarto,
51 }
55
56impl fmt::Display for MarkdownFlavor {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 match self {
59 MarkdownFlavor::Standard => write!(f, "standard"),
60 MarkdownFlavor::MkDocs => write!(f, "mkdocs"),
61 MarkdownFlavor::MDX => write!(f, "mdx"),
62 MarkdownFlavor::Quarto => write!(f, "quarto"),
63 }
64 }
65}
66
67impl FromStr for MarkdownFlavor {
68 type Err = String;
69
70 fn from_str(s: &str) -> Result<Self, Self::Err> {
71 match s.to_lowercase().as_str() {
72 "standard" | "" | "none" => Ok(MarkdownFlavor::Standard),
73 "mkdocs" => Ok(MarkdownFlavor::MkDocs),
74 "mdx" => Ok(MarkdownFlavor::MDX),
75 "quarto" | "qmd" | "rmd" | "rmarkdown" => Ok(MarkdownFlavor::Quarto),
76 "gfm" | "github" | "commonmark" => Ok(MarkdownFlavor::Standard),
80 _ => Err(format!("Unknown markdown flavor: {s}")),
81 }
82 }
83}
84
85impl MarkdownFlavor {
86 pub fn from_extension(ext: &str) -> Self {
88 match ext.to_lowercase().as_str() {
89 "mdx" => Self::MDX,
90 "qmd" => Self::Quarto,
91 "rmd" => Self::Quarto,
92 _ => Self::Standard,
93 }
94 }
95
96 pub fn from_path(path: &std::path::Path) -> Self {
98 path.extension()
99 .and_then(|e| e.to_str())
100 .map(Self::from_extension)
101 .unwrap_or(Self::Standard)
102 }
103
104 pub fn supports_esm_blocks(self) -> bool {
106 matches!(self, Self::MDX)
107 }
108
109 pub fn supports_jsx(self) -> bool {
111 matches!(self, Self::MDX)
112 }
113
114 pub fn supports_auto_references(self) -> bool {
116 matches!(self, Self::MkDocs)
117 }
118
119 pub fn name(self) -> &'static str {
121 match self {
122 Self::Standard => "Standard",
123 Self::MkDocs => "MkDocs",
124 Self::MDX => "MDX",
125 Self::Quarto => "Quarto",
126 }
127 }
128}
129
130pub fn normalize_key(key: &str) -> String {
132 if key.len() == 5 && key.to_ascii_lowercase().starts_with("md") && key[2..].chars().all(|c| c.is_ascii_digit()) {
134 key.to_ascii_uppercase()
135 } else {
136 key.replace('_', "-").to_ascii_lowercase()
137 }
138}
139
140#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, schemars::JsonSchema)]
142pub struct RuleConfig {
143 #[serde(default, skip_serializing_if = "Option::is_none")]
145 pub severity: Option<crate::rule::Severity>,
146
147 #[serde(flatten)]
149 #[schemars(schema_with = "arbitrary_value_schema")]
150 pub values: BTreeMap<String, toml::Value>,
151}
152
153fn arbitrary_value_schema(_gen: &mut schemars::SchemaGenerator) -> schemars::Schema {
155 schemars::json_schema!({
156 "type": "object",
157 "additionalProperties": true
158 })
159}
160
161#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, schemars::JsonSchema)]
163#[schemars(
164 description = "rumdl configuration for linting Markdown files. Rules can be configured individually using [MD###] sections with rule-specific options."
165)]
166pub struct Config {
167 #[serde(default)]
169 pub global: GlobalConfig,
170
171 #[serde(default, rename = "per-file-ignores")]
174 pub per_file_ignores: HashMap<String, Vec<String>>,
175
176 #[serde(flatten)]
187 pub rules: BTreeMap<String, RuleConfig>,
188
189 #[serde(skip)]
191 pub project_root: Option<std::path::PathBuf>,
192}
193
194impl Config {
195 pub fn is_mkdocs_flavor(&self) -> bool {
197 self.global.flavor == MarkdownFlavor::MkDocs
198 }
199
200 pub fn markdown_flavor(&self) -> MarkdownFlavor {
206 self.global.flavor
207 }
208
209 pub fn is_mkdocs_project(&self) -> bool {
211 self.is_mkdocs_flavor()
212 }
213
214 pub fn get_rule_severity(&self, rule_name: &str) -> Option<crate::rule::Severity> {
216 self.rules.get(rule_name).and_then(|r| r.severity)
217 }
218
219 pub fn get_ignored_rules_for_file(&self, file_path: &Path) -> HashSet<String> {
222 use globset::{Glob, GlobSetBuilder};
223
224 let mut ignored_rules = HashSet::new();
225
226 if self.per_file_ignores.is_empty() {
227 return ignored_rules;
228 }
229
230 let path_for_matching: std::borrow::Cow<'_, Path> = if let Some(ref root) = self.project_root {
233 if let Ok(canonical_path) = file_path.canonicalize() {
234 if let Ok(canonical_root) = root.canonicalize() {
235 if let Ok(relative) = canonical_path.strip_prefix(&canonical_root) {
236 std::borrow::Cow::Owned(relative.to_path_buf())
237 } else {
238 std::borrow::Cow::Borrowed(file_path)
239 }
240 } else {
241 std::borrow::Cow::Borrowed(file_path)
242 }
243 } else {
244 std::borrow::Cow::Borrowed(file_path)
245 }
246 } else {
247 std::borrow::Cow::Borrowed(file_path)
248 };
249
250 let mut builder = GlobSetBuilder::new();
252 let mut pattern_to_rules: Vec<(usize, &Vec<String>)> = Vec::new();
253
254 for (idx, (pattern, rules)) in self.per_file_ignores.iter().enumerate() {
255 if let Ok(glob) = Glob::new(pattern) {
256 builder.add(glob);
257 pattern_to_rules.push((idx, rules));
258 } else {
259 log::warn!("Invalid glob pattern in per-file-ignores: {pattern}");
260 }
261 }
262
263 let globset = match builder.build() {
264 Ok(gs) => gs,
265 Err(e) => {
266 log::error!("Failed to build globset for per-file-ignores: {e}");
267 return ignored_rules;
268 }
269 };
270
271 for match_idx in globset.matches(path_for_matching.as_ref()) {
273 if let Some((_, rules)) = pattern_to_rules.get(match_idx) {
274 for rule in rules.iter() {
275 ignored_rules.insert(normalize_key(rule));
277 }
278 }
279 }
280
281 ignored_rules
282 }
283}
284
285#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
287#[serde(default, rename_all = "kebab-case")]
288pub struct GlobalConfig {
289 #[serde(default)]
291 pub enable: Vec<String>,
292
293 #[serde(default)]
295 pub disable: Vec<String>,
296
297 #[serde(default)]
299 pub exclude: Vec<String>,
300
301 #[serde(default)]
303 pub include: Vec<String>,
304
305 #[serde(default = "default_respect_gitignore", alias = "respect_gitignore")]
307 pub respect_gitignore: bool,
308
309 #[serde(default, alias = "line_length")]
311 pub line_length: LineLength,
312
313 #[serde(skip_serializing_if = "Option::is_none", alias = "output_format")]
315 pub output_format: Option<String>,
316
317 #[serde(default)]
320 pub fixable: Vec<String>,
321
322 #[serde(default)]
325 pub unfixable: Vec<String>,
326
327 #[serde(default)]
330 pub flavor: MarkdownFlavor,
331
332 #[serde(default, alias = "force_exclude")]
337 #[deprecated(since = "0.0.156", note = "Exclude patterns are now always respected")]
338 pub force_exclude: bool,
339
340 #[serde(default, alias = "cache_dir", skip_serializing_if = "Option::is_none")]
343 pub cache_dir: Option<String>,
344
345 #[serde(default = "default_true")]
348 pub cache: bool,
349}
350
351fn default_respect_gitignore() -> bool {
352 true
353}
354
355fn default_true() -> bool {
356 true
357}
358
359impl Default for GlobalConfig {
361 #[allow(deprecated)]
362 fn default() -> Self {
363 Self {
364 enable: Vec::new(),
365 disable: Vec::new(),
366 exclude: Vec::new(),
367 include: Vec::new(),
368 respect_gitignore: true,
369 line_length: LineLength::default(),
370 output_format: None,
371 fixable: Vec::new(),
372 unfixable: Vec::new(),
373 flavor: MarkdownFlavor::default(),
374 force_exclude: false,
375 cache_dir: None,
376 cache: true,
377 }
378 }
379}
380
381const MARKDOWNLINT_CONFIG_FILES: &[&str] = &[
382 ".markdownlint.json",
383 ".markdownlint.jsonc",
384 ".markdownlint.yaml",
385 ".markdownlint.yml",
386 "markdownlint.json",
387 "markdownlint.jsonc",
388 "markdownlint.yaml",
389 "markdownlint.yml",
390];
391
392pub fn create_default_config(path: &str) -> Result<(), ConfigError> {
394 if Path::new(path).exists() {
396 return Err(ConfigError::FileExists { path: path.to_string() });
397 }
398
399 let default_config = r#"# rumdl configuration file
401
402# Global configuration options
403[global]
404# List of rules to disable (uncomment and modify as needed)
405# disable = ["MD013", "MD033"]
406
407# List of rules to enable exclusively (if provided, only these rules will run)
408# enable = ["MD001", "MD003", "MD004"]
409
410# List of file/directory patterns to include for linting (if provided, only these will be linted)
411# include = [
412# "docs/*.md",
413# "src/**/*.md",
414# "README.md"
415# ]
416
417# List of file/directory patterns to exclude from linting
418exclude = [
419 # Common directories to exclude
420 ".git",
421 ".github",
422 "node_modules",
423 "vendor",
424 "dist",
425 "build",
426
427 # Specific files or patterns
428 "CHANGELOG.md",
429 "LICENSE.md",
430]
431
432# Respect .gitignore files when scanning directories (default: true)
433respect-gitignore = true
434
435# Markdown flavor/dialect (uncomment to enable)
436# Options: standard (default), gfm, commonmark, mkdocs, mdx, quarto
437# flavor = "mkdocs"
438
439# Rule-specific configurations (uncomment and modify as needed)
440
441# [MD003]
442# style = "atx" # Heading style (atx, atx_closed, setext)
443
444# [MD004]
445# style = "asterisk" # Unordered list style (asterisk, plus, dash, consistent)
446
447# [MD007]
448# indent = 4 # Unordered list indentation
449
450# [MD013]
451# line-length = 100 # Line length
452# code-blocks = false # Exclude code blocks from line length check
453# tables = false # Exclude tables from line length check
454# headings = true # Include headings in line length check
455
456# [MD044]
457# names = ["rumdl", "Markdown", "GitHub"] # Proper names that should be capitalized correctly
458# code-blocks = false # Check code blocks for proper names (default: false, skips code blocks)
459"#;
460
461 match fs::write(path, default_config) {
463 Ok(_) => Ok(()),
464 Err(err) => Err(ConfigError::IoError {
465 source: err,
466 path: path.to_string(),
467 }),
468 }
469}
470
471#[derive(Debug, thiserror::Error)]
473pub enum ConfigError {
474 #[error("Failed to read config file at {path}: {source}")]
476 IoError { source: io::Error, path: String },
477
478 #[error("Failed to parse config: {0}")]
480 ParseError(String),
481
482 #[error("Configuration file already exists at {path}")]
484 FileExists { path: String },
485}
486
487pub fn get_rule_config_value<T: serde::de::DeserializeOwned>(config: &Config, rule_name: &str, key: &str) -> Option<T> {
491 let norm_rule_name = rule_name.to_ascii_uppercase(); let rule_config = config.rules.get(&norm_rule_name)?;
494
495 let key_variants = [
497 key.to_string(), normalize_key(key), key.replace('-', "_"), key.replace('_', "-"), ];
502
503 for variant in &key_variants {
505 if let Some(value) = rule_config.values.get(variant)
506 && let Ok(result) = T::deserialize(value.clone())
507 {
508 return Some(result);
509 }
510 }
511
512 None
513}
514
515pub fn generate_pyproject_config() -> String {
517 let config_content = r#"
518[tool.rumdl]
519# Global configuration options
520line-length = 100
521disable = []
522exclude = [
523 # Common directories to exclude
524 ".git",
525 ".github",
526 "node_modules",
527 "vendor",
528 "dist",
529 "build",
530]
531respect-gitignore = true
532
533# Rule-specific configurations (uncomment and modify as needed)
534
535# [tool.rumdl.MD003]
536# style = "atx" # Heading style (atx, atx_closed, setext)
537
538# [tool.rumdl.MD004]
539# style = "asterisk" # Unordered list style (asterisk, plus, dash, consistent)
540
541# [tool.rumdl.MD007]
542# indent = 4 # Unordered list indentation
543
544# [tool.rumdl.MD013]
545# line-length = 100 # Line length
546# code-blocks = false # Exclude code blocks from line length check
547# tables = false # Exclude tables from line length check
548# headings = true # Include headings in line length check
549
550# [tool.rumdl.MD044]
551# names = ["rumdl", "Markdown", "GitHub"] # Proper names that should be capitalized correctly
552# code-blocks = false # Check code blocks for proper names (default: false, skips code blocks)
553"#;
554
555 config_content.to_string()
556}
557
558#[cfg(test)]
559mod tests {
560 use super::*;
561 use std::fs;
562 use tempfile::tempdir;
563
564 #[test]
565 fn test_flavor_loading() {
566 let temp_dir = tempdir().unwrap();
567 let config_path = temp_dir.path().join(".rumdl.toml");
568 let config_content = r#"
569[global]
570flavor = "mkdocs"
571disable = ["MD001"]
572"#;
573 fs::write(&config_path, config_content).unwrap();
574
575 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
577 let config: Config = sourced.into_validated_unchecked().into();
578
579 assert_eq!(config.global.flavor, MarkdownFlavor::MkDocs);
581 assert!(config.is_mkdocs_flavor());
582 assert!(config.is_mkdocs_project()); assert_eq!(config.global.disable, vec!["MD001".to_string()]);
584 }
585
586 #[test]
587 fn test_pyproject_toml_root_level_config() {
588 let temp_dir = tempdir().unwrap();
589 let config_path = temp_dir.path().join("pyproject.toml");
590
591 let content = r#"
593[tool.rumdl]
594line-length = 120
595disable = ["MD033"]
596enable = ["MD001", "MD004"]
597include = ["docs/*.md"]
598exclude = ["node_modules"]
599respect-gitignore = true
600 "#;
601
602 fs::write(&config_path, content).unwrap();
603
604 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
606 let config: Config = sourced.into_validated_unchecked().into(); assert_eq!(config.global.disable, vec!["MD033".to_string()]);
610 assert_eq!(config.global.enable, vec!["MD001".to_string(), "MD004".to_string()]);
611 assert_eq!(config.global.include, vec!["docs/*.md".to_string()]);
613 assert_eq!(config.global.exclude, vec!["node_modules".to_string()]);
614 assert!(config.global.respect_gitignore);
615
616 let line_length = get_rule_config_value::<usize>(&config, "MD013", "line-length");
618 assert_eq!(line_length, Some(120));
619 }
620
621 #[test]
622 fn test_pyproject_toml_snake_case_and_kebab_case() {
623 let temp_dir = tempdir().unwrap();
624 let config_path = temp_dir.path().join("pyproject.toml");
625
626 let content = r#"
628[tool.rumdl]
629line-length = 150
630respect_gitignore = true
631 "#;
632
633 fs::write(&config_path, content).unwrap();
634
635 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
637 let config: Config = sourced.into_validated_unchecked().into(); assert!(config.global.respect_gitignore);
641 let line_length = get_rule_config_value::<usize>(&config, "MD013", "line-length");
642 assert_eq!(line_length, Some(150));
643 }
644
645 #[test]
646 fn test_md013_key_normalization_in_rumdl_toml() {
647 let temp_dir = tempdir().unwrap();
648 let config_path = temp_dir.path().join(".rumdl.toml");
649 let config_content = r#"
650[MD013]
651line_length = 111
652line-length = 222
653"#;
654 fs::write(&config_path, config_content).unwrap();
655 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
657 let rule_cfg = sourced.rules.get("MD013").expect("MD013 rule config should exist");
658 let keys: Vec<_> = rule_cfg.values.keys().cloned().collect();
660 assert_eq!(keys, vec!["line-length"]);
661 let val = &rule_cfg.values["line-length"].value;
662 assert_eq!(val.as_integer(), Some(222));
663 let config: Config = sourced.clone().into_validated_unchecked().into();
665 let v1 = get_rule_config_value::<usize>(&config, "MD013", "line_length");
666 let v2 = get_rule_config_value::<usize>(&config, "MD013", "line-length");
667 assert_eq!(v1, Some(222));
668 assert_eq!(v2, Some(222));
669 }
670
671 #[test]
672 fn test_md013_section_case_insensitivity() {
673 let temp_dir = tempdir().unwrap();
674 let config_path = temp_dir.path().join(".rumdl.toml");
675 let config_content = r#"
676[md013]
677line-length = 101
678
679[Md013]
680line-length = 102
681
682[MD013]
683line-length = 103
684"#;
685 fs::write(&config_path, config_content).unwrap();
686 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
688 let config: Config = sourced.clone().into_validated_unchecked().into();
689 let rule_cfg = sourced.rules.get("MD013").expect("MD013 rule config should exist");
691 let keys: Vec<_> = rule_cfg.values.keys().cloned().collect();
692 assert_eq!(keys, vec!["line-length"]);
693 let val = &rule_cfg.values["line-length"].value;
694 assert_eq!(val.as_integer(), Some(103));
695 let v = get_rule_config_value::<usize>(&config, "MD013", "line-length");
696 assert_eq!(v, Some(103));
697 }
698
699 #[test]
700 fn test_md013_key_snake_and_kebab_case() {
701 let temp_dir = tempdir().unwrap();
702 let config_path = temp_dir.path().join(".rumdl.toml");
703 let config_content = r#"
704[MD013]
705line_length = 201
706line-length = 202
707"#;
708 fs::write(&config_path, config_content).unwrap();
709 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
711 let config: Config = sourced.clone().into_validated_unchecked().into();
712 let rule_cfg = sourced.rules.get("MD013").expect("MD013 rule config should exist");
713 let keys: Vec<_> = rule_cfg.values.keys().cloned().collect();
714 assert_eq!(keys, vec!["line-length"]);
715 let val = &rule_cfg.values["line-length"].value;
716 assert_eq!(val.as_integer(), Some(202));
717 let v1 = get_rule_config_value::<usize>(&config, "MD013", "line_length");
718 let v2 = get_rule_config_value::<usize>(&config, "MD013", "line-length");
719 assert_eq!(v1, Some(202));
720 assert_eq!(v2, Some(202));
721 }
722
723 #[test]
724 fn test_unknown_rule_section_is_ignored() {
725 let temp_dir = tempdir().unwrap();
726 let config_path = temp_dir.path().join(".rumdl.toml");
727 let config_content = r#"
728[MD999]
729foo = 1
730bar = 2
731[MD013]
732line-length = 303
733"#;
734 fs::write(&config_path, config_content).unwrap();
735 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
737 let config: Config = sourced.clone().into_validated_unchecked().into();
738 assert!(!sourced.rules.contains_key("MD999"));
740 let v = get_rule_config_value::<usize>(&config, "MD013", "line-length");
742 assert_eq!(v, Some(303));
743 }
744
745 #[test]
746 fn test_invalid_toml_syntax() {
747 let temp_dir = tempdir().unwrap();
748 let config_path = temp_dir.path().join(".rumdl.toml");
749
750 let config_content = r#"
752[MD013]
753line-length = "unclosed string
754"#;
755 fs::write(&config_path, config_content).unwrap();
756
757 let result = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true);
758 assert!(result.is_err());
759 match result.unwrap_err() {
760 ConfigError::ParseError(msg) => {
761 assert!(msg.contains("expected") || msg.contains("invalid") || msg.contains("unterminated"));
763 }
764 _ => panic!("Expected ParseError"),
765 }
766 }
767
768 #[test]
769 fn test_wrong_type_for_config_value() {
770 let temp_dir = tempdir().unwrap();
771 let config_path = temp_dir.path().join(".rumdl.toml");
772
773 let config_content = r#"
775[MD013]
776line-length = "not a number"
777"#;
778 fs::write(&config_path, config_content).unwrap();
779
780 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
781 let config: Config = sourced.into_validated_unchecked().into();
782
783 let rule_config = config.rules.get("MD013").unwrap();
785 let value = rule_config.values.get("line-length").unwrap();
786 assert!(matches!(value, toml::Value::String(_)));
787 }
788
789 #[test]
790 fn test_empty_config_file() {
791 let temp_dir = tempdir().unwrap();
792 let config_path = temp_dir.path().join(".rumdl.toml");
793
794 fs::write(&config_path, "").unwrap();
796
797 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
798 let config: Config = sourced.into_validated_unchecked().into();
799
800 assert_eq!(config.global.line_length.get(), 80);
802 assert!(config.global.respect_gitignore);
803 assert!(config.rules.is_empty());
804 }
805
806 #[test]
807 fn test_malformed_pyproject_toml() {
808 let temp_dir = tempdir().unwrap();
809 let config_path = temp_dir.path().join("pyproject.toml");
810
811 let content = r#"
813[tool.rumdl
814line-length = 120
815"#;
816 fs::write(&config_path, content).unwrap();
817
818 let result = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true);
819 assert!(result.is_err());
820 }
821
822 #[test]
823 fn test_conflicting_config_values() {
824 let temp_dir = tempdir().unwrap();
825 let config_path = temp_dir.path().join(".rumdl.toml");
826
827 let config_content = r#"
829[global]
830enable = ["MD013"]
831disable = ["MD013"]
832"#;
833 fs::write(&config_path, config_content).unwrap();
834
835 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
836 let config: Config = sourced.into_validated_unchecked().into();
837
838 assert!(config.global.enable.contains(&"MD013".to_string()));
840 assert!(!config.global.disable.contains(&"MD013".to_string()));
841 }
842
843 #[test]
844 fn test_invalid_rule_names() {
845 let temp_dir = tempdir().unwrap();
846 let config_path = temp_dir.path().join(".rumdl.toml");
847
848 let config_content = r#"
849[global]
850enable = ["MD001", "NOT_A_RULE", "md002", "12345"]
851disable = ["MD-001", "MD_002"]
852"#;
853 fs::write(&config_path, config_content).unwrap();
854
855 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
856 let config: Config = sourced.into_validated_unchecked().into();
857
858 assert_eq!(config.global.enable.len(), 4);
860 assert_eq!(config.global.disable.len(), 2);
861 }
862
863 #[test]
864 fn test_deeply_nested_config() {
865 let temp_dir = tempdir().unwrap();
866 let config_path = temp_dir.path().join(".rumdl.toml");
867
868 let config_content = r#"
870[MD013]
871line-length = 100
872[MD013.nested]
873value = 42
874"#;
875 fs::write(&config_path, config_content).unwrap();
876
877 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
878 let config: Config = sourced.into_validated_unchecked().into();
879
880 let rule_config = config.rules.get("MD013").unwrap();
881 assert_eq!(
882 rule_config.values.get("line-length").unwrap(),
883 &toml::Value::Integer(100)
884 );
885 assert!(!rule_config.values.contains_key("nested"));
887 }
888
889 #[test]
890 fn test_unicode_in_config() {
891 let temp_dir = tempdir().unwrap();
892 let config_path = temp_dir.path().join(".rumdl.toml");
893
894 let config_content = r#"
895[global]
896include = ["文档/*.md", "ドã‚ュメント/*.md"]
897exclude = ["测试/*", "🚀/*"]
898
899[MD013]
900line-length = 80
901message = "行太长了 🚨"
902"#;
903 fs::write(&config_path, config_content).unwrap();
904
905 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
906 let config: Config = sourced.into_validated_unchecked().into();
907
908 assert_eq!(config.global.include.len(), 2);
909 assert_eq!(config.global.exclude.len(), 2);
910 assert!(config.global.include[0].contains("文档"));
911 assert!(config.global.exclude[1].contains("🚀"));
912
913 let rule_config = config.rules.get("MD013").unwrap();
914 let message = rule_config.values.get("message").unwrap();
915 if let toml::Value::String(s) = message {
916 assert!(s.contains("行太长了"));
917 assert!(s.contains("🚨"));
918 }
919 }
920
921 #[test]
922 fn test_extremely_long_values() {
923 let temp_dir = tempdir().unwrap();
924 let config_path = temp_dir.path().join(".rumdl.toml");
925
926 let long_string = "a".repeat(10000);
927 let config_content = format!(
928 r#"
929[global]
930exclude = ["{long_string}"]
931
932[MD013]
933line-length = 999999999
934"#
935 );
936
937 fs::write(&config_path, config_content).unwrap();
938
939 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
940 let config: Config = sourced.into_validated_unchecked().into();
941
942 assert_eq!(config.global.exclude[0].len(), 10000);
943 let line_length = get_rule_config_value::<usize>(&config, "MD013", "line-length");
944 assert_eq!(line_length, Some(999999999));
945 }
946
947 #[test]
948 fn test_config_with_comments() {
949 let temp_dir = tempdir().unwrap();
950 let config_path = temp_dir.path().join(".rumdl.toml");
951
952 let config_content = r#"
953[global]
954# This is a comment
955enable = ["MD001"] # Enable MD001
956# disable = ["MD002"] # This is commented out
957
958[MD013] # Line length rule
959line-length = 100 # Set to 100 characters
960# ignored = true # This setting is commented out
961"#;
962 fs::write(&config_path, config_content).unwrap();
963
964 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
965 let config: Config = sourced.into_validated_unchecked().into();
966
967 assert_eq!(config.global.enable, vec!["MD001"]);
968 assert!(config.global.disable.is_empty()); let rule_config = config.rules.get("MD013").unwrap();
971 assert_eq!(rule_config.values.len(), 1); assert!(!rule_config.values.contains_key("ignored"));
973 }
974
975 #[test]
976 fn test_arrays_in_rule_config() {
977 let temp_dir = tempdir().unwrap();
978 let config_path = temp_dir.path().join(".rumdl.toml");
979
980 let config_content = r#"
981[MD003]
982levels = [1, 2, 3]
983tags = ["important", "critical"]
984mixed = [1, "two", true]
985"#;
986 fs::write(&config_path, config_content).unwrap();
987
988 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
989 let config: Config = sourced.into_validated_unchecked().into();
990
991 let rule_config = config.rules.get("MD003").expect("MD003 config should exist");
993
994 assert!(rule_config.values.contains_key("levels"));
996 assert!(rule_config.values.contains_key("tags"));
997 assert!(rule_config.values.contains_key("mixed"));
998
999 if let Some(toml::Value::Array(levels)) = rule_config.values.get("levels") {
1001 assert_eq!(levels.len(), 3);
1002 assert_eq!(levels[0], toml::Value::Integer(1));
1003 assert_eq!(levels[1], toml::Value::Integer(2));
1004 assert_eq!(levels[2], toml::Value::Integer(3));
1005 } else {
1006 panic!("levels should be an array");
1007 }
1008
1009 if let Some(toml::Value::Array(tags)) = rule_config.values.get("tags") {
1010 assert_eq!(tags.len(), 2);
1011 assert_eq!(tags[0], toml::Value::String("important".to_string()));
1012 assert_eq!(tags[1], toml::Value::String("critical".to_string()));
1013 } else {
1014 panic!("tags should be an array");
1015 }
1016
1017 if let Some(toml::Value::Array(mixed)) = rule_config.values.get("mixed") {
1018 assert_eq!(mixed.len(), 3);
1019 assert_eq!(mixed[0], toml::Value::Integer(1));
1020 assert_eq!(mixed[1], toml::Value::String("two".to_string()));
1021 assert_eq!(mixed[2], toml::Value::Boolean(true));
1022 } else {
1023 panic!("mixed should be an array");
1024 }
1025 }
1026
1027 #[test]
1028 fn test_normalize_key_edge_cases() {
1029 assert_eq!(normalize_key("MD001"), "MD001");
1031 assert_eq!(normalize_key("md001"), "MD001");
1032 assert_eq!(normalize_key("Md001"), "MD001");
1033 assert_eq!(normalize_key("mD001"), "MD001");
1034
1035 assert_eq!(normalize_key("line_length"), "line-length");
1037 assert_eq!(normalize_key("line-length"), "line-length");
1038 assert_eq!(normalize_key("LINE_LENGTH"), "line-length");
1039 assert_eq!(normalize_key("respect_gitignore"), "respect-gitignore");
1040
1041 assert_eq!(normalize_key("MD"), "md"); assert_eq!(normalize_key("MD00"), "md00"); assert_eq!(normalize_key("MD0001"), "md0001"); assert_eq!(normalize_key("MDabc"), "mdabc"); assert_eq!(normalize_key("MD00a"), "md00a"); assert_eq!(normalize_key(""), "");
1048 assert_eq!(normalize_key("_"), "-");
1049 assert_eq!(normalize_key("___"), "---");
1050 }
1051
1052 #[test]
1053 fn test_missing_config_file() {
1054 let temp_dir = tempdir().unwrap();
1055 let config_path = temp_dir.path().join("nonexistent.toml");
1056
1057 let result = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true);
1058 assert!(result.is_err());
1059 match result.unwrap_err() {
1060 ConfigError::IoError { .. } => {}
1061 _ => panic!("Expected IoError for missing file"),
1062 }
1063 }
1064
1065 #[test]
1066 #[cfg(unix)]
1067 fn test_permission_denied_config() {
1068 use std::os::unix::fs::PermissionsExt;
1069
1070 let temp_dir = tempdir().unwrap();
1071 let config_path = temp_dir.path().join(".rumdl.toml");
1072
1073 fs::write(&config_path, "enable = [\"MD001\"]").unwrap();
1074
1075 let mut perms = fs::metadata(&config_path).unwrap().permissions();
1077 perms.set_mode(0o000);
1078 fs::set_permissions(&config_path, perms).unwrap();
1079
1080 let result = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true);
1081
1082 let mut perms = fs::metadata(&config_path).unwrap().permissions();
1084 perms.set_mode(0o644);
1085 fs::set_permissions(&config_path, perms).unwrap();
1086
1087 assert!(result.is_err());
1088 match result.unwrap_err() {
1089 ConfigError::IoError { .. } => {}
1090 _ => panic!("Expected IoError for permission denied"),
1091 }
1092 }
1093
1094 #[test]
1095 fn test_circular_reference_detection() {
1096 let temp_dir = tempdir().unwrap();
1099 let config_path = temp_dir.path().join(".rumdl.toml");
1100
1101 let mut config_content = String::from("[MD001]\n");
1102 for i in 0..100 {
1103 config_content.push_str(&format!("key{i} = {i}\n"));
1104 }
1105
1106 fs::write(&config_path, config_content).unwrap();
1107
1108 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1109 let config: Config = sourced.into_validated_unchecked().into();
1110
1111 let rule_config = config.rules.get("MD001").unwrap();
1112 assert_eq!(rule_config.values.len(), 100);
1113 }
1114
1115 #[test]
1116 fn test_special_toml_values() {
1117 let temp_dir = tempdir().unwrap();
1118 let config_path = temp_dir.path().join(".rumdl.toml");
1119
1120 let config_content = r#"
1121[MD001]
1122infinity = inf
1123neg_infinity = -inf
1124not_a_number = nan
1125datetime = 1979-05-27T07:32:00Z
1126local_date = 1979-05-27
1127local_time = 07:32:00
1128"#;
1129 fs::write(&config_path, config_content).unwrap();
1130
1131 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1132 let config: Config = sourced.into_validated_unchecked().into();
1133
1134 if let Some(rule_config) = config.rules.get("MD001") {
1136 if let Some(toml::Value::Float(f)) = rule_config.values.get("infinity") {
1138 assert!(f.is_infinite() && f.is_sign_positive());
1139 }
1140 if let Some(toml::Value::Float(f)) = rule_config.values.get("neg_infinity") {
1141 assert!(f.is_infinite() && f.is_sign_negative());
1142 }
1143 if let Some(toml::Value::Float(f)) = rule_config.values.get("not_a_number") {
1144 assert!(f.is_nan());
1145 }
1146
1147 if let Some(val) = rule_config.values.get("datetime") {
1149 assert!(matches!(val, toml::Value::Datetime(_)));
1150 }
1151 }
1153 }
1154
1155 #[test]
1156 fn test_default_config_passes_validation() {
1157 use crate::rules;
1158
1159 let temp_dir = tempdir().unwrap();
1160 let config_path = temp_dir.path().join(".rumdl.toml");
1161 let config_path_str = config_path.to_str().unwrap();
1162
1163 create_default_config(config_path_str).unwrap();
1165
1166 let sourced =
1168 SourcedConfig::load(Some(config_path_str), None).expect("Default config should load successfully");
1169
1170 let all_rules = rules::all_rules(&Config::default());
1172 let registry = RuleRegistry::from_rules(&all_rules);
1173
1174 let warnings = validate_config_sourced(&sourced, ®istry);
1176
1177 if !warnings.is_empty() {
1179 for warning in &warnings {
1180 eprintln!("Config validation warning: {}", warning.message);
1181 if let Some(rule) = &warning.rule {
1182 eprintln!(" Rule: {rule}");
1183 }
1184 if let Some(key) = &warning.key {
1185 eprintln!(" Key: {key}");
1186 }
1187 }
1188 }
1189 assert!(
1190 warnings.is_empty(),
1191 "Default config from rumdl init should pass validation without warnings"
1192 );
1193 }
1194
1195 #[test]
1196 fn test_per_file_ignores_config_parsing() {
1197 let temp_dir = tempdir().unwrap();
1198 let config_path = temp_dir.path().join(".rumdl.toml");
1199 let config_content = r#"
1200[per-file-ignores]
1201"README.md" = ["MD033"]
1202"docs/**/*.md" = ["MD013", "MD033"]
1203"test/*.md" = ["MD041"]
1204"#;
1205 fs::write(&config_path, config_content).unwrap();
1206
1207 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1208 let config: Config = sourced.into_validated_unchecked().into();
1209
1210 assert_eq!(config.per_file_ignores.len(), 3);
1212 assert_eq!(
1213 config.per_file_ignores.get("README.md"),
1214 Some(&vec!["MD033".to_string()])
1215 );
1216 assert_eq!(
1217 config.per_file_ignores.get("docs/**/*.md"),
1218 Some(&vec!["MD013".to_string(), "MD033".to_string()])
1219 );
1220 assert_eq!(
1221 config.per_file_ignores.get("test/*.md"),
1222 Some(&vec!["MD041".to_string()])
1223 );
1224 }
1225
1226 #[test]
1227 fn test_per_file_ignores_glob_matching() {
1228 use std::path::PathBuf;
1229
1230 let temp_dir = tempdir().unwrap();
1231 let config_path = temp_dir.path().join(".rumdl.toml");
1232 let config_content = r#"
1233[per-file-ignores]
1234"README.md" = ["MD033"]
1235"docs/**/*.md" = ["MD013"]
1236"**/test_*.md" = ["MD041"]
1237"#;
1238 fs::write(&config_path, config_content).unwrap();
1239
1240 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1241 let config: Config = sourced.into_validated_unchecked().into();
1242
1243 let ignored = config.get_ignored_rules_for_file(&PathBuf::from("README.md"));
1245 assert!(ignored.contains("MD033"));
1246 assert_eq!(ignored.len(), 1);
1247
1248 let ignored = config.get_ignored_rules_for_file(&PathBuf::from("docs/api/overview.md"));
1250 assert!(ignored.contains("MD013"));
1251 assert_eq!(ignored.len(), 1);
1252
1253 let ignored = config.get_ignored_rules_for_file(&PathBuf::from("tests/fixtures/test_example.md"));
1255 assert!(ignored.contains("MD041"));
1256 assert_eq!(ignored.len(), 1);
1257
1258 let ignored = config.get_ignored_rules_for_file(&PathBuf::from("other/file.md"));
1260 assert!(ignored.is_empty());
1261 }
1262
1263 #[test]
1264 fn test_per_file_ignores_pyproject_toml() {
1265 let temp_dir = tempdir().unwrap();
1266 let config_path = temp_dir.path().join("pyproject.toml");
1267 let config_content = r#"
1268[tool.rumdl]
1269[tool.rumdl.per-file-ignores]
1270"README.md" = ["MD033", "MD013"]
1271"generated/*.md" = ["MD041"]
1272"#;
1273 fs::write(&config_path, config_content).unwrap();
1274
1275 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1276 let config: Config = sourced.into_validated_unchecked().into();
1277
1278 assert_eq!(config.per_file_ignores.len(), 2);
1280 assert_eq!(
1281 config.per_file_ignores.get("README.md"),
1282 Some(&vec!["MD033".to_string(), "MD013".to_string()])
1283 );
1284 assert_eq!(
1285 config.per_file_ignores.get("generated/*.md"),
1286 Some(&vec!["MD041".to_string()])
1287 );
1288 }
1289
1290 #[test]
1291 fn test_per_file_ignores_multiple_patterns_match() {
1292 use std::path::PathBuf;
1293
1294 let temp_dir = tempdir().unwrap();
1295 let config_path = temp_dir.path().join(".rumdl.toml");
1296 let config_content = r#"
1297[per-file-ignores]
1298"docs/**/*.md" = ["MD013"]
1299"**/api/*.md" = ["MD033"]
1300"docs/api/overview.md" = ["MD041"]
1301"#;
1302 fs::write(&config_path, config_content).unwrap();
1303
1304 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1305 let config: Config = sourced.into_validated_unchecked().into();
1306
1307 let ignored = config.get_ignored_rules_for_file(&PathBuf::from("docs/api/overview.md"));
1309 assert_eq!(ignored.len(), 3);
1310 assert!(ignored.contains("MD013"));
1311 assert!(ignored.contains("MD033"));
1312 assert!(ignored.contains("MD041"));
1313 }
1314
1315 #[test]
1316 fn test_per_file_ignores_rule_name_normalization() {
1317 use std::path::PathBuf;
1318
1319 let temp_dir = tempdir().unwrap();
1320 let config_path = temp_dir.path().join(".rumdl.toml");
1321 let config_content = r#"
1322[per-file-ignores]
1323"README.md" = ["md033", "MD013", "Md041"]
1324"#;
1325 fs::write(&config_path, config_content).unwrap();
1326
1327 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1328 let config: Config = sourced.into_validated_unchecked().into();
1329
1330 let ignored = config.get_ignored_rules_for_file(&PathBuf::from("README.md"));
1332 assert_eq!(ignored.len(), 3);
1333 assert!(ignored.contains("MD033"));
1334 assert!(ignored.contains("MD013"));
1335 assert!(ignored.contains("MD041"));
1336 }
1337
1338 #[test]
1339 fn test_per_file_ignores_invalid_glob_pattern() {
1340 use std::path::PathBuf;
1341
1342 let temp_dir = tempdir().unwrap();
1343 let config_path = temp_dir.path().join(".rumdl.toml");
1344 let config_content = r#"
1345[per-file-ignores]
1346"[invalid" = ["MD033"]
1347"valid/*.md" = ["MD013"]
1348"#;
1349 fs::write(&config_path, config_content).unwrap();
1350
1351 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1352 let config: Config = sourced.into_validated_unchecked().into();
1353
1354 let ignored = config.get_ignored_rules_for_file(&PathBuf::from("valid/test.md"));
1356 assert!(ignored.contains("MD013"));
1357
1358 let ignored2 = config.get_ignored_rules_for_file(&PathBuf::from("[invalid"));
1360 assert!(ignored2.is_empty());
1361 }
1362
1363 #[test]
1364 fn test_per_file_ignores_empty_section() {
1365 use std::path::PathBuf;
1366
1367 let temp_dir = tempdir().unwrap();
1368 let config_path = temp_dir.path().join(".rumdl.toml");
1369 let config_content = r#"
1370[global]
1371disable = ["MD001"]
1372
1373[per-file-ignores]
1374"#;
1375 fs::write(&config_path, config_content).unwrap();
1376
1377 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1378 let config: Config = sourced.into_validated_unchecked().into();
1379
1380 assert_eq!(config.per_file_ignores.len(), 0);
1382 let ignored = config.get_ignored_rules_for_file(&PathBuf::from("README.md"));
1383 assert!(ignored.is_empty());
1384 }
1385
1386 #[test]
1387 fn test_per_file_ignores_with_underscores_in_pyproject() {
1388 let temp_dir = tempdir().unwrap();
1389 let config_path = temp_dir.path().join("pyproject.toml");
1390 let config_content = r#"
1391[tool.rumdl]
1392[tool.rumdl.per_file_ignores]
1393"README.md" = ["MD033"]
1394"#;
1395 fs::write(&config_path, config_content).unwrap();
1396
1397 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1398 let config: Config = sourced.into_validated_unchecked().into();
1399
1400 assert_eq!(config.per_file_ignores.len(), 1);
1402 assert_eq!(
1403 config.per_file_ignores.get("README.md"),
1404 Some(&vec!["MD033".to_string()])
1405 );
1406 }
1407
1408 #[test]
1409 fn test_per_file_ignores_absolute_path_matching() {
1410 use std::path::PathBuf;
1413
1414 let temp_dir = tempdir().unwrap();
1415 let config_path = temp_dir.path().join(".rumdl.toml");
1416
1417 let github_dir = temp_dir.path().join(".github");
1419 fs::create_dir_all(&github_dir).unwrap();
1420 let test_file = github_dir.join("pull_request_template.md");
1421 fs::write(&test_file, "Test content").unwrap();
1422
1423 let config_content = r#"
1424[per-file-ignores]
1425".github/pull_request_template.md" = ["MD041"]
1426"docs/**/*.md" = ["MD013"]
1427"#;
1428 fs::write(&config_path, config_content).unwrap();
1429
1430 let sourced = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true).unwrap();
1431 let config: Config = sourced.into_validated_unchecked().into();
1432
1433 let absolute_path = test_file.canonicalize().unwrap();
1435 let ignored = config.get_ignored_rules_for_file(&absolute_path);
1436 assert!(
1437 ignored.contains("MD041"),
1438 "Should match absolute path {absolute_path:?} against relative pattern"
1439 );
1440 assert_eq!(ignored.len(), 1);
1441
1442 let relative_path = PathBuf::from(".github/pull_request_template.md");
1444 let ignored = config.get_ignored_rules_for_file(&relative_path);
1445 assert!(ignored.contains("MD041"), "Should match relative path");
1446 }
1447
1448 #[test]
1449 fn test_generate_json_schema() {
1450 use schemars::schema_for;
1451 use std::env;
1452
1453 let schema = schema_for!(Config);
1454 let schema_json = serde_json::to_string_pretty(&schema).expect("Failed to serialize schema");
1455
1456 if env::var("RUMDL_UPDATE_SCHEMA").is_ok() {
1458 let schema_path = env::current_dir().unwrap().join("rumdl.schema.json");
1459 fs::write(&schema_path, &schema_json).expect("Failed to write schema file");
1460 println!("Schema written to: {}", schema_path.display());
1461 }
1462
1463 assert!(schema_json.contains("\"title\": \"Config\""));
1465 assert!(schema_json.contains("\"global\""));
1466 assert!(schema_json.contains("\"per-file-ignores\""));
1467 }
1468
1469 #[test]
1470 fn test_project_config_is_standalone() {
1471 let temp_dir = tempdir().unwrap();
1474
1475 let user_config_dir = temp_dir.path().join("user_config");
1478 let rumdl_config_dir = user_config_dir.join("rumdl");
1479 fs::create_dir_all(&rumdl_config_dir).unwrap();
1480 let user_config_path = rumdl_config_dir.join("rumdl.toml");
1481
1482 let user_config_content = r#"
1484[global]
1485disable = ["MD013", "MD041"]
1486line-length = 100
1487"#;
1488 fs::write(&user_config_path, user_config_content).unwrap();
1489
1490 let project_config_path = temp_dir.path().join("project").join("pyproject.toml");
1492 fs::create_dir_all(project_config_path.parent().unwrap()).unwrap();
1493 let project_config_content = r#"
1494[tool.rumdl]
1495enable = ["MD001"]
1496"#;
1497 fs::write(&project_config_path, project_config_content).unwrap();
1498
1499 let sourced = SourcedConfig::load_with_discovery_impl(
1501 Some(project_config_path.to_str().unwrap()),
1502 None,
1503 false,
1504 Some(&user_config_dir),
1505 )
1506 .unwrap();
1507
1508 let config: Config = sourced.into_validated_unchecked().into();
1509
1510 assert!(
1512 !config.global.disable.contains(&"MD013".to_string()),
1513 "User config should NOT be merged with project config"
1514 );
1515 assert!(
1516 !config.global.disable.contains(&"MD041".to_string()),
1517 "User config should NOT be merged with project config"
1518 );
1519
1520 assert!(
1522 config.global.enable.contains(&"MD001".to_string()),
1523 "Project config enabled rules should be applied"
1524 );
1525 }
1526
1527 #[test]
1528 fn test_user_config_as_fallback_when_no_project_config() {
1529 use std::env;
1531
1532 let temp_dir = tempdir().unwrap();
1533 let original_dir = env::current_dir().unwrap();
1534
1535 let user_config_dir = temp_dir.path().join("user_config");
1537 let rumdl_config_dir = user_config_dir.join("rumdl");
1538 fs::create_dir_all(&rumdl_config_dir).unwrap();
1539 let user_config_path = rumdl_config_dir.join("rumdl.toml");
1540
1541 let user_config_content = r#"
1543[global]
1544disable = ["MD013", "MD041"]
1545line-length = 88
1546"#;
1547 fs::write(&user_config_path, user_config_content).unwrap();
1548
1549 let project_dir = temp_dir.path().join("project_no_config");
1551 fs::create_dir_all(&project_dir).unwrap();
1552
1553 env::set_current_dir(&project_dir).unwrap();
1555
1556 let sourced = SourcedConfig::load_with_discovery_impl(None, None, false, Some(&user_config_dir)).unwrap();
1558
1559 let config: Config = sourced.into_validated_unchecked().into();
1560
1561 assert!(
1563 config.global.disable.contains(&"MD013".to_string()),
1564 "User config should be loaded as fallback when no project config"
1565 );
1566 assert!(
1567 config.global.disable.contains(&"MD041".to_string()),
1568 "User config should be loaded as fallback when no project config"
1569 );
1570 assert_eq!(
1571 config.global.line_length.get(),
1572 88,
1573 "User config line-length should be loaded as fallback"
1574 );
1575
1576 env::set_current_dir(original_dir).unwrap();
1577 }
1578
1579 #[test]
1580 fn test_typestate_validate_method() {
1581 use tempfile::tempdir;
1582
1583 let temp_dir = tempdir().expect("Failed to create temporary directory");
1584 let config_path = temp_dir.path().join("test.toml");
1585
1586 let config_content = r#"
1588[global]
1589enable = ["MD001"]
1590
1591[MD013]
1592line_length = 80
1593unknown_option = true
1594"#;
1595 std::fs::write(&config_path, config_content).expect("Failed to write config");
1596
1597 let loaded = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true)
1599 .expect("Should load config");
1600
1601 let default_config = Config::default();
1603 let all_rules = crate::rules::all_rules(&default_config);
1604 let registry = RuleRegistry::from_rules(&all_rules);
1605
1606 let validated = loaded.validate(®istry).expect("Should validate config");
1608
1609 let has_unknown_option_warning = validated
1612 .validation_warnings
1613 .iter()
1614 .any(|w| w.message.contains("unknown_option") || w.message.contains("Unknown option"));
1615
1616 if !has_unknown_option_warning {
1618 for w in &validated.validation_warnings {
1619 eprintln!("Warning: {}", w.message);
1620 }
1621 }
1622 assert!(
1623 has_unknown_option_warning,
1624 "Should have warning for unknown option. Got {} warnings: {:?}",
1625 validated.validation_warnings.len(),
1626 validated
1627 .validation_warnings
1628 .iter()
1629 .map(|w| &w.message)
1630 .collect::<Vec<_>>()
1631 );
1632
1633 let config: Config = validated.into();
1635
1636 assert!(config.global.enable.contains(&"MD001".to_string()));
1638 }
1639
1640 #[test]
1641 fn test_typestate_validate_into_convenience_method() {
1642 use tempfile::tempdir;
1643
1644 let temp_dir = tempdir().expect("Failed to create temporary directory");
1645 let config_path = temp_dir.path().join("test.toml");
1646
1647 let config_content = r#"
1648[global]
1649enable = ["MD022"]
1650
1651[MD022]
1652lines_above = 2
1653"#;
1654 std::fs::write(&config_path, config_content).expect("Failed to write config");
1655
1656 let loaded = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true)
1657 .expect("Should load config");
1658
1659 let default_config = Config::default();
1660 let all_rules = crate::rules::all_rules(&default_config);
1661 let registry = RuleRegistry::from_rules(&all_rules);
1662
1663 let (config, warnings) = loaded.validate_into(®istry).expect("Should validate and convert");
1665
1666 assert!(warnings.is_empty(), "Should have no warnings for valid config");
1668
1669 assert!(config.global.enable.contains(&"MD022".to_string()));
1671 }
1672}
1673
1674#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1683pub enum ConfigSource {
1684 Default,
1686 UserConfig,
1688 PyprojectToml,
1690 ProjectConfig,
1692 Cli,
1694}
1695
1696#[derive(Debug, Clone)]
1697pub struct ConfigOverride<T> {
1698 pub value: T,
1699 pub source: ConfigSource,
1700 pub file: Option<String>,
1701 pub line: Option<usize>,
1702}
1703
1704#[derive(Debug, Clone)]
1705pub struct SourcedValue<T> {
1706 pub value: T,
1707 pub source: ConfigSource,
1708 pub overrides: Vec<ConfigOverride<T>>,
1709}
1710
1711impl<T: Clone> SourcedValue<T> {
1712 pub fn new(value: T, source: ConfigSource) -> Self {
1713 Self {
1714 value: value.clone(),
1715 source,
1716 overrides: vec![ConfigOverride {
1717 value,
1718 source,
1719 file: None,
1720 line: None,
1721 }],
1722 }
1723 }
1724
1725 pub fn merge_override(
1729 &mut self,
1730 new_value: T,
1731 new_source: ConfigSource,
1732 new_file: Option<String>,
1733 new_line: Option<usize>,
1734 ) {
1735 fn source_precedence(src: ConfigSource) -> u8 {
1737 match src {
1738 ConfigSource::Default => 0,
1739 ConfigSource::UserConfig => 1,
1740 ConfigSource::PyprojectToml => 2,
1741 ConfigSource::ProjectConfig => 3,
1742 ConfigSource::Cli => 4,
1743 }
1744 }
1745
1746 if source_precedence(new_source) >= source_precedence(self.source) {
1747 self.value = new_value.clone();
1748 self.source = new_source;
1749 self.overrides.push(ConfigOverride {
1750 value: new_value,
1751 source: new_source,
1752 file: new_file,
1753 line: new_line,
1754 });
1755 }
1756 }
1757
1758 pub fn push_override(&mut self, value: T, source: ConfigSource, file: Option<String>, line: Option<usize>) {
1759 self.value = value.clone();
1762 self.source = source;
1763 self.overrides.push(ConfigOverride {
1764 value,
1765 source,
1766 file,
1767 line,
1768 });
1769 }
1770}
1771
1772impl<T: Clone + Eq + std::hash::Hash> SourcedValue<Vec<T>> {
1773 pub fn merge_union(
1776 &mut self,
1777 new_value: Vec<T>,
1778 new_source: ConfigSource,
1779 new_file: Option<String>,
1780 new_line: Option<usize>,
1781 ) {
1782 fn source_precedence(src: ConfigSource) -> u8 {
1783 match src {
1784 ConfigSource::Default => 0,
1785 ConfigSource::UserConfig => 1,
1786 ConfigSource::PyprojectToml => 2,
1787 ConfigSource::ProjectConfig => 3,
1788 ConfigSource::Cli => 4,
1789 }
1790 }
1791
1792 if source_precedence(new_source) >= source_precedence(self.source) {
1793 let mut combined = self.value.clone();
1795 for item in new_value.iter() {
1796 if !combined.contains(item) {
1797 combined.push(item.clone());
1798 }
1799 }
1800
1801 self.value = combined;
1802 self.source = new_source;
1803 self.overrides.push(ConfigOverride {
1804 value: new_value,
1805 source: new_source,
1806 file: new_file,
1807 line: new_line,
1808 });
1809 }
1810 }
1811}
1812
1813#[derive(Debug, Clone)]
1814pub struct SourcedGlobalConfig {
1815 pub enable: SourcedValue<Vec<String>>,
1816 pub disable: SourcedValue<Vec<String>>,
1817 pub exclude: SourcedValue<Vec<String>>,
1818 pub include: SourcedValue<Vec<String>>,
1819 pub respect_gitignore: SourcedValue<bool>,
1820 pub line_length: SourcedValue<LineLength>,
1821 pub output_format: Option<SourcedValue<String>>,
1822 pub fixable: SourcedValue<Vec<String>>,
1823 pub unfixable: SourcedValue<Vec<String>>,
1824 pub flavor: SourcedValue<MarkdownFlavor>,
1825 pub force_exclude: SourcedValue<bool>,
1826 pub cache_dir: Option<SourcedValue<String>>,
1827 pub cache: SourcedValue<bool>,
1828}
1829
1830impl Default for SourcedGlobalConfig {
1831 fn default() -> Self {
1832 SourcedGlobalConfig {
1833 enable: SourcedValue::new(Vec::new(), ConfigSource::Default),
1834 disable: SourcedValue::new(Vec::new(), ConfigSource::Default),
1835 exclude: SourcedValue::new(Vec::new(), ConfigSource::Default),
1836 include: SourcedValue::new(Vec::new(), ConfigSource::Default),
1837 respect_gitignore: SourcedValue::new(true, ConfigSource::Default),
1838 line_length: SourcedValue::new(LineLength::default(), ConfigSource::Default),
1839 output_format: None,
1840 fixable: SourcedValue::new(Vec::new(), ConfigSource::Default),
1841 unfixable: SourcedValue::new(Vec::new(), ConfigSource::Default),
1842 flavor: SourcedValue::new(MarkdownFlavor::default(), ConfigSource::Default),
1843 force_exclude: SourcedValue::new(false, ConfigSource::Default),
1844 cache_dir: None,
1845 cache: SourcedValue::new(true, ConfigSource::Default),
1846 }
1847 }
1848}
1849
1850#[derive(Debug, Default, Clone)]
1851pub struct SourcedRuleConfig {
1852 pub severity: Option<SourcedValue<crate::rule::Severity>>,
1853 pub values: BTreeMap<String, SourcedValue<toml::Value>>,
1854}
1855
1856#[derive(Debug, Clone)]
1859pub struct SourcedConfigFragment {
1860 pub global: SourcedGlobalConfig,
1861 pub per_file_ignores: SourcedValue<HashMap<String, Vec<String>>>,
1862 pub rules: BTreeMap<String, SourcedRuleConfig>,
1863 pub unknown_keys: Vec<(String, String, Option<String>)>, }
1866
1867impl Default for SourcedConfigFragment {
1868 fn default() -> Self {
1869 Self {
1870 global: SourcedGlobalConfig::default(),
1871 per_file_ignores: SourcedValue::new(HashMap::new(), ConfigSource::Default),
1872 rules: BTreeMap::new(),
1873 unknown_keys: Vec::new(),
1874 }
1875 }
1876}
1877
1878#[derive(Debug, Clone)]
1896pub struct SourcedConfig<State = ConfigLoaded> {
1897 pub global: SourcedGlobalConfig,
1898 pub per_file_ignores: SourcedValue<HashMap<String, Vec<String>>>,
1899 pub rules: BTreeMap<String, SourcedRuleConfig>,
1900 pub loaded_files: Vec<String>,
1901 pub unknown_keys: Vec<(String, String, Option<String>)>, pub project_root: Option<std::path::PathBuf>,
1904 pub validation_warnings: Vec<ConfigValidationWarning>,
1906 _state: PhantomData<State>,
1908}
1909
1910impl Default for SourcedConfig<ConfigLoaded> {
1911 fn default() -> Self {
1912 Self {
1913 global: SourcedGlobalConfig::default(),
1914 per_file_ignores: SourcedValue::new(HashMap::new(), ConfigSource::Default),
1915 rules: BTreeMap::new(),
1916 loaded_files: Vec::new(),
1917 unknown_keys: Vec::new(),
1918 project_root: None,
1919 validation_warnings: Vec::new(),
1920 _state: PhantomData,
1921 }
1922 }
1923}
1924
1925impl SourcedConfig<ConfigLoaded> {
1926 fn merge(&mut self, fragment: SourcedConfigFragment) {
1929 self.global.enable.merge_override(
1932 fragment.global.enable.value,
1933 fragment.global.enable.source,
1934 fragment.global.enable.overrides.first().and_then(|o| o.file.clone()),
1935 fragment.global.enable.overrides.first().and_then(|o| o.line),
1936 );
1937
1938 self.global.disable.merge_union(
1940 fragment.global.disable.value,
1941 fragment.global.disable.source,
1942 fragment.global.disable.overrides.first().and_then(|o| o.file.clone()),
1943 fragment.global.disable.overrides.first().and_then(|o| o.line),
1944 );
1945
1946 self.global
1949 .disable
1950 .value
1951 .retain(|rule| !self.global.enable.value.contains(rule));
1952 self.global.include.merge_override(
1953 fragment.global.include.value,
1954 fragment.global.include.source,
1955 fragment.global.include.overrides.first().and_then(|o| o.file.clone()),
1956 fragment.global.include.overrides.first().and_then(|o| o.line),
1957 );
1958 self.global.exclude.merge_override(
1959 fragment.global.exclude.value,
1960 fragment.global.exclude.source,
1961 fragment.global.exclude.overrides.first().and_then(|o| o.file.clone()),
1962 fragment.global.exclude.overrides.first().and_then(|o| o.line),
1963 );
1964 self.global.respect_gitignore.merge_override(
1965 fragment.global.respect_gitignore.value,
1966 fragment.global.respect_gitignore.source,
1967 fragment
1968 .global
1969 .respect_gitignore
1970 .overrides
1971 .first()
1972 .and_then(|o| o.file.clone()),
1973 fragment.global.respect_gitignore.overrides.first().and_then(|o| o.line),
1974 );
1975 self.global.line_length.merge_override(
1976 fragment.global.line_length.value,
1977 fragment.global.line_length.source,
1978 fragment
1979 .global
1980 .line_length
1981 .overrides
1982 .first()
1983 .and_then(|o| o.file.clone()),
1984 fragment.global.line_length.overrides.first().and_then(|o| o.line),
1985 );
1986 self.global.fixable.merge_override(
1987 fragment.global.fixable.value,
1988 fragment.global.fixable.source,
1989 fragment.global.fixable.overrides.first().and_then(|o| o.file.clone()),
1990 fragment.global.fixable.overrides.first().and_then(|o| o.line),
1991 );
1992 self.global.unfixable.merge_override(
1993 fragment.global.unfixable.value,
1994 fragment.global.unfixable.source,
1995 fragment.global.unfixable.overrides.first().and_then(|o| o.file.clone()),
1996 fragment.global.unfixable.overrides.first().and_then(|o| o.line),
1997 );
1998
1999 self.global.flavor.merge_override(
2001 fragment.global.flavor.value,
2002 fragment.global.flavor.source,
2003 fragment.global.flavor.overrides.first().and_then(|o| o.file.clone()),
2004 fragment.global.flavor.overrides.first().and_then(|o| o.line),
2005 );
2006
2007 self.global.force_exclude.merge_override(
2009 fragment.global.force_exclude.value,
2010 fragment.global.force_exclude.source,
2011 fragment
2012 .global
2013 .force_exclude
2014 .overrides
2015 .first()
2016 .and_then(|o| o.file.clone()),
2017 fragment.global.force_exclude.overrides.first().and_then(|o| o.line),
2018 );
2019
2020 if let Some(output_format_fragment) = fragment.global.output_format {
2022 if let Some(ref mut output_format) = self.global.output_format {
2023 output_format.merge_override(
2024 output_format_fragment.value,
2025 output_format_fragment.source,
2026 output_format_fragment.overrides.first().and_then(|o| o.file.clone()),
2027 output_format_fragment.overrides.first().and_then(|o| o.line),
2028 );
2029 } else {
2030 self.global.output_format = Some(output_format_fragment);
2031 }
2032 }
2033
2034 if let Some(cache_dir_fragment) = fragment.global.cache_dir {
2036 if let Some(ref mut cache_dir) = self.global.cache_dir {
2037 cache_dir.merge_override(
2038 cache_dir_fragment.value,
2039 cache_dir_fragment.source,
2040 cache_dir_fragment.overrides.first().and_then(|o| o.file.clone()),
2041 cache_dir_fragment.overrides.first().and_then(|o| o.line),
2042 );
2043 } else {
2044 self.global.cache_dir = Some(cache_dir_fragment);
2045 }
2046 }
2047
2048 if fragment.global.cache.source != ConfigSource::Default {
2050 self.global.cache.merge_override(
2051 fragment.global.cache.value,
2052 fragment.global.cache.source,
2053 fragment.global.cache.overrides.first().and_then(|o| o.file.clone()),
2054 fragment.global.cache.overrides.first().and_then(|o| o.line),
2055 );
2056 }
2057
2058 self.per_file_ignores.merge_override(
2060 fragment.per_file_ignores.value,
2061 fragment.per_file_ignores.source,
2062 fragment.per_file_ignores.overrides.first().and_then(|o| o.file.clone()),
2063 fragment.per_file_ignores.overrides.first().and_then(|o| o.line),
2064 );
2065
2066 for (rule_name, rule_fragment) in fragment.rules {
2068 let norm_rule_name = rule_name.to_ascii_uppercase(); let rule_entry = self.rules.entry(norm_rule_name).or_default();
2070
2071 if let Some(severity_fragment) = rule_fragment.severity {
2073 if let Some(ref mut existing_severity) = rule_entry.severity {
2074 existing_severity.merge_override(
2075 severity_fragment.value,
2076 severity_fragment.source,
2077 severity_fragment.overrides.first().and_then(|o| o.file.clone()),
2078 severity_fragment.overrides.first().and_then(|o| o.line),
2079 );
2080 } else {
2081 rule_entry.severity = Some(severity_fragment);
2082 }
2083 }
2084
2085 for (key, sourced_value_fragment) in rule_fragment.values {
2087 let sv_entry = rule_entry
2088 .values
2089 .entry(key.clone())
2090 .or_insert_with(|| SourcedValue::new(sourced_value_fragment.value.clone(), ConfigSource::Default));
2091 let file_from_fragment = sourced_value_fragment.overrides.first().and_then(|o| o.file.clone());
2092 let line_from_fragment = sourced_value_fragment.overrides.first().and_then(|o| o.line);
2093 sv_entry.merge_override(
2094 sourced_value_fragment.value, sourced_value_fragment.source, file_from_fragment, line_from_fragment, );
2099 }
2100 }
2101
2102 for (section, key, file_path) in fragment.unknown_keys {
2104 if !self.unknown_keys.iter().any(|(s, k, _)| s == §ion && k == &key) {
2106 self.unknown_keys.push((section, key, file_path));
2107 }
2108 }
2109 }
2110
2111 pub fn load(config_path: Option<&str>, cli_overrides: Option<&SourcedGlobalConfig>) -> Result<Self, ConfigError> {
2113 Self::load_with_discovery(config_path, cli_overrides, false)
2114 }
2115
2116 fn find_project_root_from(start_dir: &Path) -> std::path::PathBuf {
2119 let mut current = start_dir.to_path_buf();
2120 const MAX_DEPTH: usize = 100;
2121
2122 for _ in 0..MAX_DEPTH {
2123 if current.join(".git").exists() {
2124 log::debug!("[rumdl-config] Found .git at: {}", current.display());
2125 return current;
2126 }
2127
2128 match current.parent() {
2129 Some(parent) => current = parent.to_path_buf(),
2130 None => break,
2131 }
2132 }
2133
2134 log::debug!(
2136 "[rumdl-config] No .git found, using config location as project root: {}",
2137 start_dir.display()
2138 );
2139 start_dir.to_path_buf()
2140 }
2141
2142 fn discover_config_upward() -> Option<(std::path::PathBuf, std::path::PathBuf)> {
2148 use std::env;
2149
2150 const CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml", ".config/rumdl.toml", "pyproject.toml"];
2151 const MAX_DEPTH: usize = 100; let start_dir = match env::current_dir() {
2154 Ok(dir) => dir,
2155 Err(e) => {
2156 log::debug!("[rumdl-config] Failed to get current directory: {e}");
2157 return None;
2158 }
2159 };
2160
2161 let mut current_dir = start_dir.clone();
2162 let mut depth = 0;
2163 let mut found_config: Option<(std::path::PathBuf, std::path::PathBuf)> = None;
2164
2165 loop {
2166 if depth >= MAX_DEPTH {
2167 log::debug!("[rumdl-config] Maximum traversal depth reached");
2168 break;
2169 }
2170
2171 log::debug!("[rumdl-config] Searching for config in: {}", current_dir.display());
2172
2173 if found_config.is_none() {
2175 for config_name in CONFIG_FILES {
2176 let config_path = current_dir.join(config_name);
2177
2178 if config_path.exists() {
2179 if *config_name == "pyproject.toml" {
2181 if let Ok(content) = std::fs::read_to_string(&config_path) {
2182 if content.contains("[tool.rumdl]") || content.contains("tool.rumdl") {
2183 log::debug!("[rumdl-config] Found config file: {}", config_path.display());
2184 found_config = Some((config_path.clone(), current_dir.clone()));
2186 break;
2187 }
2188 log::debug!("[rumdl-config] Found pyproject.toml but no [tool.rumdl] section");
2189 continue;
2190 }
2191 } else {
2192 log::debug!("[rumdl-config] Found config file: {}", config_path.display());
2193 found_config = Some((config_path.clone(), current_dir.clone()));
2195 break;
2196 }
2197 }
2198 }
2199 }
2200
2201 if current_dir.join(".git").exists() {
2203 log::debug!("[rumdl-config] Stopping at .git directory");
2204 break;
2205 }
2206
2207 match current_dir.parent() {
2209 Some(parent) => {
2210 current_dir = parent.to_owned();
2211 depth += 1;
2212 }
2213 None => {
2214 log::debug!("[rumdl-config] Reached filesystem root");
2215 break;
2216 }
2217 }
2218 }
2219
2220 if let Some((config_path, config_dir)) = found_config {
2222 let project_root = Self::find_project_root_from(&config_dir);
2223 return Some((config_path, project_root));
2224 }
2225
2226 None
2227 }
2228
2229 fn discover_markdownlint_config_upward() -> Option<std::path::PathBuf> {
2233 use std::env;
2234
2235 const MAX_DEPTH: usize = 100;
2236
2237 let start_dir = match env::current_dir() {
2238 Ok(dir) => dir,
2239 Err(e) => {
2240 log::debug!("[rumdl-config] Failed to get current directory for markdownlint discovery: {e}");
2241 return None;
2242 }
2243 };
2244
2245 let mut current_dir = start_dir.clone();
2246 let mut depth = 0;
2247
2248 loop {
2249 if depth >= MAX_DEPTH {
2250 log::debug!("[rumdl-config] Maximum traversal depth reached for markdownlint discovery");
2251 break;
2252 }
2253
2254 log::debug!(
2255 "[rumdl-config] Searching for markdownlint config in: {}",
2256 current_dir.display()
2257 );
2258
2259 for config_name in MARKDOWNLINT_CONFIG_FILES {
2261 let config_path = current_dir.join(config_name);
2262 if config_path.exists() {
2263 log::debug!("[rumdl-config] Found markdownlint config: {}", config_path.display());
2264 return Some(config_path);
2265 }
2266 }
2267
2268 if current_dir.join(".git").exists() {
2270 log::debug!("[rumdl-config] Stopping markdownlint search at .git directory");
2271 break;
2272 }
2273
2274 match current_dir.parent() {
2276 Some(parent) => {
2277 current_dir = parent.to_owned();
2278 depth += 1;
2279 }
2280 None => {
2281 log::debug!("[rumdl-config] Reached filesystem root during markdownlint search");
2282 break;
2283 }
2284 }
2285 }
2286
2287 None
2288 }
2289
2290 fn user_configuration_path_impl(config_dir: &Path) -> Option<std::path::PathBuf> {
2292 let config_dir = config_dir.join("rumdl");
2293
2294 const USER_CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml", "pyproject.toml"];
2296
2297 log::debug!(
2298 "[rumdl-config] Checking for user configuration in: {}",
2299 config_dir.display()
2300 );
2301
2302 for filename in USER_CONFIG_FILES {
2303 let config_path = config_dir.join(filename);
2304
2305 if config_path.exists() {
2306 if *filename == "pyproject.toml" {
2308 if let Ok(content) = std::fs::read_to_string(&config_path) {
2309 if content.contains("[tool.rumdl]") || content.contains("tool.rumdl") {
2310 log::debug!("[rumdl-config] Found user configuration at: {}", config_path.display());
2311 return Some(config_path);
2312 }
2313 log::debug!("[rumdl-config] Found user pyproject.toml but no [tool.rumdl] section");
2314 continue;
2315 }
2316 } else {
2317 log::debug!("[rumdl-config] Found user configuration at: {}", config_path.display());
2318 return Some(config_path);
2319 }
2320 }
2321 }
2322
2323 log::debug!(
2324 "[rumdl-config] No user configuration found in: {}",
2325 config_dir.display()
2326 );
2327 None
2328 }
2329
2330 #[cfg(feature = "native")]
2333 fn user_configuration_path() -> Option<std::path::PathBuf> {
2334 use etcetera::{BaseStrategy, choose_base_strategy};
2335
2336 match choose_base_strategy() {
2337 Ok(strategy) => {
2338 let config_dir = strategy.config_dir();
2339 Self::user_configuration_path_impl(&config_dir)
2340 }
2341 Err(e) => {
2342 log::debug!("[rumdl-config] Failed to determine user config directory: {e}");
2343 None
2344 }
2345 }
2346 }
2347
2348 #[cfg(not(feature = "native"))]
2350 fn user_configuration_path() -> Option<std::path::PathBuf> {
2351 None
2352 }
2353
2354 fn load_explicit_config(sourced_config: &mut Self, path: &str) -> Result<(), ConfigError> {
2356 let path_obj = Path::new(path);
2357 let filename = path_obj.file_name().and_then(|name| name.to_str()).unwrap_or("");
2358 let path_str = path.to_string();
2359
2360 log::debug!("[rumdl-config] Loading explicit config file: {filename}");
2361
2362 if let Some(config_parent) = path_obj.parent() {
2364 let project_root = Self::find_project_root_from(config_parent);
2365 log::debug!(
2366 "[rumdl-config] Project root (from explicit config): {}",
2367 project_root.display()
2368 );
2369 sourced_config.project_root = Some(project_root);
2370 }
2371
2372 const MARKDOWNLINT_FILENAMES: &[&str] = &[".markdownlint.json", ".markdownlint.yaml", ".markdownlint.yml"];
2374
2375 if filename == "pyproject.toml" || filename == ".rumdl.toml" || filename == "rumdl.toml" {
2376 let content = std::fs::read_to_string(path).map_err(|e| ConfigError::IoError {
2377 source: e,
2378 path: path_str.clone(),
2379 })?;
2380 if filename == "pyproject.toml" {
2381 if let Some(fragment) = parse_pyproject_toml(&content, &path_str)? {
2382 sourced_config.merge(fragment);
2383 sourced_config.loaded_files.push(path_str);
2384 }
2385 } else {
2386 let fragment = parse_rumdl_toml(&content, &path_str, ConfigSource::ProjectConfig)?;
2387 sourced_config.merge(fragment);
2388 sourced_config.loaded_files.push(path_str);
2389 }
2390 } else if MARKDOWNLINT_FILENAMES.contains(&filename)
2391 || path_str.ends_with(".json")
2392 || path_str.ends_with(".jsonc")
2393 || path_str.ends_with(".yaml")
2394 || path_str.ends_with(".yml")
2395 {
2396 let fragment = load_from_markdownlint(&path_str)?;
2398 sourced_config.merge(fragment);
2399 sourced_config.loaded_files.push(path_str);
2400 } else {
2401 let content = std::fs::read_to_string(path).map_err(|e| ConfigError::IoError {
2403 source: e,
2404 path: path_str.clone(),
2405 })?;
2406 let fragment = parse_rumdl_toml(&content, &path_str, ConfigSource::ProjectConfig)?;
2407 sourced_config.merge(fragment);
2408 sourced_config.loaded_files.push(path_str);
2409 }
2410
2411 Ok(())
2412 }
2413
2414 fn load_user_config_as_fallback(
2416 sourced_config: &mut Self,
2417 user_config_dir: Option<&Path>,
2418 ) -> Result<(), ConfigError> {
2419 let user_config_path = if let Some(dir) = user_config_dir {
2420 Self::user_configuration_path_impl(dir)
2421 } else {
2422 Self::user_configuration_path()
2423 };
2424
2425 if let Some(user_config_path) = user_config_path {
2426 let path_str = user_config_path.display().to_string();
2427 let filename = user_config_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
2428
2429 log::debug!("[rumdl-config] Loading user config as fallback: {path_str}");
2430
2431 if filename == "pyproject.toml" {
2432 let content = std::fs::read_to_string(&user_config_path).map_err(|e| ConfigError::IoError {
2433 source: e,
2434 path: path_str.clone(),
2435 })?;
2436 if let Some(fragment) = parse_pyproject_toml(&content, &path_str)? {
2437 sourced_config.merge(fragment);
2438 sourced_config.loaded_files.push(path_str);
2439 }
2440 } else {
2441 let content = std::fs::read_to_string(&user_config_path).map_err(|e| ConfigError::IoError {
2442 source: e,
2443 path: path_str.clone(),
2444 })?;
2445 let fragment = parse_rumdl_toml(&content, &path_str, ConfigSource::UserConfig)?;
2446 sourced_config.merge(fragment);
2447 sourced_config.loaded_files.push(path_str);
2448 }
2449 } else {
2450 log::debug!("[rumdl-config] No user configuration file found");
2451 }
2452
2453 Ok(())
2454 }
2455
2456 #[doc(hidden)]
2458 pub fn load_with_discovery_impl(
2459 config_path: Option<&str>,
2460 cli_overrides: Option<&SourcedGlobalConfig>,
2461 skip_auto_discovery: bool,
2462 user_config_dir: Option<&Path>,
2463 ) -> Result<Self, ConfigError> {
2464 use std::env;
2465 log::debug!("[rumdl-config] Current working directory: {:?}", env::current_dir());
2466
2467 let mut sourced_config = SourcedConfig::default();
2468
2469 if let Some(path) = config_path {
2482 log::debug!("[rumdl-config] Explicit config_path provided: {path:?}");
2484 Self::load_explicit_config(&mut sourced_config, path)?;
2485 } else if skip_auto_discovery {
2486 log::debug!("[rumdl-config] Skipping config discovery due to --no-config/--isolated flag");
2487 } else {
2489 log::debug!("[rumdl-config] No explicit config_path, searching default locations");
2491
2492 if let Some((config_file, project_root)) = Self::discover_config_upward() {
2494 let path_str = config_file.display().to_string();
2496 let filename = config_file.file_name().and_then(|n| n.to_str()).unwrap_or("");
2497
2498 log::debug!("[rumdl-config] Found project config: {path_str}");
2499 log::debug!("[rumdl-config] Project root: {}", project_root.display());
2500
2501 sourced_config.project_root = Some(project_root);
2502
2503 if filename == "pyproject.toml" {
2504 let content = std::fs::read_to_string(&config_file).map_err(|e| ConfigError::IoError {
2505 source: e,
2506 path: path_str.clone(),
2507 })?;
2508 if let Some(fragment) = parse_pyproject_toml(&content, &path_str)? {
2509 sourced_config.merge(fragment);
2510 sourced_config.loaded_files.push(path_str);
2511 }
2512 } else if filename == ".rumdl.toml" || filename == "rumdl.toml" {
2513 let content = std::fs::read_to_string(&config_file).map_err(|e| ConfigError::IoError {
2514 source: e,
2515 path: path_str.clone(),
2516 })?;
2517 let fragment = parse_rumdl_toml(&content, &path_str, ConfigSource::ProjectConfig)?;
2518 sourced_config.merge(fragment);
2519 sourced_config.loaded_files.push(path_str);
2520 }
2521 } else {
2522 log::debug!("[rumdl-config] No rumdl config found, checking markdownlint config");
2524
2525 if let Some(markdownlint_path) = Self::discover_markdownlint_config_upward() {
2526 let path_str = markdownlint_path.display().to_string();
2527 log::debug!("[rumdl-config] Found markdownlint config: {path_str}");
2528 match load_from_markdownlint(&path_str) {
2529 Ok(fragment) => {
2530 sourced_config.merge(fragment);
2531 sourced_config.loaded_files.push(path_str);
2532 }
2533 Err(_e) => {
2534 log::debug!("[rumdl-config] Failed to load markdownlint config, trying user config");
2535 Self::load_user_config_as_fallback(&mut sourced_config, user_config_dir)?;
2536 }
2537 }
2538 } else {
2539 log::debug!("[rumdl-config] No project config found, using user config as fallback");
2541 Self::load_user_config_as_fallback(&mut sourced_config, user_config_dir)?;
2542 }
2543 }
2544 }
2545
2546 if let Some(cli) = cli_overrides {
2548 sourced_config
2549 .global
2550 .enable
2551 .merge_override(cli.enable.value.clone(), ConfigSource::Cli, None, None);
2552 sourced_config
2553 .global
2554 .disable
2555 .merge_override(cli.disable.value.clone(), ConfigSource::Cli, None, None);
2556 sourced_config
2557 .global
2558 .exclude
2559 .merge_override(cli.exclude.value.clone(), ConfigSource::Cli, None, None);
2560 sourced_config
2561 .global
2562 .include
2563 .merge_override(cli.include.value.clone(), ConfigSource::Cli, None, None);
2564 sourced_config.global.respect_gitignore.merge_override(
2565 cli.respect_gitignore.value,
2566 ConfigSource::Cli,
2567 None,
2568 None,
2569 );
2570 sourced_config
2571 .global
2572 .fixable
2573 .merge_override(cli.fixable.value.clone(), ConfigSource::Cli, None, None);
2574 sourced_config
2575 .global
2576 .unfixable
2577 .merge_override(cli.unfixable.value.clone(), ConfigSource::Cli, None, None);
2578 }
2580
2581 Ok(sourced_config)
2584 }
2585
2586 pub fn load_with_discovery(
2589 config_path: Option<&str>,
2590 cli_overrides: Option<&SourcedGlobalConfig>,
2591 skip_auto_discovery: bool,
2592 ) -> Result<Self, ConfigError> {
2593 Self::load_with_discovery_impl(config_path, cli_overrides, skip_auto_discovery, None)
2594 }
2595
2596 pub fn validate(self, registry: &RuleRegistry) -> Result<SourcedConfig<ConfigValidated>, ConfigError> {
2610 let warnings = validate_config_sourced_internal(&self, registry);
2611
2612 Ok(SourcedConfig {
2613 global: self.global,
2614 per_file_ignores: self.per_file_ignores,
2615 rules: self.rules,
2616 loaded_files: self.loaded_files,
2617 unknown_keys: self.unknown_keys,
2618 project_root: self.project_root,
2619 validation_warnings: warnings,
2620 _state: PhantomData,
2621 })
2622 }
2623
2624 pub fn validate_into(self, registry: &RuleRegistry) -> Result<(Config, Vec<ConfigValidationWarning>), ConfigError> {
2629 let validated = self.validate(registry)?;
2630 let warnings = validated.validation_warnings.clone();
2631 Ok((validated.into(), warnings))
2632 }
2633
2634 pub fn into_validated_unchecked(self) -> SourcedConfig<ConfigValidated> {
2645 SourcedConfig {
2646 global: self.global,
2647 per_file_ignores: self.per_file_ignores,
2648 rules: self.rules,
2649 loaded_files: self.loaded_files,
2650 unknown_keys: self.unknown_keys,
2651 project_root: self.project_root,
2652 validation_warnings: Vec::new(),
2653 _state: PhantomData,
2654 }
2655 }
2656}
2657
2658impl From<SourcedConfig<ConfigValidated>> for Config {
2663 fn from(sourced: SourcedConfig<ConfigValidated>) -> Self {
2664 let mut rules = BTreeMap::new();
2665 for (rule_name, sourced_rule_cfg) in sourced.rules {
2666 let normalized_rule_name = rule_name.to_ascii_uppercase();
2668 let severity = sourced_rule_cfg.severity.map(|sv| sv.value);
2669 let mut values = BTreeMap::new();
2670 for (key, sourced_val) in sourced_rule_cfg.values {
2671 values.insert(key, sourced_val.value);
2672 }
2673 rules.insert(normalized_rule_name, RuleConfig { severity, values });
2674 }
2675 #[allow(deprecated)]
2676 let global = GlobalConfig {
2677 enable: sourced.global.enable.value,
2678 disable: sourced.global.disable.value,
2679 exclude: sourced.global.exclude.value,
2680 include: sourced.global.include.value,
2681 respect_gitignore: sourced.global.respect_gitignore.value,
2682 line_length: sourced.global.line_length.value,
2683 output_format: sourced.global.output_format.as_ref().map(|v| v.value.clone()),
2684 fixable: sourced.global.fixable.value,
2685 unfixable: sourced.global.unfixable.value,
2686 flavor: sourced.global.flavor.value,
2687 force_exclude: sourced.global.force_exclude.value,
2688 cache_dir: sourced.global.cache_dir.as_ref().map(|v| v.value.clone()),
2689 cache: sourced.global.cache.value,
2690 };
2691 Config {
2692 global,
2693 per_file_ignores: sourced.per_file_ignores.value,
2694 rules,
2695 project_root: sourced.project_root,
2696 }
2697 }
2698}
2699
2700pub struct RuleRegistry {
2702 pub rule_schemas: std::collections::BTreeMap<String, toml::map::Map<String, toml::Value>>,
2704 pub rule_aliases: std::collections::BTreeMap<String, std::collections::HashMap<String, String>>,
2706}
2707
2708impl RuleRegistry {
2709 pub fn from_rules(rules: &[Box<dyn Rule>]) -> Self {
2711 let mut rule_schemas = std::collections::BTreeMap::new();
2712 let mut rule_aliases = std::collections::BTreeMap::new();
2713
2714 for rule in rules {
2715 let norm_name = if let Some((name, toml::Value::Table(table))) = rule.default_config_section() {
2716 let norm_name = normalize_key(&name); rule_schemas.insert(norm_name.clone(), table);
2718 norm_name
2719 } else {
2720 let norm_name = normalize_key(rule.name()); rule_schemas.insert(norm_name.clone(), toml::map::Map::new());
2722 norm_name
2723 };
2724
2725 if let Some(aliases) = rule.config_aliases() {
2727 rule_aliases.insert(norm_name, aliases);
2728 }
2729 }
2730
2731 RuleRegistry {
2732 rule_schemas,
2733 rule_aliases,
2734 }
2735 }
2736
2737 pub fn rule_names(&self) -> std::collections::BTreeSet<String> {
2739 self.rule_schemas.keys().cloned().collect()
2740 }
2741
2742 pub fn config_keys_for(&self, rule: &str) -> Option<std::collections::BTreeSet<String>> {
2744 self.rule_schemas.get(rule).map(|schema| {
2745 let mut all_keys = std::collections::BTreeSet::new();
2746
2747 all_keys.insert("severity".to_string());
2749
2750 for key in schema.keys() {
2752 all_keys.insert(key.clone());
2753 }
2754
2755 for key in schema.keys() {
2757 all_keys.insert(key.replace('_', "-"));
2759 all_keys.insert(key.replace('-', "_"));
2761 all_keys.insert(normalize_key(key));
2763 }
2764
2765 if let Some(aliases) = self.rule_aliases.get(rule) {
2767 for alias_key in aliases.keys() {
2768 all_keys.insert(alias_key.clone());
2769 all_keys.insert(alias_key.replace('_', "-"));
2771 all_keys.insert(alias_key.replace('-', "_"));
2772 all_keys.insert(normalize_key(alias_key));
2773 }
2774 }
2775
2776 all_keys
2777 })
2778 }
2779
2780 pub fn expected_value_for(&self, rule: &str, key: &str) -> Option<&toml::Value> {
2782 if let Some(schema) = self.rule_schemas.get(rule) {
2783 if let Some(aliases) = self.rule_aliases.get(rule)
2785 && let Some(canonical_key) = aliases.get(key)
2786 {
2787 if let Some(value) = schema.get(canonical_key) {
2789 return Some(value);
2790 }
2791 }
2792
2793 if let Some(value) = schema.get(key) {
2795 return Some(value);
2796 }
2797
2798 let key_variants = [
2800 key.replace('-', "_"), key.replace('_', "-"), normalize_key(key), ];
2804
2805 for variant in &key_variants {
2806 if let Some(value) = schema.get(variant) {
2807 return Some(value);
2808 }
2809 }
2810 }
2811 None
2812 }
2813
2814 pub fn resolve_rule_name(&self, name: &str) -> Option<String> {
2821 let normalized = normalize_key(name);
2823 if self.rule_schemas.contains_key(&normalized) {
2824 return Some(normalized);
2825 }
2826
2827 resolve_rule_name_alias(name).map(|s| s.to_string())
2829 }
2830}
2831
2832static RULE_ALIAS_MAP: phf::Map<&'static str, &'static str> = phf::phf_map! {
2835 "MD001" => "MD001",
2837 "MD003" => "MD003",
2838 "MD004" => "MD004",
2839 "MD005" => "MD005",
2840 "MD007" => "MD007",
2841 "MD008" => "MD008",
2842 "MD009" => "MD009",
2843 "MD010" => "MD010",
2844 "MD011" => "MD011",
2845 "MD012" => "MD012",
2846 "MD013" => "MD013",
2847 "MD014" => "MD014",
2848 "MD015" => "MD015",
2849 "MD018" => "MD018",
2850 "MD019" => "MD019",
2851 "MD020" => "MD020",
2852 "MD021" => "MD021",
2853 "MD022" => "MD022",
2854 "MD023" => "MD023",
2855 "MD024" => "MD024",
2856 "MD025" => "MD025",
2857 "MD026" => "MD026",
2858 "MD027" => "MD027",
2859 "MD028" => "MD028",
2860 "MD029" => "MD029",
2861 "MD030" => "MD030",
2862 "MD031" => "MD031",
2863 "MD032" => "MD032",
2864 "MD033" => "MD033",
2865 "MD034" => "MD034",
2866 "MD035" => "MD035",
2867 "MD036" => "MD036",
2868 "MD037" => "MD037",
2869 "MD038" => "MD038",
2870 "MD039" => "MD039",
2871 "MD040" => "MD040",
2872 "MD041" => "MD041",
2873 "MD042" => "MD042",
2874 "MD043" => "MD043",
2875 "MD044" => "MD044",
2876 "MD045" => "MD045",
2877 "MD046" => "MD046",
2878 "MD047" => "MD047",
2879 "MD048" => "MD048",
2880 "MD049" => "MD049",
2881 "MD050" => "MD050",
2882 "MD051" => "MD051",
2883 "MD052" => "MD052",
2884 "MD053" => "MD053",
2885 "MD054" => "MD054",
2886 "MD055" => "MD055",
2887 "MD056" => "MD056",
2888 "MD057" => "MD057",
2889 "MD058" => "MD058",
2890 "MD059" => "MD059",
2891 "MD060" => "MD060",
2892 "MD061" => "MD061",
2893 "MD062" => "MD062",
2894 "MD063" => "MD063",
2895 "MD064" => "MD064",
2896 "MD065" => "MD065",
2897 "MD066" => "MD066",
2898 "MD067" => "MD067",
2899 "MD068" => "MD068",
2900 "MD069" => "MD069",
2901
2902 "HEADING-INCREMENT" => "MD001",
2904 "HEADING-STYLE" => "MD003",
2905 "UL-STYLE" => "MD004",
2906 "LIST-INDENT" => "MD005",
2907 "UL-INDENT" => "MD007",
2908 "NO-TRAILING-SPACES" => "MD009",
2909 "NO-HARD-TABS" => "MD010",
2910 "NO-REVERSED-LINKS" => "MD011",
2911 "NO-MULTIPLE-BLANKS" => "MD012",
2912 "LINE-LENGTH" => "MD013",
2913 "COMMANDS-SHOW-OUTPUT" => "MD014",
2914 "NO-MISSING-SPACE-AFTER-LIST-MARKER" => "MD015",
2915 "NO-MISSING-SPACE-ATX" => "MD018",
2916 "NO-MULTIPLE-SPACE-ATX" => "MD019",
2917 "NO-MISSING-SPACE-CLOSED-ATX" => "MD020",
2918 "NO-MULTIPLE-SPACE-CLOSED-ATX" => "MD021",
2919 "BLANKS-AROUND-HEADINGS" => "MD022",
2920 "HEADING-START-LEFT" => "MD023",
2921 "NO-DUPLICATE-HEADING" => "MD024",
2922 "SINGLE-TITLE" => "MD025",
2923 "SINGLE-H1" => "MD025",
2924 "NO-TRAILING-PUNCTUATION" => "MD026",
2925 "NO-MULTIPLE-SPACE-BLOCKQUOTE" => "MD027",
2926 "NO-BLANKS-BLOCKQUOTE" => "MD028",
2927 "OL-PREFIX" => "MD029",
2928 "LIST-MARKER-SPACE" => "MD030",
2929 "BLANKS-AROUND-FENCES" => "MD031",
2930 "BLANKS-AROUND-LISTS" => "MD032",
2931 "NO-INLINE-HTML" => "MD033",
2932 "NO-BARE-URLS" => "MD034",
2933 "HR-STYLE" => "MD035",
2934 "NO-EMPHASIS-AS-HEADING" => "MD036",
2935 "NO-SPACE-IN-EMPHASIS" => "MD037",
2936 "NO-SPACE-IN-CODE" => "MD038",
2937 "NO-SPACE-IN-LINKS" => "MD039",
2938 "FENCED-CODE-LANGUAGE" => "MD040",
2939 "FIRST-LINE-HEADING" => "MD041",
2940 "FIRST-LINE-H1" => "MD041",
2941 "NO-EMPTY-LINKS" => "MD042",
2942 "REQUIRED-HEADINGS" => "MD043",
2943 "PROPER-NAMES" => "MD044",
2944 "NO-ALT-TEXT" => "MD045",
2945 "CODE-BLOCK-STYLE" => "MD046",
2946 "SINGLE-TRAILING-NEWLINE" => "MD047",
2947 "CODE-FENCE-STYLE" => "MD048",
2948 "EMPHASIS-STYLE" => "MD049",
2949 "STRONG-STYLE" => "MD050",
2950 "LINK-FRAGMENTS" => "MD051",
2951 "REFERENCE-LINKS-IMAGES" => "MD052",
2952 "LINK-IMAGE-REFERENCE-DEFINITIONS" => "MD053",
2953 "LINK-IMAGE-STYLE" => "MD054",
2954 "TABLE-PIPE-STYLE" => "MD055",
2955 "TABLE-COLUMN-COUNT" => "MD056",
2956 "EXISTING-RELATIVE-LINKS" => "MD057",
2957 "BLANKS-AROUND-TABLES" => "MD058",
2958 "TABLE-CELL-ALIGNMENT" => "MD059",
2959 "TABLE-FORMAT" => "MD060",
2960 "FORBIDDEN-TERMS" => "MD061",
2961 "LINK-DESTINATION-WHITESPACE" => "MD062",
2962 "HEADING-CAPITALIZATION" => "MD063",
2963 "NO-MULTIPLE-CONSECUTIVE-SPACES" => "MD064",
2964 "BLANKS-AROUND-HORIZONTAL-RULES" => "MD065",
2965 "FOOTNOTE-VALIDATION" => "MD066",
2966 "FOOTNOTE-DEFINITION-ORDER" => "MD067",
2967 "EMPTY-FOOTNOTE-DEFINITION" => "MD068",
2968 "NO-DUPLICATE-LIST-MARKERS" => "MD069",
2969};
2970
2971pub(crate) fn resolve_rule_name_alias(key: &str) -> Option<&'static str> {
2975 let normalized_key = key.to_ascii_uppercase().replace('_', "-");
2977
2978 RULE_ALIAS_MAP.get(normalized_key.as_str()).copied()
2980}
2981
2982#[derive(Debug, Clone)]
2984pub struct ConfigValidationWarning {
2985 pub message: String,
2986 pub rule: Option<String>,
2987 pub key: Option<String>,
2988}
2989
2990fn validate_config_sourced_internal<S>(
2993 sourced: &SourcedConfig<S>,
2994 registry: &RuleRegistry,
2995) -> Vec<ConfigValidationWarning> {
2996 validate_config_sourced_impl(&sourced.rules, &sourced.unknown_keys, registry)
2997}
2998
2999fn validate_config_sourced_impl(
3001 rules: &BTreeMap<String, SourcedRuleConfig>,
3002 unknown_keys: &[(String, String, Option<String>)],
3003 registry: &RuleRegistry,
3004) -> Vec<ConfigValidationWarning> {
3005 let mut warnings = Vec::new();
3006 let known_rules = registry.rule_names();
3007 for rule in rules.keys() {
3009 if !known_rules.contains(rule) {
3010 let all_rule_names: Vec<String> = RULE_ALIAS_MAP.keys().map(|s| s.to_string()).collect();
3012 let message = if let Some(suggestion) = suggest_similar_key(rule, &all_rule_names) {
3013 let formatted_suggestion = if suggestion.starts_with("MD") {
3015 suggestion
3016 } else {
3017 suggestion.to_lowercase()
3018 };
3019 format!("Unknown rule in config: {rule} (did you mean: {formatted_suggestion}?)")
3020 } else {
3021 format!("Unknown rule in config: {rule}")
3022 };
3023 warnings.push(ConfigValidationWarning {
3024 message,
3025 rule: Some(rule.clone()),
3026 key: None,
3027 });
3028 }
3029 }
3030 for (rule, rule_cfg) in rules {
3032 if let Some(valid_keys) = registry.config_keys_for(rule) {
3033 for key in rule_cfg.values.keys() {
3034 if !valid_keys.contains(key) {
3035 let valid_keys_vec: Vec<String> = valid_keys.iter().cloned().collect();
3036 let message = if let Some(suggestion) = suggest_similar_key(key, &valid_keys_vec) {
3037 format!("Unknown option for rule {rule}: {key} (did you mean: {suggestion}?)")
3038 } else {
3039 format!("Unknown option for rule {rule}: {key}")
3040 };
3041 warnings.push(ConfigValidationWarning {
3042 message,
3043 rule: Some(rule.clone()),
3044 key: Some(key.clone()),
3045 });
3046 } else {
3047 if let Some(expected) = registry.expected_value_for(rule, key) {
3049 let actual = &rule_cfg.values[key].value;
3050 if !toml_value_type_matches(expected, actual) {
3051 warnings.push(ConfigValidationWarning {
3052 message: format!(
3053 "Type mismatch for {}.{}: expected {}, got {}",
3054 rule,
3055 key,
3056 toml_type_name(expected),
3057 toml_type_name(actual)
3058 ),
3059 rule: Some(rule.clone()),
3060 key: Some(key.clone()),
3061 });
3062 }
3063 }
3064 }
3065 }
3066 }
3067 }
3068 let known_global_keys = vec![
3070 "enable".to_string(),
3071 "disable".to_string(),
3072 "include".to_string(),
3073 "exclude".to_string(),
3074 "respect-gitignore".to_string(),
3075 "line-length".to_string(),
3076 "fixable".to_string(),
3077 "unfixable".to_string(),
3078 "flavor".to_string(),
3079 "force-exclude".to_string(),
3080 "output-format".to_string(),
3081 "cache-dir".to_string(),
3082 "cache".to_string(),
3083 ];
3084
3085 for (section, key, file_path) in unknown_keys {
3086 if section.contains("[global]") || section.contains("[tool.rumdl]") {
3087 let message = if let Some(suggestion) = suggest_similar_key(key, &known_global_keys) {
3088 if let Some(path) = file_path {
3089 format!("Unknown global option in {path}: {key} (did you mean: {suggestion}?)")
3090 } else {
3091 format!("Unknown global option: {key} (did you mean: {suggestion}?)")
3092 }
3093 } else if let Some(path) = file_path {
3094 format!("Unknown global option in {path}: {key}")
3095 } else {
3096 format!("Unknown global option: {key}")
3097 };
3098 warnings.push(ConfigValidationWarning {
3099 message,
3100 rule: None,
3101 key: Some(key.clone()),
3102 });
3103 } else if !key.is_empty() {
3104 continue;
3106 } else {
3107 let rule_name = section.trim_matches(|c| c == '[' || c == ']');
3109 let all_rule_names: Vec<String> = RULE_ALIAS_MAP.keys().map(|s| s.to_string()).collect();
3110 let message = if let Some(suggestion) = suggest_similar_key(rule_name, &all_rule_names) {
3111 let formatted_suggestion = if suggestion.starts_with("MD") {
3113 suggestion
3114 } else {
3115 suggestion.to_lowercase()
3116 };
3117 if let Some(path) = file_path {
3118 format!("Unknown rule in {path}: {rule_name} (did you mean: {formatted_suggestion}?)")
3119 } else {
3120 format!("Unknown rule in config: {rule_name} (did you mean: {formatted_suggestion}?)")
3121 }
3122 } else if let Some(path) = file_path {
3123 format!("Unknown rule in {path}: {rule_name}")
3124 } else {
3125 format!("Unknown rule in config: {rule_name}")
3126 };
3127 warnings.push(ConfigValidationWarning {
3128 message,
3129 rule: None,
3130 key: None,
3131 });
3132 }
3133 }
3134 warnings
3135}
3136
3137pub fn validate_config_sourced(
3143 sourced: &SourcedConfig<ConfigLoaded>,
3144 registry: &RuleRegistry,
3145) -> Vec<ConfigValidationWarning> {
3146 validate_config_sourced_internal(sourced, registry)
3147}
3148
3149pub fn validate_config_sourced_validated(
3153 sourced: &SourcedConfig<ConfigValidated>,
3154 _registry: &RuleRegistry,
3155) -> Vec<ConfigValidationWarning> {
3156 sourced.validation_warnings.clone()
3157}
3158
3159fn toml_type_name(val: &toml::Value) -> &'static str {
3160 match val {
3161 toml::Value::String(_) => "string",
3162 toml::Value::Integer(_) => "integer",
3163 toml::Value::Float(_) => "float",
3164 toml::Value::Boolean(_) => "boolean",
3165 toml::Value::Array(_) => "array",
3166 toml::Value::Table(_) => "table",
3167 toml::Value::Datetime(_) => "datetime",
3168 }
3169}
3170
3171fn levenshtein_distance(s1: &str, s2: &str) -> usize {
3173 let len1 = s1.len();
3174 let len2 = s2.len();
3175
3176 if len1 == 0 {
3177 return len2;
3178 }
3179 if len2 == 0 {
3180 return len1;
3181 }
3182
3183 let s1_chars: Vec<char> = s1.chars().collect();
3184 let s2_chars: Vec<char> = s2.chars().collect();
3185
3186 let mut prev_row: Vec<usize> = (0..=len2).collect();
3187 let mut curr_row = vec![0; len2 + 1];
3188
3189 for i in 1..=len1 {
3190 curr_row[0] = i;
3191 for j in 1..=len2 {
3192 let cost = if s1_chars[i - 1] == s2_chars[j - 1] { 0 } else { 1 };
3193 curr_row[j] = (prev_row[j] + 1) .min(curr_row[j - 1] + 1) .min(prev_row[j - 1] + cost); }
3197 std::mem::swap(&mut prev_row, &mut curr_row);
3198 }
3199
3200 prev_row[len2]
3201}
3202
3203fn suggest_similar_key(unknown: &str, valid_keys: &[String]) -> Option<String> {
3205 let unknown_lower = unknown.to_lowercase();
3206 let max_distance = 2.max(unknown.len() / 3); let mut best_match: Option<(String, usize)> = None;
3209
3210 for valid in valid_keys {
3211 let valid_lower = valid.to_lowercase();
3212 let distance = levenshtein_distance(&unknown_lower, &valid_lower);
3213
3214 if distance <= max_distance {
3215 if let Some((_, best_dist)) = &best_match {
3216 if distance < *best_dist {
3217 best_match = Some((valid.clone(), distance));
3218 }
3219 } else {
3220 best_match = Some((valid.clone(), distance));
3221 }
3222 }
3223 }
3224
3225 best_match.map(|(key, _)| key)
3226}
3227
3228fn toml_value_type_matches(expected: &toml::Value, actual: &toml::Value) -> bool {
3229 use toml::Value::*;
3230 match (expected, actual) {
3231 (String(_), String(_)) => true,
3232 (Integer(_), Integer(_)) => true,
3233 (Float(_), Float(_)) => true,
3234 (Boolean(_), Boolean(_)) => true,
3235 (Array(_), Array(_)) => true,
3236 (Table(_), Table(_)) => true,
3237 (Datetime(_), Datetime(_)) => true,
3238 (Float(_), Integer(_)) => true,
3240 _ => false,
3241 }
3242}
3243
3244fn parse_pyproject_toml(content: &str, path: &str) -> Result<Option<SourcedConfigFragment>, ConfigError> {
3246 let doc: toml::Value =
3247 toml::from_str(content).map_err(|e| ConfigError::ParseError(format!("{path}: Failed to parse TOML: {e}")))?;
3248 let mut fragment = SourcedConfigFragment::default();
3249 let source = ConfigSource::PyprojectToml;
3250 let file = Some(path.to_string());
3251
3252 let all_rules = rules::all_rules(&Config::default());
3254 let registry = RuleRegistry::from_rules(&all_rules);
3255
3256 if let Some(rumdl_config) = doc.get("tool").and_then(|t| t.get("rumdl"))
3258 && let Some(rumdl_table) = rumdl_config.as_table()
3259 {
3260 let extract_global_config = |fragment: &mut SourcedConfigFragment, table: &toml::value::Table| {
3262 if let Some(enable) = table.get("enable")
3264 && let Ok(values) = Vec::<String>::deserialize(enable.clone())
3265 {
3266 let normalized_values = values
3268 .into_iter()
3269 .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3270 .collect();
3271 fragment
3272 .global
3273 .enable
3274 .push_override(normalized_values, source, file.clone(), None);
3275 }
3276
3277 if let Some(disable) = table.get("disable")
3278 && let Ok(values) = Vec::<String>::deserialize(disable.clone())
3279 {
3280 let normalized_values: Vec<String> = values
3282 .into_iter()
3283 .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3284 .collect();
3285 fragment
3286 .global
3287 .disable
3288 .push_override(normalized_values, source, file.clone(), None);
3289 }
3290
3291 if let Some(include) = table.get("include")
3292 && let Ok(values) = Vec::<String>::deserialize(include.clone())
3293 {
3294 fragment
3295 .global
3296 .include
3297 .push_override(values, source, file.clone(), None);
3298 }
3299
3300 if let Some(exclude) = table.get("exclude")
3301 && let Ok(values) = Vec::<String>::deserialize(exclude.clone())
3302 {
3303 fragment
3304 .global
3305 .exclude
3306 .push_override(values, source, file.clone(), None);
3307 }
3308
3309 if let Some(respect_gitignore) = table
3310 .get("respect-gitignore")
3311 .or_else(|| table.get("respect_gitignore"))
3312 && let Ok(value) = bool::deserialize(respect_gitignore.clone())
3313 {
3314 fragment
3315 .global
3316 .respect_gitignore
3317 .push_override(value, source, file.clone(), None);
3318 }
3319
3320 if let Some(force_exclude) = table.get("force-exclude").or_else(|| table.get("force_exclude"))
3321 && let Ok(value) = bool::deserialize(force_exclude.clone())
3322 {
3323 fragment
3324 .global
3325 .force_exclude
3326 .push_override(value, source, file.clone(), None);
3327 }
3328
3329 if let Some(output_format) = table.get("output-format").or_else(|| table.get("output_format"))
3330 && let Ok(value) = String::deserialize(output_format.clone())
3331 {
3332 if fragment.global.output_format.is_none() {
3333 fragment.global.output_format = Some(SourcedValue::new(value.clone(), source));
3334 } else {
3335 fragment
3336 .global
3337 .output_format
3338 .as_mut()
3339 .unwrap()
3340 .push_override(value, source, file.clone(), None);
3341 }
3342 }
3343
3344 if let Some(fixable) = table.get("fixable")
3345 && let Ok(values) = Vec::<String>::deserialize(fixable.clone())
3346 {
3347 let normalized_values = values
3348 .into_iter()
3349 .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3350 .collect();
3351 fragment
3352 .global
3353 .fixable
3354 .push_override(normalized_values, source, file.clone(), None);
3355 }
3356
3357 if let Some(unfixable) = table.get("unfixable")
3358 && let Ok(values) = Vec::<String>::deserialize(unfixable.clone())
3359 {
3360 let normalized_values = values
3361 .into_iter()
3362 .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3363 .collect();
3364 fragment
3365 .global
3366 .unfixable
3367 .push_override(normalized_values, source, file.clone(), None);
3368 }
3369
3370 if let Some(flavor) = table.get("flavor")
3371 && let Ok(value) = MarkdownFlavor::deserialize(flavor.clone())
3372 {
3373 fragment.global.flavor.push_override(value, source, file.clone(), None);
3374 }
3375
3376 if let Some(line_length) = table.get("line-length").or_else(|| table.get("line_length"))
3378 && let Ok(value) = u64::deserialize(line_length.clone())
3379 {
3380 fragment
3381 .global
3382 .line_length
3383 .push_override(LineLength::new(value as usize), source, file.clone(), None);
3384
3385 let norm_md013_key = normalize_key("MD013");
3387 let rule_entry = fragment.rules.entry(norm_md013_key).or_default();
3388 let norm_line_length_key = normalize_key("line-length");
3389 let sv = rule_entry
3390 .values
3391 .entry(norm_line_length_key)
3392 .or_insert_with(|| SourcedValue::new(line_length.clone(), ConfigSource::Default));
3393 sv.push_override(line_length.clone(), source, file.clone(), None);
3394 }
3395
3396 if let Some(cache_dir) = table.get("cache-dir").or_else(|| table.get("cache_dir"))
3397 && let Ok(value) = String::deserialize(cache_dir.clone())
3398 {
3399 if fragment.global.cache_dir.is_none() {
3400 fragment.global.cache_dir = Some(SourcedValue::new(value.clone(), source));
3401 } else {
3402 fragment
3403 .global
3404 .cache_dir
3405 .as_mut()
3406 .unwrap()
3407 .push_override(value, source, file.clone(), None);
3408 }
3409 }
3410
3411 if let Some(cache) = table.get("cache")
3412 && let Ok(value) = bool::deserialize(cache.clone())
3413 {
3414 fragment.global.cache.push_override(value, source, file.clone(), None);
3415 }
3416 };
3417
3418 if let Some(global_table) = rumdl_table.get("global").and_then(|g| g.as_table()) {
3420 extract_global_config(&mut fragment, global_table);
3421 }
3422
3423 extract_global_config(&mut fragment, rumdl_table);
3425
3426 let per_file_ignores_key = rumdl_table
3429 .get("per-file-ignores")
3430 .or_else(|| rumdl_table.get("per_file_ignores"));
3431
3432 if let Some(per_file_ignores_value) = per_file_ignores_key
3433 && let Some(per_file_table) = per_file_ignores_value.as_table()
3434 {
3435 let mut per_file_map = HashMap::new();
3436 for (pattern, rules_value) in per_file_table {
3437 if let Ok(rules) = Vec::<String>::deserialize(rules_value.clone()) {
3438 let normalized_rules = rules
3439 .into_iter()
3440 .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3441 .collect();
3442 per_file_map.insert(pattern.clone(), normalized_rules);
3443 } else {
3444 log::warn!(
3445 "[WARN] Expected array for per-file-ignores pattern '{pattern}' in {path}, found {rules_value:?}"
3446 );
3447 }
3448 }
3449 fragment
3450 .per_file_ignores
3451 .push_override(per_file_map, source, file.clone(), None);
3452 }
3453
3454 for (key, value) in rumdl_table {
3456 let norm_rule_key = normalize_key(key);
3457
3458 let is_global_key = [
3461 "enable",
3462 "disable",
3463 "include",
3464 "exclude",
3465 "respect_gitignore",
3466 "respect-gitignore",
3467 "force_exclude",
3468 "force-exclude",
3469 "output_format",
3470 "output-format",
3471 "fixable",
3472 "unfixable",
3473 "per-file-ignores",
3474 "per_file_ignores",
3475 "global",
3476 "flavor",
3477 "cache_dir",
3478 "cache-dir",
3479 "cache",
3480 ]
3481 .contains(&norm_rule_key.as_str());
3482
3483 let is_line_length_global =
3485 (norm_rule_key == "line-length" || norm_rule_key == "line_length") && !value.is_table();
3486
3487 if is_global_key || is_line_length_global {
3488 continue;
3489 }
3490
3491 if let Some(resolved_rule_name) = registry.resolve_rule_name(key)
3493 && value.is_table()
3494 && let Some(rule_config_table) = value.as_table()
3495 {
3496 let rule_entry = fragment.rules.entry(resolved_rule_name.clone()).or_default();
3497 for (rk, rv) in rule_config_table {
3498 let norm_rk = normalize_key(rk);
3499
3500 if norm_rk == "severity" {
3502 if let Ok(severity) = crate::rule::Severity::deserialize(rv.clone()) {
3503 if rule_entry.severity.is_none() {
3504 rule_entry.severity = Some(SourcedValue::new(severity, source));
3505 } else {
3506 rule_entry.severity.as_mut().unwrap().push_override(
3507 severity,
3508 source,
3509 file.clone(),
3510 None,
3511 );
3512 }
3513 }
3514 continue; }
3516
3517 let toml_val = rv.clone();
3518
3519 let sv = rule_entry
3520 .values
3521 .entry(norm_rk.clone())
3522 .or_insert_with(|| SourcedValue::new(toml_val.clone(), ConfigSource::Default));
3523 sv.push_override(toml_val, source, file.clone(), None);
3524 }
3525 } else if registry.resolve_rule_name(key).is_none() {
3526 fragment
3529 .unknown_keys
3530 .push(("[tool.rumdl]".to_string(), key.to_string(), Some(path.to_string())));
3531 }
3532 }
3533 }
3534
3535 if let Some(tool_table) = doc.get("tool").and_then(|t| t.as_table()) {
3537 for (key, value) in tool_table.iter() {
3538 if let Some(rule_name) = key.strip_prefix("rumdl.") {
3539 if let Some(resolved_rule_name) = registry.resolve_rule_name(rule_name) {
3541 if let Some(rule_table) = value.as_table() {
3542 let rule_entry = fragment.rules.entry(resolved_rule_name.clone()).or_default();
3543 for (rk, rv) in rule_table {
3544 let norm_rk = normalize_key(rk);
3545
3546 if norm_rk == "severity" {
3548 if let Ok(severity) = crate::rule::Severity::deserialize(rv.clone()) {
3549 if rule_entry.severity.is_none() {
3550 rule_entry.severity = Some(SourcedValue::new(severity, source));
3551 } else {
3552 rule_entry.severity.as_mut().unwrap().push_override(
3553 severity,
3554 source,
3555 file.clone(),
3556 None,
3557 );
3558 }
3559 }
3560 continue; }
3562
3563 let toml_val = rv.clone();
3564 let sv = rule_entry
3565 .values
3566 .entry(norm_rk.clone())
3567 .or_insert_with(|| SourcedValue::new(toml_val.clone(), source));
3568 sv.push_override(toml_val, source, file.clone(), None);
3569 }
3570 }
3571 } else if rule_name.to_ascii_uppercase().starts_with("MD")
3572 || rule_name.chars().any(|c| c.is_alphabetic())
3573 {
3574 fragment.unknown_keys.push((
3576 format!("[tool.rumdl.{rule_name}]"),
3577 String::new(),
3578 Some(path.to_string()),
3579 ));
3580 }
3581 }
3582 }
3583 }
3584
3585 if let Some(doc_table) = doc.as_table() {
3587 for (key, value) in doc_table.iter() {
3588 if let Some(rule_name) = key.strip_prefix("tool.rumdl.") {
3589 if let Some(resolved_rule_name) = registry.resolve_rule_name(rule_name) {
3591 if let Some(rule_table) = value.as_table() {
3592 let rule_entry = fragment.rules.entry(resolved_rule_name.clone()).or_default();
3593 for (rk, rv) in rule_table {
3594 let norm_rk = normalize_key(rk);
3595
3596 if norm_rk == "severity" {
3598 if let Ok(severity) = crate::rule::Severity::deserialize(rv.clone()) {
3599 if rule_entry.severity.is_none() {
3600 rule_entry.severity = Some(SourcedValue::new(severity, source));
3601 } else {
3602 rule_entry.severity.as_mut().unwrap().push_override(
3603 severity,
3604 source,
3605 file.clone(),
3606 None,
3607 );
3608 }
3609 }
3610 continue; }
3612
3613 let toml_val = rv.clone();
3614 let sv = rule_entry
3615 .values
3616 .entry(norm_rk.clone())
3617 .or_insert_with(|| SourcedValue::new(toml_val.clone(), source));
3618 sv.push_override(toml_val, source, file.clone(), None);
3619 }
3620 }
3621 } else if rule_name.to_ascii_uppercase().starts_with("MD")
3622 || rule_name.chars().any(|c| c.is_alphabetic())
3623 {
3624 fragment.unknown_keys.push((
3626 format!("[tool.rumdl.{rule_name}]"),
3627 String::new(),
3628 Some(path.to_string()),
3629 ));
3630 }
3631 }
3632 }
3633 }
3634
3635 let has_any = !fragment.global.enable.value.is_empty()
3637 || !fragment.global.disable.value.is_empty()
3638 || !fragment.global.include.value.is_empty()
3639 || !fragment.global.exclude.value.is_empty()
3640 || !fragment.global.fixable.value.is_empty()
3641 || !fragment.global.unfixable.value.is_empty()
3642 || fragment.global.output_format.is_some()
3643 || fragment.global.cache_dir.is_some()
3644 || !fragment.global.cache.value
3645 || !fragment.per_file_ignores.value.is_empty()
3646 || !fragment.rules.is_empty();
3647 if has_any { Ok(Some(fragment)) } else { Ok(None) }
3648}
3649
3650fn parse_rumdl_toml(content: &str, path: &str, source: ConfigSource) -> Result<SourcedConfigFragment, ConfigError> {
3652 let doc = content
3653 .parse::<DocumentMut>()
3654 .map_err(|e| ConfigError::ParseError(format!("{path}: Failed to parse TOML: {e}")))?;
3655 let mut fragment = SourcedConfigFragment::default();
3656 let file = Some(path.to_string());
3658
3659 let all_rules = rules::all_rules(&Config::default());
3661 let registry = RuleRegistry::from_rules(&all_rules);
3662
3663 if let Some(global_item) = doc.get("global")
3665 && let Some(global_table) = global_item.as_table()
3666 {
3667 for (key, value_item) in global_table.iter() {
3668 let norm_key = normalize_key(key);
3669 match norm_key.as_str() {
3670 "enable" | "disable" | "include" | "exclude" => {
3671 if let Some(toml_edit::Value::Array(formatted_array)) = value_item.as_value() {
3672 let values: Vec<String> = formatted_array
3674 .iter()
3675 .filter_map(|item| item.as_str()) .map(|s| s.to_string())
3677 .collect();
3678
3679 let final_values = if norm_key == "enable" || norm_key == "disable" {
3681 values
3682 .into_iter()
3683 .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3684 .collect()
3685 } else {
3686 values
3687 };
3688
3689 match norm_key.as_str() {
3690 "enable" => fragment
3691 .global
3692 .enable
3693 .push_override(final_values, source, file.clone(), None),
3694 "disable" => {
3695 fragment
3696 .global
3697 .disable
3698 .push_override(final_values, source, file.clone(), None)
3699 }
3700 "include" => {
3701 fragment
3702 .global
3703 .include
3704 .push_override(final_values, source, file.clone(), None)
3705 }
3706 "exclude" => {
3707 fragment
3708 .global
3709 .exclude
3710 .push_override(final_values, source, file.clone(), None)
3711 }
3712 _ => unreachable!("Outer match guarantees only enable/disable/include/exclude"),
3713 }
3714 } else {
3715 log::warn!(
3716 "[WARN] Expected array for global key '{}' in {}, found {}",
3717 key,
3718 path,
3719 value_item.type_name()
3720 );
3721 }
3722 }
3723 "respect_gitignore" | "respect-gitignore" => {
3724 if let Some(toml_edit::Value::Boolean(formatted_bool)) = value_item.as_value() {
3726 let val = *formatted_bool.value();
3727 fragment
3728 .global
3729 .respect_gitignore
3730 .push_override(val, source, file.clone(), None);
3731 } else {
3732 log::warn!(
3733 "[WARN] Expected boolean for global key '{}' in {}, found {}",
3734 key,
3735 path,
3736 value_item.type_name()
3737 );
3738 }
3739 }
3740 "force_exclude" | "force-exclude" => {
3741 if let Some(toml_edit::Value::Boolean(formatted_bool)) = value_item.as_value() {
3743 let val = *formatted_bool.value();
3744 fragment
3745 .global
3746 .force_exclude
3747 .push_override(val, source, file.clone(), None);
3748 } else {
3749 log::warn!(
3750 "[WARN] Expected boolean for global key '{}' in {}, found {}",
3751 key,
3752 path,
3753 value_item.type_name()
3754 );
3755 }
3756 }
3757 "line_length" | "line-length" => {
3758 if let Some(toml_edit::Value::Integer(formatted_int)) = value_item.as_value() {
3760 let val = LineLength::new(*formatted_int.value() as usize);
3761 fragment
3762 .global
3763 .line_length
3764 .push_override(val, source, file.clone(), None);
3765 } else {
3766 log::warn!(
3767 "[WARN] Expected integer for global key '{}' in {}, found {}",
3768 key,
3769 path,
3770 value_item.type_name()
3771 );
3772 }
3773 }
3774 "output_format" | "output-format" => {
3775 if let Some(toml_edit::Value::String(formatted_string)) = value_item.as_value() {
3777 let val = formatted_string.value().clone();
3778 if fragment.global.output_format.is_none() {
3779 fragment.global.output_format = Some(SourcedValue::new(val.clone(), source));
3780 } else {
3781 fragment.global.output_format.as_mut().unwrap().push_override(
3782 val,
3783 source,
3784 file.clone(),
3785 None,
3786 );
3787 }
3788 } else {
3789 log::warn!(
3790 "[WARN] Expected string for global key '{}' in {}, found {}",
3791 key,
3792 path,
3793 value_item.type_name()
3794 );
3795 }
3796 }
3797 "cache_dir" | "cache-dir" => {
3798 if let Some(toml_edit::Value::String(formatted_string)) = value_item.as_value() {
3800 let val = formatted_string.value().clone();
3801 if fragment.global.cache_dir.is_none() {
3802 fragment.global.cache_dir = Some(SourcedValue::new(val.clone(), source));
3803 } else {
3804 fragment
3805 .global
3806 .cache_dir
3807 .as_mut()
3808 .unwrap()
3809 .push_override(val, source, file.clone(), None);
3810 }
3811 } else {
3812 log::warn!(
3813 "[WARN] Expected string for global key '{}' in {}, found {}",
3814 key,
3815 path,
3816 value_item.type_name()
3817 );
3818 }
3819 }
3820 "cache" => {
3821 if let Some(toml_edit::Value::Boolean(b)) = value_item.as_value() {
3822 let val = *b.value();
3823 fragment.global.cache.push_override(val, source, file.clone(), None);
3824 } else {
3825 log::warn!(
3826 "[WARN] Expected boolean for global key '{}' in {}, found {}",
3827 key,
3828 path,
3829 value_item.type_name()
3830 );
3831 }
3832 }
3833 "fixable" => {
3834 if let Some(toml_edit::Value::Array(formatted_array)) = value_item.as_value() {
3835 let values: Vec<String> = formatted_array
3836 .iter()
3837 .filter_map(|item| item.as_str())
3838 .map(normalize_key)
3839 .collect();
3840 fragment
3841 .global
3842 .fixable
3843 .push_override(values, source, file.clone(), None);
3844 } else {
3845 log::warn!(
3846 "[WARN] Expected array for global key '{}' in {}, found {}",
3847 key,
3848 path,
3849 value_item.type_name()
3850 );
3851 }
3852 }
3853 "unfixable" => {
3854 if let Some(toml_edit::Value::Array(formatted_array)) = value_item.as_value() {
3855 let values: Vec<String> = formatted_array
3856 .iter()
3857 .filter_map(|item| item.as_str())
3858 .map(|s| registry.resolve_rule_name(s).unwrap_or_else(|| normalize_key(s)))
3859 .collect();
3860 fragment
3861 .global
3862 .unfixable
3863 .push_override(values, source, file.clone(), None);
3864 } else {
3865 log::warn!(
3866 "[WARN] Expected array for global key '{}' in {}, found {}",
3867 key,
3868 path,
3869 value_item.type_name()
3870 );
3871 }
3872 }
3873 "flavor" => {
3874 if let Some(toml_edit::Value::String(formatted_string)) = value_item.as_value() {
3875 let val = formatted_string.value();
3876 if let Ok(flavor) = MarkdownFlavor::from_str(val) {
3877 fragment.global.flavor.push_override(flavor, source, file.clone(), None);
3878 } else {
3879 log::warn!("[WARN] Unknown markdown flavor '{val}' in {path}");
3880 }
3881 } else {
3882 log::warn!(
3883 "[WARN] Expected string for global key '{}' in {}, found {}",
3884 key,
3885 path,
3886 value_item.type_name()
3887 );
3888 }
3889 }
3890 _ => {
3891 fragment
3893 .unknown_keys
3894 .push(("[global]".to_string(), key.to_string(), Some(path.to_string())));
3895 log::warn!("[WARN] Unknown key in [global] section of {path}: {key}");
3896 }
3897 }
3898 }
3899 }
3900
3901 if let Some(per_file_item) = doc.get("per-file-ignores")
3903 && let Some(per_file_table) = per_file_item.as_table()
3904 {
3905 let mut per_file_map = HashMap::new();
3906 for (pattern, value_item) in per_file_table.iter() {
3907 if let Some(toml_edit::Value::Array(formatted_array)) = value_item.as_value() {
3908 let rules: Vec<String> = formatted_array
3909 .iter()
3910 .filter_map(|item| item.as_str())
3911 .map(|s| registry.resolve_rule_name(s).unwrap_or_else(|| normalize_key(s)))
3912 .collect();
3913 per_file_map.insert(pattern.to_string(), rules);
3914 } else {
3915 let type_name = value_item.type_name();
3916 log::warn!(
3917 "[WARN] Expected array for per-file-ignores pattern '{pattern}' in {path}, found {type_name}"
3918 );
3919 }
3920 }
3921 fragment
3922 .per_file_ignores
3923 .push_override(per_file_map, source, file.clone(), None);
3924 }
3925
3926 for (key, item) in doc.iter() {
3928 if key == "global" || key == "per-file-ignores" {
3930 continue;
3931 }
3932
3933 let norm_rule_name = if let Some(resolved) = registry.resolve_rule_name(key) {
3935 resolved
3936 } else {
3937 fragment
3939 .unknown_keys
3940 .push((format!("[{key}]"), String::new(), Some(path.to_string())));
3941 continue;
3942 };
3943
3944 if let Some(tbl) = item.as_table() {
3945 let rule_entry = fragment.rules.entry(norm_rule_name.clone()).or_default();
3946 for (rk, rv_item) in tbl.iter() {
3947 let norm_rk = normalize_key(rk);
3948
3949 if norm_rk == "severity" {
3951 if let Some(toml_edit::Value::String(formatted_string)) = rv_item.as_value() {
3952 let severity_str = formatted_string.value();
3953 match crate::rule::Severity::deserialize(toml::Value::String(severity_str.to_string())) {
3954 Ok(severity) => {
3955 if rule_entry.severity.is_none() {
3956 rule_entry.severity = Some(SourcedValue::new(severity, source));
3957 } else {
3958 rule_entry.severity.as_mut().unwrap().push_override(
3959 severity,
3960 source,
3961 file.clone(),
3962 None,
3963 );
3964 }
3965 }
3966 Err(_) => {
3967 log::warn!(
3968 "[WARN] Invalid severity '{severity_str}' for rule {norm_rule_name} in {path}. Valid values: error, warning"
3969 );
3970 }
3971 }
3972 }
3973 continue; }
3975
3976 let maybe_toml_val: Option<toml::Value> = match rv_item.as_value() {
3977 Some(toml_edit::Value::String(formatted)) => Some(toml::Value::String(formatted.value().clone())),
3978 Some(toml_edit::Value::Integer(formatted)) => Some(toml::Value::Integer(*formatted.value())),
3979 Some(toml_edit::Value::Float(formatted)) => Some(toml::Value::Float(*formatted.value())),
3980 Some(toml_edit::Value::Boolean(formatted)) => Some(toml::Value::Boolean(*formatted.value())),
3981 Some(toml_edit::Value::Datetime(formatted)) => Some(toml::Value::Datetime(*formatted.value())),
3982 Some(toml_edit::Value::Array(formatted_array)) => {
3983 let mut values = Vec::new();
3985 for item in formatted_array.iter() {
3986 match item {
3987 toml_edit::Value::String(formatted) => {
3988 values.push(toml::Value::String(formatted.value().clone()))
3989 }
3990 toml_edit::Value::Integer(formatted) => {
3991 values.push(toml::Value::Integer(*formatted.value()))
3992 }
3993 toml_edit::Value::Float(formatted) => {
3994 values.push(toml::Value::Float(*formatted.value()))
3995 }
3996 toml_edit::Value::Boolean(formatted) => {
3997 values.push(toml::Value::Boolean(*formatted.value()))
3998 }
3999 toml_edit::Value::Datetime(formatted) => {
4000 values.push(toml::Value::Datetime(*formatted.value()))
4001 }
4002 _ => {
4003 log::warn!(
4004 "[WARN] Skipping unsupported array element type in key '{norm_rule_name}.{norm_rk}' in {path}"
4005 );
4006 }
4007 }
4008 }
4009 Some(toml::Value::Array(values))
4010 }
4011 Some(toml_edit::Value::InlineTable(_)) => {
4012 log::warn!(
4013 "[WARN] Skipping inline table value for key '{norm_rule_name}.{norm_rk}' in {path}. Table conversion not yet fully implemented in parser."
4014 );
4015 None
4016 }
4017 None => {
4018 log::warn!(
4019 "[WARN] Skipping non-value item for key '{norm_rule_name}.{norm_rk}' in {path}. Expected simple value."
4020 );
4021 None
4022 }
4023 };
4024 if let Some(toml_val) = maybe_toml_val {
4025 let sv = rule_entry
4026 .values
4027 .entry(norm_rk.clone())
4028 .or_insert_with(|| SourcedValue::new(toml_val.clone(), ConfigSource::Default));
4029 sv.push_override(toml_val, source, file.clone(), None);
4030 }
4031 }
4032 } else if item.is_value() {
4033 log::warn!("[WARN] Ignoring top-level value key in {path}: '{key}'. Expected a table like [{key}].");
4034 }
4035 }
4036
4037 Ok(fragment)
4038}
4039
4040fn load_from_markdownlint(path: &str) -> Result<SourcedConfigFragment, ConfigError> {
4042 let ml_config = crate::markdownlint_config::load_markdownlint_config(path)
4044 .map_err(|e| ConfigError::ParseError(format!("{path}: {e}")))?;
4045 Ok(ml_config.map_to_sourced_rumdl_config_fragment(Some(path)))
4046}
4047
4048#[cfg(test)]
4049#[path = "config_intelligent_merge_tests.rs"]
4050mod config_intelligent_merge_tests;