rumdl_lib/config/types.rs
1use crate::discovery::PathAliases;
2use crate::types::LineLength;
3use globset::{Glob, GlobBuilder, GlobMatcher, GlobSet, GlobSetBuilder};
4use indexmap::IndexMap;
5use serde::{Deserialize, Serialize};
6use std::collections::{BTreeMap, HashSet};
7use std::fs;
8use std::io;
9use std::path::{Path, PathBuf};
10use std::sync::{Arc, OnceLock};
11
12use super::flavor::{MarkdownFlavor, normalize_key};
13
14/// Represents a rule-specific configuration
15#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, schemars::JsonSchema)]
16pub struct RuleConfig {
17 /// Severity override for this rule (Error, Warning, or Info)
18 #[serde(default, skip_serializing_if = "Option::is_none")]
19 pub severity: Option<crate::rule::Severity>,
20
21 /// Configuration values for the rule
22 #[serde(flatten)]
23 #[schemars(schema_with = "arbitrary_value_schema")]
24 pub values: BTreeMap<String, toml::Value>,
25}
26
27/// Generate a JSON schema for arbitrary configuration values
28fn arbitrary_value_schema(_gen: &mut schemars::SchemaGenerator) -> schemars::Schema {
29 schemars::json_schema!({
30 "type": "object",
31 "additionalProperties": true
32 })
33}
34
35/// Represents the complete configuration loaded from rumdl.toml
36#[derive(Debug, Clone, Serialize, Deserialize, Default, schemars::JsonSchema)]
37#[schemars(
38 description = "rumdl configuration for linting Markdown files. Rules can be configured individually using [MD###] sections with rule-specific options."
39)]
40pub struct Config {
41 /// Path to a base config file to inherit settings from.
42 /// Supports relative paths, absolute paths, `~/` for the home directory, and
43 /// `$VAR` / `${VAR}` environment-variable expansion (a literal `$` is written `$$`).
44 /// Example: `extends = "../base.rumdl.toml"` or `extends = "$GEM_PATH/base.rumdl.toml"`
45 #[serde(default, skip_serializing_if = "Option::is_none")]
46 pub extends: Option<String>,
47
48 /// Global configuration options
49 #[serde(default)]
50 pub global: GlobalConfig,
51
52 /// Per-file rule ignores: maps file patterns to lists of rules to ignore.
53 /// Patterns are relative to the project root; a leading `~/` expands to the
54 /// home directory and absolute paths are matched as written.
55 /// Example: { "README.md": ["MD033"], "docs/**/*.md": ["MD013"] }
56 #[serde(default, rename = "per-file-ignores")]
57 pub per_file_ignores: BTreeMap<String, Vec<String>>,
58
59 /// Per-file flavor overrides: maps file patterns to Markdown flavors.
60 /// Patterns are relative to the project root; a leading `~/` expands to the
61 /// home directory and absolute paths are matched as written.
62 /// Example: { "docs/**/*.md": MkDocs, "**/*.mdx": MDX }
63 /// Uses IndexMap to preserve config file order for "first match wins" semantics
64 #[serde(default, rename = "per-file-flavor")]
65 #[schemars(with = "BTreeMap<String, MarkdownFlavor>")]
66 pub per_file_flavor: IndexMap<String, MarkdownFlavor>,
67
68 /// Code block tools configuration for per-language linting and formatting
69 /// using external tools like ruff, prettier, shellcheck, etc.
70 #[serde(default, rename = "code-block-tools")]
71 pub code_block_tools: crate::code_block_tools::CodeBlockToolsConfig,
72
73 /// Rule-specific configurations (e.g., MD013, MD007, MD044)
74 /// Each rule section can contain options specific to that rule.
75 ///
76 /// Common examples:
77 /// - MD013: line_length, code_blocks, tables, headings
78 /// - MD007: indent
79 /// - MD003: style ("atx", "atx-closed", "setext")
80 /// - MD044: names (array of proper names to check)
81 ///
82 /// See <https://github.com/rvben/rumdl> for full rule documentation.
83 #[serde(flatten)]
84 pub rules: BTreeMap<String, RuleConfig>,
85
86 /// Rules holding at least one option value that came from a config file
87 /// whose contents may not be quoted back (an `extends` target, whose path
88 /// is arbitrary and whose text the extending project need not be able to
89 /// read). The values apply as written; only a message about one has to
90 /// leave it out.
91 ///
92 /// Granularity is the rule section, because that is what a rule's options
93 /// are deserialized as: an error names one value but not which key it came
94 /// from, so a section mixing an extended value with a directly named one
95 /// withholds both. Erring that way keeps a message from carrying text the
96 /// project never wrote.
97 ///
98 /// Provenance rather than configuration, so it stays out of the serialized
99 /// form and the JSON schema.
100 #[serde(skip)]
101 #[schemars(skip)]
102 pub withheld_rule_values: std::collections::BTreeSet<String>,
103
104 /// Project root directory, used for resolving relative paths in per-file-ignores
105 #[serde(skip)]
106 pub project_root: Option<std::path::PathBuf>,
107
108 #[serde(skip)]
109 #[schemars(skip)]
110 pub(super) per_file_ignores_cache: Arc<OnceLock<PerFileIgnoreCache>>,
111
112 #[serde(skip)]
113 #[schemars(skip)]
114 pub(super) per_file_flavor_cache: Arc<OnceLock<PerFileFlavorCache>>,
115
116 /// Lazily-computed canonical form of `project_root`.
117 ///
118 /// `normalize_match_path` needs the canonical project root to strip
119 /// prefixes from absolute file paths. Without this cache, every per-file
120 /// lookup would re-canonicalize the project root (one syscall per file).
121 ///
122 /// ## Invariants
123 ///
124 /// - **Single-shot**: computed once on first use of [`Config::canonical_project_root`].
125 /// - **Never invalidated**: callers must not mutate `project_root` after
126 /// the first call. `Config` is treated as immutable post-construction
127 /// (the same assumption as `per_file_ignores_cache` and `per_file_flavor_cache`).
128 /// - **Construction-time existence**: the cache stores `None` if
129 /// `project_root` is unset, missing on disk, or otherwise can't be
130 /// canonicalized. In practice `project_root` is set after walking up to
131 /// `.git`, so the directory always exists at the time the cache is first
132 /// read; if a caller sets `project_root` to a not-yet-existing path,
133 /// the cache will permanently store `None`.
134 /// - **`Arc` wrapping**: `Config` derives `Clone`, and clones share the
135 /// same `OnceLock` so a value computed by one clone is observable to all.
136 ///
137 /// `cwd` deliberately is NOT cached symmetrically: callers read it fresh
138 /// from `std::env::current_dir()` per call because tests (and embedding
139 /// hosts like LSP servers) may legitimately mutate the process cwd
140 /// between lookups.
141 #[serde(skip)]
142 #[schemars(skip)]
143 pub(super) canonical_project_root_cache: Arc<OnceLock<Option<PathBuf>>>,
144}
145
146impl PartialEq for Config {
147 fn eq(&self, other: &Self) -> bool {
148 self.global == other.global
149 && self.per_file_ignores == other.per_file_ignores
150 && self.per_file_flavor == other.per_file_flavor
151 && self.code_block_tools == other.code_block_tools
152 && self.rules == other.rules
153 && self.project_root == other.project_root
154 }
155}
156
157#[derive(Debug)]
158pub(super) struct PerFileIgnoreCache {
159 globset: GlobSet,
160 rules: Vec<Vec<String>>,
161 /// Whether any pattern is absolute, i.e. whether matching has to consider
162 /// the file's absolute path as well as its project-relative form.
163 has_absolute: bool,
164 /// Spellings of the file that absolute patterns reach through a symlink.
165 aliases: PathAliases,
166}
167
168#[derive(Debug)]
169pub(super) struct PerFileFlavorCache {
170 matchers: Vec<(GlobMatcher, MarkdownFlavor)>,
171 /// See [`PerFileIgnoreCache::has_absolute`].
172 has_absolute: bool,
173 /// See [`PerFileIgnoreCache::aliases`].
174 aliases: PathAliases,
175}
176
177/// The file's absolute path, for matching against absolute patterns, resolved
178/// whether or not the file exists yet. `None` when the caller has no absolute
179/// pattern to match (the common case, which must not pay for the resolution).
180fn absolute_match_path(file_path: &Path, has_absolute: bool) -> Option<PathBuf> {
181 if !has_absolute {
182 return None;
183 }
184 Some(crate::discovery::resolve_for_matching(file_path))
185}
186
187/// The file's other spellings, for matching against absolute patterns that
188/// named a location through a symlink (`/var/folders/**` on macOS, whose files
189/// canonicalize to `/private/var/folders/…`). Empty for the configurations that
190/// have no such pattern, which is nearly all of them.
191fn alias_match_paths(aliases: &PathAliases, absolute: Option<&Path>) -> Vec<String> {
192 match absolute {
193 Some(absolute) if !aliases.is_empty() => aliases.spellings_of(absolute),
194 _ => Vec::new(),
195 }
196}
197
198impl Config {
199 /// Check if the Markdown flavor is set to MkDocs
200 pub fn is_mkdocs_flavor(&self) -> bool {
201 self.global.flavor == MarkdownFlavor::MkDocs
202 }
203
204 // Future methods for when GFM and CommonMark are implemented:
205 // pub fn is_gfm_flavor(&self) -> bool
206 // pub fn is_commonmark_flavor(&self) -> bool
207
208 /// Get the configured Markdown flavor
209 pub fn markdown_flavor(&self) -> MarkdownFlavor {
210 self.global.flavor
211 }
212
213 /// Legacy method for backwards compatibility - redirects to is_mkdocs_flavor
214 pub fn is_mkdocs_project(&self) -> bool {
215 self.is_mkdocs_flavor()
216 }
217
218 /// Apply per-rule `enabled` config to the global enable/disable lists.
219 ///
220 /// For `[MD060] enabled = true`: adds the rule to `extend_enable` and
221 /// removes it from `disable` and `extend_disable`, ensuring the rule is active.
222 ///
223 /// For `[MD041] enabled = false`: adds the rule to `disable` and
224 /// removes it from `extend_enable`, ensuring the rule is inactive.
225 ///
226 /// Per-rule `enabled` takes precedence over global lists when there
227 /// is a conflict, since it represents a more specific intent.
228 pub fn apply_per_rule_enabled(&mut self) {
229 let mut to_enable: Vec<String> = Vec::new();
230 let mut to_disable: Vec<String> = Vec::new();
231
232 for (name, cfg) in &self.rules {
233 match cfg.values.get("enabled") {
234 Some(toml::Value::Boolean(true)) => {
235 to_enable.push(name.clone());
236 }
237 Some(toml::Value::Boolean(false)) => {
238 to_disable.push(name.clone());
239 }
240 _ => {}
241 }
242 }
243
244 for name in to_enable {
245 if !self.global.extend_enable.contains(&name) {
246 self.global.extend_enable.push(name.clone());
247 }
248 self.global.disable.retain(|n| n != &name);
249 self.global.extend_disable.retain(|n| n != &name);
250 }
251
252 for name in to_disable {
253 if !self.global.disable.contains(&name) {
254 self.global.disable.push(name.clone());
255 }
256 self.global.extend_enable.retain(|n| n != &name);
257 }
258 }
259
260 /// Get the severity override for a specific rule, if configured
261 pub fn get_rule_severity(&self, rule_name: &str) -> Option<crate::rule::Severity> {
262 self.rules.get(rule_name).and_then(|r| r.severity)
263 }
264
265 /// Return the canonical form of `project_root`, computed once and cached.
266 ///
267 /// Returns `None` if `project_root` is unset, doesn't exist on disk, or
268 /// otherwise cannot be canonicalized. Subsequent calls reuse the cached
269 /// value, eliminating the per-file `canonicalize()` syscall that
270 /// `normalize_match_path` would otherwise perform.
271 pub(super) fn canonical_project_root(&self) -> Option<&Path> {
272 self.canonical_project_root_cache
273 .get_or_init(|| {
274 self.project_root
275 .as_deref()
276 .and_then(crate::discovery::canonicalize_for_matching)
277 })
278 .as_deref()
279 }
280
281 /// Get the set of rules that should be ignored for a specific file based on per-file-ignores configuration
282 /// Returns a HashSet of rule names (uppercase, e.g., "MD033") that match the given file path
283 pub fn get_ignored_rules_for_file(&self, file_path: &Path) -> HashSet<String> {
284 let mut ignored_rules = HashSet::new();
285
286 if self.per_file_ignores.is_empty() {
287 return ignored_rules;
288 }
289
290 let cwd = std::env::current_dir().ok();
291 let path_for_matching = normalize_match_path(file_path, self.canonical_project_root(), cwd.as_deref());
292
293 let cache = self
294 .per_file_ignores_cache
295 .get_or_init(|| PerFileIgnoreCache::new(&self.per_file_ignores));
296
297 // Match the file path against all patterns, by its project-relative
298 // form and - for absolute patterns, including expanded `~` ones - by
299 // its absolute path and by the spellings of that path a pattern named
300 // through a symlink.
301 let absolute = absolute_match_path(file_path, cache.has_absolute);
302 let aliases = alias_match_paths(&cache.aliases, absolute.as_deref());
303 let matches = cache
304 .globset
305 .matches(path_for_matching.as_ref())
306 .into_iter()
307 .chain(absolute.iter().flat_map(|abs| cache.globset.matches(abs)))
308 .chain(aliases.iter().flat_map(|alias| cache.globset.matches(alias)));
309
310 for match_idx in matches {
311 if let Some(rules) = cache.rules.get(match_idx) {
312 for rule in rules {
313 // Normalize rule names to uppercase (MD033, md033 -> MD033)
314 ignored_rules.insert(rule.clone());
315 }
316 }
317 }
318
319 ignored_rules
320 }
321
322 /// Get the MarkdownFlavor for a specific file based on per-file-flavor configuration.
323 /// Returns the first matching pattern's flavor, or falls back to global flavor,
324 /// or auto-detects from extension, or defaults to Standard.
325 pub fn get_flavor_for_file(&self, file_path: &Path) -> MarkdownFlavor {
326 // If no per-file patterns, use fallback logic
327 if self.per_file_flavor.is_empty() {
328 return self.resolve_flavor_fallback(file_path);
329 }
330
331 let cwd = std::env::current_dir().ok();
332 let path_for_matching = normalize_match_path(file_path, self.canonical_project_root(), cwd.as_deref());
333
334 let cache = self
335 .per_file_flavor_cache
336 .get_or_init(|| PerFileFlavorCache::new(&self.per_file_flavor));
337
338 // Iterate in config order and return first match (IndexMap preserves order).
339 // Each pattern sees the file's project-relative form and - for absolute
340 // patterns, including expanded `~` ones - its absolute path and the
341 // spellings of that path a pattern named through a symlink.
342 let absolute = absolute_match_path(file_path, cache.has_absolute);
343 let aliases = alias_match_paths(&cache.aliases, absolute.as_deref());
344 for (matcher, flavor) in &cache.matchers {
345 if matcher.is_match(path_for_matching.as_ref())
346 || absolute.as_ref().is_some_and(|abs| matcher.is_match(abs))
347 || aliases.iter().any(|alias| matcher.is_match(alias))
348 {
349 return *flavor;
350 }
351 }
352
353 // No pattern matched, use fallback
354 self.resolve_flavor_fallback(file_path)
355 }
356
357 /// Fallback flavor resolution: global flavor → auto-detect → Standard
358 fn resolve_flavor_fallback(&self, file_path: &Path) -> MarkdownFlavor {
359 // If global flavor is explicitly set to non-Standard, use it
360 if self.global.flavor != MarkdownFlavor::Standard {
361 return self.global.flavor;
362 }
363 // Auto-detect from extension
364 MarkdownFlavor::from_path(file_path)
365 }
366
367 /// Canonicalize every rule-name list inside this `Config`.
368 ///
369 /// This is the single enforcement point for the runtime invariant:
370 /// **after a `Config` is fully built, every rule-name list contains
371 /// canonical rule IDs (`"MD033"`) — never aliases (`"no-inline-html"`).**
372 ///
373 /// The invariant lets every consumer (`rules::filter_rules`, the LSP,
374 /// WASM, fix coordinator, per-file-ignore lookups) match against
375 /// `Rule::name()` with simple string equality. Mutation boundaries
376 /// (`From<SourcedConfig> for Config`, LSP `apply_lsp_settings_*`, WASM
377 /// `to_config_with_warnings`) call this before handing the `Config` to
378 /// the linting pipeline.
379 ///
380 /// Covers `global.{enable,disable,extend_enable,extend_disable,fixable,unfixable}`
381 /// and the values of `per_file_ignores`. Idempotent.
382 pub fn canonicalize_rule_lists(&mut self) {
383 use super::registry::canonicalize_rule_list_in_place;
384 self.global.canonicalize_rule_lists();
385 for rules in self.per_file_ignores.values_mut() {
386 canonicalize_rule_list_in_place(rules);
387 }
388 }
389
390 /// Merge inline configuration overrides into a copy of this config
391 ///
392 /// This enables automatic inline config support - the engine can merge
393 /// inline overrides and recreate rules without any per-rule changes.
394 ///
395 /// Returns a new Config with the inline overrides merged in.
396 /// If there are no inline overrides, returns a clone of self.
397 pub fn merge_with_inline_config(&self, inline_config: &crate::inline_config::InlineConfig) -> Self {
398 let overrides = inline_config.get_all_rule_configs();
399 if overrides.is_empty() {
400 return self.clone();
401 }
402
403 let mut merged = self.clone();
404
405 for (rule_name, json_override) in overrides {
406 // Get or create the rule config entry
407 let rule_config = merged.rules.entry(rule_name.clone()).or_default();
408
409 // Merge JSON values into the rule's config
410 if let Some(obj) = json_override.as_object() {
411 for (key, value) in obj {
412 // Normalize key to kebab-case for consistency
413 let normalized_key = key.replace('_', "-");
414
415 // Convert JSON value to TOML value
416 if let Some(toml_value) = json_to_toml(value) {
417 rule_config.values.insert(normalized_key, toml_value);
418 }
419 }
420 }
421 }
422
423 merged
424 }
425}
426
427/// Normalize a file path for matching against a glob pattern from configuration.
428///
429/// Glob patterns in `per-file-ignores` and `per-file-flavor` are written relative
430/// to the project root (e.g. `docs/**/*.md`), and a glob is anchored at the start
431/// of the string it matches, so an absolute path like `/home/user/proj/docs/x.md`
432/// will not match `docs/**/*.md`. This helper produces the form the glob expects:
433///
434/// 1. **Relative path** → return as-is.
435/// 2. **Absolute path under `project_root`** → return path relative to `project_root`.
436/// 3. **Absolute path under `cwd`** → return path relative to `cwd`. This is the
437/// safety net for invocations where `project_root` could not be discovered
438/// (no `.git` upward, LSP/CLI calls outside a project) but the file still
439/// lives somewhere under the working directory.
440/// 4. **Anywhere else** → return the raw path. A relative glob simply won't
441/// match it, which is the desired outcome for files outside any known root.
442///
443/// An absolute path need not exist: an editor buffer or a file about to be
444/// created is resolved through its deepest existing ancestor (see
445/// [`crate::discovery::resolve_for_matching`]), so it matches the patterns it
446/// will match once written.
447///
448/// `canonical_project_root` is expected to already be canonical (via
449/// `Config::canonical_project_root`). `cwd` is canonicalized internally on each
450/// call since it is read fresh from the environment per invocation.
451pub(super) fn normalize_match_path<'a>(
452 file_path: &'a Path,
453 canonical_project_root: Option<&Path>,
454 cwd: Option<&Path>,
455) -> std::borrow::Cow<'a, Path> {
456 use std::borrow::Cow;
457
458 if file_path.is_relative() {
459 return Cow::Borrowed(file_path);
460 }
461
462 let canonical_file = crate::discovery::resolve_for_matching(file_path);
463
464 if let Some(root) = canonical_project_root
465 && let Ok(rel) = canonical_file.strip_prefix(root)
466 {
467 return Cow::Owned(rel.to_path_buf());
468 }
469
470 if let Some(working_dir) = cwd
471 && let Some(canonical_cwd) = crate::discovery::canonicalize_for_matching(working_dir)
472 && let Ok(rel) = canonical_file.strip_prefix(&canonical_cwd)
473 {
474 return Cow::Owned(rel.to_path_buf());
475 }
476
477 // Surface the silent fallback once per process at warn level so users with
478 // per-file glob configs notice when their patterns can't match a file.
479 // Subsequent occurrences stay at debug to avoid log spam.
480 static SILENT_FALLBACK_WARNED: OnceLock<()> = OnceLock::new();
481 log::log!(
482 first_call_warn_else_debug(&SILENT_FALLBACK_WARNED),
483 "{}",
484 format_silent_fallback_message(file_path, canonical_project_root, cwd),
485 );
486 Cow::Borrowed(file_path)
487}
488
489/// Returns [`log::Level::Warn`] the first time it is called with a given
490/// `latch`, and [`log::Level::Debug`] on every subsequent call. The latch
491/// is consumed by the first caller via `OnceLock::set`; later callers
492/// observe the latch as already set and downgrade.
493///
494/// Used to flag a fallback condition once per process without flooding
495/// logs when the same condition recurs (e.g. once per linted file).
496pub(super) fn first_call_warn_else_debug(latch: &OnceLock<()>) -> log::Level {
497 if latch.set(()).is_ok() {
498 log::Level::Warn
499 } else {
500 log::Level::Debug
501 }
502}
503
504/// Format the diagnostic emitted when [`normalize_match_path`] cannot
505/// relativise `file_path` against either the project root or the current
506/// working directory. Extracted so the exact wording can be asserted in
507/// tests without capturing log output.
508pub(super) fn format_silent_fallback_message(
509 file_path: &Path,
510 canonical_project_root: Option<&Path>,
511 cwd: Option<&Path>,
512) -> String {
513 format!(
514 "Per-file glob patterns will not match {}: file is outside project_root ({}) and cwd ({})",
515 file_path.display(),
516 DisplayPathOrUnset(canonical_project_root),
517 DisplayPathOrUnset(cwd),
518 )
519}
520
521/// Display adapter for `Option<&Path>` that renders the path via
522/// [`Path::display`] when present, or the literal `<unset>` when absent.
523/// Angle brackets follow Rust's diagnostic convention (e.g. `<unknown>`)
524/// and avoid double-paren rendering when the surrounding format string
525/// already wraps the value in `(…)`.
526struct DisplayPathOrUnset<'a>(Option<&'a Path>);
527
528impl std::fmt::Display for DisplayPathOrUnset<'_> {
529 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
530 match self.0 {
531 Some(path) => std::fmt::Display::fmt(&path.display(), f),
532 None => f.write_str("<unset>"),
533 }
534 }
535}
536
537/// Convert a serde_json::Value to a toml::Value
538pub(super) fn json_to_toml(json: &serde_json::Value) -> Option<toml::Value> {
539 match json {
540 serde_json::Value::Null => None,
541 serde_json::Value::Bool(b) => Some(toml::Value::Boolean(*b)),
542 serde_json::Value::Number(n) => n
543 .as_i64()
544 .map(toml::Value::Integer)
545 .or_else(|| n.as_f64().map(toml::Value::Float)),
546 serde_json::Value::String(s) => Some(toml::Value::String(s.clone())),
547 serde_json::Value::Array(arr) => {
548 let toml_arr: Vec<toml::Value> = arr.iter().filter_map(json_to_toml).collect();
549 Some(toml::Value::Array(toml_arr))
550 }
551 serde_json::Value::Object(obj) => {
552 let mut table = toml::map::Map::new();
553 for (k, v) in obj {
554 if let Some(tv) = json_to_toml(v) {
555 table.insert(k.clone(), tv);
556 }
557 }
558 Some(toml::Value::Table(table))
559 }
560 }
561}
562
563impl PerFileIgnoreCache {
564 fn new(per_file_ignores: &BTreeMap<String, Vec<String>>) -> Self {
565 let mut builder = GlobSetBuilder::new();
566 let mut rules = Vec::new();
567
568 let mut has_absolute = false;
569 for (pattern, rules_list) in per_file_ignores {
570 let pattern = crate::discovery::expand_home_prefix(pattern);
571 has_absolute |= crate::discovery::has_absolute_spelling(&pattern);
572 if let Ok(glob) = Glob::new(&pattern) {
573 builder.add(glob);
574 // Canonicalize defensively: callers should have run
575 // Config::canonicalize_rule_lists already, but per-file-ignores
576 // has reached this cache directly from a few code paths
577 // historically, so we re-canonicalize here to keep the cache
578 // sound regardless of caller discipline.
579 rules.push(
580 rules_list
581 .iter()
582 .map(|rule| super::registry::resolve_rule_name(rule))
583 .collect(),
584 );
585 } else {
586 log::warn!("Invalid glob pattern in per-file-ignores: {pattern}");
587 }
588 }
589
590 let globset = builder.build().unwrap_or_else(|e| {
591 log::error!("Failed to build globset for per-file-ignores: {e}");
592 GlobSetBuilder::new().build().unwrap()
593 });
594
595 Self {
596 globset,
597 rules,
598 has_absolute,
599 aliases: PathAliases::new(per_file_ignores.keys().map(String::as_str)),
600 }
601 }
602}
603
604impl PerFileFlavorCache {
605 fn new(per_file_flavor: &IndexMap<String, MarkdownFlavor>) -> Self {
606 let mut matchers = Vec::new();
607
608 let mut has_absolute = false;
609 for (pattern, flavor) in per_file_flavor {
610 let pattern = crate::discovery::expand_home_prefix(pattern);
611 has_absolute |= crate::discovery::has_absolute_spelling(&pattern);
612 if let Ok(glob) = GlobBuilder::new(&pattern).literal_separator(true).build() {
613 matchers.push((glob.compile_matcher(), *flavor));
614 } else {
615 log::warn!("Invalid glob pattern in per-file-flavor: {pattern}");
616 }
617 }
618
619 Self {
620 matchers,
621 has_absolute,
622 aliases: PathAliases::new(per_file_flavor.keys().map(String::as_str)),
623 }
624 }
625}
626
627/// Global configuration options
628#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
629#[serde(default, rename_all = "kebab-case")]
630pub struct GlobalConfig {
631 /// Enabled rules
632 #[serde(default)]
633 pub enable: Vec<String>,
634
635 /// Disabled rules
636 #[serde(default)]
637 pub disable: Vec<String>,
638
639 /// Files to exclude. Glob patterns, relative to the project root; a
640 /// leading `~/` expands to the home directory and absolute paths are
641 /// matched as written.
642 #[serde(default)]
643 pub exclude: Vec<String>,
644
645 /// Files to include. Glob patterns, relative to the project root; a
646 /// leading `~/` expands to the home directory and absolute paths are
647 /// matched as written.
648 #[serde(default)]
649 pub include: Vec<String>,
650
651 /// Respect .gitignore files when scanning directories
652 #[serde(default = "default_respect_gitignore", alias = "respect_gitignore")]
653 pub respect_gitignore: bool,
654
655 /// Global line length setting (used by MD013 and other rules if not overridden)
656 #[serde(default, alias = "line_length")]
657 pub line_length: LineLength,
658
659 /// Output format for linting results (e.g., "text", "json", "pylint", etc.)
660 #[serde(skip_serializing_if = "Option::is_none", alias = "output_format")]
661 pub output_format: Option<String>,
662
663 /// Rules that are allowed to be fixed when --fix is used
664 /// If specified, only these rules will be fixed
665 #[serde(default)]
666 pub fixable: Vec<String>,
667
668 /// Rules that should never be fixed, even when --fix is used
669 /// Takes precedence over fixable
670 #[serde(default)]
671 pub unfixable: Vec<String>,
672
673 /// Markdown flavor/dialect to use (mkdocs, gfm, commonmark, etc.)
674 /// When set, adjusts parsing and validation rules for that specific Markdown variant
675 #[serde(default)]
676 pub flavor: MarkdownFlavor,
677
678 /// \[DEPRECATED\] Whether to enforce exclude patterns for explicitly passed paths.
679 /// This option is deprecated as of v0.0.156 and has no effect.
680 /// Exclude patterns are now always respected, even for explicitly provided files.
681 /// This prevents duplication between rumdl config and tool configs like pre-commit.
682 #[serde(default, alias = "force_exclude")]
683 #[deprecated(since = "0.0.156", note = "Exclude patterns are now always respected")]
684 pub force_exclude: bool,
685
686 /// Directory to store cache files (default: .rumdl_cache).
687 /// A leading `~/` expands to the home directory; a relative path resolves
688 /// against the project root.
689 /// Can also be set via --cache-dir CLI flag or RUMDL_CACHE_DIR environment variable
690 #[serde(default, alias = "cache_dir", skip_serializing_if = "Option::is_none")]
691 pub cache_dir: Option<String>,
692
693 /// Whether caching is enabled (default: true)
694 /// Can also be disabled via --no-cache CLI flag
695 #[serde(default = "default_true")]
696 pub cache: bool,
697
698 /// Additional rules to enable on top of the base set (additive)
699 #[serde(default, alias = "extend_enable")]
700 pub extend_enable: Vec<String>,
701
702 /// Additional rules to disable on top of the base set (additive)
703 #[serde(default, alias = "extend_disable")]
704 pub extend_disable: Vec<String>,
705
706 /// Whether to read settings from `.editorconfig` files (default: false).
707 /// When enabled, the `.editorconfig` properties that map onto rumdl
708 /// settings fill in anything no rumdl config sets, resolved per file so
709 /// section globs and nested `.editorconfig` files apply as written.
710 #[serde(default)]
711 pub editorconfig: bool,
712
713 /// Whether the enable list was explicitly set (even if empty).
714 /// Used to distinguish "no enable list configured" from "enable list is empty"
715 /// (e.g., markdownlint `default: false` with no rules enabled).
716 #[serde(skip)]
717 pub enable_is_explicit: bool,
718
719 /// How to name the file that supplied [`Self::include`] when a message about
720 /// those patterns may not quote them (an `extends` target, whose path is
721 /// arbitrary and whose text the extending project need not be able to read),
722 /// and `None` when it may. Provenance rather than configuration, so it stays
723 /// out of the serialized form and the JSON schema.
724 #[serde(skip)]
725 pub include_withheld: Option<String>,
726}
727
728fn default_respect_gitignore() -> bool {
729 true
730}
731
732fn default_true() -> bool {
733 true
734}
735
736// Add the Default impl
737impl Default for GlobalConfig {
738 #[allow(deprecated)]
739 fn default() -> Self {
740 Self {
741 enable: Vec::new(),
742 disable: Vec::new(),
743 exclude: Vec::new(),
744 include: Vec::new(),
745 respect_gitignore: true,
746 line_length: LineLength::default(),
747 output_format: None,
748 fixable: Vec::new(),
749 unfixable: Vec::new(),
750 flavor: MarkdownFlavor::default(),
751 force_exclude: false,
752 cache_dir: None,
753 cache: true,
754 extend_enable: Vec::new(),
755 extend_disable: Vec::new(),
756 editorconfig: false,
757 enable_is_explicit: false,
758 include_withheld: None,
759 }
760 }
761}
762
763impl GlobalConfig {
764 /// Canonicalize every rule-name list in this `GlobalConfig`.
765 ///
766 /// Rewrites `enable`, `disable`, `extend_enable`, `extend_disable`, `fixable`,
767 /// and `unfixable` so that all entries are canonical rule IDs (`"MD033"`)
768 /// rather than aliases (`"no-inline-html"`). Duplicates are removed,
769 /// preserving first-occurrence order; the special `"all"` keyword is
770 /// preserved.
771 ///
772 /// This must be called by every code path that mutates a runtime
773 /// `Config`'s rule lists from external input (markdownlint configs,
774 /// `.rumdl.toml`, LSP `initializationOptions`, WASM bindings, etc.) so
775 /// that downstream consumers (`rules::filter_rules`, the LSP, WASM) can
776 /// match against `Rule::name()` with simple string equality.
777 pub fn canonicalize_rule_lists(&mut self) {
778 use super::registry::canonicalize_rule_list_in_place;
779 canonicalize_rule_list_in_place(&mut self.enable);
780 canonicalize_rule_list_in_place(&mut self.disable);
781 canonicalize_rule_list_in_place(&mut self.extend_enable);
782 canonicalize_rule_list_in_place(&mut self.extend_disable);
783 canonicalize_rule_list_in_place(&mut self.fixable);
784 canonicalize_rule_list_in_place(&mut self.unfixable);
785 }
786}
787
788/// Names of rumdl-native config files, searched in precedence order when
789/// walking up a directory tree.
790///
791/// This is the single source of truth for config discovery. Both the CLI
792/// (`SourcedConfig::discover_config_upward`, `discover_config_for_dir`) and
793/// the LSP (`RumdlLanguageServer::resolve_config_for_file`) must use this
794/// list; any deviation causes silent config-not-found bugs where the CLI
795/// recognises a config but the LSP does not (or vice versa).
796///
797/// See `src/lsp/tests.rs::test_lsp_cli_resolver_parity_on_fixtures` for
798/// the side-by-side resolver parity test that pins this invariant across
799/// several directory layouts.
800pub const RUMDL_CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml", ".config/rumdl.toml", "pyproject.toml"];
801
802pub const MARKDOWNLINT_CONFIG_FILES: &[&str] = &[
803 ".markdownlint-cli2.jsonc",
804 ".markdownlint-cli2.yaml",
805 ".markdownlint-cli2.yml",
806 ".markdownlint.json",
807 ".markdownlint.jsonc",
808 ".markdownlint.yaml",
809 ".markdownlint.yml",
810 "markdownlint.json",
811 "markdownlint.jsonc",
812 "markdownlint.yaml",
813 "markdownlint.yml",
814];
815
816/// Create a default configuration file at the specified path
817pub fn create_default_config(path: &str) -> Result<(), ConfigError> {
818 create_preset_config("default", path)
819}
820
821/// Create a configuration file with a specific style preset
822pub fn create_preset_config(preset: &str, path: &str) -> Result<(), ConfigError> {
823 if Path::new(path).exists() {
824 return Err(ConfigError::FileExists { path: path.to_string() });
825 }
826
827 let config_content = match preset {
828 "default" => generate_default_preset(),
829 "google" => generate_google_preset(),
830 "relaxed" => generate_relaxed_preset(),
831 _ => {
832 return Err(ConfigError::UnknownPreset {
833 name: preset.to_string(),
834 });
835 }
836 };
837
838 match fs::write(path, config_content) {
839 Ok(_) => Ok(()),
840 Err(err) => Err(ConfigError::IoError {
841 source: err,
842 path: path.to_string(),
843 }),
844 }
845}
846
847/// Generate the default preset configuration content.
848/// Returns the same content as `create_default_config`.
849fn generate_default_preset() -> String {
850 r#"# rumdl configuration file
851
852# Inherit settings from another config file (relative to this file's directory)
853# extends = "../base.rumdl.toml"
854
855# Global configuration options
856[global]
857# List of rules to disable (uncomment and modify as needed)
858# disable = ["MD013", "MD033"]
859
860# List of rules to enable exclusively (replaces defaults; only these rules will run)
861# enable = ["MD001", "MD003", "MD004"]
862
863# Additional rules to enable on top of defaults (additive, does not replace)
864# Use this to activate opt-in rules like MD060, MD063, MD072, MD073, MD074
865# extend-enable = ["MD060", "MD063"]
866
867# Additional rules to disable on top of the disable list (additive)
868# extend-disable = ["MD041"]
869
870# List of file/directory patterns to include for linting (if provided, only these will be linted)
871# include = [
872# "docs/*.md",
873# "src/**/*.md",
874# "README.md"
875# ]
876
877# List of file/directory patterns to exclude from linting
878exclude = [
879 # Common directories to exclude
880 ".git",
881 ".github",
882 "node_modules",
883 "vendor",
884 "dist",
885 "build",
886
887 # Specific files or patterns
888 "CHANGELOG.md",
889 "LICENSE.md",
890]
891
892# Respect .gitignore files when scanning directories (default: true)
893respect-gitignore = true
894
895# Markdown flavor/dialect (uncomment to enable)
896# Options: standard (default), gfm, commonmark, mkdocs, mdx, pandoc, quarto, obsidian, kramdown, azure_devops, myst, hugo, mdg, gh-aw
897# flavor = "mkdocs"
898
899# Rule-specific configurations (uncomment and modify as needed)
900
901# [MD003]
902# style = "atx" # Heading style (atx, atx_closed, setext)
903
904# [MD004]
905# style = "asterisk" # Unordered list style (asterisk, plus, dash, consistent)
906
907# [MD007]
908# indent = 4 # Unordered list indentation
909
910# [MD013]
911# line-length = 100 # Line length
912# code-blocks = false # Exclude code blocks from line length check
913# tables = false # Exclude tables from line length check
914# headings = true # Include headings in line length check
915
916# [MD044]
917# names = ["rumdl", "Markdown", "GitHub"] # Proper names that should be capitalized correctly
918# code-blocks = false # Check code blocks for proper names (default: false, skips code blocks)
919"#
920 .to_string()
921}
922
923/// Generate Google developer documentation style preset.
924/// Based on <https://google.github.io/styleguide/docguide/style.html>
925fn generate_google_preset() -> String {
926 r#"# rumdl configuration - Google developer documentation style
927# Based on https://google.github.io/styleguide/docguide/style.html
928
929[global]
930exclude = [
931 ".git",
932 ".github",
933 "node_modules",
934 "vendor",
935 "dist",
936 "build",
937 "CHANGELOG.md",
938 "LICENSE.md",
939]
940respect-gitignore = true
941
942# ATX-style headings required
943[MD003]
944style = "atx"
945
946# Unordered list style: dash
947[MD004]
948style = "dash"
949
950# 4-space indent for nested lists
951[MD007]
952indent = 4
953
954# Strict mode: no trailing spaces allowed (Google uses backslash for line breaks)
955[MD009]
956strict = true
957
958# 80-character line length
959[MD013]
960line-length = 80
961code-blocks = false
962tables = false
963
964# No trailing punctuation in headings
965[MD026]
966punctuation = ".,;:!。,;:!"
967
968# Fenced code blocks only (no indented code blocks)
969[MD046]
970style = "fenced"
971
972# Emphasis with underscores
973[MD049]
974style = "underscore"
975
976# Strong with asterisks
977[MD050]
978style = "asterisk"
979"#
980 .to_string()
981}
982
983/// Generate relaxed preset for existing projects adopting rumdl incrementally.
984/// Longer line lengths, fewer rules, lenient settings to minimize initial warnings.
985fn generate_relaxed_preset() -> String {
986 r#"# rumdl configuration - Relaxed preset
987# Lenient settings for existing projects adopting rumdl incrementally.
988# Minimizes initial warnings while still catching important issues.
989
990[global]
991exclude = [
992 ".git",
993 ".github",
994 "node_modules",
995 "vendor",
996 "dist",
997 "build",
998 "CHANGELOG.md",
999 "LICENSE.md",
1000]
1001respect-gitignore = true
1002
1003# Disable rules that produce the most noise on existing projects
1004disable = [
1005 "MD013", # Line length - most existing files exceed 80 chars
1006 "MD033", # Inline HTML - commonly used in real-world markdown
1007 "MD041", # First line heading - not all files need it
1008]
1009
1010# Consistent heading style (any style, just be consistent)
1011[MD003]
1012style = "consistent"
1013
1014# Consistent list style
1015[MD004]
1016style = "consistent"
1017
1018# Consistent emphasis style
1019[MD049]
1020style = "consistent"
1021
1022# Consistent strong style
1023[MD050]
1024style = "consistent"
1025"#
1026 .to_string()
1027}
1028
1029/// How a config file being loaded was reached, which decides how much of it may
1030/// appear in a message about it.
1031///
1032/// A `Direct` file is one the user named: discovered in their project, or given
1033/// on the command line. Naming its path and quoting the line a parse error
1034/// points at tells them nothing they could not already read.
1035///
1036/// An `Extends` file was reached by following an `extends` value, and two things
1037/// about it are not the user's to see. Its path is built by substituting
1038/// environment variables, so printing the path prints their values wherever the
1039/// error goes, which under CI is the build log. And `extends` names an arbitrary
1040/// path chosen by whichever config declared it, so the file need not be config
1041/// at all: a repository you merely cloned can point rumdl at a private key and
1042/// have the parse error quote a line of it. Such a file is named by the
1043/// `extends` value as written, and its text is never quoted back.
1044///
1045/// This governs errors and warnings, which any lint run can emit unasked and
1046/// which therefore reach a build log that had no reason to hold a variable's
1047/// value. Output that answers a question about the configuration itself still
1048/// shows resolved paths, because that is the answer: `rumdl config` reports which
1049/// files took effect, a language server reports the same thing to the editor that
1050/// started it, and debug logging is how an `extends` chain gets diagnosed at all.
1051/// The first two read [`crate::config::SourcedConfig::loaded_files`], which is a
1052/// record of what loaded rather than a message about a problem, and it holds
1053/// resolved paths deliberately.
1054#[derive(Debug, Clone, Copy)]
1055pub(crate) enum ConfigOrigin<'a> {
1056 Direct,
1057 Extends {
1058 /// The reference together with the config that declared it. This is how
1059 /// the file is named by a message reporting a problem with the file
1060 /// itself, where knowing which config reached for it is what makes the
1061 /// problem diagnosable.
1062 described_as: &'a str,
1063 /// The reference alone, for the places a message only needs to identify
1064 /// the file: listing an `extends` chain, or naming it as the config that
1065 /// declared a further `extends`. Repeating the full form at every link
1066 /// nests one description inside the next.
1067 short_name: &'a str,
1068 },
1069}
1070
1071/// Stands in for text that came out of a file reached through `extends`.
1072///
1073/// Public because the file walk raises one of these messages itself: an `include`
1074/// pattern is judged where it is used rather than where it is parsed.
1075pub const WITHHELD: &str = "<withheld>";
1076
1077impl ConfigOrigin<'_> {
1078 /// How to name the file this origin describes in a message about the file.
1079 pub(crate) fn display_name(&self, path: &str) -> String {
1080 match self {
1081 Self::Direct => crate::config::validation::to_relative_display_path(path),
1082 Self::Extends { described_as, .. } => (*described_as).to_string(),
1083 }
1084 }
1085
1086 /// How to name this file when a message is about something else and only has
1087 /// to say which file it means.
1088 pub(crate) fn short_name(&self, path: &str) -> String {
1089 match self {
1090 Self::Direct => crate::config::validation::to_relative_display_path(path),
1091 Self::Extends { short_name, .. } => (*short_name).to_string(),
1092 }
1093 }
1094
1095 /// Whether a message about this file may quote the file's own text.
1096 pub(crate) fn may_quote_contents(&self) -> bool {
1097 matches!(self, Self::Direct)
1098 }
1099
1100 /// A piece of text read from this file, as a message about the file may
1101 /// show it.
1102 ///
1103 /// A `Direct` file's text is shown as written. An `Extends` target's is
1104 /// replaced by [`WITHHELD`], because an unrecognized key or an invalid value
1105 /// is still text out of a file rumdl was merely pointed at. The message
1106 /// keeps saying what kind of problem it found and which file holds it, and
1107 /// leaves the rest to whoever can open that file.
1108 pub(crate) fn quote<'t>(&self, text: &'t str) -> &'t str {
1109 if self.may_quote_contents() { text } else { WITHHELD }
1110 }
1111}
1112
1113/// A config file as a message about it refers to it: the name to use, and
1114/// whether the file's own text may be shown alongside.
1115///
1116/// Pairs the display name, worked out once when a file is parsed, with the
1117/// [`ConfigOrigin`] that decided it. Every warning a parser emits names the file
1118/// and asks the same question about its contents, so both travel together rather
1119/// than as two parameters that could drift apart.
1120#[derive(Debug, Clone, Copy)]
1121pub(crate) struct ConfigRef<'a> {
1122 name: &'a str,
1123 origin: ConfigOrigin<'a>,
1124}
1125
1126impl<'a> ConfigRef<'a> {
1127 pub(crate) fn new(name: &'a str, origin: ConfigOrigin<'a>) -> Self {
1128 Self { name, origin }
1129 }
1130
1131 /// See [`ConfigOrigin::quote`].
1132 pub(crate) fn quote<'t>(&self, text: &'t str) -> &'t str {
1133 self.origin.quote(text)
1134 }
1135
1136 /// See [`ConfigOrigin::may_quote_contents`].
1137 pub(crate) fn may_quote_contents(&self) -> bool {
1138 self.origin.may_quote_contents()
1139 }
1140}
1141
1142/// Displays as the file's name, so a message can name the file by interpolating
1143/// the reference itself.
1144impl std::fmt::Display for ConfigRef<'_> {
1145 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1146 f.write_str(self.name)
1147 }
1148}
1149
1150/// Errors that can occur when loading configuration
1151#[derive(Debug, thiserror::Error)]
1152pub enum ConfigError {
1153 /// Failed to read the configuration file
1154 #[error("Failed to read config file at {path}: {source}")]
1155 IoError { source: io::Error, path: String },
1156
1157 /// Failed to parse the configuration content (TOML or JSON)
1158 #[error("Failed to parse config: {0}")]
1159 ParseError(String),
1160
1161 /// Configuration file already exists
1162 #[error("Configuration file already exists at {path}")]
1163 FileExists { path: String },
1164
1165 /// Circular extends reference detected
1166 #[error("Circular extends reference: {path} already in chain {chain:?}")]
1167 CircularExtends { path: String, chain: Vec<String> },
1168
1169 /// Extends chain exceeds maximum depth
1170 #[error("Extends chain exceeds maximum depth of {max_depth} at {path}")]
1171 ExtendsDepthExceeded { path: String, max_depth: usize },
1172
1173 /// Extends target file not found
1174 #[error("extends target not found: {path} (referenced from {from})")]
1175 ExtendsNotFound { path: String, from: String },
1176
1177 /// An `extends` path referenced an environment variable that is not set
1178 #[error("extends path references undefined environment variable {var} (referenced from {from})")]
1179 ExtendsUndefinedVar {
1180 /// The variable as the message may name it: `$NAME`, or [`WITHHELD`] when
1181 /// the file that wrote it was itself reached through `extends` and its
1182 /// text may not be repeated.
1183 var: String,
1184 from: String,
1185 },
1186
1187 /// Unknown preset name
1188 #[error("Unknown preset: {name}. Valid presets: default, google, relaxed")]
1189 UnknownPreset { name: String },
1190}
1191
1192/// Why a config file found by discovery could not be loaded.
1193///
1194/// The two cases call for different handling. A discovered project file that
1195/// cannot be parsed is local to one project and a caller may reasonably skip it
1196/// and keep looking. A broken user config is machine-wide: every project that
1197/// merges onto it resolves to something other than what the user configured, so
1198/// it has to be surfaced instead of worked around.
1199#[derive(Debug, thiserror::Error)]
1200pub enum DiscoveredConfigError {
1201 /// The discovered file itself is unusable.
1202 #[error(transparent)]
1203 ProjectConfig(ConfigError),
1204
1205 /// The discovered file is fine, but the user config it merges on top of is
1206 /// unusable. Only a discovered markdownlint config has such a base.
1207 #[error(transparent)]
1208 UserConfig(ConfigError),
1209}
1210
1211impl From<DiscoveredConfigError> for ConfigError {
1212 fn from(error: DiscoveredConfigError) -> Self {
1213 match error {
1214 DiscoveredConfigError::ProjectConfig(error) | DiscoveredConfigError::UserConfig(error) => error,
1215 }
1216 }
1217}
1218
1219/// Get a rule-specific configuration value
1220/// Automatically tries both the original key and normalized variants (kebab-case ↔ snake_case)
1221/// for better markdownlint compatibility
1222pub fn get_rule_config_value<T: serde::de::DeserializeOwned>(config: &Config, rule_name: &str, key: &str) -> Option<T> {
1223 let norm_rule_name = rule_name.to_ascii_uppercase(); // Use uppercase for lookup
1224
1225 let rule_config = config.rules.get(&norm_rule_name)?;
1226
1227 // Try multiple key variants to support both underscore and kebab-case formats
1228 let key_variants = [
1229 key.to_string(), // Original key as provided
1230 normalize_key(key), // Normalized key (lowercase, kebab-case)
1231 key.replace('-', "_"), // Convert kebab-case to snake_case
1232 key.replace('_', "-"), // Convert snake_case to kebab-case
1233 ];
1234
1235 // Try each variant until we find a match
1236 for variant in &key_variants {
1237 if let Some(value) = rule_config.values.get(variant)
1238 && let Ok(result) = T::deserialize(value.clone())
1239 {
1240 return Some(result);
1241 }
1242 }
1243
1244 None
1245}
1246
1247/// Generate preset configuration for pyproject.toml format.
1248/// Converts the .rumdl.toml preset to pyproject.toml section format.
1249pub fn generate_pyproject_preset_config(preset: &str) -> Result<String, ConfigError> {
1250 match preset {
1251 "default" => Ok(generate_pyproject_config()),
1252 other => {
1253 let rumdl_config = match other {
1254 "google" => generate_google_preset(),
1255 "relaxed" => generate_relaxed_preset(),
1256 _ => {
1257 return Err(ConfigError::UnknownPreset {
1258 name: other.to_string(),
1259 });
1260 }
1261 };
1262 Ok(convert_rumdl_to_pyproject(&rumdl_config))
1263 }
1264 }
1265}
1266
1267/// Convert a .rumdl.toml config string to pyproject.toml format.
1268/// Rewrites `[global]` → `[tool.rumdl]` and `[MDXXX]` → `[tool.rumdl.MDXXX]`.
1269fn convert_rumdl_to_pyproject(rumdl_config: &str) -> String {
1270 let mut output = String::with_capacity(rumdl_config.len() + 128);
1271 for line in rumdl_config.lines() {
1272 let trimmed = line.trim();
1273 if trimmed.starts_with('[') && trimmed.ends_with(']') && !trimmed.starts_with("# [") {
1274 let section = &trimmed[1..trimmed.len() - 1];
1275 if section == "global" {
1276 output.push_str("[tool.rumdl]");
1277 } else {
1278 output.push_str(&format!("[tool.rumdl.{section}]"));
1279 }
1280 } else {
1281 output.push_str(line);
1282 }
1283 output.push('\n');
1284 }
1285 output
1286}
1287
1288/// Generate default rumdl configuration for pyproject.toml
1289pub fn generate_pyproject_config() -> String {
1290 let config_content = r#"
1291[tool.rumdl]
1292# Global configuration options
1293line-length = 100
1294disable = []
1295# extend-enable = ["MD060"] # Add opt-in rules (additive, keeps defaults)
1296# extend-disable = [] # Additional rules to disable (additive)
1297exclude = [
1298 # Common directories to exclude
1299 ".git",
1300 ".github",
1301 "node_modules",
1302 "vendor",
1303 "dist",
1304 "build",
1305]
1306respect-gitignore = true
1307
1308# Rule-specific configurations (uncomment and modify as needed)
1309
1310# [tool.rumdl.MD003]
1311# style = "atx" # Heading style (atx, atx_closed, setext)
1312
1313# [tool.rumdl.MD004]
1314# style = "asterisk" # Unordered list style (asterisk, plus, dash, consistent)
1315
1316# [tool.rumdl.MD007]
1317# indent = 4 # Unordered list indentation
1318
1319# [tool.rumdl.MD013]
1320# line-length = 100 # Line length
1321# code-blocks = false # Exclude code blocks from line length check
1322# tables = false # Exclude tables from line length check
1323# headings = true # Include headings in line length check
1324
1325# [tool.rumdl.MD044]
1326# names = ["rumdl", "Markdown", "GitHub"] # Proper names that should be capitalized correctly
1327# code-blocks = false # Check code blocks for proper names (default: false, skips code blocks)
1328"#;
1329
1330 config_content.to_string()
1331}