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