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, RemoteHostLocation, 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 remote_host = project.read_with(cx, |project, cx| {
275                            project
276                                .lsp_store()
277                                .read(cx)
278                                .downstream_client()
279                                .or_else(|| project.lsp_store().read(cx).upstream_client())
280                                .map(|(_, project_id)| project_id)
281                                .zip(project.remote_connection_options(cx))
282                                .map(RemoteHostLocation::from)
283                        });
284
285                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
286                            if trusted_worktrees.can_trust(parent_worktree.read(cx).id(), cx) {
287                                trusted_worktrees.trust(
288                                    HashSet::from_iter([PathTrust::AbsPath(
289                                        new_worktree_path.clone(),
290                                    )]),
291                                    remote_host,
292                                    cx,
293                                );
294                            }
295                        });
296                    }
297                }
298            })?;
299
300            let (connection_options, app_state, is_local) =
301                workspace.update(cx, |workspace, cx| {
302                    let project = workspace.project().clone();
303                    let connection_options = project.read(cx).remote_connection_options(cx);
304                    let app_state = workspace.app_state().clone();
305                    let is_local = project.read(cx).is_local();
306                    (connection_options, app_state, is_local)
307                })?;
308
309            if is_local {
310                workspace
311                    .update_in(cx, |workspace, window, cx| {
312                        workspace.open_workspace_for_paths(
313                            replace_current_window,
314                            vec![new_worktree_path],
315                            window,
316                            cx,
317                        )
318                    })?
319                    .await?;
320            } else if let Some(connection_options) = connection_options {
321                open_remote_worktree(
322                    connection_options,
323                    vec![new_worktree_path],
324                    app_state,
325                    window_handle,
326                    replace_current_window,
327                    cx,
328                )
329                .await?;
330            }
331
332            anyhow::Ok(())
333        })
334        .detach_and_prompt_err("Failed to create worktree", window, cx, |e, _, _| {
335            Some(e.to_string())
336        });
337    }
338
339    fn open_worktree(
340        &self,
341        worktree_path: &PathBuf,
342        replace_current_window: bool,
343        window: &mut Window,
344        cx: &mut Context<Picker<Self>>,
345    ) {
346        let workspace = self.workspace.clone();
347        let path = worktree_path.clone();
348
349        let Some((connection_options, app_state, is_local)) = workspace
350            .update(cx, |workspace, cx| {
351                let project = workspace.project().clone();
352                let connection_options = project.read(cx).remote_connection_options(cx);
353                let app_state = workspace.app_state().clone();
354                let is_local = project.read(cx).is_local();
355                (connection_options, app_state, is_local)
356            })
357            .log_err()
358        else {
359            return;
360        };
361
362        if is_local {
363            let open_task = workspace.update(cx, |workspace, cx| {
364                workspace.open_workspace_for_paths(replace_current_window, vec![path], window, cx)
365            });
366            cx.spawn(async move |_, _| {
367                open_task?.await?;
368                anyhow::Ok(())
369            })
370            .detach_and_prompt_err(
371                "Failed to open worktree",
372                window,
373                cx,
374                |e, _, _| Some(e.to_string()),
375            );
376        } else if let Some(connection_options) = connection_options {
377            let window_handle = window.window_handle();
378            cx.spawn_in(window, async move |_, cx| {
379                open_remote_worktree(
380                    connection_options,
381                    vec![path],
382                    app_state,
383                    window_handle,
384                    replace_current_window,
385                    cx,
386                )
387                .await
388            })
389            .detach_and_prompt_err(
390                "Failed to open worktree",
391                window,
392                cx,
393                |e, _, _| Some(e.to_string()),
394            );
395        }
396
397        cx.emit(DismissEvent);
398    }
399
400    fn base_branch<'a>(&'a self, cx: &'a mut Context<Picker<Self>>) -> Option<&'a str> {
401        self.repo
402            .as_ref()
403            .and_then(|repo| repo.read(cx).branch.as_ref().map(|b| b.name()))
404    }
405}
406
407async fn open_remote_worktree(
408    connection_options: RemoteConnectionOptions,
409    paths: Vec<PathBuf>,
410    app_state: Arc<workspace::AppState>,
411    window: gpui::AnyWindowHandle,
412    replace_current_window: bool,
413    cx: &mut AsyncApp,
414) -> anyhow::Result<()> {
415    let workspace_window = window
416        .downcast::<Workspace>()
417        .ok_or_else(|| anyhow::anyhow!("Window is not a Workspace window"))?;
418
419    let connect_task = workspace_window.update(cx, |workspace, window, cx| {
420        workspace.toggle_modal(window, cx, |window, cx| {
421            RemoteConnectionModal::new(&connection_options, Vec::new(), window, cx)
422        });
423
424        let prompt = workspace
425            .active_modal::<RemoteConnectionModal>(cx)
426            .expect("Modal just created")
427            .read(cx)
428            .prompt
429            .clone();
430
431        connect(
432            ConnectionIdentifier::setup(),
433            connection_options.clone(),
434            prompt,
435            window,
436            cx,
437        )
438        .prompt_err("Failed to connect", window, cx, |_, _, _| None)
439    })?;
440
441    let session = connect_task.await;
442
443    workspace_window.update(cx, |workspace, _window, cx| {
444        if let Some(prompt) = workspace.active_modal::<RemoteConnectionModal>(cx) {
445            prompt.update(cx, |prompt, cx| prompt.finished(cx))
446        }
447    })?;
448
449    let Some(Some(session)) = session else {
450        return Ok(());
451    };
452
453    let new_project = cx.update(|cx| {
454        project::Project::remote(
455            session,
456            app_state.client.clone(),
457            app_state.node_runtime.clone(),
458            app_state.user_store.clone(),
459            app_state.languages.clone(),
460            app_state.fs.clone(),
461            true,
462            cx,
463        )
464    })?;
465
466    let window_to_use = if replace_current_window {
467        workspace_window
468    } else {
469        let workspace_position = cx
470            .update(|cx| {
471                workspace::remote_workspace_position_from_db(connection_options.clone(), &paths, cx)
472            })?
473            .await
474            .context("fetching workspace position from db")?;
475
476        let mut options =
477            cx.update(|cx| (app_state.build_window_options)(workspace_position.display, cx))?;
478        options.window_bounds = workspace_position.window_bounds;
479
480        cx.open_window(options, |window, cx| {
481            cx.new(|cx| {
482                let mut workspace =
483                    Workspace::new(None, new_project.clone(), app_state.clone(), window, cx);
484                workspace.centered_layout = workspace_position.centered_layout;
485                workspace
486            })
487        })?
488    };
489
490    workspace::open_remote_project_with_existing_connection(
491        connection_options,
492        new_project,
493        paths,
494        app_state,
495        window_to_use,
496        cx,
497    )
498    .await?;
499
500    Ok(())
501}
502
503impl PickerDelegate for WorktreeListDelegate {
504    type ListItem = ListItem;
505
506    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
507        "Select worktree…".into()
508    }
509
510    fn editor_position(&self) -> PickerEditorPosition {
511        PickerEditorPosition::Start
512    }
513
514    fn match_count(&self) -> usize {
515        self.matches.len()
516    }
517
518    fn selected_index(&self) -> usize {
519        self.selected_index
520    }
521
522    fn set_selected_index(
523        &mut self,
524        ix: usize,
525        _window: &mut Window,
526        _: &mut Context<Picker<Self>>,
527    ) {
528        self.selected_index = ix;
529    }
530
531    fn update_matches(
532        &mut self,
533        query: String,
534        window: &mut Window,
535        cx: &mut Context<Picker<Self>>,
536    ) -> Task<()> {
537        let Some(all_worktrees) = self.all_worktrees.clone() else {
538            return Task::ready(());
539        };
540
541        cx.spawn_in(window, async move |picker, cx| {
542            let mut matches: Vec<WorktreeEntry> = if query.is_empty() {
543                all_worktrees
544                    .into_iter()
545                    .map(|worktree| WorktreeEntry {
546                        worktree,
547                        positions: Vec::new(),
548                        is_new: false,
549                    })
550                    .collect()
551            } else {
552                let candidates = all_worktrees
553                    .iter()
554                    .enumerate()
555                    .map(|(ix, worktree)| StringMatchCandidate::new(ix, worktree.branch()))
556                    .collect::<Vec<StringMatchCandidate>>();
557                fuzzy::match_strings(
558                    &candidates,
559                    &query,
560                    true,
561                    true,
562                    10000,
563                    &Default::default(),
564                    cx.background_executor().clone(),
565                )
566                .await
567                .into_iter()
568                .map(|candidate| WorktreeEntry {
569                    worktree: all_worktrees[candidate.candidate_id].clone(),
570                    positions: candidate.positions,
571                    is_new: false,
572                })
573                .collect()
574            };
575            picker
576                .update(cx, |picker, _| {
577                    if !query.is_empty()
578                        && !matches
579                            .first()
580                            .is_some_and(|entry| entry.worktree.branch() == query)
581                    {
582                        let query = query.replace(' ', "-");
583                        matches.push(WorktreeEntry {
584                            worktree: GitWorktree {
585                                path: Default::default(),
586                                ref_name: format!("refs/heads/{query}").into(),
587                                sha: Default::default(),
588                            },
589                            positions: Vec::new(),
590                            is_new: true,
591                        })
592                    }
593                    let delegate = &mut picker.delegate;
594                    delegate.matches = matches;
595                    if delegate.matches.is_empty() {
596                        delegate.selected_index = 0;
597                    } else {
598                        delegate.selected_index =
599                            core::cmp::min(delegate.selected_index, delegate.matches.len() - 1);
600                    }
601                    delegate.last_query = query;
602                })
603                .log_err();
604        })
605    }
606
607    fn confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
608        let Some(entry) = self.matches.get(self.selected_index()) else {
609            return;
610        };
611        if entry.is_new {
612            self.create_worktree(&entry.worktree.branch(), secondary, None, window, cx);
613        } else {
614            self.open_worktree(&entry.worktree.path, secondary, window, cx);
615        }
616
617        cx.emit(DismissEvent);
618    }
619
620    fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<Self>>) {
621        cx.emit(DismissEvent);
622    }
623
624    fn render_match(
625        &self,
626        ix: usize,
627        selected: bool,
628        _window: &mut Window,
629        cx: &mut Context<Picker<Self>>,
630    ) -> Option<Self::ListItem> {
631        let entry = &self.matches.get(ix)?;
632        let path = entry.worktree.path.to_string_lossy().to_string();
633        let sha = entry
634            .worktree
635            .sha
636            .clone()
637            .chars()
638            .take(7)
639            .collect::<String>();
640
641        let focus_handle = self.focus_handle.clone();
642        let icon = if let Some(default_branch) = self.default_branch.clone()
643            && entry.is_new
644        {
645            Some(
646                IconButton::new("worktree-from-default", IconName::GitBranchAlt)
647                    .on_click(|_, window, cx| {
648                        window.dispatch_action(WorktreeFromDefault.boxed_clone(), cx)
649                    })
650                    .on_right_click(|_, window, cx| {
651                        window.dispatch_action(WorktreeFromDefaultOnWindow.boxed_clone(), cx)
652                    })
653                    .tooltip(move |_, cx| {
654                        Tooltip::for_action_in(
655                            format!("From default branch {default_branch}"),
656                            &WorktreeFromDefault,
657                            &focus_handle,
658                            cx,
659                        )
660                    }),
661            )
662        } else {
663            None
664        };
665
666        let branch_name = if entry.is_new {
667            h_flex()
668                .gap_1()
669                .child(
670                    Icon::new(IconName::Plus)
671                        .size(IconSize::Small)
672                        .color(Color::Muted),
673                )
674                .child(
675                    Label::new(format!("Create worktree \"{}\"", entry.worktree.branch()))
676                        .single_line()
677                        .truncate(),
678                )
679                .into_any_element()
680        } else {
681            h_flex()
682                .gap_1()
683                .child(
684                    Icon::new(IconName::GitBranch)
685                        .size(IconSize::Small)
686                        .color(Color::Muted),
687                )
688                .child(HighlightedLabel::new(
689                    entry.worktree.branch().to_owned(),
690                    entry.positions.clone(),
691                ))
692                .truncate()
693                .into_any_element()
694        };
695
696        let sublabel = if entry.is_new {
697            format!(
698                "based off {}",
699                self.base_branch(cx).unwrap_or("the current branch")
700            )
701        } else {
702            format!("at {}", path)
703        };
704
705        Some(
706            ListItem::new(format!("worktree-menu-{ix}"))
707                .inset(true)
708                .spacing(ListItemSpacing::Sparse)
709                .toggle_state(selected)
710                .child(
711                    v_flex()
712                        .w_full()
713                        .overflow_hidden()
714                        .child(
715                            h_flex()
716                                .gap_6()
717                                .justify_between()
718                                .overflow_x_hidden()
719                                .child(branch_name)
720                                .when(!entry.is_new, |el| {
721                                    el.child(
722                                        Label::new(sha)
723                                            .size(LabelSize::Small)
724                                            .color(Color::Muted)
725                                            .into_element(),
726                                    )
727                                }),
728                        )
729                        .child(
730                            div().max_w_96().child(
731                                Label::new(sublabel)
732                                    .size(LabelSize::Small)
733                                    .color(Color::Muted)
734                                    .truncate()
735                                    .into_any_element(),
736                            ),
737                        ),
738                )
739                .end_slot::<IconButton>(icon),
740        )
741    }
742
743    fn no_matches_text(&self, _window: &mut Window, _cx: &mut App) -> Option<SharedString> {
744        Some("No worktrees found".into())
745    }
746
747    fn render_footer(&self, _: &mut Window, cx: &mut Context<Picker<Self>>) -> Option<AnyElement> {
748        let focus_handle = self.focus_handle.clone();
749
750        Some(
751            h_flex()
752                .w_full()
753                .p_1p5()
754                .gap_0p5()
755                .justify_end()
756                .border_t_1()
757                .border_color(cx.theme().colors().border_variant)
758                .child(
759                    Button::new("open-in-new-window", "Open in new window")
760                        .key_binding(
761                            KeyBinding::for_action_in(&menu::Confirm, &focus_handle, cx)
762                                .map(|kb| kb.size(rems_from_px(12.))),
763                        )
764                        .on_click(|_, window, cx| {
765                            window.dispatch_action(menu::Confirm.boxed_clone(), cx)
766                        }),
767                )
768                .child(
769                    Button::new("open-in-window", "Open")
770                        .key_binding(
771                            KeyBinding::for_action_in(&menu::SecondaryConfirm, &focus_handle, cx)
772                                .map(|kb| kb.size(rems_from_px(12.))),
773                        )
774                        .on_click(|_, window, cx| {
775                            window.dispatch_action(menu::SecondaryConfirm.boxed_clone(), cx)
776                        }),
777                )
778                .into_any(),
779        )
780    }
781}