1use crate::git_panel_settings::StatusStyle;
2use crate::project_diff::Diff;
3use crate::repository_selector::RepositorySelectorPopoverMenu;
4use crate::{
5 git_panel_settings::GitPanelSettings, git_status_icon, repository_selector::RepositorySelector,
6};
7use crate::{picker_prompt, project_diff, ProjectDiff};
8use db::kvp::KEY_VALUE_STORE;
9use editor::commit_tooltip::CommitTooltip;
10use editor::{
11 scroll::ScrollbarAutoHide, Editor, EditorElement, EditorMode, EditorSettings, MultiBuffer,
12 ShowScrollbar,
13};
14use git::repository::{Branch, CommitDetails, PushOptions, Remote, ResetMode, UpstreamTracking};
15use git::{repository::RepoPath, status::FileStatus, Commit, ToggleStaged};
16use git::{Push, RestoreTrackedFiles, StageAll, TrashUntrackedFiles, UnstageAll};
17use gpui::*;
18use itertools::Itertools;
19use language::{Buffer, File};
20use menu::{Confirm, SecondaryConfirm, SelectFirst, SelectLast, SelectNext, SelectPrev};
21use multi_buffer::ExcerptInfo;
22use panel::{panel_editor_container, panel_editor_style, panel_filled_button, PanelHeader};
23use project::{
24 git::{GitEvent, Repository},
25 Fs, Project, ProjectPath,
26};
27use serde::{Deserialize, Serialize};
28use settings::Settings as _;
29use std::cell::RefCell;
30use std::future::Future;
31use std::rc::Rc;
32use std::{collections::HashSet, sync::Arc, time::Duration, usize};
33use strum::{IntoEnumIterator, VariantNames};
34use time::OffsetDateTime;
35use ui::{
36 prelude::*, ButtonLike, Checkbox, ContextMenu, Divider, DividerColor, ElevationIndex, ListItem,
37 ListItemSpacing, PopoverMenu, Scrollbar, ScrollbarState, Tooltip,
38};
39use util::{maybe, post_inc, ResultExt, TryFutureExt};
40use workspace::{
41 dock::{DockPosition, Panel, PanelEvent},
42 notifications::{DetachAndPromptErr, NotificationId},
43 Toast, Workspace,
44};
45
46actions!(
47 git_panel,
48 [
49 Close,
50 ToggleFocus,
51 OpenMenu,
52 FocusEditor,
53 FocusChanges,
54 ToggleFillCoAuthors,
55 ]
56);
57
58fn prompt<T>(msg: &str, detail: Option<&str>, window: &mut Window, cx: &mut App) -> Task<Result<T>>
59where
60 T: IntoEnumIterator + VariantNames + 'static,
61{
62 let rx = window.prompt(PromptLevel::Info, msg, detail, &T::VARIANTS, cx);
63 cx.spawn(|_| async move { Ok(T::iter().nth(rx.await?).unwrap()) })
64}
65
66#[derive(strum::EnumIter, strum::VariantNames)]
67#[strum(serialize_all = "title_case")]
68enum TrashCancel {
69 Trash,
70 Cancel,
71}
72
73const GIT_PANEL_KEY: &str = "GitPanel";
74
75const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
76
77pub fn init(cx: &mut App) {
78 cx.observe_new(
79 |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
80 workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
81 workspace.toggle_panel_focus::<GitPanel>(window, cx);
82 });
83 },
84 )
85 .detach();
86}
87
88#[derive(Debug, Clone)]
89pub enum Event {
90 Focus,
91}
92
93#[derive(Serialize, Deserialize)]
94struct SerializedGitPanel {
95 width: Option<Pixels>,
96}
97
98#[derive(Debug, PartialEq, Eq, Clone, Copy)]
99enum Section {
100 Conflict,
101 Tracked,
102 New,
103}
104
105#[derive(Debug, PartialEq, Eq, Clone)]
106struct GitHeaderEntry {
107 header: Section,
108}
109
110impl GitHeaderEntry {
111 pub fn contains(&self, status_entry: &GitStatusEntry, repo: &Repository) -> bool {
112 let this = &self.header;
113 let status = status_entry.status;
114 match this {
115 Section::Conflict => repo.has_conflict(&status_entry.repo_path),
116 Section::Tracked => !status.is_created(),
117 Section::New => status.is_created(),
118 }
119 }
120 pub fn title(&self) -> &'static str {
121 match self.header {
122 Section::Conflict => "Conflicts",
123 Section::Tracked => "Tracked",
124 Section::New => "Untracked",
125 }
126 }
127}
128
129#[derive(Debug, PartialEq, Eq, Clone)]
130enum GitListEntry {
131 GitStatusEntry(GitStatusEntry),
132 Header(GitHeaderEntry),
133}
134
135impl GitListEntry {
136 fn status_entry(&self) -> Option<&GitStatusEntry> {
137 match self {
138 GitListEntry::GitStatusEntry(entry) => Some(entry),
139 _ => None,
140 }
141 }
142}
143
144#[derive(Debug, PartialEq, Eq, Clone)]
145pub struct GitStatusEntry {
146 pub(crate) repo_path: RepoPath,
147 pub(crate) status: FileStatus,
148 pub(crate) is_staged: Option<bool>,
149}
150
151#[derive(Clone, Copy, Debug, PartialEq, Eq)]
152enum TargetStatus {
153 Staged,
154 Unstaged,
155 Reverted,
156 Unchanged,
157}
158
159struct PendingOperation {
160 finished: bool,
161 target_status: TargetStatus,
162 repo_paths: HashSet<RepoPath>,
163 op_id: usize,
164}
165
166type RemoteOperations = Rc<RefCell<HashSet<u32>>>;
167
168pub struct GitPanel {
169 remote_operation_id: u32,
170 pending_remote_operations: RemoteOperations,
171 pub(crate) active_repository: Option<Entity<Repository>>,
172 commit_editor: Entity<Editor>,
173 suggested_commit_message: Option<String>,
174 conflicted_count: usize,
175 conflicted_staged_count: usize,
176 current_modifiers: Modifiers,
177 add_coauthors: bool,
178 entries: Vec<GitListEntry>,
179 focus_handle: FocusHandle,
180 fs: Arc<dyn Fs>,
181 hide_scrollbar_task: Option<Task<()>>,
182 new_count: usize,
183 new_staged_count: usize,
184 pending: Vec<PendingOperation>,
185 pending_commit: Option<Task<()>>,
186 pending_serialization: Task<Option<()>>,
187 pub(crate) project: Entity<Project>,
188 repository_selector: Entity<RepositorySelector>,
189 scroll_handle: UniformListScrollHandle,
190 scrollbar_state: ScrollbarState,
191 selected_entry: Option<usize>,
192 show_scrollbar: bool,
193 tracked_count: usize,
194 tracked_staged_count: usize,
195 update_visible_entries_task: Task<()>,
196 width: Option<Pixels>,
197 workspace: WeakEntity<Workspace>,
198 context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
199 modal_open: bool,
200}
201
202struct RemoteOperationGuard {
203 id: u32,
204 pending_remote_operations: RemoteOperations,
205}
206
207impl Drop for RemoteOperationGuard {
208 fn drop(&mut self) {
209 self.pending_remote_operations.borrow_mut().remove(&self.id);
210 }
211}
212
213pub(crate) fn commit_message_editor(
214 commit_message_buffer: Entity<Buffer>,
215 project: Entity<Project>,
216 in_panel: bool,
217 window: &mut Window,
218 cx: &mut Context<'_, Editor>,
219) -> Editor {
220 let buffer = cx.new(|cx| MultiBuffer::singleton(commit_message_buffer, cx));
221 let max_lines = if in_panel { 6 } else { 18 };
222 let mut commit_editor = Editor::new(
223 EditorMode::AutoHeight { max_lines },
224 buffer,
225 None,
226 false,
227 window,
228 cx,
229 );
230 commit_editor.set_collaboration_hub(Box::new(project));
231 commit_editor.set_use_autoclose(false);
232 commit_editor.set_show_gutter(false, cx);
233 commit_editor.set_show_wrap_guides(false, cx);
234 commit_editor.set_show_indent_guides(false, cx);
235 commit_editor.set_placeholder_text("Enter commit message", cx);
236 commit_editor
237}
238
239impl GitPanel {
240 pub fn new(
241 workspace: &mut Workspace,
242 window: &mut Window,
243 cx: &mut Context<Workspace>,
244 ) -> Entity<Self> {
245 let fs = workspace.app_state().fs.clone();
246 let project = workspace.project().clone();
247 let git_store = project.read(cx).git_store().clone();
248 let active_repository = project.read(cx).active_repository(cx);
249 let workspace = cx.entity().downgrade();
250
251 cx.new(|cx| {
252 let focus_handle = cx.focus_handle();
253 cx.on_focus(&focus_handle, window, Self::focus_in).detach();
254 cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
255 this.hide_scrollbar(window, cx);
256 })
257 .detach();
258
259 // just to let us render a placeholder editor.
260 // Once the active git repo is set, this buffer will be replaced.
261 let temporary_buffer = cx.new(|cx| Buffer::local("", cx));
262 let commit_editor = cx.new(|cx| {
263 commit_message_editor(temporary_buffer, project.clone(), true, window, cx)
264 });
265 commit_editor.update(cx, |editor, cx| {
266 editor.clear(window, cx);
267 });
268
269 let scroll_handle = UniformListScrollHandle::new();
270
271 cx.subscribe_in(
272 &git_store,
273 window,
274 move |this, git_store, event, window, cx| match event {
275 GitEvent::FileSystemUpdated => {
276 this.schedule_update(false, window, cx);
277 }
278 GitEvent::ActiveRepositoryChanged | GitEvent::GitStateUpdated => {
279 this.active_repository = git_store.read(cx).active_repository();
280 this.schedule_update(true, window, cx);
281 }
282 },
283 )
284 .detach();
285
286 let scrollbar_state =
287 ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity());
288
289 let repository_selector =
290 cx.new(|cx| RepositorySelector::new(project.clone(), window, cx));
291
292 let mut git_panel = Self {
293 pending_remote_operations: Default::default(),
294 remote_operation_id: 0,
295 active_repository,
296 commit_editor,
297 suggested_commit_message: None,
298 conflicted_count: 0,
299 conflicted_staged_count: 0,
300 current_modifiers: window.modifiers(),
301 add_coauthors: true,
302 entries: Vec::new(),
303 focus_handle: cx.focus_handle(),
304 fs,
305 hide_scrollbar_task: None,
306 new_count: 0,
307 new_staged_count: 0,
308 pending: Vec::new(),
309 pending_commit: None,
310 pending_serialization: Task::ready(None),
311 project,
312 repository_selector,
313 scroll_handle,
314 scrollbar_state,
315 selected_entry: None,
316 show_scrollbar: false,
317 tracked_count: 0,
318 tracked_staged_count: 0,
319 update_visible_entries_task: Task::ready(()),
320 width: Some(px(360.)),
321 context_menu: None,
322 workspace,
323 modal_open: false,
324 };
325 git_panel.schedule_update(false, window, cx);
326 git_panel.show_scrollbar = git_panel.should_show_scrollbar(cx);
327 git_panel
328 })
329 }
330
331 pub fn entry_by_path(&self, path: &RepoPath) -> Option<usize> {
332 fn binary_search<F>(mut low: usize, mut high: usize, is_target: F) -> Option<usize>
333 where
334 F: Fn(usize) -> std::cmp::Ordering,
335 {
336 while low < high {
337 let mid = low + (high - low) / 2;
338 match is_target(mid) {
339 std::cmp::Ordering::Equal => return Some(mid),
340 std::cmp::Ordering::Less => low = mid + 1,
341 std::cmp::Ordering::Greater => high = mid,
342 }
343 }
344 None
345 }
346 if self.conflicted_count > 0 {
347 let conflicted_start = 1;
348 if let Some(ix) = binary_search(
349 conflicted_start,
350 conflicted_start + self.conflicted_count,
351 |ix| {
352 self.entries[ix]
353 .status_entry()
354 .unwrap()
355 .repo_path
356 .cmp(&path)
357 },
358 ) {
359 return Some(ix);
360 }
361 }
362 if self.tracked_count > 0 {
363 let tracked_start = if self.conflicted_count > 0 {
364 1 + self.conflicted_count
365 } else {
366 0
367 } + 1;
368 if let Some(ix) =
369 binary_search(tracked_start, tracked_start + self.tracked_count, |ix| {
370 self.entries[ix]
371 .status_entry()
372 .unwrap()
373 .repo_path
374 .cmp(&path)
375 })
376 {
377 return Some(ix);
378 }
379 }
380 if self.new_count > 0 {
381 let untracked_start = if self.conflicted_count > 0 {
382 1 + self.conflicted_count
383 } else {
384 0
385 } + if self.tracked_count > 0 {
386 1 + self.tracked_count
387 } else {
388 0
389 } + 1;
390 if let Some(ix) =
391 binary_search(untracked_start, untracked_start + self.new_count, |ix| {
392 self.entries[ix]
393 .status_entry()
394 .unwrap()
395 .repo_path
396 .cmp(&path)
397 })
398 {
399 return Some(ix);
400 }
401 }
402 None
403 }
404
405 pub fn select_entry_by_path(
406 &mut self,
407 path: ProjectPath,
408 _: &mut Window,
409 cx: &mut Context<Self>,
410 ) {
411 let Some(git_repo) = self.active_repository.as_ref() else {
412 return;
413 };
414 let Some(repo_path) = git_repo.read(cx).project_path_to_repo_path(&path) else {
415 return;
416 };
417 let Some(ix) = self.entry_by_path(&repo_path) else {
418 return;
419 };
420 self.selected_entry = Some(ix);
421 cx.notify();
422 }
423
424 fn start_remote_operation(&mut self) -> RemoteOperationGuard {
425 let id = post_inc(&mut self.remote_operation_id);
426 self.pending_remote_operations.borrow_mut().insert(id);
427
428 RemoteOperationGuard {
429 id,
430 pending_remote_operations: self.pending_remote_operations.clone(),
431 }
432 }
433
434 fn serialize(&mut self, cx: &mut Context<Self>) {
435 let width = self.width;
436 self.pending_serialization = cx.background_spawn(
437 async move {
438 KEY_VALUE_STORE
439 .write_kvp(
440 GIT_PANEL_KEY.into(),
441 serde_json::to_string(&SerializedGitPanel { width })?,
442 )
443 .await?;
444 anyhow::Ok(())
445 }
446 .log_err(),
447 );
448 }
449
450 pub(crate) fn set_modal_open(&mut self, open: bool, cx: &mut Context<Self>) {
451 self.modal_open = open;
452 cx.notify();
453 }
454
455 fn dispatch_context(&self, window: &mut Window, cx: &Context<Self>) -> KeyContext {
456 let mut dispatch_context = KeyContext::new_with_defaults();
457 dispatch_context.add("GitPanel");
458
459 if self.is_focused(window, cx) {
460 dispatch_context.add("menu");
461 dispatch_context.add("ChangesList");
462 }
463
464 if self.commit_editor.read(cx).is_focused(window) {
465 dispatch_context.add("CommitEditor");
466 }
467
468 dispatch_context
469 }
470
471 fn is_focused(&self, window: &Window, cx: &Context<Self>) -> bool {
472 window
473 .focused(cx)
474 .map_or(false, |focused| self.focus_handle == focused)
475 }
476
477 fn close_panel(&mut self, _: &Close, _window: &mut Window, cx: &mut Context<Self>) {
478 cx.emit(PanelEvent::Close);
479 }
480
481 fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
482 if !self.focus_handle.contains_focused(window, cx) {
483 cx.emit(Event::Focus);
484 }
485 }
486
487 fn show_scrollbar(&self, cx: &mut Context<Self>) -> ShowScrollbar {
488 GitPanelSettings::get_global(cx)
489 .scrollbar
490 .show
491 .unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show)
492 }
493
494 fn should_show_scrollbar(&self, cx: &mut Context<Self>) -> bool {
495 let show = self.show_scrollbar(cx);
496 match show {
497 ShowScrollbar::Auto => true,
498 ShowScrollbar::System => true,
499 ShowScrollbar::Always => true,
500 ShowScrollbar::Never => false,
501 }
502 }
503
504 fn should_autohide_scrollbar(&self, cx: &mut Context<Self>) -> bool {
505 let show = self.show_scrollbar(cx);
506 match show {
507 ShowScrollbar::Auto => true,
508 ShowScrollbar::System => cx
509 .try_global::<ScrollbarAutoHide>()
510 .map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),
511 ShowScrollbar::Always => false,
512 ShowScrollbar::Never => true,
513 }
514 }
515
516 fn hide_scrollbar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
517 const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
518 if !self.should_autohide_scrollbar(cx) {
519 return;
520 }
521 self.hide_scrollbar_task = Some(cx.spawn_in(window, |panel, mut cx| async move {
522 cx.background_executor()
523 .timer(SCROLLBAR_SHOW_INTERVAL)
524 .await;
525 panel
526 .update(&mut cx, |panel, cx| {
527 panel.show_scrollbar = false;
528 cx.notify();
529 })
530 .log_err();
531 }))
532 }
533
534 fn handle_modifiers_changed(
535 &mut self,
536 event: &ModifiersChangedEvent,
537 _: &mut Window,
538 cx: &mut Context<Self>,
539 ) {
540 self.current_modifiers = event.modifiers;
541 cx.notify();
542 }
543
544 fn scroll_to_selected_entry(&mut self, cx: &mut Context<Self>) {
545 if let Some(selected_entry) = self.selected_entry {
546 self.scroll_handle
547 .scroll_to_item(selected_entry, ScrollStrategy::Center);
548 }
549
550 cx.notify();
551 }
552
553 fn select_first(&mut self, _: &SelectFirst, _window: &mut Window, cx: &mut Context<Self>) {
554 if self.entries.first().is_some() {
555 self.selected_entry = Some(1);
556 self.scroll_to_selected_entry(cx);
557 }
558 }
559
560 fn select_prev(&mut self, _: &SelectPrev, _window: &mut Window, cx: &mut Context<Self>) {
561 let item_count = self.entries.len();
562 if item_count == 0 {
563 return;
564 }
565
566 if let Some(selected_entry) = self.selected_entry {
567 let new_selected_entry = if selected_entry > 0 {
568 selected_entry - 1
569 } else {
570 selected_entry
571 };
572
573 if matches!(
574 self.entries.get(new_selected_entry),
575 Some(GitListEntry::Header(..))
576 ) {
577 if new_selected_entry > 0 {
578 self.selected_entry = Some(new_selected_entry - 1)
579 }
580 } else {
581 self.selected_entry = Some(new_selected_entry);
582 }
583
584 self.scroll_to_selected_entry(cx);
585 }
586
587 cx.notify();
588 }
589
590 fn select_next(&mut self, _: &SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
591 let item_count = self.entries.len();
592 if item_count == 0 {
593 return;
594 }
595
596 if let Some(selected_entry) = self.selected_entry {
597 let new_selected_entry = if selected_entry < item_count - 1 {
598 selected_entry + 1
599 } else {
600 selected_entry
601 };
602 if matches!(
603 self.entries.get(new_selected_entry),
604 Some(GitListEntry::Header(..))
605 ) {
606 self.selected_entry = Some(new_selected_entry + 1);
607 } else {
608 self.selected_entry = Some(new_selected_entry);
609 }
610
611 self.scroll_to_selected_entry(cx);
612 }
613
614 cx.notify();
615 }
616
617 fn select_last(&mut self, _: &SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
618 if self.entries.last().is_some() {
619 self.selected_entry = Some(self.entries.len() - 1);
620 self.scroll_to_selected_entry(cx);
621 }
622 }
623
624 fn focus_editor(&mut self, _: &FocusEditor, window: &mut Window, cx: &mut Context<Self>) {
625 self.commit_editor.update(cx, |editor, cx| {
626 window.focus(&editor.focus_handle(cx));
627 });
628 cx.notify();
629 }
630
631 fn select_first_entry_if_none(&mut self, cx: &mut Context<Self>) {
632 let have_entries = self
633 .active_repository
634 .as_ref()
635 .map_or(false, |active_repository| {
636 active_repository.read(cx).entry_count() > 0
637 });
638 if have_entries && self.selected_entry.is_none() {
639 self.selected_entry = Some(1);
640 self.scroll_to_selected_entry(cx);
641 cx.notify();
642 }
643 }
644
645 fn focus_changes_list(
646 &mut self,
647 _: &FocusChanges,
648 window: &mut Window,
649 cx: &mut Context<Self>,
650 ) {
651 self.select_first_entry_if_none(cx);
652
653 cx.focus_self(window);
654 cx.notify();
655 }
656
657 fn get_selected_entry(&self) -> Option<&GitListEntry> {
658 self.selected_entry.and_then(|i| self.entries.get(i))
659 }
660
661 fn open_diff(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
662 maybe!({
663 let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
664
665 self.workspace
666 .update(cx, |workspace, cx| {
667 ProjectDiff::deploy_at(workspace, Some(entry.clone()), window, cx);
668 })
669 .ok()
670 });
671 }
672
673 fn open_file(
674 &mut self,
675 _: &menu::SecondaryConfirm,
676 window: &mut Window,
677 cx: &mut Context<Self>,
678 ) {
679 maybe!({
680 let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
681 let active_repo = self.active_repository.as_ref()?;
682 let path = active_repo
683 .read(cx)
684 .repo_path_to_project_path(&entry.repo_path)?;
685 if entry.status.is_deleted() {
686 return None;
687 }
688
689 self.workspace
690 .update(cx, |workspace, cx| {
691 workspace
692 .open_path_preview(path, None, false, false, window, cx)
693 .detach_and_prompt_err("Failed to open file", window, cx, |e, _, _| {
694 Some(format!("{e}"))
695 });
696 })
697 .ok()
698 });
699 }
700
701 fn revert_selected(
702 &mut self,
703 _: &git::RestoreFile,
704 window: &mut Window,
705 cx: &mut Context<Self>,
706 ) {
707 maybe!({
708 let list_entry = self.entries.get(self.selected_entry?)?.clone();
709 let entry = list_entry.status_entry()?;
710 self.revert_entry(&entry, window, cx);
711 Some(())
712 });
713 }
714
715 fn revert_entry(
716 &mut self,
717 entry: &GitStatusEntry,
718 window: &mut Window,
719 cx: &mut Context<Self>,
720 ) {
721 maybe!({
722 let active_repo = self.active_repository.clone()?;
723 let path = active_repo
724 .read(cx)
725 .repo_path_to_project_path(&entry.repo_path)?;
726 let workspace = self.workspace.clone();
727
728 if entry.status.is_staged() != Some(false) {
729 self.perform_stage(false, vec![entry.repo_path.clone()], cx);
730 }
731 let filename = path.path.file_name()?.to_string_lossy();
732
733 if !entry.status.is_created() {
734 self.perform_checkout(vec![entry.repo_path.clone()], cx);
735 } else {
736 let prompt = prompt(&format!("Trash {}?", filename), None, window, cx);
737 cx.spawn_in(window, |_, mut cx| async move {
738 match prompt.await? {
739 TrashCancel::Trash => {}
740 TrashCancel::Cancel => return Ok(()),
741 }
742 let task = workspace.update(&mut cx, |workspace, cx| {
743 workspace
744 .project()
745 .update(cx, |project, cx| project.delete_file(path, true, cx))
746 })?;
747 if let Some(task) = task {
748 task.await?;
749 }
750 Ok(())
751 })
752 .detach_and_prompt_err(
753 "Failed to trash file",
754 window,
755 cx,
756 |e, _, _| Some(format!("{e}")),
757 );
758 }
759 Some(())
760 });
761 }
762
763 fn perform_checkout(&mut self, repo_paths: Vec<RepoPath>, cx: &mut Context<Self>) {
764 let workspace = self.workspace.clone();
765 let Some(active_repository) = self.active_repository.clone() else {
766 return;
767 };
768
769 let op_id = self.pending.iter().map(|p| p.op_id).max().unwrap_or(0) + 1;
770 self.pending.push(PendingOperation {
771 op_id,
772 target_status: TargetStatus::Reverted,
773 repo_paths: repo_paths.iter().cloned().collect(),
774 finished: false,
775 });
776 self.update_visible_entries(cx);
777 let task = cx.spawn(|_, mut cx| async move {
778 let tasks: Vec<_> = workspace.update(&mut cx, |workspace, cx| {
779 workspace.project().update(cx, |project, cx| {
780 repo_paths
781 .iter()
782 .filter_map(|repo_path| {
783 let path = active_repository
784 .read(cx)
785 .repo_path_to_project_path(&repo_path)?;
786 Some(project.open_buffer(path, cx))
787 })
788 .collect()
789 })
790 })?;
791
792 let buffers = futures::future::join_all(tasks).await;
793
794 active_repository
795 .update(&mut cx, |repo, _| repo.checkout_files("HEAD", repo_paths))?
796 .await??;
797
798 let tasks: Vec<_> = cx.update(|cx| {
799 buffers
800 .iter()
801 .filter_map(|buffer| {
802 buffer.as_ref().ok()?.update(cx, |buffer, cx| {
803 buffer.is_dirty().then(|| buffer.reload(cx))
804 })
805 })
806 .collect()
807 })?;
808
809 futures::future::join_all(tasks).await;
810
811 Ok(())
812 });
813
814 cx.spawn(|this, mut cx| async move {
815 let result = task.await;
816
817 this.update(&mut cx, |this, cx| {
818 for pending in this.pending.iter_mut() {
819 if pending.op_id == op_id {
820 pending.finished = true;
821 if result.is_err() {
822 pending.target_status = TargetStatus::Unchanged;
823 this.update_visible_entries(cx);
824 }
825 break;
826 }
827 }
828 result
829 .map_err(|e| {
830 this.show_err_toast(e, cx);
831 })
832 .ok();
833 })
834 .ok();
835 })
836 .detach();
837 }
838
839 fn discard_tracked_changes(
840 &mut self,
841 _: &RestoreTrackedFiles,
842 window: &mut Window,
843 cx: &mut Context<Self>,
844 ) {
845 let entries = self
846 .entries
847 .iter()
848 .filter_map(|entry| entry.status_entry().cloned())
849 .filter(|status_entry| !status_entry.status.is_created())
850 .collect::<Vec<_>>();
851
852 match entries.len() {
853 0 => return,
854 1 => return self.revert_entry(&entries[0], window, cx),
855 _ => {}
856 }
857 let mut details = entries
858 .iter()
859 .filter_map(|entry| entry.repo_path.0.file_name())
860 .map(|filename| filename.to_string_lossy())
861 .take(5)
862 .join("\n");
863 if entries.len() > 5 {
864 details.push_str(&format!("\nand {} more…", entries.len() - 5))
865 }
866
867 #[derive(strum::EnumIter, strum::VariantNames)]
868 #[strum(serialize_all = "title_case")]
869 enum DiscardCancel {
870 DiscardTrackedChanges,
871 Cancel,
872 }
873 let prompt = prompt(
874 "Discard changes to these files?",
875 Some(&details),
876 window,
877 cx,
878 );
879 cx.spawn(|this, mut cx| async move {
880 match prompt.await {
881 Ok(DiscardCancel::DiscardTrackedChanges) => {
882 this.update(&mut cx, |this, cx| {
883 let repo_paths = entries.into_iter().map(|entry| entry.repo_path).collect();
884 this.perform_checkout(repo_paths, cx);
885 })
886 .ok();
887 }
888 _ => {
889 return;
890 }
891 }
892 })
893 .detach();
894 }
895
896 fn clean_all(&mut self, _: &TrashUntrackedFiles, window: &mut Window, cx: &mut Context<Self>) {
897 let workspace = self.workspace.clone();
898 let Some(active_repo) = self.active_repository.clone() else {
899 return;
900 };
901 let to_delete = self
902 .entries
903 .iter()
904 .filter_map(|entry| entry.status_entry())
905 .filter(|status_entry| status_entry.status.is_created())
906 .cloned()
907 .collect::<Vec<_>>();
908
909 match to_delete.len() {
910 0 => return,
911 1 => return self.revert_entry(&to_delete[0], window, cx),
912 _ => {}
913 };
914
915 let mut details = to_delete
916 .iter()
917 .map(|entry| {
918 entry
919 .repo_path
920 .0
921 .file_name()
922 .map(|f| f.to_string_lossy())
923 .unwrap_or_default()
924 })
925 .take(5)
926 .join("\n");
927
928 if to_delete.len() > 5 {
929 details.push_str(&format!("\nand {} more…", to_delete.len() - 5))
930 }
931
932 let prompt = prompt("Trash these files?", Some(&details), window, cx);
933 cx.spawn_in(window, |this, mut cx| async move {
934 match prompt.await? {
935 TrashCancel::Trash => {}
936 TrashCancel::Cancel => return Ok(()),
937 }
938 let tasks = workspace.update(&mut cx, |workspace, cx| {
939 to_delete
940 .iter()
941 .filter_map(|entry| {
942 workspace.project().update(cx, |project, cx| {
943 let project_path = active_repo
944 .read(cx)
945 .repo_path_to_project_path(&entry.repo_path)?;
946 project.delete_file(project_path, true, cx)
947 })
948 })
949 .collect::<Vec<_>>()
950 })?;
951 let to_unstage = to_delete
952 .into_iter()
953 .filter_map(|entry| {
954 if entry.status.is_staged() != Some(false) {
955 Some(entry.repo_path.clone())
956 } else {
957 None
958 }
959 })
960 .collect();
961 this.update(&mut cx, |this, cx| {
962 this.perform_stage(false, to_unstage, cx)
963 })?;
964 for task in tasks {
965 task.await?;
966 }
967 Ok(())
968 })
969 .detach_and_prompt_err("Failed to trash files", window, cx, |e, _, _| {
970 Some(format!("{e}"))
971 });
972 }
973
974 fn stage_all(&mut self, _: &StageAll, _window: &mut Window, cx: &mut Context<Self>) {
975 let repo_paths = self
976 .entries
977 .iter()
978 .filter_map(|entry| entry.status_entry())
979 .filter(|status_entry| status_entry.is_staged != Some(true))
980 .map(|status_entry| status_entry.repo_path.clone())
981 .collect::<Vec<_>>();
982 self.perform_stage(true, repo_paths, cx);
983 }
984
985 fn unstage_all(&mut self, _: &UnstageAll, _window: &mut Window, cx: &mut Context<Self>) {
986 let repo_paths = self
987 .entries
988 .iter()
989 .filter_map(|entry| entry.status_entry())
990 .filter(|status_entry| status_entry.is_staged != Some(false))
991 .map(|status_entry| status_entry.repo_path.clone())
992 .collect::<Vec<_>>();
993 self.perform_stage(false, repo_paths, cx);
994 }
995
996 fn toggle_staged_for_entry(
997 &mut self,
998 entry: &GitListEntry,
999 _window: &mut Window,
1000 cx: &mut Context<Self>,
1001 ) {
1002 let Some(active_repository) = self.active_repository.as_ref() else {
1003 return;
1004 };
1005 let (stage, repo_paths) = match entry {
1006 GitListEntry::GitStatusEntry(status_entry) => {
1007 if status_entry.status.is_staged().unwrap_or(false) {
1008 (false, vec![status_entry.repo_path.clone()])
1009 } else {
1010 (true, vec![status_entry.repo_path.clone()])
1011 }
1012 }
1013 GitListEntry::Header(section) => {
1014 let goal_staged_state = !self.header_state(section.header).selected();
1015 let repository = active_repository.read(cx);
1016 let entries = self
1017 .entries
1018 .iter()
1019 .filter_map(|entry| entry.status_entry())
1020 .filter(|status_entry| {
1021 section.contains(&status_entry, repository)
1022 && status_entry.is_staged != Some(goal_staged_state)
1023 })
1024 .map(|status_entry| status_entry.repo_path.clone())
1025 .collect::<Vec<_>>();
1026
1027 (goal_staged_state, entries)
1028 }
1029 };
1030 self.perform_stage(stage, repo_paths, cx);
1031 }
1032
1033 fn perform_stage(&mut self, stage: bool, repo_paths: Vec<RepoPath>, cx: &mut Context<Self>) {
1034 let Some(active_repository) = self.active_repository.clone() else {
1035 return;
1036 };
1037 let op_id = self.pending.iter().map(|p| p.op_id).max().unwrap_or(0) + 1;
1038 self.pending.push(PendingOperation {
1039 op_id,
1040 target_status: if stage {
1041 TargetStatus::Staged
1042 } else {
1043 TargetStatus::Unstaged
1044 },
1045 repo_paths: repo_paths.iter().cloned().collect(),
1046 finished: false,
1047 });
1048 let repo_paths = repo_paths.clone();
1049 let repository = active_repository.read(cx);
1050 self.update_counts(repository);
1051 cx.notify();
1052
1053 cx.spawn({
1054 |this, mut cx| async move {
1055 let result = cx
1056 .update(|cx| {
1057 if stage {
1058 active_repository
1059 .update(cx, |repo, cx| repo.stage_entries(repo_paths.clone(), cx))
1060 } else {
1061 active_repository
1062 .update(cx, |repo, cx| repo.unstage_entries(repo_paths.clone(), cx))
1063 }
1064 })?
1065 .await;
1066
1067 this.update(&mut cx, |this, cx| {
1068 for pending in this.pending.iter_mut() {
1069 if pending.op_id == op_id {
1070 pending.finished = true
1071 }
1072 }
1073 result
1074 .map_err(|e| {
1075 this.show_err_toast(e, cx);
1076 })
1077 .ok();
1078 cx.notify();
1079 })
1080 }
1081 })
1082 .detach();
1083 }
1084
1085 pub fn total_staged_count(&self) -> usize {
1086 self.tracked_staged_count + self.new_staged_count + self.conflicted_staged_count
1087 }
1088
1089 pub fn commit_message_buffer(&self, cx: &App) -> Entity<Buffer> {
1090 self.commit_editor
1091 .read(cx)
1092 .buffer()
1093 .read(cx)
1094 .as_singleton()
1095 .unwrap()
1096 .clone()
1097 }
1098
1099 fn toggle_staged_for_selected(
1100 &mut self,
1101 _: &git::ToggleStaged,
1102 window: &mut Window,
1103 cx: &mut Context<Self>,
1104 ) {
1105 if let Some(selected_entry) = self.get_selected_entry().cloned() {
1106 self.toggle_staged_for_entry(&selected_entry, window, cx);
1107 }
1108 }
1109
1110 fn commit(&mut self, _: &git::Commit, window: &mut Window, cx: &mut Context<Self>) {
1111 if self
1112 .commit_editor
1113 .focus_handle(cx)
1114 .contains_focused(window, cx)
1115 {
1116 self.commit_changes(window, cx)
1117 } else {
1118 cx.propagate();
1119 }
1120 }
1121
1122 pub(crate) fn commit_changes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1123 let Some(active_repository) = self.active_repository.clone() else {
1124 return;
1125 };
1126 let error_spawn = |message, window: &mut Window, cx: &mut App| {
1127 let prompt = window.prompt(PromptLevel::Warning, message, None, &["Ok"], cx);
1128 cx.spawn(|_| async move {
1129 prompt.await.ok();
1130 })
1131 .detach();
1132 };
1133
1134 if self.has_unstaged_conflicts() {
1135 error_spawn(
1136 "There are still conflicts. You must stage these before committing",
1137 window,
1138 cx,
1139 );
1140 return;
1141 }
1142
1143 let mut message = self.commit_editor.read(cx).text(cx);
1144 if message.trim().is_empty() {
1145 self.commit_editor.read(cx).focus_handle(cx).focus(window);
1146 return;
1147 }
1148 if self.add_coauthors {
1149 self.fill_co_authors(&mut message, cx);
1150 }
1151
1152 let task = if self.has_staged_changes() {
1153 // Repository serializes all git operations, so we can just send a commit immediately
1154 let commit_task = active_repository.read(cx).commit(message.into(), None);
1155 cx.background_spawn(async move { commit_task.await? })
1156 } else {
1157 let changed_files = self
1158 .entries
1159 .iter()
1160 .filter_map(|entry| entry.status_entry())
1161 .filter(|status_entry| !status_entry.status.is_created())
1162 .map(|status_entry| status_entry.repo_path.clone())
1163 .collect::<Vec<_>>();
1164
1165 if changed_files.is_empty() {
1166 error_spawn("No changes to commit", window, cx);
1167 return;
1168 }
1169
1170 let stage_task =
1171 active_repository.update(cx, |repo, cx| repo.stage_entries(changed_files, cx));
1172 cx.spawn(|_, mut cx| async move {
1173 stage_task.await?;
1174 let commit_task = active_repository
1175 .update(&mut cx, |repo, _| repo.commit(message.into(), None))?;
1176 commit_task.await?
1177 })
1178 };
1179 let task = cx.spawn_in(window, |this, mut cx| async move {
1180 let result = task.await;
1181 this.update_in(&mut cx, |this, window, cx| {
1182 this.pending_commit.take();
1183 match result {
1184 Ok(()) => {
1185 this.commit_editor
1186 .update(cx, |editor, cx| editor.clear(window, cx));
1187 }
1188 Err(e) => this.show_err_toast(e, cx),
1189 }
1190 })
1191 .ok();
1192 });
1193
1194 self.pending_commit = Some(task);
1195 }
1196
1197 fn uncommit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1198 let Some(repo) = self.active_repository.clone() else {
1199 return;
1200 };
1201
1202 // TODO: Use git merge-base to find the upstream and main branch split
1203 let confirmation = Task::ready(true);
1204 // let confirmation = if self.commit_editor.read(cx).is_empty(cx) {
1205 // Task::ready(true)
1206 // } else {
1207 // let prompt = window.prompt(
1208 // PromptLevel::Warning,
1209 // "Uncomitting will replace the current commit message with the previous commit's message",
1210 // None,
1211 // &["Ok", "Cancel"],
1212 // cx,
1213 // );
1214 // cx.spawn(|_, _| async move { prompt.await.is_ok_and(|i| i == 0) })
1215 // };
1216
1217 let prior_head = self.load_commit_details("HEAD", cx);
1218
1219 let task = cx.spawn_in(window, |this, mut cx| async move {
1220 let result = maybe!(async {
1221 if !confirmation.await {
1222 Ok(None)
1223 } else {
1224 let prior_head = prior_head.await?;
1225
1226 repo.update(&mut cx, |repo, _| repo.reset("HEAD^", ResetMode::Soft))?
1227 .await??;
1228
1229 Ok(Some(prior_head))
1230 }
1231 })
1232 .await;
1233
1234 this.update_in(&mut cx, |this, window, cx| {
1235 this.pending_commit.take();
1236 match result {
1237 Ok(None) => {}
1238 Ok(Some(prior_commit)) => {
1239 this.commit_editor.update(cx, |editor, cx| {
1240 editor.set_text(prior_commit.message, window, cx)
1241 });
1242 }
1243 Err(e) => this.show_err_toast(e, cx),
1244 }
1245 })
1246 .ok();
1247 });
1248
1249 self.pending_commit = Some(task);
1250 }
1251
1252 /// Suggests a commit message based on the changed files and their statuses
1253 pub fn suggest_commit_message(&self) -> Option<String> {
1254 let entries = self
1255 .entries
1256 .iter()
1257 .filter_map(|entry| {
1258 if let GitListEntry::GitStatusEntry(status_entry) = entry {
1259 Some(status_entry)
1260 } else {
1261 None
1262 }
1263 })
1264 .collect::<Vec<&GitStatusEntry>>();
1265
1266 if entries.is_empty() {
1267 None
1268 } else if entries.len() == 1 {
1269 let entry = &entries[0];
1270 let file_name = entry
1271 .repo_path
1272 .file_name()
1273 .unwrap_or_default()
1274 .to_string_lossy();
1275
1276 if entry.status.is_deleted() {
1277 Some(format!("Delete {}", file_name))
1278 } else if entry.status.is_created() {
1279 Some(format!("Create {}", file_name))
1280 } else if entry.status.is_modified() {
1281 Some(format!("Update {}", file_name))
1282 } else {
1283 None
1284 }
1285 } else {
1286 None
1287 }
1288 }
1289
1290 fn update_editor_placeholder(&mut self, cx: &mut Context<Self>) {
1291 let suggested_commit_message = self.suggest_commit_message();
1292 self.suggested_commit_message = suggested_commit_message.clone();
1293
1294 if let Some(suggested_commit_message) = suggested_commit_message {
1295 self.commit_editor.update(cx, |editor, cx| {
1296 editor.set_placeholder_text(Arc::from(suggested_commit_message), cx)
1297 });
1298 }
1299
1300 cx.notify();
1301 }
1302
1303 fn fetch(&mut self, _: &git::Fetch, _window: &mut Window, cx: &mut Context<Self>) {
1304 let Some(repo) = self.active_repository.clone() else {
1305 return;
1306 };
1307 let guard = self.start_remote_operation();
1308 let fetch = repo.read(cx).fetch();
1309 cx.spawn(|_, _| async move {
1310 fetch.await??;
1311 drop(guard);
1312 anyhow::Ok(())
1313 })
1314 .detach_and_log_err(cx);
1315 }
1316
1317 fn pull(&mut self, _: &git::Pull, window: &mut Window, cx: &mut Context<Self>) {
1318 let guard = self.start_remote_operation();
1319 let remote = self.get_current_remote(window, cx);
1320 cx.spawn(move |this, mut cx| async move {
1321 let remote = remote.await?;
1322
1323 this.update(&mut cx, |this, cx| {
1324 let Some(repo) = this.active_repository.clone() else {
1325 return Err(anyhow::anyhow!("No active repository"));
1326 };
1327
1328 let Some(branch) = repo.read(cx).current_branch() else {
1329 return Err(anyhow::anyhow!("No active branch"));
1330 };
1331
1332 Ok(repo.read(cx).pull(branch.name.clone(), remote.name))
1333 })??
1334 .await??;
1335
1336 drop(guard);
1337 anyhow::Ok(())
1338 })
1339 .detach_and_log_err(cx);
1340 }
1341
1342 fn push(&mut self, action: &git::Push, window: &mut Window, cx: &mut Context<Self>) {
1343 let guard = self.start_remote_operation();
1344 let options = action.options;
1345 let remote = self.get_current_remote(window, cx);
1346 cx.spawn(move |this, mut cx| async move {
1347 let remote = remote.await?;
1348
1349 this.update(&mut cx, |this, cx| {
1350 let Some(repo) = this.active_repository.clone() else {
1351 return Err(anyhow::anyhow!("No active repository"));
1352 };
1353
1354 let Some(branch) = repo.read(cx).current_branch() else {
1355 return Err(anyhow::anyhow!("No active branch"));
1356 };
1357
1358 Ok(repo
1359 .read(cx)
1360 .push(branch.name.clone(), remote.name, options))
1361 })??
1362 .await??;
1363
1364 drop(guard);
1365 anyhow::Ok(())
1366 })
1367 .detach_and_log_err(cx);
1368 }
1369
1370 fn get_current_remote(
1371 &mut self,
1372 window: &mut Window,
1373 cx: &mut Context<Self>,
1374 ) -> impl Future<Output = Result<Remote>> {
1375 let repo = self.active_repository.clone();
1376 let workspace = self.workspace.clone();
1377 let mut cx = window.to_async(cx);
1378
1379 async move {
1380 let Some(repo) = repo else {
1381 return Err(anyhow::anyhow!("No active repository"));
1382 };
1383
1384 let mut current_remotes: Vec<Remote> = repo
1385 .update(&mut cx, |repo, cx| {
1386 let Some(current_branch) = repo.current_branch() else {
1387 return Err(anyhow::anyhow!("No active branch"));
1388 };
1389
1390 Ok(repo.get_remotes(Some(current_branch.name.to_string()), cx))
1391 })??
1392 .await?;
1393
1394 if current_remotes.len() == 0 {
1395 return Err(anyhow::anyhow!("No active remote"));
1396 } else if current_remotes.len() == 1 {
1397 return Ok(current_remotes.pop().unwrap());
1398 } else {
1399 let current_remotes: Vec<_> = current_remotes
1400 .into_iter()
1401 .map(|remotes| remotes.name)
1402 .collect();
1403 let selection = cx
1404 .update(|window, cx| {
1405 picker_prompt::prompt(
1406 "Pick which remote to push to",
1407 current_remotes.clone(),
1408 workspace,
1409 window,
1410 cx,
1411 )
1412 })?
1413 .await?;
1414
1415 return Ok(Remote {
1416 name: current_remotes[selection].clone(),
1417 });
1418 }
1419 }
1420 }
1421
1422 fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
1423 let mut new_co_authors = Vec::new();
1424 let project = self.project.read(cx);
1425
1426 let Some(room) = self
1427 .workspace
1428 .upgrade()
1429 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
1430 else {
1431 return Vec::default();
1432 };
1433
1434 let room = room.read(cx);
1435
1436 for (peer_id, collaborator) in project.collaborators() {
1437 if collaborator.is_host {
1438 continue;
1439 }
1440
1441 let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
1442 continue;
1443 };
1444 if participant.can_write() && participant.user.email.is_some() {
1445 let email = participant.user.email.clone().unwrap();
1446
1447 new_co_authors.push((
1448 participant
1449 .user
1450 .name
1451 .clone()
1452 .unwrap_or_else(|| participant.user.github_login.clone()),
1453 email,
1454 ))
1455 }
1456 }
1457 if !project.is_local() && !project.is_read_only(cx) {
1458 if let Some(user) = room.local_participant_user(cx) {
1459 if let Some(email) = user.email.clone() {
1460 new_co_authors.push((
1461 user.name
1462 .clone()
1463 .unwrap_or_else(|| user.github_login.clone()),
1464 email.clone(),
1465 ))
1466 }
1467 }
1468 }
1469 new_co_authors
1470 }
1471
1472 fn toggle_fill_co_authors(
1473 &mut self,
1474 _: &ToggleFillCoAuthors,
1475 _: &mut Window,
1476 cx: &mut Context<Self>,
1477 ) {
1478 self.add_coauthors = !self.add_coauthors;
1479 cx.notify();
1480 }
1481
1482 fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
1483 const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
1484
1485 let existing_text = message.to_ascii_lowercase();
1486 let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
1487 let mut ends_with_co_authors = false;
1488 let existing_co_authors = existing_text
1489 .lines()
1490 .filter_map(|line| {
1491 let line = line.trim();
1492 if line.starts_with(&lowercase_co_author_prefix) {
1493 ends_with_co_authors = true;
1494 Some(line)
1495 } else {
1496 ends_with_co_authors = false;
1497 None
1498 }
1499 })
1500 .collect::<HashSet<_>>();
1501
1502 let new_co_authors = self
1503 .potential_co_authors(cx)
1504 .into_iter()
1505 .filter(|(_, email)| {
1506 !existing_co_authors
1507 .iter()
1508 .any(|existing| existing.contains(email.as_str()))
1509 })
1510 .collect::<Vec<_>>();
1511
1512 if new_co_authors.is_empty() {
1513 return;
1514 }
1515
1516 if !ends_with_co_authors {
1517 message.push('\n');
1518 }
1519 for (name, email) in new_co_authors {
1520 message.push('\n');
1521 message.push_str(CO_AUTHOR_PREFIX);
1522 message.push_str(&name);
1523 message.push_str(" <");
1524 message.push_str(&email);
1525 message.push('>');
1526 }
1527 message.push('\n');
1528 }
1529
1530 fn schedule_update(
1531 &mut self,
1532 clear_pending: bool,
1533 window: &mut Window,
1534 cx: &mut Context<Self>,
1535 ) {
1536 let handle = cx.entity().downgrade();
1537 self.reopen_commit_buffer(window, cx);
1538 self.update_visible_entries_task = cx.spawn_in(window, |_, mut cx| async move {
1539 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
1540 if let Some(git_panel) = handle.upgrade() {
1541 git_panel
1542 .update_in(&mut cx, |git_panel, _, cx| {
1543 if clear_pending {
1544 git_panel.clear_pending();
1545 }
1546 git_panel.update_visible_entries(cx);
1547 git_panel.update_editor_placeholder(cx);
1548 })
1549 .ok();
1550 }
1551 });
1552 }
1553
1554 fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1555 let Some(active_repo) = self.active_repository.as_ref() else {
1556 return;
1557 };
1558 let load_buffer = active_repo.update(cx, |active_repo, cx| {
1559 let project = self.project.read(cx);
1560 active_repo.open_commit_buffer(
1561 Some(project.languages().clone()),
1562 project.buffer_store().clone(),
1563 cx,
1564 )
1565 });
1566
1567 cx.spawn_in(window, |git_panel, mut cx| async move {
1568 let buffer = load_buffer.await?;
1569 git_panel.update_in(&mut cx, |git_panel, window, cx| {
1570 if git_panel
1571 .commit_editor
1572 .read(cx)
1573 .buffer()
1574 .read(cx)
1575 .as_singleton()
1576 .as_ref()
1577 != Some(&buffer)
1578 {
1579 git_panel.commit_editor = cx.new(|cx| {
1580 commit_message_editor(buffer, git_panel.project.clone(), true, window, cx)
1581 });
1582 }
1583 })
1584 })
1585 .detach_and_log_err(cx);
1586 }
1587
1588 fn clear_pending(&mut self) {
1589 self.pending.retain(|v| !v.finished)
1590 }
1591
1592 fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
1593 self.entries.clear();
1594 let mut changed_entries = Vec::new();
1595 let mut new_entries = Vec::new();
1596 let mut conflict_entries = Vec::new();
1597
1598 let Some(repo) = self.active_repository.as_ref() else {
1599 // Just clear entries if no repository is active.
1600 cx.notify();
1601 return;
1602 };
1603
1604 // First pass - collect all paths
1605 let repo = repo.read(cx);
1606
1607 // Second pass - create entries with proper depth calculation
1608 for entry in repo.status() {
1609 let is_conflict = repo.has_conflict(&entry.repo_path);
1610 let is_new = entry.status.is_created();
1611 let is_staged = entry.status.is_staged();
1612
1613 if self.pending.iter().any(|pending| {
1614 pending.target_status == TargetStatus::Reverted
1615 && !pending.finished
1616 && pending.repo_paths.contains(&entry.repo_path)
1617 }) {
1618 continue;
1619 }
1620
1621 let entry = GitStatusEntry {
1622 repo_path: entry.repo_path.clone(),
1623 status: entry.status,
1624 is_staged,
1625 };
1626
1627 if is_conflict {
1628 conflict_entries.push(entry);
1629 } else if is_new {
1630 new_entries.push(entry);
1631 } else {
1632 changed_entries.push(entry);
1633 }
1634 }
1635
1636 if conflict_entries.len() > 0 {
1637 self.entries.push(GitListEntry::Header(GitHeaderEntry {
1638 header: Section::Conflict,
1639 }));
1640 self.entries.extend(
1641 conflict_entries
1642 .into_iter()
1643 .map(GitListEntry::GitStatusEntry),
1644 );
1645 }
1646
1647 if changed_entries.len() > 0 {
1648 self.entries.push(GitListEntry::Header(GitHeaderEntry {
1649 header: Section::Tracked,
1650 }));
1651 self.entries.extend(
1652 changed_entries
1653 .into_iter()
1654 .map(GitListEntry::GitStatusEntry),
1655 );
1656 }
1657 if new_entries.len() > 0 {
1658 self.entries.push(GitListEntry::Header(GitHeaderEntry {
1659 header: Section::New,
1660 }));
1661 self.entries
1662 .extend(new_entries.into_iter().map(GitListEntry::GitStatusEntry));
1663 }
1664
1665 self.update_counts(repo);
1666
1667 self.select_first_entry_if_none(cx);
1668
1669 cx.notify();
1670 }
1671
1672 fn header_state(&self, header_type: Section) -> ToggleState {
1673 let (staged_count, count) = match header_type {
1674 Section::New => (self.new_staged_count, self.new_count),
1675 Section::Tracked => (self.tracked_staged_count, self.tracked_count),
1676 Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
1677 };
1678 if staged_count == 0 {
1679 ToggleState::Unselected
1680 } else if count == staged_count {
1681 ToggleState::Selected
1682 } else {
1683 ToggleState::Indeterminate
1684 }
1685 }
1686
1687 fn update_counts(&mut self, repo: &Repository) {
1688 self.conflicted_count = 0;
1689 self.conflicted_staged_count = 0;
1690 self.new_count = 0;
1691 self.tracked_count = 0;
1692 self.new_staged_count = 0;
1693 self.tracked_staged_count = 0;
1694 for entry in &self.entries {
1695 let Some(status_entry) = entry.status_entry() else {
1696 continue;
1697 };
1698 if repo.has_conflict(&status_entry.repo_path) {
1699 self.conflicted_count += 1;
1700 if self.entry_is_staged(status_entry) != Some(false) {
1701 self.conflicted_staged_count += 1;
1702 }
1703 } else if status_entry.status.is_created() {
1704 self.new_count += 1;
1705 if self.entry_is_staged(status_entry) != Some(false) {
1706 self.new_staged_count += 1;
1707 }
1708 } else {
1709 self.tracked_count += 1;
1710 if self.entry_is_staged(status_entry) != Some(false) {
1711 self.tracked_staged_count += 1;
1712 }
1713 }
1714 }
1715 }
1716
1717 fn entry_is_staged(&self, entry: &GitStatusEntry) -> Option<bool> {
1718 for pending in self.pending.iter().rev() {
1719 if pending.repo_paths.contains(&entry.repo_path) {
1720 match pending.target_status {
1721 TargetStatus::Staged => return Some(true),
1722 TargetStatus::Unstaged => return Some(false),
1723 TargetStatus::Reverted => continue,
1724 TargetStatus::Unchanged => continue,
1725 }
1726 }
1727 }
1728 entry.is_staged
1729 }
1730
1731 pub(crate) fn has_staged_changes(&self) -> bool {
1732 self.tracked_staged_count > 0
1733 || self.new_staged_count > 0
1734 || self.conflicted_staged_count > 0
1735 }
1736
1737 pub(crate) fn has_unstaged_changes(&self) -> bool {
1738 self.tracked_count > self.tracked_staged_count
1739 || self.new_count > self.new_staged_count
1740 || self.conflicted_count > self.conflicted_staged_count
1741 }
1742
1743 fn has_conflicts(&self) -> bool {
1744 self.conflicted_count > 0
1745 }
1746
1747 fn has_tracked_changes(&self) -> bool {
1748 self.tracked_count > 0
1749 }
1750
1751 pub fn has_unstaged_conflicts(&self) -> bool {
1752 self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
1753 }
1754
1755 fn show_err_toast(&self, e: anyhow::Error, cx: &mut App) {
1756 let Some(workspace) = self.workspace.upgrade() else {
1757 return;
1758 };
1759 let notif_id = NotificationId::Named("git-operation-error".into());
1760
1761 let message = e.to_string();
1762 workspace.update(cx, |workspace, cx| {
1763 let toast = Toast::new(notif_id, message).on_click("Open Zed Log", |window, cx| {
1764 window.dispatch_action(workspace::OpenLog.boxed_clone(), cx);
1765 });
1766 workspace.show_toast(toast, cx);
1767 });
1768 }
1769
1770 pub fn panel_button(
1771 &self,
1772 id: impl Into<SharedString>,
1773 label: impl Into<SharedString>,
1774 ) -> Button {
1775 let id = id.into().clone();
1776 let label = label.into().clone();
1777
1778 Button::new(id, label)
1779 .label_size(LabelSize::Small)
1780 .layer(ElevationIndex::ElevatedSurface)
1781 .size(ButtonSize::Compact)
1782 .style(ButtonStyle::Filled)
1783 }
1784
1785 pub fn indent_size(&self, window: &Window, cx: &mut Context<Self>) -> Pixels {
1786 Checkbox::container_size(cx).to_pixels(window.rem_size())
1787 }
1788
1789 pub fn render_divider(&self, _cx: &mut Context<Self>) -> impl IntoElement {
1790 h_flex()
1791 .items_center()
1792 .h(px(8.))
1793 .child(Divider::horizontal_dashed().color(DividerColor::Border))
1794 }
1795
1796 pub fn render_panel_header(
1797 &self,
1798 window: &mut Window,
1799 cx: &mut Context<Self>,
1800 ) -> Option<impl IntoElement> {
1801 let all_repositories = self
1802 .project
1803 .read(cx)
1804 .git_store()
1805 .read(cx)
1806 .all_repositories();
1807
1808 let has_repo_above = all_repositories.iter().any(|repo| {
1809 repo.read(cx)
1810 .repository_entry
1811 .work_directory
1812 .is_above_project()
1813 });
1814
1815 let has_visible_repo = all_repositories.len() > 0 || has_repo_above;
1816
1817 if has_visible_repo {
1818 Some(
1819 self.panel_header_container(window, cx)
1820 .child(
1821 Label::new("Repository")
1822 .size(LabelSize::Small)
1823 .color(Color::Muted),
1824 )
1825 .child(self.render_repository_selector(cx))
1826 .child(div().flex_grow()) // spacer
1827 .child(
1828 div()
1829 .h_flex()
1830 .gap_1()
1831 .children(self.render_spinner(cx))
1832 .children(self.render_sync_button(cx))
1833 .children(self.render_pull_button(cx))
1834 .child(
1835 Button::new("diff", "+/-")
1836 .tooltip(Tooltip::for_action_title("Open diff", &Diff))
1837 .on_click(|_, _, cx| {
1838 cx.defer(|cx| {
1839 cx.dispatch_action(&Diff);
1840 })
1841 }),
1842 )
1843 .child(self.render_overflow_menu()),
1844 ),
1845 )
1846 } else {
1847 None
1848 }
1849 }
1850
1851 pub fn render_spinner(&self, _cx: &mut Context<Self>) -> Option<impl IntoElement> {
1852 (!self.pending_remote_operations.borrow().is_empty()).then(|| {
1853 Icon::new(IconName::ArrowCircle)
1854 .size(IconSize::XSmall)
1855 .color(Color::Info)
1856 .with_animation(
1857 "arrow-circle",
1858 Animation::new(Duration::from_secs(2)).repeat(),
1859 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
1860 )
1861 .into_any_element()
1862 })
1863 }
1864
1865 pub fn render_overflow_menu(&self) -> impl IntoElement {
1866 PopoverMenu::new("overflow-menu")
1867 .trigger(IconButton::new("overflow-menu-trigger", IconName::Ellipsis))
1868 .menu(move |window, cx| Some(Self::panel_context_menu(window, cx)))
1869 .anchor(Corner::TopRight)
1870 }
1871
1872 pub fn render_sync_button(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
1873 let active_repository = self.project.read(cx).active_repository(cx);
1874 active_repository.as_ref().map(|_| {
1875 panel_filled_button("Fetch")
1876 .icon(IconName::ArrowCircle)
1877 .icon_size(IconSize::Small)
1878 .icon_color(Color::Muted)
1879 .icon_position(IconPosition::Start)
1880 .tooltip(Tooltip::for_action_title("git fetch", &git::Fetch))
1881 .on_click(
1882 cx.listener(move |this, _, window, cx| this.fetch(&git::Fetch, window, cx)),
1883 )
1884 .into_any_element()
1885 })
1886 }
1887
1888 pub fn render_pull_button(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
1889 let active_repository = self.project.read(cx).active_repository(cx);
1890 active_repository
1891 .as_ref()
1892 .and_then(|repo| repo.read(cx).current_branch())
1893 .and_then(|branch| {
1894 branch.upstream.as_ref().map(|upstream| {
1895 let status = &upstream.tracking;
1896
1897 let disabled = status.is_gone();
1898
1899 panel_filled_button(match status {
1900 git::repository::UpstreamTracking::Tracked(status) if status.behind > 0 => {
1901 format!("Pull ({})", status.behind)
1902 }
1903 _ => "Pull".to_string(),
1904 })
1905 .icon(IconName::ArrowDown)
1906 .icon_size(IconSize::Small)
1907 .icon_color(Color::Muted)
1908 .icon_position(IconPosition::Start)
1909 .disabled(status.is_gone())
1910 .tooltip(move |window, cx| {
1911 if disabled {
1912 Tooltip::simple("Upstream is gone", cx)
1913 } else {
1914 // TODO: Add <origin> and <branch> argument substitutions to this
1915 Tooltip::for_action("git pull", &git::Pull, window, cx)
1916 }
1917 })
1918 .on_click(
1919 cx.listener(move |this, _, window, cx| this.pull(&git::Pull, window, cx)),
1920 )
1921 .into_any_element()
1922 })
1923 })
1924 }
1925
1926 pub fn render_repository_selector(&self, cx: &mut Context<Self>) -> impl IntoElement {
1927 let active_repository = self.project.read(cx).active_repository(cx);
1928 let repository_display_name = active_repository
1929 .as_ref()
1930 .map(|repo| repo.read(cx).display_name(self.project.read(cx), cx))
1931 .unwrap_or_default();
1932
1933 RepositorySelectorPopoverMenu::new(
1934 self.repository_selector.clone(),
1935 ButtonLike::new("active-repository")
1936 .style(ButtonStyle::Subtle)
1937 .child(Label::new(repository_display_name).size(LabelSize::Small)),
1938 Tooltip::text("Select a repository"),
1939 )
1940 }
1941
1942 pub fn can_commit(&self) -> bool {
1943 (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
1944 }
1945
1946 pub fn can_stage_all(&self) -> bool {
1947 self.has_unstaged_changes()
1948 }
1949
1950 pub fn can_unstage_all(&self) -> bool {
1951 self.has_staged_changes()
1952 }
1953
1954 pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
1955 let potential_co_authors = self.potential_co_authors(cx);
1956 if potential_co_authors.is_empty() {
1957 None
1958 } else {
1959 Some(
1960 IconButton::new("co-authors", IconName::Person)
1961 .icon_color(Color::Disabled)
1962 .selected_icon_color(Color::Selected)
1963 .toggle_state(self.add_coauthors)
1964 .tooltip(move |_, cx| {
1965 let title = format!(
1966 "Add co-authored-by:{}{}",
1967 if potential_co_authors.len() == 1 {
1968 ""
1969 } else {
1970 "\n"
1971 },
1972 potential_co_authors
1973 .iter()
1974 .map(|(name, email)| format!(" {} <{}>", name, email))
1975 .join("\n")
1976 );
1977 Tooltip::simple(title, cx)
1978 })
1979 .on_click(cx.listener(|this, _, _, cx| {
1980 this.add_coauthors = !this.add_coauthors;
1981 cx.notify();
1982 }))
1983 .into_any_element(),
1984 )
1985 }
1986 }
1987
1988 pub fn render_commit_editor(
1989 &self,
1990 window: &mut Window,
1991 cx: &mut Context<Self>,
1992 ) -> impl IntoElement {
1993 let editor = self.commit_editor.clone();
1994 let can_commit = self.can_commit()
1995 && self.pending_commit.is_none()
1996 && !editor.read(cx).is_empty(cx)
1997 && self.has_write_access(cx);
1998
1999 let panel_editor_style = panel_editor_style(true, window, cx);
2000 let enable_coauthors = self.render_co_authors(cx);
2001
2002 let tooltip = if self.has_staged_changes() {
2003 "git commit"
2004 } else {
2005 "git commit --all"
2006 };
2007 let title = if self.has_staged_changes() {
2008 "Commit"
2009 } else {
2010 "Commit Tracked"
2011 };
2012 let editor_focus_handle = self.commit_editor.focus_handle(cx);
2013
2014 let commit_button = panel_filled_button(title)
2015 .tooltip(move |window, cx| {
2016 Tooltip::for_action_in(tooltip, &Commit, &editor_focus_handle, window, cx)
2017 })
2018 .disabled(!can_commit)
2019 .on_click({
2020 cx.listener(move |this, _: &ClickEvent, window, cx| this.commit_changes(window, cx))
2021 });
2022
2023 let branch = self
2024 .active_repository
2025 .as_ref()
2026 .and_then(|repo| repo.read(cx).current_branch().map(|b| b.name.clone()))
2027 .unwrap_or_else(|| "<no branch>".into());
2028
2029 let branch_selector = Button::new("branch-selector", branch)
2030 .color(Color::Muted)
2031 .style(ButtonStyle::Subtle)
2032 .icon(IconName::GitBranch)
2033 .icon_size(IconSize::Small)
2034 .icon_color(Color::Muted)
2035 .size(ButtonSize::Compact)
2036 .icon_position(IconPosition::Start)
2037 .tooltip(Tooltip::for_action_title(
2038 "Switch Branch",
2039 &zed_actions::git::Branch,
2040 ))
2041 .on_click(cx.listener(|_, _, window, cx| {
2042 window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
2043 }))
2044 .style(ButtonStyle::Transparent);
2045
2046 let footer_size = px(32.);
2047 let gap = px(16.0);
2048
2049 let max_height = window.line_height() * 6. + gap + footer_size;
2050
2051 panel_editor_container(window, cx)
2052 .id("commit-editor-container")
2053 .relative()
2054 .h(max_height)
2055 .w_full()
2056 .border_t_1()
2057 .border_color(cx.theme().colors().border)
2058 .bg(cx.theme().colors().editor_background)
2059 .cursor_text()
2060 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
2061 window.focus(&this.commit_editor.focus_handle(cx));
2062 }))
2063 .when(!self.modal_open, |el| {
2064 el.child(EditorElement::new(&self.commit_editor, panel_editor_style))
2065 .child(
2066 h_flex()
2067 .absolute()
2068 .bottom_0()
2069 .left_2()
2070 .h(footer_size)
2071 .flex_none()
2072 .child(branch_selector),
2073 )
2074 .child(
2075 h_flex()
2076 .absolute()
2077 .bottom_0()
2078 .right_2()
2079 .h(footer_size)
2080 .flex_none()
2081 .children(enable_coauthors)
2082 .child(commit_button),
2083 )
2084 })
2085 }
2086
2087 fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2088 let active_repository = self.active_repository.as_ref()?;
2089 let branch = active_repository.read(cx).current_branch()?;
2090 let commit = branch.most_recent_commit.as_ref()?.clone();
2091
2092 let this = cx.entity();
2093 Some(
2094 h_flex()
2095 .items_center()
2096 .py_1p5()
2097 .px(px(8.))
2098 .bg(cx.theme().colors().background)
2099 .border_t_1()
2100 .border_color(cx.theme().colors().border)
2101 .gap_1p5()
2102 .child(
2103 div()
2104 .flex_grow()
2105 .overflow_hidden()
2106 .max_w(relative(0.6))
2107 .h_full()
2108 .child(
2109 Label::new(commit.subject.clone())
2110 .size(LabelSize::Small)
2111 .text_ellipsis(),
2112 )
2113 .id("commit-msg-hover")
2114 .hoverable_tooltip(move |window, cx| {
2115 GitPanelMessageTooltip::new(
2116 this.clone(),
2117 commit.sha.clone(),
2118 window,
2119 cx,
2120 )
2121 .into()
2122 }),
2123 )
2124 .child(div().flex_1())
2125 .child(
2126 panel_filled_button("Uncommit")
2127 .icon(IconName::Undo)
2128 .icon_size(IconSize::Small)
2129 .icon_color(Color::Muted)
2130 .icon_position(IconPosition::Start)
2131 .tooltip(Tooltip::for_action_title(
2132 if self.has_staged_changes() {
2133 "git reset HEAD^ --soft"
2134 } else {
2135 "git reset HEAD^"
2136 },
2137 &git::Uncommit,
2138 ))
2139 .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
2140 )
2141 .child(self.render_push_button(branch, cx)),
2142 )
2143 }
2144
2145 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
2146 h_flex()
2147 .h_full()
2148 .flex_grow()
2149 .justify_center()
2150 .items_center()
2151 .child(
2152 v_flex()
2153 .gap_3()
2154 .child(if self.active_repository.is_some() {
2155 "No changes to commit"
2156 } else {
2157 "No Git repositories"
2158 })
2159 .text_ui_sm(cx)
2160 .mx_auto()
2161 .text_color(Color::Placeholder.color(cx)),
2162 )
2163 }
2164
2165 fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
2166 let scroll_bar_style = self.show_scrollbar(cx);
2167 let show_container = matches!(scroll_bar_style, ShowScrollbar::Always);
2168
2169 if !self.should_show_scrollbar(cx)
2170 || !(self.show_scrollbar || self.scrollbar_state.is_dragging())
2171 {
2172 return None;
2173 }
2174
2175 Some(
2176 div()
2177 .id("git-panel-vertical-scroll")
2178 .occlude()
2179 .flex_none()
2180 .h_full()
2181 .cursor_default()
2182 .when(show_container, |this| this.pl_1().px_1p5())
2183 .when(!show_container, |this| {
2184 this.absolute().right_1().top_1().bottom_1().w(px(12.))
2185 })
2186 .on_mouse_move(cx.listener(|_, _, _, cx| {
2187 cx.notify();
2188 cx.stop_propagation()
2189 }))
2190 .on_hover(|_, _, cx| {
2191 cx.stop_propagation();
2192 })
2193 .on_any_mouse_down(|_, _, cx| {
2194 cx.stop_propagation();
2195 })
2196 .on_mouse_up(
2197 MouseButton::Left,
2198 cx.listener(|this, _, window, cx| {
2199 if !this.scrollbar_state.is_dragging()
2200 && !this.focus_handle.contains_focused(window, cx)
2201 {
2202 this.hide_scrollbar(window, cx);
2203 cx.notify();
2204 }
2205
2206 cx.stop_propagation();
2207 }),
2208 )
2209 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
2210 cx.notify();
2211 }))
2212 .children(Scrollbar::vertical(
2213 // percentage as f32..end_offset as f32,
2214 self.scrollbar_state.clone(),
2215 )),
2216 )
2217 }
2218
2219 pub fn render_buffer_header_controls(
2220 &self,
2221 entity: &Entity<Self>,
2222 file: &Arc<dyn File>,
2223 _: &Window,
2224 cx: &App,
2225 ) -> Option<AnyElement> {
2226 let repo = self.active_repository.as_ref()?.read(cx);
2227 let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
2228 let ix = self.entry_by_path(&repo_path)?;
2229 let entry = self.entries.get(ix)?;
2230
2231 let is_staged = self.entry_is_staged(entry.status_entry()?);
2232
2233 let checkbox = Checkbox::new("stage-file", is_staged.into())
2234 .disabled(!self.has_write_access(cx))
2235 .fill()
2236 .elevation(ElevationIndex::Surface)
2237 .on_click({
2238 let entry = entry.clone();
2239 let git_panel = entity.downgrade();
2240 move |_, window, cx| {
2241 git_panel
2242 .update(cx, |this, cx| {
2243 this.toggle_staged_for_entry(&entry, window, cx);
2244 cx.stop_propagation();
2245 })
2246 .ok();
2247 }
2248 });
2249 Some(
2250 h_flex()
2251 .id("start-slot")
2252 .text_lg()
2253 .child(checkbox)
2254 .on_mouse_down(MouseButton::Left, |_, _, cx| {
2255 // prevent the list item active state triggering when toggling checkbox
2256 cx.stop_propagation();
2257 })
2258 .into_any_element(),
2259 )
2260 }
2261
2262 fn render_entries(
2263 &self,
2264 has_write_access: bool,
2265 _: &Window,
2266 cx: &mut Context<Self>,
2267 ) -> impl IntoElement {
2268 let entry_count = self.entries.len();
2269
2270 v_flex()
2271 .size_full()
2272 .flex_grow()
2273 .overflow_hidden()
2274 .child(
2275 uniform_list(cx.entity().clone(), "entries", entry_count, {
2276 move |this, range, window, cx| {
2277 let mut items = Vec::with_capacity(range.end - range.start);
2278
2279 for ix in range {
2280 match &this.entries.get(ix) {
2281 Some(GitListEntry::GitStatusEntry(entry)) => {
2282 items.push(this.render_entry(
2283 ix,
2284 entry,
2285 has_write_access,
2286 window,
2287 cx,
2288 ));
2289 }
2290 Some(GitListEntry::Header(header)) => {
2291 items.push(this.render_list_header(
2292 ix,
2293 header,
2294 has_write_access,
2295 window,
2296 cx,
2297 ));
2298 }
2299 None => {}
2300 }
2301 }
2302
2303 items
2304 }
2305 })
2306 .size_full()
2307 .with_sizing_behavior(ListSizingBehavior::Infer)
2308 .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
2309 .track_scroll(self.scroll_handle.clone()),
2310 )
2311 .on_mouse_down(
2312 MouseButton::Right,
2313 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
2314 this.deploy_panel_context_menu(event.position, window, cx)
2315 }),
2316 )
2317 .children(self.render_scrollbar(cx))
2318 }
2319
2320 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
2321 Label::new(label.into()).color(color).single_line()
2322 }
2323
2324 fn render_list_header(
2325 &self,
2326 ix: usize,
2327 header: &GitHeaderEntry,
2328 _: bool,
2329 _: &Window,
2330 _: &Context<Self>,
2331 ) -> AnyElement {
2332 div()
2333 .w_full()
2334 .child(
2335 ListItem::new(ix)
2336 .spacing(ListItemSpacing::Sparse)
2337 .disabled(true)
2338 .child(
2339 Label::new(header.title())
2340 .color(Color::Muted)
2341 .size(LabelSize::Small)
2342 .single_line(),
2343 ),
2344 )
2345 .into_any_element()
2346 }
2347
2348 fn load_commit_details(
2349 &self,
2350 sha: &str,
2351 cx: &mut Context<Self>,
2352 ) -> Task<Result<CommitDetails>> {
2353 let Some(repo) = self.active_repository.clone() else {
2354 return Task::ready(Err(anyhow::anyhow!("no active repo")));
2355 };
2356 repo.update(cx, |repo, cx| repo.show(sha, cx))
2357 }
2358
2359 fn deploy_entry_context_menu(
2360 &mut self,
2361 position: Point<Pixels>,
2362 ix: usize,
2363 window: &mut Window,
2364 cx: &mut Context<Self>,
2365 ) {
2366 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
2367 return;
2368 };
2369 let stage_title = if entry.status.is_staged() == Some(true) {
2370 "Unstage File"
2371 } else {
2372 "Stage File"
2373 };
2374 let revert_title = if entry.status.is_deleted() {
2375 "Restore file"
2376 } else if entry.status.is_created() {
2377 "Trash file"
2378 } else {
2379 "Discard changes"
2380 };
2381 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
2382 context_menu
2383 .action(stage_title, ToggleStaged.boxed_clone())
2384 .action(revert_title, git::RestoreFile.boxed_clone())
2385 .separator()
2386 .action("Open Diff", Confirm.boxed_clone())
2387 .action("Open File", SecondaryConfirm.boxed_clone())
2388 });
2389 self.selected_entry = Some(ix);
2390 self.set_context_menu(context_menu, position, window, cx);
2391 }
2392
2393 fn panel_context_menu(window: &mut Window, cx: &mut App) -> Entity<ContextMenu> {
2394 ContextMenu::build(window, cx, |context_menu, _, _| {
2395 context_menu
2396 .action("Stage All", StageAll.boxed_clone())
2397 .action("Unstage All", UnstageAll.boxed_clone())
2398 .separator()
2399 .action("Open Diff", project_diff::Diff.boxed_clone())
2400 .separator()
2401 .action("Discard Tracked Changes", RestoreTrackedFiles.boxed_clone())
2402 .action("Trash Untracked Files", TrashUntrackedFiles.boxed_clone())
2403 })
2404 }
2405
2406 fn deploy_panel_context_menu(
2407 &mut self,
2408 position: Point<Pixels>,
2409 window: &mut Window,
2410 cx: &mut Context<Self>,
2411 ) {
2412 let context_menu = Self::panel_context_menu(window, cx);
2413 self.set_context_menu(context_menu, position, window, cx);
2414 }
2415
2416 fn set_context_menu(
2417 &mut self,
2418 context_menu: Entity<ContextMenu>,
2419 position: Point<Pixels>,
2420 window: &Window,
2421 cx: &mut Context<Self>,
2422 ) {
2423 let subscription = cx.subscribe_in(
2424 &context_menu,
2425 window,
2426 |this, _, _: &DismissEvent, window, cx| {
2427 if this.context_menu.as_ref().is_some_and(|context_menu| {
2428 context_menu.0.focus_handle(cx).contains_focused(window, cx)
2429 }) {
2430 cx.focus_self(window);
2431 }
2432 this.context_menu.take();
2433 cx.notify();
2434 },
2435 );
2436 self.context_menu = Some((context_menu, position, subscription));
2437 cx.notify();
2438 }
2439
2440 fn render_entry(
2441 &self,
2442 ix: usize,
2443 entry: &GitStatusEntry,
2444 has_write_access: bool,
2445 window: &Window,
2446 cx: &Context<Self>,
2447 ) -> AnyElement {
2448 let display_name = entry
2449 .repo_path
2450 .file_name()
2451 .map(|name| name.to_string_lossy().into_owned())
2452 .unwrap_or_else(|| entry.repo_path.to_string_lossy().into_owned());
2453
2454 let repo_path = entry.repo_path.clone();
2455 let selected = self.selected_entry == Some(ix);
2456 let status_style = GitPanelSettings::get_global(cx).status_style;
2457 let status = entry.status;
2458 let has_conflict = status.is_conflicted();
2459 let is_modified = status.is_modified();
2460 let is_deleted = status.is_deleted();
2461
2462 let label_color = if status_style == StatusStyle::LabelColor {
2463 if has_conflict {
2464 Color::Conflict
2465 } else if is_modified {
2466 Color::Modified
2467 } else if is_deleted {
2468 // We don't want a bunch of red labels in the list
2469 Color::Disabled
2470 } else {
2471 Color::Created
2472 }
2473 } else {
2474 Color::Default
2475 };
2476
2477 let path_color = if status.is_deleted() {
2478 Color::Disabled
2479 } else {
2480 Color::Muted
2481 };
2482
2483 let id: ElementId = ElementId::Name(format!("entry_{}", display_name).into());
2484
2485 let mut is_staged: ToggleState = self.entry_is_staged(entry).into();
2486
2487 if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
2488 is_staged = ToggleState::Selected;
2489 }
2490
2491 let checkbox = Checkbox::new(id, is_staged)
2492 .disabled(!has_write_access)
2493 .fill()
2494 .placeholder(!self.has_staged_changes() && !self.has_conflicts())
2495 .elevation(ElevationIndex::Surface)
2496 .on_click({
2497 let entry = entry.clone();
2498 cx.listener(move |this, _, window, cx| {
2499 this.toggle_staged_for_entry(
2500 &GitListEntry::GitStatusEntry(entry.clone()),
2501 window,
2502 cx,
2503 );
2504 cx.stop_propagation();
2505 })
2506 });
2507
2508 let start_slot =
2509 h_flex()
2510 .id(("start-slot", ix))
2511 .gap(DynamicSpacing::Base04.rems(cx))
2512 .child(checkbox.tooltip(|window, cx| {
2513 Tooltip::for_action("Stage File", &ToggleStaged, window, cx)
2514 }))
2515 .child(git_status_icon(status, cx))
2516 .on_mouse_down(MouseButton::Left, |_, _, cx| {
2517 // prevent the list item active state triggering when toggling checkbox
2518 cx.stop_propagation();
2519 });
2520
2521 div()
2522 .w_full()
2523 .child(
2524 ListItem::new(ix)
2525 .spacing(ListItemSpacing::Sparse)
2526 .start_slot(start_slot)
2527 .toggle_state(selected)
2528 .focused(selected && self.focus_handle(cx).is_focused(window))
2529 .disabled(!has_write_access)
2530 .on_click({
2531 cx.listener(move |this, event: &ClickEvent, window, cx| {
2532 this.selected_entry = Some(ix);
2533 cx.notify();
2534 if event.modifiers().secondary() {
2535 this.open_file(&Default::default(), window, cx)
2536 } else {
2537 this.open_diff(&Default::default(), window, cx);
2538 }
2539 })
2540 })
2541 .on_secondary_mouse_down(cx.listener(
2542 move |this, event: &MouseDownEvent, window, cx| {
2543 this.deploy_entry_context_menu(event.position, ix, window, cx);
2544 cx.stop_propagation();
2545 },
2546 ))
2547 .child(
2548 h_flex()
2549 .when_some(repo_path.parent(), |this, parent| {
2550 let parent_str = parent.to_string_lossy();
2551 if !parent_str.is_empty() {
2552 this.child(
2553 self.entry_label(format!("{}/", parent_str), path_color)
2554 .when(status.is_deleted(), |this| this.strikethrough()),
2555 )
2556 } else {
2557 this
2558 }
2559 })
2560 .child(
2561 self.entry_label(display_name.clone(), label_color)
2562 .when(status.is_deleted(), |this| this.strikethrough()),
2563 ),
2564 ),
2565 )
2566 .into_any_element()
2567 }
2568
2569 fn render_push_button(&self, branch: &Branch, cx: &Context<Self>) -> AnyElement {
2570 let mut disabled = false;
2571
2572 // TODO: Add <origin> and <branch> argument substitutions to this
2573 let button: SharedString;
2574 let tooltip: SharedString;
2575 let action: Option<Push>;
2576 if let Some(upstream) = &branch.upstream {
2577 match upstream.tracking {
2578 UpstreamTracking::Gone => {
2579 button = "Republish".into();
2580 tooltip = "git push --set-upstream".into();
2581 action = Some(git::Push {
2582 options: Some(PushOptions::SetUpstream),
2583 });
2584 }
2585 UpstreamTracking::Tracked(tracking) => {
2586 if tracking.behind > 0 {
2587 disabled = true;
2588 button = "Push".into();
2589 tooltip = "Upstream is ahead of local branch".into();
2590 action = None;
2591 } else if tracking.ahead > 0 {
2592 button = format!("Push ({})", tracking.ahead).into();
2593 tooltip = "git push".into();
2594 action = Some(git::Push { options: None });
2595 } else {
2596 disabled = true;
2597 button = "Push".into();
2598 tooltip = "Upstream matches local branch".into();
2599 action = None;
2600 }
2601 }
2602 }
2603 } else {
2604 button = "Publish".into();
2605 tooltip = "git push --set-upstream".into();
2606 action = Some(git::Push {
2607 options: Some(PushOptions::SetUpstream),
2608 });
2609 };
2610
2611 panel_filled_button(button)
2612 .icon(IconName::ArrowUp)
2613 .icon_size(IconSize::Small)
2614 .icon_color(Color::Muted)
2615 .icon_position(IconPosition::Start)
2616 .disabled(disabled)
2617 .when_some(action, |this, action| {
2618 this.on_click(
2619 cx.listener(move |this, _, window, cx| this.push(&action, window, cx)),
2620 )
2621 })
2622 .tooltip(move |window, cx| {
2623 if let Some(action) = action.as_ref() {
2624 Tooltip::for_action(tooltip.clone(), action, window, cx)
2625 } else {
2626 Tooltip::simple(tooltip.clone(), cx)
2627 }
2628 })
2629 .into_any_element()
2630 }
2631
2632 fn has_write_access(&self, cx: &App) -> bool {
2633 !self.project.read(cx).is_read_only(cx)
2634 }
2635}
2636
2637impl Render for GitPanel {
2638 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2639 let project = self.project.read(cx);
2640 let has_entries = self.entries.len() > 0;
2641 let room = self
2642 .workspace
2643 .upgrade()
2644 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
2645
2646 let has_write_access = self.has_write_access(cx);
2647
2648 let has_co_authors = room.map_or(false, |room| {
2649 room.read(cx)
2650 .remote_participants()
2651 .values()
2652 .any(|remote_participant| remote_participant.can_write())
2653 });
2654
2655 v_flex()
2656 .id("git_panel")
2657 .key_context(self.dispatch_context(window, cx))
2658 .track_focus(&self.focus_handle)
2659 .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
2660 .when(has_write_access && !project.is_read_only(cx), |this| {
2661 this.on_action(cx.listener(|this, &ToggleStaged, window, cx| {
2662 this.toggle_staged_for_selected(&ToggleStaged, window, cx)
2663 }))
2664 .on_action(cx.listener(GitPanel::commit))
2665 })
2666 .on_action(cx.listener(Self::select_first))
2667 .on_action(cx.listener(Self::select_next))
2668 .on_action(cx.listener(Self::select_prev))
2669 .on_action(cx.listener(Self::select_last))
2670 .on_action(cx.listener(Self::close_panel))
2671 .on_action(cx.listener(Self::open_diff))
2672 .on_action(cx.listener(Self::open_file))
2673 .on_action(cx.listener(Self::revert_selected))
2674 .on_action(cx.listener(Self::focus_changes_list))
2675 .on_action(cx.listener(Self::focus_editor))
2676 .on_action(cx.listener(Self::toggle_staged_for_selected))
2677 .on_action(cx.listener(Self::stage_all))
2678 .on_action(cx.listener(Self::unstage_all))
2679 .on_action(cx.listener(Self::discard_tracked_changes))
2680 .on_action(cx.listener(Self::clean_all))
2681 .on_action(cx.listener(Self::fetch))
2682 .on_action(cx.listener(Self::pull))
2683 .on_action(cx.listener(Self::push))
2684 .when(has_write_access && has_co_authors, |git_panel| {
2685 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
2686 })
2687 // .on_action(cx.listener(|this, &OpenSelected, cx| this.open_selected(&OpenSelected, cx)))
2688 .on_hover(cx.listener(|this, hovered, window, cx| {
2689 if *hovered {
2690 this.show_scrollbar = true;
2691 this.hide_scrollbar_task.take();
2692 cx.notify();
2693 } else if !this.focus_handle.contains_focused(window, cx) {
2694 this.hide_scrollbar(window, cx);
2695 }
2696 }))
2697 .size_full()
2698 .overflow_hidden()
2699 .bg(ElevationIndex::Surface.bg(cx))
2700 .child(
2701 v_flex()
2702 .size_full()
2703 .children(self.render_panel_header(window, cx))
2704 .map(|this| {
2705 if has_entries {
2706 this.child(self.render_entries(has_write_access, window, cx))
2707 } else {
2708 this.child(self.render_empty_state(cx).into_any_element())
2709 }
2710 })
2711 .children(self.render_previous_commit(cx))
2712 .child(self.render_commit_editor(window, cx))
2713 .into_any_element(),
2714 )
2715 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
2716 deferred(
2717 anchored()
2718 .position(*position)
2719 .anchor(gpui::Corner::TopLeft)
2720 .child(menu.clone()),
2721 )
2722 .with_priority(1)
2723 }))
2724 }
2725}
2726
2727impl Focusable for GitPanel {
2728 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
2729 self.focus_handle.clone()
2730 }
2731}
2732
2733impl EventEmitter<Event> for GitPanel {}
2734
2735impl EventEmitter<PanelEvent> for GitPanel {}
2736
2737pub(crate) struct GitPanelAddon {
2738 pub(crate) workspace: WeakEntity<Workspace>,
2739}
2740
2741impl editor::Addon for GitPanelAddon {
2742 fn to_any(&self) -> &dyn std::any::Any {
2743 self
2744 }
2745
2746 fn render_buffer_header_controls(
2747 &self,
2748 excerpt_info: &ExcerptInfo,
2749 window: &Window,
2750 cx: &App,
2751 ) -> Option<AnyElement> {
2752 let file = excerpt_info.buffer.file()?;
2753 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
2754
2755 git_panel
2756 .read(cx)
2757 .render_buffer_header_controls(&git_panel, &file, window, cx)
2758 }
2759}
2760
2761impl Panel for GitPanel {
2762 fn persistent_name() -> &'static str {
2763 "GitPanel"
2764 }
2765
2766 fn position(&self, _: &Window, cx: &App) -> DockPosition {
2767 GitPanelSettings::get_global(cx).dock
2768 }
2769
2770 fn position_is_valid(&self, position: DockPosition) -> bool {
2771 matches!(position, DockPosition::Left | DockPosition::Right)
2772 }
2773
2774 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
2775 settings::update_settings_file::<GitPanelSettings>(
2776 self.fs.clone(),
2777 cx,
2778 move |settings, _| settings.dock = Some(position),
2779 );
2780 }
2781
2782 fn size(&self, _: &Window, cx: &App) -> Pixels {
2783 self.width
2784 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
2785 }
2786
2787 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
2788 self.width = size;
2789 self.serialize(cx);
2790 cx.notify();
2791 }
2792
2793 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
2794 Some(ui::IconName::GitBranch).filter(|_| GitPanelSettings::get_global(cx).button)
2795 }
2796
2797 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
2798 Some("Git Panel")
2799 }
2800
2801 fn toggle_action(&self) -> Box<dyn Action> {
2802 Box::new(ToggleFocus)
2803 }
2804
2805 fn activation_priority(&self) -> u32 {
2806 2
2807 }
2808}
2809
2810impl PanelHeader for GitPanel {}
2811
2812struct GitPanelMessageTooltip {
2813 commit_tooltip: Option<Entity<CommitTooltip>>,
2814}
2815
2816impl GitPanelMessageTooltip {
2817 fn new(
2818 git_panel: Entity<GitPanel>,
2819 sha: SharedString,
2820 window: &mut Window,
2821 cx: &mut App,
2822 ) -> Entity<Self> {
2823 cx.new(|cx| {
2824 cx.spawn_in(window, |this, mut cx| async move {
2825 let details = git_panel
2826 .update(&mut cx, |git_panel, cx| {
2827 git_panel.load_commit_details(&sha, cx)
2828 })?
2829 .await?;
2830
2831 let commit_details = editor::commit_tooltip::CommitDetails {
2832 sha: details.sha.clone(),
2833 committer_name: details.committer_name.clone(),
2834 committer_email: details.committer_email.clone(),
2835 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
2836 message: Some(editor::commit_tooltip::ParsedCommitMessage {
2837 message: details.message.clone(),
2838 ..Default::default()
2839 }),
2840 };
2841
2842 this.update_in(&mut cx, |this: &mut GitPanelMessageTooltip, window, cx| {
2843 this.commit_tooltip =
2844 Some(cx.new(move |cx| CommitTooltip::new(commit_details, window, cx)));
2845 cx.notify();
2846 })
2847 })
2848 .detach();
2849
2850 Self {
2851 commit_tooltip: None,
2852 }
2853 })
2854 }
2855}
2856
2857impl Render for GitPanelMessageTooltip {
2858 fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
2859 if let Some(commit_tooltip) = &self.commit_tooltip {
2860 commit_tooltip.clone().into_any_element()
2861 } else {
2862 gpui::Empty.into_any_element()
2863 }
2864 }
2865}