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 mut 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 let computed = if let Some(ref source_file) = ctx.source_file {
219 source_file
220 .parent()
221 .map(|p| p.to_path_buf())
222 .or_else(|| Some(CURRENT_DIR.clone()))
223 } else {
224 None
226 };
227 *base_path_guard = computed.clone();
229 computed
230 }
231 };
232
233 if base_path.is_none() {
235 return Ok(warnings);
236 }
237
238 if !ctx.links.is_empty() {
240 let line_index = &ctx.line_index;
242
243 let element_cache = ElementCache::new(content);
245
246 let lines: Vec<&str> = content.lines().collect();
248
249 for link in &ctx.links {
250 let line_idx = link.line - 1;
251 if line_idx >= lines.len() {
252 continue;
253 }
254
255 let line = lines[line_idx];
256
257 if !line.contains("](") {
259 continue;
260 }
261
262 for link_match in LINK_START_REGEX.find_iter(line) {
264 let start_pos = link_match.start();
265 let end_pos = link_match.end();
266
267 let line_start_byte = line_index.get_line_start_byte(line_idx + 1).unwrap_or(0);
269 let absolute_start_pos = line_start_byte + start_pos;
270
271 if element_cache.is_in_code_span(absolute_start_pos) {
273 continue;
274 }
275
276 if let Some(caps) = URL_EXTRACT_REGEX.captures_at(line, end_pos - 1)
278 && let Some(url_group) = caps.get(1)
279 {
280 let url = url_group.as_str().trim();
281
282 let column = start_pos + 1;
284
285 self.process_link(url, link.line, column, &mut warnings);
287 }
288 }
289 }
290 }
291
292 for image in &ctx.images {
294 let url = image.url.as_ref();
295 self.process_link(url, image.line, image.start_col + 1, &mut warnings);
296 }
297
298 Ok(warnings)
299 }
300
301 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
302 Ok(ctx.content.to_string())
303 }
304
305 fn as_any(&self) -> &dyn std::any::Any {
306 self
307 }
308
309 fn default_config_section(&self) -> Option<(String, toml::Value)> {
310 None
312 }
313
314 fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
315 where
316 Self: Sized,
317 {
318 let rule_config = crate::rule_config_serde::load_rule_config::<MD057Config>(config);
319 Box::new(Self::from_config_struct(rule_config))
320 }
321
322 fn cross_file_scope(&self) -> CrossFileScope {
323 CrossFileScope::Workspace
324 }
325
326 fn contribute_to_index(&self, ctx: &crate::lint_context::LintContext, index: &mut FileIndex) {
327 let content = ctx.content;
328
329 if content.is_empty() || !content.contains("](") {
331 return;
332 }
333
334 let lines: Vec<&str> = content.lines().collect();
336 let element_cache = ElementCache::new(content);
337 let line_index = &ctx.line_index;
338
339 for link in &ctx.links {
340 let line_idx = link.line - 1;
341 if line_idx >= lines.len() {
342 continue;
343 }
344
345 let line = lines[line_idx];
346 if !line.contains("](") {
347 continue;
348 }
349
350 for link_match in LINK_START_REGEX.find_iter(line) {
352 let start_pos = link_match.start();
353 let end_pos = link_match.end();
354
355 let line_start_byte = line_index.get_line_start_byte(line_idx + 1).unwrap_or(0);
357 let absolute_start_pos = line_start_byte + start_pos;
358
359 if element_cache.is_in_code_span(absolute_start_pos) {
361 continue;
362 }
363
364 if let Some(caps) = URL_EXTRACT_REGEX.captures_at(line, end_pos - 1)
367 && let Some(url_group) = caps.get(1)
368 {
369 let file_path = url_group.as_str().trim();
370
371 if file_path.is_empty()
373 || PROTOCOL_DOMAIN_REGEX.is_match(file_path)
374 || file_path.starts_with("www.")
375 || file_path.starts_with('#')
376 {
377 continue;
378 }
379
380 let fragment = caps.get(2).map(|m| m.as_str().trim_start_matches('#')).unwrap_or("");
382
383 if is_markdown_file(file_path) {
386 index.add_cross_file_link(CrossFileLinkIndex {
387 target_path: file_path.to_string(),
388 fragment: fragment.to_string(),
389 line: link.line,
390 column: start_pos + 1,
391 });
392 }
393 }
394 }
395 }
396 }
397
398 fn cross_file_check(
399 &self,
400 file_path: &Path,
401 file_index: &FileIndex,
402 workspace_index: &crate::workspace_index::WorkspaceIndex,
403 ) -> LintResult {
404 let mut warnings = Vec::new();
405
406 let file_dir = file_path.parent();
408
409 for cross_link in &file_index.cross_file_links {
410 let target_path = if cross_link.target_path.starts_with('/') {
412 let stripped = cross_link.target_path.trim_start_matches('/');
415 resolve_absolute_link(file_path, stripped)
416 } else if let Some(dir) = file_dir {
417 dir.join(&cross_link.target_path)
418 } else {
419 Path::new(&cross_link.target_path).to_path_buf()
420 };
421
422 let target_path = normalize_path(&target_path);
424
425 if !workspace_index.contains_file(&target_path) {
427 if !target_path.exists() {
429 warnings.push(LintWarning {
430 rule_name: Some(self.name().to_string()),
431 line: cross_link.line,
432 column: cross_link.column,
433 end_line: cross_link.line,
434 end_column: cross_link.column + cross_link.target_path.len(),
435 message: format!("Relative link '{}' does not exist", cross_link.target_path),
436 severity: Severity::Warning,
437 fix: None,
438 });
439 }
440 }
441 }
442
443 Ok(warnings)
444 }
445}
446
447fn normalize_path(path: &Path) -> PathBuf {
449 let mut components = Vec::new();
450
451 for component in path.components() {
452 match component {
453 std::path::Component::ParentDir => {
454 if !components.is_empty() {
456 components.pop();
457 }
458 }
459 std::path::Component::CurDir => {
460 }
462 _ => {
463 components.push(component);
464 }
465 }
466 }
467
468 components.iter().collect()
469}
470
471fn resolve_absolute_link(file_path: &Path, stripped_path: &str) -> PathBuf {
477 let mut current = file_path.parent();
479 while let Some(dir) = current {
480 let candidate = dir.join(stripped_path);
481 if candidate.exists() {
482 return candidate;
483 }
484 current = dir.parent();
485 }
486
487 file_path
490 .parent()
491 .map(|d| d.join(stripped_path))
492 .unwrap_or_else(|| PathBuf::from(stripped_path))
493}
494
495#[cfg(test)]
496mod tests {
497 use super::*;
498 use std::fs::File;
499 use std::io::Write;
500 use tempfile::tempdir;
501
502 #[test]
503 fn test_external_urls() {
504 let rule = MD057ExistingRelativeLinks::new();
505
506 assert!(rule.is_external_url("https://example.com"));
507 assert!(rule.is_external_url("http://example.com"));
508 assert!(rule.is_external_url("ftp://example.com"));
509 assert!(rule.is_external_url("www.example.com"));
510 assert!(rule.is_external_url("example.com"));
511
512 assert!(!rule.is_external_url("./relative/path.md"));
513 assert!(!rule.is_external_url("relative/path.md"));
514 assert!(!rule.is_external_url("../parent/path.md"));
515 }
516
517 #[test]
518 fn test_no_warnings_without_base_path() {
519 let rule = MD057ExistingRelativeLinks::new();
520 let content = "[Link](missing.md)";
521
522 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
523 let result = rule.check(&ctx).unwrap();
524 assert!(result.is_empty(), "Should have no warnings without base path");
525 }
526
527 #[test]
528 fn test_existing_and_missing_links() {
529 let temp_dir = tempdir().unwrap();
531 let base_path = temp_dir.path();
532
533 let exists_path = base_path.join("exists.md");
535 File::create(&exists_path).unwrap().write_all(b"# Test File").unwrap();
536
537 assert!(exists_path.exists(), "exists.md should exist for this test");
539
540 let content = r#"
542# Test Document
543
544[Valid Link](exists.md)
545[Invalid Link](missing.md)
546[External Link](https://example.com)
547[Media Link](image.jpg)
548 "#;
549
550 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
552
553 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
555 let result = rule.check(&ctx).unwrap();
556
557 assert_eq!(result.len(), 2);
559 let messages: Vec<_> = result.iter().map(|w| w.message.as_str()).collect();
560 assert!(messages.iter().any(|m| m.contains("missing.md")));
561 assert!(messages.iter().any(|m| m.contains("image.jpg")));
562 }
563
564 #[test]
565 fn test_angle_bracket_links() {
566 let temp_dir = tempdir().unwrap();
568 let base_path = temp_dir.path();
569
570 let exists_path = base_path.join("exists.md");
572 File::create(&exists_path).unwrap().write_all(b"# Test File").unwrap();
573
574 let content = r#"
576# Test Document
577
578[Valid Link](<exists.md>)
579[Invalid Link](<missing.md>)
580[External Link](<https://example.com>)
581 "#;
582
583 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
585
586 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
587 let result = rule.check(&ctx).unwrap();
588
589 assert_eq!(result.len(), 1, "Should have exactly one warning");
591 assert!(
592 result[0].message.contains("missing.md"),
593 "Warning should mention missing.md"
594 );
595 }
596
597 #[test]
598 fn test_all_file_types_checked() {
599 let temp_dir = tempdir().unwrap();
601 let base_path = temp_dir.path();
602
603 let content = r#"
605[Image Link](image.jpg)
606[Video Link](video.mp4)
607[Markdown Link](document.md)
608[PDF Link](file.pdf)
609"#;
610
611 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
612
613 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
614 let result = rule.check(&ctx).unwrap();
615
616 assert_eq!(result.len(), 4, "Should have warnings for all missing files");
618 }
619
620 #[test]
621 fn test_code_span_detection() {
622 let rule = MD057ExistingRelativeLinks::new();
623
624 let temp_dir = tempdir().unwrap();
626 let base_path = temp_dir.path();
627
628 let rule = rule.with_path(base_path);
629
630 let content = "This is a [link](nonexistent.md) and `[not a link](not-checked.md)` in code.";
632
633 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
634 let result = rule.check(&ctx).unwrap();
635
636 assert_eq!(result.len(), 1, "Should only flag the real link");
638 assert!(result[0].message.contains("nonexistent.md"));
639 }
640
641 #[test]
642 fn test_inline_code_spans() {
643 let temp_dir = tempdir().unwrap();
645 let base_path = temp_dir.path();
646
647 let content = r#"
649# Test Document
650
651This is a normal link: [Link](missing.md)
652
653This is a code span with a link: `[Link](another-missing.md)`
654
655Some more text with `inline code [Link](yet-another-missing.md) embedded`.
656
657 "#;
658
659 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
661
662 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
664 let result = rule.check(&ctx).unwrap();
665
666 assert_eq!(result.len(), 1, "Should have exactly one warning");
668 assert!(
669 result[0].message.contains("missing.md"),
670 "Warning should be for missing.md"
671 );
672 assert!(
673 !result.iter().any(|w| w.message.contains("another-missing.md")),
674 "Should not warn about link in code span"
675 );
676 assert!(
677 !result.iter().any(|w| w.message.contains("yet-another-missing.md")),
678 "Should not warn about link in inline code"
679 );
680 }
681
682 #[test]
684 fn test_cross_file_scope() {
685 let rule = MD057ExistingRelativeLinks::new();
686 assert_eq!(rule.cross_file_scope(), CrossFileScope::Workspace);
687 }
688
689 #[test]
690 fn test_contribute_to_index_extracts_markdown_links() {
691 let rule = MD057ExistingRelativeLinks::new();
692 let content = r#"
693# Document
694
695[Link to docs](./docs/guide.md)
696[Link with fragment](./other.md#section)
697[External link](https://example.com)
698[Image link](image.png)
699[Media file](video.mp4)
700"#;
701
702 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
703 let mut index = FileIndex::new();
704 rule.contribute_to_index(&ctx, &mut index);
705
706 assert_eq!(index.cross_file_links.len(), 2);
708
709 assert_eq!(index.cross_file_links[0].target_path, "./docs/guide.md");
711 assert_eq!(index.cross_file_links[0].fragment, "");
712
713 assert_eq!(index.cross_file_links[1].target_path, "./other.md");
715 assert_eq!(index.cross_file_links[1].fragment, "section");
716 }
717
718 #[test]
719 fn test_contribute_to_index_skips_external_and_anchors() {
720 let rule = MD057ExistingRelativeLinks::new();
721 let content = r#"
722# Document
723
724[External](https://example.com)
725[Another external](http://example.org)
726[Fragment only](#section)
727[FTP link](ftp://files.example.com)
728[Mail link](mailto:test@example.com)
729[WWW link](www.example.com)
730"#;
731
732 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
733 let mut index = FileIndex::new();
734 rule.contribute_to_index(&ctx, &mut index);
735
736 assert_eq!(index.cross_file_links.len(), 0);
738 }
739
740 #[test]
741 fn test_cross_file_check_valid_link() {
742 use crate::workspace_index::WorkspaceIndex;
743
744 let rule = MD057ExistingRelativeLinks::new();
745
746 let mut workspace_index = WorkspaceIndex::new();
748 workspace_index.insert_file(PathBuf::from("docs/guide.md"), FileIndex::new());
749
750 let mut file_index = FileIndex::new();
752 file_index.add_cross_file_link(CrossFileLinkIndex {
753 target_path: "guide.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!(warnings.is_empty());
766 }
767
768 #[test]
769 fn test_cross_file_check_missing_link() {
770 use crate::workspace_index::WorkspaceIndex;
771
772 let rule = MD057ExistingRelativeLinks::new();
773
774 let workspace_index = WorkspaceIndex::new();
776
777 let mut file_index = FileIndex::new();
779 file_index.add_cross_file_link(CrossFileLinkIndex {
780 target_path: "missing.md".to_string(),
781 fragment: "".to_string(),
782 line: 5,
783 column: 1,
784 });
785
786 let warnings = rule
788 .cross_file_check(Path::new("docs/index.md"), &file_index, &workspace_index)
789 .unwrap();
790
791 assert_eq!(warnings.len(), 1);
793 assert!(warnings[0].message.contains("missing.md"));
794 assert!(warnings[0].message.contains("does not exist"));
795 }
796
797 #[test]
798 fn test_cross_file_check_parent_path() {
799 use crate::workspace_index::WorkspaceIndex;
800
801 let rule = MD057ExistingRelativeLinks::new();
802
803 let mut workspace_index = WorkspaceIndex::new();
805 workspace_index.insert_file(PathBuf::from("readme.md"), FileIndex::new());
806
807 let mut file_index = FileIndex::new();
809 file_index.add_cross_file_link(CrossFileLinkIndex {
810 target_path: "../readme.md".to_string(),
811 fragment: "".to_string(),
812 line: 5,
813 column: 1,
814 });
815
816 let warnings = rule
818 .cross_file_check(Path::new("docs/guide.md"), &file_index, &workspace_index)
819 .unwrap();
820
821 assert!(warnings.is_empty());
823 }
824
825 #[test]
826 fn test_normalize_path_function() {
827 assert_eq!(
829 normalize_path(Path::new("docs/guide.md")),
830 PathBuf::from("docs/guide.md")
831 );
832
833 assert_eq!(
835 normalize_path(Path::new("./docs/guide.md")),
836 PathBuf::from("docs/guide.md")
837 );
838
839 assert_eq!(
841 normalize_path(Path::new("docs/sub/../guide.md")),
842 PathBuf::from("docs/guide.md")
843 );
844
845 assert_eq!(normalize_path(Path::new("a/b/c/../../d.md")), PathBuf::from("a/d.md"));
847 }
848
849 #[test]
850 fn test_resolve_absolute_link() {
851 let temp_dir = tempdir().expect("Failed to create temp dir");
853 let root = temp_dir.path();
854
855 let contributing = root.join("CONTRIBUTING.md");
857 File::create(&contributing).expect("Failed to create CONTRIBUTING.md");
858
859 let docs = root.join("docs");
861 std::fs::create_dir(&docs).expect("Failed to create docs dir");
862 let readme = docs.join("README.md");
863 File::create(&readme).expect("Failed to create README.md");
864
865 let resolved = resolve_absolute_link(&readme, "CONTRIBUTING.md");
868 assert!(resolved.exists(), "Should find CONTRIBUTING.md at workspace root");
869 assert_eq!(resolved, contributing);
870
871 let nonexistent = resolve_absolute_link(&readme, "NONEXISTENT.md");
873 assert!(!nonexistent.exists(), "Should not find nonexistent file");
874 }
875}