branch_picker.rs

   1use anyhow::Context as _;
   2use editor::Editor;
   3use fuzzy::StringMatchCandidate;
   4
   5use collections::HashSet;
   6use git::repository::Branch;
   7use gpui::http_client::Url;
   8use gpui::{
   9    Action, App, AsyncApp, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
  10    InteractiveElement, IntoElement, Modifiers, ModifiersChangedEvent, ParentElement, Render,
  11    SharedString, Styled, Subscription, Task, WeakEntity, Window, actions, rems,
  12};
  13use picker::{Picker, PickerDelegate, PickerEditorPosition};
  14use project::git_store::Repository;
  15use project::project_settings::ProjectSettings;
  16use settings::Settings;
  17use std::sync::Arc;
  18use time::OffsetDateTime;
  19use ui::{
  20    CommonAnimationExt, Divider, HighlightedLabel, KeyBinding, ListItem, ListItemSpacing, Tooltip,
  21    prelude::*,
  22};
  23use util::ResultExt;
  24use workspace::notifications::DetachAndPromptErr;
  25use workspace::{ModalView, Workspace};
  26
  27use crate::{branch_picker, git_panel::show_error_toast};
  28
  29actions!(
  30    branch_picker,
  31    [
  32        /// Deletes the selected git branch or remote.
  33        DeleteBranch,
  34        /// Filter the list of remotes
  35        FilterRemotes
  36    ]
  37);
  38
  39pub fn register(workspace: &mut Workspace) {
  40    workspace.register_action(|workspace, branch: &zed_actions::git::Branch, window, cx| {
  41        open(workspace, branch, window, cx);
  42    });
  43    workspace.register_action(switch);
  44    workspace.register_action(checkout_branch);
  45}
  46
  47pub fn checkout_branch(
  48    workspace: &mut Workspace,
  49    _: &zed_actions::git::CheckoutBranch,
  50    window: &mut Window,
  51    cx: &mut Context<Workspace>,
  52) {
  53    open(workspace, &zed_actions::git::Branch, window, cx);
  54}
  55
  56pub fn switch(
  57    workspace: &mut Workspace,
  58    _: &zed_actions::git::Switch,
  59    window: &mut Window,
  60    cx: &mut Context<Workspace>,
  61) {
  62    open(workspace, &zed_actions::git::Branch, window, cx);
  63}
  64
  65pub fn open(
  66    workspace: &mut Workspace,
  67    _: &zed_actions::git::Branch,
  68    window: &mut Window,
  69    cx: &mut Context<Workspace>,
  70) {
  71    let workspace_handle = workspace.weak_handle();
  72    let repository = workspace.project().read(cx).active_repository(cx);
  73    let style = BranchListStyle::Modal;
  74    workspace.toggle_modal(window, cx, |window, cx| {
  75        BranchList::new(
  76            Some(workspace_handle),
  77            repository,
  78            style,
  79            rems(34.),
  80            window,
  81            cx,
  82        )
  83    })
  84}
  85
  86pub fn popover(
  87    repository: Option<Entity<Repository>>,
  88    window: &mut Window,
  89    cx: &mut App,
  90) -> Entity<BranchList> {
  91    cx.new(|cx| {
  92        let list = BranchList::new(
  93            None,
  94            repository,
  95            BranchListStyle::Popover,
  96            rems(20.),
  97            window,
  98            cx,
  99        );
 100        list.focus_handle(cx).focus(window);
 101        list
 102    })
 103}
 104
 105#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
 106enum BranchListStyle {
 107    Modal,
 108    Popover,
 109}
 110
 111pub struct BranchList {
 112    width: Rems,
 113    pub picker: Entity<Picker<BranchListDelegate>>,
 114    picker_focus_handle: FocusHandle,
 115    _subscription: Subscription,
 116}
 117
 118impl BranchList {
 119    fn new(
 120        workspace: Option<WeakEntity<Workspace>>,
 121        repository: Option<Entity<Repository>>,
 122        style: BranchListStyle,
 123        width: Rems,
 124        window: &mut Window,
 125        cx: &mut Context<Self>,
 126    ) -> Self {
 127        let all_branches_request = repository
 128            .clone()
 129            .map(|repository| repository.update(cx, |repository, _| repository.branches()));
 130        let default_branch_request = repository
 131            .clone()
 132            .map(|repository| repository.update(cx, |repository, _| repository.default_branch()));
 133
 134        cx.spawn_in(window, async move |this, cx| {
 135            let mut all_branches = all_branches_request
 136                .context("No active repository")?
 137                .await??;
 138            let default_branch = default_branch_request
 139                .context("No active repository")?
 140                .await
 141                .map(Result::ok)
 142                .ok()
 143                .flatten()
 144                .flatten();
 145
 146            let all_branches = cx
 147                .background_spawn(async move {
 148                    let remote_upstreams: HashSet<_> = all_branches
 149                        .iter()
 150                        .filter_map(|branch| {
 151                            branch
 152                                .upstream
 153                                .as_ref()
 154                                .filter(|upstream| upstream.is_remote())
 155                                .map(|upstream| upstream.ref_name.clone())
 156                        })
 157                        .collect();
 158
 159                    all_branches.retain(|branch| !remote_upstreams.contains(&branch.ref_name));
 160
 161                    all_branches.sort_by_key(|branch| {
 162                        (
 163                            !branch.is_head, // Current branch (is_head=true) comes first
 164                            branch
 165                                .most_recent_commit
 166                                .as_ref()
 167                                .map(|commit| 0 - commit.commit_timestamp),
 168                        )
 169                    });
 170
 171                    all_branches
 172                })
 173                .await;
 174
 175            let _ = this.update_in(cx, |this, window, cx| {
 176                this.picker.update(cx, |picker, cx| {
 177                    picker.delegate.default_branch = default_branch;
 178                    picker.delegate.all_branches = Some(all_branches);
 179                    picker.refresh(window, cx);
 180                })
 181            });
 182
 183            anyhow::Ok(())
 184        })
 185        .detach_and_log_err(cx);
 186
 187        let delegate = BranchListDelegate::new(workspace, repository, style, cx);
 188        let picker = cx.new(|cx| Picker::uniform_list(delegate, window, cx));
 189        let picker_focus_handle = picker.focus_handle(cx);
 190        picker.update(cx, |picker, _| {
 191            picker.delegate.focus_handle = picker_focus_handle.clone();
 192        });
 193
 194        let _subscription = cx.subscribe(&picker, |_, _, _, cx| {
 195            cx.emit(DismissEvent);
 196        });
 197
 198        Self {
 199            picker,
 200            picker_focus_handle,
 201            width,
 202            _subscription,
 203        }
 204    }
 205
 206    fn handle_modifiers_changed(
 207        &mut self,
 208        ev: &ModifiersChangedEvent,
 209        _: &mut Window,
 210        cx: &mut Context<Self>,
 211    ) {
 212        self.picker
 213            .update(cx, |picker, _| picker.delegate.modifiers = ev.modifiers)
 214    }
 215
 216    fn handle_delete(
 217        &mut self,
 218        _: &branch_picker::DeleteBranch,
 219        window: &mut Window,
 220        cx: &mut Context<Self>,
 221    ) {
 222        self.picker.update(cx, |picker, cx| {
 223            picker
 224                .delegate
 225                .delete_at(picker.delegate.selected_index, window, cx)
 226        })
 227    }
 228
 229    fn handle_filter(
 230        &mut self,
 231        _: &branch_picker::FilterRemotes,
 232        window: &mut Window,
 233        cx: &mut Context<Self>,
 234    ) {
 235        self.picker.update(cx, |this, cx| {
 236            this.delegate.display_remotes = !this.delegate.display_remotes;
 237            cx.spawn_in(window, async move |this, cx| {
 238                this.update_in(cx, |picker, window, cx| {
 239                    let last_query = picker.delegate.last_query.clone();
 240                    picker.delegate.update_matches(last_query, window, cx)
 241                })?
 242                .await;
 243
 244                Result::Ok::<_, anyhow::Error>(())
 245            })
 246            .detach_and_log_err(cx);
 247        });
 248
 249        cx.notify();
 250    }
 251}
 252impl ModalView for BranchList {}
 253impl EventEmitter<DismissEvent> for BranchList {}
 254
 255impl Focusable for BranchList {
 256    fn focus_handle(&self, _cx: &App) -> FocusHandle {
 257        self.picker_focus_handle.clone()
 258    }
 259}
 260
 261impl Render for BranchList {
 262    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 263        v_flex()
 264            .key_context("GitBranchSelector")
 265            .w(self.width)
 266            .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
 267            .on_action(cx.listener(Self::handle_delete))
 268            .on_action(cx.listener(Self::handle_filter))
 269            .child(self.picker.clone())
 270            .on_mouse_down_out({
 271                cx.listener(move |this, _, window, cx| {
 272                    this.picker.update(cx, |this, cx| {
 273                        this.cancel(&Default::default(), window, cx);
 274                    })
 275                })
 276            })
 277    }
 278}
 279
 280#[derive(Debug, Clone, PartialEq)]
 281enum Entry {
 282    Branch {
 283        branch: Branch,
 284        positions: Vec<usize>,
 285    },
 286    NewUrl {
 287        url: String,
 288    },
 289    NewBranch {
 290        name: String,
 291    },
 292}
 293
 294impl Entry {
 295    fn as_branch(&self) -> Option<&Branch> {
 296        match self {
 297            Entry::Branch { branch, .. } => Some(branch),
 298            _ => None,
 299        }
 300    }
 301
 302    fn name(&self) -> &str {
 303        match self {
 304            Entry::Branch { branch, .. } => branch.name(),
 305            Entry::NewUrl { url, .. } => url.as_str(),
 306            Entry::NewBranch { name, .. } => name.as_str(),
 307        }
 308    }
 309
 310    #[cfg(test)]
 311    fn is_new_url(&self) -> bool {
 312        matches!(self, Self::NewUrl { .. })
 313    }
 314
 315    #[cfg(test)]
 316    fn is_new_branch(&self) -> bool {
 317        matches!(self, Self::NewBranch { .. })
 318    }
 319}
 320
 321pub struct BranchListDelegate {
 322    workspace: Option<WeakEntity<Workspace>>,
 323    matches: Vec<Entry>,
 324    all_branches: Option<Vec<Branch>>,
 325    default_branch: Option<SharedString>,
 326    repo: Option<Entity<Repository>>,
 327    style: BranchListStyle,
 328    selected_index: usize,
 329    last_query: String,
 330    modifiers: Modifiers,
 331    display_remotes: bool,
 332    state: PickerState,
 333    loading: bool,
 334    focus_handle: FocusHandle,
 335}
 336
 337#[derive(Debug)]
 338enum PickerState {
 339    /// When we display list of branches/remotes
 340    List,
 341    /// When we set an url to create a new remote
 342    NewRemote,
 343    /// When we confirm the new remote url (after NewRemote)
 344    CreateRemote(SharedString),
 345    /// When we set a new branch to create
 346    NewBranch,
 347}
 348
 349impl BranchListDelegate {
 350    fn new(
 351        workspace: Option<WeakEntity<Workspace>>,
 352        repo: Option<Entity<Repository>>,
 353        style: BranchListStyle,
 354        cx: &mut Context<BranchList>,
 355    ) -> Self {
 356        Self {
 357            workspace,
 358            matches: vec![],
 359            repo,
 360            style,
 361            all_branches: None,
 362            default_branch: None,
 363            selected_index: 0,
 364            last_query: Default::default(),
 365            modifiers: Default::default(),
 366            display_remotes: false,
 367            state: PickerState::List,
 368            loading: false,
 369            focus_handle: cx.focus_handle(),
 370        }
 371    }
 372
 373    fn create_branch(
 374        &self,
 375        from_branch: Option<SharedString>,
 376        new_branch_name: SharedString,
 377        window: &mut Window,
 378        cx: &mut Context<Picker<Self>>,
 379    ) {
 380        let Some(repo) = self.repo.clone() else {
 381            return;
 382        };
 383        let new_branch_name = new_branch_name.to_string().replace(' ', "-");
 384        let base_branch = from_branch.map(|b| b.to_string());
 385        cx.spawn(async move |_, cx| {
 386            repo.update(cx, |repo, _| {
 387                repo.create_branch(new_branch_name, base_branch)
 388            })?
 389            .await??;
 390
 391            Ok(())
 392        })
 393        .detach_and_prompt_err("Failed to create branch", window, cx, |e, _, _| {
 394            Some(e.to_string())
 395        });
 396        cx.emit(DismissEvent);
 397    }
 398
 399    fn create_remote(
 400        &self,
 401        remote_name: String,
 402        remote_url: String,
 403        window: &mut Window,
 404        cx: &mut Context<Picker<Self>>,
 405    ) {
 406        let Some(repo) = self.repo.clone() else {
 407            return;
 408        };
 409        cx.spawn(async move |this, cx| {
 410            this.update(cx, |picker, cx| {
 411                picker.delegate.loading = true;
 412                cx.notify();
 413            })
 414            .log_err();
 415
 416            let stop_loader = |this: &WeakEntity<Picker<BranchListDelegate>>, cx: &mut AsyncApp| {
 417                this.update(cx, |picker, cx| {
 418                    picker.delegate.loading = false;
 419                    cx.notify();
 420                })
 421                .log_err();
 422            };
 423            repo.update(cx, |repo, _| repo.create_remote(remote_name, remote_url))
 424                .inspect_err(|_err| {
 425                    stop_loader(&this, cx);
 426                })?
 427                .await
 428                .inspect_err(|_err| {
 429                    stop_loader(&this, cx);
 430                })?
 431                .inspect_err(|_err| {
 432                    stop_loader(&this, cx);
 433                })?;
 434            stop_loader(&this, cx);
 435            Ok(())
 436        })
 437        .detach_and_prompt_err("Failed to create remote", window, cx, |e, _, _cx| {
 438            Some(e.to_string())
 439        });
 440        cx.emit(DismissEvent);
 441    }
 442
 443    fn loader(&self) -> AnyElement {
 444        Icon::new(IconName::LoadCircle)
 445            .size(IconSize::Small)
 446            .with_rotate_animation(3)
 447            .into_any_element()
 448    }
 449
 450    fn delete_at(&self, idx: usize, window: &mut Window, cx: &mut Context<Picker<Self>>) {
 451        let Some(entry) = self.matches.get(idx).cloned() else {
 452            return;
 453        };
 454        let Some(repo) = self.repo.clone() else {
 455            return;
 456        };
 457
 458        let workspace = self.workspace.clone();
 459
 460        cx.spawn_in(window, async move |picker, cx| {
 461            let mut is_remote = false;
 462            let result = match &entry {
 463                Entry::Branch { branch, .. } => match branch.remote_name() {
 464                    Some(remote_name) => {
 465                        is_remote = true;
 466                        repo.update(cx, |repo, _| repo.remove_remote(remote_name.to_string()))?
 467                            .await?
 468                    }
 469                    None => {
 470                        repo.update(cx, |repo, _| repo.delete_branch(branch.name().to_string()))?
 471                            .await?
 472                    }
 473                },
 474                _ => {
 475                    log::error!("Failed to delete remote: wrong entry to delete");
 476                    return Ok(());
 477                }
 478            };
 479
 480            if let Err(e) = result {
 481                if is_remote {
 482                    log::error!("Failed to delete remote: {}", e);
 483                } else {
 484                    log::error!("Failed to delete branch: {}", e);
 485                }
 486
 487                if let Some(workspace) = workspace.and_then(|w| w.upgrade()) {
 488                    cx.update(|_window, cx| {
 489                        if is_remote {
 490                            show_error_toast(
 491                                workspace,
 492                                format!("remote remove {}", entry.name()),
 493                                e,
 494                                cx,
 495                            )
 496                        } else {
 497                            show_error_toast(
 498                                workspace,
 499                                format!("branch -d {}", entry.name()),
 500                                e,
 501                                cx,
 502                            )
 503                        }
 504                    })?;
 505                }
 506
 507                return Ok(());
 508            }
 509
 510            picker.update_in(cx, |picker, _, cx| {
 511                picker.delegate.matches.retain(|e| e != &entry);
 512
 513                if let Entry::Branch { branch, .. } = &entry {
 514                    if let Some(all_branches) = &mut picker.delegate.all_branches {
 515                        all_branches.retain(|e| e.ref_name != branch.ref_name);
 516                    }
 517                }
 518
 519                if picker.delegate.matches.is_empty() {
 520                    picker.delegate.selected_index = 0;
 521                } else if picker.delegate.selected_index >= picker.delegate.matches.len() {
 522                    picker.delegate.selected_index = picker.delegate.matches.len() - 1;
 523                }
 524
 525                cx.notify();
 526            })?;
 527
 528            anyhow::Ok(())
 529        })
 530        .detach();
 531    }
 532}
 533
 534impl PickerDelegate for BranchListDelegate {
 535    type ListItem = ListItem;
 536
 537    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
 538        "Select branch…".into()
 539    }
 540
 541    fn render_editor(
 542        &self,
 543        editor: &Entity<Editor>,
 544        window: &mut Window,
 545        cx: &mut Context<Picker<Self>>,
 546    ) -> Div {
 547        cx.update_entity(editor, move |editor, cx| {
 548            let placeholder = match self.state {
 549                PickerState::List | PickerState::NewRemote | PickerState::NewBranch => {
 550                    if self.display_remotes {
 551                        "Select remote…"
 552                    } else {
 553                        "Select branch…"
 554                    }
 555                }
 556                PickerState::CreateRemote(_) => "Choose a name…",
 557            };
 558            editor.set_placeholder_text(placeholder, window, cx);
 559        });
 560
 561        v_flex()
 562            .when(
 563                self.editor_position() == PickerEditorPosition::End,
 564                |this| this.child(Divider::horizontal()),
 565            )
 566            .child(
 567                h_flex()
 568                    .overflow_hidden()
 569                    .flex_none()
 570                    .h_9()
 571                    .px_2p5()
 572                    .child(editor.clone()),
 573            )
 574            .when(
 575                self.editor_position() == PickerEditorPosition::Start,
 576                |this| this.child(Divider::horizontal()),
 577            )
 578    }
 579
 580    fn editor_position(&self) -> PickerEditorPosition {
 581        match self.style {
 582            BranchListStyle::Modal => PickerEditorPosition::Start,
 583            BranchListStyle::Popover => PickerEditorPosition::End,
 584        }
 585    }
 586
 587    fn match_count(&self) -> usize {
 588        self.matches.len()
 589    }
 590
 591    fn selected_index(&self) -> usize {
 592        self.selected_index
 593    }
 594
 595    fn set_selected_index(
 596        &mut self,
 597        ix: usize,
 598        _window: &mut Window,
 599        _: &mut Context<Picker<Self>>,
 600    ) {
 601        self.selected_index = ix;
 602    }
 603
 604    fn update_matches(
 605        &mut self,
 606        query: String,
 607        window: &mut Window,
 608        cx: &mut Context<Picker<Self>>,
 609    ) -> Task<()> {
 610        let Some(all_branches) = self.all_branches.clone() else {
 611            return Task::ready(());
 612        };
 613
 614        const RECENT_BRANCHES_COUNT: usize = 10;
 615        let display_remotes = self.display_remotes;
 616        cx.spawn_in(window, async move |picker, cx| {
 617            let mut matches: Vec<Entry> = if query.is_empty() {
 618                all_branches
 619                    .into_iter()
 620                    .filter(|branch| {
 621                        if display_remotes {
 622                            branch.is_remote()
 623                        } else {
 624                            !branch.is_remote()
 625                        }
 626                    })
 627                    .take(RECENT_BRANCHES_COUNT)
 628                    .map(|branch| Entry::Branch {
 629                        branch,
 630                        positions: Vec::new(),
 631                    })
 632                    .collect()
 633            } else {
 634                let branches = all_branches
 635                    .iter()
 636                    .filter(|branch| {
 637                        if display_remotes {
 638                            branch.is_remote()
 639                        } else {
 640                            !branch.is_remote()
 641                        }
 642                    })
 643                    .collect::<Vec<_>>();
 644                let candidates = branches
 645                    .iter()
 646                    .enumerate()
 647                    .map(|(ix, branch)| StringMatchCandidate::new(ix, branch.name()))
 648                    .collect::<Vec<StringMatchCandidate>>();
 649                fuzzy::match_strings(
 650                    &candidates,
 651                    &query,
 652                    true,
 653                    true,
 654                    10000,
 655                    &Default::default(),
 656                    cx.background_executor().clone(),
 657                )
 658                .await
 659                .into_iter()
 660                .map(|candidate| Entry::Branch {
 661                    branch: branches[candidate.candidate_id].clone(),
 662                    positions: candidate.positions,
 663                })
 664                .collect()
 665            };
 666            picker
 667                .update(cx, |picker, _| {
 668                    if matches!(picker.delegate.state, PickerState::CreateRemote(_)) {
 669                        picker.delegate.last_query = query;
 670                        picker.delegate.matches = Vec::new();
 671                        picker.delegate.selected_index = 0;
 672
 673                        return;
 674                    }
 675
 676                    if !query.is_empty()
 677                        && !matches.first().is_some_and(|entry| entry.name() == query)
 678                    {
 679                        let query = query.replace(' ', "-");
 680                        let is_url = query.trim_start_matches("git@").parse::<Url>().is_ok();
 681                        let entry = if is_url {
 682                            Entry::NewUrl { url: query }
 683                        } else {
 684                            Entry::NewBranch { name: query }
 685                        };
 686                        picker.delegate.state = if is_url {
 687                            PickerState::NewRemote
 688                        } else {
 689                            PickerState::NewBranch
 690                        };
 691                        matches.push(entry);
 692                    } else {
 693                        picker.delegate.state = PickerState::List;
 694                    }
 695                    let delegate = &mut picker.delegate;
 696                    delegate.matches = matches;
 697                    if delegate.matches.is_empty() {
 698                        delegate.selected_index = 0;
 699                    } else {
 700                        delegate.selected_index =
 701                            core::cmp::min(delegate.selected_index, delegate.matches.len() - 1);
 702                    }
 703                    delegate.last_query = query;
 704                })
 705                .log_err();
 706        })
 707    }
 708
 709    fn confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
 710        if let PickerState::CreateRemote(remote_url) = &self.state {
 711            self.create_remote(self.last_query.clone(), remote_url.to_string(), window, cx);
 712            self.state = PickerState::List;
 713            cx.notify();
 714            return;
 715        }
 716
 717        let Some(entry) = self.matches.get(self.selected_index()) else {
 718            return;
 719        };
 720
 721        match entry {
 722            Entry::Branch { branch, .. } => {
 723                let current_branch = self.repo.as_ref().map(|repo| {
 724                    repo.read_with(cx, |repo, _| {
 725                        repo.branch.as_ref().map(|branch| branch.ref_name.clone())
 726                    })
 727                });
 728
 729                if current_branch
 730                    .flatten()
 731                    .is_some_and(|current_branch| current_branch == branch.ref_name)
 732                {
 733                    cx.emit(DismissEvent);
 734                    return;
 735                }
 736
 737                let Some(repo) = self.repo.clone() else {
 738                    return;
 739                };
 740
 741                let branch = branch.clone();
 742                cx.spawn(async move |_, cx| {
 743                    repo.update(cx, |repo, _| repo.change_branch(branch.name().to_string()))?
 744                        .await??;
 745
 746                    anyhow::Ok(())
 747                })
 748                .detach_and_prompt_err(
 749                    "Failed to change branch",
 750                    window,
 751                    cx,
 752                    |_, _, _| None,
 753                );
 754            }
 755            Entry::NewUrl { url } => {
 756                self.state = PickerState::CreateRemote(url.clone().into());
 757                self.matches = Vec::new();
 758                self.selected_index = 0;
 759                cx.spawn_in(window, async move |this, cx| {
 760                    this.update_in(cx, |picker, window, cx| {
 761                        picker.set_query("", window, cx);
 762                    })
 763                })
 764                .detach_and_log_err(cx);
 765                cx.notify();
 766            }
 767            Entry::NewBranch { name } => {
 768                let from_branch = if secondary {
 769                    self.default_branch.clone()
 770                } else {
 771                    None
 772                };
 773                self.create_branch(from_branch, format!("refs/heads/{name}").into(), window, cx);
 774            }
 775        }
 776
 777        cx.emit(DismissEvent);
 778    }
 779
 780    fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<Self>>) {
 781        self.state = PickerState::List;
 782        cx.emit(DismissEvent);
 783    }
 784
 785    fn render_match(
 786        &self,
 787        ix: usize,
 788        selected: bool,
 789        _window: &mut Window,
 790        cx: &mut Context<Picker<Self>>,
 791    ) -> Option<Self::ListItem> {
 792        let entry = &self.matches.get(ix)?;
 793
 794        let (commit_time, author_name, subject) = entry
 795            .as_branch()
 796            .and_then(|branch| {
 797                branch.most_recent_commit.as_ref().map(|commit| {
 798                    let subject = commit.subject.clone();
 799                    let commit_time = OffsetDateTime::from_unix_timestamp(commit.commit_timestamp)
 800                        .unwrap_or_else(|_| OffsetDateTime::now_utc());
 801                    let local_offset =
 802                        time::UtcOffset::current_local_offset().unwrap_or(time::UtcOffset::UTC);
 803                    let formatted_time = time_format::format_localized_timestamp(
 804                        commit_time,
 805                        OffsetDateTime::now_utc(),
 806                        local_offset,
 807                        time_format::TimestampFormat::Relative,
 808                    );
 809                    let author = commit.author_name.clone();
 810                    (Some(formatted_time), Some(author), Some(subject))
 811                })
 812            })
 813            .unwrap_or_else(|| (None, None, None));
 814
 815        let icon = if let Some(default_branch) = self.default_branch.clone() {
 816            let icon = match &entry {
 817                Entry::Branch { .. } => Some((
 818                    IconName::GitBranchAlt,
 819                    format!("Create branch based off default: {default_branch}"),
 820                )),
 821                Entry::NewUrl { url } => {
 822                    Some((IconName::Screen, format!("Create remote based off {url}")))
 823                }
 824                Entry::NewBranch { .. } => None,
 825            };
 826
 827            icon.map(|(icon, tooltip_text)| {
 828                IconButton::new("branch-from-default", icon)
 829                    .on_click(cx.listener(move |this, _, window, cx| {
 830                        this.delegate.set_selected_index(ix, window, cx);
 831                        this.delegate.confirm(true, window, cx);
 832                    }))
 833                    .tooltip(move |_window, cx| {
 834                        Tooltip::for_action(tooltip_text.clone(), &menu::SecondaryConfirm, cx)
 835                    })
 836            })
 837        } else {
 838            None
 839        };
 840
 841        let icon_element = if self.display_remotes {
 842            Icon::new(IconName::Screen)
 843        } else {
 844            Icon::new(IconName::GitBranchAlt)
 845        };
 846
 847        let entry_name = match entry {
 848            Entry::NewUrl { .. } => h_flex()
 849                .gap_1()
 850                .child(
 851                    Icon::new(IconName::Plus)
 852                        .size(IconSize::Small)
 853                        .color(Color::Muted),
 854                )
 855                .child(
 856                    Label::new("Create remote repository".to_string())
 857                        .single_line()
 858                        .truncate(),
 859                )
 860                .into_any_element(),
 861            Entry::NewBranch { name } => h_flex()
 862                .gap_1()
 863                .child(
 864                    Icon::new(IconName::Plus)
 865                        .size(IconSize::Small)
 866                        .color(Color::Muted),
 867                )
 868                .child(
 869                    Label::new(format!("Create branch \"{name}\""))
 870                        .single_line()
 871                        .truncate(),
 872                )
 873                .into_any_element(),
 874            Entry::Branch { branch, positions } => h_flex()
 875                .max_w_48()
 876                .child(h_flex().mr_1().child(icon_element))
 877                .child(
 878                    HighlightedLabel::new(branch.name().to_string(), positions.clone()).truncate(),
 879                )
 880                .into_any_element(),
 881        };
 882
 883        Some(
 884            ListItem::new(SharedString::from(format!("vcs-menu-{ix}")))
 885                .inset(true)
 886                .spacing(ListItemSpacing::Sparse)
 887                .toggle_state(selected)
 888                .tooltip({
 889                    match entry {
 890                        Entry::Branch { branch, .. } => Tooltip::text(branch.name().to_string()),
 891                        Entry::NewUrl { .. } => {
 892                            Tooltip::text("Create remote repository".to_string())
 893                        }
 894                        Entry::NewBranch { name } => {
 895                            Tooltip::text(format!("Create branch \"{name}\""))
 896                        }
 897                    }
 898                })
 899                .child(
 900                    v_flex()
 901                        .w_full()
 902                        .overflow_hidden()
 903                        .child(
 904                            h_flex()
 905                                .gap_6()
 906                                .justify_between()
 907                                .overflow_x_hidden()
 908                                .child(entry_name)
 909                                .when_some(commit_time, |label, commit_time| {
 910                                    label.child(
 911                                        Label::new(commit_time)
 912                                            .size(LabelSize::Small)
 913                                            .color(Color::Muted)
 914                                            .into_element(),
 915                                    )
 916                                }),
 917                        )
 918                        .when(self.style == BranchListStyle::Modal, |el| {
 919                            el.child(div().max_w_96().child({
 920                                let message = match entry {
 921                                    Entry::NewUrl { url } => format!("based off {url}"),
 922                                    Entry::NewBranch { .. } => {
 923                                        if let Some(current_branch) =
 924                                            self.repo.as_ref().and_then(|repo| {
 925                                                repo.read(cx).branch.as_ref().map(|b| b.name())
 926                                            })
 927                                        {
 928                                            format!("based off {}", current_branch)
 929                                        } else {
 930                                            "based off the current branch".to_string()
 931                                        }
 932                                    }
 933                                    Entry::Branch { .. } => {
 934                                        let show_author_name = ProjectSettings::get_global(cx)
 935                                            .git
 936                                            .branch_picker
 937                                            .show_author_name;
 938
 939                                        subject.map_or("no commits found".into(), |subject| {
 940                                            if show_author_name && author_name.is_some() {
 941                                                format!("{}{}", author_name.unwrap(), subject)
 942                                            } else {
 943                                                subject.to_string()
 944                                            }
 945                                        })
 946                                    }
 947                                };
 948
 949                                Label::new(message)
 950                                    .size(LabelSize::Small)
 951                                    .truncate()
 952                                    .color(Color::Muted)
 953                            }))
 954                        }),
 955                )
 956                .end_slot::<IconButton>(icon),
 957        )
 958    }
 959
 960    fn render_header(
 961        &self,
 962        _window: &mut Window,
 963        cx: &mut Context<Picker<Self>>,
 964    ) -> Option<AnyElement> {
 965        if matches!(
 966            self.state,
 967            PickerState::CreateRemote(_) | PickerState::NewRemote | PickerState::NewBranch
 968        ) {
 969            return None;
 970        }
 971        let label = if self.display_remotes {
 972            "Remote"
 973        } else {
 974            "Local"
 975        };
 976        Some(
 977            h_flex()
 978                .w_full()
 979                .p_1p5()
 980                .gap_1()
 981                .border_t_1()
 982                .border_color(cx.theme().colors().border_variant)
 983                .child(Label::new(label).size(LabelSize::Small).color(Color::Muted))
 984                .into_any(),
 985        )
 986    }
 987
 988    fn render_footer(&self, _: &mut Window, cx: &mut Context<Picker<Self>>) -> Option<AnyElement> {
 989        let focus_handle = self.focus_handle.clone();
 990
 991        if self.loading {
 992            return Some(
 993                h_flex()
 994                    .w_full()
 995                    .p_1p5()
 996                    .gap_1()
 997                    .justify_end()
 998                    .border_t_1()
 999                    .border_color(cx.theme().colors().border_variant)
1000                    .child(self.loader())
1001                    .into_any(),
1002            );
1003        }
1004        match self.state {
1005            PickerState::List => Some(
1006                h_flex()
1007                    .w_full()
1008                    .p_1p5()
1009                    .gap_0p5()
1010                    .border_t_1()
1011                    .border_color(cx.theme().colors().border_variant)
1012                    .justify_between()
1013                    .child(
1014                        Button::new("filter-remotes", "Filter remotes")
1015                            .key_binding(
1016                                KeyBinding::for_action_in(
1017                                    &branch_picker::FilterRemotes,
1018                                    &focus_handle,
1019                                    cx,
1020                                )
1021                                .map(|kb| kb.size(rems_from_px(12.))),
1022                            )
1023                            .on_click(|_click, window, cx| {
1024                                window.dispatch_action(
1025                                    branch_picker::FilterRemotes.boxed_clone(),
1026                                    cx,
1027                                );
1028                            })
1029                            .disabled(self.loading)
1030                            .style(ButtonStyle::Subtle)
1031                            .toggle_state(self.display_remotes),
1032                    )
1033                    .child(
1034                        Button::new("delete-branch", "Delete")
1035                            .key_binding(
1036                                KeyBinding::for_action_in(
1037                                    &branch_picker::DeleteBranch,
1038                                    &focus_handle,
1039                                    cx,
1040                                )
1041                                .map(|kb| kb.size(rems_from_px(12.))),
1042                            )
1043                            .disabled(self.loading)
1044                            .on_click(|_, window, cx| {
1045                                window
1046                                    .dispatch_action(branch_picker::DeleteBranch.boxed_clone(), cx);
1047                            }),
1048                    )
1049                    .when(self.loading, |this| this.child(self.loader()))
1050                    .into_any(),
1051            ),
1052            PickerState::CreateRemote(_) => Some(
1053                h_flex()
1054                    .w_full()
1055                    .p_1p5()
1056                    .gap_1()
1057                    .border_t_1()
1058                    .border_color(cx.theme().colors().border_variant)
1059                    .child(
1060                        Label::new("Choose a name for this remote repository")
1061                            .size(LabelSize::Small)
1062                            .color(Color::Muted),
1063                    )
1064                    .child(
1065                        h_flex().w_full().justify_end().child(
1066                            Label::new("Save")
1067                                .size(LabelSize::Small)
1068                                .color(Color::Muted),
1069                        ),
1070                    )
1071                    .into_any(),
1072            ),
1073            PickerState::NewRemote | PickerState::NewBranch => None,
1074        }
1075    }
1076
1077    fn no_matches_text(&self, _window: &mut Window, _cx: &mut App) -> Option<SharedString> {
1078        None
1079    }
1080}
1081
1082#[cfg(test)]
1083mod tests {
1084    use std::collections::HashSet;
1085
1086    use super::*;
1087    use git::repository::{CommitSummary, Remote};
1088    use gpui::{TestAppContext, VisualTestContext};
1089    use project::{FakeFs, Project};
1090    use serde_json::json;
1091    use settings::SettingsStore;
1092    use util::path;
1093
1094    fn init_test(cx: &mut TestAppContext) {
1095        cx.update(|cx| {
1096            let settings_store = SettingsStore::test(cx);
1097            cx.set_global(settings_store);
1098            theme::init(theme::LoadThemes::JustBase, cx);
1099        });
1100    }
1101
1102    fn create_test_branch(
1103        name: &str,
1104        is_head: bool,
1105        remote_name: Option<&str>,
1106        timestamp: Option<i64>,
1107    ) -> Branch {
1108        let ref_name = match remote_name {
1109            Some(remote_name) => format!("refs/remotes/{remote_name}/{name}"),
1110            None => format!("refs/heads/{name}"),
1111        };
1112
1113        Branch {
1114            is_head,
1115            ref_name: ref_name.into(),
1116            upstream: None,
1117            most_recent_commit: timestamp.map(|ts| CommitSummary {
1118                sha: "abc123".into(),
1119                commit_timestamp: ts,
1120                author_name: "Test Author".into(),
1121                subject: "Test commit".into(),
1122                has_parent: true,
1123            }),
1124        }
1125    }
1126
1127    fn create_test_branches() -> Vec<Branch> {
1128        vec![
1129            create_test_branch("main", true, None, Some(1000)),
1130            create_test_branch("feature-auth", false, None, Some(900)),
1131            create_test_branch("feature-ui", false, None, Some(800)),
1132            create_test_branch("develop", false, None, Some(700)),
1133        ]
1134    }
1135
1136    fn init_branch_list_test(
1137        cx: &mut TestAppContext,
1138        repository: Option<Entity<Repository>>,
1139        branches: Vec<Branch>,
1140    ) -> (VisualTestContext, Entity<BranchList>) {
1141        let window = cx.add_window(|window, cx| {
1142            let mut delegate =
1143                BranchListDelegate::new(None, repository, BranchListStyle::Modal, cx);
1144            delegate.all_branches = Some(branches);
1145            let picker = cx.new(|cx| Picker::uniform_list(delegate, window, cx));
1146            let picker_focus_handle = picker.focus_handle(cx);
1147            picker.update(cx, |picker, _| {
1148                picker.delegate.focus_handle = picker_focus_handle.clone();
1149            });
1150
1151            let _subscription = cx.subscribe(&picker, |_, _, _, cx| {
1152                cx.emit(DismissEvent);
1153            });
1154
1155            BranchList {
1156                picker,
1157                picker_focus_handle,
1158                width: rems(34.),
1159                _subscription,
1160            }
1161        });
1162
1163        let branch_list = window.root(cx).unwrap();
1164        let cx = VisualTestContext::from_window(*window, cx);
1165
1166        (cx, branch_list)
1167    }
1168
1169    async fn init_fake_repository(cx: &mut TestAppContext) -> Entity<Repository> {
1170        let fs = FakeFs::new(cx.executor());
1171        fs.insert_tree(
1172            path!("/dir"),
1173            json!({
1174                ".git": {},
1175                "file.txt": "buffer_text".to_string()
1176            }),
1177        )
1178        .await;
1179        fs.set_head_for_repo(
1180            path!("/dir/.git").as_ref(),
1181            &[("file.txt", "test".to_string())],
1182            "deadbeef",
1183        );
1184        fs.set_index_for_repo(
1185            path!("/dir/.git").as_ref(),
1186            &[("file.txt", "index_text".to_string())],
1187        );
1188
1189        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
1190        let repository = cx.read(|cx| project.read(cx).active_repository(cx));
1191
1192        repository.unwrap()
1193    }
1194
1195    #[gpui::test]
1196    async fn test_update_branch_matches_with_query(cx: &mut TestAppContext) {
1197        init_test(cx);
1198
1199        let branches = create_test_branches();
1200        let (mut ctx, branch_list) = init_branch_list_test(cx, None, branches);
1201        let cx = &mut ctx;
1202
1203        branch_list
1204            .update_in(cx, |branch_list, window, cx| {
1205                let query = "feature".to_string();
1206                branch_list.picker.update(cx, |picker, cx| {
1207                    picker.delegate.update_matches(query, window, cx)
1208                })
1209            })
1210            .await;
1211        cx.run_until_parked();
1212
1213        branch_list.update(cx, |branch_list, cx| {
1214            branch_list.picker.update(cx, |picker, _cx| {
1215                // Should have 2 existing branches + 1 "create new branch" entry = 3 total
1216                assert_eq!(picker.delegate.matches.len(), 3);
1217                assert!(
1218                    picker
1219                        .delegate
1220                        .matches
1221                        .iter()
1222                        .any(|m| m.name() == "feature-auth")
1223                );
1224                assert!(
1225                    picker
1226                        .delegate
1227                        .matches
1228                        .iter()
1229                        .any(|m| m.name() == "feature-ui")
1230                );
1231                // Verify the last entry is the "create new branch" option
1232                let last_match = picker.delegate.matches.last().unwrap();
1233                assert!(last_match.is_new_branch());
1234            })
1235        });
1236    }
1237
1238    async fn update_branch_list_matches_with_empty_query(
1239        branch_list: &Entity<BranchList>,
1240        cx: &mut VisualTestContext,
1241    ) {
1242        branch_list
1243            .update_in(cx, |branch_list, window, cx| {
1244                branch_list.picker.update(cx, |picker, cx| {
1245                    picker.delegate.update_matches(String::new(), window, cx)
1246                })
1247            })
1248            .await;
1249        cx.run_until_parked();
1250    }
1251
1252    #[gpui::test]
1253    async fn test_delete_branch(cx: &mut TestAppContext) {
1254        init_test(cx);
1255        let repository = init_fake_repository(cx).await;
1256
1257        let branches = create_test_branches();
1258
1259        let branch_names = branches
1260            .iter()
1261            .map(|branch| branch.name().to_string())
1262            .collect::<Vec<String>>();
1263        let repo = repository.clone();
1264        cx.spawn(async move |mut cx| {
1265            for branch in branch_names {
1266                repo.update(&mut cx, |repo, _| repo.create_branch(branch, None))
1267                    .unwrap()
1268                    .await
1269                    .unwrap()
1270                    .unwrap();
1271            }
1272        })
1273        .await;
1274        cx.run_until_parked();
1275
1276        let (mut ctx, branch_list) = init_branch_list_test(cx, repository.into(), branches);
1277        let cx = &mut ctx;
1278
1279        update_branch_list_matches_with_empty_query(&branch_list, cx).await;
1280
1281        let branch_to_delete = branch_list.update_in(cx, |branch_list, window, cx| {
1282            branch_list.picker.update(cx, |picker, cx| {
1283                assert_eq!(picker.delegate.matches.len(), 4);
1284                let branch_to_delete = picker.delegate.matches.get(1).unwrap().name().to_string();
1285                picker.delegate.delete_at(1, window, cx);
1286                branch_to_delete
1287            })
1288        });
1289        cx.run_until_parked();
1290
1291        branch_list.update(cx, move |branch_list, cx| {
1292            branch_list.picker.update(cx, move |picker, _cx| {
1293                assert_eq!(picker.delegate.matches.len(), 3);
1294                let branches = picker
1295                    .delegate
1296                    .matches
1297                    .iter()
1298                    .map(|be| be.name())
1299                    .collect::<HashSet<_>>();
1300                assert_eq!(
1301                    branches,
1302                    ["main", "feature-auth", "feature-ui", "develop"]
1303                        .into_iter()
1304                        .filter(|name| name != &branch_to_delete)
1305                        .collect::<HashSet<_>>()
1306                );
1307            })
1308        });
1309    }
1310
1311    #[gpui::test]
1312    async fn test_delete_remote(cx: &mut TestAppContext) {
1313        init_test(cx);
1314        let repository = init_fake_repository(cx).await;
1315        let branches = vec![
1316            create_test_branch("main", true, Some("origin"), Some(1000)),
1317            create_test_branch("feature-auth", false, Some("origin"), Some(900)),
1318            create_test_branch("feature-ui", false, Some("fork"), Some(800)),
1319            create_test_branch("develop", false, Some("private"), Some(700)),
1320        ];
1321
1322        let remote_names = branches
1323            .iter()
1324            .filter_map(|branch| branch.remote_name().map(|r| r.to_string()))
1325            .collect::<Vec<String>>();
1326        let repo = repository.clone();
1327        cx.spawn(async move |mut cx| {
1328            for branch in remote_names {
1329                repo.update(&mut cx, |repo, _| {
1330                    repo.create_remote(branch, String::from("test"))
1331                })
1332                .unwrap()
1333                .await
1334                .unwrap()
1335                .unwrap();
1336            }
1337        })
1338        .await;
1339        cx.run_until_parked();
1340
1341        let (mut ctx, branch_list) = init_branch_list_test(cx, repository.into(), branches);
1342        let cx = &mut ctx;
1343        // Enable remote filter
1344        branch_list.update(cx, |branch_list, cx| {
1345            branch_list.picker.update(cx, |picker, _cx| {
1346                picker.delegate.display_remotes = true;
1347            });
1348        });
1349        update_branch_list_matches_with_empty_query(&branch_list, cx).await;
1350
1351        // Check matches, it should match all existing branches and no option to create new branch
1352        let branch_to_delete = branch_list.update_in(cx, |branch_list, window, cx| {
1353            branch_list.picker.update(cx, |picker, cx| {
1354                assert_eq!(picker.delegate.matches.len(), 4);
1355                let branch_to_delete = picker.delegate.matches.get(1).unwrap().name().to_string();
1356                picker.delegate.delete_at(1, window, cx);
1357                branch_to_delete
1358            })
1359        });
1360        cx.run_until_parked();
1361
1362        // Check matches, it should match one less branch than before
1363        branch_list.update(cx, move |branch_list, cx| {
1364            branch_list.picker.update(cx, move |picker, _cx| {
1365                assert_eq!(picker.delegate.matches.len(), 3);
1366                let branches = picker
1367                    .delegate
1368                    .matches
1369                    .iter()
1370                    .map(|be| be.name())
1371                    .collect::<HashSet<_>>();
1372                assert_eq!(
1373                    branches,
1374                    [
1375                        "origin/main",
1376                        "origin/feature-auth",
1377                        "fork/feature-ui",
1378                        "private/develop"
1379                    ]
1380                    .into_iter()
1381                    .filter(|name| name != &branch_to_delete)
1382                    .collect::<HashSet<_>>()
1383                );
1384            })
1385        });
1386    }
1387
1388    #[gpui::test]
1389    async fn test_update_remote_matches_with_query(cx: &mut TestAppContext) {
1390        init_test(cx);
1391
1392        let branches = vec![
1393            create_test_branch("main", true, Some("origin"), Some(1000)),
1394            create_test_branch("feature-auth", false, Some("fork"), Some(900)),
1395            create_test_branch("feature-ui", false, None, Some(800)),
1396            create_test_branch("develop", false, None, Some(700)),
1397        ];
1398
1399        let (mut ctx, branch_list) = init_branch_list_test(cx, None, branches);
1400        let cx = &mut ctx;
1401
1402        update_branch_list_matches_with_empty_query(&branch_list, cx).await;
1403
1404        // Check matches, it should match all existing branches and no option to create new branch
1405        branch_list
1406            .update_in(cx, |branch_list, window, cx| {
1407                branch_list.picker.update(cx, |picker, cx| {
1408                    assert_eq!(picker.delegate.matches.len(), 2);
1409                    let branches = picker
1410                        .delegate
1411                        .matches
1412                        .iter()
1413                        .map(|be| be.name())
1414                        .collect::<HashSet<_>>();
1415                    assert_eq!(
1416                        branches,
1417                        ["feature-ui", "develop"]
1418                            .into_iter()
1419                            .collect::<HashSet<_>>()
1420                    );
1421
1422                    // Verify the last entry is NOT the "create new branch" option
1423                    let last_match = picker.delegate.matches.last().unwrap();
1424                    assert!(!last_match.is_new_branch());
1425                    assert!(!last_match.is_new_url());
1426                    picker.delegate.display_remotes = true;
1427                    picker.delegate.update_matches(String::new(), window, cx)
1428                })
1429            })
1430            .await;
1431        cx.run_until_parked();
1432
1433        branch_list
1434            .update_in(cx, |branch_list, window, cx| {
1435                branch_list.picker.update(cx, |picker, cx| {
1436                    assert_eq!(picker.delegate.matches.len(), 2);
1437                    let branches = picker
1438                        .delegate
1439                        .matches
1440                        .iter()
1441                        .map(|be| be.name())
1442                        .collect::<HashSet<_>>();
1443                    assert_eq!(
1444                        branches,
1445                        ["origin/main", "fork/feature-auth"]
1446                            .into_iter()
1447                            .collect::<HashSet<_>>()
1448                    );
1449
1450                    // Verify the last entry is NOT the "create new branch" option
1451                    let last_match = picker.delegate.matches.last().unwrap();
1452                    assert!(!last_match.is_new_url());
1453                    picker.delegate.display_remotes = true;
1454                    picker
1455                        .delegate
1456                        .update_matches(String::from("fork"), window, cx)
1457                })
1458            })
1459            .await;
1460        cx.run_until_parked();
1461
1462        branch_list.update(cx, |branch_list, cx| {
1463            branch_list.picker.update(cx, |picker, _cx| {
1464                // Should have 1 existing branch + 1 "create new branch" entry = 2 total
1465                assert_eq!(picker.delegate.matches.len(), 2);
1466                assert!(
1467                    picker
1468                        .delegate
1469                        .matches
1470                        .iter()
1471                        .any(|m| m.name() == "fork/feature-auth")
1472                );
1473                // Verify the last entry is the "create new branch" option
1474                let last_match = picker.delegate.matches.last().unwrap();
1475                assert!(last_match.is_new_branch());
1476            })
1477        });
1478    }
1479
1480    #[gpui::test]
1481    async fn test_new_branch_creation_with_query(test_cx: &mut TestAppContext) {
1482        init_test(test_cx);
1483        let repository = init_fake_repository(test_cx).await;
1484
1485        let branches = vec![
1486            create_test_branch("main", true, None, Some(1000)),
1487            create_test_branch("feature", false, None, Some(900)),
1488        ];
1489
1490        let (mut ctx, branch_list) = init_branch_list_test(test_cx, repository.into(), branches);
1491        let cx = &mut ctx;
1492
1493        branch_list
1494            .update_in(cx, |branch_list, window, cx| {
1495                branch_list.picker.update(cx, |picker, cx| {
1496                    let query = "new-feature-branch".to_string();
1497                    picker.delegate.update_matches(query, window, cx)
1498                })
1499            })
1500            .await;
1501
1502        cx.run_until_parked();
1503
1504        branch_list.update_in(cx, |branch_list, window, cx| {
1505            branch_list.picker.update(cx, |picker, cx| {
1506                let last_match = picker.delegate.matches.last().unwrap();
1507                assert!(last_match.is_new_branch());
1508                assert_eq!(last_match.name(), "new-feature-branch");
1509                assert!(matches!(picker.delegate.state, PickerState::NewBranch));
1510                picker.delegate.confirm(false, window, cx);
1511            })
1512        });
1513        cx.run_until_parked();
1514
1515        let branches = branch_list
1516            .update(cx, |branch_list, cx| {
1517                branch_list.picker.update(cx, |picker, cx| {
1518                    picker
1519                        .delegate
1520                        .repo
1521                        .as_ref()
1522                        .unwrap()
1523                        .update(cx, |repo, _cx| repo.branches())
1524                })
1525            })
1526            .await
1527            .unwrap()
1528            .unwrap();
1529
1530        assert!(
1531            branches
1532                .into_iter()
1533                .any(|branch| branch.name() == "new-feature-branch")
1534        );
1535    }
1536
1537    #[gpui::test]
1538    async fn test_remote_url_detection_https(cx: &mut TestAppContext) {
1539        init_test(cx);
1540        let repository = init_fake_repository(cx).await;
1541        let branches = vec![create_test_branch("main", true, None, Some(1000))];
1542
1543        let (mut ctx, branch_list) = init_branch_list_test(cx, repository.into(), branches);
1544        let cx = &mut ctx;
1545
1546        branch_list
1547            .update_in(cx, |branch_list, window, cx| {
1548                branch_list.picker.update(cx, |picker, cx| {
1549                    let query = "https://github.com/user/repo.git".to_string();
1550                    picker.delegate.update_matches(query, window, cx)
1551                })
1552            })
1553            .await;
1554
1555        cx.run_until_parked();
1556
1557        branch_list
1558            .update_in(cx, |branch_list, window, cx| {
1559                branch_list.picker.update(cx, |picker, cx| {
1560                    let last_match = picker.delegate.matches.last().unwrap();
1561                    assert!(last_match.is_new_url());
1562                    assert!(matches!(picker.delegate.state, PickerState::NewRemote));
1563                    picker.delegate.confirm(false, window, cx);
1564                    assert_eq!(picker.delegate.matches.len(), 0);
1565                    if let PickerState::CreateRemote(remote_url) = &picker.delegate.state
1566                        && remote_url.as_ref() == "https://github.com/user/repo.git"
1567                    {
1568                    } else {
1569                        panic!("wrong picker state");
1570                    }
1571                    picker
1572                        .delegate
1573                        .update_matches("my_new_remote".to_string(), window, cx)
1574                })
1575            })
1576            .await;
1577
1578        cx.run_until_parked();
1579
1580        branch_list.update_in(cx, |branch_list, window, cx| {
1581            branch_list.picker.update(cx, |picker, cx| {
1582                picker.delegate.confirm(false, window, cx);
1583                assert_eq!(picker.delegate.matches.len(), 0);
1584            })
1585        });
1586        cx.run_until_parked();
1587
1588        // List remotes
1589        let remotes = branch_list
1590            .update(cx, |branch_list, cx| {
1591                branch_list.picker.update(cx, |picker, cx| {
1592                    picker
1593                        .delegate
1594                        .repo
1595                        .as_ref()
1596                        .unwrap()
1597                        .update(cx, |repo, _cx| repo.get_remotes(None, false))
1598                })
1599            })
1600            .await
1601            .unwrap()
1602            .unwrap();
1603        assert_eq!(
1604            remotes,
1605            vec![Remote {
1606                name: SharedString::from("my_new_remote".to_string())
1607            }]
1608        );
1609    }
1610
1611    #[gpui::test]
1612    async fn test_confirm_remote_url_transitions(cx: &mut TestAppContext) {
1613        init_test(cx);
1614
1615        let branches = vec![create_test_branch("main_branch", true, None, Some(1000))];
1616        let (mut ctx, branch_list) = init_branch_list_test(cx, None, branches);
1617        let cx = &mut ctx;
1618
1619        branch_list
1620            .update_in(cx, |branch_list, window, cx| {
1621                branch_list.picker.update(cx, |picker, cx| {
1622                    let query = "https://github.com/user/repo.git".to_string();
1623                    picker.delegate.update_matches(query, window, cx)
1624                })
1625            })
1626            .await;
1627        cx.run_until_parked();
1628
1629        // Try to create a new remote but cancel in the middle of the process
1630        branch_list
1631            .update_in(cx, |branch_list, window, cx| {
1632                branch_list.picker.update(cx, |picker, cx| {
1633                    picker.delegate.selected_index = picker.delegate.matches.len() - 1;
1634                    picker.delegate.confirm(false, window, cx);
1635
1636                    assert!(matches!(
1637                        picker.delegate.state,
1638                        PickerState::CreateRemote(_)
1639                    ));
1640                    if let PickerState::CreateRemote(ref url) = picker.delegate.state {
1641                        assert_eq!(url.as_ref(), "https://github.com/user/repo.git");
1642                    }
1643                    assert_eq!(picker.delegate.matches.len(), 0);
1644                    picker.delegate.dismissed(window, cx);
1645                    assert!(matches!(picker.delegate.state, PickerState::List));
1646                    let query = "main".to_string();
1647                    picker.delegate.update_matches(query, window, cx)
1648                })
1649            })
1650            .await;
1651        cx.run_until_parked();
1652
1653        // Try to search a branch again to see if the state is restored properly
1654        branch_list.update(cx, |branch_list, cx| {
1655            branch_list.picker.update(cx, |picker, _cx| {
1656                // Should have 1 existing branch + 1 "create new branch" entry = 2 total
1657                assert_eq!(picker.delegate.matches.len(), 2);
1658                assert!(
1659                    picker
1660                        .delegate
1661                        .matches
1662                        .iter()
1663                        .any(|m| m.name() == "main_branch")
1664                );
1665                // Verify the last entry is the "create new branch" option
1666                let last_match = picker.delegate.matches.last().unwrap();
1667                assert!(last_match.is_new_branch());
1668            })
1669        });
1670    }
1671}