1use crate::types::LineLength;
2use globset::{Glob, GlobBuilder, GlobMatcher, GlobSet, GlobSetBuilder};
3use indexmap::IndexMap;
4use serde::{Deserialize, Serialize};
5use std::collections::BTreeMap;
6use std::collections::{HashMap, HashSet};
7use std::fs;
8use std::io;
9use std::path::Path;
10use std::sync::{Arc, OnceLock};
11
12use super::flavor::{MarkdownFlavor, normalize_key};
13
14#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, schemars::JsonSchema)]
16pub struct RuleConfig {
17 #[serde(default, skip_serializing_if = "Option::is_none")]
19 pub severity: Option<crate::rule::Severity>,
20
21 #[serde(flatten)]
23 #[schemars(schema_with = "arbitrary_value_schema")]
24 pub values: BTreeMap<String, toml::Value>,
25}
26
27fn arbitrary_value_schema(_gen: &mut schemars::SchemaGenerator) -> schemars::Schema {
29 schemars::json_schema!({
30 "type": "object",
31 "additionalProperties": true
32 })
33}
34
35#[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 #[serde(default)]
43 pub global: GlobalConfig,
44
45 #[serde(default, rename = "per-file-ignores")]
48 pub per_file_ignores: HashMap<String, Vec<String>>,
49
50 #[serde(default, rename = "per-file-flavor")]
54 #[schemars(with = "HashMap<String, MarkdownFlavor>")]
55 pub per_file_flavor: IndexMap<String, MarkdownFlavor>,
56
57 #[serde(default, rename = "code-block-tools")]
60 pub code_block_tools: crate::code_block_tools::CodeBlockToolsConfig,
61
62 #[serde(flatten)]
73 pub rules: BTreeMap<String, RuleConfig>,
74
75 #[serde(skip)]
77 pub project_root: Option<std::path::PathBuf>,
78
79 #[serde(skip)]
80 #[schemars(skip)]
81 pub(super) per_file_ignores_cache: Arc<OnceLock<PerFileIgnoreCache>>,
82
83 #[serde(skip)]
84 #[schemars(skip)]
85 pub(super) per_file_flavor_cache: Arc<OnceLock<PerFileFlavorCache>>,
86}
87
88impl PartialEq for Config {
89 fn eq(&self, other: &Self) -> bool {
90 self.global == other.global
91 && self.per_file_ignores == other.per_file_ignores
92 && self.per_file_flavor == other.per_file_flavor
93 && self.code_block_tools == other.code_block_tools
94 && self.rules == other.rules
95 && self.project_root == other.project_root
96 }
97}
98
99#[derive(Debug)]
100pub(super) struct PerFileIgnoreCache {
101 globset: GlobSet,
102 rules: Vec<Vec<String>>,
103}
104
105#[derive(Debug)]
106pub(super) struct PerFileFlavorCache {
107 matchers: Vec<(GlobMatcher, MarkdownFlavor)>,
108}
109
110impl Config {
111 pub fn is_mkdocs_flavor(&self) -> bool {
113 self.global.flavor == MarkdownFlavor::MkDocs
114 }
115
116 pub fn markdown_flavor(&self) -> MarkdownFlavor {
122 self.global.flavor
123 }
124
125 pub fn is_mkdocs_project(&self) -> bool {
127 self.is_mkdocs_flavor()
128 }
129
130 pub fn get_rule_severity(&self, rule_name: &str) -> Option<crate::rule::Severity> {
132 self.rules.get(rule_name).and_then(|r| r.severity)
133 }
134
135 pub fn get_ignored_rules_for_file(&self, file_path: &Path) -> HashSet<String> {
138 let mut ignored_rules = HashSet::new();
139
140 if self.per_file_ignores.is_empty() {
141 return ignored_rules;
142 }
143
144 let path_for_matching: std::borrow::Cow<'_, Path> = if let Some(ref root) = self.project_root {
147 if let Ok(canonical_path) = file_path.canonicalize() {
148 if let Ok(canonical_root) = root.canonicalize() {
149 if let Ok(relative) = canonical_path.strip_prefix(&canonical_root) {
150 std::borrow::Cow::Owned(relative.to_path_buf())
151 } else {
152 std::borrow::Cow::Borrowed(file_path)
153 }
154 } else {
155 std::borrow::Cow::Borrowed(file_path)
156 }
157 } else {
158 std::borrow::Cow::Borrowed(file_path)
159 }
160 } else {
161 std::borrow::Cow::Borrowed(file_path)
162 };
163
164 let cache = self
165 .per_file_ignores_cache
166 .get_or_init(|| PerFileIgnoreCache::new(&self.per_file_ignores));
167
168 for match_idx in cache.globset.matches(path_for_matching.as_ref()) {
170 if let Some(rules) = cache.rules.get(match_idx) {
171 for rule in rules.iter() {
172 ignored_rules.insert(rule.clone());
174 }
175 }
176 }
177
178 ignored_rules
179 }
180
181 pub fn get_flavor_for_file(&self, file_path: &Path) -> MarkdownFlavor {
185 if self.per_file_flavor.is_empty() {
187 return self.resolve_flavor_fallback(file_path);
188 }
189
190 let path_for_matching: std::borrow::Cow<'_, Path> = if let Some(ref root) = self.project_root {
192 if let Ok(canonical_path) = file_path.canonicalize() {
193 if let Ok(canonical_root) = root.canonicalize() {
194 if let Ok(relative) = canonical_path.strip_prefix(&canonical_root) {
195 std::borrow::Cow::Owned(relative.to_path_buf())
196 } else {
197 std::borrow::Cow::Borrowed(file_path)
198 }
199 } else {
200 std::borrow::Cow::Borrowed(file_path)
201 }
202 } else {
203 std::borrow::Cow::Borrowed(file_path)
204 }
205 } else {
206 std::borrow::Cow::Borrowed(file_path)
207 };
208
209 let cache = self
210 .per_file_flavor_cache
211 .get_or_init(|| PerFileFlavorCache::new(&self.per_file_flavor));
212
213 for (matcher, flavor) in &cache.matchers {
215 if matcher.is_match(path_for_matching.as_ref()) {
216 return *flavor;
217 }
218 }
219
220 self.resolve_flavor_fallback(file_path)
222 }
223
224 fn resolve_flavor_fallback(&self, file_path: &Path) -> MarkdownFlavor {
226 if self.global.flavor != MarkdownFlavor::Standard {
228 return self.global.flavor;
229 }
230 MarkdownFlavor::from_path(file_path)
232 }
233
234 pub fn merge_with_inline_config(&self, inline_config: &crate::inline_config::InlineConfig) -> Self {
242 let overrides = inline_config.get_all_rule_configs();
243 if overrides.is_empty() {
244 return self.clone();
245 }
246
247 let mut merged = self.clone();
248
249 for (rule_name, json_override) in overrides {
250 let rule_config = merged.rules.entry(rule_name.clone()).or_default();
252
253 if let Some(obj) = json_override.as_object() {
255 for (key, value) in obj {
256 let normalized_key = key.replace('_', "-");
258
259 if let Some(toml_value) = json_to_toml(value) {
261 rule_config.values.insert(normalized_key, toml_value);
262 }
263 }
264 }
265 }
266
267 merged
268 }
269}
270
271pub(super) fn json_to_toml(json: &serde_json::Value) -> Option<toml::Value> {
273 match json {
274 serde_json::Value::Null => None,
275 serde_json::Value::Bool(b) => Some(toml::Value::Boolean(*b)),
276 serde_json::Value::Number(n) => n
277 .as_i64()
278 .map(toml::Value::Integer)
279 .or_else(|| n.as_f64().map(toml::Value::Float)),
280 serde_json::Value::String(s) => Some(toml::Value::String(s.clone())),
281 serde_json::Value::Array(arr) => {
282 let toml_arr: Vec<toml::Value> = arr.iter().filter_map(json_to_toml).collect();
283 Some(toml::Value::Array(toml_arr))
284 }
285 serde_json::Value::Object(obj) => {
286 let mut table = toml::map::Map::new();
287 for (k, v) in obj {
288 if let Some(tv) = json_to_toml(v) {
289 table.insert(k.clone(), tv);
290 }
291 }
292 Some(toml::Value::Table(table))
293 }
294 }
295}
296
297impl PerFileIgnoreCache {
298 fn new(per_file_ignores: &HashMap<String, Vec<String>>) -> Self {
299 let mut builder = GlobSetBuilder::new();
300 let mut rules = Vec::new();
301
302 for (pattern, rules_list) in per_file_ignores {
303 if let Ok(glob) = Glob::new(pattern) {
304 builder.add(glob);
305 rules.push(rules_list.iter().map(|rule| normalize_key(rule)).collect());
306 } else {
307 log::warn!("Invalid glob pattern in per-file-ignores: {pattern}");
308 }
309 }
310
311 let globset = builder.build().unwrap_or_else(|e| {
312 log::error!("Failed to build globset for per-file-ignores: {e}");
313 GlobSetBuilder::new().build().unwrap()
314 });
315
316 Self { globset, rules }
317 }
318}
319
320impl PerFileFlavorCache {
321 fn new(per_file_flavor: &IndexMap<String, MarkdownFlavor>) -> Self {
322 let mut matchers = Vec::new();
323
324 for (pattern, flavor) in per_file_flavor {
325 if let Ok(glob) = GlobBuilder::new(pattern).literal_separator(true).build() {
326 matchers.push((glob.compile_matcher(), *flavor));
327 } else {
328 log::warn!("Invalid glob pattern in per-file-flavor: {pattern}");
329 }
330 }
331
332 Self { matchers }
333 }
334}
335
336#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
338#[serde(default, rename_all = "kebab-case")]
339pub struct GlobalConfig {
340 #[serde(default)]
342 pub enable: Vec<String>,
343
344 #[serde(default)]
346 pub disable: Vec<String>,
347
348 #[serde(default)]
350 pub exclude: Vec<String>,
351
352 #[serde(default)]
354 pub include: Vec<String>,
355
356 #[serde(default = "default_respect_gitignore", alias = "respect_gitignore")]
358 pub respect_gitignore: bool,
359
360 #[serde(default, alias = "line_length")]
362 pub line_length: LineLength,
363
364 #[serde(skip_serializing_if = "Option::is_none", alias = "output_format")]
366 pub output_format: Option<String>,
367
368 #[serde(default)]
371 pub fixable: Vec<String>,
372
373 #[serde(default)]
376 pub unfixable: Vec<String>,
377
378 #[serde(default)]
381 pub flavor: MarkdownFlavor,
382
383 #[serde(default, alias = "force_exclude")]
388 #[deprecated(since = "0.0.156", note = "Exclude patterns are now always respected")]
389 pub force_exclude: bool,
390
391 #[serde(default, alias = "cache_dir", skip_serializing_if = "Option::is_none")]
394 pub cache_dir: Option<String>,
395
396 #[serde(default = "default_true")]
399 pub cache: bool,
400}
401
402fn default_respect_gitignore() -> bool {
403 true
404}
405
406fn default_true() -> bool {
407 true
408}
409
410impl Default for GlobalConfig {
412 #[allow(deprecated)]
413 fn default() -> Self {
414 Self {
415 enable: Vec::new(),
416 disable: Vec::new(),
417 exclude: Vec::new(),
418 include: Vec::new(),
419 respect_gitignore: true,
420 line_length: LineLength::default(),
421 output_format: None,
422 fixable: Vec::new(),
423 unfixable: Vec::new(),
424 flavor: MarkdownFlavor::default(),
425 force_exclude: false,
426 cache_dir: None,
427 cache: true,
428 }
429 }
430}
431
432pub(super) const MARKDOWNLINT_CONFIG_FILES: &[&str] = &[
433 ".markdownlint.json",
434 ".markdownlint.jsonc",
435 ".markdownlint.yaml",
436 ".markdownlint.yml",
437 "markdownlint.json",
438 "markdownlint.jsonc",
439 "markdownlint.yaml",
440 "markdownlint.yml",
441];
442
443pub fn create_default_config(path: &str) -> Result<(), ConfigError> {
445 if Path::new(path).exists() {
447 return Err(ConfigError::FileExists { path: path.to_string() });
448 }
449
450 let default_config = r#"# rumdl configuration file
452
453# Global configuration options
454[global]
455# List of rules to disable (uncomment and modify as needed)
456# disable = ["MD013", "MD033"]
457
458# List of rules to enable exclusively (if provided, only these rules will run)
459# enable = ["MD001", "MD003", "MD004"]
460
461# List of file/directory patterns to include for linting (if provided, only these will be linted)
462# include = [
463# "docs/*.md",
464# "src/**/*.md",
465# "README.md"
466# ]
467
468# List of file/directory patterns to exclude from linting
469exclude = [
470 # Common directories to exclude
471 ".git",
472 ".github",
473 "node_modules",
474 "vendor",
475 "dist",
476 "build",
477
478 # Specific files or patterns
479 "CHANGELOG.md",
480 "LICENSE.md",
481]
482
483# Respect .gitignore files when scanning directories (default: true)
484respect-gitignore = true
485
486# Markdown flavor/dialect (uncomment to enable)
487# Options: standard (default), gfm, commonmark, mkdocs, mdx, quarto
488# flavor = "mkdocs"
489
490# Rule-specific configurations (uncomment and modify as needed)
491
492# [MD003]
493# style = "atx" # Heading style (atx, atx_closed, setext)
494
495# [MD004]
496# style = "asterisk" # Unordered list style (asterisk, plus, dash, consistent)
497
498# [MD007]
499# indent = 4 # Unordered list indentation
500
501# [MD013]
502# line-length = 100 # Line length
503# code-blocks = false # Exclude code blocks from line length check
504# tables = false # Exclude tables from line length check
505# headings = true # Include headings in line length check
506
507# [MD044]
508# names = ["rumdl", "Markdown", "GitHub"] # Proper names that should be capitalized correctly
509# code-blocks = false # Check code blocks for proper names (default: false, skips code blocks)
510"#;
511
512 match fs::write(path, default_config) {
514 Ok(_) => Ok(()),
515 Err(err) => Err(ConfigError::IoError {
516 source: err,
517 path: path.to_string(),
518 }),
519 }
520}
521
522#[derive(Debug, thiserror::Error)]
524pub enum ConfigError {
525 #[error("Failed to read config file at {path}: {source}")]
527 IoError { source: io::Error, path: String },
528
529 #[error("Failed to parse config: {0}")]
531 ParseError(String),
532
533 #[error("Configuration file already exists at {path}")]
535 FileExists { path: String },
536}
537
538pub fn get_rule_config_value<T: serde::de::DeserializeOwned>(config: &Config, rule_name: &str, key: &str) -> Option<T> {
542 let norm_rule_name = rule_name.to_ascii_uppercase(); let rule_config = config.rules.get(&norm_rule_name)?;
545
546 let key_variants = [
548 key.to_string(), normalize_key(key), key.replace('-', "_"), key.replace('_', "-"), ];
553
554 for variant in &key_variants {
556 if let Some(value) = rule_config.values.get(variant)
557 && let Ok(result) = T::deserialize(value.clone())
558 {
559 return Some(result);
560 }
561 }
562
563 None
564}
565
566pub fn generate_pyproject_config() -> String {
568 let config_content = r#"
569[tool.rumdl]
570# Global configuration options
571line-length = 100
572disable = []
573exclude = [
574 # Common directories to exclude
575 ".git",
576 ".github",
577 "node_modules",
578 "vendor",
579 "dist",
580 "build",
581]
582respect-gitignore = true
583
584# Rule-specific configurations (uncomment and modify as needed)
585
586# [tool.rumdl.MD003]
587# style = "atx" # Heading style (atx, atx_closed, setext)
588
589# [tool.rumdl.MD004]
590# style = "asterisk" # Unordered list style (asterisk, plus, dash, consistent)
591
592# [tool.rumdl.MD007]
593# indent = 4 # Unordered list indentation
594
595# [tool.rumdl.MD013]
596# line-length = 100 # Line length
597# code-blocks = false # Exclude code blocks from line length check
598# tables = false # Exclude tables from line length check
599# headings = true # Include headings in line length check
600
601# [tool.rumdl.MD044]
602# names = ["rumdl", "Markdown", "GitHub"] # Proper names that should be capitalized correctly
603# code-blocks = false # Check code blocks for proper names (default: false, skips code blocks)
604"#;
605
606 config_content.to_string()
607}