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_user_config_loaded_with_explicit_project_config() {
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 disabled rules should be preserved"
1514 );
1515 assert!(
1516 config.global.disable.contains(&"MD041".to_string()),
1517 "User config disabled rules should be preserved"
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_typestate_validate_method() {
1529 use tempfile::tempdir;
1530
1531 let temp_dir = tempdir().expect("Failed to create temporary directory");
1532 let config_path = temp_dir.path().join("test.toml");
1533
1534 let config_content = r#"
1536[global]
1537enable = ["MD001"]
1538
1539[MD013]
1540line_length = 80
1541unknown_option = true
1542"#;
1543 std::fs::write(&config_path, config_content).expect("Failed to write config");
1544
1545 let loaded = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true)
1547 .expect("Should load config");
1548
1549 let default_config = Config::default();
1551 let all_rules = crate::rules::all_rules(&default_config);
1552 let registry = RuleRegistry::from_rules(&all_rules);
1553
1554 let validated = loaded.validate(®istry).expect("Should validate config");
1556
1557 let has_unknown_option_warning = validated
1560 .validation_warnings
1561 .iter()
1562 .any(|w| w.message.contains("unknown_option") || w.message.contains("Unknown option"));
1563
1564 if !has_unknown_option_warning {
1566 for w in &validated.validation_warnings {
1567 eprintln!("Warning: {}", w.message);
1568 }
1569 }
1570 assert!(
1571 has_unknown_option_warning,
1572 "Should have warning for unknown option. Got {} warnings: {:?}",
1573 validated.validation_warnings.len(),
1574 validated
1575 .validation_warnings
1576 .iter()
1577 .map(|w| &w.message)
1578 .collect::<Vec<_>>()
1579 );
1580
1581 let config: Config = validated.into();
1583
1584 assert!(config.global.enable.contains(&"MD001".to_string()));
1586 }
1587
1588 #[test]
1589 fn test_typestate_validate_into_convenience_method() {
1590 use tempfile::tempdir;
1591
1592 let temp_dir = tempdir().expect("Failed to create temporary directory");
1593 let config_path = temp_dir.path().join("test.toml");
1594
1595 let config_content = r#"
1596[global]
1597enable = ["MD022"]
1598
1599[MD022]
1600lines_above = 2
1601"#;
1602 std::fs::write(&config_path, config_content).expect("Failed to write config");
1603
1604 let loaded = SourcedConfig::load_with_discovery(Some(config_path.to_str().unwrap()), None, true)
1605 .expect("Should load config");
1606
1607 let default_config = Config::default();
1608 let all_rules = crate::rules::all_rules(&default_config);
1609 let registry = RuleRegistry::from_rules(&all_rules);
1610
1611 let (config, warnings) = loaded.validate_into(®istry).expect("Should validate and convert");
1613
1614 assert!(warnings.is_empty(), "Should have no warnings for valid config");
1616
1617 assert!(config.global.enable.contains(&"MD022".to_string()));
1619 }
1620}
1621
1622#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1631pub enum ConfigSource {
1632 Default,
1634 UserConfig,
1636 PyprojectToml,
1638 ProjectConfig,
1640 Cli,
1642}
1643
1644#[derive(Debug, Clone)]
1645pub struct ConfigOverride<T> {
1646 pub value: T,
1647 pub source: ConfigSource,
1648 pub file: Option<String>,
1649 pub line: Option<usize>,
1650}
1651
1652#[derive(Debug, Clone)]
1653pub struct SourcedValue<T> {
1654 pub value: T,
1655 pub source: ConfigSource,
1656 pub overrides: Vec<ConfigOverride<T>>,
1657}
1658
1659impl<T: Clone> SourcedValue<T> {
1660 pub fn new(value: T, source: ConfigSource) -> Self {
1661 Self {
1662 value: value.clone(),
1663 source,
1664 overrides: vec![ConfigOverride {
1665 value,
1666 source,
1667 file: None,
1668 line: None,
1669 }],
1670 }
1671 }
1672
1673 pub fn merge_override(
1677 &mut self,
1678 new_value: T,
1679 new_source: ConfigSource,
1680 new_file: Option<String>,
1681 new_line: Option<usize>,
1682 ) {
1683 fn source_precedence(src: ConfigSource) -> u8 {
1685 match src {
1686 ConfigSource::Default => 0,
1687 ConfigSource::UserConfig => 1,
1688 ConfigSource::PyprojectToml => 2,
1689 ConfigSource::ProjectConfig => 3,
1690 ConfigSource::Cli => 4,
1691 }
1692 }
1693
1694 if source_precedence(new_source) >= source_precedence(self.source) {
1695 self.value = new_value.clone();
1696 self.source = new_source;
1697 self.overrides.push(ConfigOverride {
1698 value: new_value,
1699 source: new_source,
1700 file: new_file,
1701 line: new_line,
1702 });
1703 }
1704 }
1705
1706 pub fn push_override(&mut self, value: T, source: ConfigSource, file: Option<String>, line: Option<usize>) {
1707 self.value = value.clone();
1710 self.source = source;
1711 self.overrides.push(ConfigOverride {
1712 value,
1713 source,
1714 file,
1715 line,
1716 });
1717 }
1718}
1719
1720impl<T: Clone + Eq + std::hash::Hash> SourcedValue<Vec<T>> {
1721 pub fn merge_union(
1724 &mut self,
1725 new_value: Vec<T>,
1726 new_source: ConfigSource,
1727 new_file: Option<String>,
1728 new_line: Option<usize>,
1729 ) {
1730 fn source_precedence(src: ConfigSource) -> u8 {
1731 match src {
1732 ConfigSource::Default => 0,
1733 ConfigSource::UserConfig => 1,
1734 ConfigSource::PyprojectToml => 2,
1735 ConfigSource::ProjectConfig => 3,
1736 ConfigSource::Cli => 4,
1737 }
1738 }
1739
1740 if source_precedence(new_source) >= source_precedence(self.source) {
1741 let mut combined = self.value.clone();
1743 for item in new_value.iter() {
1744 if !combined.contains(item) {
1745 combined.push(item.clone());
1746 }
1747 }
1748
1749 self.value = combined;
1750 self.source = new_source;
1751 self.overrides.push(ConfigOverride {
1752 value: new_value,
1753 source: new_source,
1754 file: new_file,
1755 line: new_line,
1756 });
1757 }
1758 }
1759}
1760
1761#[derive(Debug, Clone)]
1762pub struct SourcedGlobalConfig {
1763 pub enable: SourcedValue<Vec<String>>,
1764 pub disable: SourcedValue<Vec<String>>,
1765 pub exclude: SourcedValue<Vec<String>>,
1766 pub include: SourcedValue<Vec<String>>,
1767 pub respect_gitignore: SourcedValue<bool>,
1768 pub line_length: SourcedValue<LineLength>,
1769 pub output_format: Option<SourcedValue<String>>,
1770 pub fixable: SourcedValue<Vec<String>>,
1771 pub unfixable: SourcedValue<Vec<String>>,
1772 pub flavor: SourcedValue<MarkdownFlavor>,
1773 pub force_exclude: SourcedValue<bool>,
1774 pub cache_dir: Option<SourcedValue<String>>,
1775 pub cache: SourcedValue<bool>,
1776}
1777
1778impl Default for SourcedGlobalConfig {
1779 fn default() -> Self {
1780 SourcedGlobalConfig {
1781 enable: SourcedValue::new(Vec::new(), ConfigSource::Default),
1782 disable: SourcedValue::new(Vec::new(), ConfigSource::Default),
1783 exclude: SourcedValue::new(Vec::new(), ConfigSource::Default),
1784 include: SourcedValue::new(Vec::new(), ConfigSource::Default),
1785 respect_gitignore: SourcedValue::new(true, ConfigSource::Default),
1786 line_length: SourcedValue::new(LineLength::default(), ConfigSource::Default),
1787 output_format: None,
1788 fixable: SourcedValue::new(Vec::new(), ConfigSource::Default),
1789 unfixable: SourcedValue::new(Vec::new(), ConfigSource::Default),
1790 flavor: SourcedValue::new(MarkdownFlavor::default(), ConfigSource::Default),
1791 force_exclude: SourcedValue::new(false, ConfigSource::Default),
1792 cache_dir: None,
1793 cache: SourcedValue::new(true, ConfigSource::Default),
1794 }
1795 }
1796}
1797
1798#[derive(Debug, Default, Clone)]
1799pub struct SourcedRuleConfig {
1800 pub severity: Option<SourcedValue<crate::rule::Severity>>,
1801 pub values: BTreeMap<String, SourcedValue<toml::Value>>,
1802}
1803
1804#[derive(Debug, Clone)]
1807pub struct SourcedConfigFragment {
1808 pub global: SourcedGlobalConfig,
1809 pub per_file_ignores: SourcedValue<HashMap<String, Vec<String>>>,
1810 pub rules: BTreeMap<String, SourcedRuleConfig>,
1811 pub unknown_keys: Vec<(String, String, Option<String>)>, }
1814
1815impl Default for SourcedConfigFragment {
1816 fn default() -> Self {
1817 Self {
1818 global: SourcedGlobalConfig::default(),
1819 per_file_ignores: SourcedValue::new(HashMap::new(), ConfigSource::Default),
1820 rules: BTreeMap::new(),
1821 unknown_keys: Vec::new(),
1822 }
1823 }
1824}
1825
1826#[derive(Debug, Clone)]
1844pub struct SourcedConfig<State = ConfigLoaded> {
1845 pub global: SourcedGlobalConfig,
1846 pub per_file_ignores: SourcedValue<HashMap<String, Vec<String>>>,
1847 pub rules: BTreeMap<String, SourcedRuleConfig>,
1848 pub loaded_files: Vec<String>,
1849 pub unknown_keys: Vec<(String, String, Option<String>)>, pub project_root: Option<std::path::PathBuf>,
1852 pub validation_warnings: Vec<ConfigValidationWarning>,
1854 _state: PhantomData<State>,
1856}
1857
1858impl Default for SourcedConfig<ConfigLoaded> {
1859 fn default() -> Self {
1860 Self {
1861 global: SourcedGlobalConfig::default(),
1862 per_file_ignores: SourcedValue::new(HashMap::new(), ConfigSource::Default),
1863 rules: BTreeMap::new(),
1864 loaded_files: Vec::new(),
1865 unknown_keys: Vec::new(),
1866 project_root: None,
1867 validation_warnings: Vec::new(),
1868 _state: PhantomData,
1869 }
1870 }
1871}
1872
1873impl SourcedConfig<ConfigLoaded> {
1874 fn merge(&mut self, fragment: SourcedConfigFragment) {
1877 self.global.enable.merge_override(
1880 fragment.global.enable.value,
1881 fragment.global.enable.source,
1882 fragment.global.enable.overrides.first().and_then(|o| o.file.clone()),
1883 fragment.global.enable.overrides.first().and_then(|o| o.line),
1884 );
1885
1886 self.global.disable.merge_union(
1888 fragment.global.disable.value,
1889 fragment.global.disable.source,
1890 fragment.global.disable.overrides.first().and_then(|o| o.file.clone()),
1891 fragment.global.disable.overrides.first().and_then(|o| o.line),
1892 );
1893
1894 self.global
1897 .disable
1898 .value
1899 .retain(|rule| !self.global.enable.value.contains(rule));
1900 self.global.include.merge_override(
1901 fragment.global.include.value,
1902 fragment.global.include.source,
1903 fragment.global.include.overrides.first().and_then(|o| o.file.clone()),
1904 fragment.global.include.overrides.first().and_then(|o| o.line),
1905 );
1906 self.global.exclude.merge_override(
1907 fragment.global.exclude.value,
1908 fragment.global.exclude.source,
1909 fragment.global.exclude.overrides.first().and_then(|o| o.file.clone()),
1910 fragment.global.exclude.overrides.first().and_then(|o| o.line),
1911 );
1912 self.global.respect_gitignore.merge_override(
1913 fragment.global.respect_gitignore.value,
1914 fragment.global.respect_gitignore.source,
1915 fragment
1916 .global
1917 .respect_gitignore
1918 .overrides
1919 .first()
1920 .and_then(|o| o.file.clone()),
1921 fragment.global.respect_gitignore.overrides.first().and_then(|o| o.line),
1922 );
1923 self.global.line_length.merge_override(
1924 fragment.global.line_length.value,
1925 fragment.global.line_length.source,
1926 fragment
1927 .global
1928 .line_length
1929 .overrides
1930 .first()
1931 .and_then(|o| o.file.clone()),
1932 fragment.global.line_length.overrides.first().and_then(|o| o.line),
1933 );
1934 self.global.fixable.merge_override(
1935 fragment.global.fixable.value,
1936 fragment.global.fixable.source,
1937 fragment.global.fixable.overrides.first().and_then(|o| o.file.clone()),
1938 fragment.global.fixable.overrides.first().and_then(|o| o.line),
1939 );
1940 self.global.unfixable.merge_override(
1941 fragment.global.unfixable.value,
1942 fragment.global.unfixable.source,
1943 fragment.global.unfixable.overrides.first().and_then(|o| o.file.clone()),
1944 fragment.global.unfixable.overrides.first().and_then(|o| o.line),
1945 );
1946
1947 self.global.flavor.merge_override(
1949 fragment.global.flavor.value,
1950 fragment.global.flavor.source,
1951 fragment.global.flavor.overrides.first().and_then(|o| o.file.clone()),
1952 fragment.global.flavor.overrides.first().and_then(|o| o.line),
1953 );
1954
1955 self.global.force_exclude.merge_override(
1957 fragment.global.force_exclude.value,
1958 fragment.global.force_exclude.source,
1959 fragment
1960 .global
1961 .force_exclude
1962 .overrides
1963 .first()
1964 .and_then(|o| o.file.clone()),
1965 fragment.global.force_exclude.overrides.first().and_then(|o| o.line),
1966 );
1967
1968 if let Some(output_format_fragment) = fragment.global.output_format {
1970 if let Some(ref mut output_format) = self.global.output_format {
1971 output_format.merge_override(
1972 output_format_fragment.value,
1973 output_format_fragment.source,
1974 output_format_fragment.overrides.first().and_then(|o| o.file.clone()),
1975 output_format_fragment.overrides.first().and_then(|o| o.line),
1976 );
1977 } else {
1978 self.global.output_format = Some(output_format_fragment);
1979 }
1980 }
1981
1982 if let Some(cache_dir_fragment) = fragment.global.cache_dir {
1984 if let Some(ref mut cache_dir) = self.global.cache_dir {
1985 cache_dir.merge_override(
1986 cache_dir_fragment.value,
1987 cache_dir_fragment.source,
1988 cache_dir_fragment.overrides.first().and_then(|o| o.file.clone()),
1989 cache_dir_fragment.overrides.first().and_then(|o| o.line),
1990 );
1991 } else {
1992 self.global.cache_dir = Some(cache_dir_fragment);
1993 }
1994 }
1995
1996 if fragment.global.cache.source != ConfigSource::Default {
1998 self.global.cache.merge_override(
1999 fragment.global.cache.value,
2000 fragment.global.cache.source,
2001 fragment.global.cache.overrides.first().and_then(|o| o.file.clone()),
2002 fragment.global.cache.overrides.first().and_then(|o| o.line),
2003 );
2004 }
2005
2006 self.per_file_ignores.merge_override(
2008 fragment.per_file_ignores.value,
2009 fragment.per_file_ignores.source,
2010 fragment.per_file_ignores.overrides.first().and_then(|o| o.file.clone()),
2011 fragment.per_file_ignores.overrides.first().and_then(|o| o.line),
2012 );
2013
2014 for (rule_name, rule_fragment) in fragment.rules {
2016 let norm_rule_name = rule_name.to_ascii_uppercase(); let rule_entry = self.rules.entry(norm_rule_name).or_default();
2018
2019 if let Some(severity_fragment) = rule_fragment.severity {
2021 if let Some(ref mut existing_severity) = rule_entry.severity {
2022 existing_severity.merge_override(
2023 severity_fragment.value,
2024 severity_fragment.source,
2025 severity_fragment.overrides.first().and_then(|o| o.file.clone()),
2026 severity_fragment.overrides.first().and_then(|o| o.line),
2027 );
2028 } else {
2029 rule_entry.severity = Some(severity_fragment);
2030 }
2031 }
2032
2033 for (key, sourced_value_fragment) in rule_fragment.values {
2035 let sv_entry = rule_entry
2036 .values
2037 .entry(key.clone())
2038 .or_insert_with(|| SourcedValue::new(sourced_value_fragment.value.clone(), ConfigSource::Default));
2039 let file_from_fragment = sourced_value_fragment.overrides.first().and_then(|o| o.file.clone());
2040 let line_from_fragment = sourced_value_fragment.overrides.first().and_then(|o| o.line);
2041 sv_entry.merge_override(
2042 sourced_value_fragment.value, sourced_value_fragment.source, file_from_fragment, line_from_fragment, );
2047 }
2048 }
2049
2050 for (section, key, file_path) in fragment.unknown_keys {
2052 if !self.unknown_keys.iter().any(|(s, k, _)| s == §ion && k == &key) {
2054 self.unknown_keys.push((section, key, file_path));
2055 }
2056 }
2057 }
2058
2059 pub fn load(config_path: Option<&str>, cli_overrides: Option<&SourcedGlobalConfig>) -> Result<Self, ConfigError> {
2061 Self::load_with_discovery(config_path, cli_overrides, false)
2062 }
2063
2064 fn find_project_root_from(start_dir: &Path) -> std::path::PathBuf {
2067 let mut current = start_dir.to_path_buf();
2068 const MAX_DEPTH: usize = 100;
2069
2070 for _ in 0..MAX_DEPTH {
2071 if current.join(".git").exists() {
2072 log::debug!("[rumdl-config] Found .git at: {}", current.display());
2073 return current;
2074 }
2075
2076 match current.parent() {
2077 Some(parent) => current = parent.to_path_buf(),
2078 None => break,
2079 }
2080 }
2081
2082 log::debug!(
2084 "[rumdl-config] No .git found, using config location as project root: {}",
2085 start_dir.display()
2086 );
2087 start_dir.to_path_buf()
2088 }
2089
2090 fn discover_config_upward() -> Option<(std::path::PathBuf, std::path::PathBuf)> {
2096 use std::env;
2097
2098 const CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml", ".config/rumdl.toml", "pyproject.toml"];
2099 const MAX_DEPTH: usize = 100; let start_dir = match env::current_dir() {
2102 Ok(dir) => dir,
2103 Err(e) => {
2104 log::debug!("[rumdl-config] Failed to get current directory: {e}");
2105 return None;
2106 }
2107 };
2108
2109 let mut current_dir = start_dir.clone();
2110 let mut depth = 0;
2111 let mut found_config: Option<(std::path::PathBuf, std::path::PathBuf)> = None;
2112
2113 loop {
2114 if depth >= MAX_DEPTH {
2115 log::debug!("[rumdl-config] Maximum traversal depth reached");
2116 break;
2117 }
2118
2119 log::debug!("[rumdl-config] Searching for config in: {}", current_dir.display());
2120
2121 if found_config.is_none() {
2123 for config_name in CONFIG_FILES {
2124 let config_path = current_dir.join(config_name);
2125
2126 if config_path.exists() {
2127 if *config_name == "pyproject.toml" {
2129 if let Ok(content) = std::fs::read_to_string(&config_path) {
2130 if content.contains("[tool.rumdl]") || content.contains("tool.rumdl") {
2131 log::debug!("[rumdl-config] Found config file: {}", config_path.display());
2132 found_config = Some((config_path.clone(), current_dir.clone()));
2134 break;
2135 }
2136 log::debug!("[rumdl-config] Found pyproject.toml but no [tool.rumdl] section");
2137 continue;
2138 }
2139 } else {
2140 log::debug!("[rumdl-config] Found config file: {}", config_path.display());
2141 found_config = Some((config_path.clone(), current_dir.clone()));
2143 break;
2144 }
2145 }
2146 }
2147 }
2148
2149 if current_dir.join(".git").exists() {
2151 log::debug!("[rumdl-config] Stopping at .git directory");
2152 break;
2153 }
2154
2155 match current_dir.parent() {
2157 Some(parent) => {
2158 current_dir = parent.to_owned();
2159 depth += 1;
2160 }
2161 None => {
2162 log::debug!("[rumdl-config] Reached filesystem root");
2163 break;
2164 }
2165 }
2166 }
2167
2168 if let Some((config_path, config_dir)) = found_config {
2170 let project_root = Self::find_project_root_from(&config_dir);
2171 return Some((config_path, project_root));
2172 }
2173
2174 None
2175 }
2176
2177 fn discover_markdownlint_config_upward() -> Option<std::path::PathBuf> {
2181 use std::env;
2182
2183 const MAX_DEPTH: usize = 100;
2184
2185 let start_dir = match env::current_dir() {
2186 Ok(dir) => dir,
2187 Err(e) => {
2188 log::debug!("[rumdl-config] Failed to get current directory for markdownlint discovery: {e}");
2189 return None;
2190 }
2191 };
2192
2193 let mut current_dir = start_dir.clone();
2194 let mut depth = 0;
2195
2196 loop {
2197 if depth >= MAX_DEPTH {
2198 log::debug!("[rumdl-config] Maximum traversal depth reached for markdownlint discovery");
2199 break;
2200 }
2201
2202 log::debug!(
2203 "[rumdl-config] Searching for markdownlint config in: {}",
2204 current_dir.display()
2205 );
2206
2207 for config_name in MARKDOWNLINT_CONFIG_FILES {
2209 let config_path = current_dir.join(config_name);
2210 if config_path.exists() {
2211 log::debug!("[rumdl-config] Found markdownlint config: {}", config_path.display());
2212 return Some(config_path);
2213 }
2214 }
2215
2216 if current_dir.join(".git").exists() {
2218 log::debug!("[rumdl-config] Stopping markdownlint search at .git directory");
2219 break;
2220 }
2221
2222 match current_dir.parent() {
2224 Some(parent) => {
2225 current_dir = parent.to_owned();
2226 depth += 1;
2227 }
2228 None => {
2229 log::debug!("[rumdl-config] Reached filesystem root during markdownlint search");
2230 break;
2231 }
2232 }
2233 }
2234
2235 None
2236 }
2237
2238 fn user_configuration_path_impl(config_dir: &Path) -> Option<std::path::PathBuf> {
2240 let config_dir = config_dir.join("rumdl");
2241
2242 const USER_CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml", "pyproject.toml"];
2244
2245 log::debug!(
2246 "[rumdl-config] Checking for user configuration in: {}",
2247 config_dir.display()
2248 );
2249
2250 for filename in USER_CONFIG_FILES {
2251 let config_path = config_dir.join(filename);
2252
2253 if config_path.exists() {
2254 if *filename == "pyproject.toml" {
2256 if let Ok(content) = std::fs::read_to_string(&config_path) {
2257 if content.contains("[tool.rumdl]") || content.contains("tool.rumdl") {
2258 log::debug!("[rumdl-config] Found user configuration at: {}", config_path.display());
2259 return Some(config_path);
2260 }
2261 log::debug!("[rumdl-config] Found user pyproject.toml but no [tool.rumdl] section");
2262 continue;
2263 }
2264 } else {
2265 log::debug!("[rumdl-config] Found user configuration at: {}", config_path.display());
2266 return Some(config_path);
2267 }
2268 }
2269 }
2270
2271 log::debug!(
2272 "[rumdl-config] No user configuration found in: {}",
2273 config_dir.display()
2274 );
2275 None
2276 }
2277
2278 #[cfg(feature = "native")]
2281 fn user_configuration_path() -> Option<std::path::PathBuf> {
2282 use etcetera::{BaseStrategy, choose_base_strategy};
2283
2284 match choose_base_strategy() {
2285 Ok(strategy) => {
2286 let config_dir = strategy.config_dir();
2287 Self::user_configuration_path_impl(&config_dir)
2288 }
2289 Err(e) => {
2290 log::debug!("[rumdl-config] Failed to determine user config directory: {e}");
2291 None
2292 }
2293 }
2294 }
2295
2296 #[cfg(not(feature = "native"))]
2298 fn user_configuration_path() -> Option<std::path::PathBuf> {
2299 None
2300 }
2301
2302 #[doc(hidden)]
2304 pub fn load_with_discovery_impl(
2305 config_path: Option<&str>,
2306 cli_overrides: Option<&SourcedGlobalConfig>,
2307 skip_auto_discovery: bool,
2308 user_config_dir: Option<&Path>,
2309 ) -> Result<Self, ConfigError> {
2310 use std::env;
2311 log::debug!("[rumdl-config] Current working directory: {:?}", env::current_dir());
2312 if config_path.is_none() {
2313 if skip_auto_discovery {
2314 log::debug!("[rumdl-config] Skipping auto-discovery due to --no-config flag");
2315 } else {
2316 log::debug!("[rumdl-config] No explicit config_path provided, will search default locations");
2317 }
2318 } else {
2319 log::debug!("[rumdl-config] Explicit config_path provided: {config_path:?}");
2320 }
2321 let mut sourced_config = SourcedConfig::default();
2322
2323 if !skip_auto_discovery {
2326 let user_config_path = if let Some(dir) = user_config_dir {
2327 Self::user_configuration_path_impl(dir)
2328 } else {
2329 Self::user_configuration_path()
2330 };
2331
2332 if let Some(user_config_path) = user_config_path {
2333 let path_str = user_config_path.display().to_string();
2334 let filename = user_config_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
2335
2336 log::debug!("[rumdl-config] Loading user configuration file: {path_str}");
2337
2338 if filename == "pyproject.toml" {
2339 let content = std::fs::read_to_string(&user_config_path).map_err(|e| ConfigError::IoError {
2340 source: e,
2341 path: path_str.clone(),
2342 })?;
2343 if let Some(fragment) = parse_pyproject_toml(&content, &path_str)? {
2344 sourced_config.merge(fragment);
2345 sourced_config.loaded_files.push(path_str);
2346 }
2347 } else {
2348 let content = std::fs::read_to_string(&user_config_path).map_err(|e| ConfigError::IoError {
2349 source: e,
2350 path: path_str.clone(),
2351 })?;
2352 let fragment = parse_rumdl_toml(&content, &path_str, ConfigSource::UserConfig)?;
2353 sourced_config.merge(fragment);
2354 sourced_config.loaded_files.push(path_str);
2355 }
2356 } else {
2357 log::debug!("[rumdl-config] No user configuration file found");
2358 }
2359 }
2360
2361 if let Some(path) = config_path {
2363 let path_obj = Path::new(path);
2364 let filename = path_obj.file_name().and_then(|name| name.to_str()).unwrap_or("");
2365 log::debug!("[rumdl-config] Trying to load config file: {filename}");
2366 let path_str = path.to_string();
2367
2368 if let Some(config_parent) = path_obj.parent() {
2370 let project_root = Self::find_project_root_from(config_parent);
2371 log::debug!(
2372 "[rumdl-config] Project root (from explicit config): {}",
2373 project_root.display()
2374 );
2375 sourced_config.project_root = Some(project_root);
2376 }
2377
2378 const MARKDOWNLINT_FILENAMES: &[&str] = &[".markdownlint.json", ".markdownlint.yaml", ".markdownlint.yml"];
2380
2381 if filename == "pyproject.toml" || filename == ".rumdl.toml" || filename == "rumdl.toml" {
2382 let content = std::fs::read_to_string(path).map_err(|e| ConfigError::IoError {
2383 source: e,
2384 path: path_str.clone(),
2385 })?;
2386 if filename == "pyproject.toml" {
2387 if let Some(fragment) = parse_pyproject_toml(&content, &path_str)? {
2388 sourced_config.merge(fragment);
2389 sourced_config.loaded_files.push(path_str.clone());
2390 }
2391 } else {
2392 let fragment = parse_rumdl_toml(&content, &path_str, ConfigSource::ProjectConfig)?;
2393 sourced_config.merge(fragment);
2394 sourced_config.loaded_files.push(path_str.clone());
2395 }
2396 } else if MARKDOWNLINT_FILENAMES.contains(&filename)
2397 || path_str.ends_with(".json")
2398 || path_str.ends_with(".jsonc")
2399 || path_str.ends_with(".yaml")
2400 || path_str.ends_with(".yml")
2401 {
2402 let fragment = load_from_markdownlint(&path_str)?;
2404 sourced_config.merge(fragment);
2405 sourced_config.loaded_files.push(path_str.clone());
2406 } else {
2408 let content = std::fs::read_to_string(path).map_err(|e| ConfigError::IoError {
2410 source: e,
2411 path: path_str.clone(),
2412 })?;
2413 let fragment = parse_rumdl_toml(&content, &path_str, ConfigSource::ProjectConfig)?;
2414 sourced_config.merge(fragment);
2415 sourced_config.loaded_files.push(path_str.clone());
2416 }
2417 }
2418
2419 if !skip_auto_discovery && config_path.is_none() {
2421 if let Some((config_file, project_root)) = Self::discover_config_upward() {
2423 let path_str = config_file.display().to_string();
2424 let filename = config_file.file_name().and_then(|n| n.to_str()).unwrap_or("");
2425
2426 log::debug!("[rumdl-config] Loading discovered config file: {path_str}");
2427 log::debug!("[rumdl-config] Project root: {}", project_root.display());
2428
2429 sourced_config.project_root = Some(project_root);
2431
2432 if filename == "pyproject.toml" {
2433 let content = std::fs::read_to_string(&config_file).map_err(|e| ConfigError::IoError {
2434 source: e,
2435 path: path_str.clone(),
2436 })?;
2437 if let Some(fragment) = parse_pyproject_toml(&content, &path_str)? {
2438 sourced_config.merge(fragment);
2439 sourced_config.loaded_files.push(path_str);
2440 }
2441 } else if filename == ".rumdl.toml" || filename == "rumdl.toml" {
2442 let content = std::fs::read_to_string(&config_file).map_err(|e| ConfigError::IoError {
2443 source: e,
2444 path: path_str.clone(),
2445 })?;
2446 let fragment = parse_rumdl_toml(&content, &path_str, ConfigSource::ProjectConfig)?;
2447 sourced_config.merge(fragment);
2448 sourced_config.loaded_files.push(path_str);
2449 }
2450 } else {
2451 log::debug!("[rumdl-config] No configuration file found via upward traversal");
2452
2453 if let Some(config_path) = Self::discover_markdownlint_config_upward() {
2455 let path_str = config_path.display().to_string();
2456 match load_from_markdownlint(&path_str) {
2457 Ok(fragment) => {
2458 sourced_config.merge(fragment);
2459 sourced_config.loaded_files.push(path_str);
2460 }
2461 Err(_e) => {
2462 log::debug!("[rumdl-config] Failed to load markdownlint config");
2463 }
2464 }
2465 } else {
2466 log::debug!("[rumdl-config] No markdownlint configuration file found");
2467 }
2468 }
2469 }
2470
2471 if let Some(cli) = cli_overrides {
2473 sourced_config
2474 .global
2475 .enable
2476 .merge_override(cli.enable.value.clone(), ConfigSource::Cli, None, None);
2477 sourced_config
2478 .global
2479 .disable
2480 .merge_override(cli.disable.value.clone(), ConfigSource::Cli, None, None);
2481 sourced_config
2482 .global
2483 .exclude
2484 .merge_override(cli.exclude.value.clone(), ConfigSource::Cli, None, None);
2485 sourced_config
2486 .global
2487 .include
2488 .merge_override(cli.include.value.clone(), ConfigSource::Cli, None, None);
2489 sourced_config.global.respect_gitignore.merge_override(
2490 cli.respect_gitignore.value,
2491 ConfigSource::Cli,
2492 None,
2493 None,
2494 );
2495 sourced_config
2496 .global
2497 .fixable
2498 .merge_override(cli.fixable.value.clone(), ConfigSource::Cli, None, None);
2499 sourced_config
2500 .global
2501 .unfixable
2502 .merge_override(cli.unfixable.value.clone(), ConfigSource::Cli, None, None);
2503 }
2505
2506 Ok(sourced_config)
2509 }
2510
2511 pub fn load_with_discovery(
2514 config_path: Option<&str>,
2515 cli_overrides: Option<&SourcedGlobalConfig>,
2516 skip_auto_discovery: bool,
2517 ) -> Result<Self, ConfigError> {
2518 Self::load_with_discovery_impl(config_path, cli_overrides, skip_auto_discovery, None)
2519 }
2520
2521 pub fn validate(self, registry: &RuleRegistry) -> Result<SourcedConfig<ConfigValidated>, ConfigError> {
2535 let warnings = validate_config_sourced_internal(&self, registry);
2536
2537 Ok(SourcedConfig {
2538 global: self.global,
2539 per_file_ignores: self.per_file_ignores,
2540 rules: self.rules,
2541 loaded_files: self.loaded_files,
2542 unknown_keys: self.unknown_keys,
2543 project_root: self.project_root,
2544 validation_warnings: warnings,
2545 _state: PhantomData,
2546 })
2547 }
2548
2549 pub fn validate_into(self, registry: &RuleRegistry) -> Result<(Config, Vec<ConfigValidationWarning>), ConfigError> {
2554 let validated = self.validate(registry)?;
2555 let warnings = validated.validation_warnings.clone();
2556 Ok((validated.into(), warnings))
2557 }
2558
2559 pub fn into_validated_unchecked(self) -> SourcedConfig<ConfigValidated> {
2570 SourcedConfig {
2571 global: self.global,
2572 per_file_ignores: self.per_file_ignores,
2573 rules: self.rules,
2574 loaded_files: self.loaded_files,
2575 unknown_keys: self.unknown_keys,
2576 project_root: self.project_root,
2577 validation_warnings: Vec::new(),
2578 _state: PhantomData,
2579 }
2580 }
2581}
2582
2583impl From<SourcedConfig<ConfigValidated>> for Config {
2588 fn from(sourced: SourcedConfig<ConfigValidated>) -> Self {
2589 let mut rules = BTreeMap::new();
2590 for (rule_name, sourced_rule_cfg) in sourced.rules {
2591 let normalized_rule_name = rule_name.to_ascii_uppercase();
2593 let severity = sourced_rule_cfg.severity.map(|sv| sv.value);
2594 let mut values = BTreeMap::new();
2595 for (key, sourced_val) in sourced_rule_cfg.values {
2596 values.insert(key, sourced_val.value);
2597 }
2598 rules.insert(normalized_rule_name, RuleConfig { severity, values });
2599 }
2600 #[allow(deprecated)]
2601 let global = GlobalConfig {
2602 enable: sourced.global.enable.value,
2603 disable: sourced.global.disable.value,
2604 exclude: sourced.global.exclude.value,
2605 include: sourced.global.include.value,
2606 respect_gitignore: sourced.global.respect_gitignore.value,
2607 line_length: sourced.global.line_length.value,
2608 output_format: sourced.global.output_format.as_ref().map(|v| v.value.clone()),
2609 fixable: sourced.global.fixable.value,
2610 unfixable: sourced.global.unfixable.value,
2611 flavor: sourced.global.flavor.value,
2612 force_exclude: sourced.global.force_exclude.value,
2613 cache_dir: sourced.global.cache_dir.as_ref().map(|v| v.value.clone()),
2614 cache: sourced.global.cache.value,
2615 };
2616 Config {
2617 global,
2618 per_file_ignores: sourced.per_file_ignores.value,
2619 rules,
2620 project_root: sourced.project_root,
2621 }
2622 }
2623}
2624
2625pub struct RuleRegistry {
2627 pub rule_schemas: std::collections::BTreeMap<String, toml::map::Map<String, toml::Value>>,
2629 pub rule_aliases: std::collections::BTreeMap<String, std::collections::HashMap<String, String>>,
2631}
2632
2633impl RuleRegistry {
2634 pub fn from_rules(rules: &[Box<dyn Rule>]) -> Self {
2636 let mut rule_schemas = std::collections::BTreeMap::new();
2637 let mut rule_aliases = std::collections::BTreeMap::new();
2638
2639 for rule in rules {
2640 let norm_name = if let Some((name, toml::Value::Table(table))) = rule.default_config_section() {
2641 let norm_name = normalize_key(&name); rule_schemas.insert(norm_name.clone(), table);
2643 norm_name
2644 } else {
2645 let norm_name = normalize_key(rule.name()); rule_schemas.insert(norm_name.clone(), toml::map::Map::new());
2647 norm_name
2648 };
2649
2650 if let Some(aliases) = rule.config_aliases() {
2652 rule_aliases.insert(norm_name, aliases);
2653 }
2654 }
2655
2656 RuleRegistry {
2657 rule_schemas,
2658 rule_aliases,
2659 }
2660 }
2661
2662 pub fn rule_names(&self) -> std::collections::BTreeSet<String> {
2664 self.rule_schemas.keys().cloned().collect()
2665 }
2666
2667 pub fn config_keys_for(&self, rule: &str) -> Option<std::collections::BTreeSet<String>> {
2669 self.rule_schemas.get(rule).map(|schema| {
2670 let mut all_keys = std::collections::BTreeSet::new();
2671
2672 all_keys.insert("severity".to_string());
2674
2675 for key in schema.keys() {
2677 all_keys.insert(key.clone());
2678 }
2679
2680 for key in schema.keys() {
2682 all_keys.insert(key.replace('_', "-"));
2684 all_keys.insert(key.replace('-', "_"));
2686 all_keys.insert(normalize_key(key));
2688 }
2689
2690 if let Some(aliases) = self.rule_aliases.get(rule) {
2692 for alias_key in aliases.keys() {
2693 all_keys.insert(alias_key.clone());
2694 all_keys.insert(alias_key.replace('_', "-"));
2696 all_keys.insert(alias_key.replace('-', "_"));
2697 all_keys.insert(normalize_key(alias_key));
2698 }
2699 }
2700
2701 all_keys
2702 })
2703 }
2704
2705 pub fn expected_value_for(&self, rule: &str, key: &str) -> Option<&toml::Value> {
2707 if let Some(schema) = self.rule_schemas.get(rule) {
2708 if let Some(aliases) = self.rule_aliases.get(rule)
2710 && let Some(canonical_key) = aliases.get(key)
2711 {
2712 if let Some(value) = schema.get(canonical_key) {
2714 return Some(value);
2715 }
2716 }
2717
2718 if let Some(value) = schema.get(key) {
2720 return Some(value);
2721 }
2722
2723 let key_variants = [
2725 key.replace('-', "_"), key.replace('_', "-"), normalize_key(key), ];
2729
2730 for variant in &key_variants {
2731 if let Some(value) = schema.get(variant) {
2732 return Some(value);
2733 }
2734 }
2735 }
2736 None
2737 }
2738
2739 pub fn resolve_rule_name(&self, name: &str) -> Option<String> {
2746 let normalized = normalize_key(name);
2748 if self.rule_schemas.contains_key(&normalized) {
2749 return Some(normalized);
2750 }
2751
2752 resolve_rule_name_alias(name).map(|s| s.to_string())
2754 }
2755}
2756
2757static RULE_ALIAS_MAP: phf::Map<&'static str, &'static str> = phf::phf_map! {
2760 "MD001" => "MD001",
2762 "MD003" => "MD003",
2763 "MD004" => "MD004",
2764 "MD005" => "MD005",
2765 "MD007" => "MD007",
2766 "MD008" => "MD008",
2767 "MD009" => "MD009",
2768 "MD010" => "MD010",
2769 "MD011" => "MD011",
2770 "MD012" => "MD012",
2771 "MD013" => "MD013",
2772 "MD014" => "MD014",
2773 "MD015" => "MD015",
2774 "MD018" => "MD018",
2775 "MD019" => "MD019",
2776 "MD020" => "MD020",
2777 "MD021" => "MD021",
2778 "MD022" => "MD022",
2779 "MD023" => "MD023",
2780 "MD024" => "MD024",
2781 "MD025" => "MD025",
2782 "MD026" => "MD026",
2783 "MD027" => "MD027",
2784 "MD028" => "MD028",
2785 "MD029" => "MD029",
2786 "MD030" => "MD030",
2787 "MD031" => "MD031",
2788 "MD032" => "MD032",
2789 "MD033" => "MD033",
2790 "MD034" => "MD034",
2791 "MD035" => "MD035",
2792 "MD036" => "MD036",
2793 "MD037" => "MD037",
2794 "MD038" => "MD038",
2795 "MD039" => "MD039",
2796 "MD040" => "MD040",
2797 "MD041" => "MD041",
2798 "MD042" => "MD042",
2799 "MD043" => "MD043",
2800 "MD044" => "MD044",
2801 "MD045" => "MD045",
2802 "MD046" => "MD046",
2803 "MD047" => "MD047",
2804 "MD048" => "MD048",
2805 "MD049" => "MD049",
2806 "MD050" => "MD050",
2807 "MD051" => "MD051",
2808 "MD052" => "MD052",
2809 "MD053" => "MD053",
2810 "MD054" => "MD054",
2811 "MD055" => "MD055",
2812 "MD056" => "MD056",
2813 "MD057" => "MD057",
2814 "MD058" => "MD058",
2815 "MD059" => "MD059",
2816 "MD060" => "MD060",
2817 "MD061" => "MD061",
2818
2819 "HEADING-INCREMENT" => "MD001",
2821 "HEADING-STYLE" => "MD003",
2822 "UL-STYLE" => "MD004",
2823 "LIST-INDENT" => "MD005",
2824 "UL-INDENT" => "MD007",
2825 "NO-TRAILING-SPACES" => "MD009",
2826 "NO-HARD-TABS" => "MD010",
2827 "NO-REVERSED-LINKS" => "MD011",
2828 "NO-MULTIPLE-BLANKS" => "MD012",
2829 "LINE-LENGTH" => "MD013",
2830 "COMMANDS-SHOW-OUTPUT" => "MD014",
2831 "NO-MISSING-SPACE-AFTER-LIST-MARKER" => "MD015",
2832 "NO-MISSING-SPACE-ATX" => "MD018",
2833 "NO-MULTIPLE-SPACE-ATX" => "MD019",
2834 "NO-MISSING-SPACE-CLOSED-ATX" => "MD020",
2835 "NO-MULTIPLE-SPACE-CLOSED-ATX" => "MD021",
2836 "BLANKS-AROUND-HEADINGS" => "MD022",
2837 "HEADING-START-LEFT" => "MD023",
2838 "NO-DUPLICATE-HEADING" => "MD024",
2839 "SINGLE-TITLE" => "MD025",
2840 "SINGLE-H1" => "MD025",
2841 "NO-TRAILING-PUNCTUATION" => "MD026",
2842 "NO-MULTIPLE-SPACE-BLOCKQUOTE" => "MD027",
2843 "NO-BLANKS-BLOCKQUOTE" => "MD028",
2844 "OL-PREFIX" => "MD029",
2845 "LIST-MARKER-SPACE" => "MD030",
2846 "BLANKS-AROUND-FENCES" => "MD031",
2847 "BLANKS-AROUND-LISTS" => "MD032",
2848 "NO-INLINE-HTML" => "MD033",
2849 "NO-BARE-URLS" => "MD034",
2850 "HR-STYLE" => "MD035",
2851 "NO-EMPHASIS-AS-HEADING" => "MD036",
2852 "NO-SPACE-IN-EMPHASIS" => "MD037",
2853 "NO-SPACE-IN-CODE" => "MD038",
2854 "NO-SPACE-IN-LINKS" => "MD039",
2855 "FENCED-CODE-LANGUAGE" => "MD040",
2856 "FIRST-LINE-HEADING" => "MD041",
2857 "FIRST-LINE-H1" => "MD041",
2858 "NO-EMPTY-LINKS" => "MD042",
2859 "REQUIRED-HEADINGS" => "MD043",
2860 "PROPER-NAMES" => "MD044",
2861 "NO-ALT-TEXT" => "MD045",
2862 "CODE-BLOCK-STYLE" => "MD046",
2863 "SINGLE-TRAILING-NEWLINE" => "MD047",
2864 "CODE-FENCE-STYLE" => "MD048",
2865 "EMPHASIS-STYLE" => "MD049",
2866 "STRONG-STYLE" => "MD050",
2867 "LINK-FRAGMENTS" => "MD051",
2868 "REFERENCE-LINKS-IMAGES" => "MD052",
2869 "LINK-IMAGE-REFERENCE-DEFINITIONS" => "MD053",
2870 "LINK-IMAGE-STYLE" => "MD054",
2871 "TABLE-PIPE-STYLE" => "MD055",
2872 "TABLE-COLUMN-COUNT" => "MD056",
2873 "EXISTING-RELATIVE-LINKS" => "MD057",
2874 "BLANKS-AROUND-TABLES" => "MD058",
2875 "TABLE-CELL-ALIGNMENT" => "MD059",
2876 "TABLE-FORMAT" => "MD060",
2877 "FORBIDDEN-TERMS" => "MD061",
2878};
2879
2880pub(crate) fn resolve_rule_name_alias(key: &str) -> Option<&'static str> {
2884 let normalized_key = key.to_ascii_uppercase().replace('_', "-");
2886
2887 RULE_ALIAS_MAP.get(normalized_key.as_str()).copied()
2889}
2890
2891#[derive(Debug, Clone)]
2893pub struct ConfigValidationWarning {
2894 pub message: String,
2895 pub rule: Option<String>,
2896 pub key: Option<String>,
2897}
2898
2899fn validate_config_sourced_internal<S>(
2902 sourced: &SourcedConfig<S>,
2903 registry: &RuleRegistry,
2904) -> Vec<ConfigValidationWarning> {
2905 validate_config_sourced_impl(&sourced.rules, &sourced.unknown_keys, registry)
2906}
2907
2908fn validate_config_sourced_impl(
2910 rules: &BTreeMap<String, SourcedRuleConfig>,
2911 unknown_keys: &[(String, String, Option<String>)],
2912 registry: &RuleRegistry,
2913) -> Vec<ConfigValidationWarning> {
2914 let mut warnings = Vec::new();
2915 let known_rules = registry.rule_names();
2916 for rule in rules.keys() {
2918 if !known_rules.contains(rule) {
2919 let all_rule_names: Vec<String> = RULE_ALIAS_MAP.keys().map(|s| s.to_string()).collect();
2921 let message = if let Some(suggestion) = suggest_similar_key(rule, &all_rule_names) {
2922 let formatted_suggestion = if suggestion.starts_with("MD") {
2924 suggestion
2925 } else {
2926 suggestion.to_lowercase()
2927 };
2928 format!("Unknown rule in config: {rule} (did you mean: {formatted_suggestion}?)")
2929 } else {
2930 format!("Unknown rule in config: {rule}")
2931 };
2932 warnings.push(ConfigValidationWarning {
2933 message,
2934 rule: Some(rule.clone()),
2935 key: None,
2936 });
2937 }
2938 }
2939 for (rule, rule_cfg) in rules {
2941 if let Some(valid_keys) = registry.config_keys_for(rule) {
2942 for key in rule_cfg.values.keys() {
2943 if !valid_keys.contains(key) {
2944 let valid_keys_vec: Vec<String> = valid_keys.iter().cloned().collect();
2945 let message = if let Some(suggestion) = suggest_similar_key(key, &valid_keys_vec) {
2946 format!("Unknown option for rule {rule}: {key} (did you mean: {suggestion}?)")
2947 } else {
2948 format!("Unknown option for rule {rule}: {key}")
2949 };
2950 warnings.push(ConfigValidationWarning {
2951 message,
2952 rule: Some(rule.clone()),
2953 key: Some(key.clone()),
2954 });
2955 } else {
2956 if let Some(expected) = registry.expected_value_for(rule, key) {
2958 let actual = &rule_cfg.values[key].value;
2959 if !toml_value_type_matches(expected, actual) {
2960 warnings.push(ConfigValidationWarning {
2961 message: format!(
2962 "Type mismatch for {}.{}: expected {}, got {}",
2963 rule,
2964 key,
2965 toml_type_name(expected),
2966 toml_type_name(actual)
2967 ),
2968 rule: Some(rule.clone()),
2969 key: Some(key.clone()),
2970 });
2971 }
2972 }
2973 }
2974 }
2975 }
2976 }
2977 let known_global_keys = vec![
2979 "enable".to_string(),
2980 "disable".to_string(),
2981 "include".to_string(),
2982 "exclude".to_string(),
2983 "respect-gitignore".to_string(),
2984 "line-length".to_string(),
2985 "fixable".to_string(),
2986 "unfixable".to_string(),
2987 "flavor".to_string(),
2988 "force-exclude".to_string(),
2989 "output-format".to_string(),
2990 "cache-dir".to_string(),
2991 "cache".to_string(),
2992 ];
2993
2994 for (section, key, file_path) in unknown_keys {
2995 if section.contains("[global]") || section.contains("[tool.rumdl]") {
2996 let message = if let Some(suggestion) = suggest_similar_key(key, &known_global_keys) {
2997 if let Some(path) = file_path {
2998 format!("Unknown global option in {path}: {key} (did you mean: {suggestion}?)")
2999 } else {
3000 format!("Unknown global option: {key} (did you mean: {suggestion}?)")
3001 }
3002 } else if let Some(path) = file_path {
3003 format!("Unknown global option in {path}: {key}")
3004 } else {
3005 format!("Unknown global option: {key}")
3006 };
3007 warnings.push(ConfigValidationWarning {
3008 message,
3009 rule: None,
3010 key: Some(key.clone()),
3011 });
3012 } else if !key.is_empty() {
3013 continue;
3015 } else {
3016 let rule_name = section.trim_matches(|c| c == '[' || c == ']');
3018 let all_rule_names: Vec<String> = RULE_ALIAS_MAP.keys().map(|s| s.to_string()).collect();
3019 let message = if let Some(suggestion) = suggest_similar_key(rule_name, &all_rule_names) {
3020 let formatted_suggestion = if suggestion.starts_with("MD") {
3022 suggestion
3023 } else {
3024 suggestion.to_lowercase()
3025 };
3026 if let Some(path) = file_path {
3027 format!("Unknown rule in {path}: {rule_name} (did you mean: {formatted_suggestion}?)")
3028 } else {
3029 format!("Unknown rule in config: {rule_name} (did you mean: {formatted_suggestion}?)")
3030 }
3031 } else if let Some(path) = file_path {
3032 format!("Unknown rule in {path}: {rule_name}")
3033 } else {
3034 format!("Unknown rule in config: {rule_name}")
3035 };
3036 warnings.push(ConfigValidationWarning {
3037 message,
3038 rule: None,
3039 key: None,
3040 });
3041 }
3042 }
3043 warnings
3044}
3045
3046pub fn validate_config_sourced(
3052 sourced: &SourcedConfig<ConfigLoaded>,
3053 registry: &RuleRegistry,
3054) -> Vec<ConfigValidationWarning> {
3055 validate_config_sourced_internal(sourced, registry)
3056}
3057
3058pub fn validate_config_sourced_validated(
3062 sourced: &SourcedConfig<ConfigValidated>,
3063 _registry: &RuleRegistry,
3064) -> Vec<ConfigValidationWarning> {
3065 sourced.validation_warnings.clone()
3066}
3067
3068fn toml_type_name(val: &toml::Value) -> &'static str {
3069 match val {
3070 toml::Value::String(_) => "string",
3071 toml::Value::Integer(_) => "integer",
3072 toml::Value::Float(_) => "float",
3073 toml::Value::Boolean(_) => "boolean",
3074 toml::Value::Array(_) => "array",
3075 toml::Value::Table(_) => "table",
3076 toml::Value::Datetime(_) => "datetime",
3077 }
3078}
3079
3080fn levenshtein_distance(s1: &str, s2: &str) -> usize {
3082 let len1 = s1.len();
3083 let len2 = s2.len();
3084
3085 if len1 == 0 {
3086 return len2;
3087 }
3088 if len2 == 0 {
3089 return len1;
3090 }
3091
3092 let s1_chars: Vec<char> = s1.chars().collect();
3093 let s2_chars: Vec<char> = s2.chars().collect();
3094
3095 let mut prev_row: Vec<usize> = (0..=len2).collect();
3096 let mut curr_row = vec![0; len2 + 1];
3097
3098 for i in 1..=len1 {
3099 curr_row[0] = i;
3100 for j in 1..=len2 {
3101 let cost = if s1_chars[i - 1] == s2_chars[j - 1] { 0 } else { 1 };
3102 curr_row[j] = (prev_row[j] + 1) .min(curr_row[j - 1] + 1) .min(prev_row[j - 1] + cost); }
3106 std::mem::swap(&mut prev_row, &mut curr_row);
3107 }
3108
3109 prev_row[len2]
3110}
3111
3112fn suggest_similar_key(unknown: &str, valid_keys: &[String]) -> Option<String> {
3114 let unknown_lower = unknown.to_lowercase();
3115 let max_distance = 2.max(unknown.len() / 3); let mut best_match: Option<(String, usize)> = None;
3118
3119 for valid in valid_keys {
3120 let valid_lower = valid.to_lowercase();
3121 let distance = levenshtein_distance(&unknown_lower, &valid_lower);
3122
3123 if distance <= max_distance {
3124 if let Some((_, best_dist)) = &best_match {
3125 if distance < *best_dist {
3126 best_match = Some((valid.clone(), distance));
3127 }
3128 } else {
3129 best_match = Some((valid.clone(), distance));
3130 }
3131 }
3132 }
3133
3134 best_match.map(|(key, _)| key)
3135}
3136
3137fn toml_value_type_matches(expected: &toml::Value, actual: &toml::Value) -> bool {
3138 use toml::Value::*;
3139 match (expected, actual) {
3140 (String(_), String(_)) => true,
3141 (Integer(_), Integer(_)) => true,
3142 (Float(_), Float(_)) => true,
3143 (Boolean(_), Boolean(_)) => true,
3144 (Array(_), Array(_)) => true,
3145 (Table(_), Table(_)) => true,
3146 (Datetime(_), Datetime(_)) => true,
3147 (Float(_), Integer(_)) => true,
3149 _ => false,
3150 }
3151}
3152
3153fn parse_pyproject_toml(content: &str, path: &str) -> Result<Option<SourcedConfigFragment>, ConfigError> {
3155 let doc: toml::Value =
3156 toml::from_str(content).map_err(|e| ConfigError::ParseError(format!("{path}: Failed to parse TOML: {e}")))?;
3157 let mut fragment = SourcedConfigFragment::default();
3158 let source = ConfigSource::PyprojectToml;
3159 let file = Some(path.to_string());
3160
3161 let all_rules = rules::all_rules(&Config::default());
3163 let registry = RuleRegistry::from_rules(&all_rules);
3164
3165 if let Some(rumdl_config) = doc.get("tool").and_then(|t| t.get("rumdl"))
3167 && let Some(rumdl_table) = rumdl_config.as_table()
3168 {
3169 let extract_global_config = |fragment: &mut SourcedConfigFragment, table: &toml::value::Table| {
3171 if let Some(enable) = table.get("enable")
3173 && let Ok(values) = Vec::<String>::deserialize(enable.clone())
3174 {
3175 let normalized_values = values
3177 .into_iter()
3178 .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3179 .collect();
3180 fragment
3181 .global
3182 .enable
3183 .push_override(normalized_values, source, file.clone(), None);
3184 }
3185
3186 if let Some(disable) = table.get("disable")
3187 && let Ok(values) = Vec::<String>::deserialize(disable.clone())
3188 {
3189 let normalized_values: Vec<String> = values
3191 .into_iter()
3192 .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3193 .collect();
3194 fragment
3195 .global
3196 .disable
3197 .push_override(normalized_values, source, file.clone(), None);
3198 }
3199
3200 if let Some(include) = table.get("include")
3201 && let Ok(values) = Vec::<String>::deserialize(include.clone())
3202 {
3203 fragment
3204 .global
3205 .include
3206 .push_override(values, source, file.clone(), None);
3207 }
3208
3209 if let Some(exclude) = table.get("exclude")
3210 && let Ok(values) = Vec::<String>::deserialize(exclude.clone())
3211 {
3212 fragment
3213 .global
3214 .exclude
3215 .push_override(values, source, file.clone(), None);
3216 }
3217
3218 if let Some(respect_gitignore) = table
3219 .get("respect-gitignore")
3220 .or_else(|| table.get("respect_gitignore"))
3221 && let Ok(value) = bool::deserialize(respect_gitignore.clone())
3222 {
3223 fragment
3224 .global
3225 .respect_gitignore
3226 .push_override(value, source, file.clone(), None);
3227 }
3228
3229 if let Some(force_exclude) = table.get("force-exclude").or_else(|| table.get("force_exclude"))
3230 && let Ok(value) = bool::deserialize(force_exclude.clone())
3231 {
3232 fragment
3233 .global
3234 .force_exclude
3235 .push_override(value, source, file.clone(), None);
3236 }
3237
3238 if let Some(output_format) = table.get("output-format").or_else(|| table.get("output_format"))
3239 && let Ok(value) = String::deserialize(output_format.clone())
3240 {
3241 if fragment.global.output_format.is_none() {
3242 fragment.global.output_format = Some(SourcedValue::new(value.clone(), source));
3243 } else {
3244 fragment
3245 .global
3246 .output_format
3247 .as_mut()
3248 .unwrap()
3249 .push_override(value, source, file.clone(), None);
3250 }
3251 }
3252
3253 if let Some(fixable) = table.get("fixable")
3254 && let Ok(values) = Vec::<String>::deserialize(fixable.clone())
3255 {
3256 let normalized_values = values
3257 .into_iter()
3258 .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3259 .collect();
3260 fragment
3261 .global
3262 .fixable
3263 .push_override(normalized_values, source, file.clone(), None);
3264 }
3265
3266 if let Some(unfixable) = table.get("unfixable")
3267 && let Ok(values) = Vec::<String>::deserialize(unfixable.clone())
3268 {
3269 let normalized_values = values
3270 .into_iter()
3271 .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3272 .collect();
3273 fragment
3274 .global
3275 .unfixable
3276 .push_override(normalized_values, source, file.clone(), None);
3277 }
3278
3279 if let Some(flavor) = table.get("flavor")
3280 && let Ok(value) = MarkdownFlavor::deserialize(flavor.clone())
3281 {
3282 fragment.global.flavor.push_override(value, source, file.clone(), None);
3283 }
3284
3285 if let Some(line_length) = table.get("line-length").or_else(|| table.get("line_length"))
3287 && let Ok(value) = u64::deserialize(line_length.clone())
3288 {
3289 fragment
3290 .global
3291 .line_length
3292 .push_override(LineLength::new(value as usize), source, file.clone(), None);
3293
3294 let norm_md013_key = normalize_key("MD013");
3296 let rule_entry = fragment.rules.entry(norm_md013_key).or_default();
3297 let norm_line_length_key = normalize_key("line-length");
3298 let sv = rule_entry
3299 .values
3300 .entry(norm_line_length_key)
3301 .or_insert_with(|| SourcedValue::new(line_length.clone(), ConfigSource::Default));
3302 sv.push_override(line_length.clone(), source, file.clone(), None);
3303 }
3304
3305 if let Some(cache_dir) = table.get("cache-dir").or_else(|| table.get("cache_dir"))
3306 && let Ok(value) = String::deserialize(cache_dir.clone())
3307 {
3308 if fragment.global.cache_dir.is_none() {
3309 fragment.global.cache_dir = Some(SourcedValue::new(value.clone(), source));
3310 } else {
3311 fragment
3312 .global
3313 .cache_dir
3314 .as_mut()
3315 .unwrap()
3316 .push_override(value, source, file.clone(), None);
3317 }
3318 }
3319
3320 if let Some(cache) = table.get("cache")
3321 && let Ok(value) = bool::deserialize(cache.clone())
3322 {
3323 fragment.global.cache.push_override(value, source, file.clone(), None);
3324 }
3325 };
3326
3327 if let Some(global_table) = rumdl_table.get("global").and_then(|g| g.as_table()) {
3329 extract_global_config(&mut fragment, global_table);
3330 }
3331
3332 extract_global_config(&mut fragment, rumdl_table);
3334
3335 let per_file_ignores_key = rumdl_table
3338 .get("per-file-ignores")
3339 .or_else(|| rumdl_table.get("per_file_ignores"));
3340
3341 if let Some(per_file_ignores_value) = per_file_ignores_key
3342 && let Some(per_file_table) = per_file_ignores_value.as_table()
3343 {
3344 let mut per_file_map = HashMap::new();
3345 for (pattern, rules_value) in per_file_table {
3346 if let Ok(rules) = Vec::<String>::deserialize(rules_value.clone()) {
3347 let normalized_rules = rules
3348 .into_iter()
3349 .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3350 .collect();
3351 per_file_map.insert(pattern.clone(), normalized_rules);
3352 } else {
3353 log::warn!(
3354 "[WARN] Expected array for per-file-ignores pattern '{pattern}' in {path}, found {rules_value:?}"
3355 );
3356 }
3357 }
3358 fragment
3359 .per_file_ignores
3360 .push_override(per_file_map, source, file.clone(), None);
3361 }
3362
3363 for (key, value) in rumdl_table {
3365 let norm_rule_key = normalize_key(key);
3366
3367 let is_global_key = [
3370 "enable",
3371 "disable",
3372 "include",
3373 "exclude",
3374 "respect_gitignore",
3375 "respect-gitignore",
3376 "force_exclude",
3377 "force-exclude",
3378 "output_format",
3379 "output-format",
3380 "fixable",
3381 "unfixable",
3382 "per-file-ignores",
3383 "per_file_ignores",
3384 "global",
3385 "flavor",
3386 "cache_dir",
3387 "cache-dir",
3388 "cache",
3389 ]
3390 .contains(&norm_rule_key.as_str());
3391
3392 let is_line_length_global =
3394 (norm_rule_key == "line-length" || norm_rule_key == "line_length") && !value.is_table();
3395
3396 if is_global_key || is_line_length_global {
3397 continue;
3398 }
3399
3400 if let Some(resolved_rule_name) = registry.resolve_rule_name(key)
3402 && value.is_table()
3403 && let Some(rule_config_table) = value.as_table()
3404 {
3405 let rule_entry = fragment.rules.entry(resolved_rule_name.clone()).or_default();
3406 for (rk, rv) in rule_config_table {
3407 let norm_rk = normalize_key(rk);
3408
3409 if norm_rk == "severity" {
3411 if let Ok(severity) = crate::rule::Severity::deserialize(rv.clone()) {
3412 if rule_entry.severity.is_none() {
3413 rule_entry.severity = Some(SourcedValue::new(severity, source));
3414 } else {
3415 rule_entry.severity.as_mut().unwrap().push_override(
3416 severity,
3417 source,
3418 file.clone(),
3419 None,
3420 );
3421 }
3422 }
3423 continue; }
3425
3426 let toml_val = rv.clone();
3427
3428 let sv = rule_entry
3429 .values
3430 .entry(norm_rk.clone())
3431 .or_insert_with(|| SourcedValue::new(toml_val.clone(), ConfigSource::Default));
3432 sv.push_override(toml_val, source, file.clone(), None);
3433 }
3434 } else if registry.resolve_rule_name(key).is_none() {
3435 fragment
3438 .unknown_keys
3439 .push(("[tool.rumdl]".to_string(), key.to_string(), Some(path.to_string())));
3440 }
3441 }
3442 }
3443
3444 if let Some(tool_table) = doc.get("tool").and_then(|t| t.as_table()) {
3446 for (key, value) in tool_table.iter() {
3447 if let Some(rule_name) = key.strip_prefix("rumdl.") {
3448 if let Some(resolved_rule_name) = registry.resolve_rule_name(rule_name) {
3450 if let Some(rule_table) = value.as_table() {
3451 let rule_entry = fragment.rules.entry(resolved_rule_name.clone()).or_default();
3452 for (rk, rv) in rule_table {
3453 let norm_rk = normalize_key(rk);
3454
3455 if norm_rk == "severity" {
3457 if let Ok(severity) = crate::rule::Severity::deserialize(rv.clone()) {
3458 if rule_entry.severity.is_none() {
3459 rule_entry.severity = Some(SourcedValue::new(severity, source));
3460 } else {
3461 rule_entry.severity.as_mut().unwrap().push_override(
3462 severity,
3463 source,
3464 file.clone(),
3465 None,
3466 );
3467 }
3468 }
3469 continue; }
3471
3472 let toml_val = rv.clone();
3473 let sv = rule_entry
3474 .values
3475 .entry(norm_rk.clone())
3476 .or_insert_with(|| SourcedValue::new(toml_val.clone(), source));
3477 sv.push_override(toml_val, source, file.clone(), None);
3478 }
3479 }
3480 } else if rule_name.to_ascii_uppercase().starts_with("MD")
3481 || rule_name.chars().any(|c| c.is_alphabetic())
3482 {
3483 fragment.unknown_keys.push((
3485 format!("[tool.rumdl.{rule_name}]"),
3486 String::new(),
3487 Some(path.to_string()),
3488 ));
3489 }
3490 }
3491 }
3492 }
3493
3494 if let Some(doc_table) = doc.as_table() {
3496 for (key, value) in doc_table.iter() {
3497 if let Some(rule_name) = key.strip_prefix("tool.rumdl.") {
3498 if let Some(resolved_rule_name) = registry.resolve_rule_name(rule_name) {
3500 if let Some(rule_table) = value.as_table() {
3501 let rule_entry = fragment.rules.entry(resolved_rule_name.clone()).or_default();
3502 for (rk, rv) in rule_table {
3503 let norm_rk = normalize_key(rk);
3504
3505 if norm_rk == "severity" {
3507 if let Ok(severity) = crate::rule::Severity::deserialize(rv.clone()) {
3508 if rule_entry.severity.is_none() {
3509 rule_entry.severity = Some(SourcedValue::new(severity, source));
3510 } else {
3511 rule_entry.severity.as_mut().unwrap().push_override(
3512 severity,
3513 source,
3514 file.clone(),
3515 None,
3516 );
3517 }
3518 }
3519 continue; }
3521
3522 let toml_val = rv.clone();
3523 let sv = rule_entry
3524 .values
3525 .entry(norm_rk.clone())
3526 .or_insert_with(|| SourcedValue::new(toml_val.clone(), source));
3527 sv.push_override(toml_val, source, file.clone(), None);
3528 }
3529 }
3530 } else if rule_name.to_ascii_uppercase().starts_with("MD")
3531 || rule_name.chars().any(|c| c.is_alphabetic())
3532 {
3533 fragment.unknown_keys.push((
3535 format!("[tool.rumdl.{rule_name}]"),
3536 String::new(),
3537 Some(path.to_string()),
3538 ));
3539 }
3540 }
3541 }
3542 }
3543
3544 let has_any = !fragment.global.enable.value.is_empty()
3546 || !fragment.global.disable.value.is_empty()
3547 || !fragment.global.include.value.is_empty()
3548 || !fragment.global.exclude.value.is_empty()
3549 || !fragment.global.fixable.value.is_empty()
3550 || !fragment.global.unfixable.value.is_empty()
3551 || fragment.global.output_format.is_some()
3552 || fragment.global.cache_dir.is_some()
3553 || !fragment.global.cache.value
3554 || !fragment.per_file_ignores.value.is_empty()
3555 || !fragment.rules.is_empty();
3556 if has_any { Ok(Some(fragment)) } else { Ok(None) }
3557}
3558
3559fn parse_rumdl_toml(content: &str, path: &str, source: ConfigSource) -> Result<SourcedConfigFragment, ConfigError> {
3561 let doc = content
3562 .parse::<DocumentMut>()
3563 .map_err(|e| ConfigError::ParseError(format!("{path}: Failed to parse TOML: {e}")))?;
3564 let mut fragment = SourcedConfigFragment::default();
3565 let file = Some(path.to_string());
3567
3568 let all_rules = rules::all_rules(&Config::default());
3570 let registry = RuleRegistry::from_rules(&all_rules);
3571
3572 if let Some(global_item) = doc.get("global")
3574 && let Some(global_table) = global_item.as_table()
3575 {
3576 for (key, value_item) in global_table.iter() {
3577 let norm_key = normalize_key(key);
3578 match norm_key.as_str() {
3579 "enable" | "disable" | "include" | "exclude" => {
3580 if let Some(toml_edit::Value::Array(formatted_array)) = value_item.as_value() {
3581 let values: Vec<String> = formatted_array
3583 .iter()
3584 .filter_map(|item| item.as_str()) .map(|s| s.to_string())
3586 .collect();
3587
3588 let final_values = if norm_key == "enable" || norm_key == "disable" {
3590 values
3591 .into_iter()
3592 .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3593 .collect()
3594 } else {
3595 values
3596 };
3597
3598 match norm_key.as_str() {
3599 "enable" => fragment
3600 .global
3601 .enable
3602 .push_override(final_values, source, file.clone(), None),
3603 "disable" => {
3604 fragment
3605 .global
3606 .disable
3607 .push_override(final_values, source, file.clone(), None)
3608 }
3609 "include" => {
3610 fragment
3611 .global
3612 .include
3613 .push_override(final_values, source, file.clone(), None)
3614 }
3615 "exclude" => {
3616 fragment
3617 .global
3618 .exclude
3619 .push_override(final_values, source, file.clone(), None)
3620 }
3621 _ => unreachable!("Outer match guarantees only enable/disable/include/exclude"),
3622 }
3623 } else {
3624 log::warn!(
3625 "[WARN] Expected array for global key '{}' in {}, found {}",
3626 key,
3627 path,
3628 value_item.type_name()
3629 );
3630 }
3631 }
3632 "respect_gitignore" | "respect-gitignore" => {
3633 if let Some(toml_edit::Value::Boolean(formatted_bool)) = value_item.as_value() {
3635 let val = *formatted_bool.value();
3636 fragment
3637 .global
3638 .respect_gitignore
3639 .push_override(val, source, file.clone(), None);
3640 } else {
3641 log::warn!(
3642 "[WARN] Expected boolean for global key '{}' in {}, found {}",
3643 key,
3644 path,
3645 value_item.type_name()
3646 );
3647 }
3648 }
3649 "force_exclude" | "force-exclude" => {
3650 if let Some(toml_edit::Value::Boolean(formatted_bool)) = value_item.as_value() {
3652 let val = *formatted_bool.value();
3653 fragment
3654 .global
3655 .force_exclude
3656 .push_override(val, source, file.clone(), None);
3657 } else {
3658 log::warn!(
3659 "[WARN] Expected boolean for global key '{}' in {}, found {}",
3660 key,
3661 path,
3662 value_item.type_name()
3663 );
3664 }
3665 }
3666 "line_length" | "line-length" => {
3667 if let Some(toml_edit::Value::Integer(formatted_int)) = value_item.as_value() {
3669 let val = LineLength::new(*formatted_int.value() as usize);
3670 fragment
3671 .global
3672 .line_length
3673 .push_override(val, source, file.clone(), None);
3674 } else {
3675 log::warn!(
3676 "[WARN] Expected integer for global key '{}' in {}, found {}",
3677 key,
3678 path,
3679 value_item.type_name()
3680 );
3681 }
3682 }
3683 "output_format" | "output-format" => {
3684 if let Some(toml_edit::Value::String(formatted_string)) = value_item.as_value() {
3686 let val = formatted_string.value().clone();
3687 if fragment.global.output_format.is_none() {
3688 fragment.global.output_format = Some(SourcedValue::new(val.clone(), source));
3689 } else {
3690 fragment.global.output_format.as_mut().unwrap().push_override(
3691 val,
3692 source,
3693 file.clone(),
3694 None,
3695 );
3696 }
3697 } else {
3698 log::warn!(
3699 "[WARN] Expected string for global key '{}' in {}, found {}",
3700 key,
3701 path,
3702 value_item.type_name()
3703 );
3704 }
3705 }
3706 "cache_dir" | "cache-dir" => {
3707 if let Some(toml_edit::Value::String(formatted_string)) = value_item.as_value() {
3709 let val = formatted_string.value().clone();
3710 if fragment.global.cache_dir.is_none() {
3711 fragment.global.cache_dir = Some(SourcedValue::new(val.clone(), source));
3712 } else {
3713 fragment
3714 .global
3715 .cache_dir
3716 .as_mut()
3717 .unwrap()
3718 .push_override(val, source, file.clone(), None);
3719 }
3720 } else {
3721 log::warn!(
3722 "[WARN] Expected string for global key '{}' in {}, found {}",
3723 key,
3724 path,
3725 value_item.type_name()
3726 );
3727 }
3728 }
3729 "cache" => {
3730 if let Some(toml_edit::Value::Boolean(b)) = value_item.as_value() {
3731 let val = *b.value();
3732 fragment.global.cache.push_override(val, source, file.clone(), None);
3733 } else {
3734 log::warn!(
3735 "[WARN] Expected boolean for global key '{}' in {}, found {}",
3736 key,
3737 path,
3738 value_item.type_name()
3739 );
3740 }
3741 }
3742 "fixable" => {
3743 if let Some(toml_edit::Value::Array(formatted_array)) = value_item.as_value() {
3744 let values: Vec<String> = formatted_array
3745 .iter()
3746 .filter_map(|item| item.as_str())
3747 .map(normalize_key)
3748 .collect();
3749 fragment
3750 .global
3751 .fixable
3752 .push_override(values, source, file.clone(), None);
3753 } else {
3754 log::warn!(
3755 "[WARN] Expected array for global key '{}' in {}, found {}",
3756 key,
3757 path,
3758 value_item.type_name()
3759 );
3760 }
3761 }
3762 "unfixable" => {
3763 if let Some(toml_edit::Value::Array(formatted_array)) = value_item.as_value() {
3764 let values: Vec<String> = formatted_array
3765 .iter()
3766 .filter_map(|item| item.as_str())
3767 .map(|s| registry.resolve_rule_name(s).unwrap_or_else(|| normalize_key(s)))
3768 .collect();
3769 fragment
3770 .global
3771 .unfixable
3772 .push_override(values, source, file.clone(), None);
3773 } else {
3774 log::warn!(
3775 "[WARN] Expected array for global key '{}' in {}, found {}",
3776 key,
3777 path,
3778 value_item.type_name()
3779 );
3780 }
3781 }
3782 "flavor" => {
3783 if let Some(toml_edit::Value::String(formatted_string)) = value_item.as_value() {
3784 let val = formatted_string.value();
3785 if let Ok(flavor) = MarkdownFlavor::from_str(val) {
3786 fragment.global.flavor.push_override(flavor, source, file.clone(), None);
3787 } else {
3788 log::warn!("[WARN] Unknown markdown flavor '{val}' in {path}");
3789 }
3790 } else {
3791 log::warn!(
3792 "[WARN] Expected string for global key '{}' in {}, found {}",
3793 key,
3794 path,
3795 value_item.type_name()
3796 );
3797 }
3798 }
3799 _ => {
3800 fragment
3802 .unknown_keys
3803 .push(("[global]".to_string(), key.to_string(), Some(path.to_string())));
3804 log::warn!("[WARN] Unknown key in [global] section of {path}: {key}");
3805 }
3806 }
3807 }
3808 }
3809
3810 if let Some(per_file_item) = doc.get("per-file-ignores")
3812 && let Some(per_file_table) = per_file_item.as_table()
3813 {
3814 let mut per_file_map = HashMap::new();
3815 for (pattern, value_item) in per_file_table.iter() {
3816 if let Some(toml_edit::Value::Array(formatted_array)) = value_item.as_value() {
3817 let rules: Vec<String> = formatted_array
3818 .iter()
3819 .filter_map(|item| item.as_str())
3820 .map(|s| registry.resolve_rule_name(s).unwrap_or_else(|| normalize_key(s)))
3821 .collect();
3822 per_file_map.insert(pattern.to_string(), rules);
3823 } else {
3824 let type_name = value_item.type_name();
3825 log::warn!(
3826 "[WARN] Expected array for per-file-ignores pattern '{pattern}' in {path}, found {type_name}"
3827 );
3828 }
3829 }
3830 fragment
3831 .per_file_ignores
3832 .push_override(per_file_map, source, file.clone(), None);
3833 }
3834
3835 for (key, item) in doc.iter() {
3837 if key == "global" || key == "per-file-ignores" {
3839 continue;
3840 }
3841
3842 let norm_rule_name = if let Some(resolved) = registry.resolve_rule_name(key) {
3844 resolved
3845 } else {
3846 fragment
3848 .unknown_keys
3849 .push((format!("[{key}]"), String::new(), Some(path.to_string())));
3850 continue;
3851 };
3852
3853 if let Some(tbl) = item.as_table() {
3854 let rule_entry = fragment.rules.entry(norm_rule_name.clone()).or_default();
3855 for (rk, rv_item) in tbl.iter() {
3856 let norm_rk = normalize_key(rk);
3857
3858 if norm_rk == "severity" {
3860 if let Some(toml_edit::Value::String(formatted_string)) = rv_item.as_value() {
3861 let severity_str = formatted_string.value();
3862 match crate::rule::Severity::deserialize(toml::Value::String(severity_str.to_string())) {
3863 Ok(severity) => {
3864 if rule_entry.severity.is_none() {
3865 rule_entry.severity = Some(SourcedValue::new(severity, source));
3866 } else {
3867 rule_entry.severity.as_mut().unwrap().push_override(
3868 severity,
3869 source,
3870 file.clone(),
3871 None,
3872 );
3873 }
3874 }
3875 Err(_) => {
3876 log::warn!(
3877 "[WARN] Invalid severity '{severity_str}' for rule {norm_rule_name} in {path}. Valid values: error, warning"
3878 );
3879 }
3880 }
3881 }
3882 continue; }
3884
3885 let maybe_toml_val: Option<toml::Value> = match rv_item.as_value() {
3886 Some(toml_edit::Value::String(formatted)) => Some(toml::Value::String(formatted.value().clone())),
3887 Some(toml_edit::Value::Integer(formatted)) => Some(toml::Value::Integer(*formatted.value())),
3888 Some(toml_edit::Value::Float(formatted)) => Some(toml::Value::Float(*formatted.value())),
3889 Some(toml_edit::Value::Boolean(formatted)) => Some(toml::Value::Boolean(*formatted.value())),
3890 Some(toml_edit::Value::Datetime(formatted)) => Some(toml::Value::Datetime(*formatted.value())),
3891 Some(toml_edit::Value::Array(formatted_array)) => {
3892 let mut values = Vec::new();
3894 for item in formatted_array.iter() {
3895 match item {
3896 toml_edit::Value::String(formatted) => {
3897 values.push(toml::Value::String(formatted.value().clone()))
3898 }
3899 toml_edit::Value::Integer(formatted) => {
3900 values.push(toml::Value::Integer(*formatted.value()))
3901 }
3902 toml_edit::Value::Float(formatted) => {
3903 values.push(toml::Value::Float(*formatted.value()))
3904 }
3905 toml_edit::Value::Boolean(formatted) => {
3906 values.push(toml::Value::Boolean(*formatted.value()))
3907 }
3908 toml_edit::Value::Datetime(formatted) => {
3909 values.push(toml::Value::Datetime(*formatted.value()))
3910 }
3911 _ => {
3912 log::warn!(
3913 "[WARN] Skipping unsupported array element type in key '{norm_rule_name}.{norm_rk}' in {path}"
3914 );
3915 }
3916 }
3917 }
3918 Some(toml::Value::Array(values))
3919 }
3920 Some(toml_edit::Value::InlineTable(_)) => {
3921 log::warn!(
3922 "[WARN] Skipping inline table value for key '{norm_rule_name}.{norm_rk}' in {path}. Table conversion not yet fully implemented in parser."
3923 );
3924 None
3925 }
3926 None => {
3927 log::warn!(
3928 "[WARN] Skipping non-value item for key '{norm_rule_name}.{norm_rk}' in {path}. Expected simple value."
3929 );
3930 None
3931 }
3932 };
3933 if let Some(toml_val) = maybe_toml_val {
3934 let sv = rule_entry
3935 .values
3936 .entry(norm_rk.clone())
3937 .or_insert_with(|| SourcedValue::new(toml_val.clone(), ConfigSource::Default));
3938 sv.push_override(toml_val, source, file.clone(), None);
3939 }
3940 }
3941 } else if item.is_value() {
3942 log::warn!("[WARN] Ignoring top-level value key in {path}: '{key}'. Expected a table like [{key}].");
3943 }
3944 }
3945
3946 Ok(fragment)
3947}
3948
3949fn load_from_markdownlint(path: &str) -> Result<SourcedConfigFragment, ConfigError> {
3951 let ml_config = crate::markdownlint_config::load_markdownlint_config(path)
3953 .map_err(|e| ConfigError::ParseError(format!("{path}: {e}")))?;
3954 Ok(ml_config.map_to_sourced_rumdl_config_fragment(Some(path)))
3955}
3956
3957#[cfg(test)]
3958#[path = "config_intelligent_merge_tests.rs"]
3959mod config_intelligent_merge_tests;