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.

sidebar: Add submenu to create a worktree (#59341)

Danilo Leal3e8aae49b56c
diff --git a/Cargo.lock b/Cargo.lock
index 6098df115fc..7e281c25640 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -16787,6 +16787,7 @@ dependencies = [
"feature_flags",
"fs",
"git",
+ "git_ui",
"gpui",
"http_client",
"itertools 0.14.0",
diff --git a/crates/git_ui/src/worktree_picker.rs b/crates/git_ui/src/worktree_picker.rs
index 28b5ccd68f5..4cefbde5080 100644
--- a/crates/git_ui/src/worktree_picker.rs
+++ b/crates/git_ui/src/worktree_picker.rs
@@ -24,6 +24,7 @@ use workspace::{
};
use crate::git_panel::show_error_toast;
+use crate::worktree_service::{RemoteBranchName, WorktreeCreateTarget, worktree_create_targets};
use zed_actions::{
CreateWorktree, NewWorktreeBranchTarget, OpenWorktreeInNewWindow, SwitchWorktree,
};
@@ -281,30 +282,6 @@ enum WorktreeEntry {
},
}
-#[derive(Clone)]
-struct RemoteBranchName {
- remote_name: String,
- branch_name: String,
-}
-
-impl RemoteBranchName {
- fn parse(name: &str) -> Option<Self> {
- let name = name.strip_prefix("refs/remotes/").unwrap_or(name);
- let (remote_name, branch_name) = name.split_once('/')?;
- if remote_name.is_empty() || branch_name.is_empty() {
- return None;
- }
- Some(Self {
- remote_name: remote_name.to_string(),
- branch_name: branch_name.to_string(),
- })
- }
-
- fn display_name(&self) -> String {
- format!("{}/{}", self.remote_name, self.branch_name)
- }
-}
-
struct WorktreePickerDelegate {
matches: Vec<WorktreeEntry>,
all_worktrees: Vec<GitWorktree>,
@@ -427,26 +404,19 @@ impl Render for DeleteWorktreeTooltip {
impl WorktreePickerDelegate {
fn build_fixed_entries(&self) -> Vec<WorktreeEntry> {
- let mut entries = Vec::new();
-
- if self.has_multiple_repositories {
- entries.push(WorktreeEntry::CreateFromCurrentBranch);
- } else if let Some(ref default_branch) = self.default_branch {
- let is_different = self
- .current_branch_name
- .as_ref()
- .is_none_or(|current| current != &default_branch.branch_name);
- entries.push(WorktreeEntry::CreateFromDefaultBranch {
- default_branch: default_branch.clone(),
- });
- if is_different {
- entries.push(WorktreeEntry::CreateFromCurrentBranch);
+ worktree_create_targets(
+ self.has_multiple_repositories,
+ self.default_branch.clone(),
+ self.current_branch_name.as_deref(),
+ )
+ .into_iter()
+ .map(|target| match target {
+ WorktreeCreateTarget::CurrentBranch => WorktreeEntry::CreateFromCurrentBranch,
+ WorktreeCreateTarget::DefaultBranch(default_branch) => {
+ WorktreeEntry::CreateFromDefaultBranch { default_branch }
}
- } else {
- entries.push(WorktreeEntry::CreateFromCurrentBranch);
- }
-
- entries
+ })
+ .collect()
}
fn all_repo_worktrees(&self) -> &[GitWorktree] {
@@ -1102,13 +1072,10 @@ impl PickerDelegate for WorktreePickerDelegate {
.into_any_element(),
),
WorktreeEntry::CreateFromCurrentBranch => {
- let branch_label = if self.has_multiple_repositories {
- "current branches".to_string()
- } else {
- self.current_branch_name
- .clone()
- .unwrap_or_else(|| "HEAD".to_string())
- };
+ let branch_label = WorktreeCreateTarget::CurrentBranch.branch_label(
+ self.has_multiple_repositories,
+ self.current_branch_name.as_deref(),
+ );
let label = format!("Create new worktree based on {branch_label}");
@@ -1122,8 +1089,12 @@ impl PickerDelegate for WorktreePickerDelegate {
Some(item.into_any_element())
}
WorktreeEntry::CreateFromDefaultBranch { default_branch } => {
- let default_branch_name = default_branch.display_name();
- let label = format!("Create new worktree based on {default_branch_name}");
+ let branch_label = WorktreeCreateTarget::DefaultBranch(default_branch.clone())
+ .branch_label(
+ self.has_multiple_repositories,
+ self.current_branch_name.as_deref(),
+ );
+ let label = format!("Create new worktree based on {branch_label}");
let item = create_new_list_item(
"create-from-main".to_string().into(),
diff --git a/crates/git_ui/src/worktree_service.rs b/crates/git_ui/src/worktree_service.rs
index a9dcdb8406a..4c840c466c2 100644
--- a/crates/git_ui/src/worktree_service.rs
+++ b/crates/git_ui/src/worktree_service.rs
@@ -31,6 +31,95 @@ use crate::askpass_modal::AskPassModal;
use crate::git_panel::{open_output, show_error_toast};
use crate::worktree_names;
+/// A remote-tracking branch reference parsed into its remote and branch parts,
+/// e.g. `origin/main` -> remote `origin`, branch `main`.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct RemoteBranchName {
+ pub remote_name: String,
+ pub branch_name: String,
+}
+
+impl RemoteBranchName {
+ pub fn parse(name: &str) -> Option<Self> {
+ let name = name.strip_prefix("refs/remotes/").unwrap_or(name);
+ let (remote_name, branch_name) = name.split_once('/')?;
+ if remote_name.is_empty() || branch_name.is_empty() {
+ return None;
+ }
+ Some(Self {
+ remote_name: remote_name.to_string(),
+ branch_name: branch_name.to_string(),
+ })
+ }
+
+ pub fn display_name(&self) -> String {
+ format!("{}/{}", self.remote_name, self.branch_name)
+ }
+}
+
+/// A "create new worktree" option offered to the user. The set of targets is
+/// derived from repository state by [`worktree_create_targets`] so that the
+/// worktree picker and the sidebar's new-thread menu stay in sync.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum WorktreeCreateTarget {
+ CurrentBranch,
+ DefaultBranch(RemoteBranchName),
+}
+
+impl WorktreeCreateTarget {
+ pub fn branch_target(&self) -> NewWorktreeBranchTarget {
+ match self {
+ WorktreeCreateTarget::CurrentBranch => NewWorktreeBranchTarget::CurrentBranch,
+ WorktreeCreateTarget::DefaultBranch(default_branch) => {
+ NewWorktreeBranchTarget::RemoteBranch {
+ remote_name: default_branch.remote_name.clone(),
+ branch_name: default_branch.branch_name.clone(),
+ }
+ }
+ }
+ }
+
+ pub fn branch_label(
+ &self,
+ has_multiple_repositories: bool,
+ current_branch_name: Option<&str>,
+ ) -> String {
+ match self {
+ WorktreeCreateTarget::DefaultBranch(default_branch) => default_branch.display_name(),
+ WorktreeCreateTarget::CurrentBranch => {
+ if has_multiple_repositories {
+ "current branches".to_string()
+ } else {
+ current_branch_name.unwrap_or("HEAD").to_string()
+ }
+ }
+ }
+ }
+}
+
+/// Determines which "create new worktree" options to surface for the given
+/// repository state: prefer the remote default branch when it differs from the
+/// current branch, and otherwise offer the current branch.
+pub fn worktree_create_targets(
+ has_multiple_repositories: bool,
+ default_branch: Option<RemoteBranchName>,
+ current_branch_name: Option<&str>,
+) -> Vec<WorktreeCreateTarget> {
+ if has_multiple_repositories {
+ return vec![WorktreeCreateTarget::CurrentBranch];
+ }
+ let Some(default_branch) = default_branch else {
+ return vec![WorktreeCreateTarget::CurrentBranch];
+ };
+ let is_different =
+ current_branch_name.is_none_or(|current| current != default_branch.branch_name);
+ let mut targets = vec![WorktreeCreateTarget::DefaultBranch(default_branch)];
+ if is_different {
+ targets.push(WorktreeCreateTarget::CurrentBranch);
+ }
+ targets
+}
+
/// Whether a worktree operation is creating a new one or switching to an
/// existing one. Controls whether the source workspace's state (dock layout,
/// open files, agent panel draft) is inherited by the destination.
@@ -1610,4 +1699,85 @@ mod tests {
"security modal should not show for a linked worktree created from a trusted main worktree"
);
}
+
+ #[test]
+ fn test_remote_branch_name_parse() {
+ assert_eq!(
+ RemoteBranchName::parse("refs/remotes/origin/main"),
+ Some(RemoteBranchName {
+ remote_name: "origin".to_string(),
+ branch_name: "main".to_string(),
+ })
+ );
+ assert_eq!(
+ RemoteBranchName::parse("upstream/feature/foo"),
+ Some(RemoteBranchName {
+ remote_name: "upstream".to_string(),
+ branch_name: "feature/foo".to_string(),
+ })
+ );
+ assert_eq!(RemoteBranchName::parse("main"), None);
+ assert_eq!(RemoteBranchName::parse("origin/"), None);
+ }
+
+ #[test]
+ fn test_worktree_create_targets() {
+ let origin_main = RemoteBranchName {
+ remote_name: "origin".to_string(),
+ branch_name: "main".to_string(),
+ };
+
+ // Multiple repositories: only the current branch, regardless of default.
+ assert_eq!(
+ worktree_create_targets(true, Some(origin_main.clone()), Some("feature")),
+ vec![WorktreeCreateTarget::CurrentBranch]
+ );
+
+ // Default branch differs from current: offer both, default first.
+ assert_eq!(
+ worktree_create_targets(false, Some(origin_main.clone()), Some("feature")),
+ vec![
+ WorktreeCreateTarget::DefaultBranch(origin_main.clone()),
+ WorktreeCreateTarget::CurrentBranch,
+ ]
+ );
+
+ // Current branch matches the default: only the default branch entry.
+ assert_eq!(
+ worktree_create_targets(false, Some(origin_main.clone()), Some("main")),
+ vec![WorktreeCreateTarget::DefaultBranch(origin_main)]
+ );
+
+ // No default branch resolved: fall back to the current branch.
+ assert_eq!(
+ worktree_create_targets(false, None, Some("feature")),
+ vec![WorktreeCreateTarget::CurrentBranch]
+ );
+ }
+
+ #[test]
+ fn test_worktree_create_target_branch_label() {
+ let origin_main = RemoteBranchName {
+ remote_name: "origin".to_string(),
+ branch_name: "main".to_string(),
+ };
+ assert_eq!(
+ WorktreeCreateTarget::DefaultBranch(origin_main).branch_label(false, Some("feature")),
+ "origin/main"
+ );
+ assert_eq!(
+ WorktreeCreateTarget::CurrentBranch.branch_label(false, Some("feature")),
+ "feature"
+ );
+ // Detached HEAD falls back to "HEAD".
+ assert_eq!(
+ WorktreeCreateTarget::CurrentBranch.branch_label(false, None),
+ "HEAD"
+ );
+ // Multiple repositories pluralize the current branch.
+ assert_eq!(
+ WorktreeCreateTarget::CurrentBranch.branch_label(true, Some("feature")),
+ "current branches"
+ );
+ }
}
diff --git a/crates/sidebar/Cargo.toml b/crates/sidebar/Cargo.toml
index fc3b8108f65..ef3f255ee77 100644
--- a/crates/sidebar/Cargo.toml
+++ b/crates/sidebar/Cargo.toml
@@ -28,6 +28,7 @@ editor.workspace = true
feature_flags.workspace = true
fs.workspace = true
git.workspace = true
+git_ui.workspace = true
gpui.workspace = true
itertools.workspace = true
language_model.workspace = true
diff --git a/crates/sidebar/src/sidebar.rs b/crates/sidebar/src/sidebar.rs
index 1cb3ace4acc..99ddd48dcdf 100644
--- a/crates/sidebar/src/sidebar.rs
+++ b/crates/sidebar/src/sidebar.rs
@@ -69,8 +69,9 @@ use workspace::{
notifications::NotificationId, sidebar_side_context_menu,
};
-use zed_actions::OpenRecent;
+use git_ui::worktree_service::{RemoteBranchName, worktree_create_targets};
use zed_actions::editor::{MoveDown, MoveUp};
+use zed_actions::{CreateWorktree, NewWorktreeBranchTarget, OpenRecent};
use zed_actions::agents_sidebar::{FocusSidebarFilter, ToggleThreadSwitcher};
@@ -626,7 +627,7 @@ impl WorkspaceMenuWorktreeLabel {
})
.child(Label::new(self.primary_name.clone()).truncate())
.when_some(self.secondary_name.clone(), |this, secondary_name| {
- this.child(Label::new(":").alpha(0.5))
+ this.child(Label::new("/").alpha(0.5))
.child(Label::new(secondary_name).truncate())
})
}
@@ -731,6 +732,35 @@ fn connect_remote(
remote_connection::connect_with_modal(&modal_workspace, connection_options, window, cx)
}
+// Per-project-group cache of the remote default branch, used to populate the
+// "Create New Worktree" submenu without doing git I/O while the menu is open.
+enum DefaultBranchCache {
+ Pending,
+ Resolved(Option<RemoteBranchName>),
+}
+
+// Mirrors the behavior of the worktree picker's "Create new worktree" entries.
+fn create_worktree_in_workspace(
+ workspace: &Entity<Workspace>,
+ branch_target: NewWorktreeBranchTarget,
+ window: &mut Window,
+ cx: &mut App,
+) {
+ workspace.update(cx, |workspace, cx| {
+ let focused_dock = workspace.focused_dock_position(window, cx);
+ git_ui::worktree_service::handle_create_worktree(
+ workspace,
+ &CreateWorktree {
+ worktree_name: None,
+ branch_target,
+ },
+ window,
+ focused_dock,
+ cx,
+ );
+ });
+}
+
/// The sidebar re-derives its entire entry list from scratch on every
/// change via `update_entries` → `rebuild_contents`. Avoid adding
/// incremental or inter-event coordination state — if something can
@@ -780,6 +810,7 @@ pub struct Sidebar {
project_header_menu_handles: HashMap<usize, PopoverMenuHandle<ContextMenu>>,
project_header_new_thread_menu_handles: HashMap<usize, PopoverMenuHandle<ContextMenu>>,
project_header_menu_ix: Option<usize>,
+ worktree_default_branches: HashMap<ProjectGroupKey, DefaultBranchCache>,
_subscriptions: Vec<gpui::Subscription>,
_draft_editor_observations: Vec<gpui::Subscription>,
update_task: Option<Task<()>>,
@@ -917,6 +948,7 @@ impl Sidebar {
project_header_menu_handles: HashMap::new(),
project_header_new_thread_menu_handles: HashMap::new(),
project_header_menu_ix: None,
+ worktree_default_branches: HashMap::new(),
_subscriptions: Vec::new(),
_draft_editor_observations: Vec::new(),
update_task: None,
@@ -2011,6 +2043,8 @@ impl Sidebar {
// Preserve measurements for unchanged entries so sticky headers do not flicker.
self.apply_list_state_diff(&previous_shapes, multi_workspace.read(cx));
+ self.prefetch_worktree_default_branches(cx);
+
if had_notifications != self.has_notifications(cx) {
multi_workspace.update(cx, |_, cx| {
cx.notify();
@@ -2508,7 +2542,7 @@ impl Sidebar {
.and_then(|mw| mw.read(cx).workspaces_for_project_group(key, cx))
.unwrap_or_default();
- if open_workspaces.len() <= 1 {
+ if open_workspaces.is_empty() {
let key = key.clone();
return button
.tooltip(move |_, cx| {
@@ -2569,7 +2603,7 @@ impl Sidebar {
Some(ContextMenu::build(
window,
cx,
- move |mut menu, _window, _cx| {
+ move |mut menu, _window, cx| {
menu = menu.header("New Thread In…");
for (workspace, labels) in open_workspaces
@@ -2620,6 +2654,77 @@ impl Sidebar {
);
}
+ let base_workspace = active_workspace
+ .as_ref()
+ .filter(|workspace| open_workspaces.contains(workspace))
+ .cloned()
+ .or_else(|| open_workspaces.first().cloned());
+
+ // Only offer worktree creation when the base project can
+ // actually create one; otherwise the submenu would expand to
+ // nothing. Mirrors the picker's `creation_blocked_reason`.
+ let creation_blocked = base_workspace.as_ref().is_none_or(|base_workspace| {
+ let project = base_workspace.read(cx).project().read(cx);
+ project.is_via_collab() || project.repositories(cx).is_empty()
+ });
+
+ if let Some(base_workspace) = base_workspace.filter(|_| !creation_blocked) {
+ menu = menu.separator().submenu("Create New Worktree…", {
+ let this = this.clone();
+ move |mut submenu, _window, submenu_cx| {
+ let project = base_workspace.read(submenu_cx).project().clone();
+ let project_ref = project.read(submenu_cx);
+ let has_multiple_repositories =
+ project_ref.repositories(submenu_cx).len() > 1;
+ let current_branch =
+ project_ref.active_repository(submenu_cx).and_then(|repo| {
+ repo.read(submenu_cx)
+ .branch
+ .as_ref()
+ .map(|branch| branch.name().to_string())
+ });
+ let default_branch = this
+ .read_with(submenu_cx, |sidebar, _| {
+ match sidebar.worktree_default_branches.get(&key) {
+ Some(DefaultBranchCache::Resolved(branch)) => {
+ branch.clone()
+ }
+ _ => None,
+ }
+ })
+ .ok()
+ .flatten();
+
+ let targets = worktree_create_targets(
+ has_multiple_repositories,
+ default_branch,
+ current_branch.as_deref(),
+ );
+ for target in targets {
+ let label = format!(
+ "Based on {}",
+ target.branch_label(
+ has_multiple_repositories,
+ current_branch.as_deref(),
+ )
+ );
+ let branch_target = target.branch_target();
+ let workspace = base_workspace.clone();
+ submenu = submenu.entry(label, None, move |window, cx| {
+ create_worktree_in_workspace(
+ &workspace,
+ branch_target.clone(),
+ window,
+ cx,
+ );
+ });
+ }
+
+ submenu
+ }
+ });
+ }
+
menu
},
))
@@ -2632,6 +2737,71 @@ impl Sidebar {
.into_any_element()
}
+ // Warms `worktree_default_branches` for every project group with at least one
+ // open workspace. The git query runs off the menu path so the submenu can read
+ // the result synchronously when it opens. Worktrees of a repository share the
+ // same default branch, so any workspace in the group yields the same answer.
+ fn prefetch_worktree_default_branches(&mut self, cx: &mut Context<Self>) {
+ let Some(multi_workspace) = self.multi_workspace.upgrade() else {
+ return;
+ };
+ let keys: Vec<ProjectGroupKey> = self
+ .contents
+ .entries
+ .iter()
+ .filter_map(|entry| match entry {
+ ListEntry::ProjectHeader { key, .. } => Some(key.clone()),
+ _ => None,
+ })
+ .collect();
+ for key in keys {
+ if self.worktree_default_branches.contains_key(&key) {
+ continue;
+ }
+ let Some(base) = multi_workspace
+ .read(cx)
+ .workspaces_for_project_group(&key, cx)
+ .and_then(|workspaces| workspaces.first().cloned())
+ else {
+ continue;
+ };
+ self.prefetch_worktree_default_branch(&key, &base, cx);
+ }
+ }
+
+ fn prefetch_worktree_default_branch(
+ &mut self,
+ key: &ProjectGroupKey,
+ workspace: &Entity<Workspace>,
+ cx: &mut Context<Self>,
+ ) {
+ // Presence of the key means the group is already pending or resolved. The
+ // no-repository case is deliberately not inserted so it retries on a
+ // later rebuild once the repository has finished loading.
+ if self.worktree_default_branches.contains_key(key) {
+ return;
+ }
+ let Some(repository) = workspace.read(cx).project().read(cx).active_repository(cx) else {
+ return;
+ };
+ let request = repository.update(cx, |repository, _| repository.default_branch(true));
+ self.worktree_default_branches
+ .insert(key.clone(), DefaultBranchCache::Pending);
+ let key = key.clone();
+ cx.spawn(async move |this, cx| {
+ let default_branch = request.await.ok().and_then(Result::ok).flatten();
+ let parsed = default_branch.as_deref().and_then(RemoteBranchName::parse);
+ this.update(cx, |sidebar, cx| {
+ sidebar
+ .worktree_default_branches
+ .insert(key, DefaultBranchCache::Resolved(parsed));
+ cx.notify();
+ })
+ .ok();
+ })
+ .detach();
+ }
+
fn render_project_header_ellipsis_menu(
&self,
ix: usize,