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).clone();
 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.clone(), 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                match repo.update(cx, |repo, _| repo.change_branch(based_branch.to_string()))?.await {
243                    Ok(Ok(_)) => {}
244                    Ok(Err(error)) => return Err(error),
245                    Err(_) => return Err(anyhow::anyhow!("Operation was canceled")),
246                }
247            }
248            
249            match repo.update(cx, |repo, _| repo.create_branch(new_branch_name.clone()))?.await {
250                Ok(Ok(_)) => {}
251                Ok(Err(error)) => return Err(error),
252                Err(_) => return Err(anyhow::anyhow!("Operation was canceled")),
253            }
254            
255            match repo.update(cx, |repo, _| repo.change_branch(new_branch_name))?.await {
256                Ok(Ok(_)) => {}
257                Ok(Err(error)) => return Err(error),
258                Err(_) => return Err(anyhow::anyhow!("Operation was canceled")),
259            }
260
261            Ok(())
262        })
263        .detach_and_prompt_err("Failed to create branch", window, cx, |_, _, _| None);
264    }
265}
266
267impl PickerDelegate for BranchListDelegate {
268    type ListItem = ListItem;
269
270    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
271        "Select branch…".into()
272    }
273
274    fn editor_position(&self) -> PickerEditorPosition {
275        match self.style {
276            BranchListStyle::Modal => PickerEditorPosition::Start,
277            BranchListStyle::Popover => PickerEditorPosition::End,
278        }
279    }
280
281    fn match_count(&self) -> usize {
282        self.matches.len()
283    }
284
285    fn selected_index(&self) -> usize {
286        self.selected_index
287    }
288
289    fn set_selected_index(
290        &mut self,
291        ix: usize,
292        _window: &mut Window,
293        _: &mut Context<Picker<Self>>,
294    ) {
295        self.selected_index = ix;
296    }
297
298    fn update_matches(
299        &mut self,
300        query: String,
301        window: &mut Window,
302        cx: &mut Context<Picker<Self>>,
303    ) -> Task<()> {
304        let Some(all_branches) = self.all_branches.clone() else {
305            return Task::ready(());
306        };
307
308        const RECENT_BRANCHES_COUNT: usize = 10;
309        cx.spawn_in(window, async move |picker, cx| {
310            let mut matches: Vec<BranchEntry> = if query.is_empty() {
311                all_branches
312                    .into_iter()
313                    .filter(|branch| !branch.is_remote())
314                    .take(RECENT_BRANCHES_COUNT)
315                    .map(|branch| BranchEntry {
316                        branch,
317                        positions: Vec::new(),
318                        is_new: false,
319                    })
320                    .collect()
321            } else {
322                let candidates = all_branches
323                    .iter()
324                    .enumerate()
325                    .map(|(ix, branch)| StringMatchCandidate::new(ix, branch.name()))
326                    .collect::<Vec<StringMatchCandidate>>();
327                fuzzy::match_strings(
328                    &candidates,
329                    &query,
330                    true,
331                    true,
332                    10000,
333                    &Default::default(),
334                    cx.background_executor().clone(),
335                )
336                .await
337                .into_iter()
338                .map(|candidate| BranchEntry {
339                    branch: all_branches[candidate.candidate_id].clone(),
340                    positions: candidate.positions,
341                    is_new: false,
342                })
343                .collect()
344            };
345            picker
346                .update(cx, |picker, _| {
347                    #[allow(clippy::nonminimal_bool)]
348                    if !query.is_empty()
349                        && !matches
350                            .first()
351                            .is_some_and(|entry| entry.branch.name() == query)
352                    {
353                        let query = query.replace(' ', "-");
354                        matches.push(BranchEntry {
355                            branch: Branch {
356                                ref_name: format!("refs/heads/{query}").into(),
357                                is_head: false,
358                                upstream: None,
359                                most_recent_commit: None,
360                            },
361                            positions: Vec::new(),
362                            is_new: true,
363                        })
364                    }
365                    let delegate = &mut picker.delegate;
366                    delegate.matches = matches;
367                    if delegate.matches.is_empty() {
368                        delegate.selected_index = 0;
369                    } else {
370                        delegate.selected_index =
371                            core::cmp::min(delegate.selected_index, delegate.matches.len() - 1);
372                    }
373                    delegate.last_query = query;
374                })
375                .log_err();
376        })
377    }
378
379    fn confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
380        let Some(entry) = self.matches.get(self.selected_index()) else {
381            return;
382        };
383        if entry.is_new {
384            let from_branch = if secondary {
385                self.default_branch.clone()
386            } else {
387                None
388            };
389            self.create_branch(
390                from_branch,
391                entry.branch.name().to_owned().into(),
392                window,
393                cx,
394            );
395            return;
396        }
397
398        let current_branch = self.repo.as_ref().map(|repo| {
399            repo.read_with(cx, |repo, _| {
400                repo.branch.as_ref().map(|branch| branch.ref_name.clone())
401            })
402        });
403
404        if current_branch
405            .flatten()
406            .is_some_and(|current_branch| current_branch == entry.branch.ref_name)
407        {
408            cx.emit(DismissEvent);
409            return;
410        }
411
412        cx.spawn_in(window, {
413            let branch = entry.branch.clone();
414            async move |picker, cx| {
415                let branch_name = branch.name().to_string();
416
417                let branch_change_task = picker.update(cx, |this, cx| {
418                    let repo = this
419                        .delegate
420                        .repo
421                        .as_ref()
422                        .context("No active repository")?
423                        .clone();
424
425                    let mut cx = cx.to_async();
426
427                    anyhow::Ok(async move {
428                        repo.update(&mut cx, |repo, _| repo.change_branch(branch_name))?
429                            .await?
430                    })
431                })??;
432
433                match branch_change_task.await {
434                    Ok(_) => {
435                        let _ = picker.update(cx, |_, cx| {
436                            cx.emit(DismissEvent);
437                            anyhow::Ok(())
438                        })?;
439                    }
440                    Err(error) => {
441                        let _ = picker.update(cx, |_, cx| {
442                            cx.emit(DismissEvent);
443                            anyhow::Ok(())
444                        })?;
445                        return Err(error);
446                    }
447                }
448
449                anyhow::Ok(())
450            }
451        })
452        .detach_and_prompt_err("Failed to switch branch", window, cx, |_, _, _| None);
453    }
454
455    fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<Self>>) {
456        cx.emit(DismissEvent);
457    }
458
459    fn render_match(
460        &self,
461        ix: usize,
462        selected: bool,
463        _window: &mut Window,
464        cx: &mut Context<Picker<Self>>,
465    ) -> Option<Self::ListItem> {
466        let entry = &self.matches[ix];
467
468        let (commit_time, subject) = entry
469            .branch
470            .most_recent_commit
471            .as_ref()
472            .map(|commit| {
473                let subject = commit.subject.clone();
474                let commit_time = OffsetDateTime::from_unix_timestamp(commit.commit_timestamp)
475                    .unwrap_or_else(|_| OffsetDateTime::now_utc());
476                let formatted_time = format_local_timestamp(
477                    commit_time,
478                    OffsetDateTime::now_utc(),
479                    time_format::TimestampFormat::Relative,
480                );
481                (Some(formatted_time), Some(subject))
482            })
483            .unwrap_or_else(|| (None, None));
484
485        let icon = if let Some(default_branch) = self.default_branch.clone()
486            && entry.is_new
487        {
488            Some(
489                IconButton::new("branch-from-default", IconName::GitBranchAlt)
490                    .on_click(cx.listener(move |this, _, window, cx| {
491                        this.delegate.set_selected_index(ix, window, cx);
492                        this.delegate.confirm(true, window, cx);
493                    }))
494                    .tooltip(move |window, cx| {
495                        Tooltip::for_action(
496                            format!("Create branch based off default: {default_branch}"),
497                            &menu::SecondaryConfirm,
498                            window,
499                            cx,
500                        )
501                    }),
502            )
503        } else {
504            None
505        };
506
507        let branch_name = if entry.is_new {
508            h_flex()
509                .gap_1()
510                .child(
511                    Icon::new(IconName::Plus)
512                        .size(IconSize::Small)
513                        .color(Color::Muted),
514                )
515                .child(
516                    Label::new(format!("Create branch \"{}\"", entry.branch.name()))
517                        .single_line()
518                        .truncate(),
519                )
520                .into_any_element()
521        } else {
522            HighlightedLabel::new(entry.branch.name().to_owned(), entry.positions.clone())
523                .truncate()
524                .into_any_element()
525        };
526
527        Some(
528            ListItem::new(SharedString::from(format!("vcs-menu-{ix}")))
529                .inset(true)
530                .spacing(ListItemSpacing::Sparse)
531                .toggle_state(selected)
532                .child(
533                    v_flex()
534                        .w_full()
535                        .overflow_hidden()
536                        .child(
537                            h_flex()
538                                .gap_6()
539                                .justify_between()
540                                .overflow_x_hidden()
541                                .child(branch_name)
542                                .when_some(commit_time, |label, commit_time| {
543                                    label.child(
544                                        Label::new(commit_time)
545                                            .size(LabelSize::Small)
546                                            .color(Color::Muted)
547                                            .into_element(),
548                                    )
549                                }),
550                        )
551                        .when(self.style == BranchListStyle::Modal, |el| {
552                            el.child(div().max_w_96().child({
553                                let message = if entry.is_new {
554                                    if let Some(current_branch) =
555                                        self.repo.as_ref().and_then(|repo| {
556                                            repo.read(cx).branch.as_ref().map(|b| b.name())
557                                        })
558                                    {
559                                        format!("based off {}", current_branch)
560                                    } else {
561                                        "based off the current branch".to_string()
562                                    }
563                                } else {
564                                    subject.unwrap_or("no commits found".into()).to_string()
565                                };
566                                Label::new(message)
567                                    .size(LabelSize::Small)
568                                    .truncate()
569                                    .color(Color::Muted)
570                            }))
571                        }),
572                )
573                .end_slot::<IconButton>(icon),
574        )
575    }
576
577    fn no_matches_text(&self, _window: &mut Window, _cx: &mut App) -> Option<SharedString> {
578        None
579    }
580}