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