Skip to main content

rumdl_lib/config/
loading.rs

1use indexmap::IndexSet;
2use std::collections::BTreeMap;
3use std::marker::PhantomData;
4use std::path::{Path, PathBuf};
5use std::sync::{Arc, OnceLock};
6
7use super::flavor::ConfigLoaded;
8use super::flavor::ConfigValidated;
9use super::parsers;
10use super::registry::RuleRegistry;
11use super::source_tracking::{
12    ConfigSource, ConfigValidationWarning, SourcedConfig, SourcedConfigFragment, SourcedGlobalConfig, SourcedValue,
13};
14use super::types::{Config, ConfigError, GlobalConfig, MARKDOWNLINT_CONFIG_FILES, RUMDL_CONFIG_FILES, RuleConfig};
15use super::validation::validate_config_sourced_internal;
16
17/// Maximum depth for extends chains to prevent runaway recursion
18const MAX_EXTENDS_DEPTH: usize = 10;
19
20/// Cheap pre-filter for whether a `pyproject.toml` declares rumdl config.
21///
22/// Matches the flat section header `[tool.rumdl]` as well as dotted sections
23/// like `[tool.rumdl.MD013]` or `[tool.rumdl.rules.MD007]` (which are valid on
24/// their own, without a flat header). Requiring the leading `[` avoids matching
25/// a bare `tool.rumdl` in prose or dependency names; a literal `[tool.rumdl...`
26/// inside a comment or string would still match, but the subsequent parse
27/// handles that gracefully.
28fn pyproject_declares_rumdl_config(content: &str) -> bool {
29    content.contains("[tool.rumdl]") || content.contains("[tool.rumdl.")
30}
31
32/// Resolve an `extends` path relative to the config file that contains it.
33///
34/// - `~/` prefix: expanded to home directory
35/// - Relative paths: resolved against the config file's parent directory
36/// - Absolute paths: used as-is
37fn resolve_extends_path(extends_value: &str, config_file_path: &Path) -> PathBuf {
38    if let Some(suffix) = extends_value.strip_prefix("~/") {
39        // Expand tilde to home directory
40        #[cfg(feature = "native")]
41        {
42            use etcetera::{BaseStrategy, choose_base_strategy};
43            let home = choose_base_strategy().map_or_else(|_| PathBuf::from("~"), |s| s.home_dir().to_path_buf());
44            home.join(suffix)
45        }
46        #[cfg(not(feature = "native"))]
47        {
48            let _ = suffix;
49            PathBuf::from(extends_value)
50        }
51    } else {
52        let path = PathBuf::from(extends_value);
53        if path.is_absolute() {
54            path
55        } else {
56            // Resolve relative to config file's directory
57            let config_dir = config_file_path.parent().unwrap_or(Path::new("."));
58            config_dir.join(extends_value)
59        }
60    }
61}
62
63/// Determine ConfigSource from a config filename.
64fn source_from_filename(filename: &str) -> ConfigSource {
65    if filename == "pyproject.toml" {
66        ConfigSource::PyprojectToml
67    } else {
68        ConfigSource::ProjectConfig
69    }
70}
71
72/// Load a config file (and any base configs it extends) into a SourcedConfig.
73///
74/// This function handles the recursive `extends` chain:
75/// 1. Parse the config file into a fragment
76/// 2. If the fragment has `extends`, recursively load the base config first
77/// 3. Merge the base config, then merge this fragment on top
78fn load_config_with_extends(
79    sourced_config: &mut SourcedConfig<ConfigLoaded>,
80    config_file_path: &Path,
81    visited: &mut IndexSet<PathBuf>,
82    chain_source: ConfigSource,
83) -> Result<(), ConfigError> {
84    // Canonicalize the path for circular reference detection
85    let canonical = config_file_path
86        .canonicalize()
87        .unwrap_or_else(|_| config_file_path.to_path_buf());
88
89    // Check for circular references
90    if visited.contains(&canonical) {
91        let chain: Vec<String> = visited.iter().map(|p| p.display().to_string()).collect();
92        return Err(ConfigError::CircularExtends {
93            path: config_file_path.display().to_string(),
94            chain,
95        });
96    }
97
98    // Check depth limit
99    if visited.len() >= MAX_EXTENDS_DEPTH {
100        return Err(ConfigError::ExtendsDepthExceeded {
101            path: config_file_path.display().to_string(),
102            max_depth: MAX_EXTENDS_DEPTH,
103        });
104    }
105
106    // Mark as visited
107    visited.insert(canonical);
108
109    let path_str = config_file_path.display().to_string();
110    let filename = config_file_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
111
112    // Read and parse the config file
113    let content = std::fs::read_to_string(config_file_path).map_err(|e| ConfigError::IoError {
114        source: e,
115        path: path_str.clone(),
116    })?;
117
118    let fragment = if filename == "pyproject.toml" {
119        match parsers::parse_pyproject_toml(&content, &path_str, chain_source)? {
120            Some(f) => f,
121            None => return Ok(()), // No [tool.rumdl] section
122        }
123    } else {
124        parsers::parse_rumdl_toml(&content, &path_str, chain_source)?
125    };
126
127    // If this fragment has `extends`, load the base config first
128    if let Some(ref extends_value) = fragment.extends {
129        let base_path = resolve_extends_path(extends_value, config_file_path);
130
131        if !base_path.exists() {
132            return Err(ConfigError::ExtendsNotFound {
133                path: base_path.display().to_string(),
134                from: path_str.clone(),
135            });
136        }
137
138        log::debug!(
139            "[rumdl-config] Config {} extends {}, loading base first",
140            path_str,
141            base_path.display()
142        );
143
144        // Recursively load the base config
145        load_config_with_extends(sourced_config, &base_path, visited, chain_source)?;
146    }
147
148    // Merge this fragment on top (base config was already merged if present)
149    // Strip the `extends` field since it's been consumed
150    let mut fragment_for_merge = fragment;
151    fragment_for_merge.extends = None;
152    sourced_config.merge(fragment_for_merge);
153    sourced_config.loaded_files.push(path_str);
154
155    Ok(())
156}
157
158impl SourcedConfig<ConfigLoaded> {
159    /// Merges another SourcedConfigFragment into this SourcedConfig.
160    /// Uses source precedence to determine which values take effect.
161    pub(super) fn merge(&mut self, fragment: SourcedConfigFragment) {
162        // Merge global config
163        // Enable uses replace semantics (project can enforce rules)
164        self.global.enable.merge_override(
165            fragment.global.enable.value,
166            fragment.global.enable.source,
167            fragment.global.enable.overrides.first().and_then(|o| o.file.clone()),
168            fragment.global.enable.overrides.first().and_then(|o| o.line),
169        );
170
171        // Disable uses replace semantics (child config overrides parent, matching Ruff's `ignore`)
172        self.global.disable.merge_override(
173            fragment.global.disable.value,
174            fragment.global.disable.source,
175            fragment.global.disable.overrides.first().and_then(|o| o.file.clone()),
176            fragment.global.disable.overrides.first().and_then(|o| o.line),
177        );
178
179        // Extend-enable uses union semantics (additive across config levels)
180        self.global.extend_enable.merge_union(
181            fragment.global.extend_enable.value,
182            fragment.global.extend_enable.source,
183            fragment
184                .global
185                .extend_enable
186                .overrides
187                .first()
188                .and_then(|o| o.file.clone()),
189            fragment.global.extend_enable.overrides.first().and_then(|o| o.line),
190        );
191
192        // Extend-disable uses union semantics (additive across config levels)
193        self.global.extend_disable.merge_union(
194            fragment.global.extend_disable.value,
195            fragment.global.extend_disable.source,
196            fragment
197                .global
198                .extend_disable
199                .overrides
200                .first()
201                .and_then(|o| o.file.clone()),
202            fragment.global.extend_disable.overrides.first().and_then(|o| o.line),
203        );
204
205        // Conflict resolution: Enable overrides disable
206        // Remove any rules from disable that appear in enable
207        self.global
208            .disable
209            .value
210            .retain(|rule| !self.global.enable.value.contains(rule));
211        self.global.include.merge_override(
212            fragment.global.include.value,
213            fragment.global.include.source,
214            fragment.global.include.overrides.first().and_then(|o| o.file.clone()),
215            fragment.global.include.overrides.first().and_then(|o| o.line),
216        );
217        self.global.exclude.merge_override(
218            fragment.global.exclude.value,
219            fragment.global.exclude.source,
220            fragment.global.exclude.overrides.first().and_then(|o| o.file.clone()),
221            fragment.global.exclude.overrides.first().and_then(|o| o.line),
222        );
223        self.global.respect_gitignore.merge_override(
224            fragment.global.respect_gitignore.value,
225            fragment.global.respect_gitignore.source,
226            fragment
227                .global
228                .respect_gitignore
229                .overrides
230                .first()
231                .and_then(|o| o.file.clone()),
232            fragment.global.respect_gitignore.overrides.first().and_then(|o| o.line),
233        );
234        self.global.line_length.merge_override(
235            fragment.global.line_length.value,
236            fragment.global.line_length.source,
237            fragment
238                .global
239                .line_length
240                .overrides
241                .first()
242                .and_then(|o| o.file.clone()),
243            fragment.global.line_length.overrides.first().and_then(|o| o.line),
244        );
245        self.global.fixable.merge_override(
246            fragment.global.fixable.value,
247            fragment.global.fixable.source,
248            fragment.global.fixable.overrides.first().and_then(|o| o.file.clone()),
249            fragment.global.fixable.overrides.first().and_then(|o| o.line),
250        );
251        self.global.unfixable.merge_override(
252            fragment.global.unfixable.value,
253            fragment.global.unfixable.source,
254            fragment.global.unfixable.overrides.first().and_then(|o| o.file.clone()),
255            fragment.global.unfixable.overrides.first().and_then(|o| o.line),
256        );
257
258        // Merge flavor
259        self.global.flavor.merge_override(
260            fragment.global.flavor.value,
261            fragment.global.flavor.source,
262            fragment.global.flavor.overrides.first().and_then(|o| o.file.clone()),
263            fragment.global.flavor.overrides.first().and_then(|o| o.line),
264        );
265
266        // Merge force_exclude
267        self.global.force_exclude.merge_override(
268            fragment.global.force_exclude.value,
269            fragment.global.force_exclude.source,
270            fragment
271                .global
272                .force_exclude
273                .overrides
274                .first()
275                .and_then(|o| o.file.clone()),
276            fragment.global.force_exclude.overrides.first().and_then(|o| o.line),
277        );
278
279        // Merge output_format if present
280        if let Some(output_format_fragment) = fragment.global.output_format {
281            if let Some(ref mut output_format) = self.global.output_format {
282                output_format.merge_override(
283                    output_format_fragment.value,
284                    output_format_fragment.source,
285                    output_format_fragment.overrides.first().and_then(|o| o.file.clone()),
286                    output_format_fragment.overrides.first().and_then(|o| o.line),
287                );
288            } else {
289                self.global.output_format = Some(output_format_fragment);
290            }
291        }
292
293        // Merge cache_dir if present
294        if let Some(cache_dir_fragment) = fragment.global.cache_dir {
295            if let Some(ref mut cache_dir) = self.global.cache_dir {
296                cache_dir.merge_override(
297                    cache_dir_fragment.value,
298                    cache_dir_fragment.source,
299                    cache_dir_fragment.overrides.first().and_then(|o| o.file.clone()),
300                    cache_dir_fragment.overrides.first().and_then(|o| o.line),
301                );
302            } else {
303                self.global.cache_dir = Some(cache_dir_fragment);
304            }
305        }
306
307        // Merge cache if not default (only override when explicitly set)
308        if fragment.global.cache.source != ConfigSource::Default {
309            self.global.cache.merge_override(
310                fragment.global.cache.value,
311                fragment.global.cache.source,
312                fragment.global.cache.overrides.first().and_then(|o| o.file.clone()),
313                fragment.global.cache.overrides.first().and_then(|o| o.line),
314            );
315        }
316
317        // Merge per_file_ignores
318        self.per_file_ignores.merge_override(
319            fragment.per_file_ignores.value,
320            fragment.per_file_ignores.source,
321            fragment.per_file_ignores.overrides.first().and_then(|o| o.file.clone()),
322            fragment.per_file_ignores.overrides.first().and_then(|o| o.line),
323        );
324
325        // Merge per_file_flavor
326        self.per_file_flavor.merge_override(
327            fragment.per_file_flavor.value,
328            fragment.per_file_flavor.source,
329            fragment.per_file_flavor.overrides.first().and_then(|o| o.file.clone()),
330            fragment.per_file_flavor.overrides.first().and_then(|o| o.line),
331        );
332
333        // Merge code_block_tools
334        self.code_block_tools.merge_override(
335            fragment.code_block_tools.value,
336            fragment.code_block_tools.source,
337            fragment.code_block_tools.overrides.first().and_then(|o| o.file.clone()),
338            fragment.code_block_tools.overrides.first().and_then(|o| o.line),
339        );
340
341        // Merge rule configs
342        for (rule_name, rule_fragment) in fragment.rules {
343            let norm_rule_name = rule_name.to_ascii_uppercase(); // Normalize to uppercase for case-insensitivity
344            let rule_entry = self.rules.entry(norm_rule_name).or_default();
345
346            // Merge severity if present in fragment
347            if let Some(severity_fragment) = rule_fragment.severity {
348                if let Some(ref mut existing_severity) = rule_entry.severity {
349                    existing_severity.merge_override(
350                        severity_fragment.value,
351                        severity_fragment.source,
352                        severity_fragment.overrides.first().and_then(|o| o.file.clone()),
353                        severity_fragment.overrides.first().and_then(|o| o.line),
354                    );
355                } else {
356                    rule_entry.severity = Some(severity_fragment);
357                }
358            }
359
360            // Merge values
361            for (key, sourced_value_fragment) in rule_fragment.values {
362                let sv_entry = rule_entry
363                    .values
364                    .entry(key.clone())
365                    .or_insert_with(|| SourcedValue::new(sourced_value_fragment.value.clone(), ConfigSource::Default));
366                let file_from_fragment = sourced_value_fragment.overrides.first().and_then(|o| o.file.clone());
367                let line_from_fragment = sourced_value_fragment.overrides.first().and_then(|o| o.line);
368                sv_entry.merge_override(
369                    sourced_value_fragment.value,  // Use the value from the fragment
370                    sourced_value_fragment.source, // Use the source from the fragment
371                    file_from_fragment,            // Pass the file path from the fragment override
372                    line_from_fragment,            // Pass the line number from the fragment override
373                );
374            }
375        }
376
377        // Merge unknown_keys from fragment
378        for (section, key, file_path) in fragment.unknown_keys {
379            // Deduplicate: only add if not already present
380            if !self.unknown_keys.iter().any(|(s, k, _)| s == &section && k == &key) {
381                self.unknown_keys.push((section, key, file_path));
382            }
383        }
384    }
385
386    /// Load and merge configurations from files and CLI overrides.
387    pub fn load(config_path: Option<&str>, cli_overrides: Option<&SourcedGlobalConfig>) -> Result<Self, ConfigError> {
388        Self::load_with_discovery(config_path, cli_overrides, false)
389    }
390
391    /// Finds project root by walking up from start_dir looking for .git directory.
392    /// Falls back to start_dir if no .git found.
393    fn find_project_root_from(start_dir: &Path) -> std::path::PathBuf {
394        // Convert relative paths to absolute to ensure correct traversal
395        let mut current = if start_dir.is_relative() {
396            std::env::current_dir().map_or_else(|_| start_dir.to_path_buf(), |cwd| cwd.join(start_dir))
397        } else {
398            start_dir.to_path_buf()
399        };
400        const MAX_DEPTH: usize = 100;
401
402        for _ in 0..MAX_DEPTH {
403            if current.join(".git").exists() {
404                log::debug!("[rumdl-config] Found .git at: {}", current.display());
405                return current;
406            }
407
408            match current.parent() {
409                Some(parent) => current = parent.to_path_buf(),
410                None => break,
411            }
412        }
413
414        // No .git found, use start_dir as project root
415        log::debug!(
416            "[rumdl-config] No .git found, using config location as project root: {}",
417            start_dir.display()
418        );
419        start_dir.to_path_buf()
420    }
421
422    /// Discover configuration file by traversing up the directory tree.
423    /// Returns the first configuration file found.
424    /// Discovers config file and returns both the config path and project root.
425    /// Returns: (config_file_path, project_root_path)
426    /// Project root is the directory containing .git, or config parent as fallback.
427    fn discover_config_upward() -> Option<(std::path::PathBuf, std::path::PathBuf)> {
428        use std::env;
429
430        const MAX_DEPTH: usize = 100; // Prevent infinite traversal
431
432        let start_dir = match env::current_dir() {
433            Ok(dir) => dir,
434            Err(e) => {
435                log::debug!("[rumdl-config] Failed to get current directory: {e}");
436                return None;
437            }
438        };
439
440        let mut current_dir = start_dir.clone();
441        let mut depth = 0;
442        let mut found_config: Option<(std::path::PathBuf, std::path::PathBuf)> = None;
443
444        loop {
445            if depth >= MAX_DEPTH {
446                log::debug!("[rumdl-config] Maximum traversal depth reached");
447                break;
448            }
449
450            log::debug!("[rumdl-config] Searching for config in: {}", current_dir.display());
451
452            // Check for config files in order of precedence (only if not already found)
453            if found_config.is_none() {
454                for config_name in RUMDL_CONFIG_FILES {
455                    let config_path = current_dir.join(config_name);
456
457                    if config_path.exists() {
458                        // For pyproject.toml, verify it contains [tool.rumdl] section
459                        if *config_name == "pyproject.toml" {
460                            if let Ok(content) = std::fs::read_to_string(&config_path) {
461                                if pyproject_declares_rumdl_config(&content) {
462                                    log::debug!("[rumdl-config] Found config file: {}", config_path.display());
463                                    // Store config, but continue looking for .git
464                                    found_config = Some((config_path.clone(), current_dir.clone()));
465                                    break;
466                                }
467                                log::debug!("[rumdl-config] Found pyproject.toml but no [tool.rumdl] section");
468                                continue;
469                            }
470                        } else {
471                            log::debug!("[rumdl-config] Found config file: {}", config_path.display());
472                            // Store config, but continue looking for .git
473                            found_config = Some((config_path.clone(), current_dir.clone()));
474                            break;
475                        }
476                    }
477                }
478            }
479
480            // Check for .git directory (stop boundary)
481            if current_dir.join(".git").exists() {
482                log::debug!("[rumdl-config] Stopping at .git directory");
483                break;
484            }
485
486            // Move to parent directory
487            match current_dir.parent() {
488                Some(parent) => {
489                    current_dir = parent.to_owned();
490                    depth += 1;
491                }
492                None => {
493                    log::debug!("[rumdl-config] Reached filesystem root");
494                    break;
495                }
496            }
497        }
498
499        // If config found, determine project root by walking up from config location
500        if let Some((config_path, config_dir)) = found_config {
501            let project_root = Self::find_project_root_from(&config_dir);
502            return Some((config_path, project_root));
503        }
504
505        None
506    }
507
508    /// Discover markdownlint configuration file by traversing up the directory tree.
509    /// Similar to discover_config_upward but for .markdownlint.yaml/json files.
510    /// Returns the path to the config file if found.
511    fn discover_markdownlint_config_upward() -> Option<std::path::PathBuf> {
512        use std::env;
513
514        const MAX_DEPTH: usize = 100;
515
516        let start_dir = match env::current_dir() {
517            Ok(dir) => dir,
518            Err(e) => {
519                log::debug!("[rumdl-config] Failed to get current directory for markdownlint discovery: {e}");
520                return None;
521            }
522        };
523
524        let mut current_dir = start_dir.clone();
525        let mut depth = 0;
526
527        loop {
528            if depth >= MAX_DEPTH {
529                log::debug!("[rumdl-config] Maximum traversal depth reached for markdownlint discovery");
530                break;
531            }
532
533            log::debug!(
534                "[rumdl-config] Searching for markdownlint config in: {}",
535                current_dir.display()
536            );
537
538            // Check for markdownlint config files in order of precedence
539            for config_name in MARKDOWNLINT_CONFIG_FILES {
540                let config_path = current_dir.join(config_name);
541                if config_path.exists() {
542                    log::debug!("[rumdl-config] Found markdownlint config: {}", config_path.display());
543                    return Some(config_path);
544                }
545            }
546
547            // Check for .git directory (stop boundary)
548            if current_dir.join(".git").exists() {
549                log::debug!("[rumdl-config] Stopping markdownlint search at .git directory");
550                break;
551            }
552
553            // Move to parent directory
554            match current_dir.parent() {
555                Some(parent) => {
556                    current_dir = parent.to_owned();
557                    depth += 1;
558                }
559                None => {
560                    log::debug!("[rumdl-config] Reached filesystem root during markdownlint search");
561                    break;
562                }
563            }
564        }
565
566        None
567    }
568
569    /// Internal implementation that accepts config directory for testing
570    fn user_configuration_path_impl(config_dir: &Path) -> Option<std::path::PathBuf> {
571        let config_dir = config_dir.join("rumdl");
572
573        // Check for config files in precedence order (same as project discovery)
574        const USER_CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml", "pyproject.toml"];
575
576        log::debug!(
577            "[rumdl-config] Checking for user configuration in: {}",
578            config_dir.display()
579        );
580
581        for filename in USER_CONFIG_FILES {
582            let config_path = config_dir.join(filename);
583
584            if config_path.exists() {
585                // For pyproject.toml, verify it contains [tool.rumdl] section
586                if *filename == "pyproject.toml" {
587                    if let Ok(content) = std::fs::read_to_string(&config_path) {
588                        if pyproject_declares_rumdl_config(&content) {
589                            log::debug!("[rumdl-config] Found user configuration at: {}", config_path.display());
590                            return Some(config_path);
591                        }
592                        log::debug!("[rumdl-config] Found user pyproject.toml but no [tool.rumdl] section");
593                        continue;
594                    }
595                } else {
596                    log::debug!("[rumdl-config] Found user configuration at: {}", config_path.display());
597                    return Some(config_path);
598                }
599            }
600        }
601
602        log::debug!(
603            "[rumdl-config] No user configuration found in: {}",
604            config_dir.display()
605        );
606        None
607    }
608
609    /// Discover user-level configuration file from platform-specific config directory.
610    /// Returns the first configuration file found in the user config directory.
611    #[cfg(feature = "native")]
612    fn user_configuration_path() -> Option<std::path::PathBuf> {
613        use etcetera::{BaseStrategy, choose_base_strategy};
614
615        match choose_base_strategy() {
616            Ok(strategy) => {
617                let config_dir = strategy.config_dir();
618                Self::user_configuration_path_impl(&config_dir)
619            }
620            Err(e) => {
621                log::debug!("[rumdl-config] Failed to determine user config directory: {e}");
622                None
623            }
624        }
625    }
626
627    /// Stub for WASM builds - user config not supported
628    #[cfg(not(feature = "native"))]
629    fn user_configuration_path() -> Option<std::path::PathBuf> {
630        None
631    }
632
633    /// Internal implementation that accepts the home directory for testing.
634    ///
635    /// Probes `<home>/.rumdl.toml` then `<home>/rumdl.toml`, returning the first match.
636    ///
637    /// `pyproject.toml` is intentionally **not** searched in `$HOME`, even though
638    /// `user_configuration_path_impl` does check it inside the platform config dir.
639    /// The asymmetry is deliberate: a `pyproject.toml` directly in `$HOME` almost
640    /// always belongs to unrelated python tooling (poetry/uv/pip's user-level config),
641    /// and silently picking it up as a rumdl config would surprise users. The
642    /// platform config dir (`~/.config/rumdl/`) is rumdl-scoped, so the same
643    /// concern doesn't apply there.
644    fn home_configuration_path_impl(home_dir: &Path) -> Option<std::path::PathBuf> {
645        const HOME_CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml"];
646
647        log::debug!(
648            "[rumdl-config] Checking for home-directory configuration in: {}",
649            home_dir.display()
650        );
651
652        for filename in HOME_CONFIG_FILES {
653            let config_path = home_dir.join(filename);
654            if config_path.exists() {
655                log::debug!(
656                    "[rumdl-config] Found home-directory configuration at: {}",
657                    config_path.display()
658                );
659                return Some(config_path);
660            }
661        }
662
663        log::debug!(
664            "[rumdl-config] No home-directory configuration found in: {}",
665            home_dir.display()
666        );
667        None
668    }
669
670    /// Discover a home-directory configuration file (`~/.rumdl.toml` or `~/rumdl.toml`).
671    ///
672    /// This is a final fallback after the platform user-config directory
673    /// (`user_configuration_path`). It honors the classic Unix dotfile convention so
674    /// users who keep tool config in `$HOME` rather than `$XDG_CONFIG_HOME` are picked up.
675    #[cfg(feature = "native")]
676    fn home_configuration_path() -> Option<std::path::PathBuf> {
677        use etcetera::{BaseStrategy, choose_base_strategy};
678
679        match choose_base_strategy() {
680            Ok(strategy) => Self::home_configuration_path_impl(strategy.home_dir()),
681            Err(e) => {
682                log::debug!("[rumdl-config] Failed to determine home directory: {e}");
683                None
684            }
685        }
686    }
687
688    /// Stub for WASM builds - home config not supported
689    #[cfg(not(feature = "native"))]
690    fn home_configuration_path() -> Option<std::path::PathBuf> {
691        None
692    }
693
694    /// Load an explicit config file (standalone, no user config merging)
695    fn load_explicit_config(sourced_config: &mut Self, path: &str) -> Result<(), ConfigError> {
696        let path_obj = Path::new(path);
697        let filename = path_obj.file_name().and_then(|name| name.to_str()).unwrap_or("");
698        let path_str = path.to_string();
699
700        log::debug!("[rumdl-config] Loading explicit config file: {filename}");
701
702        // Find project root by walking up from config location looking for .git
703        if let Some(config_parent) = path_obj.parent() {
704            let project_root = Self::find_project_root_from(config_parent);
705            log::debug!(
706                "[rumdl-config] Project root (from explicit config): {}",
707                project_root.display()
708            );
709            sourced_config.project_root = Some(project_root);
710        }
711
712        // Known markdownlint config files
713        const MARKDOWNLINT_FILENAMES: &[&str] = &[
714            ".markdownlint-cli2.jsonc",
715            ".markdownlint-cli2.yaml",
716            ".markdownlint-cli2.yml",
717            ".markdownlint.json",
718            ".markdownlint.yaml",
719            ".markdownlint.yml",
720        ];
721
722        if filename == "pyproject.toml" || filename == ".rumdl.toml" || filename == "rumdl.toml" {
723            // Use extends-aware loading for rumdl TOML configs
724            let mut visited = IndexSet::new();
725            let chain_source = source_from_filename(filename);
726            load_config_with_extends(sourced_config, path_obj, &mut visited, chain_source)?;
727        } else if MARKDOWNLINT_FILENAMES.contains(&filename)
728            || path_str.ends_with(".json")
729            || path_str.ends_with(".jsonc")
730            || path_str.ends_with(".yaml")
731            || path_str.ends_with(".yml")
732        {
733            // Parse as markdownlint config (JSON/YAML) - no extends support
734            let fragment = parsers::load_from_markdownlint(&path_str)?;
735            sourced_config.merge(fragment);
736            sourced_config.loaded_files.push(path_str);
737        } else {
738            // Try TOML with extends support
739            let mut visited = IndexSet::new();
740            let chain_source = source_from_filename(filename);
741            load_config_with_extends(sourced_config, path_obj, &mut visited, chain_source)?;
742        }
743
744        Ok(())
745    }
746
747    /// Load and merge user-level configuration into this `SourcedConfig`.
748    ///
749    /// Discovers the user config file in this order, taking the first match:
750    /// 1. Platform user-config directory (XDG on Linux, `~/Library/Application Support`
751    ///    on macOS, `%APPDATA%` on Windows). Override with `user_config_dir` for tests.
752    /// 2. Home-directory dotfile (`~/.rumdl.toml`, then `~/rumdl.toml`). Override with
753    ///    `home_dir` for tests. Honors the classic Unix dotfile convention.
754    ///
755    /// Resolves any `extends` chain and merges each fragment with
756    /// `ConfigSource::UserConfig` precedence.
757    ///
758    /// Called in two contexts:
759    /// - When no project config is found: provides user defaults as the sole base
760    /// - When a markdownlint project config is found: provides rumdl-specific
761    ///   defaults that the markdownlint format cannot express; the markdownlint
762    ///   fragment is merged on top and wins on any overlapping key
763    fn load_user_config(
764        sourced_config: &mut Self,
765        user_config_dir: Option<&Path>,
766        home_dir: Option<&Path>,
767    ) -> Result<(), ConfigError> {
768        let user_config_path = if let Some(dir) = user_config_dir {
769            Self::user_configuration_path_impl(dir)
770        } else {
771            Self::user_configuration_path()
772        };
773
774        let user_config_path = user_config_path.or_else(|| match home_dir {
775            Some(home) => Self::home_configuration_path_impl(home),
776            None => Self::home_configuration_path(),
777        });
778
779        if let Some(user_config_path) = user_config_path {
780            let path_str = user_config_path.display().to_string();
781
782            log::debug!("[rumdl-config] Loading user config: {path_str}");
783
784            // User config fallback also supports extends chains.
785            // Use a uniform source across the chain so child overrides are determined by chain order.
786            let mut visited = IndexSet::new();
787            load_config_with_extends(
788                sourced_config,
789                &user_config_path,
790                &mut visited,
791                ConfigSource::UserConfig,
792            )?;
793        } else {
794            log::debug!("[rumdl-config] No user configuration file found");
795        }
796
797        Ok(())
798    }
799
800    /// Internal implementation that accepts user config directory and home directory for testing
801    #[doc(hidden)]
802    pub fn load_with_discovery_impl(
803        config_path: Option<&str>,
804        cli_overrides: Option<&SourcedGlobalConfig>,
805        skip_auto_discovery: bool,
806        user_config_dir: Option<&Path>,
807        home_dir: Option<&Path>,
808    ) -> Result<Self, ConfigError> {
809        use std::env;
810        log::debug!("[rumdl-config] Current working directory: {:?}", env::current_dir());
811
812        let mut sourced_config = SourcedConfig::default();
813
814        // Ruff model: Project config is standalone, user config is fallback only
815        //
816        // Priority order:
817        // 1. If explicit config path provided → use ONLY that (standalone)
818        // 2. Else if project config discovered → use ONLY that (standalone)
819        // 3. Else if user config exists → use it as fallback
820        // 4. CLI overrides always apply last
821        //
822        // This ensures project configs are reproducible across machines and
823        // CI/local runs behave identically.
824
825        // Explicit config path always takes precedence
826        if let Some(path) = config_path {
827            // Explicit config path provided - use ONLY this config (standalone)
828            log::debug!("[rumdl-config] Explicit config_path provided: {path:?}");
829            Self::load_explicit_config(&mut sourced_config, path)?;
830        } else if skip_auto_discovery {
831            log::debug!("[rumdl-config] Skipping config discovery due to --no-config/--isolated flag");
832            // No config loading, just apply CLI overrides at the end
833        } else {
834            // No explicit path - try auto-discovery
835            log::debug!("[rumdl-config] No explicit config_path, searching default locations");
836
837            // Try to discover project config first
838            if let Some((config_file, project_root)) = Self::discover_config_upward() {
839                // Project config found - use ONLY this (standalone, no user config).
840                // Rumdl project configs can express all settings directly, so user config
841                // is not needed and omitting it ensures CI and local runs are identical.
842                log::debug!("[rumdl-config] Found project config: {}", config_file.display());
843                log::debug!("[rumdl-config] Project root: {}", project_root.display());
844
845                sourced_config.project_root = Some(project_root);
846
847                // Use extends-aware loading for discovered configs
848                let mut visited = IndexSet::new();
849                let root_filename = config_file.file_name().and_then(|n| n.to_str()).unwrap_or("");
850                let chain_source = source_from_filename(root_filename);
851                load_config_with_extends(&mut sourced_config, &config_file, &mut visited, chain_source)?;
852            } else {
853                // No rumdl project config - try markdownlint config
854                log::debug!("[rumdl-config] No rumdl config found, checking markdownlint config");
855
856                if let Some(markdownlint_path) = Self::discover_markdownlint_config_upward() {
857                    let path_str = markdownlint_path.display().to_string();
858                    log::debug!("[rumdl-config] Found markdownlint config: {path_str}");
859                    // Load user config first as a base so rumdl-specific settings (e.g. flavor,
860                    // cache) take effect. Markdownlint configs cannot express these settings.
861                    // The markdownlint fragment uses ConfigSource::ProjectConfig (precedence 3)
862                    // vs UserConfig (precedence 1), so project settings always win on overlap.
863                    Self::load_user_config(&mut sourced_config, user_config_dir, home_dir)?;
864                    match parsers::load_from_markdownlint(&path_str) {
865                        Ok(fragment) => {
866                            sourced_config.merge(fragment);
867                            sourced_config.loaded_files.push(path_str);
868                        }
869                        Err(_e) => {
870                            log::debug!("[rumdl-config] Failed to load markdownlint config");
871                        }
872                    }
873                } else {
874                    // No project config at all - use user config as fallback
875                    log::debug!("[rumdl-config] No project config found, using user config as fallback");
876                    Self::load_user_config(&mut sourced_config, user_config_dir, home_dir)?;
877                }
878            }
879        }
880
881        // Apply CLI overrides (highest precedence)
882        if let Some(cli) = cli_overrides {
883            sourced_config
884                .global
885                .enable
886                .merge_override(cli.enable.value.clone(), ConfigSource::Cli, None, None);
887            sourced_config
888                .global
889                .disable
890                .merge_override(cli.disable.value.clone(), ConfigSource::Cli, None, None);
891            sourced_config
892                .global
893                .exclude
894                .merge_override(cli.exclude.value.clone(), ConfigSource::Cli, None, None);
895            sourced_config
896                .global
897                .include
898                .merge_override(cli.include.value.clone(), ConfigSource::Cli, None, None);
899            sourced_config.global.respect_gitignore.merge_override(
900                cli.respect_gitignore.value,
901                ConfigSource::Cli,
902                None,
903                None,
904            );
905            sourced_config
906                .global
907                .fixable
908                .merge_override(cli.fixable.value.clone(), ConfigSource::Cli, None, None);
909            sourced_config
910                .global
911                .unfixable
912                .merge_override(cli.unfixable.value.clone(), ConfigSource::Cli, None, None);
913            // No rule-specific CLI overrides implemented yet
914        }
915
916        // Unknown keys are now collected during parsing and validated via validate_config_sourced()
917
918        Ok(sourced_config)
919    }
920
921    /// Load and merge configurations from files and CLI overrides.
922    /// If skip_auto_discovery is true, only explicit config paths are loaded.
923    pub fn load_with_discovery(
924        config_path: Option<&str>,
925        cli_overrides: Option<&SourcedGlobalConfig>,
926        skip_auto_discovery: bool,
927    ) -> Result<Self, ConfigError> {
928        Self::load_with_discovery_impl(config_path, cli_overrides, skip_auto_discovery, None, None)
929    }
930
931    /// Validate the configuration against a rule registry.
932    ///
933    /// This method transitions the config from `ConfigLoaded` to `ConfigValidated` state,
934    /// enabling conversion to `Config`. Validation warnings are stored in the config
935    /// and can be displayed to the user.
936    ///
937    /// # Example
938    ///
939    /// ```ignore
940    /// let loaded = SourcedConfig::load_with_discovery(path, None, false)?;
941    /// let validated = loaded.validate(&registry)?;
942    /// let config: Config = validated.into();
943    /// ```
944    pub fn validate(self, registry: &RuleRegistry) -> Result<SourcedConfig<ConfigValidated>, ConfigError> {
945        let warnings = validate_config_sourced_internal(&self, registry);
946
947        Ok(SourcedConfig {
948            global: self.global,
949            per_file_ignores: self.per_file_ignores,
950            per_file_flavor: self.per_file_flavor,
951            code_block_tools: self.code_block_tools,
952            rules: self.rules,
953            loaded_files: self.loaded_files,
954            unknown_keys: self.unknown_keys,
955            project_root: self.project_root,
956            validation_warnings: warnings,
957            _state: PhantomData,
958        })
959    }
960
961    /// Validate and convert to Config in one step (convenience method).
962    ///
963    /// This combines `validate()` and `into()` for callers who want the
964    /// validation warnings separately.
965    pub fn validate_into(self, registry: &RuleRegistry) -> Result<(Config, Vec<ConfigValidationWarning>), ConfigError> {
966        let validated = self.validate(registry)?;
967        let warnings = validated.validation_warnings.clone();
968        Ok((validated.into(), warnings))
969    }
970
971    /// Skip validation and convert directly to ConfigValidated state.
972    ///
973    /// # Safety
974    ///
975    /// This method bypasses validation. Use only when:
976    /// - You've already validated via `validate_config_sourced()`
977    /// - You're in test code that doesn't need validation
978    /// - You're migrating legacy code and will add proper validation later
979    ///
980    /// Prefer `validate()` for new code.
981    pub fn into_validated_unchecked(self) -> SourcedConfig<ConfigValidated> {
982        SourcedConfig {
983            global: self.global,
984            per_file_ignores: self.per_file_ignores,
985            per_file_flavor: self.per_file_flavor,
986            code_block_tools: self.code_block_tools,
987            rules: self.rules,
988            loaded_files: self.loaded_files,
989            unknown_keys: self.unknown_keys,
990            project_root: self.project_root,
991            validation_warnings: Vec::new(),
992            _state: PhantomData,
993        }
994    }
995
996    /// Discover the nearest config file for a specific directory,
997    /// walking upward to `project_root` (inclusive).
998    ///
999    /// Searches for rumdl config files (`.rumdl.toml`, `rumdl.toml`,
1000    /// `.config/rumdl.toml`, `pyproject.toml` with `[tool.rumdl]`) and
1001    /// markdownlint config files at each directory level.
1002    ///
1003    /// Returns the config file path if found. Does NOT use CWD.
1004    pub fn discover_config_for_dir(dir: &Path, project_root: &Path) -> Option<PathBuf> {
1005        let mut current_dir = dir.to_path_buf();
1006
1007        loop {
1008            // Check rumdl config files first (higher precedence)
1009            for config_name in RUMDL_CONFIG_FILES {
1010                let config_path = current_dir.join(config_name);
1011                if config_path.exists() {
1012                    if *config_name == "pyproject.toml" {
1013                        if let Ok(content) = std::fs::read_to_string(&config_path)
1014                            && pyproject_declares_rumdl_config(&content)
1015                        {
1016                            return Some(config_path);
1017                        }
1018                        continue;
1019                    }
1020                    return Some(config_path);
1021                }
1022            }
1023
1024            // Check markdownlint config files (lower precedence)
1025            for config_name in MARKDOWNLINT_CONFIG_FILES {
1026                let config_path = current_dir.join(config_name);
1027                if config_path.exists() {
1028                    return Some(config_path);
1029                }
1030            }
1031
1032            // Stop at project root (inclusive - we already checked it)
1033            if current_dir == project_root {
1034                break;
1035            }
1036
1037            // Move to parent directory
1038            match current_dir.parent() {
1039                Some(parent) => current_dir = parent.to_path_buf(),
1040                None => break,
1041            }
1042        }
1043
1044        None
1045    }
1046
1047    /// Load a config from a specific file path, with extends resolution.
1048    ///
1049    /// Creates a fresh `SourcedConfig`, loads the config file using the
1050    /// appropriate parser, and converts to `Config`. Used for per-directory
1051    /// config loading where each subdirectory config is standalone.
1052    pub fn load_config_for_path(config_path: &Path, project_root: &Path) -> Result<Config, ConfigError> {
1053        let mut sourced_config = SourcedConfig {
1054            project_root: Some(project_root.to_path_buf()),
1055            ..SourcedConfig::default()
1056        };
1057
1058        let filename = config_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
1059        let path_str = config_path.display().to_string();
1060
1061        // Determine if this is a markdownlint config or rumdl config
1062        let is_markdownlint = MARKDOWNLINT_CONFIG_FILES.contains(&filename)
1063            || (filename != "pyproject.toml"
1064                && filename != ".rumdl.toml"
1065                && filename != "rumdl.toml"
1066                && (path_str.ends_with(".json")
1067                    || path_str.ends_with(".jsonc")
1068                    || path_str.ends_with(".yaml")
1069                    || path_str.ends_with(".yml")));
1070
1071        if is_markdownlint {
1072            let fragment = parsers::load_from_markdownlint(&path_str)?;
1073            sourced_config.merge(fragment);
1074            sourced_config.loaded_files.push(path_str);
1075        } else {
1076            let mut visited = IndexSet::new();
1077            let chain_source = source_from_filename(filename);
1078            load_config_with_extends(&mut sourced_config, config_path, &mut visited, chain_source)?;
1079        }
1080
1081        Ok(sourced_config.into_validated_unchecked().into())
1082    }
1083}
1084
1085/// Convert a validated configuration to the final Config type.
1086///
1087/// This implementation only exists for `SourcedConfig<ConfigValidated>`,
1088/// ensuring that validation must occur before conversion.
1089impl From<SourcedConfig<ConfigValidated>> for Config {
1090    fn from(sourced: SourcedConfig<ConfigValidated>) -> Self {
1091        let mut rules = BTreeMap::new();
1092        for (rule_name, sourced_rule_cfg) in sourced.rules {
1093            // Normalize rule name to uppercase for case-insensitive lookup
1094            let normalized_rule_name = rule_name.to_ascii_uppercase();
1095            let severity = sourced_rule_cfg.severity.map(|sv| sv.value);
1096            let mut values = BTreeMap::new();
1097            for (key, sourced_val) in sourced_rule_cfg.values {
1098                values.insert(key, sourced_val.value);
1099            }
1100            rules.insert(normalized_rule_name, RuleConfig { severity, values });
1101        }
1102        // Enable is "explicit" if it was set by something other than the Default source
1103        let enable_is_explicit = sourced.global.enable.source != ConfigSource::Default;
1104
1105        #[allow(deprecated)]
1106        let global = GlobalConfig {
1107            enable: sourced.global.enable.value,
1108            disable: sourced.global.disable.value,
1109            exclude: sourced.global.exclude.value,
1110            include: sourced.global.include.value,
1111            respect_gitignore: sourced.global.respect_gitignore.value,
1112            line_length: sourced.global.line_length.value,
1113            output_format: sourced.global.output_format.as_ref().map(|v| v.value.clone()),
1114            fixable: sourced.global.fixable.value,
1115            unfixable: sourced.global.unfixable.value,
1116            flavor: sourced.global.flavor.value,
1117            force_exclude: sourced.global.force_exclude.value,
1118            cache_dir: sourced.global.cache_dir.as_ref().map(|v| v.value.clone()),
1119            cache: sourced.global.cache.value,
1120            extend_enable: sourced.global.extend_enable.value,
1121            extend_disable: sourced.global.extend_disable.value,
1122            enable_is_explicit,
1123        };
1124
1125        let mut config = Config {
1126            extends: None,
1127            global,
1128            per_file_ignores: sourced.per_file_ignores.value,
1129            per_file_flavor: sourced.per_file_flavor.value,
1130            code_block_tools: sourced.code_block_tools.value,
1131            rules,
1132            project_root: sourced.project_root,
1133            per_file_ignores_cache: Arc::new(OnceLock::new()),
1134            per_file_flavor_cache: Arc::new(OnceLock::new()),
1135            canonical_project_root_cache: Arc::new(OnceLock::new()),
1136        };
1137
1138        // Apply per-rule `enabled = true/false` to global enable/disable lists
1139        config.apply_per_rule_enabled();
1140
1141        // Enforce the runtime invariant: every rule-name list is canonicalised.
1142        // After this point, downstream consumers (`rules::filter_rules`, the LSP,
1143        // WASM, fix coordinator, per-file-ignores) can match against
1144        // `Rule::name()` with simple string equality regardless of whether the
1145        // user's config used canonical IDs (`"MD033"`) or aliases
1146        // (`"no-inline-html"`).
1147        config.canonicalize_rule_lists();
1148
1149        config
1150    }
1151}
1152
1153#[cfg(test)]
1154mod tests {
1155    use super::pyproject_declares_rumdl_config;
1156
1157    #[test]
1158    fn detects_flat_and_dotted_rumdl_sections() {
1159        assert!(pyproject_declares_rumdl_config("[tool.rumdl]\nline-length = 80\n"));
1160        // Dotted sections are valid on their own, without a flat header.
1161        assert!(pyproject_declares_rumdl_config(
1162            "[tool.rumdl.MD013]\nstyle = \"fixed\"\n"
1163        ));
1164        assert!(pyproject_declares_rumdl_config(
1165            "[tool.rumdl.rules.MD007]\nindent = 4\n"
1166        ));
1167    }
1168
1169    #[test]
1170    fn ignores_incidental_mentions() {
1171        // A bare `tool.rumdl` in a comment or string value must not be treated
1172        // as a config section.
1173        assert!(!pyproject_declares_rumdl_config("# configure tool.rumdl later\n"));
1174        assert!(!pyproject_declares_rumdl_config(
1175            "[project]\ndependencies = [\"tool.rumdl-helper\"]\n"
1176        ));
1177        assert!(!pyproject_declares_rumdl_config("[tool.black]\nline-length = 88\n"));
1178    }
1179}