Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
git_ui: Create new worktree on latest origin main (#57704)
Bennet Bo Fennerb1bfde9e9dc6
diff --git a/crates/agent_ui/src/agent_panel.rs b/crates/agent_ui/src/agent_panel.rsindex 3dbd04bbddf..755c7a0abbc 100644--- a/crates/agent_ui/src/agent_panel.rs+++ b/crates/agent_ui/src/agent_panel.rs@@ -9934,6 +9934,14 @@ mod tests {&NewWorktreeBranchTarget::CurrentBranch,);assert_eq!(resolved, None);++ let resolved = git_ui::worktree_service::resolve_worktree_branch_target(+ &NewWorktreeBranchTarget::RemoteBranch {+ remote_name: "origin".to_string(),+ branch_name: "main".to_string(),+ },+ );+ assert_eq!(resolved, Some("refs/remotes/origin/main".to_string()));}#[gpui::test]diff --git a/crates/git_ui/src/git_panel.rs b/crates/git_ui/src/git_panel.rsindex 2618d84d93f..f60737af586 100644--- a/crates/git_ui/src/git_panel.rs+++ b/crates/git_ui/src/git_panel.rs@@ -7350,7 +7350,7 @@ impl Component for PanelRepoFooter {}}-fn open_output(+pub(crate) fn open_output(operation: impl Into<SharedString>,workspace: &mut Workspace,output: &str,diff --git a/crates/git_ui/src/worktree_picker.rs b/crates/git_ui/src/worktree_picker.rsindex 010a0d2deeb..70219da3cac 100644--- a/crates/git_ui/src/worktree_picker.rs+++ b/crates/git_ui/src/worktree_picker.rs@@ -96,7 +96,7 @@ impl WorktreePicker {.map(|repository| repository.update(cx, |repository, _| repository.worktrees()));let default_branch_request = repository.clone().map(|repository| {- repository.update(cx, |repository, _| repository.default_branch(false))+ repository.update(cx, |repository, _| repository.default_branch(true))});let initial_matches = vec![WorktreeEntry::CreateFromCurrentBranch];@@ -110,7 +110,7 @@ impl WorktreePicker {workspace,focused_dock,current_branch_name,- default_branch_name: None,+ default_branch: None,has_multiple_repositories,focus_handle: cx.focus_handle(),show_footer,@@ -160,8 +160,8 @@ impl WorktreePicker {picker_handle.update_in(cx, |picker, window, cx| {picker.delegate.all_worktrees = all_worktrees;- picker.delegate.default_branch_name =- default_branch.map(|branch| branch.to_string());+ picker.delegate.default_branch =+ default_branch.and_then(|branch| RemoteBranchName::parse(&branch));picker.refresh(window, cx);})?;@@ -260,7 +260,7 @@ impl Render for WorktreePicker {enum WorktreeEntry {CreateFromCurrentBranch,CreateFromDefaultBranch {- default_branch_name: String,+ default_branch: RemoteBranchName,},Separator,Worktree {@@ -269,11 +269,35 @@ enum WorktreeEntry {},CreateNamed {name: String,- from_branch: Option<String>,+ from_branch: Option<RemoteBranchName>,disabled_reason: Option<String>,},}+#[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>,@@ -283,7 +307,7 @@ struct WorktreePickerDelegate {workspace: WeakEntity<Workspace>,focused_dock: Option<DockPosition>,current_branch_name: Option<String>,- default_branch_name: Option<String>,+ default_branch: Option<RemoteBranchName>,has_multiple_repositories: bool,focus_handle: FocusHandle,show_footer: bool,@@ -396,20 +420,21 @@ impl WorktreePickerDelegate {fn build_fixed_entries(&self) -> Vec<WorktreeEntry> {let mut entries = Vec::new();- entries.push(WorktreeEntry::CreateFromCurrentBranch);-if !self.has_multiple_repositories {- if let Some(ref default_branch) = self.default_branch_name {+ 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);+ .is_none_or(|current| current != &default_branch.branch_name);+ entries.push(WorktreeEntry::CreateFromDefaultBranch {+ default_branch: default_branch.clone(),+ });if is_different {- entries.push(WorktreeEntry::CreateFromDefaultBranch {- default_branch_name: default_branch.clone(),- });+ entries.push(WorktreeEntry::CreateFromCurrentBranch);}}+ } else {+ entries.push(WorktreeEntry::CreateFromCurrentBranch);}entries@@ -628,13 +653,9 @@ impl PickerDelegate for WorktreePickerDelegate {None};- let show_default_branch_create = !self.has_multiple_repositories- && self.default_branch_name.as_ref().is_some_and(|default| {- self.current_branch_name- .as_ref()- .is_none_or(|current| current != default)- });- let default_branch_name = self.default_branch_name.clone();+ let show_default_branch_create =+ !self.has_multiple_repositories && self.default_branch.is_some();+ let default_branch = self.default_branch.clone();if query.is_empty() {let mut matches = self.build_fixed_entries();@@ -719,19 +740,20 @@ impl PickerDelegate for WorktreePickerDelegate {if !new_matches.is_empty() {new_matches.push(WorktreeEntry::Separator);}- new_matches.push(WorktreeEntry::CreateNamed {- name: normalized_query.clone(),- from_branch: None,- disabled_reason: create_named_disabled_reason.clone(),- });if show_default_branch_create {- if let Some(ref default_branch) = default_branch_name {+ if let Some(ref default_branch) = default_branch {new_matches.push(WorktreeEntry::CreateNamed {name: normalized_query.clone(),from_branch: Some(default_branch.clone()),disabled_reason: create_named_disabled_reason.clone(),});}+ } else {+ new_matches.push(WorktreeEntry::CreateNamed {+ name: normalized_query.clone(),+ from_branch: None,+ disabled_reason: create_named_disabled_reason.clone(),+ });}picker.delegate.matches = new_matches;@@ -769,9 +791,7 @@ impl PickerDelegate for WorktreePickerDelegate {});}}- WorktreeEntry::CreateFromDefaultBranch {- default_branch_name,- } => {+ WorktreeEntry::CreateFromDefaultBranch { default_branch } => {if self.creation_blocked_reason(cx).is_some() {return;}@@ -781,8 +801,9 @@ impl PickerDelegate for WorktreePickerDelegate {workspace,&CreateWorktree {worktree_name: None,- branch_target: NewWorktreeBranchTarget::ExistingBranch {- name: default_branch_name.clone(),+ branch_target: NewWorktreeBranchTarget::RemoteBranch {+ remote_name: default_branch.remote_name.clone(),+ branch_name: default_branch.branch_name.clone(),},},window,@@ -832,8 +853,9 @@ impl PickerDelegate for WorktreePickerDelegate {disabled_reason: None,} => {let branch_target = match from_branch {- Some(branch) => NewWorktreeBranchTarget::ExistingBranch {- name: branch.clone(),+ Some(branch) => NewWorktreeBranchTarget::RemoteBranch {+ remote_name: branch.remote_name.clone(),+ branch_name: branch.branch_name.clone(),},None => NewWorktreeBranchTarget::CurrentBranch,};@@ -901,9 +923,8 @@ impl PickerDelegate for WorktreePickerDelegate {Some(item.into_any_element())}- WorktreeEntry::CreateFromDefaultBranch {- default_branch_name,- } => {+ WorktreeEntry::CreateFromDefaultBranch { default_branch } => {+ let default_branch_name = default_branch.display_name();let label = format!("Create new worktree based on {default_branch_name}");let item = create_new_list_item(@@ -1088,11 +1109,16 @@ impl PickerDelegate for WorktreePickerDelegate {disabled_reason,} => {let branch_label = from_branch- .as_deref()- .unwrap_or(self.current_branch_name.as_deref().unwrap_or("HEAD"));+ .as_ref()+ .map(RemoteBranchName::display_name)+ .unwrap_or_else(|| {+ self.current_branch_name+ .clone()+ .unwrap_or_else(|| "HEAD".to_string())+ });let label = format!("Create \"{name}\" based on {branch_label}");let element_id = match from_branch {- Some(branch) => format!("create-named-from-{branch}"),+ Some(branch) => format!("create-named-from-{}", branch.display_name()),None => "create-named-from-current".to_string(),};@@ -1471,6 +1497,48 @@ mod tests {.any(|worktree| worktree.path == *worktree_path)}+ #[gpui::test]+ async fn test_remote_default_branch_is_preferred_create_target(cx: &mut TestAppContext) {+ let (_fs, worktree_picker, _repository, _worktree_path, mut cx) =+ init_worktree_picker_test(cx).await;++ worktree_picker.update(&mut cx, |worktree_picker, cx| {+ worktree_picker.picker.update(cx, |picker, _| {+ assert_eq!(picker.delegate.selected_index, 0);+ match picker.delegate.matches.first() {+ Some(WorktreeEntry::CreateFromDefaultBranch { default_branch }) => {+ assert_eq!(default_branch.display_name(), "origin/main");+ }+ _ => panic!("remote default branch should be the first create target"),+ }+ })+ });++ let update_matches = worktree_picker.update_in(&mut cx, |worktree_picker, window, cx| {+ worktree_picker.picker.update(cx, |picker, cx| {+ picker+ .delegate+ .update_matches("feature".to_string(), window, cx)+ })+ });+ update_matches.await;+ cx.run_until_parked();++ worktree_picker.update(&mut cx, |worktree_picker, cx| {+ worktree_picker+ .picker+ .update(cx, |picker, _| match picker.delegate.matches.first() {+ Some(WorktreeEntry::CreateNamed {+ from_branch: Some(default_branch),+ ..+ }) => {+ assert_eq!(default_branch.display_name(), "origin/main");+ }+ _ => panic!("named worktree creation should prefer the remote default branch"),+ })+ });+ }+#[gpui::test]async fn test_delete_dirty_worktree_prompts_for_force_delete(cx: &mut TestAppContext) {let (fs, worktree_picker, repository, worktree_path, mut cx) =diff --git a/crates/git_ui/src/worktree_service.rs b/crates/git_ui/src/worktree_service.rsindex e5301af3457..a37b08bac76 100644--- a/crates/git_ui/src/worktree_service.rs+++ b/crates/git_ui/src/worktree_service.rs@@ -1,22 +1,34 @@+use std::error::Error;+use std::fmt;use std::path::PathBuf;use std::sync::Arc;use anyhow::anyhow;+use askpass::AskPassDelegate;use collections::HashSet;use fs::Fs;-use gpui::{AsyncWindowContext, Entity, SharedString, TaskExt, WeakEntity};+use gpui::{+ AsyncWindowContext, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, SharedString,+ TaskExt, WeakEntity,+};use project::Project;use project::git_store::Repository;use project::project_settings::ProjectSettings;use project::trusted_worktrees::{PathTrust, TrustedWorktrees};use remote::RemoteConnectionOptions;use settings::Settings;-use workspace::{MultiWorkspace, OpenMode, PreviousWorkspaceState, Workspace, dock::DockPosition};+use ui::prelude::*;+use workspace::{+ MultiWorkspace, OpenMode, PreviousWorkspaceState, ToastView, Workspace, dock::DockPosition,+};use zed_actions::NewWorktreeBranchTarget;+use git::repository::{FetchOptions, Remote};+use util::ResultExt as _;-use crate::git_panel::show_error_toast;+use crate::askpass_modal::AskPassModal;+use crate::git_panel::{open_output, show_error_toast};use crate::worktree_names;/// Whether a worktree operation is creating a new one or switching to an@@ -27,6 +39,185 @@ enum WorktreeOperation {Switch,}+#[derive(Clone, Copy, PartialEq, Eq)]+enum RemoteBranchFetchMode {+ Fetch,+ UseLocal,+}++impl RemoteBranchFetchMode {+ fn should_fetch(self) -> bool {+ matches!(self, Self::Fetch)+ }+}++#[derive(Debug)]+struct WorktreeFetchError {+ remote_name: String,+ branch_name: String,+ source: anyhow::Error,+}++impl WorktreeFetchError {+ fn remote_branch_name(&self) -> String {+ format!("{}/{}", self.remote_name, self.branch_name)+ }++ fn output(&self) -> String {+ format!("git fetch {} failed:\n{:#}", self.remote_name, self.source)+ }+}++impl fmt::Display for WorktreeFetchError {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(+ formatter,+ "git fetch {} failed while creating worktree from {}: {}",+ self.remote_name,+ self.remote_branch_name(),+ self.source+ )+ }+}++impl Error for WorktreeFetchError {+ fn source(&self) -> Option<&(dyn Error + 'static)> {+ Some(self.source.as_ref())+ }+}++struct WorktreeFetchFailedToast {+ workspace: WeakEntity<Workspace>,+ worktree_name: Option<String>,+ branch_target: NewWorktreeBranchTarget,+ focused_dock: Option<DockPosition>,+ remote_branch_name: String,+ operation: SharedString,+ output: String,+ focus_handle: FocusHandle,+}++impl WorktreeFetchFailedToast {+ fn new(+ workspace: WeakEntity<Workspace>,+ worktree_name: Option<String>,+ branch_target: NewWorktreeBranchTarget,+ focused_dock: Option<DockPosition>,+ fetch_error: &WorktreeFetchError,+ cx: &mut gpui::Context<Self>,+ ) -> Self {+ Self {+ workspace,+ worktree_name,+ branch_target,+ focused_dock,+ remote_branch_name: fetch_error.remote_branch_name(),+ operation: format!("fetch {}", fetch_error.remote_name).into(),+ output: fetch_error.output(),+ focus_handle: cx.focus_handle(),+ }+ }+}++impl Focusable for WorktreeFetchFailedToast {+ fn focus_handle(&self, _cx: &gpui::App) -> FocusHandle {+ self.focus_handle.clone()+ }+}++impl EventEmitter<DismissEvent> for WorktreeFetchFailedToast {}++impl ToastView for WorktreeFetchFailedToast {+ fn action(&self) -> Option<workspace::ToastAction> {+ None+ }++ fn auto_dismiss(&self) -> bool {+ false+ }+}++impl Render for WorktreeFetchFailedToast {+ fn render(&mut self, _window: &mut Window, cx: &mut gpui::Context<Self>) -> impl IntoElement {+ let workspace_for_retry = self.workspace.clone();+ let worktree_name = self.worktree_name.clone();+ let branch_target = self.branch_target.clone();+ let focused_dock = self.focused_dock;++ let workspace_for_log = self.workspace.clone();+ let operation = self.operation.clone();+ let output = self.output.clone();++ h_flex()+ .id("worktree-fetch-failed-toast")+ .elevation_3(cx)+ .gap_2()+ .py_1p5()+ .pl_2p5()+ .pr_1p5()+ .flex_none()+ .bg(cx.theme().colors().surface_background)+ .shadow_lg()+ .child(+ Icon::new(IconName::XCircle)+ .size(IconSize::Small)+ .color(Color::Error),+ )+ .child(Label::new(format!(+ "git fetch failed for {}",+ self.remote_branch_name+ )))+ .child(+ Button::new(+ "use-local-worktree-base",+ format!("Use local {}", self.remote_branch_name),+ )+ .color(Color::Muted)+ .on_click(cx.listener(move |_, _event, window, cx| {+ cx.emit(DismissEvent);+ if let Some(workspace) = workspace_for_retry.upgrade() {+ workspace.update(cx, |workspace, cx| {+ handle_create_worktree_inner(+ workspace,+ &zed_actions::CreateWorktree {+ worktree_name: worktree_name.clone(),+ branch_target: branch_target.clone(),+ },+ window,+ focused_dock,+ RemoteBranchFetchMode::UseLocal,+ cx,+ );+ });+ }+ })),+ )+ .child(+ Button::new("view-worktree-fetch-log", "Show Error Logs")+ .color(Color::Muted)+ .on_click(cx.listener(move |_, _event, window, cx| {+ cx.emit(DismissEvent);+ let output = output.clone();+ let operation = operation.clone();+ workspace_for_log+ .update(cx, move |workspace, cx| {+ open_output(operation, workspace, &output, window, cx)+ })+ .ok();+ })),+ )+ .child(+ IconButton::new("dismiss-worktree-fetch-failed-toast", IconName::Close)+ .shape(ui::IconButtonShape::Square)+ .icon_size(IconSize::Small)+ .icon_color(Color::Muted)+ .on_click(cx.listener(|_, _event, _window, cx| {+ cx.emit(DismissEvent);+ })),+ )+ }+}+/// Classifies the project's visible worktrees into git-managed repositories/// and non-git paths. Each unique repository is returned only once.pub fn classify_worktrees(@@ -77,9 +268,84 @@ pub fn resolve_worktree_branch_target(branch_target: &NewWorktreeBranchTarget) -match branch_target {NewWorktreeBranchTarget::CurrentBranch => None,NewWorktreeBranchTarget::ExistingBranch { name } => Some(name.clone()),+ NewWorktreeBranchTarget::RemoteBranch {+ remote_name,+ branch_name,+ } => Some(format!("refs/remotes/{remote_name}/{branch_name}")),}}+fn remote_branch_to_fetch(branch_target: &NewWorktreeBranchTarget) -> Option<(&str, &str)> {+ match branch_target {+ NewWorktreeBranchTarget::RemoteBranch {+ remote_name,+ branch_name,+ } => Some((remote_name, branch_name)),+ NewWorktreeBranchTarget::CurrentBranch | NewWorktreeBranchTarget::ExistingBranch { .. } => {+ None+ }+ }+}++fn create_worktree_askpass_delegate(+ workspace: WeakEntity<Workspace>,+ operation: impl Into<SharedString>,+ window: &mut Window,+ cx: &mut Context<Workspace>,+) -> AskPassDelegate {+ let operation = operation.into();+ let window = window.window_handle();+ AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {+ window+ .update(cx, |_, window, cx| {+ workspace.update(cx, |workspace, cx| {+ workspace.toggle_modal(window, cx, |window, cx| {+ AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)+ });+ })+ })+ .ok();+ })+}++async fn fetch_remote_for_worktree_base(+ git_repos: &[Entity<Repository>],+ remote_name: String,+ askpass_delegates: Vec<AskPassDelegate>,+ cx: &mut AsyncWindowContext,+) -> anyhow::Result<()> {+ if askpass_delegates.len() != git_repos.len() {+ return Err(anyhow!(+ "Unable to fetch {remote_name}: missing credential prompt delegate"+ ));+ }++ let fetches = cx.update(|_, cx| {+ git_repos+ .iter()+ .cloned()+ .zip(askpass_delegates)+ .map(|(repo, askpass)| {+ repo.update(cx, |repo, cx| {+ repo.fetch(+ FetchOptions::Remote(Remote {+ name: remote_name.clone().into(),+ }),+ askpass,+ cx,+ )+ })+ })+ .collect::<Vec<_>>()+ })?;++ for fetch in futures::future::join_all(fetches).await {+ fetch??;+ }++ Ok(())+}+/// Kicks off an async git-worktree creation for each repository. Returns:////// - `creation_infos`: a vec of `(repo, new_path, receiver)` tuples.@@ -301,6 +567,24 @@ pub fn handle_create_worktree(window: &mut gpui::Window,fallback_focused_dock: Option<DockPosition>,cx: &mut gpui::Context<Workspace>,+) {+ handle_create_worktree_inner(+ workspace,+ action,+ window,+ fallback_focused_dock,+ RemoteBranchFetchMode::Fetch,+ cx,+ );+}++fn handle_create_worktree_inner(+ workspace: &mut Workspace,+ action: &zed_actions::CreateWorktree,+ window: &mut gpui::Window,+ fallback_focused_dock: Option<DockPosition>,+ remote_branch_fetch_mode: RemoteBranchFetchMode,+ cx: &mut gpui::Context<Workspace>,) {let project = workspace.project().clone();@@ -354,6 +638,25 @@ pub fn handle_create_worktree(let worktree_name = action.worktree_name.clone();let branch_target = action.branch_target.clone();+ let fetch_askpass_delegates = if remote_branch_fetch_mode.should_fetch() {+ remote_branch_to_fetch(&branch_target)+ .map(|(remote_name, _branch_name)| {+ git_repos+ .iter()+ .map(|_| {+ create_worktree_askpass_delegate(+ workspace_handle.clone(),+ format!("git fetch {remote_name}"),+ window,+ cx,+ )+ })+ .collect()+ })+ .unwrap_or_default()+ } else {+ Vec::new()+ };let display_name: SharedString = worktree_name.as_deref().unwrap_or("worktree")@@ -366,8 +669,10 @@ pub fn handle_create_worktree(let result = do_create_worktree(git_repos,non_git_paths,- worktree_name,- branch_target,+ worktree_name.clone(),+ branch_target.clone(),+ fetch_askpass_delegates,+ remote_branch_fetch_mode,previous_state,workspace_handle.clone(),window_handle,@@ -381,7 +686,21 @@ pub fn handle_create_worktree(workspace_handle.update(cx, |workspace, cx| {workspace.set_active_worktree_creation(None, false, cx);- show_error_toast(cx.entity(), "worktree create", anyhow!("{err:#}"), cx);+ if let Some(fetch_error) = err.downcast_ref::<WorktreeFetchError>() {+ let toast = cx.new(|cx| {+ WorktreeFetchFailedToast::new(+ workspace.weak_handle(),+ worktree_name,+ branch_target,+ fallback_focused_dock,+ fetch_error,+ cx,+ )+ });+ workspace.toggle_status_toast(toast, cx);+ } else {+ show_error_toast(cx.entity(), "worktree create", anyhow!("{err:#}"), cx);+ }}).ok();}@@ -466,6 +785,8 @@ async fn do_create_worktree(non_git_paths: Vec<PathBuf>,worktree_name: Option<String>,branch_target: NewWorktreeBranchTarget,+ fetch_askpass_delegates: Vec<AskPassDelegate>,+ remote_branch_fetch_mode: RemoteBranchFetchMode,previous_state: PreviousWorkspaceState,workspace: WeakEntity<Workspace>,window_handle: Option<gpui::WindowHandle<MultiWorkspace>>,@@ -510,6 +831,28 @@ async fn do_create_worktree(}}+ if remote_branch_fetch_mode.should_fetch()+ && let Some((remote_name, branch_name)) = remote_branch_to_fetch(&branch_target)+ {+ let remote_name = remote_name.to_string();+ let branch_name = branch_name.to_string();+ if let Err(error) = fetch_remote_for_worktree_base(+ &git_repos,+ remote_name.clone(),+ fetch_askpass_delegates,+ cx,+ )+ .await+ {+ return Err(WorktreeFetchError {+ remote_name,+ branch_name,+ source: error,+ }+ .into());+ }+ }+let mut rng = rand::rng();let base_ref = resolve_worktree_branch_target(&branch_target);diff --git a/crates/zed_actions/src/lib.rs b/crates/zed_actions/src/lib.rsindex 7d51fcbd70e..384c6fac54b 100644--- a/crates/zed_actions/src/lib.rs+++ b/crates/zed_actions/src/lib.rs@@ -264,6 +264,11 @@ pub enum NewWorktreeBranchTarget {CurrentBranch,/// Create a detached worktree at the tip of an existing branch.ExistingBranch { name: String },+ /// Create a detached worktree at the tip of a remote-tracking branch.+ RemoteBranch {+ remote_name: String,+ branch_name: String,+ },}/// Creates a new git worktree and switches the workspace to it.