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
110 let Some(worktree) = project
111 .visible_worktrees(cx)
112 .next()
113 else {
114 bail!("Cannot update branch list as there are no visible worktrees")
115 };
116 let mut cwd = worktree .read(cx)
117 .abs_path()
118 .to_path_buf();
119 cwd.push(".git");
120 let Some(repo) = project.fs().open_repo(&cwd) else {bail!("Project does not have associated git repository.")};
121 let mut branches = repo
122 .lock()
123 .branches()?;
124 const RECENT_BRANCHES_COUNT: usize = 10;
125 if query.is_empty() && branches.len() > RECENT_BRANCHES_COUNT {
126 // Truncate list of recent branches
127 // Do a partial sort to show recent-ish branches first.
128 branches.select_nth_unstable_by(RECENT_BRANCHES_COUNT - 1, |lhs, rhs| {
129 rhs.unix_timestamp.cmp(&lhs.unix_timestamp)
130 });
131 branches.truncate(RECENT_BRANCHES_COUNT);
132 branches.sort_unstable_by(|lhs, rhs| lhs.name.cmp(&rhs.name));
133 }
134 Ok(branches
135 .iter()
136 .cloned()
137 .enumerate()
138 .map(|(ix, command)| StringMatchCandidate {
139 id: ix,
140 char_bag: command.name.chars().collect(),
141 string: command.name.into(),
142 })
143 .collect::<Vec<_>>())
144 })
145 .log_err() else { return; };
146 let Some(candidates) = candidates.log_err() else {return;};
147 let matches = if query.is_empty() {
148 candidates
149 .into_iter()
150 .enumerate()
151 .map(|(index, candidate)| StringMatch {
152 candidate_id: index,
153 string: candidate.string,
154 positions: Vec::new(),
155 score: 0.0,
156 })
157 .collect()
158 } else {
159 fuzzy::match_strings(
160 &candidates,
161 &query,
162 true,
163 10000,
164 &Default::default(),
165 cx.background(),
166 )
167 .await
168 };
169 picker
170 .update(&mut cx, |picker, _| {
171 let delegate = picker.delegate_mut();
172 delegate.matches = matches;
173 if delegate.matches.is_empty() {
174 delegate.selected_index = 0;
175 } else {
176 delegate.selected_index =
177 core::cmp::min(delegate.selected_index, delegate.matches.len() - 1);
178 }
179 delegate.last_query = query;
180 })
181 .log_err();
182 })
183 }
184
185 fn confirm(&mut self, _: bool, cx: &mut ViewContext<Picker<Self>>) {
186 let current_pick = self.selected_index();
187 let Some(current_pick) = self.matches.get(current_pick).map(|pick| pick.string.clone()) else {
188 return;
189 };
190 cx.spawn(|picker, mut cx| async move {
191 picker
192 .update(&mut cx, |this, cx| {
193 let project = this.delegate().workspace.read(cx).project().read(cx);
194 let mut cwd = project
195 .visible_worktrees(cx)
196 .next()
197 .ok_or_else(|| anyhow!("There are no visisible worktrees."))?
198 .read(cx)
199 .abs_path()
200 .to_path_buf();
201 cwd.push(".git");
202 let status = project
203 .fs()
204 .open_repo(&cwd)
205 .ok_or_else(|| {
206 anyhow!(
207 "Could not open repository at path `{}`",
208 cwd.as_os_str().to_string_lossy()
209 )
210 })?
211 .lock()
212 .change_branch(¤t_pick);
213 if status.is_err() {
214 this.delegate().display_error_toast(format!("Failed to checkout branch '{current_pick}', check for conflicts or unstashed files"), cx);
215 status?;
216 }
217 cx.emit(PickerEvent::Dismiss);
218
219 Ok::<(), anyhow::Error>(())
220 })
221 .log_err();
222 })
223 .detach();
224 }
225
226 fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>) {
227 cx.emit(PickerEvent::Dismiss);
228 }
229
230 fn render_match(
231 &self,
232 ix: usize,
233 mouse_state: &mut MouseState,
234 selected: bool,
235 cx: &gpui::AppContext,
236 ) -> AnyElement<Picker<Self>> {
237 let theme = &theme::current(cx);
238 let hit = &self.matches[ix];
239 let shortened_branch_name =
240 util::truncate_and_trailoff(&hit.string, self.branch_name_trailoff_after);
241 let highlights = hit
242 .positions
243 .iter()
244 .copied()
245 .filter(|index| index < &self.branch_name_trailoff_after)
246 .collect();
247 let style = theme.picker.item.in_state(selected).style_for(mouse_state);
248 Flex::row()
249 .with_child(
250 Label::new(shortened_branch_name.clone(), style.label.clone())
251 .with_highlights(highlights)
252 .contained()
253 .aligned()
254 .left(),
255 )
256 .contained()
257 .with_style(style.container)
258 .constrained()
259 .with_height(theme.collab_panel.tabbed_modal.row_height)
260 .into_any()
261 }
262 fn render_header(
263 &self,
264 cx: &mut ViewContext<Picker<Self>>,
265 ) -> Option<AnyElement<Picker<Self>>> {
266 let theme = &theme::current(cx);
267 let style = theme.picker.header.clone();
268 let label = if self.last_query.is_empty() {
269 Flex::row()
270 .with_child(Label::new("Recent branches", style.label.clone()))
271 .contained()
272 .with_style(style.container)
273 } else {
274 Flex::row()
275 .with_child(Label::new("Branches", style.label.clone()))
276 .with_children(self.matches.is_empty().not().then(|| {
277 let suffix = if self.matches.len() == 1 { "" } else { "es" };
278 Label::new(
279 format!("{} match{}", self.matches.len(), suffix),
280 style.label,
281 )
282 .flex_float()
283 }))
284 .contained()
285 .with_style(style.container)
286 };
287 Some(label.into_any())
288 }
289 fn render_footer(
290 &self,
291 cx: &mut ViewContext<Picker<Self>>,
292 ) -> Option<AnyElement<Picker<Self>>> {
293 if !self.last_query.is_empty() {
294 let theme = &theme::current(cx);
295 let style = theme.picker.footer.clone();
296 enum BranchCreateButton {}
297 Some(
298 Flex::row().with_child(MouseEventHandler::new::<BranchCreateButton, _>(0, cx, |state, _| {
299 let style = style.style_for(state);
300 Label::new("Create branch", style.label.clone())
301 .contained()
302 .with_style(style.container)
303 })
304 .with_cursor_style(CursorStyle::PointingHand)
305 .on_down(MouseButton::Left, |_, _, cx| {
306 cx.spawn(|picker, mut cx| async move {
307 picker.update(&mut cx, |this, cx| {
308 let project = this.delegate().workspace.read(cx).project().read(cx);
309 let current_pick = &this.delegate().last_query;
310 let mut cwd = project
311 .visible_worktrees(cx)
312 .next()
313 .ok_or_else(|| anyhow!("There are no visisible worktrees."))?
314 .read(cx)
315 .abs_path()
316 .to_path_buf();
317 cwd.push(".git");
318 let repo = project
319 .fs()
320 .open_repo(&cwd)
321 .ok_or_else(|| anyhow!("Could not open repository at path `{}`", cwd.as_os_str().to_string_lossy()))?;
322 let repo = repo
323 .lock();
324 let status = repo
325 .create_branch(¤t_pick);
326 if status.is_err() {
327 this.delegate().display_error_toast(format!("Failed to create branch '{current_pick}', check for conflicts or unstashed files"), cx);
328 status?;
329 }
330 let status = repo.change_branch(¤t_pick);
331 if status.is_err() {
332 this.delegate().display_error_toast(format!("Failed to chec branch '{current_pick}', check for conflicts or unstashed files"), cx);
333 status?;
334 }
335 cx.emit(PickerEvent::Dismiss);
336 Ok::<(), anyhow::Error>(())
337 })
338 }).detach();
339 })).aligned().right()
340 .into_any(),
341 )
342 } else {
343 None
344 }
345 }
346}