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        // Cache base path lookup to avoid repeated mutex operations
212        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                // Try to determine the base path from the file being processed (cached)
218                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 we still don't have a base path, we can't validate relative links
239        if base_path.is_none() {
240            return Ok(warnings);
241        }
242
243        // Use LintContext links instead of expensive regex parsing
244        if !ctx.links.is_empty() {
245            // Use LineIndex for correct position calculation across all line ending types
246            let line_index = &ctx.line_index;
247
248            // Create element cache once for all links
249            let element_cache = ElementCache::new(content);
250
251            // Pre-collect lines to avoid repeated line iteration
252            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                // Quick check for link pattern in this line
263                if !line.contains("](") {
264                    continue;
265                }
266
267                // Find all links in this line using optimized regex
268                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                    // Calculate absolute position using LineIndex
273                    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                    // Skip if this link is in a code span
277                    if element_cache.is_in_code_span(absolute_start_pos) {
278                        continue;
279                    }
280
281                    // Find the URL part after the link text
282                    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                        // Calculate column position
288                        let column = start_pos + 1;
289
290                        // Process and validate the link
291                        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        // No configurable options for this rule
310        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        // Early returns for performance
329        if content.is_empty() || !content.contains("](") {
330            return;
331        }
332
333        // Pre-collect lines to avoid repeated line iteration
334        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            // Find all links in this line
350            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                // Calculate absolute position for code span detection
355                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                // Skip if in code span
359                if element_cache.is_in_code_span(absolute_start_pos) {
360                    continue;
361                }
362
363                // Extract the URL (group 1) and fragment (group 2)
364                // The regex separates URL and fragment: group 1 excludes #, group 2 captures #fragment
365                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                    // Skip empty, external, or fragment-only URLs
371                    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                    // Get fragment from capture group 2 (includes # prefix)
380                    let fragment = caps.get(2).map(|m| m.as_str().trim_start_matches('#')).unwrap_or("");
381
382                    // Only index links to markdown files
383                    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        // Get the directory containing this file for resolving relative links
405        let file_dir = file_path.parent();
406
407        for cross_link in &file_index.cross_file_links {
408            // Resolve the relative path
409            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            // Normalize the path (handle .., ., etc.)
416            let target_path = normalize_path(&target_path);
417
418            // Check if the target file exists in the workspace index
419            if !workspace_index.contains_file(&target_path) {
420                // File not in index - it might not exist or might not be a markdown file
421                // For markdown files, if they're not indexed, they don't exist in the workspace
422                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
444/// Normalize a path by resolving . and .. components
445fn 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                // Go up one level if possible
452                if !components.is_empty() {
453                    components.pop();
454                }
455            }
456            std::path::Component::CurDir => {
457                // Skip current directory markers
458            }
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        // Create a temporary directory for test files
503        let temp_dir = tempdir().unwrap();
504        let base_path = temp_dir.path();
505
506        // Create an existing file
507        let exists_path = base_path.join("exists.md");
508        File::create(&exists_path).unwrap().write_all(b"# Test File").unwrap();
509
510        // Verify the file exists
511        assert!(exists_path.exists(), "exists.md should exist for this test");
512
513        // Create test content with both existing and missing links
514        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        // Initialize rule with the base path (default: check all files including media)
524        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
525
526        // Test the rule
527        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
528        let result = rule.check(&ctx).unwrap();
529
530        // Should have two warnings: missing.md and image.jpg (both don't exist)
531        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        // Create a temporary directory for test files
540        let temp_dir = tempdir().unwrap();
541        let base_path = temp_dir.path();
542
543        // Create an existing file
544        let exists_path = base_path.join("exists.md");
545        File::create(&exists_path).unwrap().write_all(b"# Test File").unwrap();
546
547        // Create test content with angle bracket links
548        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        // Test with default settings
557        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        // Should have one warning for missing.md
563        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        // Create a temporary directory for test files
573        let temp_dir = tempdir().unwrap();
574        let base_path = temp_dir.path();
575
576        // Create a test with various file types - all should be checked
577        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        // Should warn about all missing files regardless of extension
590        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        // Create a temporary directory for test files
598        let temp_dir = tempdir().unwrap();
599        let base_path = temp_dir.path();
600
601        let rule = rule.with_path(base_path);
602
603        // Test with document structure
604        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        // Should only find the real link, not the one in code
610        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        // Create a temporary directory for test files
617        let temp_dir = tempdir().unwrap();
618        let base_path = temp_dir.path();
619
620        // Create test content with links in inline code spans
621        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        // Initialize rule with the base path
633        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
634
635        // Test the rule
636        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
637        let result = rule.check(&ctx).unwrap();
638
639        // Should only have warning for the normal link, not for links in code spans
640        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    // Cross-file validation tests
656    #[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        // Should only index markdown file links
680        assert_eq!(index.cross_file_links.len(), 2);
681
682        // Check first link
683        assert_eq!(index.cross_file_links[0].target_path, "./docs/guide.md");
684        assert_eq!(index.cross_file_links[0].fragment, "");
685
686        // Check second link (with fragment)
687        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        // Should not index any of these
710        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        // Create a workspace index with the target file
720        let mut workspace_index = WorkspaceIndex::new();
721        workspace_index.insert_file(PathBuf::from("docs/guide.md"), FileIndex::new());
722
723        // Create file index with a link to an existing file
724        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        // Run cross-file check from docs/index.md
733        let warnings = rule
734            .cross_file_check(Path::new("docs/index.md"), &file_index, &workspace_index)
735            .unwrap();
736
737        // Should have no warnings - file exists
738        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        // Create an empty workspace index
748        let workspace_index = WorkspaceIndex::new();
749
750        // Create file index with a link to a missing file
751        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        // Run cross-file check
760        let warnings = rule
761            .cross_file_check(Path::new("docs/index.md"), &file_index, &workspace_index)
762            .unwrap();
763
764        // Should have one warning for the missing file
765        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        // Create a workspace index with the target file at the root
777        let mut workspace_index = WorkspaceIndex::new();
778        workspace_index.insert_file(PathBuf::from("readme.md"), FileIndex::new());
779
780        // Create file index with a parent path link
781        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        // Run cross-file check from docs/guide.md
790        let warnings = rule
791            .cross_file_check(Path::new("docs/guide.md"), &file_index, &workspace_index)
792            .unwrap();
793
794        // Should have no warnings - file exists at normalized path
795        assert!(warnings.is_empty());
796    }
797
798    #[test]
799    fn test_normalize_path_function() {
800        // Test simple cases
801        assert_eq!(
802            normalize_path(Path::new("docs/guide.md")),
803            PathBuf::from("docs/guide.md")
804        );
805
806        // Test current directory removal
807        assert_eq!(
808            normalize_path(Path::new("./docs/guide.md")),
809            PathBuf::from("docs/guide.md")
810        );
811
812        // Test parent directory resolution
813        assert_eq!(
814            normalize_path(Path::new("docs/sub/../guide.md")),
815            PathBuf::from("docs/guide.md")
816        );
817
818        // Test multiple parent directories
819        assert_eq!(normalize_path(Path::new("a/b/c/../../d.md")), PathBuf::from("a/d.md"));
820    }
821}