rumdl_lib/rules/
md057_existing_relative_links.rs1use crate::rule::{LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
7use crate::utils::element_cache::ElementCache;
8use lazy_static::lazy_static;
9use regex::Regex;
10use std::collections::HashMap;
11use std::env;
12use std::path::{Path, PathBuf};
13use std::sync::{Arc, Mutex};
14
15mod md057_config;
16use md057_config::MD057Config;
17
18lazy_static! {
20 static ref FILE_EXISTENCE_CACHE: Arc<Mutex<HashMap<PathBuf, bool>>> = Arc::new(Mutex::new(HashMap::new()));
21}
22
23fn reset_file_existence_cache() {
25 let mut cache = FILE_EXISTENCE_CACHE.lock().unwrap();
26 cache.clear();
27}
28
29fn file_exists_with_cache(path: &Path) -> bool {
31 let mut cache = FILE_EXISTENCE_CACHE.lock().unwrap();
32 *cache.entry(path.to_path_buf()).or_insert_with(|| path.exists())
33}
34
35lazy_static! {
36 static ref LINK_START_REGEX: Regex =
38 Regex::new(r"!?\[[^\]]*\]").unwrap();
39
40 static ref URL_EXTRACT_REGEX: Regex =
43 Regex::new("\\]\\(\\s*<?([^>\\)\\s#]+)(#[^)\\s]*)?\\s*(?:\"[^\"]*\")?\\s*>?\\s*\\)").unwrap();
44
45 static ref CODE_FENCE_REGEX: Regex =
47 Regex::new(r"^( {0,3})(`{3,}|~{3,})").unwrap();
48
49 static ref PROTOCOL_DOMAIN_REGEX: Regex =
51 Regex::new(r"^(https?://|ftp://|mailto:|www\.)").unwrap();
52
53 static ref MEDIA_FILE_REGEX: Regex =
55 Regex::new(r"\.(jpg|jpeg|png|gif|bmp|svg|webp|tiff|mp3|mp4|avi|mov|webm|wav|ogg|pdf)$").unwrap();
56
57 static ref FRAGMENT_ONLY_REGEX: Regex =
59 Regex::new(r"^#").unwrap();
60
61 static ref CURRENT_DIR: PathBuf = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
63}
64
65#[derive(Debug, Default, Clone)]
67pub struct MD057ExistingRelativeLinks {
68 base_path: Arc<Mutex<Option<PathBuf>>>,
70 config: MD057Config,
72}
73
74impl MD057ExistingRelativeLinks {
75 pub fn new() -> Self {
77 Self::default()
78 }
79
80 pub fn with_path<P: AsRef<Path>>(self, path: P) -> Self {
82 let path = path.as_ref();
83 let dir_path = if path.is_file() {
84 path.parent().map(|p| p.to_path_buf())
85 } else {
86 Some(path.to_path_buf())
87 };
88
89 *self.base_path.lock().unwrap() = dir_path;
90 self
91 }
92
93 pub fn with_skip_media_files(mut self, skip_media_files: bool) -> Self {
95 self.config.skip_media_files = skip_media_files;
96 self
97 }
98
99 pub fn from_config_struct(config: MD057Config) -> Self {
100 Self {
101 base_path: Arc::new(Mutex::new(None)),
102 config,
103 }
104 }
105
106 #[inline]
108 fn is_external_url(&self, url: &str) -> bool {
109 if url.is_empty() {
110 return false;
111 }
112
113 if PROTOCOL_DOMAIN_REGEX.is_match(url) || url.starts_with("www.") {
115 return true;
116 }
117
118 if !self.is_media_file(url) && url.ends_with(".com") {
120 return true;
121 }
122
123 if url.starts_with('/') {
125 return false;
126 }
127
128 false
130 }
131
132 #[inline]
134 fn is_fragment_only_link(&self, url: &str) -> bool {
135 url.starts_with('#')
136 }
137
138 #[inline]
140 fn is_media_file(&self, url: &str) -> bool {
141 if !url.contains('.') {
143 return false;
144 }
145 MEDIA_FILE_REGEX.is_match(url)
146 }
147
148 #[inline]
150 fn should_skip_media_file(&self, url: &str) -> bool {
151 self.config.skip_media_files && self.is_media_file(url)
152 }
153
154 fn resolve_link_path(&self, link: &str) -> Option<PathBuf> {
156 self.base_path
157 .lock()
158 .unwrap()
159 .as_ref()
160 .map(|base_path| base_path.join(link))
161 }
162
163 fn process_link(&self, url: &str, line_num: usize, column: usize, warnings: &mut Vec<LintWarning>) {
165 if url.is_empty() {
167 return;
168 }
169
170 if self.is_external_url(url) || self.is_fragment_only_link(url) {
172 return;
173 }
174
175 if self.should_skip_media_file(url) {
177 return;
178 }
179
180 if let Some(resolved_path) = self.resolve_link_path(url) {
182 if !file_exists_with_cache(&resolved_path) {
184 warnings.push(LintWarning {
185 rule_name: Some(self.name()),
186 line: line_num,
187 column,
188 end_line: line_num,
189 end_column: column + url.len(),
190 message: format!("Relative link '{url}' does not exist"),
191 severity: Severity::Warning,
192 fix: None, });
194 }
195 }
196 }
197}
198
199impl Rule for MD057ExistingRelativeLinks {
200 fn name(&self) -> &'static str {
201 "MD057"
202 }
203
204 fn description(&self) -> &'static str {
205 "Relative links should point to existing files"
206 }
207
208 fn category(&self) -> RuleCategory {
209 RuleCategory::Link
210 }
211
212 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
213 ctx.content.is_empty() || !ctx.likely_has_links_or_images()
214 }
215
216 fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
217 let content = ctx.content;
218
219 if content.is_empty() || !content.contains('[') {
221 return Ok(Vec::new());
222 }
223
224 if !content.contains("](") {
226 return Ok(Vec::new());
227 }
228
229 reset_file_existence_cache();
231
232 let mut warnings = Vec::new();
233
234 let base_path = {
236 let base_path_guard = self.base_path.lock().unwrap();
237 if base_path_guard.is_some() {
238 base_path_guard.clone()
239 } else {
240 static CACHED_FILE_PATH: std::sync::OnceLock<Option<PathBuf>> = std::sync::OnceLock::new();
242 CACHED_FILE_PATH
243 .get_or_init(|| {
244 if let Ok(file_path) = env::var("RUMDL_FILE_PATH") {
245 let path = Path::new(&file_path);
246 if path.exists() {
247 path.parent()
248 .map(|p| p.to_path_buf())
249 .or_else(|| Some(CURRENT_DIR.clone()))
250 } else {
251 Some(CURRENT_DIR.clone())
252 }
253 } else {
254 Some(CURRENT_DIR.clone())
255 }
256 })
257 .clone()
258 }
259 };
260
261 if base_path.is_none() {
263 return Ok(warnings);
264 }
265
266 if !ctx.links.is_empty() {
268 let mut line_positions = Vec::new();
270 let mut pos = 0;
271 line_positions.push(0);
272 for ch in content.chars() {
273 pos += ch.len_utf8();
274 if ch == '\n' {
275 line_positions.push(pos);
276 }
277 }
278
279 let element_cache = ElementCache::new(content);
281
282 let lines: Vec<&str> = content.lines().collect();
284
285 for link in &ctx.links {
286 let line_idx = link.line - 1;
287 if line_idx >= lines.len() {
288 continue;
289 }
290
291 let line = lines[line_idx];
292
293 if !line.contains("](") {
295 continue;
296 }
297
298 for link_match in LINK_START_REGEX.find_iter(line) {
300 let start_pos = link_match.start();
301 let end_pos = link_match.end();
302
303 let absolute_start_pos = if line_idx < line_positions.len() {
305 line_positions[line_idx] + start_pos
306 } else {
307 content.lines().take(line_idx).map(|l| l.len() + 1).sum::<usize>() + start_pos
309 };
310
311 if element_cache.is_in_code_span(absolute_start_pos) {
313 continue;
314 }
315
316 if let Some(caps) = URL_EXTRACT_REGEX.captures_at(line, end_pos - 1)
318 && let Some(url_group) = caps.get(1)
319 {
320 let url = url_group.as_str().trim();
321
322 let column = start_pos + 1;
324
325 self.process_link(url, link.line, column, &mut warnings);
327 }
328 }
329 }
330 }
331
332 Ok(warnings)
333 }
334
335 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
336 Ok(ctx.content.to_string())
337 }
338
339 fn as_any(&self) -> &dyn std::any::Any {
340 self
341 }
342
343 fn default_config_section(&self) -> Option<(String, toml::Value)> {
344 let json_value = serde_json::to_value(&self.config).ok()?;
345 Some((
346 self.name().to_string(),
347 crate::rule_config_serde::json_to_toml_value(&json_value)?,
348 ))
349 }
350
351 fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
352 where
353 Self: Sized,
354 {
355 let rule_config = crate::rule_config_serde::load_rule_config::<MD057Config>(config);
356 Box::new(Self::from_config_struct(rule_config))
357 }
358}
359
360#[cfg(test)]
361mod tests {
362 use super::*;
363 use std::fs::File;
364 use std::io::Write;
365 use tempfile::tempdir;
366
367 #[test]
368 fn test_external_urls() {
369 let rule = MD057ExistingRelativeLinks::new();
370
371 assert!(rule.is_external_url("https://example.com"));
372 assert!(rule.is_external_url("http://example.com"));
373 assert!(rule.is_external_url("ftp://example.com"));
374 assert!(rule.is_external_url("www.example.com"));
375 assert!(rule.is_external_url("example.com"));
376
377 assert!(!rule.is_external_url("./relative/path.md"));
378 assert!(!rule.is_external_url("relative/path.md"));
379 assert!(!rule.is_external_url("../parent/path.md"));
380 }
381
382 #[test]
383 fn test_media_files() {
384 let rule_default = MD057ExistingRelativeLinks::new();
386
387 assert!(
389 rule_default.is_media_file("image.jpg"),
390 "image.jpg should be identified as a media file"
391 );
392 assert!(
393 rule_default.is_media_file("video.mp4"),
394 "video.mp4 should be identified as a media file"
395 );
396 assert!(
397 rule_default.is_media_file("document.pdf"),
398 "document.pdf should be identified as a media file"
399 );
400 assert!(
401 rule_default.is_media_file("path/to/audio.mp3"),
402 "path/to/audio.mp3 should be identified as a media file"
403 );
404
405 assert!(
406 !rule_default.is_media_file("document.md"),
407 "document.md should not be identified as a media file"
408 );
409 assert!(
410 !rule_default.is_media_file("code.rs"),
411 "code.rs should not be identified as a media file"
412 );
413
414 assert!(
416 rule_default.should_skip_media_file("image.jpg"),
417 "image.jpg should be skipped with default settings"
418 );
419 assert!(
420 !rule_default.should_skip_media_file("document.md"),
421 "document.md should not be skipped"
422 );
423
424 let rule_no_skip = MD057ExistingRelativeLinks::new().with_skip_media_files(false);
426 assert!(
427 !rule_no_skip.should_skip_media_file("image.jpg"),
428 "image.jpg should not be skipped when skip_media_files is false"
429 );
430 }
431
432 #[test]
433 fn test_no_warnings_without_base_path() {
434 let rule = MD057ExistingRelativeLinks::new();
435 let content = "[Link](missing.md)";
436
437 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
438 let result = rule.check(&ctx).unwrap();
439 assert!(result.is_empty(), "Should have no warnings without base path");
440 }
441
442 #[test]
443 fn test_existing_and_missing_links() {
444 let temp_dir = tempdir().unwrap();
446 let base_path = temp_dir.path();
447
448 let exists_path = base_path.join("exists.md");
450 File::create(&exists_path).unwrap().write_all(b"# Test File").unwrap();
451
452 assert!(exists_path.exists(), "exists.md should exist for this test");
454
455 let content = r#"
457# Test Document
458
459[Valid Link](exists.md)
460[Invalid Link](missing.md)
461[External Link](https://example.com)
462[Media Link](image.jpg)
463 "#;
464
465 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
467
468 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
470 let result = rule.check(&ctx).unwrap();
471
472 assert_eq!(result.len(), 1);
474 assert!(result[0].message.contains("missing.md"));
475
476 let result_with_structure = rule.check(&ctx).unwrap();
478
479 assert_eq!(result.len(), result_with_structure.len());
481 assert!(result_with_structure[0].message.contains("missing.md"));
482 }
483
484 #[test]
485 fn test_angle_bracket_links() {
486 let temp_dir = tempdir().unwrap();
488 let base_path = temp_dir.path();
489
490 let exists_path = base_path.join("exists.md");
492 File::create(&exists_path).unwrap().write_all(b"# Test File").unwrap();
493
494 let content = r#"
496# Test Document
497
498[Valid Link](<exists.md>)
499[Invalid Link](<missing.md>)
500[External Link](<https://example.com>)
501 "#;
502
503 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
505
506 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
507 let result = rule.check(&ctx).unwrap();
508
509 assert_eq!(result.len(), 1, "Should have exactly one warning");
511 assert!(
512 result[0].message.contains("missing.md"),
513 "Warning should mention missing.md"
514 );
515 }
516
517 #[test]
518 fn test_media_file_handling() {
519 let temp_dir = tempdir().unwrap();
521 let base_path = temp_dir.path();
522
523 let image_path = base_path.join("image.jpg");
525 assert!(
526 !image_path.exists(),
527 "Test precondition failed: image.jpg should not exist"
528 );
529
530 let content = "[Media Link](image.jpg)";
532
533 let rule_skip_media = MD057ExistingRelativeLinks::new().with_path(base_path);
535
536 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
537 let result_skip = rule_skip_media.check(&ctx).unwrap();
538
539 assert_eq!(
541 result_skip.len(),
542 0,
543 "Should have no warnings when skip_media_files is true"
544 );
545
546 let rule_check_all = MD057ExistingRelativeLinks::new()
548 .with_path(base_path)
549 .with_skip_media_files(false);
550
551 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
552 let result_all = rule_check_all.check(&ctx).unwrap();
553
554 assert_eq!(
556 result_all.len(),
557 1,
558 "Should have one warning when skip_media_files is false"
559 );
560 assert!(
561 result_all[0].message.contains("image.jpg"),
562 "Warning should mention image.jpg"
563 );
564 }
565
566 #[test]
567 fn test_code_span_detection() {
568 let rule = MD057ExistingRelativeLinks::new();
569
570 let temp_dir = tempdir().unwrap();
572 let base_path = temp_dir.path();
573
574 let rule = rule.with_path(base_path);
575
576 let content = "This is a [link](nonexistent.md) and `[not a link](not-checked.md)` in code.";
578
579 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
580 let result = rule.check(&ctx).unwrap();
581
582 assert_eq!(result.len(), 1, "Should only flag the real link");
584 assert!(result[0].message.contains("nonexistent.md"));
585 }
586
587 #[test]
588 fn test_inline_code_spans() {
589 let temp_dir = tempdir().unwrap();
591 let base_path = temp_dir.path();
592
593 let content = r#"
595# Test Document
596
597This is a normal link: [Link](missing.md)
598
599This is a code span with a link: `[Link](another-missing.md)`
600
601Some more text with `inline code [Link](yet-another-missing.md) embedded`.
602
603 "#;
604
605 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
607
608 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
610 let result = rule.check(&ctx).unwrap();
611
612 assert_eq!(result.len(), 1, "Should have exactly one warning");
614 assert!(
615 result[0].message.contains("missing.md"),
616 "Warning should be for missing.md"
617 );
618 assert!(
619 !result.iter().any(|w| w.message.contains("another-missing.md")),
620 "Should not warn about link in code span"
621 );
622 assert!(
623 !result.iter().any(|w| w.message.contains("yet-another-missing.md")),
624 "Should not warn about link in inline code"
625 );
626 }
627}