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::{
15    Config, ConfigError, DiscoveredConfigError, GlobalConfig, MARKDOWNLINT_CONFIG_FILES, RUMDL_CONFIG_FILES, RuleConfig,
16};
17use super::validation::validate_config_sourced_internal;
18use crate::utils::upward_walk::UpwardWalk;
19
20/// Maximum depth for extends chains to prevent runaway recursion
21const MAX_EXTENDS_DEPTH: usize = 10;
22
23/// Cheap pre-filter for whether a `pyproject.toml` declares rumdl config.
24///
25/// Matches the flat section header `[tool.rumdl]` as well as dotted sections
26/// like `[tool.rumdl.MD013]` or `[tool.rumdl.rules.MD007]` (which are valid on
27/// their own, without a flat header). Requiring the leading `[` avoids matching
28/// a bare `tool.rumdl` in prose or dependency names; a literal `[tool.rumdl...`
29/// inside a comment or string would still match, but the subsequent parse
30/// handles that gracefully.
31fn pyproject_declares_rumdl_config(content: &str) -> bool {
32    content.contains("[tool.rumdl]") || content.contains("[tool.rumdl.")
33}
34
35/// True if `b` may start a `$VAR` identifier (`[A-Za-z_]`).
36fn is_var_name_start(b: u8) -> bool {
37    b == b'_' || b.is_ascii_alphabetic()
38}
39
40/// True if `b` may continue a `$VAR` identifier (`[A-Za-z0-9_]`).
41fn is_var_name_continue(b: u8) -> bool {
42    b == b'_' || b.is_ascii_alphanumeric()
43}
44
45/// True if `name` is a non-empty valid environment-variable identifier.
46fn is_valid_var_name(name: &str) -> bool {
47    let bytes = name.as_bytes();
48    !bytes.is_empty() && is_var_name_start(bytes[0]) && bytes[1..].iter().all(|&b| is_var_name_continue(b))
49}
50
51/// Expand `$VAR` and `${VAR}` references in `input` using `lookup`.
52///
53/// Grammar (frozen; documented in `docs/global-settings.md`):
54/// - `$NAME` / `${NAME}` with `NAME = [A-Za-z_][A-Za-z0-9_]*` expands to the variable's
55///   value; the longest valid identifier is matched (`$FOO_BAR` is one name).
56/// - `$$` is a literal `$` (escape), so `$$VAR` -> `$VAR` and `$${VAR}` -> `${VAR}` (no
57///   expansion of the escaped form).
58/// - Any other `$` is left literal: `$` before a non-identifier char (`$5`, trailing `$`),
59///   an empty `${}`, an unterminated `${VAR`, or a `${...}` whose body is not a valid
60///   identifier (e.g. nested `${A${B}}`) - the whole `${...}` span up to the first `}` is
61///   emitted literally.
62/// - Replacement values are inserted literally and are NOT re-scanned (single left-to-right
63///   pass): if `A="$B"`, then `$A` expands to the literal string `$B`.
64///
65/// Returns `Err(name)` on the first well-formed reference to an undefined variable. All
66/// special characters (`$`, `{`, `}`, identifier chars) are ASCII, so byte scanning never
67/// splits a multibyte UTF-8 sequence; non-ASCII bytes are copied verbatim as literals.
68fn expand_env_vars(input: &str, lookup: impl Fn(&str) -> Option<String>) -> Result<String, String> {
69    let bytes = input.as_bytes();
70    let mut out = String::with_capacity(input.len());
71    let mut i = 0;
72
73    while i < bytes.len() {
74        if bytes[i] != b'$' {
75            // Copy the maximal run of non-`$` bytes as a slice (preserves UTF-8).
76            let start = i;
77            while i < bytes.len() && bytes[i] != b'$' {
78                i += 1;
79            }
80            out.push_str(&input[start..i]);
81            continue;
82        }
83
84        match bytes.get(i + 1).copied() {
85            // `$$` -> literal `$`.
86            Some(b'$') => {
87                out.push('$');
88                i += 2;
89            }
90            // `${...}` braced form.
91            Some(b'{') => {
92                if let Some(rel) = input[i + 2..].find('}') {
93                    let close = i + 2 + rel;
94                    let name = &input[i + 2..close];
95                    if is_valid_var_name(name) {
96                        match lookup(name) {
97                            Some(value) => out.push_str(&value),
98                            None => return Err(name.to_string()),
99                        }
100                    } else {
101                        // Empty / invalid / nested body -> whole `${...}` span is literal.
102                        out.push_str(&input[i..=close]);
103                    }
104                    i = close + 1;
105                } else {
106                    // No closing `}` -> leave the `$` literal and resume at `{`.
107                    out.push('$');
108                    i += 1;
109                }
110            }
111            // `$NAME` bare form.
112            Some(b) if is_var_name_start(b) => {
113                let start = i + 1;
114                let mut j = start;
115                while j < bytes.len() && is_var_name_continue(bytes[j]) {
116                    j += 1;
117                }
118                let name = &input[start..j];
119                match lookup(name) {
120                    Some(value) => out.push_str(&value),
121                    None => return Err(name.to_string()),
122                }
123                i = j;
124            }
125            // `$` before a non-identifier char or at end of input -> literal `$`.
126            _ => {
127                out.push('$');
128                i += 1;
129            }
130        }
131    }
132
133    Ok(out)
134}
135
136/// Resolve an `extends` path relative to the config file that contains it.
137///
138/// - `$VAR` / `${VAR}`: expanded from the environment first (see [`expand_env_vars`])
139/// - `~/` prefix: expanded to home directory
140/// - Relative paths: resolved against the config file's parent directory
141/// - Absolute paths: used as-is
142fn resolve_extends_path(extends_value: &str, config_file_path: &Path) -> Result<PathBuf, ConfigError> {
143    let expanded = expand_env_vars(extends_value, |key| std::env::var(key).ok()).map_err(|var| {
144        ConfigError::ExtendsUndefinedVar {
145            var,
146            from: config_file_path.display().to_string(),
147        }
148    })?;
149
150    if let Some(suffix) = expanded.strip_prefix("~/") {
151        // Expand tilde to home directory
152        #[cfg(feature = "native")]
153        {
154            use etcetera::{BaseStrategy, choose_base_strategy};
155            let home = choose_base_strategy().map_or_else(|_| PathBuf::from("~"), |s| s.home_dir().to_path_buf());
156            Ok(home.join(suffix))
157        }
158        #[cfg(not(feature = "native"))]
159        {
160            let _ = suffix;
161            Ok(PathBuf::from(expanded))
162        }
163    } else {
164        let path = PathBuf::from(&expanded);
165        if path.is_absolute() {
166            Ok(path)
167        } else {
168            // Resolve relative to config file's directory
169            let config_dir = config_file_path.parent().unwrap_or(Path::new("."));
170            Ok(config_dir.join(&expanded))
171        }
172    }
173}
174
175/// Determine ConfigSource from a config filename.
176fn source_from_filename(filename: &str) -> ConfigSource {
177    if filename == "pyproject.toml" {
178        ConfigSource::PyprojectToml
179    } else {
180        ConfigSource::ProjectConfig
181    }
182}
183
184/// The rumdl-native config files that actually exist in `dir`, in precedence order.
185///
186/// Walks `RUMDL_CONFIG_FILES` (the single source of truth for discovery) joined onto
187/// `dir`, so `.config/rumdl.toml` is recognised at the same level as `.rumdl.toml`.
188/// `pyproject.toml` counts only when it declares `[tool.rumdl]`. markdownlint configs
189/// are intentionally excluded: they are a separate fallback tier, not a same-tool
190/// collision, and projects routinely keep one around while migrating.
191pub(crate) fn rumdl_configs_in_dir(dir: &Path) -> Vec<PathBuf> {
192    RUMDL_CONFIG_FILES
193        .iter()
194        .map(|name| dir.join(name))
195        .filter(|path| {
196            if !path.exists() {
197                return false;
198            }
199            if path.file_name().and_then(|n| n.to_str()) == Some("pyproject.toml") {
200                std::fs::read_to_string(path).is_ok_and(|content| pyproject_declares_rumdl_config(&content))
201            } else {
202                true
203            }
204        })
205        .collect()
206}
207
208/// A directory holding more than one rumdl-native config file.
209///
210/// `winner` is the file discovery uses (highest precedence); `shadowed` are the
211/// silently-ignored siblings. Having both `.rumdl.toml` and `rumdl.toml` (or either
212/// plus a `[tool.rumdl]` in `pyproject.toml`) in one directory is redundant by
213/// construction and a common footgun: editing the shadowed file appears to do
214/// nothing. Resolution is unchanged (the dot file still wins, matching Ruff); this
215/// type only lets callers surface the collision.
216#[derive(Debug, Clone, PartialEq, Eq)]
217pub(crate) struct ShadowedConfigs {
218    pub dir: PathBuf,
219    pub winner: PathBuf,
220    pub shadowed: Vec<PathBuf>,
221}
222
223/// Detect rumdl-native config files that shadow each other in `dir`.
224///
225/// Returns `None` unless two or more rumdl-native configs coexist at this directory
226/// level (markdownlint files and configs in other directories never count). The
227/// highest-precedence file is the `winner`; the rest are silently `shadowed`.
228pub(crate) fn detect_shadowed_configs(dir: &Path) -> Option<ShadowedConfigs> {
229    let mut configs = rumdl_configs_in_dir(dir);
230    if configs.len() < 2 {
231        return None;
232    }
233    let winner = configs.remove(0);
234    Some(ShadowedConfigs {
235        dir: dir.to_path_buf(),
236        winner,
237        shadowed: configs,
238    })
239}
240
241/// Format a shadowed-config collision as a single user-facing warning line.
242///
243/// The directory is named once; the winner and shadowed files are shown relative
244/// to it (e.g. `.rumdl.toml`, `.config/rumdl.toml`) rather than repeating the full
245/// directory in every path. Paths are normalized to forward slashes on Windows for
246/// stable, copy-pasteable output; non-UTF-8 components degrade lossily rather than
247/// panicking.
248pub(crate) fn format_shadow_warning(shadow: &ShadowedConfigs) -> String {
249    let norm = |s: String| if cfg!(windows) { s.replace('\\', "/") } else { s };
250    let rel = |path: &Path| {
251        let relative = path.strip_prefix(&shadow.dir).unwrap_or(path);
252        norm(relative.to_string_lossy().into_owned())
253    };
254    let shadowed = shadow.shadowed.iter().map(|p| rel(p)).collect::<Vec<_>>().join(", ");
255    format!(
256        "multiple rumdl config files in {}: using {}, ignoring {}",
257        norm(shadow.dir.to_string_lossy().into_owned()),
258        rel(&shadow.winner),
259        shadowed,
260    )
261}
262
263/// Load a config file (and any base configs it extends) into a SourcedConfig.
264///
265/// This function handles the recursive `extends` chain:
266/// 1. Parse the config file into a fragment
267/// 2. If the fragment has `extends`, recursively load the base config first
268/// 3. Merge the base config, then merge this fragment on top
269fn load_config_with_extends(
270    sourced_config: &mut SourcedConfig<ConfigLoaded>,
271    config_file_path: &Path,
272    visited: &mut IndexSet<PathBuf>,
273    chain_source: ConfigSource,
274) -> Result<(), ConfigError> {
275    // Canonicalize the path for circular reference detection
276    let canonical = config_file_path
277        .canonicalize()
278        .unwrap_or_else(|_| config_file_path.to_path_buf());
279
280    // Check for circular references
281    if visited.contains(&canonical) {
282        let chain: Vec<String> = visited.iter().map(|p| p.display().to_string()).collect();
283        return Err(ConfigError::CircularExtends {
284            path: config_file_path.display().to_string(),
285            chain,
286        });
287    }
288
289    // Check depth limit
290    if visited.len() >= MAX_EXTENDS_DEPTH {
291        return Err(ConfigError::ExtendsDepthExceeded {
292            path: config_file_path.display().to_string(),
293            max_depth: MAX_EXTENDS_DEPTH,
294        });
295    }
296
297    // Mark as visited
298    visited.insert(canonical);
299
300    let path_str = config_file_path.display().to_string();
301    let filename = config_file_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
302
303    // Read and parse the config file
304    let content = std::fs::read_to_string(config_file_path).map_err(|e| ConfigError::IoError {
305        source: e,
306        path: path_str.clone(),
307    })?;
308
309    let fragment = if filename == "pyproject.toml" {
310        match parsers::parse_pyproject_toml(&content, &path_str, chain_source)? {
311            Some(f) => f,
312            None => return Ok(()), // No [tool.rumdl] section
313        }
314    } else {
315        parsers::parse_rumdl_toml(&content, &path_str, chain_source)?
316    };
317
318    // If this fragment has `extends`, load the base config first
319    if let Some(ref extends_value) = fragment.extends {
320        let base_path = resolve_extends_path(extends_value, config_file_path)?;
321
322        if !base_path.exists() {
323            return Err(ConfigError::ExtendsNotFound {
324                path: base_path.display().to_string(),
325                from: path_str.clone(),
326            });
327        }
328
329        log::debug!(
330            "[rumdl-config] Config {} extends {}, loading base first",
331            path_str,
332            base_path.display()
333        );
334
335        // Recursively load the base config
336        load_config_with_extends(sourced_config, &base_path, visited, chain_source)?;
337    }
338
339    // Merge this fragment on top (base config was already merged if present)
340    // Strip the `extends` field since it's been consumed
341    let mut fragment_for_merge = fragment;
342    fragment_for_merge.extends = None;
343    sourced_config.merge(fragment_for_merge);
344    sourced_config.loaded_files.push(path_str);
345
346    Ok(())
347}
348
349impl SourcedConfig<ConfigLoaded> {
350    /// Merges another SourcedConfigFragment into this SourcedConfig.
351    /// Uses source precedence to determine which values take effect.
352    pub(super) fn merge(&mut self, fragment: SourcedConfigFragment) {
353        // Merge global config. Enable/disable use replace semantics (child
354        // config overrides parent, matching Ruff's `select`/`ignore`);
355        // extend-enable/extend-disable use union semantics (additive across
356        // config levels).
357        self.global.enable.merge_from(fragment.global.enable);
358        self.global.disable.merge_from(fragment.global.disable);
359        self.global
360            .extend_enable
361            .merge_union_from(fragment.global.extend_enable);
362        self.global
363            .extend_disable
364            .merge_union_from(fragment.global.extend_disable);
365
366        // Conflict resolution: Enable overrides disable
367        // Remove any rules from disable that appear in enable
368        self.global
369            .disable
370            .value
371            .retain(|rule| !self.global.enable.value.contains(rule));
372
373        self.global.include.merge_from(fragment.global.include);
374        self.global.exclude.merge_from(fragment.global.exclude);
375        self.global
376            .respect_gitignore
377            .merge_from(fragment.global.respect_gitignore);
378        self.global.line_length.merge_from(fragment.global.line_length);
379        self.global.fixable.merge_from(fragment.global.fixable);
380        self.global.unfixable.merge_from(fragment.global.unfixable);
381        self.global.flavor.merge_from(fragment.global.flavor);
382        self.global.force_exclude.merge_from(fragment.global.force_exclude);
383        self.global.editorconfig.merge_from(fragment.global.editorconfig);
384
385        // Merge output_format if present
386        if let Some(output_format_fragment) = fragment.global.output_format {
387            if let Some(ref mut output_format) = self.global.output_format {
388                output_format.merge_from(output_format_fragment);
389            } else {
390                self.global.output_format = Some(output_format_fragment);
391            }
392        }
393
394        // Merge cache_dir if present
395        if let Some(cache_dir_fragment) = fragment.global.cache_dir {
396            if let Some(ref mut cache_dir) = self.global.cache_dir {
397                cache_dir.merge_from(cache_dir_fragment);
398            } else {
399                self.global.cache_dir = Some(cache_dir_fragment);
400            }
401        }
402
403        // Merge cache if not default (only override when explicitly set)
404        if fragment.global.cache.source != ConfigSource::Default {
405            self.global.cache.merge_from(fragment.global.cache);
406        }
407
408        self.per_file_ignores.merge_from(fragment.per_file_ignores);
409        self.per_file_flavor.merge_from(fragment.per_file_flavor);
410        self.code_block_tools.merge_from(fragment.code_block_tools);
411
412        // Merge rule configs
413        for (rule_name, rule_fragment) in fragment.rules {
414            let norm_rule_name = rule_name.to_ascii_uppercase(); // Normalize to uppercase for case-insensitivity
415            let rule_entry = self.rules.entry(norm_rule_name).or_default();
416
417            // Merge severity if present in fragment
418            if let Some(severity_fragment) = rule_fragment.severity {
419                if let Some(ref mut existing_severity) = rule_entry.severity {
420                    existing_severity.merge_from(severity_fragment);
421                } else {
422                    rule_entry.severity = Some(severity_fragment);
423                }
424            }
425
426            // Merge values
427            for (key, sourced_value_fragment) in rule_fragment.values {
428                let sv_entry = rule_entry
429                    .values
430                    .entry(key.clone())
431                    .or_insert_with(|| SourcedValue::new(sourced_value_fragment.value.clone(), ConfigSource::Default));
432                sv_entry.merge_from(sourced_value_fragment);
433            }
434        }
435
436        // Merge unknown_keys from fragment
437        for (section, key, file_path) in fragment.unknown_keys {
438            // Deduplicate: only add if not already present
439            if !self.unknown_keys.iter().any(|(s, k, _)| s == &section && k == &key) {
440                self.unknown_keys.push((section, key, file_path));
441            }
442        }
443    }
444
445    /// Load and merge configurations from files and CLI overrides.
446    pub fn load(config_path: Option<&str>, cli_overrides: Option<&SourcedGlobalConfig>) -> Result<Self, ConfigError> {
447        Self::load_with_discovery(config_path, cli_overrides, false)
448    }
449
450    /// Finds project root by walking up from start_dir looking for .git directory.
451    /// Falls back to start_dir if no .git found.
452    fn find_project_root_from(start_dir: &Path) -> std::path::PathBuf {
453        UpwardWalk::new(start_dir)
454            .find(|dir| dir.join(".git").exists())
455            .unwrap_or_else(|| {
456                log::debug!(
457                    "[rumdl-config] No .git found, using config location as project root: {}",
458                    start_dir.display()
459                );
460                start_dir.to_path_buf()
461            })
462    }
463
464    /// Resolve the home-directory boundary used to stop project-config discovery.
465    ///
466    /// `home_override` wins (supplied by tests); otherwise the real home is resolved on
467    /// native builds via `etcetera`. Wasm has no home/project walk to bound, so it
468    /// returns `None` there.
469    fn resolve_home_boundary(home_override: Option<&Path>) -> Option<std::path::PathBuf> {
470        home_override.map(Path::to_path_buf).or_else(|| {
471            #[cfg(feature = "native")]
472            {
473                use etcetera::{BaseStrategy, choose_base_strategy};
474                choose_base_strategy().ok().map(|s| s.home_dir().to_path_buf())
475            }
476            #[cfg(not(feature = "native"))]
477            {
478                None
479            }
480        })
481    }
482
483    /// Discover configuration file by traversing up the directory tree.
484    /// Returns the first configuration file found.
485    /// Discovers config file and returns both the config path and project root.
486    /// Returns: (config_file_path, project_root_path)
487    /// Project root is the directory containing .git, or config parent as fallback.
488    ///
489    /// The walk stops at the home directory: a config file located in `$HOME`
490    /// itself is user-level, not a project config, and must reach the loader only
491    /// through the user-config fallback (`load_user_config`) so the platform
492    /// user-config directory keeps precedence over `~/.rumdl.toml`. The cwd is
493    /// exempt from that boundary: it is an explicitly chosen project context, so
494    /// its configs apply even when the cwd *is* `$HOME` (pre-commit.ci sets `HOME`
495    /// to the git checkout, and `pyproject.toml` has no user-config fallback).
496    /// `home_override` supplies the boundary for tests; production resolves the
497    /// real home directory.
498    fn discover_config_upward(
499        home_override: Option<&Path>,
500    ) -> Option<(std::path::PathBuf, std::path::PathBuf, Option<ShadowedConfigs>)> {
501        let start_dir = match std::env::current_dir() {
502            Ok(dir) => dir,
503            Err(e) => {
504                log::debug!("[rumdl-config] Failed to get current directory: {e}");
505                return None;
506            }
507        };
508
509        // `rumdl_configs_in_dir` is the single source of truth for "which rumdl
510        // configs live here", shared with the LSP and the shadow detector, so the
511        // winner and the silently-shadowed siblings are computed identically.
512        let (config_path, config_dir, shadow) = UpwardWalk::new(&start_dir)
513            .stop_below(Self::resolve_home_boundary(home_override))
514            .always_yield_start()
515            .stop_at_git_root()
516            .find_map(|dir| {
517                rumdl_configs_in_dir(&dir).into_iter().next().map(|winner| {
518                    log::debug!("[rumdl-config] Found config file: {}", winner.display());
519                    let shadow = detect_shadowed_configs(&dir);
520                    (winner, dir, shadow)
521                })
522            })?;
523
524        // Determine project root by walking up from the config location.
525        let project_root = Self::find_project_root_from(&config_dir);
526        Some((config_path, project_root, shadow))
527    }
528
529    /// Discover markdownlint configuration file by traversing up the directory tree.
530    /// Similar to discover_config_upward but for .markdownlint.yaml/json files, and
531    /// bounded at the home directory for the same reason: a markdownlint config in
532    /// `$HOME` is user-level, not a project config. The cwd is exempt from the
533    /// boundary just like rumdl config discovery, and markdownlint files have no
534    /// user-config fallback at all, so without the exemption a config in a
535    /// `HOME == cwd` checkout would be ignored entirely.
536    fn discover_markdownlint_config_upward(home_override: Option<&Path>) -> Option<std::path::PathBuf> {
537        let start_dir = match std::env::current_dir() {
538            Ok(dir) => dir,
539            Err(e) => {
540                log::debug!("[rumdl-config] Failed to get current directory for markdownlint discovery: {e}");
541                return None;
542            }
543        };
544
545        UpwardWalk::new(&start_dir)
546            .stop_below(Self::resolve_home_boundary(home_override))
547            .always_yield_start()
548            .stop_at_git_root()
549            .find_map(|dir| {
550                MARKDOWNLINT_CONFIG_FILES
551                    .iter()
552                    .map(|name| dir.join(name))
553                    .find(|path| path.exists())
554            })
555    }
556
557    /// Internal implementation that accepts config directory for testing
558    fn user_configuration_path_impl(config_dir: &Path) -> Option<std::path::PathBuf> {
559        let config_dir = config_dir.join("rumdl");
560
561        // Check for config files in precedence order (same as project discovery)
562        const USER_CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml", "pyproject.toml"];
563
564        log::debug!(
565            "[rumdl-config] Checking for user configuration in: {}",
566            config_dir.display()
567        );
568
569        for filename in USER_CONFIG_FILES {
570            let config_path = config_dir.join(filename);
571
572            if config_path.exists() {
573                // For pyproject.toml, verify it contains [tool.rumdl] section
574                if *filename == "pyproject.toml" {
575                    if let Ok(content) = std::fs::read_to_string(&config_path) {
576                        if pyproject_declares_rumdl_config(&content) {
577                            log::debug!("[rumdl-config] Found user configuration at: {}", config_path.display());
578                            return Some(config_path);
579                        }
580                        log::debug!("[rumdl-config] Found user pyproject.toml but no [tool.rumdl] section");
581                        continue;
582                    }
583                } else {
584                    log::debug!("[rumdl-config] Found user configuration at: {}", config_path.display());
585                    return Some(config_path);
586                }
587            }
588        }
589
590        log::debug!(
591            "[rumdl-config] No user configuration found in: {}",
592            config_dir.display()
593        );
594        None
595    }
596
597    /// Discover user-level configuration file from platform-specific config directory.
598    /// Returns the first configuration file found in the user config directory.
599    #[cfg(feature = "native")]
600    fn user_configuration_path() -> Option<std::path::PathBuf> {
601        use etcetera::{BaseStrategy, choose_base_strategy};
602
603        match choose_base_strategy() {
604            Ok(strategy) => {
605                let config_dir = strategy.config_dir();
606                Self::user_configuration_path_impl(&config_dir)
607            }
608            Err(e) => {
609                log::debug!("[rumdl-config] Failed to determine user config directory: {e}");
610                None
611            }
612        }
613    }
614
615    /// Stub for WASM builds - user config not supported
616    #[cfg(not(feature = "native"))]
617    fn user_configuration_path() -> Option<std::path::PathBuf> {
618        None
619    }
620
621    /// Internal implementation that accepts the home directory for testing.
622    ///
623    /// Probes `<home>/.rumdl.toml` then `<home>/rumdl.toml`, returning the first match.
624    ///
625    /// `pyproject.toml` is intentionally **not** searched in `$HOME`, even though
626    /// `user_configuration_path_impl` does check it inside the platform config dir.
627    /// The asymmetry is deliberate: a `pyproject.toml` directly in `$HOME` almost
628    /// always belongs to unrelated python tooling (poetry/uv/pip's user-level config),
629    /// and silently picking it up as a rumdl config would surprise users. The
630    /// platform config dir (`~/.config/rumdl/`) is rumdl-scoped, so the same
631    /// concern doesn't apply there.
632    fn home_configuration_path_impl(home_dir: &Path) -> Option<std::path::PathBuf> {
633        const HOME_CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml"];
634
635        log::debug!(
636            "[rumdl-config] Checking for home-directory configuration in: {}",
637            home_dir.display()
638        );
639
640        for filename in HOME_CONFIG_FILES {
641            let config_path = home_dir.join(filename);
642            if config_path.exists() {
643                log::debug!(
644                    "[rumdl-config] Found home-directory configuration at: {}",
645                    config_path.display()
646                );
647                return Some(config_path);
648            }
649        }
650
651        log::debug!(
652            "[rumdl-config] No home-directory configuration found in: {}",
653            home_dir.display()
654        );
655        None
656    }
657
658    /// Discover a home-directory configuration file (`~/.rumdl.toml` or `~/rumdl.toml`).
659    ///
660    /// This is a final fallback after the platform user-config directory
661    /// (`user_configuration_path`). It honors the classic Unix dotfile convention so
662    /// users who keep tool config in `$HOME` rather than `$XDG_CONFIG_HOME` are picked up.
663    #[cfg(feature = "native")]
664    fn home_configuration_path() -> Option<std::path::PathBuf> {
665        use etcetera::{BaseStrategy, choose_base_strategy};
666
667        match choose_base_strategy() {
668            Ok(strategy) => Self::home_configuration_path_impl(strategy.home_dir()),
669            Err(e) => {
670                log::debug!("[rumdl-config] Failed to determine home directory: {e}");
671                None
672            }
673        }
674    }
675
676    /// Stub for WASM builds - home config not supported
677    #[cfg(not(feature = "native"))]
678    fn home_configuration_path() -> Option<std::path::PathBuf> {
679        None
680    }
681
682    /// Load an explicit config file (standalone, no user config merging)
683    fn load_explicit_config(sourced_config: &mut Self, path: &str) -> Result<(), ConfigError> {
684        let path_obj = Path::new(path);
685        let filename = path_obj.file_name().and_then(|name| name.to_str()).unwrap_or("");
686        let path_str = path.to_string();
687
688        log::debug!("[rumdl-config] Loading explicit config file: {filename}");
689
690        // Find project root by walking up from config location looking for .git
691        if let Some(config_parent) = path_obj.parent() {
692            let project_root = Self::find_project_root_from(config_parent);
693            log::debug!(
694                "[rumdl-config] Project root (from explicit config): {}",
695                project_root.display()
696            );
697            sourced_config.project_root = Some(project_root);
698        }
699
700        // Known markdownlint config files
701        const MARKDOWNLINT_FILENAMES: &[&str] = &[
702            ".markdownlint-cli2.jsonc",
703            ".markdownlint-cli2.yaml",
704            ".markdownlint-cli2.yml",
705            ".markdownlint.json",
706            ".markdownlint.yaml",
707            ".markdownlint.yml",
708        ];
709
710        if filename == "pyproject.toml" || filename == ".rumdl.toml" || filename == "rumdl.toml" {
711            // Use extends-aware loading for rumdl TOML configs
712            let mut visited = IndexSet::new();
713            let chain_source = source_from_filename(filename);
714            load_config_with_extends(sourced_config, path_obj, &mut visited, chain_source)?;
715        } else if MARKDOWNLINT_FILENAMES.contains(&filename)
716            || path_str.ends_with(".json")
717            || path_str.ends_with(".jsonc")
718            || path_str.ends_with(".yaml")
719            || path_str.ends_with(".yml")
720        {
721            // Parse as markdownlint config (JSON/YAML) - no extends support
722            let fragment = parsers::load_from_markdownlint(&path_str)?;
723            sourced_config.merge(fragment);
724            sourced_config.loaded_files.push(path_str);
725        } else {
726            // Try TOML with extends support
727            let mut visited = IndexSet::new();
728            let chain_source = source_from_filename(filename);
729            load_config_with_extends(sourced_config, path_obj, &mut visited, chain_source)?;
730        }
731
732        Ok(())
733    }
734
735    /// Load and merge user-level configuration into this `SourcedConfig`.
736    ///
737    /// Discovers the user config file in this order, taking the first match:
738    /// 1. Platform user-config directory, resolved via `etcetera::choose_base_strategy`
739    ///    (the CLI/XDG convention): `~/.config` on Linux and macOS, `%APPDATA%` on
740    ///    Windows. Note macOS uses the XDG-style `~/.config`, not the GUI-app location
741    ///    `~/Library/Application Support`. Override with `user_config_dir` for tests.
742    /// 2. Home-directory dotfile (`~/.rumdl.toml`, then `~/rumdl.toml`). Override with
743    ///    `home_dir` for tests. Honors the classic Unix dotfile convention.
744    ///
745    /// Resolves any `extends` chain and merges each fragment with
746    /// `ConfigSource::UserConfig` precedence.
747    ///
748    /// Called in two contexts:
749    /// - When no project config is found: provides user defaults as the sole base
750    /// - When a markdownlint project config is found: provides rumdl-specific
751    ///   defaults that the markdownlint format cannot express; the markdownlint
752    ///   fragment is merged on top and wins on any overlapping key
753    fn load_user_config(
754        sourced_config: &mut Self,
755        user_config_dir: Option<&Path>,
756        home_dir: Option<&Path>,
757    ) -> Result<(), ConfigError> {
758        let user_config_path = if let Some(dir) = user_config_dir {
759            Self::user_configuration_path_impl(dir)
760        } else {
761            Self::user_configuration_path()
762        };
763
764        let user_config_path = user_config_path.or_else(|| match home_dir {
765            Some(home) => Self::home_configuration_path_impl(home),
766            None => Self::home_configuration_path(),
767        });
768
769        if let Some(user_config_path) = user_config_path {
770            let path_str = user_config_path.display().to_string();
771
772            log::debug!("[rumdl-config] Loading user config: {path_str}");
773
774            // User config fallback also supports extends chains.
775            // Use a uniform source across the chain so child overrides are determined by chain order.
776            let mut visited = IndexSet::new();
777            load_config_with_extends(
778                sourced_config,
779                &user_config_path,
780                &mut visited,
781                ConfigSource::UserConfig,
782            )?;
783        } else {
784            log::debug!("[rumdl-config] No user configuration file found");
785        }
786
787        Ok(())
788    }
789
790    /// Load a project config file that discovery found, as opposed to one the user
791    /// named explicitly.
792    ///
793    /// The two are not interchangeable. An explicit config is standalone by design
794    /// (`load_explicit_config`), and so is a discovered rumdl-native config: a
795    /// project's ruleset has to be reproducible on any machine. A discovered
796    /// *markdownlint* config is the exception. That format cannot express
797    /// rumdl-specific settings (flavor, cache, per-file ignores), so the user config
798    /// is loaded first as a base and the markdownlint fragment merged on top. The
799    /// fragment carries `ConfigSource::ProjectConfig` (precedence 3) against the
800    /// base's `ConfigSource::UserConfig` (1), so project settings still win on every
801    /// overlapping key.
802    ///
803    /// Both the CLI (`load_with_discovery_impl`) and the LSP (`load_discovered`,
804    /// via `RumdlLanguageServer::resolve_config_for_file`) load discovered files
805    /// through here, so a discovered config resolves the same way in an editor as
806    /// it does on the command line.
807    fn load_discovered_config(
808        sourced_config: &mut Self,
809        config_file: &Path,
810        user_config_dir: Option<&Path>,
811        home_dir: Option<&Path>,
812    ) -> Result<(), DiscoveredConfigError> {
813        let filename = config_file.file_name().and_then(|name| name.to_str()).unwrap_or("");
814
815        if MARKDOWNLINT_CONFIG_FILES.contains(&filename) {
816            Self::load_user_config(sourced_config, user_config_dir, home_dir)
817                .map_err(DiscoveredConfigError::UserConfig)?;
818
819            let path_str = config_file.display().to_string();
820            let fragment = parsers::load_from_markdownlint(&path_str).map_err(DiscoveredConfigError::ProjectConfig)?;
821            sourced_config.merge(fragment);
822            sourced_config.loaded_files.push(path_str);
823        } else {
824            let mut visited = IndexSet::new();
825            let chain_source = source_from_filename(filename);
826            load_config_with_extends(sourced_config, config_file, &mut visited, chain_source)
827                .map_err(DiscoveredConfigError::ProjectConfig)?;
828        }
829
830        Ok(())
831    }
832
833    /// Load a config file that the caller discovered by walking the tree itself.
834    ///
835    /// The LSP cannot use `load_with_discovery`: that walk starts at the process
836    /// working directory, while the server resolves a config per document and stops
837    /// at the workspace root. It finds the file with its own walk and hands it here,
838    /// so the discovered-config rules in `load_discovered_config` still apply.
839    ///
840    /// `project_root` comes from the config file's own location, which is what
841    /// per-file ignore globs are matched against.
842    ///
843    /// `user_config_dir` and `home_dir` override the platform user-config directory
844    /// and the home directory; the server passes the home directory it already
845    /// resolved for its walk boundary, and tests pass both.
846    ///
847    /// The error distinguishes an unusable discovered file from an unusable user
848    /// config so a caller walking several candidates can tell "try the next one"
849    /// from "nothing here will resolve correctly".
850    pub fn load_discovered(
851        config_file: &Path,
852        user_config_dir: Option<&Path>,
853        home_dir: Option<&Path>,
854    ) -> Result<Self, DiscoveredConfigError> {
855        let mut sourced_config = SourcedConfig::default();
856
857        if let Some(config_parent) = config_file.parent() {
858            sourced_config.project_root = Some(Self::find_project_root_from(config_parent));
859        }
860
861        Self::load_discovered_config(&mut sourced_config, config_file, user_config_dir, home_dir)?;
862
863        Ok(sourced_config)
864    }
865
866    /// Internal implementation that accepts user config directory and home directory for testing
867    #[doc(hidden)]
868    pub fn load_with_discovery_impl(
869        config_path: Option<&str>,
870        cli_overrides: Option<&SourcedGlobalConfig>,
871        skip_auto_discovery: bool,
872        user_config_dir: Option<&Path>,
873        home_dir: Option<&Path>,
874    ) -> Result<Self, ConfigError> {
875        use std::env;
876        log::debug!("[rumdl-config] Current working directory: {:?}", env::current_dir());
877
878        let mut sourced_config = SourcedConfig::default();
879
880        // Ruff model: Project config is standalone, user config is fallback only
881        //
882        // Priority order:
883        // 1. If explicit config path provided → use ONLY that (standalone)
884        // 2. Else if project config discovered → use ONLY that (standalone)
885        // 3. Else if user config exists → use it as fallback
886        // 4. CLI overrides always apply last
887        //
888        // This ensures project configs are reproducible across machines and
889        // CI/local runs behave identically.
890
891        // Explicit config path always takes precedence
892        if let Some(path) = config_path {
893            // Explicit config path provided - use ONLY this config (standalone)
894            log::debug!("[rumdl-config] Explicit config_path provided: {path:?}");
895            Self::load_explicit_config(&mut sourced_config, path)?;
896        } else if skip_auto_discovery {
897            log::debug!("[rumdl-config] Skipping config discovery due to --no-config/--isolated flag");
898            // No config loading, just apply CLI overrides at the end
899        } else {
900            // No explicit path - try auto-discovery
901            log::debug!("[rumdl-config] No explicit config_path, searching default locations");
902
903            // Try to discover project config first
904            if let Some((config_file, project_root, shadow)) = Self::discover_config_upward(home_dir) {
905                // Project config found - use ONLY this (standalone, no user config).
906                // Rumdl project configs can express all settings directly, so user config
907                // is not needed and omitting it ensures CI and local runs are identical.
908                log::debug!("[rumdl-config] Found project config: {}", config_file.display());
909                log::debug!("[rumdl-config] Project root: {}", project_root.display());
910
911                // Record any same-directory sibling configs that are silently shadowed,
912                // so the CLI and LSP can warn the user. Resolution is unchanged.
913                if let Some(shadow) = shadow {
914                    sourced_config.discovery_warnings.push(format_shadow_warning(&shadow));
915                }
916
917                sourced_config.project_root = Some(project_root);
918
919                Self::load_discovered_config(&mut sourced_config, &config_file, user_config_dir, home_dir)?;
920            } else {
921                // No rumdl project config - try markdownlint config
922                log::debug!("[rumdl-config] No rumdl config found, checking markdownlint config");
923
924                if let Some(markdownlint_path) = Self::discover_markdownlint_config_upward(home_dir) {
925                    log::debug!(
926                        "[rumdl-config] Found markdownlint config: {}",
927                        markdownlint_path.display()
928                    );
929
930                    if let Err(e) =
931                        Self::load_discovered_config(&mut sourced_config, &markdownlint_path, user_config_dir, home_dir)
932                    {
933                        match e {
934                            // A markdownlint file rumdl cannot parse is skipped rather
935                            // than fatal: the user never named it, and rumdl only reads
936                            // the format as a courtesy. The user config it would have
937                            // merged onto is already loaded, which is the state of the
938                            // no-project-config case.
939                            DiscoveredConfigError::ProjectConfig(e) => {
940                                log::debug!("[rumdl-config] Failed to load markdownlint config: {e}");
941                            }
942                            // A broken user config is fatal, as in every other arm.
943                            DiscoveredConfigError::UserConfig(e) => return Err(e),
944                        }
945                    }
946                } else {
947                    // No project config at all - use user config as fallback
948                    log::debug!("[rumdl-config] No project config found, using user config as fallback");
949                    Self::load_user_config(&mut sourced_config, user_config_dir, home_dir)?;
950                }
951            }
952        }
953
954        // Apply CLI overrides (highest precedence)
955        if let Some(cli) = cli_overrides {
956            sourced_config
957                .global
958                .enable
959                .merge_override(cli.enable.value.clone(), ConfigSource::Cli, None);
960            sourced_config
961                .global
962                .disable
963                .merge_override(cli.disable.value.clone(), ConfigSource::Cli, None);
964            sourced_config
965                .global
966                .exclude
967                .merge_override(cli.exclude.value.clone(), ConfigSource::Cli, None);
968            sourced_config
969                .global
970                .include
971                .merge_override(cli.include.value.clone(), ConfigSource::Cli, None);
972            sourced_config.global.respect_gitignore.merge_override(
973                cli.respect_gitignore.value,
974                ConfigSource::Cli,
975                None,
976            );
977            sourced_config
978                .global
979                .fixable
980                .merge_override(cli.fixable.value.clone(), ConfigSource::Cli, None);
981            sourced_config
982                .global
983                .unfixable
984                .merge_override(cli.unfixable.value.clone(), ConfigSource::Cli, None);
985            // No rule-specific CLI overrides implemented yet
986        }
987
988        // Unknown keys are now collected during parsing and validated via validate_config_sourced()
989
990        Ok(sourced_config)
991    }
992
993    /// Load and merge configurations from files and CLI overrides.
994    /// If skip_auto_discovery is true, only explicit config paths are loaded.
995    pub fn load_with_discovery(
996        config_path: Option<&str>,
997        cli_overrides: Option<&SourcedGlobalConfig>,
998        skip_auto_discovery: bool,
999    ) -> Result<Self, ConfigError> {
1000        Self::load_with_discovery_impl(config_path, cli_overrides, skip_auto_discovery, None, None)
1001    }
1002
1003    /// Validate the configuration against a rule registry.
1004    ///
1005    /// This method transitions the config from `ConfigLoaded` to `ConfigValidated` state,
1006    /// enabling conversion to `Config`. Validation warnings are stored in the config
1007    /// and can be displayed to the user.
1008    ///
1009    /// # Example
1010    ///
1011    /// ```ignore
1012    /// let loaded = SourcedConfig::load_with_discovery(path, None, false)?;
1013    /// let validated = loaded.validate(&registry)?;
1014    /// let config: Config = validated.into();
1015    /// ```
1016    pub fn validate(self, registry: &RuleRegistry) -> Result<SourcedConfig<ConfigValidated>, ConfigError> {
1017        let warnings = validate_config_sourced_internal(&self, registry);
1018
1019        Ok(SourcedConfig {
1020            global: self.global,
1021            per_file_ignores: self.per_file_ignores,
1022            per_file_flavor: self.per_file_flavor,
1023            code_block_tools: self.code_block_tools,
1024            rules: self.rules,
1025            loaded_files: self.loaded_files,
1026            unknown_keys: self.unknown_keys,
1027            project_root: self.project_root,
1028            discovery_warnings: self.discovery_warnings,
1029            validation_warnings: warnings,
1030            _state: PhantomData,
1031        })
1032    }
1033
1034    /// Validate and convert to Config in one step (convenience method).
1035    ///
1036    /// This combines `validate()` and `into()` for callers who want the
1037    /// validation warnings separately.
1038    pub fn validate_into(self, registry: &RuleRegistry) -> Result<(Config, Vec<ConfigValidationWarning>), ConfigError> {
1039        let validated = self.validate(registry)?;
1040        let warnings = validated.validation_warnings.clone();
1041        Ok((validated.into(), warnings))
1042    }
1043
1044    /// Skip validation and convert directly to ConfigValidated state.
1045    ///
1046    /// # Safety
1047    ///
1048    /// This method bypasses validation. Use only when:
1049    /// - You've already validated via `validate_config_sourced()`
1050    /// - You're in test code that doesn't need validation
1051    /// - You're migrating legacy code and will add proper validation later
1052    ///
1053    /// Prefer `validate()` for new code.
1054    pub fn into_validated_unchecked(self) -> SourcedConfig<ConfigValidated> {
1055        SourcedConfig {
1056            global: self.global,
1057            per_file_ignores: self.per_file_ignores,
1058            per_file_flavor: self.per_file_flavor,
1059            code_block_tools: self.code_block_tools,
1060            rules: self.rules,
1061            loaded_files: self.loaded_files,
1062            unknown_keys: self.unknown_keys,
1063            project_root: self.project_root,
1064            discovery_warnings: self.discovery_warnings,
1065            validation_warnings: Vec::new(),
1066            _state: PhantomData,
1067        }
1068    }
1069
1070    /// Discover the nearest config file for a specific directory,
1071    /// walking upward to `project_root` (inclusive).
1072    ///
1073    /// Searches for rumdl config files (`.rumdl.toml`, `rumdl.toml`,
1074    /// `.config/rumdl.toml`, `pyproject.toml` with `[tool.rumdl]`) and
1075    /// markdownlint config files at each directory level.
1076    ///
1077    /// Returns the config file path if found. Does NOT use CWD.
1078    pub fn discover_config_for_dir(dir: &Path, project_root: &Path) -> Option<PathBuf> {
1079        // The walk never canonicalizes the directories it yields (symlinks and
1080        // Windows short names stay as the caller wrote them); only the stop
1081        // checks inside `UpwardWalk` compare canonically. A relative `dir` is
1082        // resolved against the current directory, so the returned config path
1083        // is always absolute.
1084        //
1085        // The home boundary keeps the walk from treating `~/.rumdl.toml` as a
1086        // project config, consistent with `discover_config_upward`. This only has
1087        // an effect when `project_root` is at or above the home directory (e.g. a
1088        // multi-path run whose grouping root spans the home boundary); for the
1089        // usual project root below home the walk stops there first.
1090        UpwardWalk::new(dir)
1091            .stop_below(Self::resolve_home_boundary(None))
1092            .stop_at(project_root)
1093            .find_map(|current| {
1094                // Check rumdl config files first (higher precedence)
1095                for config_name in RUMDL_CONFIG_FILES {
1096                    let config_path = current.join(config_name);
1097                    if config_path.exists() {
1098                        if *config_name == "pyproject.toml" {
1099                            if let Ok(content) = std::fs::read_to_string(&config_path)
1100                                && pyproject_declares_rumdl_config(&content)
1101                            {
1102                                return Some(config_path);
1103                            }
1104                            continue;
1105                        }
1106                        return Some(config_path);
1107                    }
1108                }
1109
1110                // Check markdownlint config files (lower precedence)
1111                MARKDOWNLINT_CONFIG_FILES
1112                    .iter()
1113                    .map(|name| current.join(name))
1114                    .find(|path| path.exists())
1115            })
1116    }
1117
1118    /// Load a config from a specific file path, with extends resolution, returning
1119    /// the still-`Loaded` `SourcedConfig` (before validation and conversion).
1120    ///
1121    /// Used by per-directory resolution so the caller can layer CLI-level overrides
1122    /// (e.g. inline `--config`) on top before converting to `Config`, matching the
1123    /// precedence applied to the global config.
1124    pub fn load_sourced_for_path(
1125        config_path: &Path,
1126        project_root: &Path,
1127    ) -> Result<SourcedConfig<ConfigLoaded>, ConfigError> {
1128        let mut sourced_config = SourcedConfig {
1129            project_root: Some(project_root.to_path_buf()),
1130            ..SourcedConfig::default()
1131        };
1132
1133        let filename = config_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
1134        let path_str = config_path.display().to_string();
1135
1136        // Determine if this is a markdownlint config or rumdl config
1137        let is_markdownlint = MARKDOWNLINT_CONFIG_FILES.contains(&filename)
1138            || (filename != "pyproject.toml"
1139                && filename != ".rumdl.toml"
1140                && filename != "rumdl.toml"
1141                && (path_str.ends_with(".json")
1142                    || path_str.ends_with(".jsonc")
1143                    || path_str.ends_with(".yaml")
1144                    || path_str.ends_with(".yml")));
1145
1146        if is_markdownlint {
1147            let fragment = parsers::load_from_markdownlint(&path_str)?;
1148            sourced_config.merge(fragment);
1149            sourced_config.loaded_files.push(path_str);
1150        } else {
1151            let mut visited = IndexSet::new();
1152            let chain_source = source_from_filename(filename);
1153            load_config_with_extends(&mut sourced_config, config_path, &mut visited, chain_source)?;
1154        }
1155
1156        Ok(sourced_config)
1157    }
1158
1159    /// Load a config from a specific file path, with extends resolution, and convert
1160    /// to `Config`. Used for per-directory config loading where each subdirectory
1161    /// config is standalone.
1162    pub fn load_config_for_path(config_path: &Path, project_root: &Path) -> Result<Config, ConfigError> {
1163        Ok(Self::load_sourced_for_path(config_path, project_root)?
1164            .into_validated_unchecked()
1165            .into())
1166    }
1167}
1168
1169/// Convert a validated configuration to the final Config type.
1170///
1171/// This implementation only exists for `SourcedConfig<ConfigValidated>`,
1172/// ensuring that validation must occur before conversion.
1173impl From<SourcedConfig<ConfigValidated>> for Config {
1174    fn from(sourced: SourcedConfig<ConfigValidated>) -> Self {
1175        let mut rules = BTreeMap::new();
1176        for (rule_name, sourced_rule_cfg) in sourced.rules {
1177            // Normalize rule name to uppercase for case-insensitive lookup
1178            let normalized_rule_name = rule_name.to_ascii_uppercase();
1179            let severity = sourced_rule_cfg.severity.map(|sv| sv.value);
1180            let mut values = BTreeMap::new();
1181            for (key, sourced_val) in sourced_rule_cfg.values {
1182                values.insert(key, sourced_val.value);
1183            }
1184            rules.insert(normalized_rule_name, RuleConfig { severity, values });
1185        }
1186        // Enable is "explicit" if it was set by something other than the Default source
1187        let enable_is_explicit = sourced.global.enable.source != ConfigSource::Default;
1188
1189        #[allow(deprecated)]
1190        let global = GlobalConfig {
1191            enable: sourced.global.enable.value,
1192            disable: sourced.global.disable.value,
1193            exclude: sourced.global.exclude.value,
1194            include: sourced.global.include.value,
1195            respect_gitignore: sourced.global.respect_gitignore.value,
1196            line_length: sourced.global.line_length.value,
1197            output_format: sourced.global.output_format.as_ref().map(|v| v.value.clone()),
1198            fixable: sourced.global.fixable.value,
1199            unfixable: sourced.global.unfixable.value,
1200            flavor: sourced.global.flavor.value,
1201            force_exclude: sourced.global.force_exclude.value,
1202            cache_dir: sourced.global.cache_dir.as_ref().map(|v| v.value.clone()),
1203            cache: sourced.global.cache.value,
1204            extend_enable: sourced.global.extend_enable.value,
1205            extend_disable: sourced.global.extend_disable.value,
1206            editorconfig: sourced.global.editorconfig.value,
1207            enable_is_explicit,
1208        };
1209
1210        let mut config = Config {
1211            extends: None,
1212            global,
1213            per_file_ignores: sourced.per_file_ignores.value,
1214            per_file_flavor: sourced.per_file_flavor.value,
1215            code_block_tools: sourced.code_block_tools.value,
1216            rules,
1217            project_root: sourced.project_root,
1218            per_file_ignores_cache: Arc::new(OnceLock::new()),
1219            per_file_flavor_cache: Arc::new(OnceLock::new()),
1220            canonical_project_root_cache: Arc::new(OnceLock::new()),
1221        };
1222
1223        // Apply per-rule `enabled = true/false` to global enable/disable lists
1224        config.apply_per_rule_enabled();
1225
1226        // Enforce the runtime invariant: every rule-name list is canonicalised.
1227        // After this point, downstream consumers (`rules::filter_rules`, the LSP,
1228        // WASM, fix coordinator, per-file-ignores) can match against
1229        // `Rule::name()` with simple string equality regardless of whether the
1230        // user's config used canonical IDs (`"MD033"`) or aliases
1231        // (`"no-inline-html"`).
1232        config.canonicalize_rule_lists();
1233
1234        config
1235    }
1236}
1237
1238#[cfg(test)]
1239mod tests {
1240    use super::pyproject_declares_rumdl_config;
1241
1242    #[test]
1243    fn detects_flat_and_dotted_rumdl_sections() {
1244        assert!(pyproject_declares_rumdl_config("[tool.rumdl]\nline-length = 80\n"));
1245        // Dotted sections are valid on their own, without a flat header.
1246        assert!(pyproject_declares_rumdl_config(
1247            "[tool.rumdl.MD013]\nstyle = \"fixed\"\n"
1248        ));
1249        assert!(pyproject_declares_rumdl_config(
1250            "[tool.rumdl.rules.MD007]\nindent = 4\n"
1251        ));
1252    }
1253
1254    #[test]
1255    fn ignores_incidental_mentions() {
1256        // A bare `tool.rumdl` in a comment or string value must not be treated
1257        // as a config section.
1258        assert!(!pyproject_declares_rumdl_config("# configure tool.rumdl later\n"));
1259        assert!(!pyproject_declares_rumdl_config(
1260            "[project]\ndependencies = [\"tool.rumdl-helper\"]\n"
1261        ));
1262        assert!(!pyproject_declares_rumdl_config("[tool.black]\nline-length = 88\n"));
1263    }
1264
1265    /// Pure tests for the `$VAR` / `${VAR}` expander used by `extends` resolution.
1266    /// The injected `lookup` keeps these independent of the real process environment.
1267    mod expand_env_vars {
1268        use super::super::expand_env_vars;
1269        use std::collections::HashMap;
1270
1271        /// Build a lookup closure from `(name, value)` pairs.
1272        fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
1273            let map: HashMap<String, String> = pairs
1274                .iter()
1275                .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
1276                .collect();
1277            move |k: &str| map.get(k).cloned()
1278        }
1279
1280        #[test]
1281        fn expands_bare_and_braced_forms() {
1282            let e = env(&[("VAR", "val"), ("FOO_BAR", "fb")]);
1283            assert_eq!(expand_env_vars("$VAR", &e).unwrap(), "val");
1284            assert_eq!(expand_env_vars("${VAR}", &e).unwrap(), "val");
1285            // Longest-match identifier: `$FOO_BAR` is one name, not `$FOO` + `_BAR`.
1286            assert_eq!(expand_env_vars("$FOO_BAR", &e).unwrap(), "fb");
1287        }
1288
1289        #[test]
1290        fn expands_within_paths() {
1291            let e = env(&[("BASE", "/opt/cfg"), ("A", "x"), ("B", "y")]);
1292            assert_eq!(expand_env_vars("$BASE/x/y.toml", &e).unwrap(), "/opt/cfg/x/y.toml");
1293            assert_eq!(expand_env_vars("$A/$B", &e).unwrap(), "x/y");
1294            assert_eq!(expand_env_vars("${A}suffix", &e).unwrap(), "xsuffix");
1295        }
1296
1297        #[test]
1298        fn dollar_dollar_is_a_literal_dollar() {
1299            let e = env(&[("VAR", "val")]);
1300            assert_eq!(expand_env_vars("$$", &e).unwrap(), "$");
1301            // The escaped `$` is consumed; what follows is literal (not expanded).
1302            assert_eq!(expand_env_vars("$$VAR", &e).unwrap(), "$VAR");
1303            assert_eq!(expand_env_vars("$${VAR}", &e).unwrap(), "${VAR}");
1304            // `$$` is how a literal `$` in a path is written once this feature exists.
1305            assert_eq!(expand_env_vars("file-$$name.toml", &e).unwrap(), "file-$name.toml");
1306        }
1307
1308        #[test]
1309        fn bare_dollar_name_in_path_is_a_variable_reference() {
1310            // Documented behavior change: an unescaped `$name` in a path is a variable,
1311            // not a literal. `$$` writes a literal `$` (see dollar_dollar test above).
1312            let e = env(&[("name", "core")]);
1313            assert_eq!(expand_env_vars("file-$name.toml", &e).unwrap(), "file-core.toml");
1314        }
1315
1316        #[test]
1317        fn incidental_dollar_stays_literal() {
1318            let e = env(&[]);
1319            // `$` before a non-identifier-start char (or end of input) is literal.
1320            assert_eq!(expand_env_vars("$5", &e).unwrap(), "$5");
1321            assert_eq!(expand_env_vars("cost$", &e).unwrap(), "cost$");
1322            assert_eq!(expand_env_vars("a$/b", &e).unwrap(), "a$/b");
1323        }
1324
1325        #[test]
1326        fn malformed_braces_stay_literal() {
1327            let e = env(&[("B", "x")]);
1328            assert_eq!(expand_env_vars("${}", &e).unwrap(), "${}");
1329            assert_eq!(expand_env_vars("${VAR", &e).unwrap(), "${VAR");
1330            // Nested `${...}` is not supported: the whole span is literal, no partial expand.
1331            assert_eq!(expand_env_vars("${A${B}}", &e).unwrap(), "${A${B}}");
1332        }
1333
1334        #[test]
1335        fn undefined_variable_is_an_error() {
1336            let e = env(&[]);
1337            assert_eq!(expand_env_vars("$NOPE", &e).unwrap_err(), "NOPE");
1338            assert_eq!(expand_env_vars("${NOPE}", &e).unwrap_err(), "NOPE");
1339            assert_eq!(expand_env_vars("prefix/$NOPE/x", &e).unwrap_err(), "NOPE");
1340        }
1341
1342        #[test]
1343        fn replacement_is_not_rescanned() {
1344            // If `A` expands to "$B", the result is the literal "$B"; `B` is NOT expanded.
1345            let e = env(&[("A", "$B"), ("B", "should-not-appear")]);
1346            assert_eq!(expand_env_vars("$A", &e).unwrap(), "$B");
1347            assert_eq!(expand_env_vars("${A}", &e).unwrap(), "$B");
1348        }
1349
1350        #[test]
1351        fn identifiers_are_ascii_only_unicode_stays_literal() {
1352            let e = env(&[("VAR", "v")]);
1353            // Non-ASCII inside braces is not a valid identifier -> whole span literal.
1354            assert_eq!(expand_env_vars("${föö}", &e).unwrap(), "${föö}");
1355            // A name ends at the first non-identifier byte; trailing unicode is preserved.
1356            assert_eq!(expand_env_vars("$VARö", &e).unwrap(), "vö");
1357            // Literal runs preserve multibyte content around an expansion.
1358            assert_eq!(expand_env_vars("café/$VAR", &e).unwrap(), "café/v");
1359        }
1360
1361        #[test]
1362        fn passthrough_for_plain_input() {
1363            let e = env(&[]);
1364            assert_eq!(expand_env_vars("", &e).unwrap(), "");
1365            assert_eq!(expand_env_vars("/plain/path.toml", &e).unwrap(), "/plain/path.toml");
1366        }
1367    }
1368
1369    /// Discovery must stop at the project root even when the root is supplied in
1370    /// a different path representation than the walked directory's ancestors.
1371    ///
1372    /// This reproduces the Windows 8.3-short-name / canonical mismatch using a
1373    /// Unix symlink: the project root is passed as a symlink to the real root, so
1374    /// it does not string-match the canonical ancestors of the starting
1375    /// directory. Without canonicalization the walk overshoots the project root
1376    /// and incorrectly picks up the config in the parent directory.
1377    #[cfg(unix)]
1378    #[test]
1379    fn discover_stops_at_project_root_across_path_representations() {
1380        use super::SourcedConfig;
1381        use std::os::unix::fs::symlink;
1382        use tempfile::tempdir;
1383
1384        let tmp = tempdir().unwrap();
1385        // A config ABOVE the project root that must never be discovered.
1386        std::fs::write(tmp.path().join(".rumdl.toml"), "").unwrap();
1387
1388        let real_root = tmp.path().join("project");
1389        let subdir = real_root.join("docs");
1390        std::fs::create_dir_all(&subdir).unwrap();
1391
1392        // Supply the project root via a symlink so it does not string-match the
1393        // canonical ancestors of `subdir`.
1394        let linked_root = tmp.path().join("project-link");
1395        symlink(&real_root, &linked_root).unwrap();
1396
1397        let found = SourcedConfig::discover_config_for_dir(&subdir, &linked_root);
1398        assert_eq!(
1399            found, None,
1400            "discovery must stop at the project root, not overshoot to the parent config"
1401        );
1402    }
1403
1404    mod shadowed_configs {
1405        use super::super::{ShadowedConfigs, detect_shadowed_configs, format_shadow_warning, rumdl_configs_in_dir};
1406        use tempfile::tempdir;
1407
1408        fn names(paths: &[std::path::PathBuf]) -> Vec<String> {
1409            paths
1410                .iter()
1411                .map(|p| {
1412                    // Use the last two components so `.config/rumdl.toml` is distinguishable
1413                    // from a top-level `rumdl.toml` without depending on the temp dir prefix.
1414                    let file = p.file_name().and_then(|n| n.to_str()).unwrap_or_default();
1415                    let parent = p.parent().and_then(|d| d.file_name()).and_then(|n| n.to_str());
1416                    match parent {
1417                        Some(".config") => format!(".config/{file}"),
1418                        _ => file.to_string(),
1419                    }
1420                })
1421                .collect()
1422        }
1423
1424        #[test]
1425        fn empty_directory_has_no_configs_and_no_shadow() {
1426            let tmp = tempdir().unwrap();
1427            assert!(rumdl_configs_in_dir(tmp.path()).is_empty());
1428            assert!(detect_shadowed_configs(tmp.path()).is_none());
1429        }
1430
1431        #[test]
1432        fn single_config_does_not_shadow() {
1433            let tmp = tempdir().unwrap();
1434            std::fs::write(tmp.path().join(".rumdl.toml"), "").unwrap();
1435            assert_eq!(names(&rumdl_configs_in_dir(tmp.path())), vec![".rumdl.toml"]);
1436            assert!(detect_shadowed_configs(tmp.path()).is_none());
1437        }
1438
1439        #[test]
1440        fn dot_wins_over_non_dot_and_non_dot_is_shadowed() {
1441            let tmp = tempdir().unwrap();
1442            std::fs::write(tmp.path().join(".rumdl.toml"), "").unwrap();
1443            std::fs::write(tmp.path().join("rumdl.toml"), "").unwrap();
1444
1445            let ShadowedConfigs { winner, shadowed, .. } = detect_shadowed_configs(tmp.path()).unwrap();
1446            assert_eq!(names(&[winner]), vec![".rumdl.toml"]);
1447            assert_eq!(names(&shadowed), vec!["rumdl.toml"]);
1448        }
1449
1450        #[test]
1451        fn config_subdir_counts_as_same_level_shadow() {
1452            let tmp = tempdir().unwrap();
1453            std::fs::write(tmp.path().join(".rumdl.toml"), "").unwrap();
1454            std::fs::create_dir_all(tmp.path().join(".config")).unwrap();
1455            std::fs::write(tmp.path().join(".config/rumdl.toml"), "").unwrap();
1456
1457            let ShadowedConfigs { winner, shadowed, .. } = detect_shadowed_configs(tmp.path()).unwrap();
1458            assert_eq!(names(&[winner]), vec![".rumdl.toml"]);
1459            assert_eq!(names(&shadowed), vec![".config/rumdl.toml"]);
1460        }
1461
1462        #[test]
1463        fn pyproject_counts_only_when_it_declares_rumdl() {
1464            // pyproject WITHOUT [tool.rumdl] is not a rumdl config source -> no shadow.
1465            let bare = tempdir().unwrap();
1466            std::fs::write(bare.path().join(".rumdl.toml"), "").unwrap();
1467            std::fs::write(bare.path().join("pyproject.toml"), "[tool.black]\nline-length = 88\n").unwrap();
1468            assert_eq!(names(&rumdl_configs_in_dir(bare.path())), vec![".rumdl.toml"]);
1469            assert!(detect_shadowed_configs(bare.path()).is_none());
1470
1471            // pyproject WITH [tool.rumdl] is a real shadowed source.
1472            let declared = tempdir().unwrap();
1473            std::fs::write(declared.path().join(".rumdl.toml"), "").unwrap();
1474            std::fs::write(
1475                declared.path().join("pyproject.toml"),
1476                "[tool.rumdl]\nline-length = 80\n",
1477            )
1478            .unwrap();
1479            let ShadowedConfigs { winner, shadowed, .. } = detect_shadowed_configs(declared.path()).unwrap();
1480            assert_eq!(names(&[winner]), vec![".rumdl.toml"]);
1481            assert_eq!(names(&shadowed), vec!["pyproject.toml"]);
1482        }
1483
1484        #[test]
1485        fn markdownlint_configs_are_not_rumdl_native_and_never_shadow() {
1486            let tmp = tempdir().unwrap();
1487            std::fs::write(tmp.path().join(".rumdl.toml"), "").unwrap();
1488            std::fs::write(tmp.path().join(".markdownlint.json"), "{}").unwrap();
1489            assert_eq!(names(&rumdl_configs_in_dir(tmp.path())), vec![".rumdl.toml"]);
1490            assert!(detect_shadowed_configs(tmp.path()).is_none());
1491        }
1492
1493        #[test]
1494        fn configs_returned_in_precedence_order() {
1495            let tmp = tempdir().unwrap();
1496            std::fs::write(tmp.path().join(".rumdl.toml"), "").unwrap();
1497            std::fs::write(tmp.path().join("rumdl.toml"), "").unwrap();
1498            std::fs::create_dir_all(tmp.path().join(".config")).unwrap();
1499            std::fs::write(tmp.path().join(".config/rumdl.toml"), "").unwrap();
1500            std::fs::write(tmp.path().join("pyproject.toml"), "[tool.rumdl]\n").unwrap();
1501
1502            assert_eq!(
1503                names(&rumdl_configs_in_dir(tmp.path())),
1504                vec![".rumdl.toml", "rumdl.toml", ".config/rumdl.toml", "pyproject.toml"]
1505            );
1506        }
1507
1508        #[test]
1509        fn warning_names_dir_once_with_relative_filenames() {
1510            let tmp = tempdir().unwrap();
1511            std::fs::write(tmp.path().join(".rumdl.toml"), "").unwrap();
1512            std::fs::write(tmp.path().join("rumdl.toml"), "").unwrap();
1513            std::fs::write(tmp.path().join("pyproject.toml"), "[tool.rumdl]\n").unwrap();
1514
1515            let shadow = detect_shadowed_configs(tmp.path()).unwrap();
1516            let msg = format_shadow_warning(&shadow);
1517
1518            let dir = {
1519                let s = tmp.path().to_string_lossy().into_owned();
1520                if cfg!(windows) { s.replace('\\', "/") } else { s }
1521            };
1522            assert!(msg.contains("multiple rumdl config files"), "got: {msg}");
1523            // The directory is named once; files are shown relative to it (no
1524            // repeated directory prefix on every path).
1525            assert_eq!(
1526                msg.matches(dir.as_str()).count(),
1527                1,
1528                "directory should appear exactly once, got: {msg}"
1529            );
1530            assert!(
1531                msg.contains("using .rumdl.toml, ignoring rumdl.toml, pyproject.toml"),
1532                "winner and shadowed files should be relative names in precedence order, got: {msg}"
1533            );
1534            // Paths are normalized to forward slashes on all platforms.
1535            assert!(!msg.contains('\\'), "paths must be normalized to '/': {msg}");
1536        }
1537    }
1538}