1use indexmap::IndexSet;
2use std::collections::BTreeMap;
3use std::marker::PhantomData;
4use std::path::{Path, PathBuf};
5use std::sync::{Arc, OnceLock};
6
7use super::flavor::ConfigLoaded;
8use super::flavor::ConfigValidated;
9use super::parsers;
10use super::registry::RuleRegistry;
11use super::source_tracking::{
12 ConfigSource, ConfigValidationWarning, SourcedConfig, SourcedConfigFragment, SourcedGlobalConfig, SourcedValue,
13};
14use super::types::{Config, ConfigError, GlobalConfig, MARKDOWNLINT_CONFIG_FILES, RUMDL_CONFIG_FILES, RuleConfig};
15use super::validation::validate_config_sourced_internal;
16
17const MAX_EXTENDS_DEPTH: usize = 10;
19
20fn pyproject_declares_rumdl_config(content: &str) -> bool {
29 content.contains("[tool.rumdl]") || content.contains("[tool.rumdl.")
30}
31
32fn resolve_extends_path(extends_value: &str, config_file_path: &Path) -> PathBuf {
38 if let Some(suffix) = extends_value.strip_prefix("~/") {
39 #[cfg(feature = "native")]
41 {
42 use etcetera::{BaseStrategy, choose_base_strategy};
43 let home = choose_base_strategy().map_or_else(|_| PathBuf::from("~"), |s| s.home_dir().to_path_buf());
44 home.join(suffix)
45 }
46 #[cfg(not(feature = "native"))]
47 {
48 let _ = suffix;
49 PathBuf::from(extends_value)
50 }
51 } else {
52 let path = PathBuf::from(extends_value);
53 if path.is_absolute() {
54 path
55 } else {
56 let config_dir = config_file_path.parent().unwrap_or(Path::new("."));
58 config_dir.join(extends_value)
59 }
60 }
61}
62
63fn source_from_filename(filename: &str) -> ConfigSource {
65 if filename == "pyproject.toml" {
66 ConfigSource::PyprojectToml
67 } else {
68 ConfigSource::ProjectConfig
69 }
70}
71
72fn load_config_with_extends(
79 sourced_config: &mut SourcedConfig<ConfigLoaded>,
80 config_file_path: &Path,
81 visited: &mut IndexSet<PathBuf>,
82 chain_source: ConfigSource,
83) -> Result<(), ConfigError> {
84 let canonical = config_file_path
86 .canonicalize()
87 .unwrap_or_else(|_| config_file_path.to_path_buf());
88
89 if visited.contains(&canonical) {
91 let chain: Vec<String> = visited.iter().map(|p| p.display().to_string()).collect();
92 return Err(ConfigError::CircularExtends {
93 path: config_file_path.display().to_string(),
94 chain,
95 });
96 }
97
98 if visited.len() >= MAX_EXTENDS_DEPTH {
100 return Err(ConfigError::ExtendsDepthExceeded {
101 path: config_file_path.display().to_string(),
102 max_depth: MAX_EXTENDS_DEPTH,
103 });
104 }
105
106 visited.insert(canonical);
108
109 let path_str = config_file_path.display().to_string();
110 let filename = config_file_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
111
112 let content = std::fs::read_to_string(config_file_path).map_err(|e| ConfigError::IoError {
114 source: e,
115 path: path_str.clone(),
116 })?;
117
118 let fragment = if filename == "pyproject.toml" {
119 match parsers::parse_pyproject_toml(&content, &path_str, chain_source)? {
120 Some(f) => f,
121 None => return Ok(()), }
123 } else {
124 parsers::parse_rumdl_toml(&content, &path_str, chain_source)?
125 };
126
127 if let Some(ref extends_value) = fragment.extends {
129 let base_path = resolve_extends_path(extends_value, config_file_path);
130
131 if !base_path.exists() {
132 return Err(ConfigError::ExtendsNotFound {
133 path: base_path.display().to_string(),
134 from: path_str.clone(),
135 });
136 }
137
138 log::debug!(
139 "[rumdl-config] Config {} extends {}, loading base first",
140 path_str,
141 base_path.display()
142 );
143
144 load_config_with_extends(sourced_config, &base_path, visited, chain_source)?;
146 }
147
148 let mut fragment_for_merge = fragment;
151 fragment_for_merge.extends = None;
152 sourced_config.merge(fragment_for_merge);
153 sourced_config.loaded_files.push(path_str);
154
155 Ok(())
156}
157
158impl SourcedConfig<ConfigLoaded> {
159 pub(super) fn merge(&mut self, fragment: SourcedConfigFragment) {
162 self.global.enable.merge_override(
165 fragment.global.enable.value,
166 fragment.global.enable.source,
167 fragment.global.enable.overrides.first().and_then(|o| o.file.clone()),
168 fragment.global.enable.overrides.first().and_then(|o| o.line),
169 );
170
171 self.global.disable.merge_override(
173 fragment.global.disable.value,
174 fragment.global.disable.source,
175 fragment.global.disable.overrides.first().and_then(|o| o.file.clone()),
176 fragment.global.disable.overrides.first().and_then(|o| o.line),
177 );
178
179 self.global.extend_enable.merge_union(
181 fragment.global.extend_enable.value,
182 fragment.global.extend_enable.source,
183 fragment
184 .global
185 .extend_enable
186 .overrides
187 .first()
188 .and_then(|o| o.file.clone()),
189 fragment.global.extend_enable.overrides.first().and_then(|o| o.line),
190 );
191
192 self.global.extend_disable.merge_union(
194 fragment.global.extend_disable.value,
195 fragment.global.extend_disable.source,
196 fragment
197 .global
198 .extend_disable
199 .overrides
200 .first()
201 .and_then(|o| o.file.clone()),
202 fragment.global.extend_disable.overrides.first().and_then(|o| o.line),
203 );
204
205 self.global
208 .disable
209 .value
210 .retain(|rule| !self.global.enable.value.contains(rule));
211 self.global.include.merge_override(
212 fragment.global.include.value,
213 fragment.global.include.source,
214 fragment.global.include.overrides.first().and_then(|o| o.file.clone()),
215 fragment.global.include.overrides.first().and_then(|o| o.line),
216 );
217 self.global.exclude.merge_override(
218 fragment.global.exclude.value,
219 fragment.global.exclude.source,
220 fragment.global.exclude.overrides.first().and_then(|o| o.file.clone()),
221 fragment.global.exclude.overrides.first().and_then(|o| o.line),
222 );
223 self.global.respect_gitignore.merge_override(
224 fragment.global.respect_gitignore.value,
225 fragment.global.respect_gitignore.source,
226 fragment
227 .global
228 .respect_gitignore
229 .overrides
230 .first()
231 .and_then(|o| o.file.clone()),
232 fragment.global.respect_gitignore.overrides.first().and_then(|o| o.line),
233 );
234 self.global.line_length.merge_override(
235 fragment.global.line_length.value,
236 fragment.global.line_length.source,
237 fragment
238 .global
239 .line_length
240 .overrides
241 .first()
242 .and_then(|o| o.file.clone()),
243 fragment.global.line_length.overrides.first().and_then(|o| o.line),
244 );
245 self.global.fixable.merge_override(
246 fragment.global.fixable.value,
247 fragment.global.fixable.source,
248 fragment.global.fixable.overrides.first().and_then(|o| o.file.clone()),
249 fragment.global.fixable.overrides.first().and_then(|o| o.line),
250 );
251 self.global.unfixable.merge_override(
252 fragment.global.unfixable.value,
253 fragment.global.unfixable.source,
254 fragment.global.unfixable.overrides.first().and_then(|o| o.file.clone()),
255 fragment.global.unfixable.overrides.first().and_then(|o| o.line),
256 );
257
258 self.global.flavor.merge_override(
260 fragment.global.flavor.value,
261 fragment.global.flavor.source,
262 fragment.global.flavor.overrides.first().and_then(|o| o.file.clone()),
263 fragment.global.flavor.overrides.first().and_then(|o| o.line),
264 );
265
266 self.global.force_exclude.merge_override(
268 fragment.global.force_exclude.value,
269 fragment.global.force_exclude.source,
270 fragment
271 .global
272 .force_exclude
273 .overrides
274 .first()
275 .and_then(|o| o.file.clone()),
276 fragment.global.force_exclude.overrides.first().and_then(|o| o.line),
277 );
278
279 if let Some(output_format_fragment) = fragment.global.output_format {
281 if let Some(ref mut output_format) = self.global.output_format {
282 output_format.merge_override(
283 output_format_fragment.value,
284 output_format_fragment.source,
285 output_format_fragment.overrides.first().and_then(|o| o.file.clone()),
286 output_format_fragment.overrides.first().and_then(|o| o.line),
287 );
288 } else {
289 self.global.output_format = Some(output_format_fragment);
290 }
291 }
292
293 if let Some(cache_dir_fragment) = fragment.global.cache_dir {
295 if let Some(ref mut cache_dir) = self.global.cache_dir {
296 cache_dir.merge_override(
297 cache_dir_fragment.value,
298 cache_dir_fragment.source,
299 cache_dir_fragment.overrides.first().and_then(|o| o.file.clone()),
300 cache_dir_fragment.overrides.first().and_then(|o| o.line),
301 );
302 } else {
303 self.global.cache_dir = Some(cache_dir_fragment);
304 }
305 }
306
307 if fragment.global.cache.source != ConfigSource::Default {
309 self.global.cache.merge_override(
310 fragment.global.cache.value,
311 fragment.global.cache.source,
312 fragment.global.cache.overrides.first().and_then(|o| o.file.clone()),
313 fragment.global.cache.overrides.first().and_then(|o| o.line),
314 );
315 }
316
317 self.per_file_ignores.merge_override(
319 fragment.per_file_ignores.value,
320 fragment.per_file_ignores.source,
321 fragment.per_file_ignores.overrides.first().and_then(|o| o.file.clone()),
322 fragment.per_file_ignores.overrides.first().and_then(|o| o.line),
323 );
324
325 self.per_file_flavor.merge_override(
327 fragment.per_file_flavor.value,
328 fragment.per_file_flavor.source,
329 fragment.per_file_flavor.overrides.first().and_then(|o| o.file.clone()),
330 fragment.per_file_flavor.overrides.first().and_then(|o| o.line),
331 );
332
333 self.code_block_tools.merge_override(
335 fragment.code_block_tools.value,
336 fragment.code_block_tools.source,
337 fragment.code_block_tools.overrides.first().and_then(|o| o.file.clone()),
338 fragment.code_block_tools.overrides.first().and_then(|o| o.line),
339 );
340
341 for (rule_name, rule_fragment) in fragment.rules {
343 let norm_rule_name = rule_name.to_ascii_uppercase(); let rule_entry = self.rules.entry(norm_rule_name).or_default();
345
346 if let Some(severity_fragment) = rule_fragment.severity {
348 if let Some(ref mut existing_severity) = rule_entry.severity {
349 existing_severity.merge_override(
350 severity_fragment.value,
351 severity_fragment.source,
352 severity_fragment.overrides.first().and_then(|o| o.file.clone()),
353 severity_fragment.overrides.first().and_then(|o| o.line),
354 );
355 } else {
356 rule_entry.severity = Some(severity_fragment);
357 }
358 }
359
360 for (key, sourced_value_fragment) in rule_fragment.values {
362 let sv_entry = rule_entry
363 .values
364 .entry(key.clone())
365 .or_insert_with(|| SourcedValue::new(sourced_value_fragment.value.clone(), ConfigSource::Default));
366 let file_from_fragment = sourced_value_fragment.overrides.first().and_then(|o| o.file.clone());
367 let line_from_fragment = sourced_value_fragment.overrides.first().and_then(|o| o.line);
368 sv_entry.merge_override(
369 sourced_value_fragment.value, sourced_value_fragment.source, file_from_fragment, line_from_fragment, );
374 }
375 }
376
377 for (section, key, file_path) in fragment.unknown_keys {
379 if !self.unknown_keys.iter().any(|(s, k, _)| s == §ion && k == &key) {
381 self.unknown_keys.push((section, key, file_path));
382 }
383 }
384 }
385
386 pub fn load(config_path: Option<&str>, cli_overrides: Option<&SourcedGlobalConfig>) -> Result<Self, ConfigError> {
388 Self::load_with_discovery(config_path, cli_overrides, false)
389 }
390
391 fn find_project_root_from(start_dir: &Path) -> std::path::PathBuf {
394 let mut current = if start_dir.is_relative() {
396 std::env::current_dir().map_or_else(|_| start_dir.to_path_buf(), |cwd| cwd.join(start_dir))
397 } else {
398 start_dir.to_path_buf()
399 };
400 const MAX_DEPTH: usize = 100;
401
402 for _ in 0..MAX_DEPTH {
403 if current.join(".git").exists() {
404 log::debug!("[rumdl-config] Found .git at: {}", current.display());
405 return current;
406 }
407
408 match current.parent() {
409 Some(parent) => current = parent.to_path_buf(),
410 None => break,
411 }
412 }
413
414 log::debug!(
416 "[rumdl-config] No .git found, using config location as project root: {}",
417 start_dir.display()
418 );
419 start_dir.to_path_buf()
420 }
421
422 fn discover_config_upward() -> Option<(std::path::PathBuf, std::path::PathBuf)> {
428 use std::env;
429
430 const MAX_DEPTH: usize = 100; let start_dir = match env::current_dir() {
433 Ok(dir) => dir,
434 Err(e) => {
435 log::debug!("[rumdl-config] Failed to get current directory: {e}");
436 return None;
437 }
438 };
439
440 let mut current_dir = start_dir.clone();
441 let mut depth = 0;
442 let mut found_config: Option<(std::path::PathBuf, std::path::PathBuf)> = None;
443
444 loop {
445 if depth >= MAX_DEPTH {
446 log::debug!("[rumdl-config] Maximum traversal depth reached");
447 break;
448 }
449
450 log::debug!("[rumdl-config] Searching for config in: {}", current_dir.display());
451
452 if found_config.is_none() {
454 for config_name in RUMDL_CONFIG_FILES {
455 let config_path = current_dir.join(config_name);
456
457 if config_path.exists() {
458 if *config_name == "pyproject.toml" {
460 if let Ok(content) = std::fs::read_to_string(&config_path) {
461 if pyproject_declares_rumdl_config(&content) {
462 log::debug!("[rumdl-config] Found config file: {}", config_path.display());
463 found_config = Some((config_path.clone(), current_dir.clone()));
465 break;
466 }
467 log::debug!("[rumdl-config] Found pyproject.toml but no [tool.rumdl] section");
468 continue;
469 }
470 } else {
471 log::debug!("[rumdl-config] Found config file: {}", config_path.display());
472 found_config = Some((config_path.clone(), current_dir.clone()));
474 break;
475 }
476 }
477 }
478 }
479
480 if current_dir.join(".git").exists() {
482 log::debug!("[rumdl-config] Stopping at .git directory");
483 break;
484 }
485
486 match current_dir.parent() {
488 Some(parent) => {
489 current_dir = parent.to_owned();
490 depth += 1;
491 }
492 None => {
493 log::debug!("[rumdl-config] Reached filesystem root");
494 break;
495 }
496 }
497 }
498
499 if let Some((config_path, config_dir)) = found_config {
501 let project_root = Self::find_project_root_from(&config_dir);
502 return Some((config_path, project_root));
503 }
504
505 None
506 }
507
508 fn discover_markdownlint_config_upward() -> Option<std::path::PathBuf> {
512 use std::env;
513
514 const MAX_DEPTH: usize = 100;
515
516 let start_dir = match env::current_dir() {
517 Ok(dir) => dir,
518 Err(e) => {
519 log::debug!("[rumdl-config] Failed to get current directory for markdownlint discovery: {e}");
520 return None;
521 }
522 };
523
524 let mut current_dir = start_dir.clone();
525 let mut depth = 0;
526
527 loop {
528 if depth >= MAX_DEPTH {
529 log::debug!("[rumdl-config] Maximum traversal depth reached for markdownlint discovery");
530 break;
531 }
532
533 log::debug!(
534 "[rumdl-config] Searching for markdownlint config in: {}",
535 current_dir.display()
536 );
537
538 for config_name in MARKDOWNLINT_CONFIG_FILES {
540 let config_path = current_dir.join(config_name);
541 if config_path.exists() {
542 log::debug!("[rumdl-config] Found markdownlint config: {}", config_path.display());
543 return Some(config_path);
544 }
545 }
546
547 if current_dir.join(".git").exists() {
549 log::debug!("[rumdl-config] Stopping markdownlint search at .git directory");
550 break;
551 }
552
553 match current_dir.parent() {
555 Some(parent) => {
556 current_dir = parent.to_owned();
557 depth += 1;
558 }
559 None => {
560 log::debug!("[rumdl-config] Reached filesystem root during markdownlint search");
561 break;
562 }
563 }
564 }
565
566 None
567 }
568
569 fn user_configuration_path_impl(config_dir: &Path) -> Option<std::path::PathBuf> {
571 let config_dir = config_dir.join("rumdl");
572
573 const USER_CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml", "pyproject.toml"];
575
576 log::debug!(
577 "[rumdl-config] Checking for user configuration in: {}",
578 config_dir.display()
579 );
580
581 for filename in USER_CONFIG_FILES {
582 let config_path = config_dir.join(filename);
583
584 if config_path.exists() {
585 if *filename == "pyproject.toml" {
587 if let Ok(content) = std::fs::read_to_string(&config_path) {
588 if pyproject_declares_rumdl_config(&content) {
589 log::debug!("[rumdl-config] Found user configuration at: {}", config_path.display());
590 return Some(config_path);
591 }
592 log::debug!("[rumdl-config] Found user pyproject.toml but no [tool.rumdl] section");
593 continue;
594 }
595 } else {
596 log::debug!("[rumdl-config] Found user configuration at: {}", config_path.display());
597 return Some(config_path);
598 }
599 }
600 }
601
602 log::debug!(
603 "[rumdl-config] No user configuration found in: {}",
604 config_dir.display()
605 );
606 None
607 }
608
609 #[cfg(feature = "native")]
612 fn user_configuration_path() -> Option<std::path::PathBuf> {
613 use etcetera::{BaseStrategy, choose_base_strategy};
614
615 match choose_base_strategy() {
616 Ok(strategy) => {
617 let config_dir = strategy.config_dir();
618 Self::user_configuration_path_impl(&config_dir)
619 }
620 Err(e) => {
621 log::debug!("[rumdl-config] Failed to determine user config directory: {e}");
622 None
623 }
624 }
625 }
626
627 #[cfg(not(feature = "native"))]
629 fn user_configuration_path() -> Option<std::path::PathBuf> {
630 None
631 }
632
633 fn home_configuration_path_impl(home_dir: &Path) -> Option<std::path::PathBuf> {
645 const HOME_CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml"];
646
647 log::debug!(
648 "[rumdl-config] Checking for home-directory configuration in: {}",
649 home_dir.display()
650 );
651
652 for filename in HOME_CONFIG_FILES {
653 let config_path = home_dir.join(filename);
654 if config_path.exists() {
655 log::debug!(
656 "[rumdl-config] Found home-directory configuration at: {}",
657 config_path.display()
658 );
659 return Some(config_path);
660 }
661 }
662
663 log::debug!(
664 "[rumdl-config] No home-directory configuration found in: {}",
665 home_dir.display()
666 );
667 None
668 }
669
670 #[cfg(feature = "native")]
676 fn home_configuration_path() -> Option<std::path::PathBuf> {
677 use etcetera::{BaseStrategy, choose_base_strategy};
678
679 match choose_base_strategy() {
680 Ok(strategy) => Self::home_configuration_path_impl(strategy.home_dir()),
681 Err(e) => {
682 log::debug!("[rumdl-config] Failed to determine home directory: {e}");
683 None
684 }
685 }
686 }
687
688 #[cfg(not(feature = "native"))]
690 fn home_configuration_path() -> Option<std::path::PathBuf> {
691 None
692 }
693
694 fn load_explicit_config(sourced_config: &mut Self, path: &str) -> Result<(), ConfigError> {
696 let path_obj = Path::new(path);
697 let filename = path_obj.file_name().and_then(|name| name.to_str()).unwrap_or("");
698 let path_str = path.to_string();
699
700 log::debug!("[rumdl-config] Loading explicit config file: {filename}");
701
702 if let Some(config_parent) = path_obj.parent() {
704 let project_root = Self::find_project_root_from(config_parent);
705 log::debug!(
706 "[rumdl-config] Project root (from explicit config): {}",
707 project_root.display()
708 );
709 sourced_config.project_root = Some(project_root);
710 }
711
712 const MARKDOWNLINT_FILENAMES: &[&str] = &[
714 ".markdownlint-cli2.jsonc",
715 ".markdownlint-cli2.yaml",
716 ".markdownlint-cli2.yml",
717 ".markdownlint.json",
718 ".markdownlint.yaml",
719 ".markdownlint.yml",
720 ];
721
722 if filename == "pyproject.toml" || filename == ".rumdl.toml" || filename == "rumdl.toml" {
723 let mut visited = IndexSet::new();
725 let chain_source = source_from_filename(filename);
726 load_config_with_extends(sourced_config, path_obj, &mut visited, chain_source)?;
727 } else if MARKDOWNLINT_FILENAMES.contains(&filename)
728 || path_str.ends_with(".json")
729 || path_str.ends_with(".jsonc")
730 || path_str.ends_with(".yaml")
731 || path_str.ends_with(".yml")
732 {
733 let fragment = parsers::load_from_markdownlint(&path_str)?;
735 sourced_config.merge(fragment);
736 sourced_config.loaded_files.push(path_str);
737 } else {
738 let mut visited = IndexSet::new();
740 let chain_source = source_from_filename(filename);
741 load_config_with_extends(sourced_config, path_obj, &mut visited, chain_source)?;
742 }
743
744 Ok(())
745 }
746
747 fn load_user_config(
764 sourced_config: &mut Self,
765 user_config_dir: Option<&Path>,
766 home_dir: Option<&Path>,
767 ) -> Result<(), ConfigError> {
768 let user_config_path = if let Some(dir) = user_config_dir {
769 Self::user_configuration_path_impl(dir)
770 } else {
771 Self::user_configuration_path()
772 };
773
774 let user_config_path = user_config_path.or_else(|| match home_dir {
775 Some(home) => Self::home_configuration_path_impl(home),
776 None => Self::home_configuration_path(),
777 });
778
779 if let Some(user_config_path) = user_config_path {
780 let path_str = user_config_path.display().to_string();
781
782 log::debug!("[rumdl-config] Loading user config: {path_str}");
783
784 let mut visited = IndexSet::new();
787 load_config_with_extends(
788 sourced_config,
789 &user_config_path,
790 &mut visited,
791 ConfigSource::UserConfig,
792 )?;
793 } else {
794 log::debug!("[rumdl-config] No user configuration file found");
795 }
796
797 Ok(())
798 }
799
800 #[doc(hidden)]
802 pub fn load_with_discovery_impl(
803 config_path: Option<&str>,
804 cli_overrides: Option<&SourcedGlobalConfig>,
805 skip_auto_discovery: bool,
806 user_config_dir: Option<&Path>,
807 home_dir: Option<&Path>,
808 ) -> Result<Self, ConfigError> {
809 use std::env;
810 log::debug!("[rumdl-config] Current working directory: {:?}", env::current_dir());
811
812 let mut sourced_config = SourcedConfig::default();
813
814 if let Some(path) = config_path {
827 log::debug!("[rumdl-config] Explicit config_path provided: {path:?}");
829 Self::load_explicit_config(&mut sourced_config, path)?;
830 } else if skip_auto_discovery {
831 log::debug!("[rumdl-config] Skipping config discovery due to --no-config/--isolated flag");
832 } else {
834 log::debug!("[rumdl-config] No explicit config_path, searching default locations");
836
837 if let Some((config_file, project_root)) = Self::discover_config_upward() {
839 log::debug!("[rumdl-config] Found project config: {}", config_file.display());
843 log::debug!("[rumdl-config] Project root: {}", project_root.display());
844
845 sourced_config.project_root = Some(project_root);
846
847 let mut visited = IndexSet::new();
849 let root_filename = config_file.file_name().and_then(|n| n.to_str()).unwrap_or("");
850 let chain_source = source_from_filename(root_filename);
851 load_config_with_extends(&mut sourced_config, &config_file, &mut visited, chain_source)?;
852 } else {
853 log::debug!("[rumdl-config] No rumdl config found, checking markdownlint config");
855
856 if let Some(markdownlint_path) = Self::discover_markdownlint_config_upward() {
857 let path_str = markdownlint_path.display().to_string();
858 log::debug!("[rumdl-config] Found markdownlint config: {path_str}");
859 Self::load_user_config(&mut sourced_config, user_config_dir, home_dir)?;
864 match parsers::load_from_markdownlint(&path_str) {
865 Ok(fragment) => {
866 sourced_config.merge(fragment);
867 sourced_config.loaded_files.push(path_str);
868 }
869 Err(_e) => {
870 log::debug!("[rumdl-config] Failed to load markdownlint config");
871 }
872 }
873 } else {
874 log::debug!("[rumdl-config] No project config found, using user config as fallback");
876 Self::load_user_config(&mut sourced_config, user_config_dir, home_dir)?;
877 }
878 }
879 }
880
881 if let Some(cli) = cli_overrides {
883 sourced_config
884 .global
885 .enable
886 .merge_override(cli.enable.value.clone(), ConfigSource::Cli, None, None);
887 sourced_config
888 .global
889 .disable
890 .merge_override(cli.disable.value.clone(), ConfigSource::Cli, None, None);
891 sourced_config
892 .global
893 .exclude
894 .merge_override(cli.exclude.value.clone(), ConfigSource::Cli, None, None);
895 sourced_config
896 .global
897 .include
898 .merge_override(cli.include.value.clone(), ConfigSource::Cli, None, None);
899 sourced_config.global.respect_gitignore.merge_override(
900 cli.respect_gitignore.value,
901 ConfigSource::Cli,
902 None,
903 None,
904 );
905 sourced_config
906 .global
907 .fixable
908 .merge_override(cli.fixable.value.clone(), ConfigSource::Cli, None, None);
909 sourced_config
910 .global
911 .unfixable
912 .merge_override(cli.unfixable.value.clone(), ConfigSource::Cli, None, None);
913 }
915
916 Ok(sourced_config)
919 }
920
921 pub fn load_with_discovery(
924 config_path: Option<&str>,
925 cli_overrides: Option<&SourcedGlobalConfig>,
926 skip_auto_discovery: bool,
927 ) -> Result<Self, ConfigError> {
928 Self::load_with_discovery_impl(config_path, cli_overrides, skip_auto_discovery, None, None)
929 }
930
931 pub fn validate(self, registry: &RuleRegistry) -> Result<SourcedConfig<ConfigValidated>, ConfigError> {
945 let warnings = validate_config_sourced_internal(&self, registry);
946
947 Ok(SourcedConfig {
948 global: self.global,
949 per_file_ignores: self.per_file_ignores,
950 per_file_flavor: self.per_file_flavor,
951 code_block_tools: self.code_block_tools,
952 rules: self.rules,
953 loaded_files: self.loaded_files,
954 unknown_keys: self.unknown_keys,
955 project_root: self.project_root,
956 validation_warnings: warnings,
957 _state: PhantomData,
958 })
959 }
960
961 pub fn validate_into(self, registry: &RuleRegistry) -> Result<(Config, Vec<ConfigValidationWarning>), ConfigError> {
966 let validated = self.validate(registry)?;
967 let warnings = validated.validation_warnings.clone();
968 Ok((validated.into(), warnings))
969 }
970
971 pub fn into_validated_unchecked(self) -> SourcedConfig<ConfigValidated> {
982 SourcedConfig {
983 global: self.global,
984 per_file_ignores: self.per_file_ignores,
985 per_file_flavor: self.per_file_flavor,
986 code_block_tools: self.code_block_tools,
987 rules: self.rules,
988 loaded_files: self.loaded_files,
989 unknown_keys: self.unknown_keys,
990 project_root: self.project_root,
991 validation_warnings: Vec::new(),
992 _state: PhantomData,
993 }
994 }
995
996 pub fn discover_config_for_dir(dir: &Path, project_root: &Path) -> Option<PathBuf> {
1005 let mut current_dir = dir.to_path_buf();
1006
1007 loop {
1008 for config_name in RUMDL_CONFIG_FILES {
1010 let config_path = current_dir.join(config_name);
1011 if config_path.exists() {
1012 if *config_name == "pyproject.toml" {
1013 if let Ok(content) = std::fs::read_to_string(&config_path)
1014 && pyproject_declares_rumdl_config(&content)
1015 {
1016 return Some(config_path);
1017 }
1018 continue;
1019 }
1020 return Some(config_path);
1021 }
1022 }
1023
1024 for config_name in MARKDOWNLINT_CONFIG_FILES {
1026 let config_path = current_dir.join(config_name);
1027 if config_path.exists() {
1028 return Some(config_path);
1029 }
1030 }
1031
1032 if current_dir == project_root {
1034 break;
1035 }
1036
1037 match current_dir.parent() {
1039 Some(parent) => current_dir = parent.to_path_buf(),
1040 None => break,
1041 }
1042 }
1043
1044 None
1045 }
1046
1047 pub fn load_config_for_path(config_path: &Path, project_root: &Path) -> Result<Config, ConfigError> {
1053 let mut sourced_config = SourcedConfig {
1054 project_root: Some(project_root.to_path_buf()),
1055 ..SourcedConfig::default()
1056 };
1057
1058 let filename = config_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
1059 let path_str = config_path.display().to_string();
1060
1061 let is_markdownlint = MARKDOWNLINT_CONFIG_FILES.contains(&filename)
1063 || (filename != "pyproject.toml"
1064 && filename != ".rumdl.toml"
1065 && filename != "rumdl.toml"
1066 && (path_str.ends_with(".json")
1067 || path_str.ends_with(".jsonc")
1068 || path_str.ends_with(".yaml")
1069 || path_str.ends_with(".yml")));
1070
1071 if is_markdownlint {
1072 let fragment = parsers::load_from_markdownlint(&path_str)?;
1073 sourced_config.merge(fragment);
1074 sourced_config.loaded_files.push(path_str);
1075 } else {
1076 let mut visited = IndexSet::new();
1077 let chain_source = source_from_filename(filename);
1078 load_config_with_extends(&mut sourced_config, config_path, &mut visited, chain_source)?;
1079 }
1080
1081 Ok(sourced_config.into_validated_unchecked().into())
1082 }
1083}
1084
1085impl From<SourcedConfig<ConfigValidated>> for Config {
1090 fn from(sourced: SourcedConfig<ConfigValidated>) -> Self {
1091 let mut rules = BTreeMap::new();
1092 for (rule_name, sourced_rule_cfg) in sourced.rules {
1093 let normalized_rule_name = rule_name.to_ascii_uppercase();
1095 let severity = sourced_rule_cfg.severity.map(|sv| sv.value);
1096 let mut values = BTreeMap::new();
1097 for (key, sourced_val) in sourced_rule_cfg.values {
1098 values.insert(key, sourced_val.value);
1099 }
1100 rules.insert(normalized_rule_name, RuleConfig { severity, values });
1101 }
1102 let enable_is_explicit = sourced.global.enable.source != ConfigSource::Default;
1104
1105 #[allow(deprecated)]
1106 let global = GlobalConfig {
1107 enable: sourced.global.enable.value,
1108 disable: sourced.global.disable.value,
1109 exclude: sourced.global.exclude.value,
1110 include: sourced.global.include.value,
1111 respect_gitignore: sourced.global.respect_gitignore.value,
1112 line_length: sourced.global.line_length.value,
1113 output_format: sourced.global.output_format.as_ref().map(|v| v.value.clone()),
1114 fixable: sourced.global.fixable.value,
1115 unfixable: sourced.global.unfixable.value,
1116 flavor: sourced.global.flavor.value,
1117 force_exclude: sourced.global.force_exclude.value,
1118 cache_dir: sourced.global.cache_dir.as_ref().map(|v| v.value.clone()),
1119 cache: sourced.global.cache.value,
1120 extend_enable: sourced.global.extend_enable.value,
1121 extend_disable: sourced.global.extend_disable.value,
1122 enable_is_explicit,
1123 };
1124
1125 let mut config = Config {
1126 extends: None,
1127 global,
1128 per_file_ignores: sourced.per_file_ignores.value,
1129 per_file_flavor: sourced.per_file_flavor.value,
1130 code_block_tools: sourced.code_block_tools.value,
1131 rules,
1132 project_root: sourced.project_root,
1133 per_file_ignores_cache: Arc::new(OnceLock::new()),
1134 per_file_flavor_cache: Arc::new(OnceLock::new()),
1135 canonical_project_root_cache: Arc::new(OnceLock::new()),
1136 };
1137
1138 config.apply_per_rule_enabled();
1140
1141 config.canonicalize_rule_lists();
1148
1149 config
1150 }
1151}
1152
1153#[cfg(test)]
1154mod tests {
1155 use super::pyproject_declares_rumdl_config;
1156
1157 #[test]
1158 fn detects_flat_and_dotted_rumdl_sections() {
1159 assert!(pyproject_declares_rumdl_config("[tool.rumdl]\nline-length = 80\n"));
1160 assert!(pyproject_declares_rumdl_config(
1162 "[tool.rumdl.MD013]\nstyle = \"fixed\"\n"
1163 ));
1164 assert!(pyproject_declares_rumdl_config(
1165 "[tool.rumdl.rules.MD007]\nindent = 4\n"
1166 ));
1167 }
1168
1169 #[test]
1170 fn ignores_incidental_mentions() {
1171 assert!(!pyproject_declares_rumdl_config("# configure tool.rumdl later\n"));
1174 assert!(!pyproject_declares_rumdl_config(
1175 "[project]\ndependencies = [\"tool.rumdl-helper\"]\n"
1176 ));
1177 assert!(!pyproject_declares_rumdl_config("[tool.black]\nline-length = 88\n"));
1178 }
1179}