branch_picker.rs

  1use anyhow::Context as _;
  2use fuzzy::StringMatchCandidate;
  3
  4use collections::HashSet;
  5use git::repository::Branch;
  6use gpui::{
  7    App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, InteractiveElement,
  8    IntoElement, Modifiers, ModifiersChangedEvent, ParentElement, Render, SharedString, Styled,
  9    Subscription, Task, Window, rems,
 10};
 11use picker::{Picker, PickerDelegate, PickerEditorPosition};
 12use project::git_store::Repository;
 13use std::sync::Arc;
 14use time::OffsetDateTime;
 15use time_format::format_local_timestamp;
 16use ui::{HighlightedLabel, ListItem, ListItemSpacing, Tooltip, prelude::*};
 17use util::ResultExt;
 18use workspace::notifications::DetachAndPromptErr;
 19use workspace::{ModalView, Workspace};
 20
 21pub fn register(workspace: &mut Workspace) {
 22    workspace.register_action(open);
 23    workspace.register_action(switch);
 24    workspace.register_action(checkout_branch);
 25}
 26
 27pub fn checkout_branch(
 28    workspace: &mut Workspace,
 29    _: &zed_actions::git::CheckoutBranch,
 30    window: &mut Window,
 31    cx: &mut Context<Workspace>,
 32) {
 33    open(workspace, &zed_actions::git::Branch, window, cx);
 34}
 35
 36pub fn switch(
 37    workspace: &mut Workspace,
 38    _: &zed_actions::git::Switch,
 39    window: &mut Window,
 40    cx: &mut Context<Workspace>,
 41) {
 42    open(workspace, &zed_actions::git::Branch, window, cx);
 43}
 44
 45pub fn open(
 46    workspace: &mut Workspace,
 47    _: &zed_actions::git::Branch,
 48    window: &mut Window,
 49    cx: &mut Context<Workspace>,
 50) {
 51    let repository = workspace.project().read(cx).active_repository(cx);
 52    let style = BranchListStyle::Modal;
 53    workspace.toggle_modal(window, cx, |window, cx| {
 54        BranchList::new(repository, style, rems(34.), window, cx)
 55    })
 56}
 57
 58pub fn popover(
 59    repository: Option<Entity<Repository>>,
 60    window: &mut Window,
 61    cx: &mut App,
 62) -> Entity<BranchList> {
 63    cx.new(|cx| {
 64        let list = BranchList::new(repository, BranchListStyle::Popover, rems(20.), window, cx);
 65        list.focus_handle(cx).focus(window);
 66        list
 67    })
 68}
 69
 70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
 71enum BranchListStyle {
 72    Modal,
 73    Popover,
 74}
 75
 76pub struct BranchList {
 77    width: Rems,
 78    pub picker: Entity<Picker<BranchListDelegate>>,
 79    _subscription: Subscription,
 80}
 81
 82impl BranchList {
 83    fn new(
 84        repository: Option<Entity<Repository>>,
 85        style: BranchListStyle,
 86        width: Rems,
 87        window: &mut Window,
 88        cx: &mut Context<Self>,
 89    ) -> Self {
 90        let all_branches_request = repository
 91            .clone()
 92            .map(|repository| repository.update(cx, |repository, _| repository.branches()));
 93        let default_branch_request = repository
 94            .clone()
 95            .map(|repository| repository.update(cx, |repository, _| repository.default_branch()));
 96
 97        cx.spawn_in(window, async move |this, cx| {
 98            let mut all_branches = all_branches_request
 99                .context("No active repository")?
100                .await??;
101            let default_branch = default_branch_request
102                .context("No active repository")?
103                .await
104                .map(Result::ok)
105                .ok()
106                .flatten()
107                .flatten();
108
109            let all_branches = cx
110                .background_spawn(async move {
111                    let remote_upstreams: HashSet<_> = all_branches
112                        .iter()
113                        .filter_map(|branch| {
114                            branch
115                                .upstream
116                                .as_ref()
117                                .filter(|upstream| upstream.is_remote())
118                                .map(|upstream| upstream.ref_name.clone())
119                        })
120                        .collect();
121
122                    all_branches.retain(|branch| !remote_upstreams.contains(&branch.ref_name));
123
124                    all_branches.sort_by_key(|branch| {
125                        branch
126                            .most_recent_commit
127                            .as_ref()
128                            .map(|commit| 0 - commit.commit_timestamp)
129                    });
130
131                    all_branches
132                })
133                .await;
134
135            this.update_in(cx, |this, window, cx| {
136                this.picker.update(cx, |picker, cx| {
137                    picker.delegate.default_branch = default_branch;
138                    picker.delegate.all_branches = Some(all_branches);
139                    picker.refresh(window, cx);
140                })
141            })?;
142
143            anyhow::Ok(())
144        })
145        .detach_and_log_err(cx);
146
147        let delegate = BranchListDelegate::new(repository, style);
148        let picker = cx.new(|cx| Picker::uniform_list(delegate, window, cx));
149
150        let _subscription = cx.subscribe(&picker, |_, _, _, cx| {
151            cx.emit(DismissEvent);
152        });
153
154        Self {
155            picker,
156            width,
157            _subscription,
158        }
159    }
160
161    fn handle_modifiers_changed(
162        &mut self,
163        ev: &ModifiersChangedEvent,
164        _: &mut Window,
165        cx: &mut Context<Self>,
166    ) {
167        self.picker
168            .update(cx, |picker, _| picker.delegate.modifiers = ev.modifiers)
169    }
170}
171impl ModalView for BranchList {}
172impl EventEmitter<DismissEvent> for BranchList {}
173
174impl Focusable for BranchList {
175    fn focus_handle(&self, cx: &App) -> FocusHandle {
176        self.picker.focus_handle(cx)
177    }
178}
179
180impl Render for BranchList {
181    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
182        v_flex()
183            .key_context("GitBranchSelector")
184            .w(self.width)
185            .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
186            .child(self.picker.clone())
187            .on_mouse_down_out({
188                cx.listener(move |this, _, window, cx| {
189                    this.picker.update(cx, |this, cx| {
190                        this.cancel(&Default::default(), window, cx);
191                    })
192                })
193            })
194    }
195}
196
197#[derive(Debug, Clone)]
198struct BranchEntry {
199    branch: Branch,
200    positions: Vec<usize>,
201    is_new: bool,
202}
203
204pub struct BranchListDelegate {
205    matches: Vec<BranchEntry>,
206    all_branches: Option<Vec<Branch>>,
207    default_branch: Option<SharedString>,
208    repo: Option<Entity<Repository>>,
209    style: BranchListStyle,
210    selected_index: usize,
211    last_query: String,
212    modifiers: Modifiers,
213}
214
215impl BranchListDelegate {
216    fn new(repo: Option<Entity<Repository>>, style: BranchListStyle) -> Self {
217        Self {
218            matches: vec![],
219            repo,
220            style,
221            all_branches: None,
222            default_branch: None,
223            selected_index: 0,
224            last_query: Default::default(),
225            modifiers: Default::default(),
226        }
227    }
228
229    fn create_branch(
230        &self,
231        from_branch: Option<SharedString>,
232        new_branch_name: SharedString,
233        window: &mut Window,
234        cx: &mut Context<Picker<Self>>,
235    ) {
236        let Some(repo) = self.repo.clone() else {
237            return;
238        };
239        let new_branch_name = new_branch_name.to_string().replace(' ', "-");
240        cx.spawn(async move |_, cx| {
241            if let Some(based_branch) = from_branch {
242                repo.update(cx, |repo, _| repo.change_branch(based_branch.to_string()))?
243                    .await??;
244            }
245
246            repo.update(cx, |repo, _| {
247                repo.create_branch(new_branch_name.to_string())
248            })?
249            .await??;
250            repo.update(cx, |repo, _| {
251                repo.change_branch(new_branch_name.to_string())
252            })?
253            .await??;
254
255            Ok(())
256        })
257        .detach_and_prompt_err("Failed to create branch", window, cx, |e, _, _| {
258            Some(e.to_string())
259        });
260        cx.emit(DismissEvent);
261    }
262}
263
264impl PickerDelegate for BranchListDelegate {
265    type ListItem = ListItem;
266
267    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
268        "Select branch…".into()
269    }
270
271    fn editor_position(&self) -> PickerEditorPosition {
272        match self.style {
273            BranchListStyle::Modal => PickerEditorPosition::Start,
274            BranchListStyle::Popover => PickerEditorPosition::End,
275        }
276    }
277
278    fn match_count(&self) -> usize {
279        self.matches.len()
280    }
281
282    fn selected_index(&self) -> usize {
283        self.selected_index
284    }
285
286    fn set_selected_index(
287        &mut self,
288        ix: usize,
289        _window: &mut Window,
290        _: &mut Context<Picker<Self>>,
291    ) {
292        self.selected_index = ix;
293    }
294
295    fn update_matches(
296        &mut self,
297        query: String,
298        window: &mut Window,
299        cx: &mut Context<Picker<Self>>,
300    ) -> Task<()> {
301        let Some(all_branches) = self.all_branches.clone() else {
302            return Task::ready(());
303        };
304
305        const RECENT_BRANCHES_COUNT: usize = 10;
306        cx.spawn_in(window, async move |picker, cx| {
307            let mut matches: Vec<BranchEntry> = if query.is_empty() {
308                all_branches
309                    .into_iter()
310                    .filter(|branch| !branch.is_remote())
311                    .take(RECENT_BRANCHES_COUNT)
312                    .map(|branch| BranchEntry {
313                        branch,
314                        positions: Vec::new(),
315                        is_new: false,
316                    })
317                    .collect()
318            } else {
319                let candidates = all_branches
320                    .iter()
321                    .enumerate()
322                    .map(|(ix, branch)| StringMatchCandidate::new(ix, branch.name()))
323                    .collect::<Vec<StringMatchCandidate>>();
324                fuzzy::match_strings(
325                    &candidates,
326                    &query,
327                    true,
328                    true,
329                    10000,
330                    &Default::default(),
331                    cx.background_executor().clone(),
332                )
333                .await
334                .into_iter()
335                .map(|candidate| BranchEntry {
336                    branch: all_branches[candidate.candidate_id].clone(),
337                    positions: candidate.positions,
338                    is_new: false,
339                })
340                .collect()
341            };
342            picker
343                .update(cx, |picker, _| {
344                    if !query.is_empty()
345                        && !matches
346                            .first()
347                            .is_some_and(|entry| entry.branch.name() == query)
348                    {
349                        let query = query.replace(' ', "-");
350                        matches.push(BranchEntry {
351                            branch: Branch {
352                                ref_name: format!("refs/heads/{query}").into(),
353                                is_head: false,
354                                upstream: None,
355                                most_recent_commit: None,
356                            },
357                            positions: Vec::new(),
358                            is_new: true,
359                        })
360                    }
361                    let delegate = &mut picker.delegate;
362                    delegate.matches = matches;
363                    if delegate.matches.is_empty() {
364                        delegate.selected_index = 0;
365                    } else {
366                        delegate.selected_index =
367                            core::cmp::min(delegate.selected_index, delegate.matches.len() - 1);
368                    }
369                    delegate.last_query = query;
370                })
371                .log_err();
372        })
373    }
374
375    fn confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
376        let Some(entry) = self.matches.get(self.selected_index()) else {
377            return;
378        };
379        if entry.is_new {
380            let from_branch = if secondary {
381                self.default_branch.clone()
382            } else {
383                None
384            };
385            self.create_branch(
386                from_branch,
387                entry.branch.name().to_owned().into(),
388                window,
389                cx,
390            );
391            return;
392        }
393
394        let current_branch = self.repo.as_ref().map(|repo| {
395            repo.read_with(cx, |repo, _| {
396                repo.branch.as_ref().map(|branch| branch.ref_name.clone())
397            })
398        });
399
400        if current_branch
401            .flatten()
402            .is_some_and(|current_branch| current_branch == entry.branch.ref_name)
403        {
404            cx.emit(DismissEvent);
405            return;
406        }
407
408        cx.spawn_in(window, {
409            let branch = entry.branch.clone();
410            async move |picker, cx| {
411                let branch_change_task = picker.update(cx, |this, cx| {
412                    let repo = this
413                        .delegate
414                        .repo
415                        .as_ref()
416                        .context("No active repository")?
417                        .clone();
418
419                    let mut cx = cx.to_async();
420
421                    anyhow::Ok(async move {
422                        repo.update(&mut cx, |repo, _| {
423                            repo.change_branch(branch.name().to_string())
424                        })?
425                        .await?
426                    })
427                })??;
428
429                branch_change_task.await?;
430
431                picker.update(cx, |_, cx| {
432                    cx.emit(DismissEvent);
433
434                    anyhow::Ok(())
435                })
436            }
437        })
438        .detach_and_prompt_err("Failed to change branch", window, cx, |_, _, _| None);
439    }
440
441    fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<Self>>) {
442        cx.emit(DismissEvent);
443    }
444
445    fn render_match(
446        &self,
447        ix: usize,
448        selected: bool,
449        _window: &mut Window,
450        cx: &mut Context<Picker<Self>>,
451    ) -> Option<Self::ListItem> {
452        let entry = &self.matches[ix];
453
454        let (commit_time, subject) = entry
455            .branch
456            .most_recent_commit
457            .as_ref()
458            .map(|commit| {
459                let subject = commit.subject.clone();
460                let commit_time = OffsetDateTime::from_unix_timestamp(commit.commit_timestamp)
461                    .unwrap_or_else(|_| OffsetDateTime::now_utc());
462                let formatted_time = format_local_timestamp(
463                    commit_time,
464                    OffsetDateTime::now_utc(),
465                    time_format::TimestampFormat::Relative,
466                );
467                (Some(formatted_time), Some(subject))
468            })
469            .unwrap_or_else(|| (None, None));
470
471        let icon = if let Some(default_branch) = self.default_branch.clone()
472            && entry.is_new
473        {
474            Some(
475                IconButton::new("branch-from-default", IconName::GitBranchAlt)
476                    .on_click(cx.listener(move |this, _, window, cx| {
477                        this.delegate.set_selected_index(ix, window, cx);
478                        this.delegate.confirm(true, window, cx);
479                    }))
480                    .tooltip(move |window, cx| {
481                        Tooltip::for_action(
482                            format!("Create branch based off default: {default_branch}"),
483                            &menu::SecondaryConfirm,
484                            window,
485                            cx,
486                        )
487                    }),
488            )
489        } else {
490            None
491        };
492
493        let branch_name = if entry.is_new {
494            h_flex()
495                .gap_1()
496                .child(
497                    Icon::new(IconName::Plus)
498                        .size(IconSize::Small)
499                        .color(Color::Muted),
500                )
501                .child(
502                    Label::new(format!("Create branch \"{}\"", entry.branch.name()))
503                        .single_line()
504                        .truncate(),
505                )
506                .into_any_element()
507        } else {
508            HighlightedLabel::new(entry.branch.name().to_owned(), entry.positions.clone())
509                .truncate()
510                .into_any_element()
511        };
512
513        Some(
514            ListItem::new(SharedString::from(format!("vcs-menu-{ix}")))
515                .inset(true)
516                .spacing(ListItemSpacing::Sparse)
517                .toggle_state(selected)
518                .child(
519                    v_flex()
520                        .w_full()
521                        .overflow_hidden()
522                        .child(
523                            h_flex()
524                                .gap_6()
525                                .justify_between()
526                                .overflow_x_hidden()
527                                .child(branch_name)
528                                .when_some(commit_time, |label, commit_time| {
529                                    label.child(
530                                        Label::new(commit_time)
531                                            .size(LabelSize::Small)
532                                            .color(Color::Muted)
533                                            .into_element(),
534                                    )
535                                }),
536                        )
537                        .when(self.style == BranchListStyle::Modal, |el| {
538                            el.child(div().max_w_96().child({
539                                let message = if entry.is_new {
540                                    if let Some(current_branch) =
541                                        self.repo.as_ref().and_then(|repo| {
542                                            repo.read(cx).branch.as_ref().map(|b| b.name())
543                                        })
544                                    {
545                                        format!("based off {}", current_branch)
546                                    } else {
547                                        "based off the current branch".to_string()
548                                    }
549                                } else {
550                                    subject.unwrap_or("no commits found".into()).to_string()
551                                };
552                                Label::new(message)
553                                    .size(LabelSize::Small)
554                                    .truncate()
555                                    .color(Color::Muted)
556                            }))
557                        }),
558                )
559                .end_slot::<IconButton>(icon),
560        )
561    }
562
563    fn no_matches_text(&self, _window: &mut Window, _cx: &mut App) -> Option<SharedString> {
564        None
565    }
566}