fix: strip windows verbatim prefix and build valid file base url

This commit is contained in:
2026-10-21 16:13:28 +08:00
parent f63aff47a8
commit 0ca339dcf7
2 changed files with 62 additions and 33 deletions

View File

@@ -153,13 +153,30 @@ fn normalize_path(path: PathBuf) -> PathBuf {
} else {
std::env::current_dir().unwrap_or_default().join(path)
};
fs::canonicalize(&absolute).unwrap_or_else(|_| {
let resolved = fs::canonicalize(&absolute).unwrap_or_else(|_| {
absolute
.parent()
.and_then(|parent| fs::canonicalize(parent).ok())
.and_then(|parent| absolute.file_name().map(|name| parent.join(name)))
.unwrap_or(absolute)
})
});
strip_verbatim(resolved)
}
/// Windows canonicalize returns verbatim paths. Strip that prefix so session
/// and recent-file entries stay readable and usable by other tools.
pub(crate) fn strip_verbatim(path: PathBuf) -> PathBuf {
#[cfg(target_os = "windows")]
{
let text = path.to_string_lossy().into_owned();
if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
return PathBuf::from(format!(r"\\{rest}"));
}
if let Some(rest) = text.strip_prefix(r"\\?\") {
return PathBuf::from(rest.to_string());
}
}
path
}
#[cfg(test)]
@@ -217,6 +234,22 @@ mod tests {
let _ = fs::remove_dir_all(dir);
}
#[cfg(target_os = "windows")]
#[test]
fn opened_paths_drop_windows_verbatim_prefix() {
let dir = temp_dir("verbatim");
let file = dir.join("note.md");
fs::write(&file, "# Note").unwrap();
let mut session = DocumentSession::default();
session.open(file.clone(), false);
let stored = session.tabs[0].path.to_string_lossy().to_string();
assert!(!stored.starts_with(r"\\?\"), "verbatim prefix leaked: {stored}");
assert!(session.tabs[0].path.ends_with("note.md"));
let _ = fs::remove_dir_all(dir);
}
#[test]
fn persisted_session_keeps_missing_tabs_and_active_order() {
let dir = temp_dir("roundtrip");
@@ -232,12 +265,13 @@ mod tests {
let restored = DocumentSession::load(&state_path);
assert_eq!(restored.tabs.len(), 2);
assert_eq!(restored.tabs[0].path, fs::canonicalize(existing).unwrap());
assert_eq!(
restored.tabs[0].path,
strip_verbatim(fs::canonicalize(existing).unwrap())
);
assert_eq!(
restored.tabs[1].path,
fs::canonicalize(&dir)
.unwrap()
.join(missing.file_name().unwrap())
strip_verbatim(fs::canonicalize(&dir).unwrap()).join(missing.file_name().unwrap())
);
assert!(!restored.tabs[0].missing);
assert!(restored.tabs[1].missing);