lib.rs

  1use anyhow::{anyhow, bail, Result};
  2use fuzzy::{StringMatch, StringMatchCandidate};
  3use gpui::{
  4    actions,
  5    elements::*,
  6    platform::{CursorStyle, MouseButton},
  7    AppContext, MouseState, Task, ViewContext, ViewHandle,
  8};
  9use picker::{Picker, PickerDelegate, PickerEvent};
 10use std::{ops::Not, sync::Arc};
 11use util::ResultExt;
 12use workspace::{Toast, Workspace};
 13
 14actions!(branches, [OpenRecent]);
 15
 16pub fn init(cx: &mut AppContext) {
 17    Picker::<BranchListDelegate>::init(cx);
 18    cx.add_async_action(toggle);
 19}
 20pub type BranchList = Picker<BranchListDelegate>;
 21
 22pub fn build_branch_list(
 23    workspace: ViewHandle<Workspace>,
 24    cx: &mut ViewContext<BranchList>,
 25) -> BranchList {
 26    Picker::new(
 27        BranchListDelegate {
 28            matches: vec![],
 29            workspace,
 30            selected_index: 0,
 31            last_query: String::default(),
 32            branch_name_trailoff_after: 29,
 33        },
 34        cx,
 35    )
 36    .with_theme(|theme| theme.picker.clone())
 37}
 38
 39fn toggle(
 40    _: &mut Workspace,
 41    _: &OpenRecent,
 42    cx: &mut ViewContext<Workspace>,
 43) -> Option<Task<Result<()>>> {
 44    Some(cx.spawn(|workspace, mut cx| async move {
 45        workspace.update(&mut cx, |workspace, cx| {
 46            workspace.toggle_modal(cx, |_, cx| {
 47                let workspace = cx.handle();
 48                cx.add_view(|cx| {
 49                    Picker::new(
 50                        BranchListDelegate {
 51                            matches: vec![],
 52                            workspace,
 53                            selected_index: 0,
 54                            last_query: String::default(),
 55                            /// Modal branch picker has a longer trailoff than a popover one.
 56                            branch_name_trailoff_after: 70,
 57                        },
 58                        cx,
 59                    )
 60                    .with_theme(|theme| theme.picker.clone())
 61                    .with_max_size(800., 1200.)
 62                })
 63            });
 64        })?;
 65        Ok(())
 66    }))
 67}
 68
 69pub struct BranchListDelegate {
 70    matches: Vec<StringMatch>,
 71    workspace: ViewHandle<Workspace>,
 72    selected_index: usize,
 73    last_query: String,
 74    /// Max length of branch name before we truncate it and add a trailing `...`.
 75    branch_name_trailoff_after: usize,
 76}
 77
 78impl BranchListDelegate {
 79    fn display_error_toast(&self, message: String, cx: &mut ViewContext<BranchList>) {
 80        const GIT_CHECKOUT_FAILURE_ID: usize = 2048;
 81        self.workspace.update(cx, |model, ctx| {
 82            model.show_toast(Toast::new(GIT_CHECKOUT_FAILURE_ID, message), ctx)
 83        });
 84    }
 85}
 86impl PickerDelegate for BranchListDelegate {
 87    fn placeholder_text(&self) -> Arc<str> {
 88        "Select branch...".into()
 89    }
 90
 91    fn match_count(&self) -> usize {
 92        self.matches.len()
 93    }
 94
 95    fn selected_index(&self) -> usize {
 96        self.selected_index
 97    }
 98
 99    fn set_selected_index(&mut self, ix: usize, _: &mut ViewContext<Picker<Self>>) {
100        self.selected_index = ix;
101    }
102
103    fn update_matches(&mut self, query: String, cx: &mut ViewContext<Picker<Self>>) -> Task<()> {
104        cx.spawn(move |picker, mut cx| async move {
105            let Some(candidates) = picker
106                .read_with(&mut cx, |view, cx| {
107                    let delegate = view.delegate();
108                    let project = delegate.workspace.read(cx).project().read(&cx);
109                    let mut cwd =
110                    project
111                        .visible_worktrees(cx)
112                        .next()
113                        .unwrap()
114                        .read(cx)
115                        .abs_path()
116                        .to_path_buf();
117                    cwd.push(".git");
118                    let Some(repo) = project.fs().open_repo(&cwd) else {bail!("Project does not have associated git repository.")};
119                    let mut branches = repo
120                        .lock()
121                        .branches()?;
122                    const RECENT_BRANCHES_COUNT: usize = 10;
123                    if query.is_empty() && branches.len() > RECENT_BRANCHES_COUNT {
124                        // Truncate list of recent branches
125                        // Do a partial sort to show recent-ish branches first.
126                        branches.select_nth_unstable_by(RECENT_BRANCHES_COUNT - 1, |lhs, rhs| {
127                            rhs.unix_timestamp.cmp(&lhs.unix_timestamp)
128                        });
129                        branches.truncate(RECENT_BRANCHES_COUNT);
130                        branches.sort_unstable_by(|lhs, rhs| lhs.name.cmp(&rhs.name));
131                    }
132                    Ok(branches
133                        .iter()
134                        .cloned()
135                        .enumerate()
136                        .map(|(ix, command)| StringMatchCandidate {
137                            id: ix,
138                            char_bag: command.name.chars().collect(),
139                            string: command.name.into(),
140                        })
141                        .collect::<Vec<_>>())
142                })
143                .log_err() else { return; };
144            let Some(candidates) = candidates.log_err() else {return;};
145            let matches = if query.is_empty() {
146                candidates
147                    .into_iter()
148                    .enumerate()
149                    .map(|(index, candidate)| StringMatch {
150                        candidate_id: index,
151                        string: candidate.string,
152                        positions: Vec::new(),
153                        score: 0.0,
154                    })
155                    .collect()
156            } else {
157                fuzzy::match_strings(
158                    &candidates,
159                    &query,
160                    true,
161                    10000,
162                    &Default::default(),
163                    cx.background(),
164                )
165                .await
166            };
167            picker
168                .update(&mut cx, |picker, _| {
169                    let delegate = picker.delegate_mut();
170                    delegate.matches = matches;
171                    if delegate.matches.is_empty() {
172                        delegate.selected_index = 0;
173                    } else {
174                        delegate.selected_index =
175                            core::cmp::min(delegate.selected_index, delegate.matches.len() - 1);
176                    }
177                    delegate.last_query = query;
178                })
179                .log_err();
180        })
181    }
182
183    fn confirm(&mut self, cx: &mut ViewContext<Picker<Self>>) {
184        let current_pick = self.selected_index();
185        let current_pick = self.matches[current_pick].string.clone();
186        cx.spawn(|picker, mut cx| async move {
187            picker
188                .update(&mut cx, |this, cx| {
189                    let project = this.delegate().workspace.read(cx).project().read(cx);
190                    let mut cwd = project
191                        .visible_worktrees(cx)
192                        .next()
193                        .ok_or_else(|| anyhow!("There are no visisible worktrees."))?
194                        .read(cx)
195                        .abs_path()
196                        .to_path_buf();
197                    cwd.push(".git");
198                    let status = project
199                        .fs()
200                        .open_repo(&cwd)
201                        .ok_or_else(|| {
202                            anyhow!(
203                                "Could not open repository at path `{}`",
204                                cwd.as_os_str().to_string_lossy()
205                            )
206                        })?
207                        .lock()
208                        .change_branch(&current_pick);
209                    if status.is_err() {
210                        this.delegate().display_error_toast(format!("Failed to checkout branch '{current_pick}', check for conflicts or unstashed files"), cx);
211                        status?;
212                    }
213                    cx.emit(PickerEvent::Dismiss);
214
215                    Ok::<(), anyhow::Error>(())
216                })
217                .log_err();
218        })
219        .detach();
220    }
221
222    fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>) {
223        cx.emit(PickerEvent::Dismiss);
224    }
225
226    fn render_match(
227        &self,
228        ix: usize,
229        mouse_state: &mut MouseState,
230        selected: bool,
231        cx: &gpui::AppContext,
232    ) -> AnyElement<Picker<Self>> {
233        let theme = &theme::current(cx);
234        let hit = &self.matches[ix];
235        let shortened_branch_name =
236            util::truncate_and_trailoff(&hit.string, self.branch_name_trailoff_after);
237        let highlights = hit
238            .positions
239            .iter()
240            .copied()
241            .filter(|index| index < &self.branch_name_trailoff_after)
242            .collect();
243        let style = theme.picker.item.in_state(selected).style_for(mouse_state);
244        Flex::row()
245            .with_child(
246                Label::new(shortened_branch_name.clone(), style.label.clone())
247                    .with_highlights(highlights)
248                    .contained()
249                    .aligned()
250                    .left(),
251            )
252            .contained()
253            .with_style(style.container)
254            .constrained()
255            .with_height(theme.contact_finder.row_height)
256            .into_any()
257    }
258    fn render_header(
259        &self,
260        cx: &mut ViewContext<Picker<Self>>,
261    ) -> Option<AnyElement<Picker<Self>>> {
262        let theme = &theme::current(cx);
263        let style = theme.picker.header.clone();
264        let label = if self.last_query.is_empty() {
265            Flex::row()
266                .with_child(Label::new("Recent branches", style.label.clone()))
267                .contained()
268                .with_style(style.container)
269        } else {
270            Flex::row()
271                .with_child(Label::new("Branches", style.label.clone()))
272                .with_children(self.matches.is_empty().not().then(|| {
273                    let suffix = if self.matches.len() == 1 { "" } else { "es" };
274                    Label::new(
275                        format!("{} match{}", self.matches.len(), suffix),
276                        style.label,
277                    )
278                    .flex_float()
279                }))
280                .contained()
281                .with_style(style.container)
282        };
283        Some(label.into_any())
284    }
285    fn render_footer(
286        &self,
287        cx: &mut ViewContext<Picker<Self>>,
288    ) -> Option<AnyElement<Picker<Self>>> {
289        if !self.last_query.is_empty() {
290            let theme = &theme::current(cx);
291            let style = theme.picker.footer.clone();
292            enum BranchCreateButton {}
293            Some(
294                Flex::row().with_child(MouseEventHandler::<BranchCreateButton, _>::new(0, cx, |state, _| {
295                    let style = style.style_for(state);
296                    Label::new("Create branch", style.label.clone())
297                        .contained()
298                        .with_style(style.container)
299                })
300                .with_cursor_style(CursorStyle::PointingHand)
301                .on_down(MouseButton::Left, |_, _, cx| {
302                    cx.spawn(|picker, mut cx| async move {
303                        picker.update(&mut cx, |this, cx| {
304                            let project = this.delegate().workspace.read(cx).project().read(cx);
305                            let current_pick = &this.delegate().last_query;
306                            let mut cwd = project
307                            .visible_worktrees(cx)
308                            .next()
309                            .ok_or_else(|| anyhow!("There are no visisible worktrees."))?
310                            .read(cx)
311                            .abs_path()
312                            .to_path_buf();
313                            cwd.push(".git");
314                            let repo = project
315                                .fs()
316                                .open_repo(&cwd)
317                                .ok_or_else(|| anyhow!("Could not open repository at path `{}`", cwd.as_os_str().to_string_lossy()))?;
318                            let repo = repo
319                                .lock();
320                            let status = repo
321                                .create_branch(&current_pick);
322                            if status.is_err() {
323                                this.delegate().display_error_toast(format!("Failed to create branch '{current_pick}', check for conflicts or unstashed files"), cx);
324                                status?;
325                            }
326                            let status = repo.change_branch(&current_pick);
327                            if status.is_err() {
328                                this.delegate().display_error_toast(format!("Failed to chec branch '{current_pick}', check for conflicts or unstashed files"), cx);
329                                status?;
330                            }
331                            cx.emit(PickerEvent::Dismiss);
332                            Ok::<(), anyhow::Error>(())
333                })
334                    }).detach();
335                })).aligned().right()
336                .into_any(),
337            )
338        } else {
339            None
340        }
341    }
342}