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 = if start_dir.is_relative() {
2351 std::env::current_dir()
2352 .map(|cwd| cwd.join(start_dir))
2353 .unwrap_or_else(|_| start_dir.to_path_buf())
2354 } else {
2355 start_dir.to_path_buf()
2356 };
2357 const MAX_DEPTH: usize = 100;
2358
2359 for _ in 0..MAX_DEPTH {
2360 if current.join(".git").exists() {
2361 log::debug!("[rumdl-config] Found .git at: {}", current.display());
2362 return current;
2363 }
2364
2365 match current.parent() {
2366 Some(parent) => current = parent.to_path_buf(),
2367 None => break,
2368 }
2369 }
2370
2371 log::debug!(
2373 "[rumdl-config] No .git found, using config location as project root: {}",
2374 start_dir.display()
2375 );
2376 start_dir.to_path_buf()
2377 }
2378
2379 fn discover_config_upward() -> Option<(std::path::PathBuf, std::path::PathBuf)> {
2385 use std::env;
2386
2387 const CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml", ".config/rumdl.toml", "pyproject.toml"];
2388 const MAX_DEPTH: usize = 100; let start_dir = match env::current_dir() {
2391 Ok(dir) => dir,
2392 Err(e) => {
2393 log::debug!("[rumdl-config] Failed to get current directory: {e}");
2394 return None;
2395 }
2396 };
2397
2398 let mut current_dir = start_dir.clone();
2399 let mut depth = 0;
2400 let mut found_config: Option<(std::path::PathBuf, std::path::PathBuf)> = None;
2401
2402 loop {
2403 if depth >= MAX_DEPTH {
2404 log::debug!("[rumdl-config] Maximum traversal depth reached");
2405 break;
2406 }
2407
2408 log::debug!("[rumdl-config] Searching for config in: {}", current_dir.display());
2409
2410 if found_config.is_none() {
2412 for config_name in CONFIG_FILES {
2413 let config_path = current_dir.join(config_name);
2414
2415 if config_path.exists() {
2416 if *config_name == "pyproject.toml" {
2418 if let Ok(content) = std::fs::read_to_string(&config_path) {
2419 if content.contains("[tool.rumdl]") || content.contains("tool.rumdl") {
2420 log::debug!("[rumdl-config] Found config file: {}", config_path.display());
2421 found_config = Some((config_path.clone(), current_dir.clone()));
2423 break;
2424 }
2425 log::debug!("[rumdl-config] Found pyproject.toml but no [tool.rumdl] section");
2426 continue;
2427 }
2428 } else {
2429 log::debug!("[rumdl-config] Found config file: {}", config_path.display());
2430 found_config = Some((config_path.clone(), current_dir.clone()));
2432 break;
2433 }
2434 }
2435 }
2436 }
2437
2438 if current_dir.join(".git").exists() {
2440 log::debug!("[rumdl-config] Stopping at .git directory");
2441 break;
2442 }
2443
2444 match current_dir.parent() {
2446 Some(parent) => {
2447 current_dir = parent.to_owned();
2448 depth += 1;
2449 }
2450 None => {
2451 log::debug!("[rumdl-config] Reached filesystem root");
2452 break;
2453 }
2454 }
2455 }
2456
2457 if let Some((config_path, config_dir)) = found_config {
2459 let project_root = Self::find_project_root_from(&config_dir);
2460 return Some((config_path, project_root));
2461 }
2462
2463 None
2464 }
2465
2466 fn discover_markdownlint_config_upward() -> Option<std::path::PathBuf> {
2470 use std::env;
2471
2472 const MAX_DEPTH: usize = 100;
2473
2474 let start_dir = match env::current_dir() {
2475 Ok(dir) => dir,
2476 Err(e) => {
2477 log::debug!("[rumdl-config] Failed to get current directory for markdownlint discovery: {e}");
2478 return None;
2479 }
2480 };
2481
2482 let mut current_dir = start_dir.clone();
2483 let mut depth = 0;
2484
2485 loop {
2486 if depth >= MAX_DEPTH {
2487 log::debug!("[rumdl-config] Maximum traversal depth reached for markdownlint discovery");
2488 break;
2489 }
2490
2491 log::debug!(
2492 "[rumdl-config] Searching for markdownlint config in: {}",
2493 current_dir.display()
2494 );
2495
2496 for config_name in MARKDOWNLINT_CONFIG_FILES {
2498 let config_path = current_dir.join(config_name);
2499 if config_path.exists() {
2500 log::debug!("[rumdl-config] Found markdownlint config: {}", config_path.display());
2501 return Some(config_path);
2502 }
2503 }
2504
2505 if current_dir.join(".git").exists() {
2507 log::debug!("[rumdl-config] Stopping markdownlint search at .git directory");
2508 break;
2509 }
2510
2511 match current_dir.parent() {
2513 Some(parent) => {
2514 current_dir = parent.to_owned();
2515 depth += 1;
2516 }
2517 None => {
2518 log::debug!("[rumdl-config] Reached filesystem root during markdownlint search");
2519 break;
2520 }
2521 }
2522 }
2523
2524 None
2525 }
2526
2527 fn user_configuration_path_impl(config_dir: &Path) -> Option<std::path::PathBuf> {
2529 let config_dir = config_dir.join("rumdl");
2530
2531 const USER_CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml", "pyproject.toml"];
2533
2534 log::debug!(
2535 "[rumdl-config] Checking for user configuration in: {}",
2536 config_dir.display()
2537 );
2538
2539 for filename in USER_CONFIG_FILES {
2540 let config_path = config_dir.join(filename);
2541
2542 if config_path.exists() {
2543 if *filename == "pyproject.toml" {
2545 if let Ok(content) = std::fs::read_to_string(&config_path) {
2546 if content.contains("[tool.rumdl]") || content.contains("tool.rumdl") {
2547 log::debug!("[rumdl-config] Found user configuration at: {}", config_path.display());
2548 return Some(config_path);
2549 }
2550 log::debug!("[rumdl-config] Found user pyproject.toml but no [tool.rumdl] section");
2551 continue;
2552 }
2553 } else {
2554 log::debug!("[rumdl-config] Found user configuration at: {}", config_path.display());
2555 return Some(config_path);
2556 }
2557 }
2558 }
2559
2560 log::debug!(
2561 "[rumdl-config] No user configuration found in: {}",
2562 config_dir.display()
2563 );
2564 None
2565 }
2566
2567 #[cfg(feature = "native")]
2570 fn user_configuration_path() -> Option<std::path::PathBuf> {
2571 use etcetera::{BaseStrategy, choose_base_strategy};
2572
2573 match choose_base_strategy() {
2574 Ok(strategy) => {
2575 let config_dir = strategy.config_dir();
2576 Self::user_configuration_path_impl(&config_dir)
2577 }
2578 Err(e) => {
2579 log::debug!("[rumdl-config] Failed to determine user config directory: {e}");
2580 None
2581 }
2582 }
2583 }
2584
2585 #[cfg(not(feature = "native"))]
2587 fn user_configuration_path() -> Option<std::path::PathBuf> {
2588 None
2589 }
2590
2591 fn load_explicit_config(sourced_config: &mut Self, path: &str) -> Result<(), ConfigError> {
2593 let path_obj = Path::new(path);
2594 let filename = path_obj.file_name().and_then(|name| name.to_str()).unwrap_or("");
2595 let path_str = path.to_string();
2596
2597 log::debug!("[rumdl-config] Loading explicit config file: {filename}");
2598
2599 if let Some(config_parent) = path_obj.parent() {
2601 let project_root = Self::find_project_root_from(config_parent);
2602 log::debug!(
2603 "[rumdl-config] Project root (from explicit config): {}",
2604 project_root.display()
2605 );
2606 sourced_config.project_root = Some(project_root);
2607 }
2608
2609 const MARKDOWNLINT_FILENAMES: &[&str] = &[".markdownlint.json", ".markdownlint.yaml", ".markdownlint.yml"];
2611
2612 if filename == "pyproject.toml" || filename == ".rumdl.toml" || filename == "rumdl.toml" {
2613 let content = std::fs::read_to_string(path).map_err(|e| ConfigError::IoError {
2614 source: e,
2615 path: path_str.clone(),
2616 })?;
2617 if filename == "pyproject.toml" {
2618 if let Some(fragment) = parse_pyproject_toml(&content, &path_str)? {
2619 sourced_config.merge(fragment);
2620 sourced_config.loaded_files.push(path_str);
2621 }
2622 } else {
2623 let fragment = parse_rumdl_toml(&content, &path_str, ConfigSource::ProjectConfig)?;
2624 sourced_config.merge(fragment);
2625 sourced_config.loaded_files.push(path_str);
2626 }
2627 } else if MARKDOWNLINT_FILENAMES.contains(&filename)
2628 || path_str.ends_with(".json")
2629 || path_str.ends_with(".jsonc")
2630 || path_str.ends_with(".yaml")
2631 || path_str.ends_with(".yml")
2632 {
2633 let fragment = load_from_markdownlint(&path_str)?;
2635 sourced_config.merge(fragment);
2636 sourced_config.loaded_files.push(path_str);
2637 } else {
2638 let content = std::fs::read_to_string(path).map_err(|e| ConfigError::IoError {
2640 source: e,
2641 path: path_str.clone(),
2642 })?;
2643 let fragment = parse_rumdl_toml(&content, &path_str, ConfigSource::ProjectConfig)?;
2644 sourced_config.merge(fragment);
2645 sourced_config.loaded_files.push(path_str);
2646 }
2647
2648 Ok(())
2649 }
2650
2651 fn load_user_config_as_fallback(
2653 sourced_config: &mut Self,
2654 user_config_dir: Option<&Path>,
2655 ) -> Result<(), ConfigError> {
2656 let user_config_path = if let Some(dir) = user_config_dir {
2657 Self::user_configuration_path_impl(dir)
2658 } else {
2659 Self::user_configuration_path()
2660 };
2661
2662 if let Some(user_config_path) = user_config_path {
2663 let path_str = user_config_path.display().to_string();
2664 let filename = user_config_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
2665
2666 log::debug!("[rumdl-config] Loading user config as fallback: {path_str}");
2667
2668 if filename == "pyproject.toml" {
2669 let content = std::fs::read_to_string(&user_config_path).map_err(|e| ConfigError::IoError {
2670 source: e,
2671 path: path_str.clone(),
2672 })?;
2673 if let Some(fragment) = parse_pyproject_toml(&content, &path_str)? {
2674 sourced_config.merge(fragment);
2675 sourced_config.loaded_files.push(path_str);
2676 }
2677 } else {
2678 let content = std::fs::read_to_string(&user_config_path).map_err(|e| ConfigError::IoError {
2679 source: e,
2680 path: path_str.clone(),
2681 })?;
2682 let fragment = parse_rumdl_toml(&content, &path_str, ConfigSource::UserConfig)?;
2683 sourced_config.merge(fragment);
2684 sourced_config.loaded_files.push(path_str);
2685 }
2686 } else {
2687 log::debug!("[rumdl-config] No user configuration file found");
2688 }
2689
2690 Ok(())
2691 }
2692
2693 #[doc(hidden)]
2695 pub fn load_with_discovery_impl(
2696 config_path: Option<&str>,
2697 cli_overrides: Option<&SourcedGlobalConfig>,
2698 skip_auto_discovery: bool,
2699 user_config_dir: Option<&Path>,
2700 ) -> Result<Self, ConfigError> {
2701 use std::env;
2702 log::debug!("[rumdl-config] Current working directory: {:?}", env::current_dir());
2703
2704 let mut sourced_config = SourcedConfig::default();
2705
2706 if let Some(path) = config_path {
2719 log::debug!("[rumdl-config] Explicit config_path provided: {path:?}");
2721 Self::load_explicit_config(&mut sourced_config, path)?;
2722 } else if skip_auto_discovery {
2723 log::debug!("[rumdl-config] Skipping config discovery due to --no-config/--isolated flag");
2724 } else {
2726 log::debug!("[rumdl-config] No explicit config_path, searching default locations");
2728
2729 if let Some((config_file, project_root)) = Self::discover_config_upward() {
2731 let path_str = config_file.display().to_string();
2733 let filename = config_file.file_name().and_then(|n| n.to_str()).unwrap_or("");
2734
2735 log::debug!("[rumdl-config] Found project config: {path_str}");
2736 log::debug!("[rumdl-config] Project root: {}", project_root.display());
2737
2738 sourced_config.project_root = Some(project_root);
2739
2740 if filename == "pyproject.toml" {
2741 let content = std::fs::read_to_string(&config_file).map_err(|e| ConfigError::IoError {
2742 source: e,
2743 path: path_str.clone(),
2744 })?;
2745 if let Some(fragment) = parse_pyproject_toml(&content, &path_str)? {
2746 sourced_config.merge(fragment);
2747 sourced_config.loaded_files.push(path_str);
2748 }
2749 } else if filename == ".rumdl.toml" || filename == "rumdl.toml" {
2750 let content = std::fs::read_to_string(&config_file).map_err(|e| ConfigError::IoError {
2751 source: e,
2752 path: path_str.clone(),
2753 })?;
2754 let fragment = parse_rumdl_toml(&content, &path_str, ConfigSource::ProjectConfig)?;
2755 sourced_config.merge(fragment);
2756 sourced_config.loaded_files.push(path_str);
2757 }
2758 } else {
2759 log::debug!("[rumdl-config] No rumdl config found, checking markdownlint config");
2761
2762 if let Some(markdownlint_path) = Self::discover_markdownlint_config_upward() {
2763 let path_str = markdownlint_path.display().to_string();
2764 log::debug!("[rumdl-config] Found markdownlint config: {path_str}");
2765 match load_from_markdownlint(&path_str) {
2766 Ok(fragment) => {
2767 sourced_config.merge(fragment);
2768 sourced_config.loaded_files.push(path_str);
2769 }
2770 Err(_e) => {
2771 log::debug!("[rumdl-config] Failed to load markdownlint config, trying user config");
2772 Self::load_user_config_as_fallback(&mut sourced_config, user_config_dir)?;
2773 }
2774 }
2775 } else {
2776 log::debug!("[rumdl-config] No project config found, using user config as fallback");
2778 Self::load_user_config_as_fallback(&mut sourced_config, user_config_dir)?;
2779 }
2780 }
2781 }
2782
2783 if let Some(cli) = cli_overrides {
2785 sourced_config
2786 .global
2787 .enable
2788 .merge_override(cli.enable.value.clone(), ConfigSource::Cli, None, None);
2789 sourced_config
2790 .global
2791 .disable
2792 .merge_override(cli.disable.value.clone(), ConfigSource::Cli, None, None);
2793 sourced_config
2794 .global
2795 .exclude
2796 .merge_override(cli.exclude.value.clone(), ConfigSource::Cli, None, None);
2797 sourced_config
2798 .global
2799 .include
2800 .merge_override(cli.include.value.clone(), ConfigSource::Cli, None, None);
2801 sourced_config.global.respect_gitignore.merge_override(
2802 cli.respect_gitignore.value,
2803 ConfigSource::Cli,
2804 None,
2805 None,
2806 );
2807 sourced_config
2808 .global
2809 .fixable
2810 .merge_override(cli.fixable.value.clone(), ConfigSource::Cli, None, None);
2811 sourced_config
2812 .global
2813 .unfixable
2814 .merge_override(cli.unfixable.value.clone(), ConfigSource::Cli, None, None);
2815 }
2817
2818 Ok(sourced_config)
2821 }
2822
2823 pub fn load_with_discovery(
2826 config_path: Option<&str>,
2827 cli_overrides: Option<&SourcedGlobalConfig>,
2828 skip_auto_discovery: bool,
2829 ) -> Result<Self, ConfigError> {
2830 Self::load_with_discovery_impl(config_path, cli_overrides, skip_auto_discovery, None)
2831 }
2832
2833 pub fn validate(self, registry: &RuleRegistry) -> Result<SourcedConfig<ConfigValidated>, ConfigError> {
2847 let warnings = validate_config_sourced_internal(&self, registry);
2848
2849 Ok(SourcedConfig {
2850 global: self.global,
2851 per_file_ignores: self.per_file_ignores,
2852 rules: self.rules,
2853 loaded_files: self.loaded_files,
2854 unknown_keys: self.unknown_keys,
2855 project_root: self.project_root,
2856 validation_warnings: warnings,
2857 _state: PhantomData,
2858 })
2859 }
2860
2861 pub fn validate_into(self, registry: &RuleRegistry) -> Result<(Config, Vec<ConfigValidationWarning>), ConfigError> {
2866 let validated = self.validate(registry)?;
2867 let warnings = validated.validation_warnings.clone();
2868 Ok((validated.into(), warnings))
2869 }
2870
2871 pub fn into_validated_unchecked(self) -> SourcedConfig<ConfigValidated> {
2882 SourcedConfig {
2883 global: self.global,
2884 per_file_ignores: self.per_file_ignores,
2885 rules: self.rules,
2886 loaded_files: self.loaded_files,
2887 unknown_keys: self.unknown_keys,
2888 project_root: self.project_root,
2889 validation_warnings: Vec::new(),
2890 _state: PhantomData,
2891 }
2892 }
2893}
2894
2895impl From<SourcedConfig<ConfigValidated>> for Config {
2900 fn from(sourced: SourcedConfig<ConfigValidated>) -> Self {
2901 let mut rules = BTreeMap::new();
2902 for (rule_name, sourced_rule_cfg) in sourced.rules {
2903 let normalized_rule_name = rule_name.to_ascii_uppercase();
2905 let severity = sourced_rule_cfg.severity.map(|sv| sv.value);
2906 let mut values = BTreeMap::new();
2907 for (key, sourced_val) in sourced_rule_cfg.values {
2908 values.insert(key, sourced_val.value);
2909 }
2910 rules.insert(normalized_rule_name, RuleConfig { severity, values });
2911 }
2912 #[allow(deprecated)]
2913 let global = GlobalConfig {
2914 enable: sourced.global.enable.value,
2915 disable: sourced.global.disable.value,
2916 exclude: sourced.global.exclude.value,
2917 include: sourced.global.include.value,
2918 respect_gitignore: sourced.global.respect_gitignore.value,
2919 line_length: sourced.global.line_length.value,
2920 output_format: sourced.global.output_format.as_ref().map(|v| v.value.clone()),
2921 fixable: sourced.global.fixable.value,
2922 unfixable: sourced.global.unfixable.value,
2923 flavor: sourced.global.flavor.value,
2924 force_exclude: sourced.global.force_exclude.value,
2925 cache_dir: sourced.global.cache_dir.as_ref().map(|v| v.value.clone()),
2926 cache: sourced.global.cache.value,
2927 };
2928 Config {
2929 global,
2930 per_file_ignores: sourced.per_file_ignores.value,
2931 rules,
2932 project_root: sourced.project_root,
2933 }
2934 }
2935}
2936
2937pub struct RuleRegistry {
2939 pub rule_schemas: std::collections::BTreeMap<String, toml::map::Map<String, toml::Value>>,
2941 pub rule_aliases: std::collections::BTreeMap<String, std::collections::HashMap<String, String>>,
2943}
2944
2945impl RuleRegistry {
2946 pub fn from_rules(rules: &[Box<dyn Rule>]) -> Self {
2948 let mut rule_schemas = std::collections::BTreeMap::new();
2949 let mut rule_aliases = std::collections::BTreeMap::new();
2950
2951 for rule in rules {
2952 let norm_name = if let Some((name, toml::Value::Table(table))) = rule.default_config_section() {
2953 let norm_name = normalize_key(&name); rule_schemas.insert(norm_name.clone(), table);
2955 norm_name
2956 } else {
2957 let norm_name = normalize_key(rule.name()); rule_schemas.insert(norm_name.clone(), toml::map::Map::new());
2959 norm_name
2960 };
2961
2962 if let Some(aliases) = rule.config_aliases() {
2964 rule_aliases.insert(norm_name, aliases);
2965 }
2966 }
2967
2968 RuleRegistry {
2969 rule_schemas,
2970 rule_aliases,
2971 }
2972 }
2973
2974 pub fn rule_names(&self) -> std::collections::BTreeSet<String> {
2976 self.rule_schemas.keys().cloned().collect()
2977 }
2978
2979 pub fn config_keys_for(&self, rule: &str) -> Option<std::collections::BTreeSet<String>> {
2981 self.rule_schemas.get(rule).map(|schema| {
2982 let mut all_keys = std::collections::BTreeSet::new();
2983
2984 all_keys.insert("severity".to_string());
2986
2987 for key in schema.keys() {
2989 all_keys.insert(key.clone());
2990 }
2991
2992 for key in schema.keys() {
2994 all_keys.insert(key.replace('_', "-"));
2996 all_keys.insert(key.replace('-', "_"));
2998 all_keys.insert(normalize_key(key));
3000 }
3001
3002 if let Some(aliases) = self.rule_aliases.get(rule) {
3004 for alias_key in aliases.keys() {
3005 all_keys.insert(alias_key.clone());
3006 all_keys.insert(alias_key.replace('_', "-"));
3008 all_keys.insert(alias_key.replace('-', "_"));
3009 all_keys.insert(normalize_key(alias_key));
3010 }
3011 }
3012
3013 all_keys
3014 })
3015 }
3016
3017 pub fn expected_value_for(&self, rule: &str, key: &str) -> Option<&toml::Value> {
3019 if let Some(schema) = self.rule_schemas.get(rule) {
3020 if let Some(aliases) = self.rule_aliases.get(rule)
3022 && let Some(canonical_key) = aliases.get(key)
3023 {
3024 if let Some(value) = schema.get(canonical_key) {
3026 return Some(value);
3027 }
3028 }
3029
3030 if let Some(value) = schema.get(key) {
3032 return Some(value);
3033 }
3034
3035 let key_variants = [
3037 key.replace('-', "_"), key.replace('_', "-"), normalize_key(key), ];
3041
3042 for variant in &key_variants {
3043 if let Some(value) = schema.get(variant) {
3044 return Some(value);
3045 }
3046 }
3047 }
3048 None
3049 }
3050
3051 pub fn resolve_rule_name(&self, name: &str) -> Option<String> {
3058 let normalized = normalize_key(name);
3060 if self.rule_schemas.contains_key(&normalized) {
3061 return Some(normalized);
3062 }
3063
3064 resolve_rule_name_alias(name).map(|s| s.to_string())
3066 }
3067}
3068
3069pub static RULE_ALIAS_MAP: phf::Map<&'static str, &'static str> = phf::phf_map! {
3072 "MD001" => "MD001",
3074 "MD003" => "MD003",
3075 "MD004" => "MD004",
3076 "MD005" => "MD005",
3077 "MD007" => "MD007",
3078 "MD009" => "MD009",
3079 "MD010" => "MD010",
3080 "MD011" => "MD011",
3081 "MD012" => "MD012",
3082 "MD013" => "MD013",
3083 "MD014" => "MD014",
3084 "MD018" => "MD018",
3085 "MD019" => "MD019",
3086 "MD020" => "MD020",
3087 "MD021" => "MD021",
3088 "MD022" => "MD022",
3089 "MD023" => "MD023",
3090 "MD024" => "MD024",
3091 "MD025" => "MD025",
3092 "MD026" => "MD026",
3093 "MD027" => "MD027",
3094 "MD028" => "MD028",
3095 "MD029" => "MD029",
3096 "MD030" => "MD030",
3097 "MD031" => "MD031",
3098 "MD032" => "MD032",
3099 "MD033" => "MD033",
3100 "MD034" => "MD034",
3101 "MD035" => "MD035",
3102 "MD036" => "MD036",
3103 "MD037" => "MD037",
3104 "MD038" => "MD038",
3105 "MD039" => "MD039",
3106 "MD040" => "MD040",
3107 "MD041" => "MD041",
3108 "MD042" => "MD042",
3109 "MD043" => "MD043",
3110 "MD044" => "MD044",
3111 "MD045" => "MD045",
3112 "MD046" => "MD046",
3113 "MD047" => "MD047",
3114 "MD048" => "MD048",
3115 "MD049" => "MD049",
3116 "MD050" => "MD050",
3117 "MD051" => "MD051",
3118 "MD052" => "MD052",
3119 "MD053" => "MD053",
3120 "MD054" => "MD054",
3121 "MD055" => "MD055",
3122 "MD056" => "MD056",
3123 "MD057" => "MD057",
3124 "MD058" => "MD058",
3125 "MD059" => "MD059",
3126 "MD060" => "MD060",
3127 "MD061" => "MD061",
3128 "MD062" => "MD062",
3129 "MD063" => "MD063",
3130 "MD064" => "MD064",
3131 "MD065" => "MD065",
3132 "MD066" => "MD066",
3133 "MD067" => "MD067",
3134 "MD068" => "MD068",
3135 "MD069" => "MD069",
3136
3137 "HEADING-INCREMENT" => "MD001",
3139 "HEADING-STYLE" => "MD003",
3140 "UL-STYLE" => "MD004",
3141 "LIST-INDENT" => "MD005",
3142 "UL-INDENT" => "MD007",
3143 "NO-TRAILING-SPACES" => "MD009",
3144 "NO-HARD-TABS" => "MD010",
3145 "NO-REVERSED-LINKS" => "MD011",
3146 "NO-MULTIPLE-BLANKS" => "MD012",
3147 "LINE-LENGTH" => "MD013",
3148 "COMMANDS-SHOW-OUTPUT" => "MD014",
3149 "NO-MISSING-SPACE-ATX" => "MD018",
3150 "NO-MULTIPLE-SPACE-ATX" => "MD019",
3151 "NO-MISSING-SPACE-CLOSED-ATX" => "MD020",
3152 "NO-MULTIPLE-SPACE-CLOSED-ATX" => "MD021",
3153 "BLANKS-AROUND-HEADINGS" => "MD022",
3154 "HEADING-START-LEFT" => "MD023",
3155 "NO-DUPLICATE-HEADING" => "MD024",
3156 "SINGLE-TITLE" => "MD025",
3157 "SINGLE-H1" => "MD025",
3158 "NO-TRAILING-PUNCTUATION" => "MD026",
3159 "NO-MULTIPLE-SPACE-BLOCKQUOTE" => "MD027",
3160 "NO-BLANKS-BLOCKQUOTE" => "MD028",
3161 "OL-PREFIX" => "MD029",
3162 "LIST-MARKER-SPACE" => "MD030",
3163 "BLANKS-AROUND-FENCES" => "MD031",
3164 "BLANKS-AROUND-LISTS" => "MD032",
3165 "NO-INLINE-HTML" => "MD033",
3166 "NO-BARE-URLS" => "MD034",
3167 "HR-STYLE" => "MD035",
3168 "NO-EMPHASIS-AS-HEADING" => "MD036",
3169 "NO-SPACE-IN-EMPHASIS" => "MD037",
3170 "NO-SPACE-IN-CODE" => "MD038",
3171 "NO-SPACE-IN-LINKS" => "MD039",
3172 "FENCED-CODE-LANGUAGE" => "MD040",
3173 "FIRST-LINE-HEADING" => "MD041",
3174 "FIRST-LINE-H1" => "MD041",
3175 "NO-EMPTY-LINKS" => "MD042",
3176 "REQUIRED-HEADINGS" => "MD043",
3177 "PROPER-NAMES" => "MD044",
3178 "NO-ALT-TEXT" => "MD045",
3179 "CODE-BLOCK-STYLE" => "MD046",
3180 "SINGLE-TRAILING-NEWLINE" => "MD047",
3181 "CODE-FENCE-STYLE" => "MD048",
3182 "EMPHASIS-STYLE" => "MD049",
3183 "STRONG-STYLE" => "MD050",
3184 "LINK-FRAGMENTS" => "MD051",
3185 "REFERENCE-LINKS-IMAGES" => "MD052",
3186 "LINK-IMAGE-REFERENCE-DEFINITIONS" => "MD053",
3187 "LINK-IMAGE-STYLE" => "MD054",
3188 "TABLE-PIPE-STYLE" => "MD055",
3189 "TABLE-COLUMN-COUNT" => "MD056",
3190 "EXISTING-RELATIVE-LINKS" => "MD057",
3191 "BLANKS-AROUND-TABLES" => "MD058",
3192 "TABLE-CELL-ALIGNMENT" => "MD059",
3193 "TABLE-FORMAT" => "MD060",
3194 "FORBIDDEN-TERMS" => "MD061",
3195 "LINK-DESTINATION-WHITESPACE" => "MD062",
3196 "HEADING-CAPITALIZATION" => "MD063",
3197 "NO-MULTIPLE-CONSECUTIVE-SPACES" => "MD064",
3198 "BLANKS-AROUND-HORIZONTAL-RULES" => "MD065",
3199 "FOOTNOTE-VALIDATION" => "MD066",
3200 "FOOTNOTE-DEFINITION-ORDER" => "MD067",
3201 "EMPTY-FOOTNOTE-DEFINITION" => "MD068",
3202 "NO-DUPLICATE-LIST-MARKERS" => "MD069",
3203};
3204
3205pub fn resolve_rule_name_alias(key: &str) -> Option<&'static str> {
3209 let normalized_key = key.to_ascii_uppercase().replace('_', "-");
3211
3212 RULE_ALIAS_MAP.get(normalized_key.as_str()).copied()
3214}
3215
3216pub fn resolve_rule_name(name: &str) -> String {
3224 resolve_rule_name_alias(name)
3225 .map(|s| s.to_string())
3226 .unwrap_or_else(|| normalize_key(name))
3227}
3228
3229pub fn resolve_rule_names(input: &str) -> std::collections::HashSet<String> {
3233 input
3234 .split(',')
3235 .map(|s| s.trim())
3236 .filter(|s| !s.is_empty())
3237 .map(resolve_rule_name)
3238 .collect()
3239}
3240
3241pub fn validate_cli_rule_names(
3247 enable: Option<&str>,
3248 disable: Option<&str>,
3249 extend_enable: Option<&str>,
3250 extend_disable: Option<&str>,
3251) -> Vec<ConfigValidationWarning> {
3252 let mut warnings = Vec::new();
3253 let all_rule_names: Vec<String> = RULE_ALIAS_MAP.keys().map(|s| s.to_string()).collect();
3254
3255 let validate_list = |input: &str, flag_name: &str, warnings: &mut Vec<ConfigValidationWarning>| {
3256 for name in input.split(',').map(|s| s.trim()).filter(|s| !s.is_empty()) {
3257 if name.eq_ignore_ascii_case("all") {
3259 continue;
3260 }
3261 if resolve_rule_name_alias(name).is_none() {
3262 let message = if let Some(suggestion) = suggest_similar_key(name, &all_rule_names) {
3263 let formatted = if suggestion.starts_with("MD") {
3264 suggestion
3265 } else {
3266 suggestion.to_lowercase()
3267 };
3268 format!("Unknown rule in {flag_name}: {name} (did you mean: {formatted}?)")
3269 } else {
3270 format!("Unknown rule in {flag_name}: {name}")
3271 };
3272 warnings.push(ConfigValidationWarning {
3273 message,
3274 rule: Some(name.to_string()),
3275 key: None,
3276 });
3277 }
3278 }
3279 };
3280
3281 if let Some(e) = enable {
3282 validate_list(e, "--enable", &mut warnings);
3283 }
3284 if let Some(d) = disable {
3285 validate_list(d, "--disable", &mut warnings);
3286 }
3287 if let Some(ee) = extend_enable {
3288 validate_list(ee, "--extend-enable", &mut warnings);
3289 }
3290 if let Some(ed) = extend_disable {
3291 validate_list(ed, "--extend-disable", &mut warnings);
3292 }
3293
3294 warnings
3295}
3296
3297pub fn is_valid_rule_name(name: &str) -> bool {
3301 if name.eq_ignore_ascii_case("all") {
3303 return true;
3304 }
3305 resolve_rule_name_alias(name).is_some()
3306}
3307
3308#[derive(Debug, Clone)]
3310pub struct ConfigValidationWarning {
3311 pub message: String,
3312 pub rule: Option<String>,
3313 pub key: Option<String>,
3314}
3315
3316fn validate_config_sourced_internal<S>(
3319 sourced: &SourcedConfig<S>,
3320 registry: &RuleRegistry,
3321) -> Vec<ConfigValidationWarning> {
3322 let mut warnings = validate_config_sourced_impl(&sourced.rules, &sourced.unknown_keys, registry);
3323
3324 let all_rule_names: Vec<String> = RULE_ALIAS_MAP.keys().map(|s| s.to_string()).collect();
3326
3327 for rule_name in &sourced.global.enable.value {
3328 if !is_valid_rule_name(rule_name) {
3329 let message = if let Some(suggestion) = suggest_similar_key(rule_name, &all_rule_names) {
3330 let formatted = if suggestion.starts_with("MD") {
3331 suggestion
3332 } else {
3333 suggestion.to_lowercase()
3334 };
3335 format!("Unknown rule in global.enable: {rule_name} (did you mean: {formatted}?)")
3336 } else {
3337 format!("Unknown rule in global.enable: {rule_name}")
3338 };
3339 warnings.push(ConfigValidationWarning {
3340 message,
3341 rule: Some(rule_name.clone()),
3342 key: None,
3343 });
3344 }
3345 }
3346
3347 for rule_name in &sourced.global.disable.value {
3348 if !is_valid_rule_name(rule_name) {
3349 let message = if let Some(suggestion) = suggest_similar_key(rule_name, &all_rule_names) {
3350 let formatted = if suggestion.starts_with("MD") {
3351 suggestion
3352 } else {
3353 suggestion.to_lowercase()
3354 };
3355 format!("Unknown rule in global.disable: {rule_name} (did you mean: {formatted}?)")
3356 } else {
3357 format!("Unknown rule in global.disable: {rule_name}")
3358 };
3359 warnings.push(ConfigValidationWarning {
3360 message,
3361 rule: Some(rule_name.clone()),
3362 key: None,
3363 });
3364 }
3365 }
3366
3367 warnings
3368}
3369
3370fn validate_config_sourced_impl(
3372 rules: &BTreeMap<String, SourcedRuleConfig>,
3373 unknown_keys: &[(String, String, Option<String>)],
3374 registry: &RuleRegistry,
3375) -> Vec<ConfigValidationWarning> {
3376 let mut warnings = Vec::new();
3377 let known_rules = registry.rule_names();
3378 for rule in rules.keys() {
3380 if !known_rules.contains(rule) {
3381 let all_rule_names: Vec<String> = RULE_ALIAS_MAP.keys().map(|s| s.to_string()).collect();
3383 let message = if let Some(suggestion) = suggest_similar_key(rule, &all_rule_names) {
3384 let formatted_suggestion = if suggestion.starts_with("MD") {
3386 suggestion
3387 } else {
3388 suggestion.to_lowercase()
3389 };
3390 format!("Unknown rule in config: {rule} (did you mean: {formatted_suggestion}?)")
3391 } else {
3392 format!("Unknown rule in config: {rule}")
3393 };
3394 warnings.push(ConfigValidationWarning {
3395 message,
3396 rule: Some(rule.clone()),
3397 key: None,
3398 });
3399 }
3400 }
3401 for (rule, rule_cfg) in rules {
3403 if let Some(valid_keys) = registry.config_keys_for(rule) {
3404 for key in rule_cfg.values.keys() {
3405 if !valid_keys.contains(key) {
3406 let valid_keys_vec: Vec<String> = valid_keys.iter().cloned().collect();
3407 let message = if let Some(suggestion) = suggest_similar_key(key, &valid_keys_vec) {
3408 format!("Unknown option for rule {rule}: {key} (did you mean: {suggestion}?)")
3409 } else {
3410 format!("Unknown option for rule {rule}: {key}")
3411 };
3412 warnings.push(ConfigValidationWarning {
3413 message,
3414 rule: Some(rule.clone()),
3415 key: Some(key.clone()),
3416 });
3417 } else {
3418 if let Some(expected) = registry.expected_value_for(rule, key) {
3420 let actual = &rule_cfg.values[key].value;
3421 if !toml_value_type_matches(expected, actual) {
3422 warnings.push(ConfigValidationWarning {
3423 message: format!(
3424 "Type mismatch for {}.{}: expected {}, got {}",
3425 rule,
3426 key,
3427 toml_type_name(expected),
3428 toml_type_name(actual)
3429 ),
3430 rule: Some(rule.clone()),
3431 key: Some(key.clone()),
3432 });
3433 }
3434 }
3435 }
3436 }
3437 }
3438 }
3439 let known_global_keys = vec![
3441 "enable".to_string(),
3442 "disable".to_string(),
3443 "include".to_string(),
3444 "exclude".to_string(),
3445 "respect-gitignore".to_string(),
3446 "line-length".to_string(),
3447 "fixable".to_string(),
3448 "unfixable".to_string(),
3449 "flavor".to_string(),
3450 "force-exclude".to_string(),
3451 "output-format".to_string(),
3452 "cache-dir".to_string(),
3453 "cache".to_string(),
3454 ];
3455
3456 for (section, key, file_path) in unknown_keys {
3457 if section.contains("[global]") || section.contains("[tool.rumdl]") {
3458 let message = if let Some(suggestion) = suggest_similar_key(key, &known_global_keys) {
3459 if let Some(path) = file_path {
3460 format!("Unknown global option in {path}: {key} (did you mean: {suggestion}?)")
3461 } else {
3462 format!("Unknown global option: {key} (did you mean: {suggestion}?)")
3463 }
3464 } else if let Some(path) = file_path {
3465 format!("Unknown global option in {path}: {key}")
3466 } else {
3467 format!("Unknown global option: {key}")
3468 };
3469 warnings.push(ConfigValidationWarning {
3470 message,
3471 rule: None,
3472 key: Some(key.clone()),
3473 });
3474 } else if !key.is_empty() {
3475 continue;
3477 } else {
3478 let rule_name = section.trim_matches(|c| c == '[' || c == ']');
3480 let all_rule_names: Vec<String> = RULE_ALIAS_MAP.keys().map(|s| s.to_string()).collect();
3481 let message = if let Some(suggestion) = suggest_similar_key(rule_name, &all_rule_names) {
3482 let formatted_suggestion = if suggestion.starts_with("MD") {
3484 suggestion
3485 } else {
3486 suggestion.to_lowercase()
3487 };
3488 if let Some(path) = file_path {
3489 format!("Unknown rule in {path}: {rule_name} (did you mean: {formatted_suggestion}?)")
3490 } else {
3491 format!("Unknown rule in config: {rule_name} (did you mean: {formatted_suggestion}?)")
3492 }
3493 } else if let Some(path) = file_path {
3494 format!("Unknown rule in {path}: {rule_name}")
3495 } else {
3496 format!("Unknown rule in config: {rule_name}")
3497 };
3498 warnings.push(ConfigValidationWarning {
3499 message,
3500 rule: None,
3501 key: None,
3502 });
3503 }
3504 }
3505 warnings
3506}
3507
3508pub fn validate_config_sourced(
3514 sourced: &SourcedConfig<ConfigLoaded>,
3515 registry: &RuleRegistry,
3516) -> Vec<ConfigValidationWarning> {
3517 validate_config_sourced_internal(sourced, registry)
3518}
3519
3520pub fn validate_config_sourced_validated(
3524 sourced: &SourcedConfig<ConfigValidated>,
3525 _registry: &RuleRegistry,
3526) -> Vec<ConfigValidationWarning> {
3527 sourced.validation_warnings.clone()
3528}
3529
3530fn toml_type_name(val: &toml::Value) -> &'static str {
3531 match val {
3532 toml::Value::String(_) => "string",
3533 toml::Value::Integer(_) => "integer",
3534 toml::Value::Float(_) => "float",
3535 toml::Value::Boolean(_) => "boolean",
3536 toml::Value::Array(_) => "array",
3537 toml::Value::Table(_) => "table",
3538 toml::Value::Datetime(_) => "datetime",
3539 }
3540}
3541
3542fn levenshtein_distance(s1: &str, s2: &str) -> usize {
3544 let len1 = s1.len();
3545 let len2 = s2.len();
3546
3547 if len1 == 0 {
3548 return len2;
3549 }
3550 if len2 == 0 {
3551 return len1;
3552 }
3553
3554 let s1_chars: Vec<char> = s1.chars().collect();
3555 let s2_chars: Vec<char> = s2.chars().collect();
3556
3557 let mut prev_row: Vec<usize> = (0..=len2).collect();
3558 let mut curr_row = vec![0; len2 + 1];
3559
3560 for i in 1..=len1 {
3561 curr_row[0] = i;
3562 for j in 1..=len2 {
3563 let cost = if s1_chars[i - 1] == s2_chars[j - 1] { 0 } else { 1 };
3564 curr_row[j] = (prev_row[j] + 1) .min(curr_row[j - 1] + 1) .min(prev_row[j - 1] + cost); }
3568 std::mem::swap(&mut prev_row, &mut curr_row);
3569 }
3570
3571 prev_row[len2]
3572}
3573
3574pub fn suggest_similar_key(unknown: &str, valid_keys: &[String]) -> Option<String> {
3576 let unknown_lower = unknown.to_lowercase();
3577 let max_distance = 2.max(unknown.len() / 3); let mut best_match: Option<(String, usize)> = None;
3580
3581 for valid in valid_keys {
3582 let valid_lower = valid.to_lowercase();
3583 let distance = levenshtein_distance(&unknown_lower, &valid_lower);
3584
3585 if distance <= max_distance {
3586 if let Some((_, best_dist)) = &best_match {
3587 if distance < *best_dist {
3588 best_match = Some((valid.clone(), distance));
3589 }
3590 } else {
3591 best_match = Some((valid.clone(), distance));
3592 }
3593 }
3594 }
3595
3596 best_match.map(|(key, _)| key)
3597}
3598
3599fn toml_value_type_matches(expected: &toml::Value, actual: &toml::Value) -> bool {
3600 use toml::Value::*;
3601 match (expected, actual) {
3602 (String(_), String(_)) => true,
3603 (Integer(_), Integer(_)) => true,
3604 (Float(_), Float(_)) => true,
3605 (Boolean(_), Boolean(_)) => true,
3606 (Array(_), Array(_)) => true,
3607 (Table(_), Table(_)) => true,
3608 (Datetime(_), Datetime(_)) => true,
3609 (Float(_), Integer(_)) => true,
3611 _ => false,
3612 }
3613}
3614
3615fn parse_pyproject_toml(content: &str, path: &str) -> Result<Option<SourcedConfigFragment>, ConfigError> {
3617 let doc: toml::Value =
3618 toml::from_str(content).map_err(|e| ConfigError::ParseError(format!("{path}: Failed to parse TOML: {e}")))?;
3619 let mut fragment = SourcedConfigFragment::default();
3620 let source = ConfigSource::PyprojectToml;
3621 let file = Some(path.to_string());
3622
3623 let all_rules = rules::all_rules(&Config::default());
3625 let registry = RuleRegistry::from_rules(&all_rules);
3626
3627 if let Some(rumdl_config) = doc.get("tool").and_then(|t| t.get("rumdl"))
3629 && let Some(rumdl_table) = rumdl_config.as_table()
3630 {
3631 let extract_global_config = |fragment: &mut SourcedConfigFragment, table: &toml::value::Table| {
3633 if let Some(enable) = table.get("enable")
3635 && let Ok(values) = Vec::<String>::deserialize(enable.clone())
3636 {
3637 let normalized_values = values
3639 .into_iter()
3640 .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3641 .collect();
3642 fragment
3643 .global
3644 .enable
3645 .push_override(normalized_values, source, file.clone(), None);
3646 }
3647
3648 if let Some(disable) = table.get("disable")
3649 && let Ok(values) = Vec::<String>::deserialize(disable.clone())
3650 {
3651 let normalized_values: Vec<String> = values
3653 .into_iter()
3654 .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3655 .collect();
3656 fragment
3657 .global
3658 .disable
3659 .push_override(normalized_values, source, file.clone(), None);
3660 }
3661
3662 if let Some(include) = table.get("include")
3663 && let Ok(values) = Vec::<String>::deserialize(include.clone())
3664 {
3665 fragment
3666 .global
3667 .include
3668 .push_override(values, source, file.clone(), None);
3669 }
3670
3671 if let Some(exclude) = table.get("exclude")
3672 && let Ok(values) = Vec::<String>::deserialize(exclude.clone())
3673 {
3674 fragment
3675 .global
3676 .exclude
3677 .push_override(values, source, file.clone(), None);
3678 }
3679
3680 if let Some(respect_gitignore) = table
3681 .get("respect-gitignore")
3682 .or_else(|| table.get("respect_gitignore"))
3683 && let Ok(value) = bool::deserialize(respect_gitignore.clone())
3684 {
3685 fragment
3686 .global
3687 .respect_gitignore
3688 .push_override(value, source, file.clone(), None);
3689 }
3690
3691 if let Some(force_exclude) = table.get("force-exclude").or_else(|| table.get("force_exclude"))
3692 && let Ok(value) = bool::deserialize(force_exclude.clone())
3693 {
3694 fragment
3695 .global
3696 .force_exclude
3697 .push_override(value, source, file.clone(), None);
3698 }
3699
3700 if let Some(output_format) = table.get("output-format").or_else(|| table.get("output_format"))
3701 && let Ok(value) = String::deserialize(output_format.clone())
3702 {
3703 if fragment.global.output_format.is_none() {
3704 fragment.global.output_format = Some(SourcedValue::new(value.clone(), source));
3705 } else {
3706 fragment
3707 .global
3708 .output_format
3709 .as_mut()
3710 .unwrap()
3711 .push_override(value, source, file.clone(), None);
3712 }
3713 }
3714
3715 if let Some(fixable) = table.get("fixable")
3716 && let Ok(values) = Vec::<String>::deserialize(fixable.clone())
3717 {
3718 let normalized_values = values
3719 .into_iter()
3720 .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3721 .collect();
3722 fragment
3723 .global
3724 .fixable
3725 .push_override(normalized_values, source, file.clone(), None);
3726 }
3727
3728 if let Some(unfixable) = table.get("unfixable")
3729 && let Ok(values) = Vec::<String>::deserialize(unfixable.clone())
3730 {
3731 let normalized_values = values
3732 .into_iter()
3733 .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3734 .collect();
3735 fragment
3736 .global
3737 .unfixable
3738 .push_override(normalized_values, source, file.clone(), None);
3739 }
3740
3741 if let Some(flavor) = table.get("flavor")
3742 && let Ok(value) = MarkdownFlavor::deserialize(flavor.clone())
3743 {
3744 fragment.global.flavor.push_override(value, source, file.clone(), None);
3745 }
3746
3747 if let Some(line_length) = table.get("line-length").or_else(|| table.get("line_length"))
3749 && let Ok(value) = u64::deserialize(line_length.clone())
3750 {
3751 fragment
3752 .global
3753 .line_length
3754 .push_override(LineLength::new(value as usize), source, file.clone(), None);
3755
3756 let norm_md013_key = normalize_key("MD013");
3758 let rule_entry = fragment.rules.entry(norm_md013_key).or_default();
3759 let norm_line_length_key = normalize_key("line-length");
3760 let sv = rule_entry
3761 .values
3762 .entry(norm_line_length_key)
3763 .or_insert_with(|| SourcedValue::new(line_length.clone(), ConfigSource::Default));
3764 sv.push_override(line_length.clone(), source, file.clone(), None);
3765 }
3766
3767 if let Some(cache_dir) = table.get("cache-dir").or_else(|| table.get("cache_dir"))
3768 && let Ok(value) = String::deserialize(cache_dir.clone())
3769 {
3770 if fragment.global.cache_dir.is_none() {
3771 fragment.global.cache_dir = Some(SourcedValue::new(value.clone(), source));
3772 } else {
3773 fragment
3774 .global
3775 .cache_dir
3776 .as_mut()
3777 .unwrap()
3778 .push_override(value, source, file.clone(), None);
3779 }
3780 }
3781
3782 if let Some(cache) = table.get("cache")
3783 && let Ok(value) = bool::deserialize(cache.clone())
3784 {
3785 fragment.global.cache.push_override(value, source, file.clone(), None);
3786 }
3787 };
3788
3789 if let Some(global_table) = rumdl_table.get("global").and_then(|g| g.as_table()) {
3791 extract_global_config(&mut fragment, global_table);
3792 }
3793
3794 extract_global_config(&mut fragment, rumdl_table);
3796
3797 let per_file_ignores_key = rumdl_table
3800 .get("per-file-ignores")
3801 .or_else(|| rumdl_table.get("per_file_ignores"));
3802
3803 if let Some(per_file_ignores_value) = per_file_ignores_key
3804 && let Some(per_file_table) = per_file_ignores_value.as_table()
3805 {
3806 let mut per_file_map = HashMap::new();
3807 for (pattern, rules_value) in per_file_table {
3808 if let Ok(rules) = Vec::<String>::deserialize(rules_value.clone()) {
3809 let normalized_rules = rules
3810 .into_iter()
3811 .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
3812 .collect();
3813 per_file_map.insert(pattern.clone(), normalized_rules);
3814 } else {
3815 log::warn!(
3816 "[WARN] Expected array for per-file-ignores pattern '{pattern}' in {path}, found {rules_value:?}"
3817 );
3818 }
3819 }
3820 fragment
3821 .per_file_ignores
3822 .push_override(per_file_map, source, file.clone(), None);
3823 }
3824
3825 for (key, value) in rumdl_table {
3827 let norm_rule_key = normalize_key(key);
3828
3829 let is_global_key = [
3832 "enable",
3833 "disable",
3834 "include",
3835 "exclude",
3836 "respect_gitignore",
3837 "respect-gitignore",
3838 "force_exclude",
3839 "force-exclude",
3840 "output_format",
3841 "output-format",
3842 "fixable",
3843 "unfixable",
3844 "per-file-ignores",
3845 "per_file_ignores",
3846 "global",
3847 "flavor",
3848 "cache_dir",
3849 "cache-dir",
3850 "cache",
3851 ]
3852 .contains(&norm_rule_key.as_str());
3853
3854 let is_line_length_global =
3856 (norm_rule_key == "line-length" || norm_rule_key == "line_length") && !value.is_table();
3857
3858 if is_global_key || is_line_length_global {
3859 continue;
3860 }
3861
3862 if let Some(resolved_rule_name) = registry.resolve_rule_name(key)
3864 && value.is_table()
3865 && let Some(rule_config_table) = value.as_table()
3866 {
3867 let rule_entry = fragment.rules.entry(resolved_rule_name.clone()).or_default();
3868 for (rk, rv) in rule_config_table {
3869 let norm_rk = normalize_key(rk);
3870
3871 if norm_rk == "severity" {
3873 if let Ok(severity) = crate::rule::Severity::deserialize(rv.clone()) {
3874 if rule_entry.severity.is_none() {
3875 rule_entry.severity = Some(SourcedValue::new(severity, source));
3876 } else {
3877 rule_entry.severity.as_mut().unwrap().push_override(
3878 severity,
3879 source,
3880 file.clone(),
3881 None,
3882 );
3883 }
3884 }
3885 continue; }
3887
3888 let toml_val = rv.clone();
3889
3890 let sv = rule_entry
3891 .values
3892 .entry(norm_rk.clone())
3893 .or_insert_with(|| SourcedValue::new(toml_val.clone(), ConfigSource::Default));
3894 sv.push_override(toml_val, source, file.clone(), None);
3895 }
3896 } else if registry.resolve_rule_name(key).is_none() {
3897 fragment
3900 .unknown_keys
3901 .push(("[tool.rumdl]".to_string(), key.to_string(), Some(path.to_string())));
3902 }
3903 }
3904 }
3905
3906 if let Some(tool_table) = doc.get("tool").and_then(|t| t.as_table()) {
3908 for (key, value) in tool_table.iter() {
3909 if let Some(rule_name) = key.strip_prefix("rumdl.") {
3910 if let Some(resolved_rule_name) = registry.resolve_rule_name(rule_name) {
3912 if let Some(rule_table) = value.as_table() {
3913 let rule_entry = fragment.rules.entry(resolved_rule_name.clone()).or_default();
3914 for (rk, rv) in rule_table {
3915 let norm_rk = normalize_key(rk);
3916
3917 if norm_rk == "severity" {
3919 if let Ok(severity) = crate::rule::Severity::deserialize(rv.clone()) {
3920 if rule_entry.severity.is_none() {
3921 rule_entry.severity = Some(SourcedValue::new(severity, source));
3922 } else {
3923 rule_entry.severity.as_mut().unwrap().push_override(
3924 severity,
3925 source,
3926 file.clone(),
3927 None,
3928 );
3929 }
3930 }
3931 continue; }
3933
3934 let toml_val = rv.clone();
3935 let sv = rule_entry
3936 .values
3937 .entry(norm_rk.clone())
3938 .or_insert_with(|| SourcedValue::new(toml_val.clone(), source));
3939 sv.push_override(toml_val, source, file.clone(), None);
3940 }
3941 }
3942 } else if rule_name.to_ascii_uppercase().starts_with("MD")
3943 || rule_name.chars().any(|c| c.is_alphabetic())
3944 {
3945 fragment.unknown_keys.push((
3947 format!("[tool.rumdl.{rule_name}]"),
3948 String::new(),
3949 Some(path.to_string()),
3950 ));
3951 }
3952 }
3953 }
3954 }
3955
3956 if let Some(doc_table) = doc.as_table() {
3958 for (key, value) in doc_table.iter() {
3959 if let Some(rule_name) = key.strip_prefix("tool.rumdl.") {
3960 if let Some(resolved_rule_name) = registry.resolve_rule_name(rule_name) {
3962 if let Some(rule_table) = value.as_table() {
3963 let rule_entry = fragment.rules.entry(resolved_rule_name.clone()).or_default();
3964 for (rk, rv) in rule_table {
3965 let norm_rk = normalize_key(rk);
3966
3967 if norm_rk == "severity" {
3969 if let Ok(severity) = crate::rule::Severity::deserialize(rv.clone()) {
3970 if rule_entry.severity.is_none() {
3971 rule_entry.severity = Some(SourcedValue::new(severity, source));
3972 } else {
3973 rule_entry.severity.as_mut().unwrap().push_override(
3974 severity,
3975 source,
3976 file.clone(),
3977 None,
3978 );
3979 }
3980 }
3981 continue; }
3983
3984 let toml_val = rv.clone();
3985 let sv = rule_entry
3986 .values
3987 .entry(norm_rk.clone())
3988 .or_insert_with(|| SourcedValue::new(toml_val.clone(), source));
3989 sv.push_override(toml_val, source, file.clone(), None);
3990 }
3991 }
3992 } else if rule_name.to_ascii_uppercase().starts_with("MD")
3993 || rule_name.chars().any(|c| c.is_alphabetic())
3994 {
3995 fragment.unknown_keys.push((
3997 format!("[tool.rumdl.{rule_name}]"),
3998 String::new(),
3999 Some(path.to_string()),
4000 ));
4001 }
4002 }
4003 }
4004 }
4005
4006 let has_any = !fragment.global.enable.value.is_empty()
4008 || !fragment.global.disable.value.is_empty()
4009 || !fragment.global.include.value.is_empty()
4010 || !fragment.global.exclude.value.is_empty()
4011 || !fragment.global.fixable.value.is_empty()
4012 || !fragment.global.unfixable.value.is_empty()
4013 || fragment.global.output_format.is_some()
4014 || fragment.global.cache_dir.is_some()
4015 || !fragment.global.cache.value
4016 || !fragment.per_file_ignores.value.is_empty()
4017 || !fragment.rules.is_empty();
4018 if has_any { Ok(Some(fragment)) } else { Ok(None) }
4019}
4020
4021fn parse_rumdl_toml(content: &str, path: &str, source: ConfigSource) -> Result<SourcedConfigFragment, ConfigError> {
4023 let doc = content
4024 .parse::<DocumentMut>()
4025 .map_err(|e| ConfigError::ParseError(format!("{path}: Failed to parse TOML: {e}")))?;
4026 let mut fragment = SourcedConfigFragment::default();
4027 let file = Some(path.to_string());
4029
4030 let all_rules = rules::all_rules(&Config::default());
4032 let registry = RuleRegistry::from_rules(&all_rules);
4033
4034 if let Some(global_item) = doc.get("global")
4036 && let Some(global_table) = global_item.as_table()
4037 {
4038 for (key, value_item) in global_table.iter() {
4039 let norm_key = normalize_key(key);
4040 match norm_key.as_str() {
4041 "enable" | "disable" | "include" | "exclude" => {
4042 if let Some(toml_edit::Value::Array(formatted_array)) = value_item.as_value() {
4043 let values: Vec<String> = formatted_array
4045 .iter()
4046 .filter_map(|item| item.as_str()) .map(|s| s.to_string())
4048 .collect();
4049
4050 let final_values = if norm_key == "enable" || norm_key == "disable" {
4052 values
4053 .into_iter()
4054 .map(|s| registry.resolve_rule_name(&s).unwrap_or_else(|| normalize_key(&s)))
4055 .collect()
4056 } else {
4057 values
4058 };
4059
4060 match norm_key.as_str() {
4061 "enable" => fragment
4062 .global
4063 .enable
4064 .push_override(final_values, source, file.clone(), None),
4065 "disable" => {
4066 fragment
4067 .global
4068 .disable
4069 .push_override(final_values, source, file.clone(), None)
4070 }
4071 "include" => {
4072 fragment
4073 .global
4074 .include
4075 .push_override(final_values, source, file.clone(), None)
4076 }
4077 "exclude" => {
4078 fragment
4079 .global
4080 .exclude
4081 .push_override(final_values, source, file.clone(), None)
4082 }
4083 _ => unreachable!("Outer match guarantees only enable/disable/include/exclude"),
4084 }
4085 } else {
4086 log::warn!(
4087 "[WARN] Expected array for global key '{}' in {}, found {}",
4088 key,
4089 path,
4090 value_item.type_name()
4091 );
4092 }
4093 }
4094 "respect_gitignore" | "respect-gitignore" => {
4095 if let Some(toml_edit::Value::Boolean(formatted_bool)) = value_item.as_value() {
4097 let val = *formatted_bool.value();
4098 fragment
4099 .global
4100 .respect_gitignore
4101 .push_override(val, source, file.clone(), None);
4102 } else {
4103 log::warn!(
4104 "[WARN] Expected boolean for global key '{}' in {}, found {}",
4105 key,
4106 path,
4107 value_item.type_name()
4108 );
4109 }
4110 }
4111 "force_exclude" | "force-exclude" => {
4112 if let Some(toml_edit::Value::Boolean(formatted_bool)) = value_item.as_value() {
4114 let val = *formatted_bool.value();
4115 fragment
4116 .global
4117 .force_exclude
4118 .push_override(val, source, file.clone(), None);
4119 } else {
4120 log::warn!(
4121 "[WARN] Expected boolean for global key '{}' in {}, found {}",
4122 key,
4123 path,
4124 value_item.type_name()
4125 );
4126 }
4127 }
4128 "line_length" | "line-length" => {
4129 if let Some(toml_edit::Value::Integer(formatted_int)) = value_item.as_value() {
4131 let val = LineLength::new(*formatted_int.value() as usize);
4132 fragment
4133 .global
4134 .line_length
4135 .push_override(val, source, file.clone(), None);
4136 } else {
4137 log::warn!(
4138 "[WARN] Expected integer for global key '{}' in {}, found {}",
4139 key,
4140 path,
4141 value_item.type_name()
4142 );
4143 }
4144 }
4145 "output_format" | "output-format" => {
4146 if let Some(toml_edit::Value::String(formatted_string)) = value_item.as_value() {
4148 let val = formatted_string.value().clone();
4149 if fragment.global.output_format.is_none() {
4150 fragment.global.output_format = Some(SourcedValue::new(val.clone(), source));
4151 } else {
4152 fragment.global.output_format.as_mut().unwrap().push_override(
4153 val,
4154 source,
4155 file.clone(),
4156 None,
4157 );
4158 }
4159 } else {
4160 log::warn!(
4161 "[WARN] Expected string for global key '{}' in {}, found {}",
4162 key,
4163 path,
4164 value_item.type_name()
4165 );
4166 }
4167 }
4168 "cache_dir" | "cache-dir" => {
4169 if let Some(toml_edit::Value::String(formatted_string)) = value_item.as_value() {
4171 let val = formatted_string.value().clone();
4172 if fragment.global.cache_dir.is_none() {
4173 fragment.global.cache_dir = Some(SourcedValue::new(val.clone(), source));
4174 } else {
4175 fragment
4176 .global
4177 .cache_dir
4178 .as_mut()
4179 .unwrap()
4180 .push_override(val, source, file.clone(), None);
4181 }
4182 } else {
4183 log::warn!(
4184 "[WARN] Expected string for global key '{}' in {}, found {}",
4185 key,
4186 path,
4187 value_item.type_name()
4188 );
4189 }
4190 }
4191 "cache" => {
4192 if let Some(toml_edit::Value::Boolean(b)) = value_item.as_value() {
4193 let val = *b.value();
4194 fragment.global.cache.push_override(val, source, file.clone(), None);
4195 } else {
4196 log::warn!(
4197 "[WARN] Expected boolean for global key '{}' in {}, found {}",
4198 key,
4199 path,
4200 value_item.type_name()
4201 );
4202 }
4203 }
4204 "fixable" => {
4205 if let Some(toml_edit::Value::Array(formatted_array)) = value_item.as_value() {
4206 let values: Vec<String> = formatted_array
4207 .iter()
4208 .filter_map(|item| item.as_str())
4209 .map(normalize_key)
4210 .collect();
4211 fragment
4212 .global
4213 .fixable
4214 .push_override(values, source, file.clone(), None);
4215 } else {
4216 log::warn!(
4217 "[WARN] Expected array for global key '{}' in {}, found {}",
4218 key,
4219 path,
4220 value_item.type_name()
4221 );
4222 }
4223 }
4224 "unfixable" => {
4225 if let Some(toml_edit::Value::Array(formatted_array)) = value_item.as_value() {
4226 let values: Vec<String> = formatted_array
4227 .iter()
4228 .filter_map(|item| item.as_str())
4229 .map(|s| registry.resolve_rule_name(s).unwrap_or_else(|| normalize_key(s)))
4230 .collect();
4231 fragment
4232 .global
4233 .unfixable
4234 .push_override(values, source, file.clone(), None);
4235 } else {
4236 log::warn!(
4237 "[WARN] Expected array for global key '{}' in {}, found {}",
4238 key,
4239 path,
4240 value_item.type_name()
4241 );
4242 }
4243 }
4244 "flavor" => {
4245 if let Some(toml_edit::Value::String(formatted_string)) = value_item.as_value() {
4246 let val = formatted_string.value();
4247 if let Ok(flavor) = MarkdownFlavor::from_str(val) {
4248 fragment.global.flavor.push_override(flavor, source, file.clone(), None);
4249 } else {
4250 log::warn!("[WARN] Unknown markdown flavor '{val}' in {path}");
4251 }
4252 } else {
4253 log::warn!(
4254 "[WARN] Expected string for global key '{}' in {}, found {}",
4255 key,
4256 path,
4257 value_item.type_name()
4258 );
4259 }
4260 }
4261 _ => {
4262 fragment
4264 .unknown_keys
4265 .push(("[global]".to_string(), key.to_string(), Some(path.to_string())));
4266 log::warn!("[WARN] Unknown key in [global] section of {path}: {key}");
4267 }
4268 }
4269 }
4270 }
4271
4272 if let Some(per_file_item) = doc.get("per-file-ignores")
4274 && let Some(per_file_table) = per_file_item.as_table()
4275 {
4276 let mut per_file_map = HashMap::new();
4277 for (pattern, value_item) in per_file_table.iter() {
4278 if let Some(toml_edit::Value::Array(formatted_array)) = value_item.as_value() {
4279 let rules: Vec<String> = formatted_array
4280 .iter()
4281 .filter_map(|item| item.as_str())
4282 .map(|s| registry.resolve_rule_name(s).unwrap_or_else(|| normalize_key(s)))
4283 .collect();
4284 per_file_map.insert(pattern.to_string(), rules);
4285 } else {
4286 let type_name = value_item.type_name();
4287 log::warn!(
4288 "[WARN] Expected array for per-file-ignores pattern '{pattern}' in {path}, found {type_name}"
4289 );
4290 }
4291 }
4292 fragment
4293 .per_file_ignores
4294 .push_override(per_file_map, source, file.clone(), None);
4295 }
4296
4297 for (key, item) in doc.iter() {
4299 if key == "global" || key == "per-file-ignores" {
4301 continue;
4302 }
4303
4304 let norm_rule_name = if let Some(resolved) = registry.resolve_rule_name(key) {
4306 resolved
4307 } else {
4308 fragment
4310 .unknown_keys
4311 .push((format!("[{key}]"), String::new(), Some(path.to_string())));
4312 continue;
4313 };
4314
4315 if let Some(tbl) = item.as_table() {
4316 let rule_entry = fragment.rules.entry(norm_rule_name.clone()).or_default();
4317 for (rk, rv_item) in tbl.iter() {
4318 let norm_rk = normalize_key(rk);
4319
4320 if norm_rk == "severity" {
4322 if let Some(toml_edit::Value::String(formatted_string)) = rv_item.as_value() {
4323 let severity_str = formatted_string.value();
4324 match crate::rule::Severity::deserialize(toml::Value::String(severity_str.to_string())) {
4325 Ok(severity) => {
4326 if rule_entry.severity.is_none() {
4327 rule_entry.severity = Some(SourcedValue::new(severity, source));
4328 } else {
4329 rule_entry.severity.as_mut().unwrap().push_override(
4330 severity,
4331 source,
4332 file.clone(),
4333 None,
4334 );
4335 }
4336 }
4337 Err(_) => {
4338 log::warn!(
4339 "[WARN] Invalid severity '{severity_str}' for rule {norm_rule_name} in {path}. Valid values: error, warning"
4340 );
4341 }
4342 }
4343 }
4344 continue; }
4346
4347 let maybe_toml_val: Option<toml::Value> = match rv_item.as_value() {
4348 Some(toml_edit::Value::String(formatted)) => Some(toml::Value::String(formatted.value().clone())),
4349 Some(toml_edit::Value::Integer(formatted)) => Some(toml::Value::Integer(*formatted.value())),
4350 Some(toml_edit::Value::Float(formatted)) => Some(toml::Value::Float(*formatted.value())),
4351 Some(toml_edit::Value::Boolean(formatted)) => Some(toml::Value::Boolean(*formatted.value())),
4352 Some(toml_edit::Value::Datetime(formatted)) => Some(toml::Value::Datetime(*formatted.value())),
4353 Some(toml_edit::Value::Array(formatted_array)) => {
4354 let mut values = Vec::new();
4356 for item in formatted_array.iter() {
4357 match item {
4358 toml_edit::Value::String(formatted) => {
4359 values.push(toml::Value::String(formatted.value().clone()))
4360 }
4361 toml_edit::Value::Integer(formatted) => {
4362 values.push(toml::Value::Integer(*formatted.value()))
4363 }
4364 toml_edit::Value::Float(formatted) => {
4365 values.push(toml::Value::Float(*formatted.value()))
4366 }
4367 toml_edit::Value::Boolean(formatted) => {
4368 values.push(toml::Value::Boolean(*formatted.value()))
4369 }
4370 toml_edit::Value::Datetime(formatted) => {
4371 values.push(toml::Value::Datetime(*formatted.value()))
4372 }
4373 _ => {
4374 log::warn!(
4375 "[WARN] Skipping unsupported array element type in key '{norm_rule_name}.{norm_rk}' in {path}"
4376 );
4377 }
4378 }
4379 }
4380 Some(toml::Value::Array(values))
4381 }
4382 Some(toml_edit::Value::InlineTable(_)) => {
4383 log::warn!(
4384 "[WARN] Skipping inline table value for key '{norm_rule_name}.{norm_rk}' in {path}. Table conversion not yet fully implemented in parser."
4385 );
4386 None
4387 }
4388 None => {
4389 log::warn!(
4390 "[WARN] Skipping non-value item for key '{norm_rule_name}.{norm_rk}' in {path}. Expected simple value."
4391 );
4392 None
4393 }
4394 };
4395 if let Some(toml_val) = maybe_toml_val {
4396 let sv = rule_entry
4397 .values
4398 .entry(norm_rk.clone())
4399 .or_insert_with(|| SourcedValue::new(toml_val.clone(), ConfigSource::Default));
4400 sv.push_override(toml_val, source, file.clone(), None);
4401 }
4402 }
4403 } else if item.is_value() {
4404 log::warn!("[WARN] Ignoring top-level value key in {path}: '{key}'. Expected a table like [{key}].");
4405 }
4406 }
4407
4408 Ok(fragment)
4409}
4410
4411fn load_from_markdownlint(path: &str) -> Result<SourcedConfigFragment, ConfigError> {
4413 let ml_config = crate::markdownlint_config::load_markdownlint_config(path)
4415 .map_err(|e| ConfigError::ParseError(format!("{path}: {e}")))?;
4416 Ok(ml_config.map_to_sourced_rumdl_config_fragment(Some(path)))
4417}
4418
4419#[cfg(test)]
4420#[path = "config_intelligent_merge_tests.rs"]
4421mod config_intelligent_merge_tests;