1use crate::rule::{CrossFileScope, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
7use crate::utils::element_cache::ElementCache;
8use crate::workspace_index::{CrossFileLinkIndex, FileIndex};
9use regex::Regex;
10use std::collections::HashMap;
11use std::env;
12use std::path::{Path, PathBuf};
13use std::sync::LazyLock;
14use std::sync::{Arc, Mutex};
15
16mod md057_config;
17use md057_config::MD057Config;
18
19static FILE_EXISTENCE_CACHE: LazyLock<Arc<Mutex<HashMap<PathBuf, bool>>>> =
21 LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));
22
23fn reset_file_existence_cache() {
25 let mut cache = FILE_EXISTENCE_CACHE
26 .lock()
27 .expect("File existence cache mutex poisoned");
28 cache.clear();
29}
30
31fn file_exists_with_cache(path: &Path) -> bool {
33 let mut cache = FILE_EXISTENCE_CACHE
34 .lock()
35 .expect("File existence cache mutex poisoned");
36 *cache.entry(path.to_path_buf()).or_insert_with(|| path.exists())
37}
38
39static LINK_START_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"!?\[[^\]]*\]").unwrap());
41
42static URL_EXTRACT_REGEX: LazyLock<Regex> =
45 LazyLock::new(|| Regex::new("\\]\\(\\s*<?([^>\\)\\s#]+)(#[^)\\s]*)?\\s*(?:\"[^\"]*\")?\\s*>?\\s*\\)").unwrap());
46
47static PROTOCOL_DOMAIN_REGEX: LazyLock<Regex> =
49 LazyLock::new(|| Regex::new(r"^(https?://|ftp://|mailto:|www\.)").unwrap());
50
51static CURRENT_DIR: LazyLock<PathBuf> = LazyLock::new(|| env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
53
54const MARKDOWN_EXTENSIONS: &[&str] = &[
56 ".md",
57 ".markdown",
58 ".mdx",
59 ".mkd",
60 ".mkdn",
61 ".mdown",
62 ".mdwn",
63 ".qmd",
64 ".rmd",
65];
66
67#[inline]
69fn is_markdown_file(path: &str) -> bool {
70 let path_lower = path.to_lowercase();
71 MARKDOWN_EXTENSIONS.iter().any(|ext| path_lower.ends_with(ext))
72}
73
74#[derive(Debug, Default, Clone)]
76pub struct MD057ExistingRelativeLinks {
77 base_path: Arc<Mutex<Option<PathBuf>>>,
79}
80
81impl MD057ExistingRelativeLinks {
82 pub fn new() -> Self {
84 Self::default()
85 }
86
87 pub fn with_path<P: AsRef<Path>>(self, path: P) -> Self {
89 let path = path.as_ref();
90 let dir_path = if path.is_file() {
91 path.parent().map(|p| p.to_path_buf())
92 } else {
93 Some(path.to_path_buf())
94 };
95
96 *self.base_path.lock().expect("Base path mutex poisoned") = dir_path;
97 self
98 }
99
100 pub fn from_config_struct(_config: MD057Config) -> Self {
101 Self::default()
102 }
103
104 #[inline]
106 fn is_external_url(&self, url: &str) -> bool {
107 if url.is_empty() {
108 return false;
109 }
110
111 if PROTOCOL_DOMAIN_REGEX.is_match(url) || url.starts_with("www.") {
113 return true;
114 }
115
116 if url.ends_with(".com") {
118 return true;
119 }
120
121 if url.starts_with('/') {
123 return false;
124 }
125
126 false
128 }
129
130 #[inline]
132 fn is_fragment_only_link(&self, url: &str) -> bool {
133 url.starts_with('#')
134 }
135
136 fn resolve_link_path(&self, link: &str) -> Option<PathBuf> {
138 self.base_path
139 .lock()
140 .unwrap()
141 .as_ref()
142 .map(|base_path| base_path.join(link))
143 }
144
145 fn process_link(&self, url: &str, line_num: usize, column: usize, warnings: &mut Vec<LintWarning>) {
147 if url.is_empty() {
149 return;
150 }
151
152 if self.is_external_url(url) || self.is_fragment_only_link(url) {
154 return;
155 }
156
157 if let Some(resolved_path) = self.resolve_link_path(url) {
159 if !file_exists_with_cache(&resolved_path) {
161 warnings.push(LintWarning {
162 rule_name: Some(self.name().to_string()),
163 line: line_num,
164 column,
165 end_line: line_num,
166 end_column: column + url.len(),
167 message: format!("Relative link '{url}' does not exist"),
168 severity: Severity::Warning,
169 fix: None, });
171 }
172 }
173 }
174}
175
176impl Rule for MD057ExistingRelativeLinks {
177 fn name(&self) -> &'static str {
178 "MD057"
179 }
180
181 fn description(&self) -> &'static str {
182 "Relative links should point to existing files"
183 }
184
185 fn category(&self) -> RuleCategory {
186 RuleCategory::Link
187 }
188
189 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
190 ctx.content.is_empty() || !ctx.likely_has_links_or_images()
191 }
192
193 fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
194 let content = ctx.content;
195
196 if content.is_empty() || !content.contains('[') {
198 return Ok(Vec::new());
199 }
200
201 if !content.contains("](") {
203 return Ok(Vec::new());
204 }
205
206 reset_file_existence_cache();
208
209 let mut warnings = Vec::new();
210
211 let base_path = {
213 let base_path_guard = self.base_path.lock().expect("Base path mutex poisoned");
214 if base_path_guard.is_some() {
215 base_path_guard.clone()
216 } else {
217 static CACHED_FILE_PATH: std::sync::OnceLock<Option<PathBuf>> = std::sync::OnceLock::new();
219 CACHED_FILE_PATH
220 .get_or_init(|| {
221 if let Ok(file_path) = env::var("RUMDL_FILE_PATH") {
222 let path = Path::new(&file_path);
223 if path.exists() {
224 path.parent()
225 .map(|p| p.to_path_buf())
226 .or_else(|| Some(CURRENT_DIR.clone()))
227 } else {
228 Some(CURRENT_DIR.clone())
229 }
230 } else {
231 Some(CURRENT_DIR.clone())
232 }
233 })
234 .clone()
235 }
236 };
237
238 if base_path.is_none() {
240 return Ok(warnings);
241 }
242
243 if !ctx.links.is_empty() {
245 let line_index = &ctx.line_index;
247
248 let element_cache = ElementCache::new(content);
250
251 let lines: Vec<&str> = content.lines().collect();
253
254 for link in &ctx.links {
255 let line_idx = link.line - 1;
256 if line_idx >= lines.len() {
257 continue;
258 }
259
260 let line = lines[line_idx];
261
262 if !line.contains("](") {
264 continue;
265 }
266
267 for link_match in LINK_START_REGEX.find_iter(line) {
269 let start_pos = link_match.start();
270 let end_pos = link_match.end();
271
272 let line_start_byte = line_index.get_line_start_byte(line_idx + 1).unwrap_or(0);
274 let absolute_start_pos = line_start_byte + start_pos;
275
276 if element_cache.is_in_code_span(absolute_start_pos) {
278 continue;
279 }
280
281 if let Some(caps) = URL_EXTRACT_REGEX.captures_at(line, end_pos - 1)
283 && let Some(url_group) = caps.get(1)
284 {
285 let url = url_group.as_str().trim();
286
287 let column = start_pos + 1;
289
290 self.process_link(url, link.line, column, &mut warnings);
292 }
293 }
294 }
295 }
296
297 Ok(warnings)
298 }
299
300 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
301 Ok(ctx.content.to_string())
302 }
303
304 fn as_any(&self) -> &dyn std::any::Any {
305 self
306 }
307
308 fn default_config_section(&self) -> Option<(String, toml::Value)> {
309 None
311 }
312
313 fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
314 where
315 Self: Sized,
316 {
317 let rule_config = crate::rule_config_serde::load_rule_config::<MD057Config>(config);
318 Box::new(Self::from_config_struct(rule_config))
319 }
320
321 fn cross_file_scope(&self) -> CrossFileScope {
322 CrossFileScope::Workspace
323 }
324
325 fn contribute_to_index(&self, ctx: &crate::lint_context::LintContext, index: &mut FileIndex) {
326 let content = ctx.content;
327
328 if content.is_empty() || !content.contains("](") {
330 return;
331 }
332
333 let lines: Vec<&str> = content.lines().collect();
335 let element_cache = ElementCache::new(content);
336 let line_index = &ctx.line_index;
337
338 for link in &ctx.links {
339 let line_idx = link.line - 1;
340 if line_idx >= lines.len() {
341 continue;
342 }
343
344 let line = lines[line_idx];
345 if !line.contains("](") {
346 continue;
347 }
348
349 for link_match in LINK_START_REGEX.find_iter(line) {
351 let start_pos = link_match.start();
352 let end_pos = link_match.end();
353
354 let line_start_byte = line_index.get_line_start_byte(line_idx + 1).unwrap_or(0);
356 let absolute_start_pos = line_start_byte + start_pos;
357
358 if element_cache.is_in_code_span(absolute_start_pos) {
360 continue;
361 }
362
363 if let Some(caps) = URL_EXTRACT_REGEX.captures_at(line, end_pos - 1)
366 && let Some(url_group) = caps.get(1)
367 {
368 let file_path = url_group.as_str().trim();
369
370 if file_path.is_empty()
372 || PROTOCOL_DOMAIN_REGEX.is_match(file_path)
373 || file_path.starts_with("www.")
374 || file_path.starts_with('#')
375 {
376 continue;
377 }
378
379 let fragment = caps.get(2).map(|m| m.as_str().trim_start_matches('#')).unwrap_or("");
381
382 if is_markdown_file(file_path) {
384 index.add_cross_file_link(CrossFileLinkIndex {
385 target_path: file_path.to_string(),
386 fragment: fragment.to_string(),
387 line: link.line,
388 column: start_pos + 1,
389 });
390 }
391 }
392 }
393 }
394 }
395
396 fn cross_file_check(
397 &self,
398 file_path: &Path,
399 file_index: &FileIndex,
400 workspace_index: &crate::workspace_index::WorkspaceIndex,
401 ) -> LintResult {
402 let mut warnings = Vec::new();
403
404 let file_dir = file_path.parent();
406
407 for cross_link in &file_index.cross_file_links {
408 let target_path = if let Some(dir) = file_dir {
410 dir.join(&cross_link.target_path)
411 } else {
412 Path::new(&cross_link.target_path).to_path_buf()
413 };
414
415 let target_path = normalize_path(&target_path);
417
418 if !workspace_index.contains_file(&target_path) {
420 if cross_link.target_path.ends_with(".md") || cross_link.target_path.ends_with(".markdown") {
423 warnings.push(LintWarning {
424 rule_name: Some(self.name().to_string()),
425 line: cross_link.line,
426 column: cross_link.column,
427 end_line: cross_link.line,
428 end_column: cross_link.column + cross_link.target_path.len(),
429 message: format!(
430 "Relative link '{}' does not exist in the workspace",
431 cross_link.target_path
432 ),
433 severity: Severity::Warning,
434 fix: None,
435 });
436 }
437 }
438 }
439
440 Ok(warnings)
441 }
442}
443
444fn normalize_path(path: &Path) -> PathBuf {
446 let mut components = Vec::new();
447
448 for component in path.components() {
449 match component {
450 std::path::Component::ParentDir => {
451 if !components.is_empty() {
453 components.pop();
454 }
455 }
456 std::path::Component::CurDir => {
457 }
459 _ => {
460 components.push(component);
461 }
462 }
463 }
464
465 components.iter().collect()
466}
467
468#[cfg(test)]
469mod tests {
470 use super::*;
471 use std::fs::File;
472 use std::io::Write;
473 use tempfile::tempdir;
474
475 #[test]
476 fn test_external_urls() {
477 let rule = MD057ExistingRelativeLinks::new();
478
479 assert!(rule.is_external_url("https://example.com"));
480 assert!(rule.is_external_url("http://example.com"));
481 assert!(rule.is_external_url("ftp://example.com"));
482 assert!(rule.is_external_url("www.example.com"));
483 assert!(rule.is_external_url("example.com"));
484
485 assert!(!rule.is_external_url("./relative/path.md"));
486 assert!(!rule.is_external_url("relative/path.md"));
487 assert!(!rule.is_external_url("../parent/path.md"));
488 }
489
490 #[test]
491 fn test_no_warnings_without_base_path() {
492 let rule = MD057ExistingRelativeLinks::new();
493 let content = "[Link](missing.md)";
494
495 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
496 let result = rule.check(&ctx).unwrap();
497 assert!(result.is_empty(), "Should have no warnings without base path");
498 }
499
500 #[test]
501 fn test_existing_and_missing_links() {
502 let temp_dir = tempdir().unwrap();
504 let base_path = temp_dir.path();
505
506 let exists_path = base_path.join("exists.md");
508 File::create(&exists_path).unwrap().write_all(b"# Test File").unwrap();
509
510 assert!(exists_path.exists(), "exists.md should exist for this test");
512
513 let content = r#"
515# Test Document
516
517[Valid Link](exists.md)
518[Invalid Link](missing.md)
519[External Link](https://example.com)
520[Media Link](image.jpg)
521 "#;
522
523 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
525
526 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
528 let result = rule.check(&ctx).unwrap();
529
530 assert_eq!(result.len(), 2);
532 let messages: Vec<_> = result.iter().map(|w| w.message.as_str()).collect();
533 assert!(messages.iter().any(|m| m.contains("missing.md")));
534 assert!(messages.iter().any(|m| m.contains("image.jpg")));
535 }
536
537 #[test]
538 fn test_angle_bracket_links() {
539 let temp_dir = tempdir().unwrap();
541 let base_path = temp_dir.path();
542
543 let exists_path = base_path.join("exists.md");
545 File::create(&exists_path).unwrap().write_all(b"# Test File").unwrap();
546
547 let content = r#"
549# Test Document
550
551[Valid Link](<exists.md>)
552[Invalid Link](<missing.md>)
553[External Link](<https://example.com>)
554 "#;
555
556 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
558
559 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
560 let result = rule.check(&ctx).unwrap();
561
562 assert_eq!(result.len(), 1, "Should have exactly one warning");
564 assert!(
565 result[0].message.contains("missing.md"),
566 "Warning should mention missing.md"
567 );
568 }
569
570 #[test]
571 fn test_all_file_types_checked() {
572 let temp_dir = tempdir().unwrap();
574 let base_path = temp_dir.path();
575
576 let content = r#"
578[Image Link](image.jpg)
579[Video Link](video.mp4)
580[Markdown Link](document.md)
581[PDF Link](file.pdf)
582"#;
583
584 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
585
586 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
587 let result = rule.check(&ctx).unwrap();
588
589 assert_eq!(result.len(), 4, "Should have warnings for all missing files");
591 }
592
593 #[test]
594 fn test_code_span_detection() {
595 let rule = MD057ExistingRelativeLinks::new();
596
597 let temp_dir = tempdir().unwrap();
599 let base_path = temp_dir.path();
600
601 let rule = rule.with_path(base_path);
602
603 let content = "This is a [link](nonexistent.md) and `[not a link](not-checked.md)` in code.";
605
606 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
607 let result = rule.check(&ctx).unwrap();
608
609 assert_eq!(result.len(), 1, "Should only flag the real link");
611 assert!(result[0].message.contains("nonexistent.md"));
612 }
613
614 #[test]
615 fn test_inline_code_spans() {
616 let temp_dir = tempdir().unwrap();
618 let base_path = temp_dir.path();
619
620 let content = r#"
622# Test Document
623
624This is a normal link: [Link](missing.md)
625
626This is a code span with a link: `[Link](another-missing.md)`
627
628Some more text with `inline code [Link](yet-another-missing.md) embedded`.
629
630 "#;
631
632 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
634
635 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
637 let result = rule.check(&ctx).unwrap();
638
639 assert_eq!(result.len(), 1, "Should have exactly one warning");
641 assert!(
642 result[0].message.contains("missing.md"),
643 "Warning should be for missing.md"
644 );
645 assert!(
646 !result.iter().any(|w| w.message.contains("another-missing.md")),
647 "Should not warn about link in code span"
648 );
649 assert!(
650 !result.iter().any(|w| w.message.contains("yet-another-missing.md")),
651 "Should not warn about link in inline code"
652 );
653 }
654
655 #[test]
657 fn test_cross_file_scope() {
658 let rule = MD057ExistingRelativeLinks::new();
659 assert_eq!(rule.cross_file_scope(), CrossFileScope::Workspace);
660 }
661
662 #[test]
663 fn test_contribute_to_index_extracts_markdown_links() {
664 let rule = MD057ExistingRelativeLinks::new();
665 let content = r#"
666# Document
667
668[Link to docs](./docs/guide.md)
669[Link with fragment](./other.md#section)
670[External link](https://example.com)
671[Image link](image.png)
672[Media file](video.mp4)
673"#;
674
675 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
676 let mut index = FileIndex::new();
677 rule.contribute_to_index(&ctx, &mut index);
678
679 assert_eq!(index.cross_file_links.len(), 2);
681
682 assert_eq!(index.cross_file_links[0].target_path, "./docs/guide.md");
684 assert_eq!(index.cross_file_links[0].fragment, "");
685
686 assert_eq!(index.cross_file_links[1].target_path, "./other.md");
688 assert_eq!(index.cross_file_links[1].fragment, "section");
689 }
690
691 #[test]
692 fn test_contribute_to_index_skips_external_and_anchors() {
693 let rule = MD057ExistingRelativeLinks::new();
694 let content = r#"
695# Document
696
697[External](https://example.com)
698[Another external](http://example.org)
699[Fragment only](#section)
700[FTP link](ftp://files.example.com)
701[Mail link](mailto:test@example.com)
702[WWW link](www.example.com)
703"#;
704
705 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
706 let mut index = FileIndex::new();
707 rule.contribute_to_index(&ctx, &mut index);
708
709 assert_eq!(index.cross_file_links.len(), 0);
711 }
712
713 #[test]
714 fn test_cross_file_check_valid_link() {
715 use crate::workspace_index::WorkspaceIndex;
716
717 let rule = MD057ExistingRelativeLinks::new();
718
719 let mut workspace_index = WorkspaceIndex::new();
721 workspace_index.insert_file(PathBuf::from("docs/guide.md"), FileIndex::new());
722
723 let mut file_index = FileIndex::new();
725 file_index.add_cross_file_link(CrossFileLinkIndex {
726 target_path: "guide.md".to_string(),
727 fragment: "".to_string(),
728 line: 5,
729 column: 1,
730 });
731
732 let warnings = rule
734 .cross_file_check(Path::new("docs/index.md"), &file_index, &workspace_index)
735 .unwrap();
736
737 assert!(warnings.is_empty());
739 }
740
741 #[test]
742 fn test_cross_file_check_missing_link() {
743 use crate::workspace_index::WorkspaceIndex;
744
745 let rule = MD057ExistingRelativeLinks::new();
746
747 let workspace_index = WorkspaceIndex::new();
749
750 let mut file_index = FileIndex::new();
752 file_index.add_cross_file_link(CrossFileLinkIndex {
753 target_path: "missing.md".to_string(),
754 fragment: "".to_string(),
755 line: 5,
756 column: 1,
757 });
758
759 let warnings = rule
761 .cross_file_check(Path::new("docs/index.md"), &file_index, &workspace_index)
762 .unwrap();
763
764 assert_eq!(warnings.len(), 1);
766 assert!(warnings[0].message.contains("missing.md"));
767 assert!(warnings[0].message.contains("does not exist"));
768 }
769
770 #[test]
771 fn test_cross_file_check_parent_path() {
772 use crate::workspace_index::WorkspaceIndex;
773
774 let rule = MD057ExistingRelativeLinks::new();
775
776 let mut workspace_index = WorkspaceIndex::new();
778 workspace_index.insert_file(PathBuf::from("readme.md"), FileIndex::new());
779
780 let mut file_index = FileIndex::new();
782 file_index.add_cross_file_link(CrossFileLinkIndex {
783 target_path: "../readme.md".to_string(),
784 fragment: "".to_string(),
785 line: 5,
786 column: 1,
787 });
788
789 let warnings = rule
791 .cross_file_check(Path::new("docs/guide.md"), &file_index, &workspace_index)
792 .unwrap();
793
794 assert!(warnings.is_empty());
796 }
797
798 #[test]
799 fn test_normalize_path_function() {
800 assert_eq!(
802 normalize_path(Path::new("docs/guide.md")),
803 PathBuf::from("docs/guide.md")
804 );
805
806 assert_eq!(
808 normalize_path(Path::new("./docs/guide.md")),
809 PathBuf::from("docs/guide.md")
810 );
811
812 assert_eq!(
814 normalize_path(Path::new("docs/sub/../guide.md")),
815 PathBuf::from("docs/guide.md")
816 );
817
818 assert_eq!(normalize_path(Path::new("a/b/c/../../d.md")), PathBuf::from("a/d.md"));
820 }
821}