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 if let Ok(mut cache) = FILE_EXISTENCE_CACHE.lock() {
26 cache.clear();
27 }
28}
29
30fn file_exists_with_cache(path: &Path) -> bool {
32 match FILE_EXISTENCE_CACHE.lock() {
33 Ok(mut cache) => *cache.entry(path.to_path_buf()).or_insert_with(|| path.exists()),
34 Err(_) => path.exists(), }
36}
37
38fn file_exists_or_markdown_extension(path: &Path) -> bool {
41 if file_exists_with_cache(path) {
43 return true;
44 }
45
46 if path.extension().is_none() {
48 for ext in MARKDOWN_EXTENSIONS {
49 let path_with_ext = path.with_extension(&ext[1..]);
51 if file_exists_with_cache(&path_with_ext) {
52 return true;
53 }
54 }
55 }
56
57 false
58}
59
60static LINK_START_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"!?\[[^\]]*\]").unwrap());
62
63static URL_EXTRACT_ANGLE_BRACKET_REGEX: LazyLock<Regex> =
67 LazyLock::new(|| Regex::new(r#"\]\(\s*<([^>]+)>(#[^\)\s]*)?\s*(?:"[^"]*")?\s*\)"#).unwrap());
68
69static URL_EXTRACT_REGEX: LazyLock<Regex> =
72 LazyLock::new(|| Regex::new("\\]\\(\\s*([^>\\)\\s#]+)(#[^)\\s]*)?\\s*(?:\"[^\"]*\")?\\s*\\)").unwrap());
73
74static PROTOCOL_DOMAIN_REGEX: LazyLock<Regex> =
78 LazyLock::new(|| Regex::new(r"^([a-zA-Z][a-zA-Z0-9+.-]*://|[a-zA-Z][a-zA-Z0-9+.-]*:|www\.)").unwrap());
79
80static CURRENT_DIR: LazyLock<PathBuf> = LazyLock::new(|| env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
82
83#[inline]
86fn hex_digit_to_value(byte: u8) -> Option<u8> {
87 match byte {
88 b'0'..=b'9' => Some(byte - b'0'),
89 b'a'..=b'f' => Some(byte - b'a' + 10),
90 b'A'..=b'F' => Some(byte - b'A' + 10),
91 _ => None,
92 }
93}
94
95const MARKDOWN_EXTENSIONS: &[&str] = &[
97 ".md",
98 ".markdown",
99 ".mdx",
100 ".mkd",
101 ".mkdn",
102 ".mdown",
103 ".mdwn",
104 ".qmd",
105 ".rmd",
106];
107
108#[inline]
110fn is_markdown_file(path: &str) -> bool {
111 let path_lower = path.to_lowercase();
112 MARKDOWN_EXTENSIONS.iter().any(|ext| path_lower.ends_with(ext))
113}
114
115#[derive(Debug, Clone, Default)]
117pub struct MD057ExistingRelativeLinks {
118 base_path: Arc<Mutex<Option<PathBuf>>>,
120}
121
122impl MD057ExistingRelativeLinks {
123 pub fn new() -> Self {
125 Self::default()
126 }
127
128 pub fn with_path<P: AsRef<Path>>(self, path: P) -> Self {
130 let path = path.as_ref();
131 let dir_path = if path.is_file() {
132 path.parent().map(|p| p.to_path_buf())
133 } else {
134 Some(path.to_path_buf())
135 };
136
137 if let Ok(mut guard) = self.base_path.lock() {
138 *guard = dir_path;
139 }
140 self
141 }
142
143 #[allow(unused_variables)]
144 pub fn from_config_struct(config: MD057Config) -> Self {
145 Self::default()
146 }
147
148 #[inline]
159 fn is_external_url(&self, url: &str) -> bool {
160 if url.is_empty() {
161 return false;
162 }
163
164 if PROTOCOL_DOMAIN_REGEX.is_match(url) || url.starts_with("www.") {
166 return true;
167 }
168
169 if url.starts_with("{{") || url.starts_with("{%") {
172 return true;
173 }
174
175 if url.ends_with(".com") {
182 return true;
183 }
184
185 if url.starts_with('/') {
189 return true;
190 }
191
192 if url.starts_with('~') || url.starts_with('@') {
196 return true;
197 }
198
199 false
201 }
202
203 #[inline]
205 fn is_fragment_only_link(&self, url: &str) -> bool {
206 url.starts_with('#')
207 }
208
209 fn url_decode(path: &str) -> String {
213 if !path.contains('%') {
215 return path.to_string();
216 }
217
218 let bytes = path.as_bytes();
219 let mut result = Vec::with_capacity(bytes.len());
220 let mut i = 0;
221
222 while i < bytes.len() {
223 if bytes[i] == b'%' && i + 2 < bytes.len() {
224 let hex1 = bytes[i + 1];
226 let hex2 = bytes[i + 2];
227 if let (Some(d1), Some(d2)) = (hex_digit_to_value(hex1), hex_digit_to_value(hex2)) {
228 result.push(d1 * 16 + d2);
229 i += 3;
230 continue;
231 }
232 }
233 result.push(bytes[i]);
234 i += 1;
235 }
236
237 String::from_utf8(result).unwrap_or_else(|_| path.to_string())
239 }
240
241 fn strip_query_and_fragment(url: &str) -> &str {
249 let query_pos = url.find('?');
252 let fragment_pos = url.find('#');
253
254 match (query_pos, fragment_pos) {
255 (Some(q), Some(f)) => {
256 &url[..q.min(f)]
258 }
259 (Some(q), None) => &url[..q],
260 (None, Some(f)) => &url[..f],
261 (None, None) => url,
262 }
263 }
264
265 fn resolve_link_path_with_base(link: &str, base_path: &Path) -> PathBuf {
267 base_path.join(link)
268 }
269
270 fn process_link_with_base(
272 &self,
273 url: &str,
274 line_num: usize,
275 column: usize,
276 base_path: &Path,
277 warnings: &mut Vec<LintWarning>,
278 ) {
279 if url.is_empty() {
281 return;
282 }
283
284 if self.is_external_url(url) || self.is_fragment_only_link(url) {
286 return;
287 }
288
289 let file_path = Self::strip_query_and_fragment(url);
292
293 let decoded_path = Self::url_decode(file_path);
296
297 let resolved_path = Self::resolve_link_path_with_base(&decoded_path, base_path);
299
300 if file_exists_or_markdown_extension(&resolved_path) {
302 return; }
304
305 if let Some(ext) = resolved_path.extension().and_then(|e| e.to_str())
308 && (ext.eq_ignore_ascii_case("html") || ext.eq_ignore_ascii_case("htm"))
309 && let (Some(stem), Some(parent)) = (
310 resolved_path.file_stem().and_then(|s| s.to_str()),
311 resolved_path.parent(),
312 )
313 {
314 for md_ext in MARKDOWN_EXTENSIONS {
315 let source_path = parent.join(format!("{stem}{md_ext}"));
316 if file_exists_with_cache(&source_path) {
317 return; }
319 }
320 }
321
322 warnings.push(LintWarning {
324 rule_name: Some(self.name().to_string()),
325 line: line_num,
326 column,
327 end_line: line_num,
328 end_column: column + url.len(),
329 message: format!("Relative link '{url}' does not exist"),
330 severity: Severity::Warning,
331 fix: None,
332 });
333 }
334}
335
336impl Rule for MD057ExistingRelativeLinks {
337 fn name(&self) -> &'static str {
338 "MD057"
339 }
340
341 fn description(&self) -> &'static str {
342 "Relative links should point to existing files"
343 }
344
345 fn category(&self) -> RuleCategory {
346 RuleCategory::Link
347 }
348
349 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
350 ctx.content.is_empty() || !ctx.likely_has_links_or_images()
351 }
352
353 fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
354 let content = ctx.content;
355
356 if content.is_empty() || !content.contains('[') {
358 return Ok(Vec::new());
359 }
360
361 if !content.contains("](") {
363 return Ok(Vec::new());
364 }
365
366 reset_file_existence_cache();
368
369 let mut warnings = Vec::new();
370
371 let base_path: Option<PathBuf> = {
375 let explicit_base = self.base_path.lock().ok().and_then(|g| g.clone());
377 if explicit_base.is_some() {
378 explicit_base
379 } else if let Some(ref source_file) = ctx.source_file {
380 let resolved_file = source_file.canonicalize().unwrap_or_else(|_| source_file.clone());
384 resolved_file
385 .parent()
386 .map(|p| p.to_path_buf())
387 .or_else(|| Some(CURRENT_DIR.clone()))
388 } else {
389 None
391 }
392 };
393
394 let Some(base_path) = base_path else {
396 return Ok(warnings);
397 };
398
399 if !ctx.links.is_empty() {
401 let line_index = &ctx.line_index;
403
404 let element_cache = ElementCache::new(content);
406
407 let lines: Vec<&str> = content.lines().collect();
409
410 for link in &ctx.links {
411 let line_idx = link.line - 1;
412 if line_idx >= lines.len() {
413 continue;
414 }
415
416 let line = lines[line_idx];
417
418 if !line.contains("](") {
420 continue;
421 }
422
423 for link_match in LINK_START_REGEX.find_iter(line) {
425 let start_pos = link_match.start();
426 let end_pos = link_match.end();
427
428 let line_start_byte = line_index.get_line_start_byte(line_idx + 1).unwrap_or(0);
430 let absolute_start_pos = line_start_byte + start_pos;
431
432 if element_cache.is_in_code_span(absolute_start_pos) {
434 continue;
435 }
436
437 let caps_and_url = URL_EXTRACT_ANGLE_BRACKET_REGEX
441 .captures_at(line, end_pos - 1)
442 .and_then(|caps| caps.get(1).map(|g| (caps, g)))
443 .or_else(|| {
444 URL_EXTRACT_REGEX
445 .captures_at(line, end_pos - 1)
446 .and_then(|caps| caps.get(1).map(|g| (caps, g)))
447 });
448
449 if let Some((_caps, url_group)) = caps_and_url {
450 let url = url_group.as_str().trim();
451
452 let column = start_pos + 1;
454
455 self.process_link_with_base(url, link.line, column, &base_path, &mut warnings);
457 }
458 }
459 }
460 }
461
462 for image in &ctx.images {
464 let url = image.url.as_ref();
465 self.process_link_with_base(url, image.line, image.start_col + 1, &base_path, &mut warnings);
466 }
467
468 Ok(warnings)
469 }
470
471 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
472 Ok(ctx.content.to_string())
473 }
474
475 fn as_any(&self) -> &dyn std::any::Any {
476 self
477 }
478
479 fn default_config_section(&self) -> Option<(String, toml::Value)> {
480 None
482 }
483
484 fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
485 where
486 Self: Sized,
487 {
488 let rule_config = crate::rule_config_serde::load_rule_config::<MD057Config>(config);
489 Box::new(Self::from_config_struct(rule_config))
490 }
491
492 fn cross_file_scope(&self) -> CrossFileScope {
493 CrossFileScope::Workspace
494 }
495
496 fn contribute_to_index(&self, ctx: &crate::lint_context::LintContext, index: &mut FileIndex) {
497 let content = ctx.content;
498
499 if content.is_empty() || !content.contains("](") {
501 return;
502 }
503
504 let lines: Vec<&str> = content.lines().collect();
506 let element_cache = ElementCache::new(content);
507 let line_index = &ctx.line_index;
508
509 for link in &ctx.links {
510 let line_idx = link.line - 1;
511 if line_idx >= lines.len() {
512 continue;
513 }
514
515 let line = lines[line_idx];
516 if !line.contains("](") {
517 continue;
518 }
519
520 for link_match in LINK_START_REGEX.find_iter(line) {
522 let start_pos = link_match.start();
523 let end_pos = link_match.end();
524
525 let line_start_byte = line_index.get_line_start_byte(line_idx + 1).unwrap_or(0);
527 let absolute_start_pos = line_start_byte + start_pos;
528
529 if element_cache.is_in_code_span(absolute_start_pos) {
531 continue;
532 }
533
534 let caps_result = URL_EXTRACT_ANGLE_BRACKET_REGEX
538 .captures_at(line, end_pos - 1)
539 .or_else(|| URL_EXTRACT_REGEX.captures_at(line, end_pos - 1));
540
541 if let Some(caps) = caps_result
542 && let Some(url_group) = caps.get(1)
543 {
544 let file_path = url_group.as_str().trim();
545
546 if file_path.is_empty()
549 || PROTOCOL_DOMAIN_REGEX.is_match(file_path)
550 || file_path.starts_with("www.")
551 || file_path.starts_with('#')
552 || file_path.starts_with("{{")
553 || file_path.starts_with("{%")
554 || file_path.starts_with('/')
555 || file_path.starts_with('~')
556 || file_path.starts_with('@')
557 {
558 continue;
559 }
560
561 let file_path = Self::strip_query_and_fragment(file_path);
563
564 let fragment = caps.get(2).map(|m| m.as_str().trim_start_matches('#')).unwrap_or("");
566
567 if is_markdown_file(file_path) {
570 index.add_cross_file_link(CrossFileLinkIndex {
571 target_path: file_path.to_string(),
572 fragment: fragment.to_string(),
573 line: link.line,
574 column: start_pos + 1,
575 });
576 }
577 }
578 }
579 }
580 }
581
582 fn cross_file_check(
583 &self,
584 file_path: &Path,
585 file_index: &FileIndex,
586 workspace_index: &crate::workspace_index::WorkspaceIndex,
587 ) -> LintResult {
588 let mut warnings = Vec::new();
589
590 let file_dir = file_path.parent();
592
593 for cross_link in &file_index.cross_file_links {
594 let target_path = if cross_link.target_path.starts_with('/') {
596 let stripped = cross_link.target_path.trim_start_matches('/');
599 resolve_absolute_link(file_path, stripped)
600 } else if let Some(dir) = file_dir {
601 dir.join(&cross_link.target_path)
602 } else {
603 Path::new(&cross_link.target_path).to_path_buf()
604 };
605
606 let target_path = normalize_path(&target_path);
608
609 if !workspace_index.contains_file(&target_path) {
611 if !target_path.exists() {
613 warnings.push(LintWarning {
614 rule_name: Some(self.name().to_string()),
615 line: cross_link.line,
616 column: cross_link.column,
617 end_line: cross_link.line,
618 end_column: cross_link.column + cross_link.target_path.len(),
619 message: format!("Relative link '{}' does not exist", cross_link.target_path),
620 severity: Severity::Warning,
621 fix: None,
622 });
623 }
624 }
625 }
626
627 Ok(warnings)
628 }
629}
630
631fn normalize_path(path: &Path) -> PathBuf {
633 let mut components = Vec::new();
634
635 for component in path.components() {
636 match component {
637 std::path::Component::ParentDir => {
638 if !components.is_empty() {
640 components.pop();
641 }
642 }
643 std::path::Component::CurDir => {
644 }
646 _ => {
647 components.push(component);
648 }
649 }
650 }
651
652 components.iter().collect()
653}
654
655fn resolve_absolute_link(file_path: &Path, stripped_path: &str) -> PathBuf {
661 let mut current = file_path.parent();
663 while let Some(dir) = current {
664 let candidate = dir.join(stripped_path);
665 if candidate.exists() {
666 return candidate;
667 }
668 current = dir.parent();
669 }
670
671 file_path
674 .parent()
675 .map(|d| d.join(stripped_path))
676 .unwrap_or_else(|| PathBuf::from(stripped_path))
677}
678
679#[cfg(test)]
680mod tests {
681 use super::*;
682 use std::fs::File;
683 use std::io::Write;
684 use tempfile::tempdir;
685
686 #[test]
687 fn test_strip_query_and_fragment() {
688 assert_eq!(
690 MD057ExistingRelativeLinks::strip_query_and_fragment("file.png?raw=true"),
691 "file.png"
692 );
693 assert_eq!(
694 MD057ExistingRelativeLinks::strip_query_and_fragment("file.png?raw=true&version=1"),
695 "file.png"
696 );
697 assert_eq!(
698 MD057ExistingRelativeLinks::strip_query_and_fragment("file.png?"),
699 "file.png"
700 );
701
702 assert_eq!(
704 MD057ExistingRelativeLinks::strip_query_and_fragment("file.md#section"),
705 "file.md"
706 );
707 assert_eq!(
708 MD057ExistingRelativeLinks::strip_query_and_fragment("file.md#"),
709 "file.md"
710 );
711
712 assert_eq!(
714 MD057ExistingRelativeLinks::strip_query_and_fragment("file.md?raw=true#section"),
715 "file.md"
716 );
717
718 assert_eq!(
720 MD057ExistingRelativeLinks::strip_query_and_fragment("file.png"),
721 "file.png"
722 );
723
724 assert_eq!(
726 MD057ExistingRelativeLinks::strip_query_and_fragment("path/to/image.png?raw=true"),
727 "path/to/image.png"
728 );
729 assert_eq!(
730 MD057ExistingRelativeLinks::strip_query_and_fragment("path/to/image.png?raw=true#anchor"),
731 "path/to/image.png"
732 );
733
734 assert_eq!(
736 MD057ExistingRelativeLinks::strip_query_and_fragment("file.md#section?query"),
737 "file.md"
738 );
739 }
740
741 #[test]
742 fn test_url_decode() {
743 assert_eq!(
745 MD057ExistingRelativeLinks::url_decode("penguin%20with%20space.jpg"),
746 "penguin with space.jpg"
747 );
748
749 assert_eq!(
751 MD057ExistingRelativeLinks::url_decode("assets/my%20file%20name.png"),
752 "assets/my file name.png"
753 );
754
755 assert_eq!(
757 MD057ExistingRelativeLinks::url_decode("hello%20world%21.md"),
758 "hello world!.md"
759 );
760
761 assert_eq!(MD057ExistingRelativeLinks::url_decode("%2f%2e%2e"), "/..");
763
764 assert_eq!(MD057ExistingRelativeLinks::url_decode("%2F%2E%2E"), "/..");
766
767 assert_eq!(MD057ExistingRelativeLinks::url_decode("%2f%2E%2e"), "/..");
769
770 assert_eq!(
772 MD057ExistingRelativeLinks::url_decode("normal-file.md"),
773 "normal-file.md"
774 );
775
776 assert_eq!(MD057ExistingRelativeLinks::url_decode("file%2.txt"), "file%2.txt");
778
779 assert_eq!(MD057ExistingRelativeLinks::url_decode("file%"), "file%");
781
782 assert_eq!(MD057ExistingRelativeLinks::url_decode("file%GG.txt"), "file%GG.txt");
784
785 assert_eq!(MD057ExistingRelativeLinks::url_decode("file+name.txt"), "file+name.txt");
787
788 assert_eq!(MD057ExistingRelativeLinks::url_decode(""), "");
790
791 assert_eq!(MD057ExistingRelativeLinks::url_decode("caf%C3%A9.md"), "café.md");
793
794 assert_eq!(MD057ExistingRelativeLinks::url_decode("%20%20%20"), " ");
796
797 assert_eq!(
799 MD057ExistingRelativeLinks::url_decode("path%2Fto%2Ffile.md"),
800 "path/to/file.md"
801 );
802
803 assert_eq!(
805 MD057ExistingRelativeLinks::url_decode("hello%20world/foo%20bar.md"),
806 "hello world/foo bar.md"
807 );
808
809 assert_eq!(MD057ExistingRelativeLinks::url_decode("file%5B1%5D.md"), "file[1].md");
811
812 assert_eq!(MD057ExistingRelativeLinks::url_decode("100%pure.md"), "100%pure.md");
814 }
815
816 #[test]
817 fn test_url_encoded_filenames() {
818 let temp_dir = tempdir().unwrap();
820 let base_path = temp_dir.path();
821
822 let file_with_spaces = base_path.join("penguin with space.jpg");
824 File::create(&file_with_spaces)
825 .unwrap()
826 .write_all(b"image data")
827 .unwrap();
828
829 let subdir = base_path.join("my images");
831 std::fs::create_dir(&subdir).unwrap();
832 let nested_file = subdir.join("photo 1.png");
833 File::create(&nested_file).unwrap().write_all(b"photo data").unwrap();
834
835 let content = r#"
837# Test Document with URL-Encoded Links
838
839
840
841
842"#;
843
844 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
845
846 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
847 let result = rule.check(&ctx).unwrap();
848
849 assert_eq!(
851 result.len(),
852 1,
853 "Should only warn about missing%20file.jpg. Got: {result:?}"
854 );
855 assert!(
856 result[0].message.contains("missing%20file.jpg"),
857 "Warning should mention the URL-encoded filename"
858 );
859 }
860
861 #[test]
862 fn test_external_urls() {
863 let rule = MD057ExistingRelativeLinks::new();
864
865 assert!(rule.is_external_url("https://example.com"));
867 assert!(rule.is_external_url("http://example.com"));
868 assert!(rule.is_external_url("ftp://example.com"));
869 assert!(rule.is_external_url("www.example.com"));
870 assert!(rule.is_external_url("example.com"));
871
872 assert!(rule.is_external_url("file:///path/to/file"));
874 assert!(rule.is_external_url("smb://server/share"));
875 assert!(rule.is_external_url("macappstores://apps.apple.com/"));
876 assert!(rule.is_external_url("mailto:user@example.com"));
877 assert!(rule.is_external_url("tel:+1234567890"));
878 assert!(rule.is_external_url("data:text/plain;base64,SGVsbG8="));
879 assert!(rule.is_external_url("javascript:void(0)"));
880 assert!(rule.is_external_url("ssh://git@github.com/repo"));
881 assert!(rule.is_external_url("git://github.com/repo.git"));
882
883 assert!(rule.is_external_url("{{URL}}")); assert!(rule.is_external_url("{{#URL}}")); assert!(rule.is_external_url("{{> partial}}")); assert!(rule.is_external_url("{{ variable }}")); assert!(rule.is_external_url("{{% include %}}")); assert!(rule.is_external_url("{{")); assert!(rule.is_external_url("/api/v1/users"));
894 assert!(rule.is_external_url("/blog/2024/release.html"));
895 assert!(rule.is_external_url("/react/hooks/use-state.html"));
896 assert!(rule.is_external_url("/pkg/runtime"));
897 assert!(rule.is_external_url("/doc/go1compat"));
898 assert!(rule.is_external_url("/index.html"));
899 assert!(rule.is_external_url("/assets/logo.png"));
900
901 assert!(rule.is_external_url("~/assets/image.png"));
904 assert!(rule.is_external_url("~/components/Button.vue"));
905 assert!(rule.is_external_url("~assets/logo.svg")); assert!(rule.is_external_url("@/components/Header.vue"));
909 assert!(rule.is_external_url("@images/photo.jpg"));
910 assert!(rule.is_external_url("@assets/styles.css"));
911
912 assert!(!rule.is_external_url("./relative/path.md"));
914 assert!(!rule.is_external_url("relative/path.md"));
915 assert!(!rule.is_external_url("../parent/path.md"));
916 }
917
918 #[test]
919 fn test_framework_path_aliases() {
920 let temp_dir = tempdir().unwrap();
922 let base_path = temp_dir.path();
923
924 let content = r#"
926# Framework Path Aliases
927
928
929
930
931
932[Link](@/pages/about.md)
933
934This is a [real missing link](missing.md) that should be flagged.
935"#;
936
937 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
938
939 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
940 let result = rule.check(&ctx).unwrap();
941
942 assert_eq!(
944 result.len(),
945 1,
946 "Should only warn about missing.md, not framework aliases. Got: {result:?}"
947 );
948 assert!(
949 result[0].message.contains("missing.md"),
950 "Warning should be for missing.md"
951 );
952 }
953
954 #[test]
955 fn test_url_decode_security_path_traversal() {
956 let temp_dir = tempdir().unwrap();
959 let base_path = temp_dir.path();
960
961 let file_in_base = base_path.join("safe.md");
963 File::create(&file_in_base).unwrap().write_all(b"# Safe").unwrap();
964
965 let content = r#"
970[Traversal attempt](..%2F..%2Fnonexistent_dir_12345%2Fmissing.md)
971[Double encoded](..%252F..%252Fnonexistent%252Ffile.md)
972[Safe link](safe.md)
973"#;
974
975 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
976
977 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
978 let result = rule.check(&ctx).unwrap();
979
980 assert_eq!(
983 result.len(),
984 2,
985 "Should have warnings for traversal attempts. Got: {result:?}"
986 );
987 }
988
989 #[test]
990 fn test_url_encoded_utf8_filenames() {
991 let temp_dir = tempdir().unwrap();
993 let base_path = temp_dir.path();
994
995 let cafe_file = base_path.join("café.md");
997 File::create(&cafe_file).unwrap().write_all(b"# Cafe").unwrap();
998
999 let content = r#"
1000[Café link](caf%C3%A9.md)
1001[Missing unicode](r%C3%A9sum%C3%A9.md)
1002"#;
1003
1004 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
1005
1006 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1007 let result = rule.check(&ctx).unwrap();
1008
1009 assert_eq!(
1011 result.len(),
1012 1,
1013 "Should only warn about missing résumé.md. Got: {result:?}"
1014 );
1015 assert!(
1016 result[0].message.contains("r%C3%A9sum%C3%A9.md"),
1017 "Warning should mention the URL-encoded filename"
1018 );
1019 }
1020
1021 #[test]
1022 fn test_no_warnings_without_base_path() {
1023 let rule = MD057ExistingRelativeLinks::new();
1024 let content = "[Link](missing.md)";
1025
1026 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1027 let result = rule.check(&ctx).unwrap();
1028 assert!(result.is_empty(), "Should have no warnings without base path");
1029 }
1030
1031 #[test]
1032 fn test_existing_and_missing_links() {
1033 let temp_dir = tempdir().unwrap();
1035 let base_path = temp_dir.path();
1036
1037 let exists_path = base_path.join("exists.md");
1039 File::create(&exists_path).unwrap().write_all(b"# Test File").unwrap();
1040
1041 assert!(exists_path.exists(), "exists.md should exist for this test");
1043
1044 let content = r#"
1046# Test Document
1047
1048[Valid Link](exists.md)
1049[Invalid Link](missing.md)
1050[External Link](https://example.com)
1051[Media Link](image.jpg)
1052 "#;
1053
1054 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
1056
1057 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1059 let result = rule.check(&ctx).unwrap();
1060
1061 assert_eq!(result.len(), 2);
1063 let messages: Vec<_> = result.iter().map(|w| w.message.as_str()).collect();
1064 assert!(messages.iter().any(|m| m.contains("missing.md")));
1065 assert!(messages.iter().any(|m| m.contains("image.jpg")));
1066 }
1067
1068 #[test]
1069 fn test_angle_bracket_links() {
1070 let temp_dir = tempdir().unwrap();
1072 let base_path = temp_dir.path();
1073
1074 let exists_path = base_path.join("exists.md");
1076 File::create(&exists_path).unwrap().write_all(b"# Test File").unwrap();
1077
1078 let content = r#"
1080# Test Document
1081
1082[Valid Link](<exists.md>)
1083[Invalid Link](<missing.md>)
1084[External Link](<https://example.com>)
1085 "#;
1086
1087 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
1089
1090 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1091 let result = rule.check(&ctx).unwrap();
1092
1093 assert_eq!(result.len(), 1, "Should have exactly one warning");
1095 assert!(
1096 result[0].message.contains("missing.md"),
1097 "Warning should mention missing.md"
1098 );
1099 }
1100
1101 #[test]
1102 fn test_angle_bracket_links_with_parens() {
1103 let temp_dir = tempdir().unwrap();
1105 let base_path = temp_dir.path();
1106
1107 let app_dir = base_path.join("app");
1109 std::fs::create_dir(&app_dir).unwrap();
1110 let upload_dir = app_dir.join("(upload)");
1111 std::fs::create_dir(&upload_dir).unwrap();
1112 let page_file = upload_dir.join("page.tsx");
1113 File::create(&page_file)
1114 .unwrap()
1115 .write_all(b"export default function Page() {}")
1116 .unwrap();
1117
1118 let content = r#"
1120# Test Document with Paths Containing Parens
1121
1122[Upload Page](<app/(upload)/page.tsx>)
1123[Unix pipe](<https://en.wikipedia.org/wiki/Pipeline_(Unix)>)
1124[Missing](<app/(missing)/file.md>)
1125"#;
1126
1127 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
1128
1129 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1130 let result = rule.check(&ctx).unwrap();
1131
1132 assert_eq!(
1134 result.len(),
1135 1,
1136 "Should have exactly one warning for missing file. Got: {result:?}"
1137 );
1138 assert!(
1139 result[0].message.contains("app/(missing)/file.md"),
1140 "Warning should mention app/(missing)/file.md"
1141 );
1142 }
1143
1144 #[test]
1145 fn test_all_file_types_checked() {
1146 let temp_dir = tempdir().unwrap();
1148 let base_path = temp_dir.path();
1149
1150 let content = r#"
1152[Image Link](image.jpg)
1153[Video Link](video.mp4)
1154[Markdown Link](document.md)
1155[PDF Link](file.pdf)
1156"#;
1157
1158 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
1159
1160 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1161 let result = rule.check(&ctx).unwrap();
1162
1163 assert_eq!(result.len(), 4, "Should have warnings for all missing files");
1165 }
1166
1167 #[test]
1168 fn test_code_span_detection() {
1169 let rule = MD057ExistingRelativeLinks::new();
1170
1171 let temp_dir = tempdir().unwrap();
1173 let base_path = temp_dir.path();
1174
1175 let rule = rule.with_path(base_path);
1176
1177 let content = "This is a [link](nonexistent.md) and `[not a link](not-checked.md)` in code.";
1179
1180 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1181 let result = rule.check(&ctx).unwrap();
1182
1183 assert_eq!(result.len(), 1, "Should only flag the real link");
1185 assert!(result[0].message.contains("nonexistent.md"));
1186 }
1187
1188 #[test]
1189 fn test_inline_code_spans() {
1190 let temp_dir = tempdir().unwrap();
1192 let base_path = temp_dir.path();
1193
1194 let content = r#"
1196# Test Document
1197
1198This is a normal link: [Link](missing.md)
1199
1200This is a code span with a link: `[Link](another-missing.md)`
1201
1202Some more text with `inline code [Link](yet-another-missing.md) embedded`.
1203
1204 "#;
1205
1206 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
1208
1209 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1211 let result = rule.check(&ctx).unwrap();
1212
1213 assert_eq!(result.len(), 1, "Should have exactly one warning");
1215 assert!(
1216 result[0].message.contains("missing.md"),
1217 "Warning should be for missing.md"
1218 );
1219 assert!(
1220 !result.iter().any(|w| w.message.contains("another-missing.md")),
1221 "Should not warn about link in code span"
1222 );
1223 assert!(
1224 !result.iter().any(|w| w.message.contains("yet-another-missing.md")),
1225 "Should not warn about link in inline code"
1226 );
1227 }
1228
1229 #[test]
1230 fn test_extensionless_link_resolution() {
1231 let temp_dir = tempdir().unwrap();
1233 let base_path = temp_dir.path();
1234
1235 let page_path = base_path.join("page.md");
1237 File::create(&page_path).unwrap().write_all(b"# Page").unwrap();
1238
1239 let content = r#"
1241# Test Document
1242
1243[Link without extension](page)
1244[Link with extension](page.md)
1245[Missing link](nonexistent)
1246"#;
1247
1248 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
1249
1250 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1251 let result = rule.check(&ctx).unwrap();
1252
1253 assert_eq!(result.len(), 1, "Should only warn about nonexistent link");
1256 assert!(
1257 result[0].message.contains("nonexistent"),
1258 "Warning should be for 'nonexistent' not 'page'"
1259 );
1260 }
1261
1262 #[test]
1264 fn test_cross_file_scope() {
1265 let rule = MD057ExistingRelativeLinks::new();
1266 assert_eq!(rule.cross_file_scope(), CrossFileScope::Workspace);
1267 }
1268
1269 #[test]
1270 fn test_contribute_to_index_extracts_markdown_links() {
1271 let rule = MD057ExistingRelativeLinks::new();
1272 let content = r#"
1273# Document
1274
1275[Link to docs](./docs/guide.md)
1276[Link with fragment](./other.md#section)
1277[External link](https://example.com)
1278[Image link](image.png)
1279[Media file](video.mp4)
1280"#;
1281
1282 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1283 let mut index = FileIndex::new();
1284 rule.contribute_to_index(&ctx, &mut index);
1285
1286 assert_eq!(index.cross_file_links.len(), 2);
1288
1289 assert_eq!(index.cross_file_links[0].target_path, "./docs/guide.md");
1291 assert_eq!(index.cross_file_links[0].fragment, "");
1292
1293 assert_eq!(index.cross_file_links[1].target_path, "./other.md");
1295 assert_eq!(index.cross_file_links[1].fragment, "section");
1296 }
1297
1298 #[test]
1299 fn test_contribute_to_index_skips_external_and_anchors() {
1300 let rule = MD057ExistingRelativeLinks::new();
1301 let content = r#"
1302# Document
1303
1304[External](https://example.com)
1305[Another external](http://example.org)
1306[Fragment only](#section)
1307[FTP link](ftp://files.example.com)
1308[Mail link](mailto:test@example.com)
1309[WWW link](www.example.com)
1310"#;
1311
1312 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1313 let mut index = FileIndex::new();
1314 rule.contribute_to_index(&ctx, &mut index);
1315
1316 assert_eq!(index.cross_file_links.len(), 0);
1318 }
1319
1320 #[test]
1321 fn test_cross_file_check_valid_link() {
1322 use crate::workspace_index::WorkspaceIndex;
1323
1324 let rule = MD057ExistingRelativeLinks::new();
1325
1326 let mut workspace_index = WorkspaceIndex::new();
1328 workspace_index.insert_file(PathBuf::from("docs/guide.md"), FileIndex::new());
1329
1330 let mut file_index = FileIndex::new();
1332 file_index.add_cross_file_link(CrossFileLinkIndex {
1333 target_path: "guide.md".to_string(),
1334 fragment: "".to_string(),
1335 line: 5,
1336 column: 1,
1337 });
1338
1339 let warnings = rule
1341 .cross_file_check(Path::new("docs/index.md"), &file_index, &workspace_index)
1342 .unwrap();
1343
1344 assert!(warnings.is_empty());
1346 }
1347
1348 #[test]
1349 fn test_cross_file_check_missing_link() {
1350 use crate::workspace_index::WorkspaceIndex;
1351
1352 let rule = MD057ExistingRelativeLinks::new();
1353
1354 let workspace_index = WorkspaceIndex::new();
1356
1357 let mut file_index = FileIndex::new();
1359 file_index.add_cross_file_link(CrossFileLinkIndex {
1360 target_path: "missing.md".to_string(),
1361 fragment: "".to_string(),
1362 line: 5,
1363 column: 1,
1364 });
1365
1366 let warnings = rule
1368 .cross_file_check(Path::new("docs/index.md"), &file_index, &workspace_index)
1369 .unwrap();
1370
1371 assert_eq!(warnings.len(), 1);
1373 assert!(warnings[0].message.contains("missing.md"));
1374 assert!(warnings[0].message.contains("does not exist"));
1375 }
1376
1377 #[test]
1378 fn test_cross_file_check_parent_path() {
1379 use crate::workspace_index::WorkspaceIndex;
1380
1381 let rule = MD057ExistingRelativeLinks::new();
1382
1383 let mut workspace_index = WorkspaceIndex::new();
1385 workspace_index.insert_file(PathBuf::from("readme.md"), FileIndex::new());
1386
1387 let mut file_index = FileIndex::new();
1389 file_index.add_cross_file_link(CrossFileLinkIndex {
1390 target_path: "../readme.md".to_string(),
1391 fragment: "".to_string(),
1392 line: 5,
1393 column: 1,
1394 });
1395
1396 let warnings = rule
1398 .cross_file_check(Path::new("docs/guide.md"), &file_index, &workspace_index)
1399 .unwrap();
1400
1401 assert!(warnings.is_empty());
1403 }
1404
1405 #[test]
1406 fn test_normalize_path_function() {
1407 assert_eq!(
1409 normalize_path(Path::new("docs/guide.md")),
1410 PathBuf::from("docs/guide.md")
1411 );
1412
1413 assert_eq!(
1415 normalize_path(Path::new("./docs/guide.md")),
1416 PathBuf::from("docs/guide.md")
1417 );
1418
1419 assert_eq!(
1421 normalize_path(Path::new("docs/sub/../guide.md")),
1422 PathBuf::from("docs/guide.md")
1423 );
1424
1425 assert_eq!(normalize_path(Path::new("a/b/c/../../d.md")), PathBuf::from("a/d.md"));
1427 }
1428
1429 #[test]
1430 fn test_resolve_absolute_link() {
1431 let temp_dir = tempdir().expect("Failed to create temp dir");
1433 let root = temp_dir.path();
1434
1435 let contributing = root.join("CONTRIBUTING.md");
1437 File::create(&contributing).expect("Failed to create CONTRIBUTING.md");
1438
1439 let docs = root.join("docs");
1441 std::fs::create_dir(&docs).expect("Failed to create docs dir");
1442 let readme = docs.join("README.md");
1443 File::create(&readme).expect("Failed to create README.md");
1444
1445 let resolved = resolve_absolute_link(&readme, "CONTRIBUTING.md");
1448 assert!(resolved.exists(), "Should find CONTRIBUTING.md at workspace root");
1449 assert_eq!(resolved, contributing);
1450
1451 let nonexistent = resolve_absolute_link(&readme, "NONEXISTENT.md");
1453 assert!(!nonexistent.exists(), "Should not find nonexistent file");
1454 }
1455
1456 #[test]
1457 fn test_html_link_with_md_source() {
1458 let temp_dir = tempdir().unwrap();
1460 let base_path = temp_dir.path();
1461
1462 let md_file = base_path.join("guide.md");
1464 File::create(&md_file).unwrap().write_all(b"# Guide").unwrap();
1465
1466 let content = r#"
1467[Read the guide](guide.html)
1468[Also here](getting-started.html)
1469"#;
1470
1471 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
1472 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1473 let result = rule.check(&ctx).unwrap();
1474
1475 assert_eq!(
1477 result.len(),
1478 1,
1479 "Should only warn about missing source. Got: {result:?}"
1480 );
1481 assert!(result[0].message.contains("getting-started.html"));
1482 }
1483
1484 #[test]
1485 fn test_htm_link_with_md_source() {
1486 let temp_dir = tempdir().unwrap();
1488 let base_path = temp_dir.path();
1489
1490 let md_file = base_path.join("page.md");
1491 File::create(&md_file).unwrap().write_all(b"# Page").unwrap();
1492
1493 let content = "[Page](page.htm)";
1494
1495 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
1496 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1497 let result = rule.check(&ctx).unwrap();
1498
1499 assert!(
1500 result.is_empty(),
1501 "Should not warn when .md source exists for .htm link"
1502 );
1503 }
1504
1505 #[test]
1506 fn test_html_link_finds_various_markdown_extensions() {
1507 let temp_dir = tempdir().unwrap();
1509 let base_path = temp_dir.path();
1510
1511 File::create(base_path.join("doc.md")).unwrap();
1512 File::create(base_path.join("tutorial.mdx")).unwrap();
1513 File::create(base_path.join("guide.markdown")).unwrap();
1514
1515 let content = r#"
1516[Doc](doc.html)
1517[Tutorial](tutorial.html)
1518[Guide](guide.html)
1519"#;
1520
1521 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
1522 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1523 let result = rule.check(&ctx).unwrap();
1524
1525 assert!(
1526 result.is_empty(),
1527 "Should find all markdown variants as source files. Got: {result:?}"
1528 );
1529 }
1530
1531 #[test]
1532 fn test_html_link_in_subdirectory() {
1533 let temp_dir = tempdir().unwrap();
1535 let base_path = temp_dir.path();
1536
1537 let docs_dir = base_path.join("docs");
1538 std::fs::create_dir(&docs_dir).unwrap();
1539 File::create(docs_dir.join("guide.md"))
1540 .unwrap()
1541 .write_all(b"# Guide")
1542 .unwrap();
1543
1544 let content = "[Guide](docs/guide.html)";
1545
1546 let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
1547 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1548 let result = rule.check(&ctx).unwrap();
1549
1550 assert!(result.is_empty(), "Should find markdown source in subdirectory");
1551 }
1552}