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
+46 -35
View File
@@ -17,13 +17,14 @@ use std::{
any::{Any, TypeId, type_name},
fmt::Debug,
ops::Range,
path::{Path, PathBuf},
path::PathBuf,
rc::Rc,
str::{self, FromStr},
sync::Arc,
};
use util::{
ResultExt as _,
rel_path::RelPath,
schemars::{DefaultDenyUnknownFields, replace_subschema},
};
@@ -134,7 +135,7 @@ pub trait Settings: 'static + Send + Sync + Sized {
#[derive(Clone, Copy, Debug)]
pub struct SettingsLocation<'a> {
pub worktree_id: WorktreeId,
pub path: &'a Path,
pub path: &'a RelPath,
}
pub struct SettingsStore {
@@ -148,8 +149,8 @@ pub struct SettingsStore {
merged_settings: Rc<SettingsContent>,
local_settings: BTreeMap<(WorktreeId, Arc<Path>), SettingsContent>,
raw_editorconfig_settings: BTreeMap<(WorktreeId, Arc<Path>), (String, Option<Editorconfig>)>,
local_settings: BTreeMap<(WorktreeId, Arc<RelPath>), SettingsContent>,
raw_editorconfig_settings: BTreeMap<(WorktreeId, Arc<RelPath>), (String, Option<Editorconfig>)>,
_setting_file_updates: Task<()>,
setting_file_updates_tx:
@@ -199,7 +200,7 @@ impl Global for SettingsStore {}
#[derive(Debug)]
struct SettingValue<T> {
global_value: Option<T>,
local_values: Vec<(WorktreeId, Arc<Path>, T)>,
local_values: Vec<(WorktreeId, Arc<RelPath>, T)>,
}
trait AnySettingValue: 'static + Send + Sync {
@@ -208,9 +209,9 @@ trait AnySettingValue: 'static + Send + Sync {
fn from_settings(&self, s: &SettingsContent, cx: &mut App) -> Box<dyn Any>;
fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any;
fn all_local_values(&self) -> Vec<(WorktreeId, Arc<Path>, &dyn Any)>;
fn all_local_values(&self) -> Vec<(WorktreeId, Arc<RelPath>, &dyn Any)>;
fn set_global_value(&mut self, value: Box<dyn Any>);
fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<Path>, value: Box<dyn Any>);
fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<RelPath>, value: Box<dyn Any>);
fn import_from_vscode(
&self,
vscode_settings: &VsCodeSettings,
@@ -299,7 +300,7 @@ impl SettingsStore {
}
/// Get all values from project specific settings
pub fn get_all_locals<T: Settings>(&self) -> Vec<(WorktreeId, Arc<Path>, &T)> {
pub fn get_all_locals<T: Settings>(&self) -> Vec<(WorktreeId, Arc<RelPath>, &T)> {
self.setting_values
.get(&TypeId::of::<T>())
.unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
@@ -644,7 +645,7 @@ impl SettingsStore {
pub fn set_local_settings(
&mut self,
root_id: WorktreeId,
directory_path: Arc<Path>,
directory_path: Arc<RelPath>,
kind: LocalSettingsKind,
settings_content: Option<&str>,
cx: &mut App,
@@ -659,14 +660,20 @@ impl SettingsStore {
(LocalSettingsKind::Tasks, _) => {
return Err(InvalidSettingsError::Tasks {
message: "Attempted to submit tasks into the settings store".to_string(),
path: directory_path.join(task_file_name()),
path: directory_path
.join(RelPath::new(task_file_name()).unwrap())
.as_std_path()
.to_path_buf(),
});
}
(LocalSettingsKind::Debug, _) => {
return Err(InvalidSettingsError::Debug {
message: "Attempted to submit debugger config into the settings store"
.to_string(),
path: directory_path.join(task_file_name()),
path: directory_path
.join(RelPath::new(task_file_name()).unwrap())
.as_std_path()
.to_path_buf(),
});
}
(LocalSettingsKind::Settings, None) => {
@@ -719,7 +726,7 @@ impl SettingsStore {
v.insert((editorconfig_contents.to_owned(), None));
return Err(InvalidSettingsError::Editorconfig {
message: e.to_string(),
path: directory_path.join(EDITORCONFIG_NAME),
path: directory_path.join(RelPath::new(EDITORCONFIG_NAME).unwrap()),
});
}
},
@@ -736,7 +743,8 @@ impl SettingsStore {
o.insert((editorconfig_contents.to_owned(), None));
return Err(InvalidSettingsError::Editorconfig {
message: e.to_string(),
path: directory_path.join(EDITORCONFIG_NAME),
path: directory_path
.join(RelPath::new(EDITORCONFIG_NAME).unwrap()),
});
}
}
@@ -772,20 +780,20 @@ impl SettingsStore {
pub fn clear_local_settings(&mut self, root_id: WorktreeId, cx: &mut App) -> Result<()> {
self.local_settings
.retain(|(worktree_id, _), _| worktree_id != &root_id);
self.recompute_values(Some((root_id, "".as_ref())), cx)?;
self.recompute_values(Some((root_id, RelPath::empty())), cx)?;
Ok(())
}
pub fn local_settings(
&self,
root_id: WorktreeId,
) -> impl '_ + Iterator<Item = (Arc<Path>, &ProjectSettingsContent)> {
) -> impl '_ + Iterator<Item = (Arc<RelPath>, &ProjectSettingsContent)> {
self.local_settings
.range(
(root_id, Path::new("").into())
(root_id, RelPath::empty().into())
..(
WorktreeId::from_usize(root_id.to_usize() + 1),
Path::new("").into(),
RelPath::empty().into(),
),
)
.map(|((_, path), content)| (path.clone(), &content.project))
@@ -794,13 +802,13 @@ impl SettingsStore {
pub fn local_editorconfig_settings(
&self,
root_id: WorktreeId,
) -> impl '_ + Iterator<Item = (Arc<Path>, String, Option<Editorconfig>)> {
) -> impl '_ + Iterator<Item = (Arc<RelPath>, String, Option<Editorconfig>)> {
self.raw_editorconfig_settings
.range(
(root_id, Path::new("").into())
(root_id, RelPath::empty().into())
..(
WorktreeId::from_usize(root_id.to_usize() + 1),
Path::new("").into(),
RelPath::empty().into(),
),
)
.map(|((_, path), (content, parsed_content))| {
@@ -862,12 +870,12 @@ impl SettingsStore {
fn recompute_values(
&mut self,
changed_local_path: Option<(WorktreeId, &Path)>,
changed_local_path: Option<(WorktreeId, &RelPath)>,
cx: &mut App,
) -> std::result::Result<(), InvalidSettingsError> {
// Reload the global and local values for every setting.
let mut project_settings_stack = Vec::<SettingsContent>::new();
let mut paths_stack = Vec::<Option<(WorktreeId, &Path)>>::new();
let mut paths_stack = Vec::<Option<(WorktreeId, &RelPath)>>::new();
if changed_local_path.is_none() {
let mut merged = self.default_settings.as_ref().clone();
@@ -931,7 +939,7 @@ impl SettingsStore {
pub fn editorconfig_properties(
&self,
for_worktree: WorktreeId,
for_path: &Path,
for_path: &RelPath,
) -> Option<EditorconfigProperties> {
let mut properties = EditorconfigProperties::new();
@@ -947,7 +955,9 @@ impl SettingsStore {
properties = EditorconfigProperties::new();
}
for section in parsed_editorconfig.sections {
section.apply_to(&mut properties, for_path).log_err()?;
section
.apply_to(&mut properties, for_path.as_std_path())
.log_err()?;
}
}
@@ -958,11 +968,11 @@ impl SettingsStore {
#[derive(Debug, Clone, PartialEq)]
pub enum InvalidSettingsError {
LocalSettings { path: PathBuf, message: String },
LocalSettings { path: Arc<RelPath>, message: String },
UserSettings { message: String },
ServerSettings { message: String },
DefaultSettings { message: String },
Editorconfig { path: PathBuf, message: String },
Editorconfig { path: Arc<RelPath>, message: String },
Tasks { path: PathBuf, message: String },
Debug { path: PathBuf, message: String },
}
@@ -1011,7 +1021,7 @@ impl<T: Settings> AnySettingValue for SettingValue<T> {
type_name::<T>()
}
fn all_local_values(&self) -> Vec<(WorktreeId, Arc<Path>, &dyn Any)> {
fn all_local_values(&self) -> Vec<(WorktreeId, Arc<RelPath>, &dyn Any)> {
self.local_values
.iter()
.map(|(id, path, value)| (*id, path.clone(), value as _))
@@ -1036,7 +1046,7 @@ impl<T: Settings> AnySettingValue for SettingValue<T> {
self.global_value = Some(*value.downcast().unwrap());
}
fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<Path>, value: Box<dyn Any>) {
fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<RelPath>, value: Box<dyn Any>) {
let value = *value.downcast().unwrap();
match self
.local_values
@@ -1067,6 +1077,7 @@ mod tests {
use super::*;
use unindent::Unindent;
use util::rel_path::rel_path;
#[derive(Debug, PartialEq)]
struct AutoUpdateSetting {
@@ -1178,7 +1189,7 @@ mod tests {
store
.set_local_settings(
WorktreeId::from_usize(1),
Path::new("/root1").into(),
rel_path("root1").into(),
LocalSettingsKind::Settings,
Some(r#"{ "tab_size": 5 }"#),
cx,
@@ -1187,7 +1198,7 @@ mod tests {
store
.set_local_settings(
WorktreeId::from_usize(1),
Path::new("/root1/subdir").into(),
rel_path("root1/subdir").into(),
LocalSettingsKind::Settings,
Some(r#"{ "preferred_line_length": 50 }"#),
cx,
@@ -1197,7 +1208,7 @@ mod tests {
store
.set_local_settings(
WorktreeId::from_usize(1),
Path::new("/root2").into(),
rel_path("root2").into(),
LocalSettingsKind::Settings,
Some(r#"{ "tab_size": 9, "auto_update": true}"#),
cx,
@@ -1207,7 +1218,7 @@ mod tests {
assert_eq!(
store.get::<DefaultLanguageSettings>(Some(SettingsLocation {
worktree_id: WorktreeId::from_usize(1),
path: Path::new("/root1/something"),
path: rel_path("root1/something"),
})),
&DefaultLanguageSettings {
preferred_line_length: 80,
@@ -1217,7 +1228,7 @@ mod tests {
assert_eq!(
store.get::<DefaultLanguageSettings>(Some(SettingsLocation {
worktree_id: WorktreeId::from_usize(1),
path: Path::new("/root1/subdir/something")
path: rel_path("root1/subdir/something"),
})),
&DefaultLanguageSettings {
preferred_line_length: 50,
@@ -1227,7 +1238,7 @@ mod tests {
assert_eq!(
store.get::<DefaultLanguageSettings>(Some(SettingsLocation {
worktree_id: WorktreeId::from_usize(1),
path: Path::new("/root2/something")
path: rel_path("root2/something"),
})),
&DefaultLanguageSettings {
preferred_line_length: 80,
@@ -1237,7 +1248,7 @@ mod tests {
assert_eq!(
store.get::<AutoUpdateSetting>(Some(SettingsLocation {
worktree_id: WorktreeId::from_usize(1),
path: Path::new("/root2/something")
path: rel_path("root2/something")
})),
&AutoUpdateSetting { auto_update: false }
);