worktree_picker.rs

  1use anyhow::Context as _;
  2use collections::HashSet;
  3use fuzzy::StringMatchCandidate;
  4
  5use git::repository::Worktree as GitWorktree;
  6use gpui::{
  7    Action, App, AsyncApp, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
  8    InteractiveElement, IntoElement, Modifiers, ModifiersChangedEvent, ParentElement,
  9    PathPromptOptions, Render, SharedString, Styled, Subscription, Task, WeakEntity, Window,
 10    actions, rems,
 11};
 12use picker::{Picker, PickerDelegate, PickerEditorPosition};
 13use project::{
 14    DirectoryLister,
 15    git_store::Repository,
 16    trusted_worktrees::{PathTrust, TrustedWorktrees},
 17};
 18use recent_projects::{RemoteConnectionModal, connect};
 19use remote::{RemoteConnectionOptions, remote_client::ConnectionIdentifier};
 20use std::{path::PathBuf, sync::Arc};
 21use ui::{HighlightedLabel, KeyBinding, ListItem, ListItemSpacing, Tooltip, prelude::*};
 22use util::ResultExt;
 23use workspace::{ModalView, Workspace, notifications::DetachAndPromptErr};
 24
 25actions!(git, [WorktreeFromDefault, WorktreeFromDefaultOnWindow]);
 26
 27pub fn register(workspace: &mut Workspace) {
 28    workspace.register_action(open);
 29}
 30
 31pub fn open(
 32    workspace: &mut Workspace,
 33    _: &zed_actions::git::Worktree,
 34    window: &mut Window,
 35    cx: &mut Context<Workspace>,
 36) {
 37    let repository = workspace.project().read(cx).active_repository(cx);
 38    let workspace_handle = workspace.weak_handle();
 39    workspace.toggle_modal(window, cx, |window, cx| {
 40        WorktreeList::new(repository, workspace_handle, rems(34.), window, cx)
 41    })
 42}
 43
 44pub struct WorktreeList {
 45    width: Rems,
 46    pub picker: Entity<Picker<WorktreeListDelegate>>,
 47    picker_focus_handle: FocusHandle,
 48    _subscription: Subscription,
 49}
 50
 51impl WorktreeList {
 52    fn new(
 53        repository: Option<Entity<Repository>>,
 54        workspace: WeakEntity<Workspace>,
 55        width: Rems,
 56        window: &mut Window,
 57        cx: &mut Context<Self>,
 58    ) -> Self {
 59        let all_worktrees_request = repository
 60            .clone()
 61            .map(|repository| repository.update(cx, |repository, _| repository.worktrees()));
 62
 63        let default_branch_request = repository
 64            .clone()
 65            .map(|repository| repository.update(cx, |repository, _| repository.default_branch()));
 66
 67        cx.spawn_in(window, async move |this, cx| {
 68            let all_worktrees = all_worktrees_request
 69                .context("No active repository")?
 70                .await??;
 71
 72            let default_branch = default_branch_request
 73                .context("No active repository")?
 74                .await
 75                .map(Result::ok)
 76                .ok()
 77                .flatten()
 78                .flatten();
 79
 80            this.update_in(cx, |this, window, cx| {
 81                this.picker.update(cx, |picker, cx| {
 82                    picker.delegate.all_worktrees = Some(all_worktrees);
 83                    picker.delegate.default_branch = default_branch;
 84                    picker.refresh(window, cx);
 85                })
 86            })?;
 87
 88            anyhow::Ok(())
 89        })
 90        .detach_and_log_err(cx);
 91
 92        let delegate = WorktreeListDelegate::new(workspace, repository, window, cx);
 93        let picker = cx.new(|cx| Picker::uniform_list(delegate, window, cx));
 94        let picker_focus_handle = picker.focus_handle(cx);
 95        picker.update(cx, |picker, _| {
 96            picker.delegate.focus_handle = picker_focus_handle.clone();
 97        });
 98
 99        let _subscription = cx.subscribe(&picker, |_, _, _, cx| {
100            cx.emit(DismissEvent);
101        });
102
103        Self {
104            picker,
105            picker_focus_handle,
106            width,
107            _subscription,
108        }
109    }
110
111    fn handle_modifiers_changed(
112        &mut self,
113        ev: &ModifiersChangedEvent,
114        _: &mut Window,
115        cx: &mut Context<Self>,
116    ) {
117        self.picker
118            .update(cx, |picker, _| picker.delegate.modifiers = ev.modifiers)
119    }
120
121    fn handle_new_worktree(
122        &mut self,
123        replace_current_window: bool,
124        window: &mut Window,
125        cx: &mut Context<Self>,
126    ) {
127        self.picker.update(cx, |picker, cx| {
128            let ix = picker.delegate.selected_index();
129            let Some(entry) = picker.delegate.matches.get(ix) else {
130                return;
131            };
132            let Some(default_branch) = picker.delegate.default_branch.clone() else {
133                return;
134            };
135            if !entry.is_new {
136                return;
137            }
138            picker.delegate.create_worktree(
139                entry.worktree.branch(),
140                replace_current_window,
141                Some(default_branch.into()),
142                window,
143                cx,
144            );
145        })
146    }
147}
148impl ModalView for WorktreeList {}
149impl EventEmitter<DismissEvent> for WorktreeList {}
150
151impl Focusable for WorktreeList {
152    fn focus_handle(&self, _: &App) -> FocusHandle {
153        self.picker_focus_handle.clone()
154    }
155}
156
157impl Render for WorktreeList {
158    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
159        v_flex()
160            .key_context("GitWorktreeSelector")
161            .w(self.width)
162            .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
163            .on_action(cx.listener(|this, _: &WorktreeFromDefault, w, cx| {
164                this.handle_new_worktree(false, w, cx)
165            }))
166            .on_action(cx.listener(|this, _: &WorktreeFromDefaultOnWindow, w, cx| {
167                this.handle_new_worktree(true, w, cx)
168            }))
169            .child(self.picker.clone())
170            .on_mouse_down_out({
171                cx.listener(move |this, _, window, cx| {
172                    this.picker.update(cx, |this, cx| {
173                        this.cancel(&Default::default(), window, cx);
174                    })
175                })
176            })
177    }
178}
179
180#[derive(Debug, Clone)]
181struct WorktreeEntry {
182    worktree: GitWorktree,
183    positions: Vec<usize>,
184    is_new: bool,
185}
186
187pub struct WorktreeListDelegate {
188    matches: Vec<WorktreeEntry>,
189    all_worktrees: Option<Vec<GitWorktree>>,
190    workspace: WeakEntity<Workspace>,
191    repo: Option<Entity<Repository>>,
192    selected_index: usize,
193    last_query: String,
194    modifiers: Modifiers,
195    focus_handle: FocusHandle,
196    default_branch: Option<SharedString>,
197}
198
199impl WorktreeListDelegate {
200    fn new(
201        workspace: WeakEntity<Workspace>,
202        repo: Option<Entity<Repository>>,
203        _window: &mut Window,
204        cx: &mut Context<WorktreeList>,
205    ) -> Self {
206        Self {
207            matches: vec![],
208            all_worktrees: None,
209            workspace,
210            selected_index: 0,
211            repo,
212            last_query: Default::default(),
213            modifiers: Default::default(),
214            focus_handle: cx.focus_handle(),
215            default_branch: None,
216        }
217    }
218
219    fn create_worktree(
220        &self,
221        worktree_branch: &str,
222        replace_current_window: bool,
223        commit: Option<String>,
224        window: &mut Window,
225        cx: &mut Context<Picker<Self>>,
226    ) {
227        let Some(repo) = self.repo.clone() else {
228            return;
229        };
230
231        let worktree_path = self
232            .workspace
233            .clone()
234            .update(cx, |this, cx| {
235                this.prompt_for_open_path(
236                    PathPromptOptions {
237                        files: false,
238                        directories: true,
239                        multiple: false,
240                        prompt: Some("Select directory for new worktree".into()),
241                    },
242                    DirectoryLister::Project(this.project().clone()),
243                    window,
244                    cx,
245                )
246            })
247            .log_err();
248        let Some(worktree_path) = worktree_path else {
249            return;
250        };
251
252        let branch = worktree_branch.to_string();
253        let window_handle = window.window_handle();
254        let workspace = self.workspace.clone();
255        cx.spawn_in(window, async move |_, cx| {
256            let Some(paths) = worktree_path.await? else {
257                return anyhow::Ok(());
258            };
259            let path = paths.get(0).cloned().context("No path selected")?;
260
261            repo.update(cx, |repo, _| {
262                repo.create_worktree(branch.clone(), path.clone(), commit)
263            })?
264            .await??;
265            let new_worktree_path = path.join(branch);
266
267            workspace.update(cx, |workspace, cx| {
268                if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
269                    let repo_path = &repo.read(cx).snapshot().work_directory_abs_path;
270                    let project = workspace.project();
271                    if let Some((parent_worktree, _)) =
272                        project.read(cx).find_worktree(repo_path, cx)
273                    {
274                        let worktree_store = project.read(cx).worktree_store();
275                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
276                            if trusted_worktrees.can_trust(
277                                &worktree_store,
278                                parent_worktree.read(cx).id(),
279                                cx,
280                            ) {
281                                trusted_worktrees.trust(
282                                    &worktree_store,
283                                    HashSet::from_iter([PathTrust::AbsPath(
284                                        new_worktree_path.clone(),
285                                    )]),
286                                    cx,
287                                );
288                            }
289                        });
290                    }
291                }
292            })?;
293
294            let (connection_options, app_state, is_local) =
295                workspace.update(cx, |workspace, cx| {
296                    let project = workspace.project().clone();
297                    let connection_options = project.read(cx).remote_connection_options(cx);
298                    let app_state = workspace.app_state().clone();
299                    let is_local = project.read(cx).is_local();
300                    (connection_options, app_state, is_local)
301                })?;
302
303            if is_local {
304                workspace
305                    .update_in(cx, |workspace, window, cx| {
306                        workspace.open_workspace_for_paths(
307                            replace_current_window,
308                            vec![new_worktree_path],
309                            window,
310                            cx,
311                        )
312                    })?
313                    .await?;
314            } else if let Some(connection_options) = connection_options {
315                open_remote_worktree(
316                    connection_options,
317                    vec![new_worktree_path],
318                    app_state,
319                    window_handle,
320                    replace_current_window,
321                    cx,
322                )
323                .await?;
324            }
325
326            anyhow::Ok(())
327        })
328        .detach_and_prompt_err("Failed to create worktree", window, cx, |e, _, _| {
329            Some(e.to_string())
330        });
331    }
332
333    fn open_worktree(
334        &self,
335        worktree_path: &PathBuf,
336        replace_current_window: bool,
337        window: &mut Window,
338        cx: &mut Context<Picker<Self>>,
339    ) {
340        let workspace = self.workspace.clone();
341        let path = worktree_path.clone();
342
343        let Some((connection_options, app_state, is_local)) = workspace
344            .update(cx, |workspace, cx| {
345                let project = workspace.project().clone();
346                let connection_options = project.read(cx).remote_connection_options(cx);
347                let app_state = workspace.app_state().clone();
348                let is_local = project.read(cx).is_local();
349                (connection_options, app_state, is_local)
350            })
351            .log_err()
352        else {
353            return;
354        };
355
356        if is_local {
357            let open_task = workspace.update(cx, |workspace, cx| {
358                workspace.open_workspace_for_paths(replace_current_window, vec![path], window, cx)
359            });
360            cx.spawn(async move |_, _| {
361                open_task?.await?;
362                anyhow::Ok(())
363            })
364            .detach_and_prompt_err(
365                "Failed to open worktree",
366                window,
367                cx,
368                |e, _, _| Some(e.to_string()),
369            );
370        } else if let Some(connection_options) = connection_options {
371            let window_handle = window.window_handle();
372            cx.spawn_in(window, async move |_, cx| {
373                open_remote_worktree(
374                    connection_options,
375                    vec![path],
376                    app_state,
377                    window_handle,
378                    replace_current_window,
379                    cx,
380                )
381                .await
382            })
383            .detach_and_prompt_err(
384                "Failed to open worktree",
385                window,
386                cx,
387                |e, _, _| Some(e.to_string()),
388            );
389        }
390
391        cx.emit(DismissEvent);
392    }
393
394    fn base_branch<'a>(&'a self, cx: &'a mut Context<Picker<Self>>) -> Option<&'a str> {
395        self.repo
396            .as_ref()
397            .and_then(|repo| repo.read(cx).branch.as_ref().map(|b| b.name()))
398    }
399}
400
401async fn open_remote_worktree(
402    connection_options: RemoteConnectionOptions,
403    paths: Vec<PathBuf>,
404    app_state: Arc<workspace::AppState>,
405    window: gpui::AnyWindowHandle,
406    replace_current_window: bool,
407    cx: &mut AsyncApp,
408) -> anyhow::Result<()> {
409    let workspace_window = window
410        .downcast::<Workspace>()
411        .ok_or_else(|| anyhow::anyhow!("Window is not a Workspace window"))?;
412
413    let connect_task = workspace_window.update(cx, |workspace, window, cx| {
414        workspace.toggle_modal(window, cx, |window, cx| {
415            RemoteConnectionModal::new(&connection_options, Vec::new(), window, cx)
416        });
417
418        let prompt = workspace
419            .active_modal::<RemoteConnectionModal>(cx)
420            .expect("Modal just created")
421            .read(cx)
422            .prompt
423            .clone();
424
425        connect(
426            ConnectionIdentifier::setup(),
427            connection_options.clone(),
428            prompt,
429            window,
430            cx,
431        )
432        .prompt_err("Failed to connect", window, cx, |_, _, _| None)
433    })?;
434
435    let session = connect_task.await;
436
437    workspace_window.update(cx, |workspace, _window, cx| {
438        if let Some(prompt) = workspace.active_modal::<RemoteConnectionModal>(cx) {
439            prompt.update(cx, |prompt, cx| prompt.finished(cx))
440        }
441    })?;
442
443    let Some(Some(session)) = session else {
444        return Ok(());
445    };
446
447    let new_project = cx.update(|cx| {
448        project::Project::remote(
449            session,
450            app_state.client.clone(),
451            app_state.node_runtime.clone(),
452            app_state.user_store.clone(),
453            app_state.languages.clone(),
454            app_state.fs.clone(),
455            true,
456            cx,
457        )
458    })?;
459
460    let window_to_use = if replace_current_window {
461        workspace_window
462    } else {
463        let workspace_position = cx
464            .update(|cx| {
465                workspace::remote_workspace_position_from_db(connection_options.clone(), &paths, cx)
466            })?
467            .await
468            .context("fetching workspace position from db")?;
469
470        let mut options =
471            cx.update(|cx| (app_state.build_window_options)(workspace_position.display, cx))?;
472        options.window_bounds = workspace_position.window_bounds;
473
474        cx.open_window(options, |window, cx| {
475            cx.new(|cx| {
476                let mut workspace =
477                    Workspace::new(None, new_project.clone(), app_state.clone(), window, cx);
478                workspace.centered_layout = workspace_position.centered_layout;
479                workspace
480            })
481        })?
482    };
483
484    workspace::open_remote_project_with_existing_connection(
485        connection_options,
486        new_project,
487        paths,
488        app_state,
489        window_to_use,
490        cx,
491    )
492    .await?;
493
494    Ok(())
495}
496
497impl PickerDelegate for WorktreeListDelegate {
498    type ListItem = ListItem;
499
500    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
501        "Select worktree…".into()
502    }
503
504    fn editor_position(&self) -> PickerEditorPosition {
505        PickerEditorPosition::Start
506    }
507
508    fn match_count(&self) -> usize {
509        self.matches.len()
510    }
511
512    fn selected_index(&self) -> usize {
513        self.selected_index
514    }
515
516    fn set_selected_index(
517        &mut self,
518        ix: usize,
519        _window: &mut Window,
520        _: &mut Context<Picker<Self>>,
521    ) {
522        self.selected_index = ix;
523    }
524
525    fn update_matches(
526        &mut self,
527        query: String,
528        window: &mut Window,
529        cx: &mut Context<Picker<Self>>,
530    ) -> Task<()> {
531        let Some(all_worktrees) = self.all_worktrees.clone() else {
532            return Task::ready(());
533        };
534
535        cx.spawn_in(window, async move |picker, cx| {
536            let mut matches: Vec<WorktreeEntry> = if query.is_empty() {
537                all_worktrees
538                    .into_iter()
539                    .map(|worktree| WorktreeEntry {
540                        worktree,
541                        positions: Vec::new(),
542                        is_new: false,
543                    })
544                    .collect()
545            } else {
546                let candidates = all_worktrees
547                    .iter()
548                    .enumerate()
549                    .map(|(ix, worktree)| StringMatchCandidate::new(ix, worktree.branch()))
550                    .collect::<Vec<StringMatchCandidate>>();
551                fuzzy::match_strings(
552                    &candidates,
553                    &query,
554                    true,
555                    true,
556                    10000,
557                    &Default::default(),
558                    cx.background_executor().clone(),
559                )
560                .await
561                .into_iter()
562                .map(|candidate| WorktreeEntry {
563                    worktree: all_worktrees[candidate.candidate_id].clone(),
564                    positions: candidate.positions,
565                    is_new: false,
566                })
567                .collect()
568            };
569            picker
570                .update(cx, |picker, _| {
571                    if !query.is_empty()
572                        && !matches
573                            .first()
574                            .is_some_and(|entry| entry.worktree.branch() == query)
575                    {
576                        let query = query.replace(' ', "-");
577                        matches.push(WorktreeEntry {
578                            worktree: GitWorktree {
579                                path: Default::default(),
580                                ref_name: format!("refs/heads/{query}").into(),
581                                sha: Default::default(),
582                            },
583                            positions: Vec::new(),
584                            is_new: true,
585                        })
586                    }
587                    let delegate = &mut picker.delegate;
588                    delegate.matches = matches;
589                    if delegate.matches.is_empty() {
590                        delegate.selected_index = 0;
591                    } else {
592                        delegate.selected_index =
593                            core::cmp::min(delegate.selected_index, delegate.matches.len() - 1);
594                    }
595                    delegate.last_query = query;
596                })
597                .log_err();
598        })
599    }
600
601    fn confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
602        let Some(entry) = self.matches.get(self.selected_index()) else {
603            return;
604        };
605        if entry.is_new {
606            self.create_worktree(&entry.worktree.branch(), secondary, None, window, cx);
607        } else {
608            self.open_worktree(&entry.worktree.path, secondary, window, cx);
609        }
610
611        cx.emit(DismissEvent);
612    }
613
614    fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<Self>>) {
615        cx.emit(DismissEvent);
616    }
617
618    fn render_match(
619        &self,
620        ix: usize,
621        selected: bool,
622        _window: &mut Window,
623        cx: &mut Context<Picker<Self>>,
624    ) -> Option<Self::ListItem> {
625        let entry = &self.matches.get(ix)?;
626        let path = entry.worktree.path.to_string_lossy().to_string();
627        let sha = entry
628            .worktree
629            .sha
630            .clone()
631            .chars()
632            .take(7)
633            .collect::<String>();
634
635        let focus_handle = self.focus_handle.clone();
636        let icon = if let Some(default_branch) = self.default_branch.clone()
637            && entry.is_new
638        {
639            Some(
640                IconButton::new("worktree-from-default", IconName::GitBranchAlt)
641                    .on_click(|_, window, cx| {
642                        window.dispatch_action(WorktreeFromDefault.boxed_clone(), cx)
643                    })
644                    .on_right_click(|_, window, cx| {
645                        window.dispatch_action(WorktreeFromDefaultOnWindow.boxed_clone(), cx)
646                    })
647                    .tooltip(move |_, cx| {
648                        Tooltip::for_action_in(
649                            format!("From default branch {default_branch}"),
650                            &WorktreeFromDefault,
651                            &focus_handle,
652                            cx,
653                        )
654                    }),
655            )
656        } else {
657            None
658        };
659
660        let branch_name = if entry.is_new {
661            h_flex()
662                .gap_1()
663                .child(
664                    Icon::new(IconName::Plus)
665                        .size(IconSize::Small)
666                        .color(Color::Muted),
667                )
668                .child(
669                    Label::new(format!("Create worktree \"{}\"", entry.worktree.branch()))
670                        .single_line()
671                        .truncate(),
672                )
673                .into_any_element()
674        } else {
675            h_flex()
676                .gap_1()
677                .child(
678                    Icon::new(IconName::GitBranch)
679                        .size(IconSize::Small)
680                        .color(Color::Muted),
681                )
682                .child(HighlightedLabel::new(
683                    entry.worktree.branch().to_owned(),
684                    entry.positions.clone(),
685                ))
686                .truncate()
687                .into_any_element()
688        };
689
690        let sublabel = if entry.is_new {
691            format!(
692                "based off {}",
693                self.base_branch(cx).unwrap_or("the current branch")
694            )
695        } else {
696            format!("at {}", path)
697        };
698
699        Some(
700            ListItem::new(format!("worktree-menu-{ix}"))
701                .inset(true)
702                .spacing(ListItemSpacing::Sparse)
703                .toggle_state(selected)
704                .child(
705                    v_flex()
706                        .w_full()
707                        .overflow_hidden()
708                        .child(
709                            h_flex()
710                                .gap_6()
711                                .justify_between()
712                                .overflow_x_hidden()
713                                .child(branch_name)
714                                .when(!entry.is_new, |el| {
715                                    el.child(
716                                        Label::new(sha)
717                                            .size(LabelSize::Small)
718                                            .color(Color::Muted)
719                                            .into_element(),
720                                    )
721                                }),
722                        )
723                        .child(
724                            div().max_w_96().child(
725                                Label::new(sublabel)
726                                    .size(LabelSize::Small)
727                                    .color(Color::Muted)
728                                    .truncate()
729                                    .into_any_element(),
730                            ),
731                        ),
732                )
733                .end_slot::<IconButton>(icon),
734        )
735    }
736
737    fn no_matches_text(&self, _window: &mut Window, _cx: &mut App) -> Option<SharedString> {
738        Some("No worktrees found".into())
739    }
740
741    fn render_footer(&self, _: &mut Window, cx: &mut Context<Picker<Self>>) -> Option<AnyElement> {
742        let focus_handle = self.focus_handle.clone();
743
744        Some(
745            h_flex()
746                .w_full()
747                .p_1p5()
748                .gap_0p5()
749                .justify_end()
750                .border_t_1()
751                .border_color(cx.theme().colors().border_variant)
752                .child(
753                    Button::new("open-in-new-window", "Open in new window")
754                        .key_binding(
755                            KeyBinding::for_action_in(&menu::Confirm, &focus_handle, cx)
756                                .map(|kb| kb.size(rems_from_px(12.))),
757                        )
758                        .on_click(|_, window, cx| {
759                            window.dispatch_action(menu::Confirm.boxed_clone(), cx)
760                        }),
761                )
762                .child(
763                    Button::new("open-in-window", "Open")
764                        .key_binding(
765                            KeyBinding::for_action_in(&menu::SecondaryConfirm, &focus_handle, cx)
766                                .map(|kb| kb.size(rems_from_px(12.))),
767                        )
768                        .on_click(|_, window, cx| {
769                            window.dispatch_action(menu::SecondaryConfirm.boxed_clone(), cx)
770                        }),
771                )
772                .into_any(),
773        )
774    }
775}