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 #[serde(skip)]
405 pub enable_is_explicit: bool,
406}
407
408fn default_respect_gitignore() -> bool {
409 true
410}
411
412fn default_true() -> bool {
413 true
414}
415
416impl Default for GlobalConfig {
418 #[allow(deprecated)]
419 fn default() -> Self {
420 Self {
421 enable: Vec::new(),
422 disable: Vec::new(),
423 exclude: Vec::new(),
424 include: Vec::new(),
425 respect_gitignore: true,
426 line_length: LineLength::default(),
427 output_format: None,
428 fixable: Vec::new(),
429 unfixable: Vec::new(),
430 flavor: MarkdownFlavor::default(),
431 force_exclude: false,
432 cache_dir: None,
433 cache: true,
434 enable_is_explicit: false,
435 }
436 }
437}
438
439pub(super) const MARKDOWNLINT_CONFIG_FILES: &[&str] = &[
440 ".markdownlint.json",
441 ".markdownlint.jsonc",
442 ".markdownlint.yaml",
443 ".markdownlint.yml",
444 "markdownlint.json",
445 "markdownlint.jsonc",
446 "markdownlint.yaml",
447 "markdownlint.yml",
448];
449
450pub fn create_default_config(path: &str) -> Result<(), ConfigError> {
452 if Path::new(path).exists() {
454 return Err(ConfigError::FileExists { path: path.to_string() });
455 }
456
457 let default_config = r#"# rumdl configuration file
459
460# Global configuration options
461[global]
462# List of rules to disable (uncomment and modify as needed)
463# disable = ["MD013", "MD033"]
464
465# List of rules to enable exclusively (if provided, only these rules will run)
466# enable = ["MD001", "MD003", "MD004"]
467
468# List of file/directory patterns to include for linting (if provided, only these will be linted)
469# include = [
470# "docs/*.md",
471# "src/**/*.md",
472# "README.md"
473# ]
474
475# List of file/directory patterns to exclude from linting
476exclude = [
477 # Common directories to exclude
478 ".git",
479 ".github",
480 "node_modules",
481 "vendor",
482 "dist",
483 "build",
484
485 # Specific files or patterns
486 "CHANGELOG.md",
487 "LICENSE.md",
488]
489
490# Respect .gitignore files when scanning directories (default: true)
491respect-gitignore = true
492
493# Markdown flavor/dialect (uncomment to enable)
494# Options: standard (default), gfm, commonmark, mkdocs, mdx, quarto
495# flavor = "mkdocs"
496
497# Rule-specific configurations (uncomment and modify as needed)
498
499# [MD003]
500# style = "atx" # Heading style (atx, atx_closed, setext)
501
502# [MD004]
503# style = "asterisk" # Unordered list style (asterisk, plus, dash, consistent)
504
505# [MD007]
506# indent = 4 # Unordered list indentation
507
508# [MD013]
509# line-length = 100 # Line length
510# code-blocks = false # Exclude code blocks from line length check
511# tables = false # Exclude tables from line length check
512# headings = true # Include headings in line length check
513
514# [MD044]
515# names = ["rumdl", "Markdown", "GitHub"] # Proper names that should be capitalized correctly
516# code-blocks = false # Check code blocks for proper names (default: false, skips code blocks)
517"#;
518
519 match fs::write(path, default_config) {
521 Ok(_) => Ok(()),
522 Err(err) => Err(ConfigError::IoError {
523 source: err,
524 path: path.to_string(),
525 }),
526 }
527}
528
529#[derive(Debug, thiserror::Error)]
531pub enum ConfigError {
532 #[error("Failed to read config file at {path}: {source}")]
534 IoError { source: io::Error, path: String },
535
536 #[error("Failed to parse config: {0}")]
538 ParseError(String),
539
540 #[error("Configuration file already exists at {path}")]
542 FileExists { path: String },
543}
544
545pub fn get_rule_config_value<T: serde::de::DeserializeOwned>(config: &Config, rule_name: &str, key: &str) -> Option<T> {
549 let norm_rule_name = rule_name.to_ascii_uppercase(); let rule_config = config.rules.get(&norm_rule_name)?;
552
553 let key_variants = [
555 key.to_string(), normalize_key(key), key.replace('-', "_"), key.replace('_', "-"), ];
560
561 for variant in &key_variants {
563 if let Some(value) = rule_config.values.get(variant)
564 && let Ok(result) = T::deserialize(value.clone())
565 {
566 return Some(result);
567 }
568 }
569
570 None
571}
572
573pub fn generate_pyproject_config() -> String {
575 let config_content = r#"
576[tool.rumdl]
577# Global configuration options
578line-length = 100
579disable = []
580exclude = [
581 # Common directories to exclude
582 ".git",
583 ".github",
584 "node_modules",
585 "vendor",
586 "dist",
587 "build",
588]
589respect-gitignore = true
590
591# Rule-specific configurations (uncomment and modify as needed)
592
593# [tool.rumdl.MD003]
594# style = "atx" # Heading style (atx, atx_closed, setext)
595
596# [tool.rumdl.MD004]
597# style = "asterisk" # Unordered list style (asterisk, plus, dash, consistent)
598
599# [tool.rumdl.MD007]
600# indent = 4 # Unordered list indentation
601
602# [tool.rumdl.MD013]
603# line-length = 100 # Line length
604# code-blocks = false # Exclude code blocks from line length check
605# tables = false # Exclude tables from line length check
606# headings = true # Include headings in line length check
607
608# [tool.rumdl.MD044]
609# names = ["rumdl", "Markdown", "GitHub"] # Proper names that should be capitalized correctly
610# code-blocks = false # Check code blocks for proper names (default: false, skips code blocks)
611"#;
612
613 config_content.to_string()
614}