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
20const MAX_EXTENDS_DEPTH: usize = 10;
22
23fn pyproject_declares_rumdl_config(content: &str) -> bool {
32 content.contains("[tool.rumdl]") || content.contains("[tool.rumdl.")
33}
34
35fn is_var_name_start(b: u8) -> bool {
37 b == b'_' || b.is_ascii_alphabetic()
38}
39
40fn is_var_name_continue(b: u8) -> bool {
42 b == b'_' || b.is_ascii_alphanumeric()
43}
44
45fn 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
51fn 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 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 Some(b'$') => {
87 out.push('$');
88 i += 2;
89 }
90 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 out.push_str(&input[i..=close]);
103 }
104 i = close + 1;
105 } else {
106 out.push('$');
108 i += 1;
109 }
110 }
111 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 _ => {
127 out.push('$');
128 i += 1;
129 }
130 }
131 }
132
133 Ok(out)
134}
135
136fn 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 #[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 let config_dir = config_file_path.parent().unwrap_or(Path::new("."));
170 Ok(config_dir.join(&expanded))
171 }
172 }
173}
174
175fn source_from_filename(filename: &str) -> ConfigSource {
177 if filename == "pyproject.toml" {
178 ConfigSource::PyprojectToml
179 } else {
180 ConfigSource::ProjectConfig
181 }
182}
183
184pub(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#[derive(Debug, Clone, PartialEq, Eq)]
217pub(crate) struct ShadowedConfigs {
218 pub dir: PathBuf,
219 pub winner: PathBuf,
220 pub shadowed: Vec<PathBuf>,
221}
222
223pub(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
241pub(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
263fn 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 let canonical = config_file_path
277 .canonicalize()
278 .unwrap_or_else(|_| config_file_path.to_path_buf());
279
280 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 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 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 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(()), }
314 } else {
315 parsers::parse_rumdl_toml(&content, &path_str, chain_source)?
316 };
317
318 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 load_config_with_extends(sourced_config, &base_path, visited, chain_source)?;
337 }
338
339 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 pub(super) fn merge(&mut self, fragment: SourcedConfigFragment) {
353 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 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 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 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 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 for (rule_name, rule_fragment) in fragment.rules {
414 let norm_rule_name = rule_name.to_ascii_uppercase(); let rule_entry = self.rules.entry(norm_rule_name).or_default();
416
417 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 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 for (section, key, file_path) in fragment.unknown_keys {
438 if !self.unknown_keys.iter().any(|(s, k, _)| s == §ion && k == &key) {
440 self.unknown_keys.push((section, key, file_path));
441 }
442 }
443 }
444
445 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 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 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 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 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 let project_root = Self::find_project_root_from(&config_dir);
526 Some((config_path, project_root, shadow))
527 }
528
529 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 fn user_configuration_path_impl(config_dir: &Path) -> Option<std::path::PathBuf> {
559 let config_dir = config_dir.join("rumdl");
560
561 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 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 #[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 #[cfg(not(feature = "native"))]
617 fn user_configuration_path() -> Option<std::path::PathBuf> {
618 None
619 }
620
621 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 #[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 #[cfg(not(feature = "native"))]
678 fn home_configuration_path() -> Option<std::path::PathBuf> {
679 None
680 }
681
682 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 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 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 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 let fragment = parsers::load_from_markdownlint(&path_str)?;
723 sourced_config.merge(fragment);
724 sourced_config.loaded_files.push(path_str);
725 } else {
726 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 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 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 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 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 #[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 if let Some(path) = config_path {
893 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 } else {
900 log::debug!("[rumdl-config] No explicit config_path, searching default locations");
902
903 if let Some((config_file, project_root, shadow)) = Self::discover_config_upward(home_dir) {
905 log::debug!("[rumdl-config] Found project config: {}", config_file.display());
909 log::debug!("[rumdl-config] Project root: {}", project_root.display());
910
911 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 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 DiscoveredConfigError::ProjectConfig(e) => {
940 log::debug!("[rumdl-config] Failed to load markdownlint config: {e}");
941 }
942 DiscoveredConfigError::UserConfig(e) => return Err(e),
944 }
945 }
946 } else {
947 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 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 }
987
988 Ok(sourced_config)
991 }
992
993 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 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 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 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 pub fn discover_config_for_dir(dir: &Path, project_root: &Path) -> Option<PathBuf> {
1079 UpwardWalk::new(dir)
1091 .stop_below(Self::resolve_home_boundary(None))
1092 .stop_at(project_root)
1093 .find_map(|current| {
1094 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 MARKDOWNLINT_CONFIG_FILES
1112 .iter()
1113 .map(|name| current.join(name))
1114 .find(|path| path.exists())
1115 })
1116 }
1117
1118 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 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 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
1169impl 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 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 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 config.apply_per_rule_enabled();
1225
1226 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 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 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 mod expand_env_vars {
1268 use super::super::expand_env_vars;
1269 use std::collections::HashMap;
1270
1271 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 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 assert_eq!(expand_env_vars("$$VAR", &e).unwrap(), "$VAR");
1303 assert_eq!(expand_env_vars("$${VAR}", &e).unwrap(), "${VAR}");
1304 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 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 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 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 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 assert_eq!(expand_env_vars("${föö}", &e).unwrap(), "${föö}");
1355 assert_eq!(expand_env_vars("$VARö", &e).unwrap(), "vö");
1357 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 #[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 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 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 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 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 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 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 assert!(!msg.contains('\\'), "paths must be normalized to '/': {msg}");
1536 }
1537 }
1538}