Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

project: Remove the `PathStyle` guard for repository identity paths (#66209)

Xin Zhao2e5765372493
diff --git a/crates/git/src/repository.rs b/crates/git/src/repository.rs
index 1b9df6cedd8..507e282a29d 100644
--- a/crates/git/src/repository.rs
+++ b/crates/git/src/repository.rs
@@ -351,24 +351,24 @@ impl Worktree {
.unwrap_or(&self.sha[..self.sha.len().min(SHORT_SHA_LENGTH)])
}
- pub fn directory_name(&self, name_anchor_path: Option<&Path>) -> String {
+ pub fn directory_name(&self, name_anchor_path: Option<&Path>, path_style: PathStyle) -> String {
if self.is_main {
return "main worktree".to_string();
}
- let dir_name = self
- .path
- .file_name()
+ let dir_name = path_style
+ .file_name(&self.path)
.and_then(|name| name.to_str())
.unwrap_or(self.display_name());
if let Some(name_anchor_path) = name_anchor_path {
- let name_anchor_dir = name_anchor_path.file_name().and_then(|name| name.to_str());
+ let name_anchor_dir = path_style
+ .file_name(name_anchor_path)
+ .and_then(|name| name.to_str());
if name_anchor_dir == Some(dir_name) {
- if let Some(parent_name) = self
- .path
- .parent()
- .and_then(|parent| parent.file_name())
+ if let Some(parent_name) = path_style
+ .parent(&self.path)
+ .and_then(|parent| path_style.file_name(parent))
.and_then(|name| name.to_str())
{
return parent_name.to_string();
@@ -5976,6 +5976,65 @@ mod tests {
assert_eq!(upstream.branch_name(), Some("feature/git-pull-request"));
}
+ #[test]
+ fn test_directory_name_uses_path_style() {
+ let cases = [
+ (
+ "/worktrees/zed/plum-warbler/zed",
+ Some("/repos/zed"),
+ PathStyle::Unix,
+ "plum-warbler",
+ ),
+ (
+ "/worktrees/feature-1",
+ Some("/repos/zed"),
+ PathStyle::Unix,
+ "feature-1",
+ ),
+ ("/worktrees/feature-1", None, PathStyle::Unix, "feature-1"),
+ (
+ r"C:\worktrees\zed\plum-warbler\zed",
+ Some(r"C:\repos\zed"),
+ PathStyle::Windows,
+ "plum-warbler",
+ ),
+ (
+ r"C:\worktrees\feature-1",
+ Some(r"C:\repos\zed"),
+ PathStyle::Windows,
+ "feature-1",
+ ),
+ (
+ r"C:\worktrees\feature-1",
+ None,
+ PathStyle::Windows,
+ "feature-1",
+ ),
+ (
+ "C:/worktrees/zed/plum-warbler/zed",
+ Some("C:/repos/zed"),
+ PathStyle::Windows,
+ "plum-warbler",
+ ),
+ ];
+
+ for (worktree_path, name_anchor, path_style, expected) in cases {
+ let worktree = Worktree {
+ path: PathBuf::from(worktree_path),
+ ref_name: None,
+ sha: "8166e3d".into(),
+ is_main: false,
+ is_bare: false,
+ };
+
+ assert_eq!(
+ worktree.directory_name(name_anchor.map(Path::new), path_style),
+ expected,
+ "directory name for {worktree_path:?} anchored at {name_anchor:?} with {path_style:?}",
+ );
+ }
+ }
+
#[test]
fn test_parse_worktrees_from_str() {
// Empty input
diff --git a/crates/git_ui_core/src/worktree_picker.rs b/crates/git_ui_core/src/worktree_picker.rs
index 53980722846..d172eaf4a41 100644
--- a/crates/git_ui_core/src/worktree_picker.rs
+++ b/crates/git_ui_core/src/worktree_picker.rs
@@ -11,12 +11,15 @@ use gpui::{
Render, SharedString, Styled, Subscription, Task, TaskExt, WeakEntity, Window, actions,
};
use picker::{Picker, PickerDelegate, PickerEditorPosition};
-use project::{Project, git_store::RepositoryEvent, repo_identity_path_if_local};
+use project::{Project, git_store::RepositoryEvent, repo_identity_path};
use ui::{
Button, CommonAnimationExt as _, Divider, HighlightedLabel, IconButton, KeyBinding, ListItem,
ListItemSpacing, ListSubHeader, Tooltip, prelude::*,
};
-use util::{ResultExt as _, paths::PathExt};
+use util::{
+ ResultExt as _,
+ paths::{PathExt, PathStyle},
+};
use workspace::{
ModalView, MultiWorkspace, RemovalIntent, Workspace, dock::DockPosition,
notifications::DetachAndPromptErr,
@@ -86,11 +89,11 @@ impl WorktreePicker {
let project_worktree_paths = active_worktree_paths.clone();
let has_multiple_repositories = project_ref.repositories(cx).len() > 1;
+ let path_style = project_ref.path_style(cx);
let repository = project_ref.active_repository(cx);
- let repository_identity_path = repository.as_ref().and_then(|repository| {
+ let repository_identity_path = repository.as_ref().map(|repository| {
let repository = repository.read(cx);
- repo_identity_path_if_local(&repository.common_dir_abs_path, repository.path_style)
- .map(Path::to_path_buf)
+ repo_identity_path(&repository.common_dir_abs_path, path_style).to_path_buf()
});
let current_branch_name = repository.as_ref().and_then(|repo| {
@@ -128,6 +131,7 @@ impl WorktreePicker {
active_worktree_paths,
hovered_delete_index: None,
deleting_worktree_paths: HashSet::default(),
+ path_style,
};
let picker = cx.new(|cx| {
@@ -308,6 +312,7 @@ struct WorktreePickerDelegate {
modifiers: Modifiers,
hovered_delete_index: Option<usize>,
deleting_worktree_paths: HashSet<PathBuf>,
+ path_style: PathStyle,
}
fn worktree_name_anchor<'a>(
@@ -518,7 +523,7 @@ impl WorktreePickerDelegate {
return;
};
let path = worktree.path.clone();
- let display_name = worktree.directory_name(self.worktree_name_anchor());
+ let display_name = worktree.directory_name(self.worktree_name_anchor(), self.path_style);
let workspace = self.workspace.clone();
self.deleting_worktree_paths.insert(path.clone());
@@ -804,7 +809,8 @@ impl PickerDelegate for WorktreePickerDelegate {
let normalized_query = query.replace(' ', "-");
let worktree_name_anchor = self.worktree_name_anchor().map(Path::to_path_buf);
let has_named_worktree = self.all_worktrees.iter().any(|worktree| {
- worktree.directory_name(worktree_name_anchor.as_deref()) == normalized_query
+ worktree.directory_name(worktree_name_anchor.as_deref(), self.path_style)
+ == normalized_query
});
let create_named_disabled_reason: Option<String> = if self.has_multiple_repositories {
Some("Cannot create a named worktree in a project with multiple repositories".into())
@@ -825,8 +831,8 @@ impl PickerDelegate for WorktreePickerDelegate {
let project_paths = &self.project_worktree_paths;
let sort_by_name = |a: &GitWorktree, b: &GitWorktree| {
- a.directory_name(worktree_name_anchor.as_deref())
- .cmp(&b.directory_name(worktree_name_anchor.as_deref()))
+ a.directory_name(worktree_name_anchor.as_deref(), self.path_style)
+ .cmp(&b.directory_name(worktree_name_anchor.as_deref(), self.path_style))
};
let (mut open_here, mut others): (Vec<_>, Vec<_>) = repo_worktrees
@@ -877,7 +883,7 @@ impl PickerDelegate for WorktreePickerDelegate {
.map(|(ix, worktree)| {
StringMatchCandidate::new(
ix,
- &worktree.directory_name(worktree_name_anchor.as_deref()),
+ &worktree.directory_name(worktree_name_anchor.as_deref(), self.path_style),
)
})
.collect();
@@ -1010,8 +1016,10 @@ impl PickerDelegate for WorktreePickerDelegate {
workspace,
&SwitchWorktree {
path: worktree.path.clone(),
- display_name: worktree
- .directory_name(self.worktree_name_anchor()),
+ display_name: worktree.directory_name(
+ self.worktree_name_anchor(),
+ self.path_style,
+ ),
},
window,
self.focused_dock,
@@ -1121,7 +1129,8 @@ impl PickerDelegate for WorktreePickerDelegate {
worktree,
positions,
} => {
- let display_name = worktree.directory_name(self.worktree_name_anchor());
+ let display_name =
+ worktree.directory_name(self.worktree_name_anchor(), self.path_style);
let first_line = display_name.lines().next().unwrap_or(&display_name);
let positions: Vec<_> = positions
.iter()
@@ -1692,7 +1701,10 @@ mod tests {
let worktrees = [worktree.clone()];
let name_anchor = worktree_name_anchor(&worktrees, Some(Path::new("/repos/zed")));
- assert_eq!(worktree.directory_name(name_anchor), "plum-warbler");
+ assert_eq!(
+ worktree.directory_name(name_anchor, PathStyle::local()),
+ "plum-warbler"
+ );
}
async fn init_worktree_picker_test(
diff --git a/crates/project/src/git_store.rs b/crates/project/src/git_store.rs
index cffd24674d4..66b50de981d 100644
--- a/crates/project/src/git_store.rs
+++ b/crates/project/src/git_store.rs
@@ -6139,11 +6139,10 @@ impl RepositorySnapshot {
/// The path that anchors a linked worktree's location: the main worktree
/// when one exists, otherwise the repository's identity path (relevant for
- /// bare repositories), falling back to the common Git directory.
- fn linked_worktree_anchor_path(&self) -> &Path {
+ /// bare repositories).
+ pub fn linked_worktree_anchor_path(&self) -> &Path {
self.main_worktree_abs_path()
- .or_else(|| repo_identity_path_if_local(&self.common_dir_abs_path, self.path_style))
- .unwrap_or(self.common_dir_abs_path.as_ref())
+ .unwrap_or_else(|| repo_identity_path(&self.common_dir_abs_path, self.path_style))
}
/// Computes the path where a new linked worktree for this repository
@@ -10691,14 +10690,6 @@ pub fn repo_identity_path(common_dir: &Path, path_style: PathStyle) -> &Path {
}
}
-/// Returns the repository identity only when `std::path` can interpret the path correctly.
-///
-/// Callers whose downstream path operations are not yet `PathStyle`-aware use this to preserve
-/// their existing behavior for foreign path styles.
-pub fn repo_identity_path_if_local(common_dir: &Path, path_style: PathStyle) -> Option<&Path> {
- (path_style == PathStyle::local()).then(|| repo_identity_path(common_dir, path_style))
-}
-
/// Returns true if `git_dir` is a Git submodule's git directory.
///
/// Submodules store their git directory inside the superproject at
@@ -12174,6 +12165,102 @@ mod tests {
);
}
+ #[test]
+ fn test_linked_worktree_anchor_path() {
+ let cases = [
+ // Normal clone (`.git`): the main worktree's checkout is the anchor.
+ (
+ "/worktrees/zed/feature/zed",
+ "/repos/zed/.git/worktrees/feature",
+ "/worktrees/zed/feature/zed/.git",
+ "/repos/zed/.git",
+ PathStyle::Unix,
+ Some("/repos/zed"),
+ "/repos/zed",
+ ),
+ (
+ r"C:\worktrees\zed\feature\zed",
+ r"C:\repos\zed\.git\worktrees\feature",
+ r"C:\worktrees\zed\feature\zed\.git",
+ r"C:\repos\zed\.git",
+ PathStyle::Windows,
+ Some(r"C:\repos\zed"),
+ r"C:\repos\zed",
+ ),
+ // Bare clone stored in `.bare`: there is no main worktree, so the parent
+ // of `.bare` is the anchor.
+ (
+ "/worktrees/zed/plum-warbler/zed",
+ "/repos/zed/.bare/worktrees/plum-warbler",
+ "/worktrees/zed/plum-warbler/zed/.git",
+ "/repos/zed/.bare",
+ PathStyle::Unix,
+ None,
+ "/repos/zed",
+ ),
+ (
+ r"C:\worktrees\zed\plum-warbler\zed",
+ r"C:\repos\zed\.bare\worktrees\plum-warbler",
+ r"C:\worktrees\zed\plum-warbler\zed\.git",
+ r"C:\repos\zed\.bare",
+ PathStyle::Windows,
+ None,
+ r"C:\repos\zed",
+ ),
+ // Bare clone named `repo.git`: there is no main worktree and no parent to
+ // strip, so the common directory itself is the anchor.
+ (
+ "/worktrees/zed.git/plum-warbler/zed.git",
+ "/repos/zed.git/worktrees/plum-warbler",
+ "/worktrees/zed.git/plum-warbler/zed.git/.git",
+ "/repos/zed.git",
+ PathStyle::Unix,
+ None,
+ "/repos/zed.git",
+ ),
+ (
+ r"C:\worktrees\zed.git\plum-warbler\zed.git",
+ r"C:\repos\zed.git\worktrees\plum-warbler",
+ r"C:\worktrees\zed.git\plum-warbler\zed.git\.git",
+ r"C:\repos\zed.git",
+ PathStyle::Windows,
+ None,
+ r"C:\repos\zed.git",
+ ),
+ ];
+
+ for (
+ work_directory,
+ repository_dir,
+ dot_git,
+ common_dir,
+ path_style,
+ expected_main_worktree,
+ expected_anchor,
+ ) in cases
+ {
+ let snapshot = RepositorySnapshot::empty(
+ RepositoryId(0),
+ Path::new(work_directory).into(),
+ Some(Path::new(repository_dir).into()),
+ Some(Path::new(dot_git).into()),
+ Some(Path::new(common_dir).into()),
+ path_style,
+ );
+
+ assert_eq!(
+ snapshot.main_worktree_abs_path(),
+ expected_main_worktree.map(Path::new),
+ "main worktree for {work_directory:?} with {path_style:?}",
+ );
+ assert_eq!(
+ snapshot.linked_worktree_anchor_path(),
+ Path::new(expected_anchor),
+ "anchor for {work_directory:?} with {path_style:?}",
+ );
+ }
+ }
+
fn verify_invariants(repository: &Repository) -> anyhow::Result<()> {
match &repository.commit_data_handler {
CommitDataHandlerState::Open(handler) => {
diff --git a/crates/project/src/project.rs b/crates/project/src/project.rs
index d57040ce5f9..83c391b31fb 100644
--- a/crates/project/src/project.rs
+++ b/crates/project/src/project.rs
@@ -50,7 +50,7 @@ pub use git_store::{
ConflictRegion, ConflictSet, ConflictSetSnapshot, ConflictSetUpdate,
git_traversal::{ChildEntriesGitIter, GitEntry, GitEntryRef, GitTraversal},
is_submodule_git_dir, linked_worktree_short_name, repo_identity_path,
- repo_identity_path_if_local, worktrees_directory_for_repo,
+ worktrees_directory_for_repo,
};
pub use manifest_tree::ManifestTree;
pub use project_search::{Search, SearchResults};
diff --git a/crates/sidebar/src/sidebar.rs b/crates/sidebar/src/sidebar.rs
index 6f01115fe1d..e135bdd0bac 100644
--- a/crates/sidebar/src/sidebar.rs
+++ b/crates/sidebar/src/sidebar.rs
@@ -40,9 +40,7 @@ use menu::{
};
use notifications::status_toast::StatusToast;
use platform_title_bar::apply_title_bar_insets;
-use project::{
- AgentId, AgentRegistryStore, Event as ProjectEvent, WorktreeId, repo_identity_path_if_local,
-};
+use project::{AgentId, AgentRegistryStore, Event as ProjectEvent, WorktreeId};
use recent_projects::sidebar_recent_projects::SidebarRecentProjects;
use remote::RemoteConnectionOptions;
use ui::utils::platform_title_bar_height;
@@ -683,21 +681,12 @@ fn workspace_menu_worktree_labels(
if let Some(snapshot) = repository_snapshot {
let worktree_name = if snapshot.is_linked_worktree() {
- let identity_fallback = repo_identity_path_if_local(
- &snapshot.common_dir_abs_path,
+ project::linked_worktree_short_name(
+ snapshot.linked_worktree_anchor_path(),
+ root_path,
snapshot.path_style,
- );
- snapshot
- .main_worktree_abs_path()
- .or(identity_fallback)
- .and_then(|name_anchor_path| {
- project::linked_worktree_short_name(
- name_anchor_path,
- root_path,
- snapshot.path_style,
- )
- })
- .unwrap_or_else(|| folder_name.clone())
+ )
+ .unwrap_or_else(|| folder_name.clone())
} else {
"main".into()
};
diff --git a/crates/title_bar/src/title_bar.rs b/crates/title_bar/src/title_bar.rs
index d1e12738ee7..4f1b09ca13b 100644
--- a/crates/title_bar/src/title_bar.rs
+++ b/crates/title_bar/src/title_bar.rs
@@ -15,7 +15,7 @@ pub use platform_title_bar::{
self, DraggedWindowTab, MergeAllWindows, MoveTabToNewWindow, PlatformTitleBar,
ShowNextWindowTab, ShowPreviousWindowTab,
};
-use project::{linked_worktree_short_name, repo_identity_path, repo_identity_path_if_local};
+use project::{linked_worktree_short_name, repo_identity_path};
#[cfg(not(target_os = "macos"))]
use crate::application_menu::{
@@ -42,7 +42,6 @@ use remote::RemoteConnectionOptions;
use settings::{Settings as _, SettingsStore};
use std::any::TypeId;
-use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use theme::ActiveTheme;
@@ -66,18 +65,6 @@ const MAX_PROJECT_NAME_LENGTH: usize = 40;
const MAX_BRANCH_NAME_LENGTH: usize = 40;
const MAX_SHORT_SHA_LENGTH: usize = 8;
-fn linked_worktree_name_anchor<'a>(
- main_worktree_path: Option<&'a Path>,
- repository_identity_path: Option<&'a Path>,
- is_linked_worktree: bool,
-) -> Option<&'a Path> {
- main_worktree_path.or_else(|| {
- is_linked_worktree
- .then_some(repository_identity_path)
- .flatten()
- })
-}
-
actions!(
collab,
[
@@ -261,20 +248,11 @@ impl Render for TitleBar {
if let Some(repo) = &repository {
let repo = repo.read(cx);
let identity = repo_identity_path(&repo.common_dir_abs_path, path_style);
- let identity_fallback =
- repo_identity_path_if_local(&repo.common_dir_abs_path, path_style);
- linked_worktree_name = linked_worktree_name_anchor(
- repo.main_worktree_abs_path(),
- identity_fallback,
- repo.is_linked_worktree(),
+ linked_worktree_name = linked_worktree_short_name(
+ repo.linked_worktree_anchor_path(),
+ repo.work_directory_abs_path.as_ref(),
+ path_style,
)
- .and_then(|name_anchor_path| {
- linked_worktree_short_name(
- name_anchor_path,
- repo.work_directory_abs_path.as_ref(),
- path_style,
- )
- })
.or_else(|| {
repo.is_linked_worktree()
.then_some(project_name.clone())
@@ -1447,52 +1425,3 @@ impl TitleBar {
.anchor(Anchor::TopRight)
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use util::paths::PathStyle;
-
- #[test]
- fn test_foreign_path_style_does_not_use_repository_identity_as_name_anchor() {
- let (common_dir, foreign_path_style) = match PathStyle::local() {
- PathStyle::Unix => (Path::new(r"C:\repos\zed"), PathStyle::Windows),
- PathStyle::Windows => (Path::new("/repos/zed"), PathStyle::Unix),
- };
- let repository_identity_path = repo_identity_path_if_local(common_dir, foreign_path_style);
-
- assert_eq!(
- linked_worktree_name_anchor(None, repository_identity_path, true),
- None
- );
- }
-
- #[test]
- fn test_local_path_style_uses_bare_repository_worktree_name() {
- let (repository_identity_path, work_directory_path) = match PathStyle::local() {
- PathStyle::Unix => (
- Path::new("/repos/zed"),
- Path::new("/worktrees/zed/plum-warbler/zed"),
- ),
- PathStyle::Windows => (
- Path::new(r"C:\repos\zed"),
- Path::new(r"C:\worktrees\zed\plum-warbler\zed"),
- ),
- };
-
- let repository_identity_path =
- repo_identity_path_if_local(repository_identity_path, PathStyle::local());
- let name_anchor_path = linked_worktree_name_anchor(None, repository_identity_path, true);
-
- assert_eq!(
- name_anchor_path.and_then(|name_anchor_path| {
- linked_worktree_short_name(
- name_anchor_path,
- work_directory_path,
- PathStyle::local(),
- )
- }),
- Some("plum-warbler".into())
- );
- }
-}