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    if let Ok(mut cache) = FILE_EXISTENCE_CACHE.lock() {
26        cache.clear();
27    }
28}
29
30// Check if a file exists with caching
31fn 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(), // Fallback to uncached check on mutex poison
35    }
36}
37
38/// Check if a file exists, also trying markdown extensions for extensionless links.
39/// This supports wiki-style links like `[Link](page)` that resolve to `page.md`.
40fn file_exists_or_markdown_extension(path: &Path) -> bool {
41    // First, check exact path
42    if file_exists_with_cache(path) {
43        return true;
44    }
45
46    // If the path has no extension, try adding markdown extensions
47    if path.extension().is_none() {
48        for ext in MARKDOWN_EXTENSIONS {
49            // MARKDOWN_EXTENSIONS includes the dot, e.g., ".md"
50            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
60// Regex to match the start of a link - simplified for performance
61static LINK_START_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"!?\[[^\]]*\]").unwrap());
62
63/// Regex to extract the URL from an angle-bracketed markdown link
64/// Format: `](<URL>)` or `](<URL> "title")`
65/// This handles URLs with parentheses like `](<path/(with)/parens.md>)`
66static URL_EXTRACT_ANGLE_BRACKET_REGEX: LazyLock<Regex> =
67    LazyLock::new(|| Regex::new(r#"\]\(\s*<([^>]+)>(#[^\)\s]*)?\s*(?:"[^"]*")?\s*\)"#).unwrap());
68
69/// Regex to extract the URL from a normal markdown link (without angle brackets)
70/// Format: `](URL)` or `](URL "title")`
71static URL_EXTRACT_REGEX: LazyLock<Regex> =
72    LazyLock::new(|| Regex::new("\\]\\(\\s*([^>\\)\\s#]+)(#[^)\\s]*)?\\s*(?:\"[^\"]*\")?\\s*\\)").unwrap());
73
74/// Regex to detect URLs with explicit schemes (should not be checked as relative links)
75/// Matches: scheme:// or scheme: (per RFC 3986)
76/// This covers http, https, ftp, file, smb, mailto, tel, data, macappstores, etc.
77static 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
80// Current working directory
81static CURRENT_DIR: LazyLock<PathBuf> = LazyLock::new(|| env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
82
83/// Convert a hex digit (0-9, a-f, A-F) to its numeric value.
84/// Returns None for non-hex characters.
85#[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
95/// Supported markdown file extensions
96const MARKDOWN_EXTENSIONS: &[&str] = &[
97    ".md",
98    ".markdown",
99    ".mdx",
100    ".mkd",
101    ".mkdn",
102    ".mdown",
103    ".mdwn",
104    ".qmd",
105    ".rmd",
106];
107
108/// Check if a path has a markdown extension (case-insensitive)
109#[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/// Rule MD057: Existing relative links should point to valid files or directories.
116#[derive(Debug, Clone, Default)]
117pub struct MD057ExistingRelativeLinks {
118    /// Base directory for resolving relative links
119    base_path: Arc<Mutex<Option<PathBuf>>>,
120}
121
122impl MD057ExistingRelativeLinks {
123    /// Create a new instance with default settings
124    pub fn new() -> Self {
125        Self::default()
126    }
127
128    /// Set the base path for resolving relative links
129    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    /// Check if a URL is external or should be skipped for validation.
149    ///
150    /// Returns `true` (skip validation) for:
151    /// - URLs with protocols: `https://`, `http://`, `ftp://`, `mailto:`, etc.
152    /// - Bare domains: `www.example.com`, `example.com`
153    /// - Template variables: `{{URL}}`, `{{% include %}}`
154    /// - Absolute web URL paths: `/api/docs`, `/blog/post.html`
155    ///
156    /// Returns `false` (validate) for:
157    /// - Relative filesystem paths: `./file.md`, `../parent/file.md`, `file.md`
158    #[inline]
159    fn is_external_url(&self, url: &str) -> bool {
160        if url.is_empty() {
161            return false;
162        }
163
164        // Quick checks for common external URL patterns
165        if PROTOCOL_DOMAIN_REGEX.is_match(url) || url.starts_with("www.") {
166            return true;
167        }
168
169        // Skip template variables (Handlebars/Mustache/Jinja2 syntax)
170        // Examples: {{URL}}, {{#URL}}, {{> partial}}, {{% include %}}, {{ variable }}
171        if url.starts_with("{{") || url.starts_with("{%") {
172            return true;
173        }
174
175        // Bare domain check (e.g., "example.com")
176        // Note: We intentionally DON'T skip all TLDs like .org, .net, etc.
177        // Links like [text](nodejs.org/path) without a protocol are broken -
178        // they'll be treated as relative paths by markdown renderers.
179        // Flagging them helps users find missing protocols.
180        // We only skip .com as a minimal safety net for the most common case.
181        if url.ends_with(".com") {
182            return true;
183        }
184
185        // Absolute URL paths (e.g., /api/docs, /blog/post.html) are treated as web paths
186        // and skipped. These are typically routes for published documentation sites,
187        // not filesystem paths that can be validated locally.
188        if url.starts_with('/') {
189            return true;
190        }
191
192        // Framework path aliases (resolved by build tools like Vite, webpack, etc.)
193        // These are not filesystem paths but module/asset aliases
194        // Examples: ~/assets/image.png, @images/photo.jpg, @/components/Button.vue
195        if url.starts_with('~') || url.starts_with('@') {
196            return true;
197        }
198
199        // All other cases (relative paths, etc.) are not external
200        false
201    }
202
203    /// Check if the URL is a fragment-only link (internal document link)
204    #[inline]
205    fn is_fragment_only_link(&self, url: &str) -> bool {
206        url.starts_with('#')
207    }
208
209    /// Decode URL percent-encoded sequences in a path.
210    /// Converts `%20` to space, `%2F` to `/`, etc.
211    /// Returns the original string if decoding fails or produces invalid UTF-8.
212    fn url_decode(path: &str) -> String {
213        // Quick check: if no percent sign, return as-is
214        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                // Try to parse the two hex digits following %
225                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        // Convert to UTF-8, falling back to original if invalid
238        String::from_utf8(result).unwrap_or_else(|_| path.to_string())
239    }
240
241    /// Strip query parameters and fragments from a URL for file existence checking.
242    /// URLs like `path/to/image.png?raw=true` or `file.md#section` should check
243    /// for `path/to/image.png` or `file.md` respectively.
244    ///
245    /// Note: In standard URLs, query parameters (`?`) come before fragments (`#`),
246    /// so we check for `?` first. If a URL has both, only the query is stripped here
247    /// (fragments are handled separately by the regex in `contribute_to_index`).
248    fn strip_query_and_fragment(url: &str) -> &str {
249        // Find the first occurrence of '?' or '#', whichever comes first
250        // This handles both standard URLs (? before #) and edge cases (# before ?)
251        let query_pos = url.find('?');
252        let fragment_pos = url.find('#');
253
254        match (query_pos, fragment_pos) {
255            (Some(q), Some(f)) => {
256                // Both exist - strip at whichever comes first
257                &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    /// Resolve a relative link against a provided base path
266    fn resolve_link_path_with_base(link: &str, base_path: &Path) -> PathBuf {
267        base_path.join(link)
268    }
269
270    /// Process a single link and check if it exists
271    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        // Skip empty URLs
280        if url.is_empty() {
281            return;
282        }
283
284        // Skip external URLs and fragment-only links (optimized order)
285        if self.is_external_url(url) || self.is_fragment_only_link(url) {
286            return;
287        }
288
289        // Strip query parameters and fragments before checking file existence
290        // URLs like `path/to/image.png?raw=true` should check for `path/to/image.png`
291        let file_path = Self::strip_query_and_fragment(url);
292
293        // URL-decode the path to handle percent-encoded characters
294        // e.g., `penguin%20with%20space.jpg` -> `penguin with space.jpg`
295        let decoded_path = Self::url_decode(file_path);
296
297        // Resolve the relative link against the base path
298        let resolved_path = Self::resolve_link_path_with_base(&decoded_path, base_path);
299
300        // Check if the file exists, also trying markdown extensions for extensionless links
301        if file_exists_or_markdown_extension(&resolved_path) {
302            return; // File exists, no warning needed
303        }
304
305        // For .html/.htm links, check if a corresponding markdown source exists
306        // This handles doc sites where .md is compiled to .html at build time
307        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; // Markdown source exists, link is valid
318                }
319            }
320        }
321
322        // File doesn't exist and no source file found
323        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        // Early returns for performance
357        if content.is_empty() || !content.contains('[') {
358            return Ok(Vec::new());
359        }
360
361        // Quick check for any potential links before expensive operations
362        if !content.contains("](") {
363            return Ok(Vec::new());
364        }
365
366        // Reset the file existence cache for a fresh run
367        reset_file_existence_cache();
368
369        let mut warnings = Vec::new();
370
371        // Determine base path for resolving relative links
372        // ALWAYS compute from ctx.source_file for each file - do not reuse cached base_path
373        // This ensures each file resolves links relative to its own directory
374        let base_path: Option<PathBuf> = {
375            // First check if base_path was explicitly set via with_path() (for tests)
376            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                // Resolve symlinks to get the actual file location
381                // This ensures relative links are resolved from the target's directory,
382                // not the symlink's directory
383                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                // No source file available - cannot validate relative links
390                None
391            }
392        };
393
394        // If we still don't have a base path, we can't validate relative links
395        let Some(base_path) = base_path else {
396            return Ok(warnings);
397        };
398
399        // Use LintContext links instead of expensive regex parsing
400        if !ctx.links.is_empty() {
401            // Use LineIndex for correct position calculation across all line ending types
402            let line_index = &ctx.line_index;
403
404            // Create element cache once for all links
405            let element_cache = ElementCache::new(content);
406
407            // Pre-collect lines to avoid repeated line iteration
408            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                // Quick check for link pattern in this line
419                if !line.contains("](") {
420                    continue;
421                }
422
423                // Find all links in this line using optimized regex
424                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                    // Calculate absolute position using LineIndex
429                    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                    // Skip if this link is in a code span
433                    if element_cache.is_in_code_span(absolute_start_pos) {
434                        continue;
435                    }
436
437                    // Find the URL part after the link text
438                    // Try angle-bracket regex first (handles URLs with parens like `<path/(with)/parens.md>`)
439                    // Then fall back to normal URL regex
440                    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                        // Calculate column position
453                        let column = start_pos + 1;
454
455                        // Process and validate the link
456                        self.process_link_with_base(url, link.line, column, &base_path, &mut warnings);
457                    }
458                }
459            }
460        }
461
462        // Also process images - they have URLs already parsed
463        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        // No configurable options for this rule
481        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        // Early returns for performance
500        if content.is_empty() || !content.contains("](") {
501            return;
502        }
503
504        // Pre-collect lines to avoid repeated line iteration
505        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            // Find all links in this line
521            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                // Calculate absolute position for code span detection
526                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                // Skip if in code span
530                if element_cache.is_in_code_span(absolute_start_pos) {
531                    continue;
532                }
533
534                // Extract the URL (group 1) and fragment (group 2)
535                // The regex separates URL and fragment: group 1 excludes #, group 2 captures #fragment
536                // Try angle-bracket regex first (handles URLs with parens)
537                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                    // Skip empty, external, template variables, absolute URL paths,
547                    // framework aliases, or fragment-only URLs
548                    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                    // Strip query parameters before indexing (e.g., `file.md?raw=true` -> `file.md`)
562                    let file_path = Self::strip_query_and_fragment(file_path);
563
564                    // Get fragment from capture group 2 (includes # prefix)
565                    let fragment = caps.get(2).map(|m| m.as_str().trim_start_matches('#')).unwrap_or("");
566
567                    // Only index markdown file links for cross-file validation
568                    // Non-markdown files (images, media) are validated via filesystem in check()
569                    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        // Get the directory containing this file for resolving relative links
591        let file_dir = file_path.parent();
592
593        for cross_link in &file_index.cross_file_links {
594            // Resolve the relative path
595            let target_path = if cross_link.target_path.starts_with('/') {
596                // Absolute path from workspace root (e.g., "/CONTRIBUTING.md")
597                // Walk up from the current file's directory to find the workspace root
598                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            // Normalize the path (handle .., ., etc.)
607            let target_path = normalize_path(&target_path);
608
609            // Check if the target markdown file exists in the workspace index
610            if !workspace_index.contains_file(&target_path) {
611                // File not in index - check filesystem directly for case-insensitive filesystems
612                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
631/// Normalize a path by resolving . and .. components
632fn 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                // Go up one level if possible
639                if !components.is_empty() {
640                    components.pop();
641                }
642            }
643            std::path::Component::CurDir => {
644                // Skip current directory markers
645            }
646            _ => {
647                components.push(component);
648            }
649        }
650    }
651
652    components.iter().collect()
653}
654
655/// Resolve an absolute link (e.g., "/CONTRIBUTING.md") relative to the workspace root.
656///
657/// Absolute paths in markdown (starting with "/") are relative to the workspace/repo root,
658/// not the filesystem root. This function walks up from the current file's directory
659/// to find where the target file exists.
660fn resolve_absolute_link(file_path: &Path, stripped_path: &str) -> PathBuf {
661    // Walk up from the file's directory, checking each ancestor for the target
662    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    // If not found by walking up, return the path relative to the file's directory
672    // (this will likely fail the existence check later, which is correct behavior)
673    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        // Test query parameter stripping
689        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        // Test fragment stripping
703        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        // Test both query and fragment (query comes first, per RFC 3986)
713        assert_eq!(
714            MD057ExistingRelativeLinks::strip_query_and_fragment("file.md?raw=true#section"),
715            "file.md"
716        );
717
718        // Test no query or fragment
719        assert_eq!(
720            MD057ExistingRelativeLinks::strip_query_and_fragment("file.png"),
721            "file.png"
722        );
723
724        // Test with path
725        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        // Edge case: fragment before query (non-standard but possible)
735        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        // Simple space encoding
744        assert_eq!(
745            MD057ExistingRelativeLinks::url_decode("penguin%20with%20space.jpg"),
746            "penguin with space.jpg"
747        );
748
749        // Path with encoded spaces
750        assert_eq!(
751            MD057ExistingRelativeLinks::url_decode("assets/my%20file%20name.png"),
752            "assets/my file name.png"
753        );
754
755        // Multiple encoded characters
756        assert_eq!(
757            MD057ExistingRelativeLinks::url_decode("hello%20world%21.md"),
758            "hello world!.md"
759        );
760
761        // Lowercase hex
762        assert_eq!(MD057ExistingRelativeLinks::url_decode("%2f%2e%2e"), "/..");
763
764        // Uppercase hex
765        assert_eq!(MD057ExistingRelativeLinks::url_decode("%2F%2E%2E"), "/..");
766
767        // Mixed case hex
768        assert_eq!(MD057ExistingRelativeLinks::url_decode("%2f%2E%2e"), "/..");
769
770        // No encoding - return as-is
771        assert_eq!(
772            MD057ExistingRelativeLinks::url_decode("normal-file.md"),
773            "normal-file.md"
774        );
775
776        // Incomplete percent encoding - leave as-is
777        assert_eq!(MD057ExistingRelativeLinks::url_decode("file%2.txt"), "file%2.txt");
778
779        // Percent at end - leave as-is
780        assert_eq!(MD057ExistingRelativeLinks::url_decode("file%"), "file%");
781
782        // Invalid hex digits - leave as-is
783        assert_eq!(MD057ExistingRelativeLinks::url_decode("file%GG.txt"), "file%GG.txt");
784
785        // Plus sign (should NOT be decoded - that's form encoding, not URL encoding)
786        assert_eq!(MD057ExistingRelativeLinks::url_decode("file+name.txt"), "file+name.txt");
787
788        // Empty string
789        assert_eq!(MD057ExistingRelativeLinks::url_decode(""), "");
790
791        // UTF-8 multi-byte characters (é = C3 A9 in UTF-8)
792        assert_eq!(MD057ExistingRelativeLinks::url_decode("caf%C3%A9.md"), "café.md");
793
794        // Multiple consecutive encoded characters
795        assert_eq!(MD057ExistingRelativeLinks::url_decode("%20%20%20"), "   ");
796
797        // Encoded path separators
798        assert_eq!(
799            MD057ExistingRelativeLinks::url_decode("path%2Fto%2Ffile.md"),
800            "path/to/file.md"
801        );
802
803        // Mixed encoded and non-encoded
804        assert_eq!(
805            MD057ExistingRelativeLinks::url_decode("hello%20world/foo%20bar.md"),
806            "hello world/foo bar.md"
807        );
808
809        // Special characters that are commonly encoded
810        assert_eq!(MD057ExistingRelativeLinks::url_decode("file%5B1%5D.md"), "file[1].md");
811
812        // Percent at position that looks like encoding but isn't valid
813        assert_eq!(MD057ExistingRelativeLinks::url_decode("100%pure.md"), "100%pure.md");
814    }
815
816    #[test]
817    fn test_url_encoded_filenames() {
818        // Create a temporary directory for test files
819        let temp_dir = tempdir().unwrap();
820        let base_path = temp_dir.path();
821
822        // Create a file with spaces in the name
823        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        // Create a subdirectory with spaces
830        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        // Test content with URL-encoded links
836        let content = r#"
837# Test Document with URL-Encoded Links
838
839![Penguin](penguin%20with%20space.jpg)
840![Photo](my%20images/photo%201.png)
841![Missing](missing%20file.jpg)
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        // Should only have one warning for the missing file
850        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        // Common web protocols
866        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        // Special URI schemes (issue #192)
873        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        // Template variables should be skipped (not checked as relative links)
884        assert!(rule.is_external_url("{{URL}}")); // Handlebars/Mustache
885        assert!(rule.is_external_url("{{#URL}}")); // Handlebars block helper
886        assert!(rule.is_external_url("{{> partial}}")); // Handlebars partial
887        assert!(rule.is_external_url("{{ variable }}")); // Mustache with spaces
888        assert!(rule.is_external_url("{{% include %}}")); // Jinja2/Hugo shortcode
889        assert!(rule.is_external_url("{{")); // Even partial matches (regex edge case)
890
891        // Absolute web URL paths should be skipped (not validated)
892        // These are typically routes for published documentation sites
893        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        // Framework path aliases should be skipped (resolved by build tools)
902        // Tilde prefix (common in Vite, Nuxt, Astro for project root)
903        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")); // Nuxt style without /
906
907        // @ prefix (common in Vue, webpack, Vite aliases)
908        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        // Relative paths should NOT be external (should be validated)
913        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        // Create a temporary directory for test files
921        let temp_dir = tempdir().unwrap();
922        let base_path = temp_dir.path();
923
924        // Test content with framework path aliases (should all be skipped)
925        let content = r#"
926# Framework Path Aliases
927
928![Image 1](~/assets/penguin.jpg)
929![Image 2](~assets/logo.svg)
930![Image 3](@images/photo.jpg)
931![Image 4](@/components/icon.svg)
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        // Should only have one warning for the real missing link
943        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        // Ensure URL decoding doesn't enable path traversal attacks
957        // The decoded path is still validated against the base path
958        let temp_dir = tempdir().unwrap();
959        let base_path = temp_dir.path();
960
961        // Create a file in the temp directory
962        let file_in_base = base_path.join("safe.md");
963        File::create(&file_in_base).unwrap().write_all(b"# Safe").unwrap();
964
965        // Test with encoded path traversal attempt
966        // Use a path that definitely won't exist on any platform (not /etc/passwd which exists on Linux)
967        // %2F = /, so ..%2F..%2Fnonexistent%2Ffile = ../../nonexistent/file
968        // %252F = %2F (double encoded), so ..%252F..%252F = ..%2F..%2F (literal, won't decode to ..)
969        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        // The traversal attempts should still be flagged as missing
981        // (they don't exist relative to base_path after decoding)
982        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        // Test with actual UTF-8 encoded filenames
992        let temp_dir = tempdir().unwrap();
993        let base_path = temp_dir.path();
994
995        // Create files with unicode names
996        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        // Should only warn about the missing file
1010        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        // Create a temporary directory for test files
1034        let temp_dir = tempdir().unwrap();
1035        let base_path = temp_dir.path();
1036
1037        // Create an existing file
1038        let exists_path = base_path.join("exists.md");
1039        File::create(&exists_path).unwrap().write_all(b"# Test File").unwrap();
1040
1041        // Verify the file exists
1042        assert!(exists_path.exists(), "exists.md should exist for this test");
1043
1044        // Create test content with both existing and missing links
1045        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        // Initialize rule with the base path (default: check all files including media)
1055        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
1056
1057        // Test the rule
1058        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1059        let result = rule.check(&ctx).unwrap();
1060
1061        // Should have two warnings: missing.md and image.jpg (both don't exist)
1062        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        // Create a temporary directory for test files
1071        let temp_dir = tempdir().unwrap();
1072        let base_path = temp_dir.path();
1073
1074        // Create an existing file
1075        let exists_path = base_path.join("exists.md");
1076        File::create(&exists_path).unwrap().write_all(b"# Test File").unwrap();
1077
1078        // Create test content with angle bracket links
1079        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        // Test with default settings
1088        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        // Should have one warning for missing.md
1094        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        // Create a temporary directory for test files
1104        let temp_dir = tempdir().unwrap();
1105        let base_path = temp_dir.path();
1106
1107        // Create directory structure with parentheses in path
1108        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        // Create test content with angle bracket links containing parentheses
1119        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        // Should only have one warning for the missing file
1133        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        // Create a temporary directory for test files
1147        let temp_dir = tempdir().unwrap();
1148        let base_path = temp_dir.path();
1149
1150        // Create a test with various file types - all should be checked
1151        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        // Should warn about all missing files regardless of extension
1164        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        // Create a temporary directory for test files
1172        let temp_dir = tempdir().unwrap();
1173        let base_path = temp_dir.path();
1174
1175        let rule = rule.with_path(base_path);
1176
1177        // Test with document structure
1178        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        // Should only find the real link, not the one in code
1184        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        // Create a temporary directory for test files
1191        let temp_dir = tempdir().unwrap();
1192        let base_path = temp_dir.path();
1193
1194        // Create test content with links in inline code spans
1195        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        // Initialize rule with the base path
1207        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
1208
1209        // Test the rule
1210        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1211        let result = rule.check(&ctx).unwrap();
1212
1213        // Should only have warning for the normal link, not for links in code spans
1214        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        // Create a temporary directory for test files
1232        let temp_dir = tempdir().unwrap();
1233        let base_path = temp_dir.path();
1234
1235        // Create a markdown file WITHOUT specifying .md extension in the link
1236        let page_path = base_path.join("page.md");
1237        File::create(&page_path).unwrap().write_all(b"# Page").unwrap();
1238
1239        // Test content with extensionless link that should resolve to page.md
1240        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        // Should only have warning for nonexistent link
1254        // Both "page" and "page.md" should resolve to the same file
1255        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    // Cross-file validation tests
1263    #[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        // Should only index markdown file links
1287        assert_eq!(index.cross_file_links.len(), 2);
1288
1289        // Check first link
1290        assert_eq!(index.cross_file_links[0].target_path, "./docs/guide.md");
1291        assert_eq!(index.cross_file_links[0].fragment, "");
1292
1293        // Check second link (with fragment)
1294        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        // Should not index any of these
1317        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        // Create a workspace index with the target file
1327        let mut workspace_index = WorkspaceIndex::new();
1328        workspace_index.insert_file(PathBuf::from("docs/guide.md"), FileIndex::new());
1329
1330        // Create file index with a link to an existing file
1331        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        // Run cross-file check from docs/index.md
1340        let warnings = rule
1341            .cross_file_check(Path::new("docs/index.md"), &file_index, &workspace_index)
1342            .unwrap();
1343
1344        // Should have no warnings - file exists
1345        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        // Create an empty workspace index
1355        let workspace_index = WorkspaceIndex::new();
1356
1357        // Create file index with a link to a missing file
1358        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        // Run cross-file check
1367        let warnings = rule
1368            .cross_file_check(Path::new("docs/index.md"), &file_index, &workspace_index)
1369            .unwrap();
1370
1371        // Should have one warning for the missing file
1372        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        // Create a workspace index with the target file at the root
1384        let mut workspace_index = WorkspaceIndex::new();
1385        workspace_index.insert_file(PathBuf::from("readme.md"), FileIndex::new());
1386
1387        // Create file index with a parent path link
1388        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        // Run cross-file check from docs/guide.md
1397        let warnings = rule
1398            .cross_file_check(Path::new("docs/guide.md"), &file_index, &workspace_index)
1399            .unwrap();
1400
1401        // Should have no warnings - file exists at normalized path
1402        assert!(warnings.is_empty());
1403    }
1404
1405    #[test]
1406    fn test_normalize_path_function() {
1407        // Test simple cases
1408        assert_eq!(
1409            normalize_path(Path::new("docs/guide.md")),
1410            PathBuf::from("docs/guide.md")
1411        );
1412
1413        // Test current directory removal
1414        assert_eq!(
1415            normalize_path(Path::new("./docs/guide.md")),
1416            PathBuf::from("docs/guide.md")
1417        );
1418
1419        // Test parent directory resolution
1420        assert_eq!(
1421            normalize_path(Path::new("docs/sub/../guide.md")),
1422            PathBuf::from("docs/guide.md")
1423        );
1424
1425        // Test multiple parent directories
1426        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        // Create a temporary directory structure for testing
1432        let temp_dir = tempdir().expect("Failed to create temp dir");
1433        let root = temp_dir.path();
1434
1435        // Create root-level file
1436        let contributing = root.join("CONTRIBUTING.md");
1437        File::create(&contributing).expect("Failed to create CONTRIBUTING.md");
1438
1439        // Create nested directory with a markdown file
1440        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        // Test: absolute link from nested file to root file
1446        // From docs/README.md, link to /CONTRIBUTING.md should resolve to root/CONTRIBUTING.md
1447        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        // Test: file that doesn't exist should not resolve (returns path relative to file's dir)
1452        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        // Links to .html files should pass if corresponding .md source exists
1459        let temp_dir = tempdir().unwrap();
1460        let base_path = temp_dir.path();
1461
1462        // Create guide.md (source file)
1463        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        // guide.html passes (guide.md exists), getting-started.html fails
1476        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        // .htm extension should also check for markdown source
1487        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        // Should find .mdx, .markdown, etc. as source files
1508        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        // Should find markdown source in subdirectories
1534        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}