Skip to main content

rumdl_lib/config/
types.rs

1use crate::types::LineLength;
2use globset::{Glob, GlobBuilder, GlobMatcher, GlobSet, GlobSetBuilder};
3use indexmap::IndexMap;
4use serde::{Deserialize, Serialize};
5use std::collections::BTreeMap;
6use std::collections::{HashMap, HashSet};
7use std::fs;
8use std::io;
9use std::path::Path;
10use std::sync::{Arc, OnceLock};
11
12use super::flavor::{MarkdownFlavor, normalize_key};
13
14/// Represents a rule-specific configuration
15#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, schemars::JsonSchema)]
16pub struct RuleConfig {
17    /// Severity override for this rule (Error, Warning, or Info)
18    #[serde(default, skip_serializing_if = "Option::is_none")]
19    pub severity: Option<crate::rule::Severity>,
20
21    /// Configuration values for the rule
22    #[serde(flatten)]
23    #[schemars(schema_with = "arbitrary_value_schema")]
24    pub values: BTreeMap<String, toml::Value>,
25}
26
27/// Generate a JSON schema for arbitrary configuration values
28fn arbitrary_value_schema(_gen: &mut schemars::SchemaGenerator) -> schemars::Schema {
29    schemars::json_schema!({
30        "type": "object",
31        "additionalProperties": true
32    })
33}
34
35/// Represents the complete configuration loaded from rumdl.toml
36#[derive(Debug, Clone, Serialize, Deserialize, Default, schemars::JsonSchema)]
37#[schemars(
38    description = "rumdl configuration for linting Markdown files. Rules can be configured individually using [MD###] sections with rule-specific options."
39)]
40pub struct Config {
41    /// Path to a base config file to inherit settings from.
42    /// Supports relative paths, absolute paths, and `~/` for home directory.
43    /// Example: `extends = "../base.rumdl.toml"`
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub extends: Option<String>,
46
47    /// Global configuration options
48    #[serde(default)]
49    pub global: GlobalConfig,
50
51    /// Per-file rule ignores: maps file patterns to lists of rules to ignore
52    /// Example: { "README.md": ["MD033"], "docs/**/*.md": ["MD013"] }
53    #[serde(default, rename = "per-file-ignores")]
54    pub per_file_ignores: HashMap<String, Vec<String>>,
55
56    /// Per-file flavor overrides: maps file patterns to Markdown flavors
57    /// Example: { "docs/**/*.md": MkDocs, "**/*.mdx": MDX }
58    /// Uses IndexMap to preserve config file order for "first match wins" semantics
59    #[serde(default, rename = "per-file-flavor")]
60    #[schemars(with = "HashMap<String, MarkdownFlavor>")]
61    pub per_file_flavor: IndexMap<String, MarkdownFlavor>,
62
63    /// Code block tools configuration for per-language linting and formatting
64    /// using external tools like ruff, prettier, shellcheck, etc.
65    #[serde(default, rename = "code-block-tools")]
66    pub code_block_tools: crate::code_block_tools::CodeBlockToolsConfig,
67
68    /// Rule-specific configurations (e.g., MD013, MD007, MD044)
69    /// Each rule section can contain options specific to that rule.
70    ///
71    /// Common examples:
72    /// - MD013: line_length, code_blocks, tables, headings
73    /// - MD007: indent
74    /// - MD003: style ("atx", "atx-closed", "setext")
75    /// - MD044: names (array of proper names to check)
76    ///
77    /// See <https://github.com/rvben/rumdl> for full rule documentation.
78    #[serde(flatten)]
79    pub rules: BTreeMap<String, RuleConfig>,
80
81    /// Project root directory, used for resolving relative paths in per-file-ignores
82    #[serde(skip)]
83    pub project_root: Option<std::path::PathBuf>,
84
85    #[serde(skip)]
86    #[schemars(skip)]
87    pub(super) per_file_ignores_cache: Arc<OnceLock<PerFileIgnoreCache>>,
88
89    #[serde(skip)]
90    #[schemars(skip)]
91    pub(super) per_file_flavor_cache: Arc<OnceLock<PerFileFlavorCache>>,
92}
93
94impl PartialEq for Config {
95    fn eq(&self, other: &Self) -> bool {
96        self.global == other.global
97            && self.per_file_ignores == other.per_file_ignores
98            && self.per_file_flavor == other.per_file_flavor
99            && self.code_block_tools == other.code_block_tools
100            && self.rules == other.rules
101            && self.project_root == other.project_root
102    }
103}
104
105#[derive(Debug)]
106pub(super) struct PerFileIgnoreCache {
107    globset: GlobSet,
108    rules: Vec<Vec<String>>,
109}
110
111#[derive(Debug)]
112pub(super) struct PerFileFlavorCache {
113    matchers: Vec<(GlobMatcher, MarkdownFlavor)>,
114}
115
116impl Config {
117    /// Check if the Markdown flavor is set to MkDocs
118    pub fn is_mkdocs_flavor(&self) -> bool {
119        self.global.flavor == MarkdownFlavor::MkDocs
120    }
121
122    // Future methods for when GFM and CommonMark are implemented:
123    // pub fn is_gfm_flavor(&self) -> bool
124    // pub fn is_commonmark_flavor(&self) -> bool
125
126    /// Get the configured Markdown flavor
127    pub fn markdown_flavor(&self) -> MarkdownFlavor {
128        self.global.flavor
129    }
130
131    /// Legacy method for backwards compatibility - redirects to is_mkdocs_flavor
132    pub fn is_mkdocs_project(&self) -> bool {
133        self.is_mkdocs_flavor()
134    }
135
136    /// Apply per-rule `enabled` config to the global enable/disable lists.
137    ///
138    /// For `[MD060] enabled = true`: adds the rule to `extend_enable` and
139    /// removes it from `disable` and `extend_disable`, ensuring the rule is active.
140    ///
141    /// For `[MD041] enabled = false`: adds the rule to `disable` and
142    /// removes it from `extend_enable`, ensuring the rule is inactive.
143    ///
144    /// Per-rule `enabled` takes precedence over global lists when there
145    /// is a conflict, since it represents a more specific intent.
146    pub fn apply_per_rule_enabled(&mut self) {
147        let mut to_enable: Vec<String> = Vec::new();
148        let mut to_disable: Vec<String> = Vec::new();
149
150        for (name, cfg) in &self.rules {
151            match cfg.values.get("enabled") {
152                Some(toml::Value::Boolean(true)) => {
153                    to_enable.push(name.clone());
154                }
155                Some(toml::Value::Boolean(false)) => {
156                    to_disable.push(name.clone());
157                }
158                _ => {}
159            }
160        }
161
162        for name in to_enable {
163            if !self.global.extend_enable.contains(&name) {
164                self.global.extend_enable.push(name.clone());
165            }
166            self.global.disable.retain(|n| n != &name);
167            self.global.extend_disable.retain(|n| n != &name);
168        }
169
170        for name in to_disable {
171            if !self.global.disable.contains(&name) {
172                self.global.disable.push(name.clone());
173            }
174            self.global.extend_enable.retain(|n| n != &name);
175        }
176    }
177
178    /// Get the severity override for a specific rule, if configured
179    pub fn get_rule_severity(&self, rule_name: &str) -> Option<crate::rule::Severity> {
180        self.rules.get(rule_name).and_then(|r| r.severity)
181    }
182
183    /// Get the set of rules that should be ignored for a specific file based on per-file-ignores configuration
184    /// Returns a HashSet of rule names (uppercase, e.g., "MD033") that match the given file path
185    pub fn get_ignored_rules_for_file(&self, file_path: &Path) -> HashSet<String> {
186        let mut ignored_rules = HashSet::new();
187
188        if self.per_file_ignores.is_empty() {
189            return ignored_rules;
190        }
191
192        // Normalize the file path to be relative to project_root for pattern matching
193        // This ensures patterns like ".github/file.md" work with absolute paths
194        let path_for_matching: std::borrow::Cow<'_, Path> = if let Some(ref root) = self.project_root {
195            if let Ok(canonical_path) = file_path.canonicalize() {
196                if let Ok(canonical_root) = root.canonicalize() {
197                    if let Ok(relative) = canonical_path.strip_prefix(&canonical_root) {
198                        std::borrow::Cow::Owned(relative.to_path_buf())
199                    } else {
200                        std::borrow::Cow::Borrowed(file_path)
201                    }
202                } else {
203                    std::borrow::Cow::Borrowed(file_path)
204                }
205            } else {
206                std::borrow::Cow::Borrowed(file_path)
207            }
208        } else {
209            std::borrow::Cow::Borrowed(file_path)
210        };
211
212        let cache = self
213            .per_file_ignores_cache
214            .get_or_init(|| PerFileIgnoreCache::new(&self.per_file_ignores));
215
216        // Match the file path against all patterns
217        for match_idx in cache.globset.matches(path_for_matching.as_ref()) {
218            if let Some(rules) = cache.rules.get(match_idx) {
219                for rule in rules.iter() {
220                    // Normalize rule names to uppercase (MD033, md033 -> MD033)
221                    ignored_rules.insert(rule.clone());
222                }
223            }
224        }
225
226        ignored_rules
227    }
228
229    /// Get the MarkdownFlavor for a specific file based on per-file-flavor configuration.
230    /// Returns the first matching pattern's flavor, or falls back to global flavor,
231    /// or auto-detects from extension, or defaults to Standard.
232    pub fn get_flavor_for_file(&self, file_path: &Path) -> MarkdownFlavor {
233        // If no per-file patterns, use fallback logic
234        if self.per_file_flavor.is_empty() {
235            return self.resolve_flavor_fallback(file_path);
236        }
237
238        // Normalize path for matching (same logic as get_ignored_rules_for_file)
239        let path_for_matching: std::borrow::Cow<'_, Path> = if let Some(ref root) = self.project_root {
240            if let Ok(canonical_path) = file_path.canonicalize() {
241                if let Ok(canonical_root) = root.canonicalize() {
242                    if let Ok(relative) = canonical_path.strip_prefix(&canonical_root) {
243                        std::borrow::Cow::Owned(relative.to_path_buf())
244                    } else {
245                        std::borrow::Cow::Borrowed(file_path)
246                    }
247                } else {
248                    std::borrow::Cow::Borrowed(file_path)
249                }
250            } else {
251                std::borrow::Cow::Borrowed(file_path)
252            }
253        } else {
254            std::borrow::Cow::Borrowed(file_path)
255        };
256
257        let cache = self
258            .per_file_flavor_cache
259            .get_or_init(|| PerFileFlavorCache::new(&self.per_file_flavor));
260
261        // Iterate in config order and return first match (IndexMap preserves order)
262        for (matcher, flavor) in &cache.matchers {
263            if matcher.is_match(path_for_matching.as_ref()) {
264                return *flavor;
265            }
266        }
267
268        // No pattern matched, use fallback
269        self.resolve_flavor_fallback(file_path)
270    }
271
272    /// Fallback flavor resolution: global flavor → auto-detect → Standard
273    fn resolve_flavor_fallback(&self, file_path: &Path) -> MarkdownFlavor {
274        // If global flavor is explicitly set to non-Standard, use it
275        if self.global.flavor != MarkdownFlavor::Standard {
276            return self.global.flavor;
277        }
278        // Auto-detect from extension
279        MarkdownFlavor::from_path(file_path)
280    }
281
282    /// Merge inline configuration overrides into a copy of this config
283    ///
284    /// This enables automatic inline config support - the engine can merge
285    /// inline overrides and recreate rules without any per-rule changes.
286    ///
287    /// Returns a new Config with the inline overrides merged in.
288    /// If there are no inline overrides, returns a clone of self.
289    pub fn merge_with_inline_config(&self, inline_config: &crate::inline_config::InlineConfig) -> Self {
290        let overrides = inline_config.get_all_rule_configs();
291        if overrides.is_empty() {
292            return self.clone();
293        }
294
295        let mut merged = self.clone();
296
297        for (rule_name, json_override) in overrides {
298            // Get or create the rule config entry
299            let rule_config = merged.rules.entry(rule_name.clone()).or_default();
300
301            // Merge JSON values into the rule's config
302            if let Some(obj) = json_override.as_object() {
303                for (key, value) in obj {
304                    // Normalize key to kebab-case for consistency
305                    let normalized_key = key.replace('_', "-");
306
307                    // Convert JSON value to TOML value
308                    if let Some(toml_value) = json_to_toml(value) {
309                        rule_config.values.insert(normalized_key, toml_value);
310                    }
311                }
312            }
313        }
314
315        merged
316    }
317}
318
319/// Convert a serde_json::Value to a toml::Value
320pub(super) fn json_to_toml(json: &serde_json::Value) -> Option<toml::Value> {
321    match json {
322        serde_json::Value::Null => None,
323        serde_json::Value::Bool(b) => Some(toml::Value::Boolean(*b)),
324        serde_json::Value::Number(n) => n
325            .as_i64()
326            .map(toml::Value::Integer)
327            .or_else(|| n.as_f64().map(toml::Value::Float)),
328        serde_json::Value::String(s) => Some(toml::Value::String(s.clone())),
329        serde_json::Value::Array(arr) => {
330            let toml_arr: Vec<toml::Value> = arr.iter().filter_map(json_to_toml).collect();
331            Some(toml::Value::Array(toml_arr))
332        }
333        serde_json::Value::Object(obj) => {
334            let mut table = toml::map::Map::new();
335            for (k, v) in obj {
336                if let Some(tv) = json_to_toml(v) {
337                    table.insert(k.clone(), tv);
338                }
339            }
340            Some(toml::Value::Table(table))
341        }
342    }
343}
344
345impl PerFileIgnoreCache {
346    fn new(per_file_ignores: &HashMap<String, Vec<String>>) -> Self {
347        let mut builder = GlobSetBuilder::new();
348        let mut rules = Vec::new();
349
350        for (pattern, rules_list) in per_file_ignores {
351            if let Ok(glob) = Glob::new(pattern) {
352                builder.add(glob);
353                rules.push(rules_list.iter().map(|rule| normalize_key(rule)).collect());
354            } else {
355                log::warn!("Invalid glob pattern in per-file-ignores: {pattern}");
356            }
357        }
358
359        let globset = builder.build().unwrap_or_else(|e| {
360            log::error!("Failed to build globset for per-file-ignores: {e}");
361            GlobSetBuilder::new().build().unwrap()
362        });
363
364        Self { globset, rules }
365    }
366}
367
368impl PerFileFlavorCache {
369    fn new(per_file_flavor: &IndexMap<String, MarkdownFlavor>) -> Self {
370        let mut matchers = Vec::new();
371
372        for (pattern, flavor) in per_file_flavor {
373            if let Ok(glob) = GlobBuilder::new(pattern).literal_separator(true).build() {
374                matchers.push((glob.compile_matcher(), *flavor));
375            } else {
376                log::warn!("Invalid glob pattern in per-file-flavor: {pattern}");
377            }
378        }
379
380        Self { matchers }
381    }
382}
383
384/// Global configuration options
385#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
386#[serde(default, rename_all = "kebab-case")]
387pub struct GlobalConfig {
388    /// Enabled rules
389    #[serde(default)]
390    pub enable: Vec<String>,
391
392    /// Disabled rules
393    #[serde(default)]
394    pub disable: Vec<String>,
395
396    /// Files to exclude
397    #[serde(default)]
398    pub exclude: Vec<String>,
399
400    /// Files to include
401    #[serde(default)]
402    pub include: Vec<String>,
403
404    /// Respect .gitignore files when scanning directories
405    #[serde(default = "default_respect_gitignore", alias = "respect_gitignore")]
406    pub respect_gitignore: bool,
407
408    /// Global line length setting (used by MD013 and other rules if not overridden)
409    #[serde(default, alias = "line_length")]
410    pub line_length: LineLength,
411
412    /// Output format for linting results (e.g., "text", "json", "pylint", etc.)
413    #[serde(skip_serializing_if = "Option::is_none", alias = "output_format")]
414    pub output_format: Option<String>,
415
416    /// Rules that are allowed to be fixed when --fix is used
417    /// If specified, only these rules will be fixed
418    #[serde(default)]
419    pub fixable: Vec<String>,
420
421    /// Rules that should never be fixed, even when --fix is used
422    /// Takes precedence over fixable
423    #[serde(default)]
424    pub unfixable: Vec<String>,
425
426    /// Markdown flavor/dialect to use (mkdocs, gfm, commonmark, etc.)
427    /// When set, adjusts parsing and validation rules for that specific Markdown variant
428    #[serde(default)]
429    pub flavor: MarkdownFlavor,
430
431    /// \[DEPRECATED\] Whether to enforce exclude patterns for explicitly passed paths.
432    /// This option is deprecated as of v0.0.156 and has no effect.
433    /// Exclude patterns are now always respected, even for explicitly provided files.
434    /// This prevents duplication between rumdl config and tool configs like pre-commit.
435    #[serde(default, alias = "force_exclude")]
436    #[deprecated(since = "0.0.156", note = "Exclude patterns are now always respected")]
437    pub force_exclude: bool,
438
439    /// Directory to store cache files (default: .rumdl_cache)
440    /// Can also be set via --cache-dir CLI flag or RUMDL_CACHE_DIR environment variable
441    #[serde(default, alias = "cache_dir", skip_serializing_if = "Option::is_none")]
442    pub cache_dir: Option<String>,
443
444    /// Whether caching is enabled (default: true)
445    /// Can also be disabled via --no-cache CLI flag
446    #[serde(default = "default_true")]
447    pub cache: bool,
448
449    /// Additional rules to enable on top of the base set (additive)
450    #[serde(default, alias = "extend_enable")]
451    pub extend_enable: Vec<String>,
452
453    /// Additional rules to disable on top of the base set (additive)
454    #[serde(default, alias = "extend_disable")]
455    pub extend_disable: Vec<String>,
456
457    /// Whether the enable list was explicitly set (even if empty).
458    /// Used to distinguish "no enable list configured" from "enable list is empty"
459    /// (e.g., markdownlint `default: false` with no rules enabled).
460    #[serde(skip)]
461    pub enable_is_explicit: bool,
462}
463
464fn default_respect_gitignore() -> bool {
465    true
466}
467
468fn default_true() -> bool {
469    true
470}
471
472// Add the Default impl
473impl Default for GlobalConfig {
474    #[allow(deprecated)]
475    fn default() -> Self {
476        Self {
477            enable: Vec::new(),
478            disable: Vec::new(),
479            exclude: Vec::new(),
480            include: Vec::new(),
481            respect_gitignore: true,
482            line_length: LineLength::default(),
483            output_format: None,
484            fixable: Vec::new(),
485            unfixable: Vec::new(),
486            flavor: MarkdownFlavor::default(),
487            force_exclude: false,
488            cache_dir: None,
489            cache: true,
490            extend_enable: Vec::new(),
491            extend_disable: Vec::new(),
492            enable_is_explicit: false,
493        }
494    }
495}
496
497pub const MARKDOWNLINT_CONFIG_FILES: &[&str] = &[
498    ".markdownlint-cli2.jsonc",
499    ".markdownlint-cli2.yaml",
500    ".markdownlint-cli2.yml",
501    ".markdownlint.json",
502    ".markdownlint.jsonc",
503    ".markdownlint.yaml",
504    ".markdownlint.yml",
505    "markdownlint.json",
506    "markdownlint.jsonc",
507    "markdownlint.yaml",
508    "markdownlint.yml",
509];
510
511/// Create a default configuration file at the specified path
512pub fn create_default_config(path: &str) -> Result<(), ConfigError> {
513    create_preset_config("default", path)
514}
515
516/// Create a configuration file with a specific style preset
517pub fn create_preset_config(preset: &str, path: &str) -> Result<(), ConfigError> {
518    if Path::new(path).exists() {
519        return Err(ConfigError::FileExists { path: path.to_string() });
520    }
521
522    let config_content = match preset {
523        "default" => generate_default_preset(),
524        "google" => generate_google_preset(),
525        "relaxed" => generate_relaxed_preset(),
526        _ => {
527            return Err(ConfigError::UnknownPreset {
528                name: preset.to_string(),
529            });
530        }
531    };
532
533    match fs::write(path, config_content) {
534        Ok(_) => Ok(()),
535        Err(err) => Err(ConfigError::IoError {
536            source: err,
537            path: path.to_string(),
538        }),
539    }
540}
541
542/// Generate the default preset configuration content.
543/// Returns the same content as `create_default_config`.
544fn generate_default_preset() -> String {
545    r#"# rumdl configuration file
546
547# Inherit settings from another config file (relative to this file's directory)
548# extends = "../base.rumdl.toml"
549
550# Global configuration options
551[global]
552# List of rules to disable (uncomment and modify as needed)
553# disable = ["MD013", "MD033"]
554
555# List of rules to enable exclusively (replaces defaults; only these rules will run)
556# enable = ["MD001", "MD003", "MD004"]
557
558# Additional rules to enable on top of defaults (additive, does not replace)
559# Use this to activate opt-in rules like MD060, MD063, MD072, MD073, MD074
560# extend-enable = ["MD060", "MD063"]
561
562# Additional rules to disable on top of the disable list (additive)
563# extend-disable = ["MD041"]
564
565# List of file/directory patterns to include for linting (if provided, only these will be linted)
566# include = [
567#    "docs/*.md",
568#    "src/**/*.md",
569#    "README.md"
570# ]
571
572# List of file/directory patterns to exclude from linting
573exclude = [
574    # Common directories to exclude
575    ".git",
576    ".github",
577    "node_modules",
578    "vendor",
579    "dist",
580    "build",
581
582    # Specific files or patterns
583    "CHANGELOG.md",
584    "LICENSE.md",
585]
586
587# Respect .gitignore files when scanning directories (default: true)
588respect-gitignore = true
589
590# Markdown flavor/dialect (uncomment to enable)
591# Options: standard (default), gfm, commonmark, mkdocs, mdx, quarto
592# flavor = "mkdocs"
593
594# Rule-specific configurations (uncomment and modify as needed)
595
596# [MD003]
597# style = "atx"  # Heading style (atx, atx_closed, setext)
598
599# [MD004]
600# style = "asterisk"  # Unordered list style (asterisk, plus, dash, consistent)
601
602# [MD007]
603# indent = 4  # Unordered list indentation
604
605# [MD013]
606# line-length = 100  # Line length
607# code-blocks = false  # Exclude code blocks from line length check
608# tables = false  # Exclude tables from line length check
609# headings = true  # Include headings in line length check
610
611# [MD044]
612# names = ["rumdl", "Markdown", "GitHub"]  # Proper names that should be capitalized correctly
613# code-blocks = false  # Check code blocks for proper names (default: false, skips code blocks)
614"#
615    .to_string()
616}
617
618/// Generate Google developer documentation style preset.
619/// Based on https://google.github.io/styleguide/docguide/style.html
620fn generate_google_preset() -> String {
621    r#"# rumdl configuration - Google developer documentation style
622# Based on https://google.github.io/styleguide/docguide/style.html
623
624[global]
625exclude = [
626    ".git",
627    ".github",
628    "node_modules",
629    "vendor",
630    "dist",
631    "build",
632    "CHANGELOG.md",
633    "LICENSE.md",
634]
635respect-gitignore = true
636
637# ATX-style headings required
638[MD003]
639style = "atx"
640
641# Unordered list style: dash
642[MD004]
643style = "dash"
644
645# 4-space indent for nested lists
646[MD007]
647indent = 4
648
649# Strict mode: no trailing spaces allowed (Google uses backslash for line breaks)
650[MD009]
651strict = true
652
653# 80-character line length
654[MD013]
655line-length = 80
656code-blocks = false
657tables = false
658
659# No trailing punctuation in headings
660[MD026]
661punctuation = ".,;:!。,;:!"
662
663# Fenced code blocks only (no indented code blocks)
664[MD046]
665style = "fenced"
666
667# Emphasis with underscores
668[MD049]
669style = "underscore"
670
671# Strong with asterisks
672[MD050]
673style = "asterisk"
674"#
675    .to_string()
676}
677
678/// Generate relaxed preset for existing projects adopting rumdl incrementally.
679/// Longer line lengths, fewer rules, lenient settings to minimize initial warnings.
680fn generate_relaxed_preset() -> String {
681    r#"# rumdl configuration - Relaxed preset
682# Lenient settings for existing projects adopting rumdl incrementally.
683# Minimizes initial warnings while still catching important issues.
684
685[global]
686exclude = [
687    ".git",
688    ".github",
689    "node_modules",
690    "vendor",
691    "dist",
692    "build",
693    "CHANGELOG.md",
694    "LICENSE.md",
695]
696respect-gitignore = true
697
698# Disable rules that produce the most noise on existing projects
699disable = [
700    "MD013",  # Line length - most existing files exceed 80 chars
701    "MD033",  # Inline HTML - commonly used in real-world markdown
702    "MD041",  # First line heading - not all files need it
703]
704
705# Consistent heading style (any style, just be consistent)
706[MD003]
707style = "consistent"
708
709# Consistent list style
710[MD004]
711style = "consistent"
712
713# Consistent emphasis style
714[MD049]
715style = "consistent"
716
717# Consistent strong style
718[MD050]
719style = "consistent"
720"#
721    .to_string()
722}
723
724/// Errors that can occur when loading configuration
725#[derive(Debug, thiserror::Error)]
726pub enum ConfigError {
727    /// Failed to read the configuration file
728    #[error("Failed to read config file at {path}: {source}")]
729    IoError { source: io::Error, path: String },
730
731    /// Failed to parse the configuration content (TOML or JSON)
732    #[error("Failed to parse config: {0}")]
733    ParseError(String),
734
735    /// Configuration file already exists
736    #[error("Configuration file already exists at {path}")]
737    FileExists { path: String },
738
739    /// Circular extends reference detected
740    #[error("Circular extends reference: {path} already in chain {chain:?}")]
741    CircularExtends { path: String, chain: Vec<String> },
742
743    /// Extends chain exceeds maximum depth
744    #[error("Extends chain exceeds maximum depth of {max_depth} at {path}")]
745    ExtendsDepthExceeded { path: String, max_depth: usize },
746
747    /// Extends target file not found
748    #[error("extends target not found: {path} (referenced from {from})")]
749    ExtendsNotFound { path: String, from: String },
750
751    /// Unknown preset name
752    #[error("Unknown preset: {name}. Valid presets: default, google, relaxed")]
753    UnknownPreset { name: String },
754}
755
756/// Get a rule-specific configuration value
757/// Automatically tries both the original key and normalized variants (kebab-case ↔ snake_case)
758/// for better markdownlint compatibility
759pub fn get_rule_config_value<T: serde::de::DeserializeOwned>(config: &Config, rule_name: &str, key: &str) -> Option<T> {
760    let norm_rule_name = rule_name.to_ascii_uppercase(); // Use uppercase for lookup
761
762    let rule_config = config.rules.get(&norm_rule_name)?;
763
764    // Try multiple key variants to support both underscore and kebab-case formats
765    let key_variants = [
766        key.to_string(),       // Original key as provided
767        normalize_key(key),    // Normalized key (lowercase, kebab-case)
768        key.replace('-', "_"), // Convert kebab-case to snake_case
769        key.replace('_', "-"), // Convert snake_case to kebab-case
770    ];
771
772    // Try each variant until we find a match
773    for variant in &key_variants {
774        if let Some(value) = rule_config.values.get(variant)
775            && let Ok(result) = T::deserialize(value.clone())
776        {
777            return Some(result);
778        }
779    }
780
781    None
782}
783
784/// Generate preset configuration for pyproject.toml format.
785/// Converts the .rumdl.toml preset to pyproject.toml section format.
786pub fn generate_pyproject_preset_config(preset: &str) -> Result<String, ConfigError> {
787    match preset {
788        "default" => Ok(generate_pyproject_config()),
789        other => {
790            let rumdl_config = match other {
791                "google" => generate_google_preset(),
792                "relaxed" => generate_relaxed_preset(),
793                _ => {
794                    return Err(ConfigError::UnknownPreset {
795                        name: other.to_string(),
796                    });
797                }
798            };
799            Ok(convert_rumdl_to_pyproject(&rumdl_config))
800        }
801    }
802}
803
804/// Convert a .rumdl.toml config string to pyproject.toml format.
805/// Rewrites `[global]` → `[tool.rumdl]` and `[MDXXX]` → `[tool.rumdl.MDXXX]`.
806fn convert_rumdl_to_pyproject(rumdl_config: &str) -> String {
807    let mut output = String::with_capacity(rumdl_config.len() + 128);
808    for line in rumdl_config.lines() {
809        let trimmed = line.trim();
810        if trimmed.starts_with('[') && trimmed.ends_with(']') && !trimmed.starts_with("# [") {
811            let section = &trimmed[1..trimmed.len() - 1];
812            if section == "global" {
813                output.push_str("[tool.rumdl]");
814            } else {
815                output.push_str(&format!("[tool.rumdl.{section}]"));
816            }
817        } else {
818            output.push_str(line);
819        }
820        output.push('\n');
821    }
822    output
823}
824
825/// Generate default rumdl configuration for pyproject.toml
826pub fn generate_pyproject_config() -> String {
827    let config_content = r#"
828[tool.rumdl]
829# Global configuration options
830line-length = 100
831disable = []
832# extend-enable = ["MD060"]  # Add opt-in rules (additive, keeps defaults)
833# extend-disable = []  # Additional rules to disable (additive)
834exclude = [
835    # Common directories to exclude
836    ".git",
837    ".github",
838    "node_modules",
839    "vendor",
840    "dist",
841    "build",
842]
843respect-gitignore = true
844
845# Rule-specific configurations (uncomment and modify as needed)
846
847# [tool.rumdl.MD003]
848# style = "atx"  # Heading style (atx, atx_closed, setext)
849
850# [tool.rumdl.MD004]
851# style = "asterisk"  # Unordered list style (asterisk, plus, dash, consistent)
852
853# [tool.rumdl.MD007]
854# indent = 4  # Unordered list indentation
855
856# [tool.rumdl.MD013]
857# line-length = 100  # Line length
858# code-blocks = false  # Exclude code blocks from line length check
859# tables = false  # Exclude tables from line length check
860# headings = true  # Include headings in line length check
861
862# [tool.rumdl.MD044]
863# names = ["rumdl", "Markdown", "GitHub"]  # Proper names that should be capitalized correctly
864# code-blocks = false  # Check code blocks for proper names (default: false, skips code blocks)
865"#;
866
867    config_content.to_string()
868}