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:
co-authored by
Cole Miller
Piotr Osiewicz
Peter Tripp
Smit Barmase
Lukas Wirth
parent
3c626f3758
commit
03f9cf4414
@@ -1298,7 +1298,8 @@ pub mod test {
|
||||
InteractiveElement, IntoElement, Render, SharedString, Task, WeakEntity, Window,
|
||||
};
|
||||
use project::{Project, ProjectEntryId, ProjectPath, WorktreeId};
|
||||
use std::{any::Any, cell::Cell, path::Path};
|
||||
use std::{any::Any, cell::Cell};
|
||||
use util::rel_path::rel_path;
|
||||
|
||||
pub struct TestProjectItem {
|
||||
pub entry_id: Option<ProjectEntryId>,
|
||||
@@ -1355,7 +1356,7 @@ pub mod test {
|
||||
let entry_id = Some(ProjectEntryId::from_proto(id));
|
||||
let project_path = Some(ProjectPath {
|
||||
worktree_id: WorktreeId::from_usize(0),
|
||||
path: Path::new(path).into(),
|
||||
path: rel_path(path).into(),
|
||||
});
|
||||
cx.new(|_| Self {
|
||||
entry_id,
|
||||
@@ -1376,7 +1377,7 @@ pub mod test {
|
||||
let entry_id = Some(ProjectEntryId::from_proto(id));
|
||||
let project_path = Some(ProjectPath {
|
||||
worktree_id: WorktreeId::from_usize(0),
|
||||
path: Path::new(path).into(),
|
||||
path: rel_path(path).into(),
|
||||
});
|
||||
cx.new(|_| Self {
|
||||
entry_id,
|
||||
|
||||
@@ -50,7 +50,7 @@ use ui::{
|
||||
PopoverMenu, PopoverMenuHandle, Tab, TabBar, TabPosition, Tooltip, prelude::*,
|
||||
right_click_menu,
|
||||
};
|
||||
use util::{ResultExt, debug_panic, maybe, truncate_and_remove_front};
|
||||
use util::{ResultExt, debug_panic, maybe, paths::PathStyle, truncate_and_remove_front};
|
||||
|
||||
/// A selected entry in e.g. project panel.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
@@ -1652,11 +1652,9 @@ impl Pane {
|
||||
if !project_item.is_dirty() {
|
||||
return;
|
||||
}
|
||||
let filename = project_item.project_path(cx).and_then(|path| {
|
||||
path.path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str().map(ToOwned::to_owned))
|
||||
});
|
||||
let filename = project_item
|
||||
.project_path(cx)
|
||||
.and_then(|path| path.path.file_name().map(ToOwned::to_owned));
|
||||
file_names.insert(filename.unwrap_or("untitled".to_string()));
|
||||
});
|
||||
}
|
||||
@@ -1965,9 +1963,10 @@ impl Pane {
|
||||
|
||||
const DELETED_MESSAGE: &str = "This file has been deleted on disk since you started editing it. Do you want to recreate it?";
|
||||
|
||||
let path_style = project.read_with(cx, |project, cx| project.path_style(cx))?;
|
||||
if save_intent == SaveIntent::Skip {
|
||||
return Ok(true);
|
||||
}
|
||||
};
|
||||
let Some(item_ix) = pane
|
||||
.read_with(cx, |pane, _| pane.index_for_item(item))
|
||||
.ok()
|
||||
@@ -2090,7 +2089,7 @@ impl Pane {
|
||||
let answer_task = pane.update_in(cx, |pane, window, cx| {
|
||||
if pane.save_modals_spawned.insert(item_id) {
|
||||
pane.activate_item(item_ix, true, true, window, cx);
|
||||
let prompt = dirty_message_for(item.project_path(cx));
|
||||
let prompt = dirty_message_for(item.project_path(cx), path_style);
|
||||
Some(window.prompt(
|
||||
PromptLevel::Warning,
|
||||
&prompt,
|
||||
@@ -2184,7 +2183,7 @@ impl Pane {
|
||||
let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id())?;
|
||||
let new_path = ProjectPath {
|
||||
worktree_id,
|
||||
path: path.into(),
|
||||
path: path,
|
||||
};
|
||||
|
||||
pane.update_in(cx, |pane, window, cx| {
|
||||
@@ -2321,10 +2320,10 @@ impl Pane {
|
||||
.worktree_for_entry(entry, cx)?
|
||||
.read(cx);
|
||||
let entry = worktree.entry_for_id(entry)?;
|
||||
match &entry.canonical_path {
|
||||
Some(canonical_path) => Some(canonical_path.to_path_buf()),
|
||||
None => worktree.absolutize(&entry.path).ok(),
|
||||
}
|
||||
Some(match &entry.canonical_path {
|
||||
Some(canonical_path) => canonical_path.to_path_buf(),
|
||||
None => worktree.absolutize(&entry.path),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn icon_color(selected: bool) -> Color {
|
||||
@@ -2875,9 +2874,14 @@ impl Pane {
|
||||
menu.entry(
|
||||
"Copy Relative Path",
|
||||
Some(Box::new(zed_actions::workspace::CopyRelativePath)),
|
||||
window.handler_for(&pane, move |_, _, cx| {
|
||||
window.handler_for(&pane, move |this, _, cx| {
|
||||
let Some(project) = this.project.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let path_style = project
|
||||
.update(cx, |project, cx| project.path_style(cx));
|
||||
cx.write_to_clipboard(ClipboardItem::new_string(
|
||||
relative_path.to_string_lossy().to_string(),
|
||||
relative_path.display(path_style).to_string(),
|
||||
));
|
||||
}),
|
||||
)
|
||||
@@ -4007,16 +4011,15 @@ impl NavHistoryState {
|
||||
}
|
||||
}
|
||||
|
||||
fn dirty_message_for(buffer_path: Option<ProjectPath>) -> String {
|
||||
fn dirty_message_for(buffer_path: Option<ProjectPath>, path_style: PathStyle) -> String {
|
||||
let path = buffer_path
|
||||
.as_ref()
|
||||
.and_then(|p| {
|
||||
p.path
|
||||
.to_str()
|
||||
.and_then(|s| if s.is_empty() { None } else { Some(s) })
|
||||
let path = p.path.display(path_style);
|
||||
if path.is_empty() { None } else { Some(path) }
|
||||
})
|
||||
.unwrap_or("This buffer");
|
||||
let path = truncate_and_remove_front(path, 80);
|
||||
.unwrap_or("This buffer".into());
|
||||
let path = truncate_and_remove_front(&path, 80);
|
||||
format!("{path} contains unsaved edits. Do you want to save it?")
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ use sqlez::{
|
||||
};
|
||||
|
||||
use ui::{App, SharedString, px};
|
||||
use util::{ResultExt, maybe};
|
||||
use util::{ResultExt, maybe, rel_path::RelPath};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
@@ -915,10 +915,13 @@ impl WorkspaceDb {
|
||||
relative_worktree_path == String::default()
|
||||
);
|
||||
|
||||
let Some(relative_path) = RelPath::new(&relative_worktree_path).log_err() else {
|
||||
continue;
|
||||
};
|
||||
if worktree_id != u64::MAX && relative_worktree_path != String::default() {
|
||||
ToolchainScope::Subproject(
|
||||
WorktreeId::from_usize(worktree_id as usize),
|
||||
Arc::from(relative_worktree_path.as_ref()),
|
||||
relative_path.into(),
|
||||
)
|
||||
} else {
|
||||
ToolchainScope::Project
|
||||
@@ -998,7 +1001,7 @@ impl WorkspaceDb {
|
||||
for toolchain in toolchains {
|
||||
let query = sql!(INSERT OR REPLACE INTO user_toolchains(remote_connection_id, workspace_id, worktree_id, relative_worktree_path, language_name, name, path, raw_json) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8));
|
||||
let (workspace_id, worktree_id, relative_worktree_path) = match scope {
|
||||
ToolchainScope::Subproject(worktree_id, ref path) => (Some(workspace.id), Some(worktree_id), Some(path.to_string_lossy().into_owned())),
|
||||
ToolchainScope::Subproject(worktree_id, ref path) => (Some(workspace.id), Some(worktree_id), Some(path.as_str().to_owned())),
|
||||
ToolchainScope::Project => (Some(workspace.id), None, None),
|
||||
ToolchainScope::Global => (None, None, None),
|
||||
};
|
||||
@@ -1637,25 +1640,41 @@ impl WorkspaceDb {
|
||||
&self,
|
||||
workspace_id: WorkspaceId,
|
||||
worktree_id: WorktreeId,
|
||||
relative_worktree_path: String,
|
||||
relative_worktree_path: Arc<RelPath>,
|
||||
language_name: LanguageName,
|
||||
) -> Result<Option<Toolchain>> {
|
||||
self.write(move |this| {
|
||||
let mut select = this
|
||||
.select_bound(sql!(
|
||||
SELECT name, path, raw_json FROM toolchains WHERE workspace_id = ? AND language_name = ? AND worktree_id = ? AND relative_worktree_path = ?
|
||||
SELECT
|
||||
name, path, raw_json
|
||||
FROM toolchains
|
||||
WHERE
|
||||
workspace_id = ? AND
|
||||
language_name = ? AND
|
||||
worktree_id = ? AND
|
||||
relative_worktree_path = ?
|
||||
))
|
||||
.context("select toolchain")?;
|
||||
|
||||
let toolchain: Vec<(String, String, String)> =
|
||||
select((workspace_id, language_name.as_ref().to_string(), worktree_id.to_usize(), relative_worktree_path))?;
|
||||
let toolchain: Vec<(String, String, String)> = select((
|
||||
workspace_id,
|
||||
language_name.as_ref().to_string(),
|
||||
worktree_id.to_usize(),
|
||||
relative_worktree_path.as_str().to_string(),
|
||||
))?;
|
||||
|
||||
Ok(toolchain.into_iter().next().and_then(|(name, path, raw_json)| Some(Toolchain {
|
||||
name: name.into(),
|
||||
path: path.into(),
|
||||
language_name,
|
||||
as_json: serde_json::Value::from_str(&raw_json).ok()?,
|
||||
})))
|
||||
Ok(toolchain
|
||||
.into_iter()
|
||||
.next()
|
||||
.and_then(|(name, path, raw_json)| {
|
||||
Some(Toolchain {
|
||||
name: name.into(),
|
||||
path: path.into(),
|
||||
language_name,
|
||||
as_json: serde_json::Value::from_str(&raw_json).ok()?,
|
||||
})
|
||||
}))
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -1663,31 +1682,46 @@ impl WorkspaceDb {
|
||||
pub(crate) async fn toolchains(
|
||||
&self,
|
||||
workspace_id: WorkspaceId,
|
||||
) -> Result<Vec<(Toolchain, WorktreeId, Arc<Path>)>> {
|
||||
) -> Result<Vec<(Toolchain, WorktreeId, Arc<RelPath>)>> {
|
||||
self.write(move |this| {
|
||||
let mut select = this
|
||||
.select_bound(sql!(
|
||||
SELECT name, path, worktree_id, relative_worktree_path, language_name, raw_json FROM toolchains WHERE workspace_id = ?
|
||||
SELECT
|
||||
name, path, worktree_id, relative_worktree_path, language_name, raw_json
|
||||
FROM toolchains
|
||||
WHERE workspace_id = ?
|
||||
))
|
||||
.context("select toolchains")?;
|
||||
|
||||
let toolchain: Vec<(String, String, u64, String, String, String)> =
|
||||
select(workspace_id)?;
|
||||
|
||||
Ok(toolchain.into_iter().filter_map(|(name, path, worktree_id, relative_worktree_path, language_name, raw_json)| Some((Toolchain {
|
||||
name: name.into(),
|
||||
path: path.into(),
|
||||
language_name: LanguageName::new(&language_name),
|
||||
as_json: serde_json::Value::from_str(&raw_json).ok()?,
|
||||
}, WorktreeId::from_proto(worktree_id), Arc::from(relative_worktree_path.as_ref())))).collect())
|
||||
Ok(toolchain
|
||||
.into_iter()
|
||||
.filter_map(
|
||||
|(name, path, worktree_id, relative_worktree_path, language, json)| {
|
||||
Some((
|
||||
Toolchain {
|
||||
name: name.into(),
|
||||
path: path.into(),
|
||||
language_name: LanguageName::new(&language),
|
||||
as_json: serde_json::Value::from_str(&json).ok()?,
|
||||
},
|
||||
WorktreeId::from_proto(worktree_id),
|
||||
RelPath::from_proto(&relative_worktree_path).log_err()?,
|
||||
))
|
||||
},
|
||||
)
|
||||
.collect())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn set_toolchain(
|
||||
&self,
|
||||
workspace_id: WorkspaceId,
|
||||
worktree_id: WorktreeId,
|
||||
relative_worktree_path: String,
|
||||
relative_worktree_path: Arc<RelPath>,
|
||||
toolchain: Toolchain,
|
||||
) -> Result<()> {
|
||||
log::debug!(
|
||||
@@ -1709,7 +1743,7 @@ impl WorkspaceDb {
|
||||
insert((
|
||||
workspace_id,
|
||||
worktree_id.to_usize(),
|
||||
relative_worktree_path,
|
||||
relative_worktree_path.as_str(),
|
||||
toolchain.language_name.as_ref(),
|
||||
toolchain.name.as_ref(),
|
||||
toolchain.path.as_ref(),
|
||||
|
||||
@@ -104,7 +104,12 @@ use theme::{ActiveTheme, SystemAppearance, ThemeSettings};
|
||||
pub use toolbar::{Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView};
|
||||
pub use ui;
|
||||
use ui::{Window, prelude::*};
|
||||
use util::{ResultExt, TryFutureExt, paths::SanitizedPath, serde::default_true};
|
||||
use util::{
|
||||
ResultExt, TryFutureExt,
|
||||
paths::{PathStyle, SanitizedPath},
|
||||
rel_path::RelPath,
|
||||
serde::default_true,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
pub use workspace_settings::{
|
||||
AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, TabBarSettings, WorkspaceSettings,
|
||||
@@ -625,7 +630,7 @@ impl ProjectItemRegistry {
|
||||
match project_item.await.with_context(|| {
|
||||
format!(
|
||||
"opening project path {:?}",
|
||||
entry_abs_path.as_deref().unwrap_or(&project_path.path)
|
||||
entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
|
||||
)
|
||||
}) {
|
||||
Ok(project_item) => {
|
||||
@@ -1754,6 +1759,10 @@ impl Workspace {
|
||||
&self.project
|
||||
}
|
||||
|
||||
pub fn path_style(&self, cx: &App) -> PathStyle {
|
||||
self.project.read(cx).path_style(cx)
|
||||
}
|
||||
|
||||
pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
|
||||
let mut history: HashMap<EntityId, usize> = HashMap::default();
|
||||
|
||||
@@ -2622,7 +2631,12 @@ impl Workspace {
|
||||
.strip_prefix(worktree_abs_path.as_ref())
|
||||
.ok()
|
||||
.and_then(|relative_path| {
|
||||
worktree.entry_for_path(relative_path)
|
||||
let relative_path = RelPath::from_std_path(
|
||||
relative_path,
|
||||
PathStyle::local(),
|
||||
)
|
||||
.log_err()?;
|
||||
worktree.entry_for_path(&relative_path)
|
||||
})
|
||||
}
|
||||
.map(|entry| entry.id);
|
||||
@@ -2668,7 +2682,7 @@ impl Workspace {
|
||||
self.open_path(project_path, None, true, window, cx)
|
||||
}
|
||||
ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
|
||||
path,
|
||||
PathBuf::from(path),
|
||||
OpenOptions {
|
||||
visible: Some(OpenVisible::None),
|
||||
..Default::default()
|
||||
@@ -2757,7 +2771,7 @@ impl Workspace {
|
||||
worktree,
|
||||
ProjectPath {
|
||||
worktree_id,
|
||||
path: path.into(),
|
||||
path: path,
|
||||
},
|
||||
))
|
||||
})
|
||||
@@ -4399,17 +4413,17 @@ impl Workspace {
|
||||
let project = self.project().read(cx);
|
||||
let mut title = String::new();
|
||||
|
||||
for (i, worktree) in project.worktrees(cx).enumerate() {
|
||||
for (i, worktree) in project.visible_worktrees(cx).enumerate() {
|
||||
let name = {
|
||||
let settings_location = SettingsLocation {
|
||||
worktree_id: worktree.read(cx).id(),
|
||||
path: Path::new(""),
|
||||
path: RelPath::empty(),
|
||||
};
|
||||
|
||||
let settings = WorktreeSettings::get(Some(settings_location), cx);
|
||||
match &settings.project_name {
|
||||
Some(name) => name.as_str(),
|
||||
None => worktree.read(cx).root_name(),
|
||||
None => worktree.read(cx).root_name_str(),
|
||||
}
|
||||
};
|
||||
if i > 0 {
|
||||
@@ -4423,18 +4437,14 @@ impl Workspace {
|
||||
}
|
||||
|
||||
if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
|
||||
let filename = path
|
||||
.path
|
||||
.file_name()
|
||||
.map(|s| s.to_string_lossy())
|
||||
.or_else(|| {
|
||||
Some(Cow::Borrowed(
|
||||
project
|
||||
.worktree_for_id(path.worktree_id, cx)?
|
||||
.read(cx)
|
||||
.root_name(),
|
||||
))
|
||||
});
|
||||
let filename = path.path.file_name().or_else(|| {
|
||||
Some(
|
||||
project
|
||||
.worktree_for_id(path.worktree_id, cx)?
|
||||
.read(cx)
|
||||
.root_name_str(),
|
||||
)
|
||||
});
|
||||
|
||||
if let Some(filename) = filename {
|
||||
title.push_str(" — ");
|
||||
@@ -8174,6 +8184,7 @@ mod tests {
|
||||
use project::{Project, ProjectEntryId};
|
||||
use serde_json::json;
|
||||
use settings::SettingsStore;
|
||||
use util::rel_path::rel_path;
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_tab_disambiguation(cx: &mut TestAppContext) {
|
||||
@@ -8268,7 +8279,7 @@ mod tests {
|
||||
assert_eq!(
|
||||
project.active_entry(),
|
||||
project
|
||||
.entry_for_path(&(worktree_id, "one.txt").into(), cx)
|
||||
.entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
|
||||
.map(|e| e.id)
|
||||
);
|
||||
});
|
||||
@@ -8283,7 +8294,7 @@ mod tests {
|
||||
assert_eq!(
|
||||
project.active_entry(),
|
||||
project
|
||||
.entry_for_path(&(worktree_id, "two.txt").into(), cx)
|
||||
.entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
|
||||
.map(|e| e.id)
|
||||
);
|
||||
});
|
||||
@@ -8299,7 +8310,7 @@ mod tests {
|
||||
assert_eq!(
|
||||
project.active_entry(),
|
||||
project
|
||||
.entry_for_path(&(worktree_id, "one.txt").into(), cx)
|
||||
.entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
|
||||
.map(|e| e.id)
|
||||
);
|
||||
});
|
||||
@@ -10665,7 +10676,7 @@ mod tests {
|
||||
|
||||
let handle = workspace
|
||||
.update_in(cx, |workspace, window, cx| {
|
||||
let project_path = (worktree_id, "one.png");
|
||||
let project_path = (worktree_id, rel_path("one.png"));
|
||||
workspace.open_path(project_path, None, true, window, cx)
|
||||
})
|
||||
.await
|
||||
@@ -10679,7 +10690,7 @@ mod tests {
|
||||
|
||||
let handle = workspace
|
||||
.update_in(cx, |workspace, window, cx| {
|
||||
let project_path = (worktree_id, "two.ipynb");
|
||||
let project_path = (worktree_id, rel_path("two.ipynb"));
|
||||
workspace.open_path(project_path, None, true, window, cx)
|
||||
})
|
||||
.await
|
||||
@@ -10692,7 +10703,7 @@ mod tests {
|
||||
|
||||
let handle = workspace
|
||||
.update_in(cx, |workspace, window, cx| {
|
||||
let project_path = (worktree_id, "three.txt");
|
||||
let project_path = (worktree_id, rel_path("three.txt"));
|
||||
workspace.open_path(project_path, None, true, window, cx)
|
||||
})
|
||||
.await;
|
||||
@@ -10727,7 +10738,7 @@ mod tests {
|
||||
|
||||
let handle = workspace
|
||||
.update_in(cx, |workspace, window, cx| {
|
||||
let project_path = (worktree_id, "one.png");
|
||||
let project_path = (worktree_id, rel_path("one.png"));
|
||||
workspace.open_path(project_path, None, true, window, cx)
|
||||
})
|
||||
.await
|
||||
@@ -10741,7 +10752,7 @@ mod tests {
|
||||
|
||||
let handle = workspace
|
||||
.update_in(cx, |workspace, window, cx| {
|
||||
let project_path = (worktree_id, "three.txt");
|
||||
let project_path = (worktree_id, rel_path("three.txt"));
|
||||
workspace.open_path(project_path, None, true, window, cx)
|
||||
})
|
||||
.await;
|
||||
@@ -10755,7 +10766,7 @@ mod tests {
|
||||
.flat_map(|item| {
|
||||
item.project_paths(cx)
|
||||
.into_iter()
|
||||
.map(|path| path.path.to_string_lossy().to_string())
|
||||
.map(|path| path.path.as_str().to_string())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user