Represent relative paths using a dedicated, separator-agnostic type (#38744)

Closes https://github.com/zed-industries/zed/issues/38690
Closes #37353

### Background

On Windows, paths are normally separated by `\`, unlike mac and linux
where they are separated by `/`. When editing code in a project that
uses a different path style than your local system (e.g. remoting from
Windows to Linux, using WSL, and collaboration between windows and unix
users), the correct separator for a path may differ from the "native"
separator.

Previously, to work around this, Zed converted paths' separators in
numerous places. This was applied to both absolute and relative paths,
leading to incorrect conversions in some cases.

### Solution

Many code paths in Zed use paths that are *relative* to either a
worktree root or a git repository. This PR introduces a dedicated type
for these paths called `RelPath`, which stores the path in the same way
regardless of host platform, and offers `Path`-like manipulation APIs.
RelPath supports *displaying* the path using either separator, so that
we can display paths in a style that is determined at runtime based on
the current project.

The representation of absolute paths is left untouched, for now.
Absolute paths are different from relative paths because (except in
contexts where we know that the path refers to the local filesystem)
they should generally be treated as opaque strings. Currently we use a
mix of types for these paths (std::path::Path, String, SanitizedPath).

Release Notes:

- N/A

---------

Co-authored-by: Cole Miller <cole@zed.dev>
Co-authored-by: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com>
Co-authored-by: Peter Tripp <petertripp@gmail.com>
Co-authored-by: Smit Barmase <heysmitbarmase@gmail.com>
Co-authored-by: Lukas Wirth <me@lukaswirth.dev>
This commit is contained in:
Max Brunsfeld
2025-09-24 18:57:33 -04:00
committed by GitHub
co-authored by Cole Miller Piotr Osiewicz Peter Tripp Smit Barmase Lukas Wirth
parent 3c626f3758
commit 03f9cf4414
216 changed files with 5873 additions and 5257 deletions
+17 -12
View File
@@ -41,13 +41,12 @@ use std::{
cell::Cell,
cmp::{self, Ordering, Reverse},
collections::{BTreeMap, BTreeSet},
ffi::OsStr,
future::Future,
iter::{self, Iterator, Peekable},
mem,
num::NonZeroU32,
ops::{Deref, Range},
path::{Path, PathBuf},
path::PathBuf,
rc,
sync::{Arc, LazyLock},
time::{Duration, Instant},
@@ -65,7 +64,7 @@ pub use text::{
use theme::{ActiveTheme as _, SyntaxTheme};
#[cfg(any(test, feature = "test-support"))]
use util::RandomCharIter;
use util::{RangeExt, debug_panic, maybe};
use util::{RangeExt, debug_panic, maybe, paths::PathStyle, rel_path::RelPath};
#[cfg(any(test, feature = "test-support"))]
pub use {tree_sitter_python, tree_sitter_rust, tree_sitter_typescript};
@@ -349,15 +348,18 @@ pub trait File: Send + Sync + Any {
fn disk_state(&self) -> DiskState;
/// Returns the path of this file relative to the worktree's root directory.
fn path(&self) -> &Arc<Path>;
fn path(&self) -> &Arc<RelPath>;
/// Returns the path of this file relative to the worktree's parent directory (this means it
/// includes the name of the worktree's root folder).
fn full_path(&self, cx: &App) -> PathBuf;
/// Returns the path style of this file.
fn path_style(&self, cx: &App) -> PathStyle;
/// Returns the last component of this handle's absolute path. If this handle refers to the root
/// of its worktree, then this method will return the name of the worktree itself.
fn file_name<'a>(&'a self, cx: &'a App) -> &'a OsStr;
fn file_name<'a>(&'a self, cx: &'a App) -> &'a str;
/// Returns the id of the worktree to which this file belongs.
///
@@ -4626,13 +4628,12 @@ impl BufferSnapshot {
self.file.as_ref()
}
/// Resolves the file path (relative to the worktree root) associated with the underlying file.
pub fn resolve_file_path(&self, cx: &App, include_root: bool) -> Option<PathBuf> {
if let Some(file) = self.file() {
if file.path().file_name().is_none() || include_root {
Some(file.full_path(cx))
} else {
Some(file.path().to_path_buf())
Some(file.path().as_std_path().to_owned())
}
} else {
None
@@ -5117,19 +5118,19 @@ impl IndentSize {
#[cfg(any(test, feature = "test-support"))]
pub struct TestFile {
pub path: Arc<Path>,
pub path: Arc<RelPath>,
pub root_name: String,
pub local_root: Option<PathBuf>,
}
#[cfg(any(test, feature = "test-support"))]
impl File for TestFile {
fn path(&self) -> &Arc<Path> {
fn path(&self) -> &Arc<RelPath> {
&self.path
}
fn full_path(&self, _: &gpui::App) -> PathBuf {
PathBuf::from(&self.root_name).join(self.path.as_ref())
PathBuf::from(self.root_name.clone()).join(self.path.as_std_path())
}
fn as_local(&self) -> Option<&dyn LocalFile> {
@@ -5144,7 +5145,7 @@ impl File for TestFile {
unimplemented!()
}
fn file_name<'a>(&'a self, _: &'a gpui::App) -> &'a std::ffi::OsStr {
fn file_name<'a>(&'a self, _: &'a gpui::App) -> &'a str {
self.path().file_name().unwrap_or(self.root_name.as_ref())
}
@@ -5159,6 +5160,10 @@ impl File for TestFile {
fn is_private(&self) -> bool {
false
}
fn path_style(&self, _cx: &App) -> PathStyle {
PathStyle::local()
}
}
#[cfg(any(test, feature = "test-support"))]
@@ -5166,7 +5171,7 @@ impl LocalFile for TestFile {
fn abs_path(&self, _cx: &App) -> PathBuf {
PathBuf::from(self.local_root.as_ref().unwrap())
.join(&self.root_name)
.join(self.path.as_ref())
.join(self.path.as_std_path())
}
fn load(&self, _cx: &App) -> Task<Result<String>> {
+2 -1
View File
@@ -24,6 +24,7 @@ use text::{BufferId, LineEnding};
use text::{Point, ToPoint};
use theme::ActiveTheme;
use unindent::Unindent as _;
use util::rel_path::rel_path;
use util::test::marked_text_offsets;
use util::{RandomCharIter, assert_set_eq, post_inc, test::marked_text_ranges};
@@ -380,7 +381,7 @@ async fn test_language_for_file_with_custom_file_types(cx: &mut TestAppContext)
fn file(path: &str) -> Arc<dyn File> {
Arc::new(TestFile {
path: Path::new(path).into(),
path: Arc::from(rel_path(path)),
root_name: "zed".into(),
local_root: None,
})
+2 -1
View File
@@ -70,6 +70,7 @@ pub use toolchain::{
ToolchainMetadata, ToolchainScope,
};
use tree_sitter::{self, Query, QueryCursor, WasmStore, wasmtime};
use util::rel_path::RelPath;
use util::serde::default_true;
pub use buffer::Operation;
@@ -307,7 +308,7 @@ pub trait LspAdapterDelegate: Send + Sync {
) -> Result<Option<(PathBuf, String)>>;
async fn which(&self, command: &OsStr) -> Option<PathBuf>;
async fn shell_env(&self) -> HashMap<String, String>;
async fn read_text_file(&self, path: PathBuf) -> Result<String>;
async fn read_text_file(&self, path: &RelPath) -> Result<String>;
async fn try_exec(&self, binary: LanguageServerBinary) -> Result<()>;
}
+1 -1
View File
@@ -753,7 +753,7 @@ impl LanguageRegistry {
content: Option<&Rope>,
user_file_types: Option<&FxHashMap<Arc<str>, GlobSet>>,
) -> Option<AvailableLanguage> {
let filename = path.file_name().and_then(|name| name.to_str());
let filename = path.file_name().and_then(|filename| filename.to_str());
// `Path.extension()` returns None for files with a leading '.'
// and no other extension which is not the desired behavior here,
// as we want `.zshrc` to result in extension being `Some("zshrc")`
+12 -7
View File
@@ -390,7 +390,7 @@ impl EditPredictionSettings {
file.as_local()
.is_some_and(|local| glob.matcher.is_match(local.abs_path(cx)))
} else {
glob.matcher.is_match(file.path())
glob.matcher.is_match(file.path().as_std_path())
}
})
}
@@ -798,6 +798,7 @@ pub struct JsxTagAutoCloseSettings {
mod tests {
use super::*;
use gpui::TestAppContext;
use util::rel_path::rel_path;
#[gpui::test]
fn test_edit_predictions_enabled_for_file(cx: &mut TestAppContext) {
@@ -839,11 +840,11 @@ mod tests {
const WORKTREE_NAME: &str = "project";
let make_test_file = |segments: &[&str]| -> Arc<dyn File> {
let mut path_buf = PathBuf::new();
path_buf.extend(segments);
let path = segments.join("/");
let path = rel_path(&path);
Arc::new(TestFile {
path: path_buf.as_path().into(),
path: path.into(),
root_name: WORKTREE_NAME.to_string(),
local_root: Some(PathBuf::from(if cfg!(windows) {
"C:\\absolute\\"
@@ -896,7 +897,7 @@ mod tests {
assert!(!settings.enabled_for_file(&test_file, &cx));
let test_file_root: Arc<dyn File> = Arc::new(TestFile {
path: PathBuf::from("file.rs").as_path().into(),
path: rel_path("file.rs").into(),
root_name: WORKTREE_NAME.to_string(),
local_root: Some(PathBuf::from("/absolute/")),
});
@@ -928,8 +929,12 @@ mod tests {
// Test tilde expansion
let home = shellexpand::tilde("~").into_owned();
let home_file = make_test_file(&[&home, "test.rs"]);
let settings = build_settings(&["~/test.rs"]);
let home_file = Arc::new(TestFile {
path: rel_path("test.rs").into(),
root_name: "the-dir".to_string(),
local_root: Some(PathBuf::from(home)),
}) as Arc<dyn File>;
let settings = build_settings(&["~/the-dir/test.rs"]);
assert!(!settings.enabled_for_file(&home_file, &cx));
}
+5 -4
View File
@@ -1,7 +1,8 @@
use std::{borrow::Borrow, path::Path, sync::Arc};
use std::{borrow::Borrow, sync::Arc};
use gpui::SharedString;
use settings::WorktreeId;
use util::rel_path::RelPath;
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ManifestName(SharedString);
@@ -42,17 +43,17 @@ impl AsRef<SharedString> for ManifestName {
/// For example, given a path like `foo/bar/baz`, a depth of 2 would explore `foo/bar/baz` and `foo/bar`, but not `foo`.
pub struct ManifestQuery {
/// Path to the file, relative to worktree root.
pub path: Arc<Path>,
pub path: Arc<RelPath>,
pub depth: usize,
pub delegate: Arc<dyn ManifestDelegate>,
}
pub trait ManifestProvider {
fn name(&self) -> ManifestName;
fn search(&self, query: ManifestQuery) -> Option<Arc<Path>>;
fn search(&self, query: ManifestQuery) -> Option<Arc<RelPath>>;
}
pub trait ManifestDelegate: Send + Sync {
fn worktree_id(&self) -> WorktreeId;
fn exists(&self, path: &Path, is_dir: Option<bool>) -> bool;
fn exists(&self, path: &RelPath, is_dir: Option<bool>) -> bool;
}
+8 -9
View File
@@ -4,10 +4,7 @@
//! which is a set of tools used to interact with the projects written in said language.
//! For example, a Python project can have an associated virtual environment; a Rust project can have a toolchain override.
use std::{
path::{Path, PathBuf},
sync::Arc,
};
use std::{path::PathBuf, sync::Arc};
use async_trait::async_trait;
use collections::HashMap;
@@ -15,6 +12,7 @@ use fs::Fs;
use gpui::{AsyncApp, SharedString};
use settings::WorktreeId;
use task::ShellKind;
use util::rel_path::RelPath;
use crate::{LanguageName, ManifestName};
@@ -23,6 +21,7 @@ use crate::{LanguageName, ManifestName};
pub struct Toolchain {
/// User-facing label
pub name: SharedString,
/// Absolute path
pub path: SharedString,
pub language_name: LanguageName,
/// Full toolchain data (including language-specific details)
@@ -37,7 +36,7 @@ pub struct Toolchain {
/// - Only in the subproject they're currently in.
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum ToolchainScope {
Subproject(WorktreeId, Arc<Path>),
Subproject(WorktreeId, Arc<RelPath>),
Project,
/// Available in all projects on this box. It wouldn't make sense to show suggestions across machines.
Global,
@@ -97,7 +96,7 @@ pub trait ToolchainLister: Send + Sync + 'static {
async fn list(
&self,
worktree_root: PathBuf,
subroot_relative_path: Arc<Path>,
subroot_relative_path: Arc<RelPath>,
project_env: Option<HashMap<String, String>>,
) -> ToolchainList;
@@ -134,7 +133,7 @@ pub trait LanguageToolchainStore: Send + Sync + 'static {
async fn active_toolchain(
self: Arc<Self>,
worktree_id: WorktreeId,
relative_path: Arc<Path>,
relative_path: Arc<RelPath>,
language_name: LanguageName,
cx: &mut AsyncApp,
) -> Option<Toolchain>;
@@ -144,7 +143,7 @@ pub trait LocalLanguageToolchainStore: Send + Sync + 'static {
fn active_toolchain(
self: Arc<Self>,
worktree_id: WorktreeId,
relative_path: &Arc<Path>,
relative_path: &Arc<RelPath>,
language_name: LanguageName,
cx: &mut AsyncApp,
) -> Option<Toolchain>;
@@ -155,7 +154,7 @@ impl<T: LocalLanguageToolchainStore> LanguageToolchainStore for T {
async fn active_toolchain(
self: Arc<Self>,
worktree_id: WorktreeId,
relative_path: Arc<Path>,
relative_path: Arc<RelPath>,
language_name: LanguageName,
cx: &mut AsyncApp,
) -> Option<Toolchain> {