rumdl_lib/rules/
md057_existing_relative_links.rs

1//!
2//! Rule MD057: Existing relative links
3//!
4//! See [docs/md057.md](../../docs/md057.md) for full documentation, configuration, and examples.
5
6use 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
19// Thread-safe cache for file existence checks to avoid redundant filesystem operations
20static FILE_EXISTENCE_CACHE: LazyLock<Arc<Mutex<HashMap<PathBuf, bool>>>> =
21    LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));
22
23// Reset the file existence cache (typically between rule runs)
24fn 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
31// Check if a file exists with caching
32fn 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
39// Regex to match the start of a link - simplified for performance
40static LINK_START_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"!?\[[^\]]*\]").unwrap());
41
42/// Regex to extract the URL from a markdown link
43/// Format: `](URL)` or `](URL "title")`
44static URL_EXTRACT_REGEX: LazyLock<Regex> =
45    LazyLock::new(|| Regex::new("\\]\\(\\s*<?([^>\\)\\s#]+)(#[^)\\s]*)?\\s*(?:\"[^\"]*\")?\\s*>?\\s*\\)").unwrap());
46
47/// Regex to detect protocol and domain for external links
48static PROTOCOL_DOMAIN_REGEX: LazyLock<Regex> =
49    LazyLock::new(|| Regex::new(r"^(https?://|ftp://|mailto:|www\.)").unwrap());
50
51// Current working directory
52static CURRENT_DIR: LazyLock<PathBuf> = LazyLock::new(|| env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
53
54/// Supported markdown file extensions
55const MARKDOWN_EXTENSIONS: &[&str] = &[
56    ".md",
57    ".markdown",
58    ".mdx",
59    ".mkd",
60    ".mkdn",
61    ".mdown",
62    ".mdwn",
63    ".qmd",
64    ".rmd",
65];
66
67/// Check if a path has a markdown extension (case-insensitive)
68#[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/// Rule MD057: Existing relative links should point to valid files or directories.
75#[derive(Debug, Default, Clone)]
76pub struct MD057ExistingRelativeLinks {
77    /// Base directory for resolving relative links
78    base_path: Arc<Mutex<Option<PathBuf>>>,
79}
80
81impl MD057ExistingRelativeLinks {
82    /// Create a new instance with default settings
83    pub fn new() -> Self {
84        Self::default()
85    }
86
87    /// Set the base path for resolving relative links
88    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    /// Check if a URL is external (optimized version)
105    #[inline]
106    fn is_external_url(&self, url: &str) -> bool {
107        if url.is_empty() {
108            return false;
109        }
110
111        // Quick checks for common external URL patterns
112        if PROTOCOL_DOMAIN_REGEX.is_match(url) || url.starts_with("www.") {
113            return true;
114        }
115
116        // Bare domain check (e.g., "example.com")
117        if url.ends_with(".com") {
118            return true;
119        }
120
121        // Absolute paths within the site are not external
122        if url.starts_with('/') {
123            return false;
124        }
125
126        // All other cases (relative paths, etc.) are not external
127        false
128    }
129
130    /// Check if the URL is a fragment-only link (internal document link)
131    #[inline]
132    fn is_fragment_only_link(&self, url: &str) -> bool {
133        url.starts_with('#')
134    }
135
136    /// Resolve a relative link against the base path
137    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    /// Process a single link and check if it exists
146    fn process_link(&self, url: &str, line_num: usize, column: usize, warnings: &mut Vec<LintWarning>) {
147        // Skip empty URLs
148        if url.is_empty() {
149            return;
150        }
151
152        // Skip external URLs and fragment-only links (optimized order)
153        if self.is_external_url(url) || self.is_fragment_only_link(url) {
154            return;
155        }
156
157        // Resolve the relative link against the base path
158        if let Some(resolved_path) = self.resolve_link_path(url) {
159            // Check if the file exists (with caching to avoid filesystem calls)
160            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, // No automatic fix for missing files
170                });
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        // Early returns for performance
197        if content.is_empty() || !content.contains('[') {
198            return Ok(Vec::new());
199        }
200
201        // Quick check for any potential links before expensive operations
202        if !content.contains("](") {
203            return Ok(Vec::new());
204        }
205
206        // Reset the file existence cache for a fresh run
207        reset_file_existence_cache();
208
209        let mut warnings = Vec::new();
210
211        // Determine base path for resolving relative links
212        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                // Get the file path from LintContext
218                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                    // No source file available - cannot validate relative links
225                    None
226                };
227                // Store the computed base path so resolve_link_path can use it
228                *base_path_guard = computed.clone();
229                computed
230            }
231        };
232
233        // If we still don't have a base path, we can't validate relative links
234        if base_path.is_none() {
235            return Ok(warnings);
236        }
237
238        // Use LintContext links instead of expensive regex parsing
239        if !ctx.links.is_empty() {
240            // Use LineIndex for correct position calculation across all line ending types
241            let line_index = &ctx.line_index;
242
243            // Create element cache once for all links
244            let element_cache = ElementCache::new(content);
245
246            // Pre-collect lines to avoid repeated line iteration
247            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                // Quick check for link pattern in this line
258                if !line.contains("](") {
259                    continue;
260                }
261
262                // Find all links in this line using optimized regex
263                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                    // Calculate absolute position using LineIndex
268                    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                    // Skip if this link is in a code span
272                    if element_cache.is_in_code_span(absolute_start_pos) {
273                        continue;
274                    }
275
276                    // Find the URL part after the link text
277                    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                        // Calculate column position
283                        let column = start_pos + 1;
284
285                        // Process and validate the link
286                        self.process_link(url, link.line, column, &mut warnings);
287                    }
288                }
289            }
290        }
291
292        // Also process images - they have URLs already parsed
293        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        // No configurable options for this rule
311        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        // Early returns for performance
330        if content.is_empty() || !content.contains("](") {
331            return;
332        }
333
334        // Pre-collect lines to avoid repeated line iteration
335        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            // Find all links in this line
351            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                // Calculate absolute position for code span detection
356                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                // Skip if in code span
360                if element_cache.is_in_code_span(absolute_start_pos) {
361                    continue;
362                }
363
364                // Extract the URL (group 1) and fragment (group 2)
365                // The regex separates URL and fragment: group 1 excludes #, group 2 captures #fragment
366                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                    // Skip empty, external, or fragment-only URLs
372                    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                    // Get fragment from capture group 2 (includes # prefix)
381                    let fragment = caps.get(2).map(|m| m.as_str().trim_start_matches('#')).unwrap_or("");
382
383                    // Only index markdown file links for cross-file validation
384                    // Non-markdown files (images, media) are validated via filesystem in check()
385                    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        // Get the directory containing this file for resolving relative links
407        let file_dir = file_path.parent();
408
409        for cross_link in &file_index.cross_file_links {
410            // Resolve the relative path
411            let target_path = if cross_link.target_path.starts_with('/') {
412                // Absolute path from workspace root (e.g., "/CONTRIBUTING.md")
413                // Walk up from the current file's directory to find the workspace root
414                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            // Normalize the path (handle .., ., etc.)
423            let target_path = normalize_path(&target_path);
424
425            // Check if the target markdown file exists in the workspace index
426            if !workspace_index.contains_file(&target_path) {
427                // File not in index - check filesystem directly for case-insensitive filesystems
428                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
447/// Normalize a path by resolving . and .. components
448fn 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                // Go up one level if possible
455                if !components.is_empty() {
456                    components.pop();
457                }
458            }
459            std::path::Component::CurDir => {
460                // Skip current directory markers
461            }
462            _ => {
463                components.push(component);
464            }
465        }
466    }
467
468    components.iter().collect()
469}
470
471/// Resolve an absolute link (e.g., "/CONTRIBUTING.md") relative to the workspace root.
472///
473/// Absolute paths in markdown (starting with "/") are relative to the workspace/repo root,
474/// not the filesystem root. This function walks up from the current file's directory
475/// to find where the target file exists.
476fn resolve_absolute_link(file_path: &Path, stripped_path: &str) -> PathBuf {
477    // Walk up from the file's directory, checking each ancestor for the target
478    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    // If not found by walking up, return the path relative to the file's directory
488    // (this will likely fail the existence check later, which is correct behavior)
489    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        // Create a temporary directory for test files
530        let temp_dir = tempdir().unwrap();
531        let base_path = temp_dir.path();
532
533        // Create an existing file
534        let exists_path = base_path.join("exists.md");
535        File::create(&exists_path).unwrap().write_all(b"# Test File").unwrap();
536
537        // Verify the file exists
538        assert!(exists_path.exists(), "exists.md should exist for this test");
539
540        // Create test content with both existing and missing links
541        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        // Initialize rule with the base path (default: check all files including media)
551        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
552
553        // Test the rule
554        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
555        let result = rule.check(&ctx).unwrap();
556
557        // Should have two warnings: missing.md and image.jpg (both don't exist)
558        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        // Create a temporary directory for test files
567        let temp_dir = tempdir().unwrap();
568        let base_path = temp_dir.path();
569
570        // Create an existing file
571        let exists_path = base_path.join("exists.md");
572        File::create(&exists_path).unwrap().write_all(b"# Test File").unwrap();
573
574        // Create test content with angle bracket links
575        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        // Test with default settings
584        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        // Should have one warning for missing.md
590        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        // Create a temporary directory for test files
600        let temp_dir = tempdir().unwrap();
601        let base_path = temp_dir.path();
602
603        // Create a test with various file types - all should be checked
604        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        // Should warn about all missing files regardless of extension
617        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        // Create a temporary directory for test files
625        let temp_dir = tempdir().unwrap();
626        let base_path = temp_dir.path();
627
628        let rule = rule.with_path(base_path);
629
630        // Test with document structure
631        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        // Should only find the real link, not the one in code
637        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        // Create a temporary directory for test files
644        let temp_dir = tempdir().unwrap();
645        let base_path = temp_dir.path();
646
647        // Create test content with links in inline code spans
648        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        // Initialize rule with the base path
660        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
661
662        // Test the rule
663        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
664        let result = rule.check(&ctx).unwrap();
665
666        // Should only have warning for the normal link, not for links in code spans
667        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    // Cross-file validation tests
683    #[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        // Should only index markdown file links
707        assert_eq!(index.cross_file_links.len(), 2);
708
709        // Check first link
710        assert_eq!(index.cross_file_links[0].target_path, "./docs/guide.md");
711        assert_eq!(index.cross_file_links[0].fragment, "");
712
713        // Check second link (with fragment)
714        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        // Should not index any of these
737        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        // Create a workspace index with the target file
747        let mut workspace_index = WorkspaceIndex::new();
748        workspace_index.insert_file(PathBuf::from("docs/guide.md"), FileIndex::new());
749
750        // Create file index with a link to an existing file
751        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        // Run cross-file check from docs/index.md
760        let warnings = rule
761            .cross_file_check(Path::new("docs/index.md"), &file_index, &workspace_index)
762            .unwrap();
763
764        // Should have no warnings - file exists
765        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        // Create an empty workspace index
775        let workspace_index = WorkspaceIndex::new();
776
777        // Create file index with a link to a missing file
778        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        // Run cross-file check
787        let warnings = rule
788            .cross_file_check(Path::new("docs/index.md"), &file_index, &workspace_index)
789            .unwrap();
790
791        // Should have one warning for the missing file
792        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        // Create a workspace index with the target file at the root
804        let mut workspace_index = WorkspaceIndex::new();
805        workspace_index.insert_file(PathBuf::from("readme.md"), FileIndex::new());
806
807        // Create file index with a parent path link
808        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        // Run cross-file check from docs/guide.md
817        let warnings = rule
818            .cross_file_check(Path::new("docs/guide.md"), &file_index, &workspace_index)
819            .unwrap();
820
821        // Should have no warnings - file exists at normalized path
822        assert!(warnings.is_empty());
823    }
824
825    #[test]
826    fn test_normalize_path_function() {
827        // Test simple cases
828        assert_eq!(
829            normalize_path(Path::new("docs/guide.md")),
830            PathBuf::from("docs/guide.md")
831        );
832
833        // Test current directory removal
834        assert_eq!(
835            normalize_path(Path::new("./docs/guide.md")),
836            PathBuf::from("docs/guide.md")
837        );
838
839        // Test parent directory resolution
840        assert_eq!(
841            normalize_path(Path::new("docs/sub/../guide.md")),
842            PathBuf::from("docs/guide.md")
843        );
844
845        // Test multiple parent directories
846        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        // Create a temporary directory structure for testing
852        let temp_dir = tempdir().expect("Failed to create temp dir");
853        let root = temp_dir.path();
854
855        // Create root-level file
856        let contributing = root.join("CONTRIBUTING.md");
857        File::create(&contributing).expect("Failed to create CONTRIBUTING.md");
858
859        // Create nested directory with a markdown file
860        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        // Test: absolute link from nested file to root file
866        // From docs/README.md, link to /CONTRIBUTING.md should resolve to root/CONTRIBUTING.md
867        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        // Test: file that doesn't exist should not resolve (returns path relative to file's dir)
872        let nonexistent = resolve_absolute_link(&readme, "NONEXISTENT.md");
873        assert!(!nonexistent.exists(), "Should not find nonexistent file");
874    }
875}