Skip to content

Commit e215c65

Browse files
committed
fix(md051): validate cross-file link fragments for a document read from stdin
A run over files indexes the whole workspace before resolving cross-file references. A document piped through `--stdin` has no workspace, so MD051's cross-file check found nothing to resolve against and stayed silent: `rumdl check .` reported a broken `[link](other.md#missing)` and piping the same bytes with `--stdin-filename` reported nothing. Editors and pre-commit hooks drive rumdl this way, so the finding disappeared for them. The stdin path now resolves the targets the piped document names, reading each from disk exactly as MD057 already does here, and only for links that carry a fragment. A document that links to itself is resolved against the piped buffer rather than the copy on disk, which is the whole point of piping an unsaved buffer. Without `--stdin-filename` there is no directory to resolve a relative destination against, so nothing is read and nothing is reported, matching MD057. Which files a run knows about is decided by the ignore files, the configured include and exclude patterns and the walk's own extension filter, all of which interact, so a target is read only when a directory scan of the same project would index it - and that question is put to the scanner itself rather than to a second opinion about what it would do. A gitignored or config-excluded target is one `rumdl check .` never reads, and reading it here would report a finding the batch run does not. The scan runs at most once per document, and only once a destination names a file that exists. A scan also indexes each file under the config that governs it, so a target is read under the config a scan would have resolved for it rather than the piped document's. A directory with its own rumdl config decides how its headings are anchored, and reading its files under the root config would check a link against anchors that file does not have. A config governing a target that fails to load counts toward --deny-config-warnings, exactly as it does for a run over files. Nothing from a target reaches the output: a finding names the fragment and the destination as the piped document wrote them. Resolving a destination to the file it names is now one shared function, replacing three private copies of the same walk, and it keeps a traversal that leaves the path's own root. A `--stdin-filename` is usually relative, so `../notes.md` had nothing above it to cancel and the `..` was dropped, renaming the target to a sibling that exists, sits in the workspace and answers with its own headings. Above a real root there is nothing to name, so `/..` stays `/`, which is what the filesystem answers.
1 parent 7c8390f commit e215c65

9 files changed

Lines changed: 844 additions & 164 deletions

‎src/check_runner.rs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,19 @@ pub fn perform_check_run(ctx: &CheckRunContext<'_>) -> CheckRunOutcome {
128128
args,
129129
&stdin.config,
130130
external_config_warning || stdin.config_warning,
131+
// Resolving this document's cross-file references reads files from the
132+
// project, and each of them is governed by whatever config a scan would
133+
// have resolved for it, so the stdin path is handed the same roots and
134+
// overrides a run over paths resolves its groups with.
135+
&crate::stdin_processor::StdinWorkspace {
136+
root: crate::resolution::RootConfig { config, sourced },
137+
roots: crate::resolution::ResolutionRoots {
138+
grouping_root,
139+
project_root,
140+
},
141+
inline_overrides,
142+
bypass_discovery: explicit_config || isolated,
143+
},
131144
);
132145
// stdin owns its own exit (including the --deny-config-warnings decision,
133146
// wired in the stdin processor), so nothing to report here.

‎src/lsp/completion.rs‎

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ use crate::linguist_data::{CANONICAL_TO_ALIASES, default_alias};
1616
use crate::rule_config_serde::load_rule_config;
1717
use crate::rules::md040_fenced_code_language::md040_config::MD040Config;
1818

19+
use crate::workspace_index::normalize_relative_path;
20+
1921
use super::position::{byte_to_utf16_offset, utf16_to_byte_offset};
2022
use super::server::RumdlLanguageServer;
2123

@@ -503,7 +505,7 @@ impl RumdlLanguageServer {
503505
let base = if rel_dir.is_empty() {
504506
root.clone()
505507
} else {
506-
normalize_path(&root.join(rel_dir))
508+
normalize_relative_path(&root.join(rel_dir))
507509
};
508510

509511
// List only the immediate children of `base`, honoring .gitignore.
@@ -602,7 +604,7 @@ impl RumdlLanguageServer {
602604
out.push(super::resolve_workspace_root(&path));
603605
} else {
604606
for root in roots.iter() {
605-
out.push(normalize_path(&root.join(&path)));
607+
out.push(normalize_relative_path(&root.join(&path)));
606608
}
607609
}
608610
}
@@ -633,7 +635,7 @@ impl RumdlLanguageServer {
633635
let content_roots = self.resolve_content_roots().await;
634636
let candidates: Vec<PathBuf> = content_roots
635637
.iter()
636-
.map(|root| normalize_path(&root.join(rel)))
638+
.map(|root| normalize_relative_path(&root.join(rel)))
637639
.collect();
638640
let indexed = {
639641
let index = self.workspace_index.read().await;
@@ -643,7 +645,7 @@ impl RumdlLanguageServer {
643645
}
644646

645647
let current_dir = current_file.parent()?;
646-
Some(normalize_path(&current_dir.join(file_path)))
648+
Some(normalize_relative_path(&current_dir.join(file_path)))
647649
}
648650

649651
/// Get heading anchor completion items for a markdown link target
@@ -772,18 +774,3 @@ fn path_distance(rel: &Path) -> usize {
772774
.take_while(|c| matches!(c, std::path::Component::ParentDir))
773775
.count()
774776
}
775-
776-
/// Resolve `..` and `.` components in a path without touching the filesystem.
777-
pub(super) fn normalize_path(path: &std::path::Path) -> PathBuf {
778-
let mut result = PathBuf::new();
779-
for component in path.components() {
780-
match component {
781-
std::path::Component::ParentDir => {
782-
result.pop();
783-
}
784-
std::path::Component::CurDir => {}
785-
c => result.push(c),
786-
}
787-
}
788-
result
789-
}

‎src/lsp/navigation.rs‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,10 @@ use std::path::{Path, PathBuf};
1515

1616
use tower_lsp::lsp_types::*;
1717

18-
use super::completion::normalize_path;
1918
use super::position::{byte_to_utf16_offset, utf16_to_byte_offset};
2019
use super::server::RumdlLanguageServer;
2120
use crate::utils::anchor_styles::AnchorStyle;
22-
use crate::workspace_index::{PROTOCOL_DOMAIN_REGEX, link_target_file};
21+
use crate::workspace_index::{PROTOCOL_DOMAIN_REGEX, link_target_file, normalize_relative_path};
2322

2423
/// Full link target extracted from a markdown link `[text](file_path#anchor)`.
2524
///
@@ -64,7 +63,7 @@ fn is_external_url(target: &str) -> bool {
6463
fn root_relative_link_resolves(content_roots: &[PathBuf], link_target: &str, target: &Path) -> bool {
6564
content_roots
6665
.iter()
67-
.any(|root| normalize_path(&root.join(link_target)) == *target)
66+
.any(|root| normalize_relative_path(&root.join(link_target)) == *target)
6867
}
6968

7069
/// Find the position of the closing `)` that balances with the opening `(`.

‎src/rules/md051_link_fragments.rs‎

Lines changed: 6 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use pulldown_cmark::LinkType;
88
use regex::Regex;
99
use serde::{Deserialize, Serialize};
1010
use std::collections::{HashMap, HashSet};
11-
use std::path::{Component, Path, PathBuf};
11+
use std::path::Path;
1212
use std::sync::LazyLock;
1313

1414
/// Configuration for MD051 (Link fragments)
@@ -96,21 +96,6 @@ static ATTR_ANCHOR_PATTERN: LazyLock<Regex> =
9696
static MD_SETTING_PATTERN: LazyLock<Regex> =
9797
LazyLock::new(|| Regex::new(r"<!--\s*md:setting\s+([^\s]+)\s*-->").unwrap());
9898

99-
/// Normalize a path by resolving . and .. components
100-
fn normalize_path(path: &Path) -> PathBuf {
101-
let mut result = PathBuf::new();
102-
for component in path.components() {
103-
match component {
104-
Component::CurDir => {} // Skip .
105-
Component::ParentDir => {
106-
result.pop(); // Go up one level for ..
107-
}
108-
c => result.push(c.as_os_str()),
109-
}
110-
}
111-
result
112-
}
113-
11499
/// Rule MD051: Link fragments
115100
///
116101
/// See [docs/md051.md](../../docs/md051.md) for full documentation, configuration, and examples.
@@ -504,32 +489,6 @@ impl MD051LinkFragments {
504489
|| url.starts_with("//")
505490
}
506491

507-
/// Resolve a path by trying markdown extensions if it has no extension
508-
///
509-
/// For extension-less paths (e.g., `page`), returns a list of paths to try:
510-
/// 1. The original path (in case it's already in the index)
511-
/// 2. The path with each markdown extension (e.g., `page.md`, `page.markdown`, etc.)
512-
///
513-
/// For paths with extensions, returns just the original path.
514-
#[inline]
515-
fn resolve_path_with_extensions(path: &Path, extensions: &[&str]) -> Vec<PathBuf> {
516-
if path.extension().is_none() {
517-
// Extension-less path - try with markdown extensions
518-
let mut paths = Vec::with_capacity(extensions.len() + 1);
519-
// First try the exact path (in case it's already in the index)
520-
paths.push(path.to_path_buf());
521-
// Then try with each markdown extension
522-
for ext in extensions {
523-
let path_with_ext = path.with_extension(&ext[1..]); // Remove leading dot
524-
paths.push(path_with_ext);
525-
}
526-
paths
527-
} else {
528-
// Path has extension - use as-is
529-
vec![path.to_path_buf()]
530-
}
531-
}
532-
533492
/// Check if a path part (without fragment or query) is an extension-less path
534493
///
535494
/// Extension-less paths are potential cross-file links that need resolution
@@ -1158,19 +1117,6 @@ impl Rule for MD051LinkFragments {
11581117
) -> LintResult {
11591118
let mut warnings = Vec::new();
11601119

1161-
// Supported markdown file extensions (with leading dot, matching MD057)
1162-
const MARKDOWN_EXTENSIONS: &[&str] = &[
1163-
".md",
1164-
".markdown",
1165-
".mdx",
1166-
".mkd",
1167-
".mkdn",
1168-
".mdown",
1169-
".mdwn",
1170-
".qmd",
1171-
".rmd",
1172-
];
1173-
11741120
let ignored_pattern = self.ignored_pattern_regex.as_ref();
11751121
let ignore_case = self.config.ignore_case;
11761122

@@ -1192,27 +1138,10 @@ impl Rule for MD051LinkFragments {
11921138
continue;
11931139
}
11941140

1195-
// A query string is not part of the file name: `other.md?raw=true`
1196-
// names `other.md`. The message keeps the destination as written.
1197-
let target_path = cross_link
1198-
.target_path
1199-
.split('?')
1200-
.next()
1201-
.unwrap_or(&cross_link.target_path);
1202-
1203-
// Resolve the target file path relative to the current file
1204-
let base_target_path = if let Some(parent) = file_path.parent() {
1205-
parent.join(target_path)
1206-
} else {
1207-
Path::new(target_path).to_path_buf()
1208-
};
1209-
1210-
// Normalize the path (remove . and ..)
1211-
let base_target_path = normalize_path(&base_target_path);
1212-
1213-
// For extension-less paths, try resolving with markdown extensions
1214-
// This handles GitHub-style links like [link](page#section) -> page.md#section
1215-
let target_paths_to_try = Self::resolve_path_with_extensions(&base_target_path, MARKDOWN_EXTENSIONS);
1141+
// The message keeps the destination as written; the lookup uses the
1142+
// file the link names.
1143+
let target_paths_to_try =
1144+
crate::workspace_index::link_target_candidates(file_path, &cross_link.target_path);
12161145

12171146
// Try to find the target file in the workspace index
12181147
let mut target_file_index = None;
@@ -1258,6 +1187,7 @@ impl Rule for MD051LinkFragments {
12581187
mod tests {
12591188
use super::*;
12601189
use crate::lint_context::LintContext;
1190+
use std::path::PathBuf;
12611191

12621192
/// An em dash collapses to one hyphen under Python-Markdown and to nothing
12631193
/// (leaving both surrounding spaces as hyphens) under GitHub, so exactly one

‎src/rules/md057_existing_relative_links.rs‎

Lines changed: 11 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use crate::rule::{
88
};
99
use crate::utils::frontmatter_values;
1010
use crate::utils::range_utils::byte_to_char_count;
11-
use crate::workspace_index::{FileIndex, extract_cross_file_links};
11+
use crate::workspace_index::{FileIndex, extract_cross_file_links, normalize_relative_path};
1212
use pulldown_cmark::LinkType;
1313
use regex::Regex;
1414
use std::collections::{HashMap, HashSet};
@@ -638,7 +638,7 @@ impl MD057ExistingRelativeLinks {
638638
}
639639
match (resolved.canonicalize(), source_file.canonicalize()) {
640640
(Ok(link), Ok(source)) => link == source,
641-
_ => normalize_path(resolved) == normalize_path(source_file),
641+
_ => normalize_relative_path(resolved) == normalize_relative_path(source_file),
642642
}
643643
}
644644

@@ -1454,10 +1454,10 @@ fn compute_compact_path(source_dir: &Path, raw_link_path: &str) -> Option<String
14541454

14551455
// Resolve: source_dir + raw_link_path, then normalize
14561456
let combined = source_dir.join(link_path);
1457-
let normalized_target = normalize_path(&combined);
1457+
let normalized_target = normalize_relative_path(&combined);
14581458

14591459
// Compute shortest path from source_dir back to the normalized target
1460-
let normalized_source = normalize_path(source_dir);
1460+
let normalized_source = normalize_relative_path(source_dir);
14611461
let shortest = shortest_relative_path(&normalized_source, &normalized_target);
14621462

14631463
// Compare against the raw link path — if it differs, the path can be compacted
@@ -1474,30 +1474,6 @@ fn compute_compact_path(source_dir: &Path, raw_link_path: &str) -> Option<String
14741474
}
14751475
}
14761476

1477-
/// Normalize a path by resolving . and .. components
1478-
fn normalize_path(path: &Path) -> PathBuf {
1479-
let mut components = Vec::new();
1480-
1481-
for component in path.components() {
1482-
match component {
1483-
std::path::Component::ParentDir => {
1484-
// Go up one level if possible
1485-
if !components.is_empty() {
1486-
components.pop();
1487-
}
1488-
}
1489-
std::path::Component::CurDir => {
1490-
// Skip current directory markers
1491-
}
1492-
_ => {
1493-
components.push(component);
1494-
}
1495-
}
1496-
}
1497-
1498-
components.iter().collect()
1499-
}
1500-
15011477
#[cfg(test)]
15021478
mod tests {
15031479
use super::*;
@@ -2367,24 +2343,27 @@ Some more text with `inline code [Link](yet-another-missing.md) embedded`.
23672343
fn test_normalize_path_function() {
23682344
// Test simple cases
23692345
assert_eq!(
2370-
normalize_path(Path::new("docs/guide.md")),
2346+
normalize_relative_path(Path::new("docs/guide.md")),
23712347
PathBuf::from("docs/guide.md")
23722348
);
23732349

23742350
// Test current directory removal
23752351
assert_eq!(
2376-
normalize_path(Path::new("./docs/guide.md")),
2352+
normalize_relative_path(Path::new("./docs/guide.md")),
23772353
PathBuf::from("docs/guide.md")
23782354
);
23792355

23802356
// Test parent directory resolution
23812357
assert_eq!(
2382-
normalize_path(Path::new("docs/sub/../guide.md")),
2358+
normalize_relative_path(Path::new("docs/sub/../guide.md")),
23832359
PathBuf::from("docs/guide.md")
23842360
);
23852361

23862362
// Test multiple parent directories
2387-
assert_eq!(normalize_path(Path::new("a/b/c/../../d.md")), PathBuf::from("a/d.md"));
2363+
assert_eq!(
2364+
normalize_relative_path(Path::new("a/b/c/../../d.md")),
2365+
PathBuf::from("a/d.md")
2366+
);
23882367
}
23892368

23902369
#[test]

0 commit comments

Comments
 (0)