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