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 details = entries
858 .iter()
859 .filter_map(|entry| entry.repo_path.0.file_name())
860 .map(|filename| filename.to_string_lossy())
861 .join("\n");
862
863 #[derive(strum::EnumIter, strum::VariantNames)]
864 #[strum(serialize_all = "title_case")]
865 enum DiscardCancel {
866 DiscardTrackedChanges,
867 Cancel,
868 }
869 let prompt = prompt(
870 "Discard changes to these files?",
871 Some(&details),
872 window,
873 cx,
874 );
875 cx.spawn(|this, mut cx| async move {
876 match prompt.await {
877 Ok(DiscardCancel::DiscardTrackedChanges) => {
878 this.update(&mut cx, |this, cx| {
879 let repo_paths = entries.into_iter().map(|entry| entry.repo_path).collect();
880 this.perform_checkout(repo_paths, cx);
881 })
882 .ok();
883 }
884 _ => {
885 return;
886 }
887 }
888 })
889 .detach();
890 }
891
892 fn clean_all(&mut self, _: &TrashUntrackedFiles, window: &mut Window, cx: &mut Context<Self>) {
893 let workspace = self.workspace.clone();
894 let Some(active_repo) = self.active_repository.clone() else {
895 return;
896 };
897 let to_delete = self
898 .entries
899 .iter()
900 .filter_map(|entry| entry.status_entry())
901 .filter(|status_entry| status_entry.status.is_created())
902 .cloned()
903 .collect::<Vec<_>>();
904
905 match to_delete.len() {
906 0 => return,
907 1 => return self.revert_entry(&to_delete[0], window, cx),
908 _ => {}
909 };
910
911 let details = to_delete
912 .iter()
913 .map(|entry| {
914 entry
915 .repo_path
916 .0
917 .file_name()
918 .map(|f| f.to_string_lossy())
919 .unwrap_or_default()
920 })
921 .join("\n");
922
923 let prompt = prompt("Trash these files?", Some(&details), window, cx);
924 cx.spawn_in(window, |this, mut cx| async move {
925 match prompt.await? {
926 TrashCancel::Trash => {}
927 TrashCancel::Cancel => return Ok(()),
928 }
929 let tasks = workspace.update(&mut cx, |workspace, cx| {
930 to_delete
931 .iter()
932 .filter_map(|entry| {
933 workspace.project().update(cx, |project, cx| {
934 let project_path = active_repo
935 .read(cx)
936 .repo_path_to_project_path(&entry.repo_path)?;
937 project.delete_file(project_path, true, cx)
938 })
939 })
940 .collect::<Vec<_>>()
941 })?;
942 let to_unstage = to_delete
943 .into_iter()
944 .filter_map(|entry| {
945 if entry.status.is_staged() != Some(false) {
946 Some(entry.repo_path.clone())
947 } else {
948 None
949 }
950 })
951 .collect();
952 this.update(&mut cx, |this, cx| {
953 this.perform_stage(false, to_unstage, cx)
954 })?;
955 for task in tasks {
956 task.await?;
957 }
958 Ok(())
959 })
960 .detach_and_prompt_err("Failed to trash files", window, cx, |e, _, _| {
961 Some(format!("{e}"))
962 });
963 }
964
965 fn stage_all(&mut self, _: &StageAll, _window: &mut Window, cx: &mut Context<Self>) {
966 let repo_paths = self
967 .entries
968 .iter()
969 .filter_map(|entry| entry.status_entry())
970 .filter(|status_entry| status_entry.is_staged != Some(true))
971 .map(|status_entry| status_entry.repo_path.clone())
972 .collect::<Vec<_>>();
973 self.perform_stage(true, repo_paths, cx);
974 }
975
976 fn unstage_all(&mut self, _: &UnstageAll, _window: &mut Window, cx: &mut Context<Self>) {
977 let repo_paths = self
978 .entries
979 .iter()
980 .filter_map(|entry| entry.status_entry())
981 .filter(|status_entry| status_entry.is_staged != Some(false))
982 .map(|status_entry| status_entry.repo_path.clone())
983 .collect::<Vec<_>>();
984 self.perform_stage(false, repo_paths, cx);
985 }
986
987 fn toggle_staged_for_entry(
988 &mut self,
989 entry: &GitListEntry,
990 _window: &mut Window,
991 cx: &mut Context<Self>,
992 ) {
993 let Some(active_repository) = self.active_repository.as_ref() else {
994 return;
995 };
996 let (stage, repo_paths) = match entry {
997 GitListEntry::GitStatusEntry(status_entry) => {
998 if status_entry.status.is_staged().unwrap_or(false) {
999 (false, vec![status_entry.repo_path.clone()])
1000 } else {
1001 (true, vec![status_entry.repo_path.clone()])
1002 }
1003 }
1004 GitListEntry::Header(section) => {
1005 let goal_staged_state = !self.header_state(section.header).selected();
1006 let repository = active_repository.read(cx);
1007 let entries = self
1008 .entries
1009 .iter()
1010 .filter_map(|entry| entry.status_entry())
1011 .filter(|status_entry| {
1012 section.contains(&status_entry, repository)
1013 && status_entry.is_staged != Some(goal_staged_state)
1014 })
1015 .map(|status_entry| status_entry.repo_path.clone())
1016 .collect::<Vec<_>>();
1017
1018 (goal_staged_state, entries)
1019 }
1020 };
1021 self.perform_stage(stage, repo_paths, cx);
1022 }
1023
1024 fn perform_stage(&mut self, stage: bool, repo_paths: Vec<RepoPath>, cx: &mut Context<Self>) {
1025 let Some(active_repository) = self.active_repository.clone() else {
1026 return;
1027 };
1028 let op_id = self.pending.iter().map(|p| p.op_id).max().unwrap_or(0) + 1;
1029 self.pending.push(PendingOperation {
1030 op_id,
1031 target_status: if stage {
1032 TargetStatus::Staged
1033 } else {
1034 TargetStatus::Unstaged
1035 },
1036 repo_paths: repo_paths.iter().cloned().collect(),
1037 finished: false,
1038 });
1039 let repo_paths = repo_paths.clone();
1040 let repository = active_repository.read(cx);
1041 self.update_counts(repository);
1042 cx.notify();
1043
1044 cx.spawn({
1045 |this, mut cx| async move {
1046 let result = cx
1047 .update(|cx| {
1048 if stage {
1049 active_repository
1050 .update(cx, |repo, cx| repo.stage_entries(repo_paths.clone(), cx))
1051 } else {
1052 active_repository
1053 .update(cx, |repo, cx| repo.unstage_entries(repo_paths.clone(), cx))
1054 }
1055 })?
1056 .await;
1057
1058 this.update(&mut cx, |this, cx| {
1059 for pending in this.pending.iter_mut() {
1060 if pending.op_id == op_id {
1061 pending.finished = true
1062 }
1063 }
1064 result
1065 .map_err(|e| {
1066 this.show_err_toast(e, cx);
1067 })
1068 .ok();
1069 cx.notify();
1070 })
1071 }
1072 })
1073 .detach();
1074 }
1075
1076 pub fn total_staged_count(&self) -> usize {
1077 self.tracked_staged_count + self.new_staged_count + self.conflicted_staged_count
1078 }
1079
1080 pub fn commit_message_buffer(&self, cx: &App) -> Entity<Buffer> {
1081 self.commit_editor
1082 .read(cx)
1083 .buffer()
1084 .read(cx)
1085 .as_singleton()
1086 .unwrap()
1087 .clone()
1088 }
1089
1090 fn toggle_staged_for_selected(
1091 &mut self,
1092 _: &git::ToggleStaged,
1093 window: &mut Window,
1094 cx: &mut Context<Self>,
1095 ) {
1096 if let Some(selected_entry) = self.get_selected_entry().cloned() {
1097 self.toggle_staged_for_entry(&selected_entry, window, cx);
1098 }
1099 }
1100
1101 fn commit(&mut self, _: &git::Commit, window: &mut Window, cx: &mut Context<Self>) {
1102 if self
1103 .commit_editor
1104 .focus_handle(cx)
1105 .contains_focused(window, cx)
1106 {
1107 self.commit_changes(window, cx)
1108 } else {
1109 cx.propagate();
1110 }
1111 }
1112
1113 pub(crate) fn commit_changes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1114 let Some(active_repository) = self.active_repository.clone() else {
1115 return;
1116 };
1117 let error_spawn = |message, window: &mut Window, cx: &mut App| {
1118 let prompt = window.prompt(PromptLevel::Warning, message, None, &["Ok"], cx);
1119 cx.spawn(|_| async move {
1120 prompt.await.ok();
1121 })
1122 .detach();
1123 };
1124
1125 if self.has_unstaged_conflicts() {
1126 error_spawn(
1127 "There are still conflicts. You must stage these before committing",
1128 window,
1129 cx,
1130 );
1131 return;
1132 }
1133
1134 let mut message = self.commit_editor.read(cx).text(cx);
1135 if message.trim().is_empty() {
1136 self.commit_editor.read(cx).focus_handle(cx).focus(window);
1137 return;
1138 }
1139 if self.add_coauthors {
1140 self.fill_co_authors(&mut message, cx);
1141 }
1142
1143 let task = if self.has_staged_changes() {
1144 // Repository serializes all git operations, so we can just send a commit immediately
1145 let commit_task = active_repository.read(cx).commit(message.into(), None);
1146 cx.background_spawn(async move { commit_task.await? })
1147 } else {
1148 let changed_files = self
1149 .entries
1150 .iter()
1151 .filter_map(|entry| entry.status_entry())
1152 .filter(|status_entry| !status_entry.status.is_created())
1153 .map(|status_entry| status_entry.repo_path.clone())
1154 .collect::<Vec<_>>();
1155
1156 if changed_files.is_empty() {
1157 error_spawn("No changes to commit", window, cx);
1158 return;
1159 }
1160
1161 let stage_task =
1162 active_repository.update(cx, |repo, cx| repo.stage_entries(changed_files, cx));
1163 cx.spawn(|_, mut cx| async move {
1164 stage_task.await?;
1165 let commit_task = active_repository
1166 .update(&mut cx, |repo, _| repo.commit(message.into(), None))?;
1167 commit_task.await?
1168 })
1169 };
1170 let task = cx.spawn_in(window, |this, mut cx| async move {
1171 let result = task.await;
1172 this.update_in(&mut cx, |this, window, cx| {
1173 this.pending_commit.take();
1174 match result {
1175 Ok(()) => {
1176 this.commit_editor
1177 .update(cx, |editor, cx| editor.clear(window, cx));
1178 }
1179 Err(e) => this.show_err_toast(e, cx),
1180 }
1181 })
1182 .ok();
1183 });
1184
1185 self.pending_commit = Some(task);
1186 }
1187
1188 fn uncommit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1189 let Some(repo) = self.active_repository.clone() else {
1190 return;
1191 };
1192
1193 // TODO: Use git merge-base to find the upstream and main branch split
1194 let confirmation = Task::ready(true);
1195 // let confirmation = if self.commit_editor.read(cx).is_empty(cx) {
1196 // Task::ready(true)
1197 // } else {
1198 // let prompt = window.prompt(
1199 // PromptLevel::Warning,
1200 // "Uncomitting will replace the current commit message with the previous commit's message",
1201 // None,
1202 // &["Ok", "Cancel"],
1203 // cx,
1204 // );
1205 // cx.spawn(|_, _| async move { prompt.await.is_ok_and(|i| i == 0) })
1206 // };
1207
1208 let prior_head = self.load_commit_details("HEAD", cx);
1209
1210 let task = cx.spawn_in(window, |this, mut cx| async move {
1211 let result = maybe!(async {
1212 if !confirmation.await {
1213 Ok(None)
1214 } else {
1215 let prior_head = prior_head.await?;
1216
1217 repo.update(&mut cx, |repo, _| repo.reset("HEAD^", ResetMode::Soft))?
1218 .await??;
1219
1220 Ok(Some(prior_head))
1221 }
1222 })
1223 .await;
1224
1225 this.update_in(&mut cx, |this, window, cx| {
1226 this.pending_commit.take();
1227 match result {
1228 Ok(None) => {}
1229 Ok(Some(prior_commit)) => {
1230 this.commit_editor.update(cx, |editor, cx| {
1231 editor.set_text(prior_commit.message, window, cx)
1232 });
1233 }
1234 Err(e) => this.show_err_toast(e, cx),
1235 }
1236 })
1237 .ok();
1238 });
1239
1240 self.pending_commit = Some(task);
1241 }
1242
1243 /// Suggests a commit message based on the changed files and their statuses
1244 pub fn suggest_commit_message(&self) -> Option<String> {
1245 let entries = self
1246 .entries
1247 .iter()
1248 .filter_map(|entry| {
1249 if let GitListEntry::GitStatusEntry(status_entry) = entry {
1250 Some(status_entry)
1251 } else {
1252 None
1253 }
1254 })
1255 .collect::<Vec<&GitStatusEntry>>();
1256
1257 if entries.is_empty() {
1258 None
1259 } else if entries.len() == 1 {
1260 let entry = &entries[0];
1261 let file_name = entry
1262 .repo_path
1263 .file_name()
1264 .unwrap_or_default()
1265 .to_string_lossy();
1266
1267 if entry.status.is_deleted() {
1268 Some(format!("Delete {}", file_name))
1269 } else if entry.status.is_created() {
1270 Some(format!("Create {}", file_name))
1271 } else if entry.status.is_modified() {
1272 Some(format!("Update {}", file_name))
1273 } else {
1274 None
1275 }
1276 } else {
1277 None
1278 }
1279 }
1280
1281 fn update_editor_placeholder(&mut self, cx: &mut Context<Self>) {
1282 let suggested_commit_message = self.suggest_commit_message();
1283 self.suggested_commit_message = suggested_commit_message.clone();
1284
1285 if let Some(suggested_commit_message) = suggested_commit_message {
1286 self.commit_editor.update(cx, |editor, cx| {
1287 editor.set_placeholder_text(Arc::from(suggested_commit_message), cx)
1288 });
1289 }
1290
1291 cx.notify();
1292 }
1293
1294 fn fetch(&mut self, _: &git::Fetch, _window: &mut Window, cx: &mut Context<Self>) {
1295 let Some(repo) = self.active_repository.clone() else {
1296 return;
1297 };
1298 let guard = self.start_remote_operation();
1299 let fetch = repo.read(cx).fetch();
1300 cx.spawn(|_, _| async move {
1301 fetch.await??;
1302 drop(guard);
1303 anyhow::Ok(())
1304 })
1305 .detach_and_log_err(cx);
1306 }
1307
1308 fn pull(&mut self, _: &git::Pull, window: &mut Window, cx: &mut Context<Self>) {
1309 let guard = self.start_remote_operation();
1310 let remote = self.get_current_remote(window, cx);
1311 cx.spawn(move |this, mut cx| async move {
1312 let remote = remote.await?;
1313
1314 this.update(&mut cx, |this, cx| {
1315 let Some(repo) = this.active_repository.clone() else {
1316 return Err(anyhow::anyhow!("No active repository"));
1317 };
1318
1319 let Some(branch) = repo.read(cx).current_branch() else {
1320 return Err(anyhow::anyhow!("No active branch"));
1321 };
1322
1323 Ok(repo.read(cx).pull(branch.name.clone(), remote.name))
1324 })??
1325 .await??;
1326
1327 drop(guard);
1328 anyhow::Ok(())
1329 })
1330 .detach_and_log_err(cx);
1331 }
1332
1333 fn push(&mut self, action: &git::Push, window: &mut Window, cx: &mut Context<Self>) {
1334 let guard = self.start_remote_operation();
1335 let options = action.options;
1336 let remote = self.get_current_remote(window, cx);
1337 cx.spawn(move |this, mut cx| async move {
1338 let remote = remote.await?;
1339
1340 this.update(&mut cx, |this, cx| {
1341 let Some(repo) = this.active_repository.clone() else {
1342 return Err(anyhow::anyhow!("No active repository"));
1343 };
1344
1345 let Some(branch) = repo.read(cx).current_branch() else {
1346 return Err(anyhow::anyhow!("No active branch"));
1347 };
1348
1349 Ok(repo
1350 .read(cx)
1351 .push(branch.name.clone(), remote.name, options))
1352 })??
1353 .await??;
1354
1355 drop(guard);
1356 anyhow::Ok(())
1357 })
1358 .detach_and_log_err(cx);
1359 }
1360
1361 fn get_current_remote(
1362 &mut self,
1363 window: &mut Window,
1364 cx: &mut Context<Self>,
1365 ) -> impl Future<Output = Result<Remote>> {
1366 let repo = self.active_repository.clone();
1367 let workspace = self.workspace.clone();
1368 let mut cx = window.to_async(cx);
1369
1370 async move {
1371 let Some(repo) = repo else {
1372 return Err(anyhow::anyhow!("No active repository"));
1373 };
1374
1375 let mut current_remotes: Vec<Remote> = repo
1376 .update(&mut cx, |repo, cx| {
1377 let Some(current_branch) = repo.current_branch() else {
1378 return Err(anyhow::anyhow!("No active branch"));
1379 };
1380
1381 Ok(repo.get_remotes(Some(current_branch.name.to_string()), cx))
1382 })??
1383 .await?;
1384
1385 if current_remotes.len() == 0 {
1386 return Err(anyhow::anyhow!("No active remote"));
1387 } else if current_remotes.len() == 1 {
1388 return Ok(current_remotes.pop().unwrap());
1389 } else {
1390 let current_remotes: Vec<_> = current_remotes
1391 .into_iter()
1392 .map(|remotes| remotes.name)
1393 .collect();
1394 let selection = cx
1395 .update(|window, cx| {
1396 picker_prompt::prompt(
1397 "Pick which remote to push to",
1398 current_remotes.clone(),
1399 workspace,
1400 window,
1401 cx,
1402 )
1403 })?
1404 .await?;
1405
1406 return Ok(Remote {
1407 name: current_remotes[selection].clone(),
1408 });
1409 }
1410 }
1411 }
1412
1413 fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
1414 let mut new_co_authors = Vec::new();
1415 let project = self.project.read(cx);
1416
1417 let Some(room) = self
1418 .workspace
1419 .upgrade()
1420 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
1421 else {
1422 return Vec::default();
1423 };
1424
1425 let room = room.read(cx);
1426
1427 for (peer_id, collaborator) in project.collaborators() {
1428 if collaborator.is_host {
1429 continue;
1430 }
1431
1432 let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
1433 continue;
1434 };
1435 if participant.can_write() && participant.user.email.is_some() {
1436 let email = participant.user.email.clone().unwrap();
1437
1438 new_co_authors.push((
1439 participant
1440 .user
1441 .name
1442 .clone()
1443 .unwrap_or_else(|| participant.user.github_login.clone()),
1444 email,
1445 ))
1446 }
1447 }
1448 if !project.is_local() && !project.is_read_only(cx) {
1449 if let Some(user) = room.local_participant_user(cx) {
1450 if let Some(email) = user.email.clone() {
1451 new_co_authors.push((
1452 user.name
1453 .clone()
1454 .unwrap_or_else(|| user.github_login.clone()),
1455 email.clone(),
1456 ))
1457 }
1458 }
1459 }
1460 new_co_authors
1461 }
1462
1463 fn toggle_fill_co_authors(
1464 &mut self,
1465 _: &ToggleFillCoAuthors,
1466 _: &mut Window,
1467 cx: &mut Context<Self>,
1468 ) {
1469 self.add_coauthors = !self.add_coauthors;
1470 cx.notify();
1471 }
1472
1473 fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
1474 const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
1475
1476 let existing_text = message.to_ascii_lowercase();
1477 let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
1478 let mut ends_with_co_authors = false;
1479 let existing_co_authors = existing_text
1480 .lines()
1481 .filter_map(|line| {
1482 let line = line.trim();
1483 if line.starts_with(&lowercase_co_author_prefix) {
1484 ends_with_co_authors = true;
1485 Some(line)
1486 } else {
1487 ends_with_co_authors = false;
1488 None
1489 }
1490 })
1491 .collect::<HashSet<_>>();
1492
1493 let new_co_authors = self
1494 .potential_co_authors(cx)
1495 .into_iter()
1496 .filter(|(_, email)| {
1497 !existing_co_authors
1498 .iter()
1499 .any(|existing| existing.contains(email.as_str()))
1500 })
1501 .collect::<Vec<_>>();
1502
1503 if new_co_authors.is_empty() {
1504 return;
1505 }
1506
1507 if !ends_with_co_authors {
1508 message.push('\n');
1509 }
1510 for (name, email) in new_co_authors {
1511 message.push('\n');
1512 message.push_str(CO_AUTHOR_PREFIX);
1513 message.push_str(&name);
1514 message.push_str(" <");
1515 message.push_str(&email);
1516 message.push('>');
1517 }
1518 message.push('\n');
1519 }
1520
1521 fn schedule_update(
1522 &mut self,
1523 clear_pending: bool,
1524 window: &mut Window,
1525 cx: &mut Context<Self>,
1526 ) {
1527 let handle = cx.entity().downgrade();
1528 self.reopen_commit_buffer(window, cx);
1529 self.update_visible_entries_task = cx.spawn_in(window, |_, mut cx| async move {
1530 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
1531 if let Some(git_panel) = handle.upgrade() {
1532 git_panel
1533 .update_in(&mut cx, |git_panel, _, cx| {
1534 if clear_pending {
1535 git_panel.clear_pending();
1536 }
1537 git_panel.update_visible_entries(cx);
1538 git_panel.update_editor_placeholder(cx);
1539 })
1540 .ok();
1541 }
1542 });
1543 }
1544
1545 fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1546 let Some(active_repo) = self.active_repository.as_ref() else {
1547 return;
1548 };
1549 let load_buffer = active_repo.update(cx, |active_repo, cx| {
1550 let project = self.project.read(cx);
1551 active_repo.open_commit_buffer(
1552 Some(project.languages().clone()),
1553 project.buffer_store().clone(),
1554 cx,
1555 )
1556 });
1557
1558 cx.spawn_in(window, |git_panel, mut cx| async move {
1559 let buffer = load_buffer.await?;
1560 git_panel.update_in(&mut cx, |git_panel, window, cx| {
1561 if git_panel
1562 .commit_editor
1563 .read(cx)
1564 .buffer()
1565 .read(cx)
1566 .as_singleton()
1567 .as_ref()
1568 != Some(&buffer)
1569 {
1570 git_panel.commit_editor = cx.new(|cx| {
1571 commit_message_editor(buffer, git_panel.project.clone(), true, window, cx)
1572 });
1573 }
1574 })
1575 })
1576 .detach_and_log_err(cx);
1577 }
1578
1579 fn clear_pending(&mut self) {
1580 self.pending.retain(|v| !v.finished)
1581 }
1582
1583 fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
1584 self.entries.clear();
1585 let mut changed_entries = Vec::new();
1586 let mut new_entries = Vec::new();
1587 let mut conflict_entries = Vec::new();
1588
1589 let Some(repo) = self.active_repository.as_ref() else {
1590 // Just clear entries if no repository is active.
1591 cx.notify();
1592 return;
1593 };
1594
1595 // First pass - collect all paths
1596 let repo = repo.read(cx);
1597
1598 // Second pass - create entries with proper depth calculation
1599 for entry in repo.status() {
1600 let is_conflict = repo.has_conflict(&entry.repo_path);
1601 let is_new = entry.status.is_created();
1602 let is_staged = entry.status.is_staged();
1603
1604 if self.pending.iter().any(|pending| {
1605 pending.target_status == TargetStatus::Reverted
1606 && !pending.finished
1607 && pending.repo_paths.contains(&entry.repo_path)
1608 }) {
1609 continue;
1610 }
1611
1612 let entry = GitStatusEntry {
1613 repo_path: entry.repo_path.clone(),
1614 status: entry.status,
1615 is_staged,
1616 };
1617
1618 if is_conflict {
1619 conflict_entries.push(entry);
1620 } else if is_new {
1621 new_entries.push(entry);
1622 } else {
1623 changed_entries.push(entry);
1624 }
1625 }
1626
1627 if conflict_entries.len() > 0 {
1628 self.entries.push(GitListEntry::Header(GitHeaderEntry {
1629 header: Section::Conflict,
1630 }));
1631 self.entries.extend(
1632 conflict_entries
1633 .into_iter()
1634 .map(GitListEntry::GitStatusEntry),
1635 );
1636 }
1637
1638 if changed_entries.len() > 0 {
1639 self.entries.push(GitListEntry::Header(GitHeaderEntry {
1640 header: Section::Tracked,
1641 }));
1642 self.entries.extend(
1643 changed_entries
1644 .into_iter()
1645 .map(GitListEntry::GitStatusEntry),
1646 );
1647 }
1648 if new_entries.len() > 0 {
1649 self.entries.push(GitListEntry::Header(GitHeaderEntry {
1650 header: Section::New,
1651 }));
1652 self.entries
1653 .extend(new_entries.into_iter().map(GitListEntry::GitStatusEntry));
1654 }
1655
1656 self.update_counts(repo);
1657
1658 self.select_first_entry_if_none(cx);
1659
1660 cx.notify();
1661 }
1662
1663 fn header_state(&self, header_type: Section) -> ToggleState {
1664 let (staged_count, count) = match header_type {
1665 Section::New => (self.new_staged_count, self.new_count),
1666 Section::Tracked => (self.tracked_staged_count, self.tracked_count),
1667 Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
1668 };
1669 if staged_count == 0 {
1670 ToggleState::Unselected
1671 } else if count == staged_count {
1672 ToggleState::Selected
1673 } else {
1674 ToggleState::Indeterminate
1675 }
1676 }
1677
1678 fn update_counts(&mut self, repo: &Repository) {
1679 self.conflicted_count = 0;
1680 self.conflicted_staged_count = 0;
1681 self.new_count = 0;
1682 self.tracked_count = 0;
1683 self.new_staged_count = 0;
1684 self.tracked_staged_count = 0;
1685 for entry in &self.entries {
1686 let Some(status_entry) = entry.status_entry() else {
1687 continue;
1688 };
1689 if repo.has_conflict(&status_entry.repo_path) {
1690 self.conflicted_count += 1;
1691 if self.entry_is_staged(status_entry) != Some(false) {
1692 self.conflicted_staged_count += 1;
1693 }
1694 } else if status_entry.status.is_created() {
1695 self.new_count += 1;
1696 if self.entry_is_staged(status_entry) != Some(false) {
1697 self.new_staged_count += 1;
1698 }
1699 } else {
1700 self.tracked_count += 1;
1701 if self.entry_is_staged(status_entry) != Some(false) {
1702 self.tracked_staged_count += 1;
1703 }
1704 }
1705 }
1706 }
1707
1708 fn entry_is_staged(&self, entry: &GitStatusEntry) -> Option<bool> {
1709 for pending in self.pending.iter().rev() {
1710 if pending.repo_paths.contains(&entry.repo_path) {
1711 match pending.target_status {
1712 TargetStatus::Staged => return Some(true),
1713 TargetStatus::Unstaged => return Some(false),
1714 TargetStatus::Reverted => continue,
1715 TargetStatus::Unchanged => continue,
1716 }
1717 }
1718 }
1719 entry.is_staged
1720 }
1721
1722 pub(crate) fn has_staged_changes(&self) -> bool {
1723 self.tracked_staged_count > 0
1724 || self.new_staged_count > 0
1725 || self.conflicted_staged_count > 0
1726 }
1727
1728 pub(crate) fn has_unstaged_changes(&self) -> bool {
1729 self.tracked_count > self.tracked_staged_count
1730 || self.new_count > self.new_staged_count
1731 || self.conflicted_count > self.conflicted_staged_count
1732 }
1733
1734 fn has_conflicts(&self) -> bool {
1735 self.conflicted_count > 0
1736 }
1737
1738 fn has_tracked_changes(&self) -> bool {
1739 self.tracked_count > 0
1740 }
1741
1742 pub fn has_unstaged_conflicts(&self) -> bool {
1743 self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
1744 }
1745
1746 fn show_err_toast(&self, e: anyhow::Error, cx: &mut App) {
1747 let Some(workspace) = self.workspace.upgrade() else {
1748 return;
1749 };
1750 let notif_id = NotificationId::Named("git-operation-error".into());
1751
1752 let message = e.to_string();
1753 workspace.update(cx, |workspace, cx| {
1754 let toast = Toast::new(notif_id, message).on_click("Open Zed Log", |window, cx| {
1755 window.dispatch_action(workspace::OpenLog.boxed_clone(), cx);
1756 });
1757 workspace.show_toast(toast, cx);
1758 });
1759 }
1760
1761 pub fn panel_button(
1762 &self,
1763 id: impl Into<SharedString>,
1764 label: impl Into<SharedString>,
1765 ) -> Button {
1766 let id = id.into().clone();
1767 let label = label.into().clone();
1768
1769 Button::new(id, label)
1770 .label_size(LabelSize::Small)
1771 .layer(ElevationIndex::ElevatedSurface)
1772 .size(ButtonSize::Compact)
1773 .style(ButtonStyle::Filled)
1774 }
1775
1776 pub fn indent_size(&self, window: &Window, cx: &mut Context<Self>) -> Pixels {
1777 Checkbox::container_size(cx).to_pixels(window.rem_size())
1778 }
1779
1780 pub fn render_divider(&self, _cx: &mut Context<Self>) -> impl IntoElement {
1781 h_flex()
1782 .items_center()
1783 .h(px(8.))
1784 .child(Divider::horizontal_dashed().color(DividerColor::Border))
1785 }
1786
1787 pub fn render_panel_header(
1788 &self,
1789 window: &mut Window,
1790 cx: &mut Context<Self>,
1791 ) -> Option<impl IntoElement> {
1792 let all_repositories = self
1793 .project
1794 .read(cx)
1795 .git_store()
1796 .read(cx)
1797 .all_repositories();
1798
1799 let has_repo_above = all_repositories.iter().any(|repo| {
1800 repo.read(cx)
1801 .repository_entry
1802 .work_directory
1803 .is_above_project()
1804 });
1805
1806 let has_visible_repo = all_repositories.len() > 0 || has_repo_above;
1807
1808 if has_visible_repo {
1809 Some(
1810 self.panel_header_container(window, cx)
1811 .child(
1812 Label::new("Repository")
1813 .size(LabelSize::Small)
1814 .color(Color::Muted),
1815 )
1816 .child(self.render_repository_selector(cx))
1817 .child(div().flex_grow()) // spacer
1818 .child(
1819 div()
1820 .h_flex()
1821 .gap_1()
1822 .children(self.render_spinner(cx))
1823 .children(self.render_sync_button(cx))
1824 .children(self.render_pull_button(cx))
1825 .child(
1826 Button::new("diff", "+/-")
1827 .tooltip(Tooltip::for_action_title("Open diff", &Diff))
1828 .on_click(|_, _, cx| {
1829 cx.defer(|cx| {
1830 cx.dispatch_action(&Diff);
1831 })
1832 }),
1833 )
1834 .child(self.render_overflow_menu()),
1835 ),
1836 )
1837 } else {
1838 None
1839 }
1840 }
1841
1842 pub fn render_spinner(&self, _cx: &mut Context<Self>) -> Option<impl IntoElement> {
1843 (!self.pending_remote_operations.borrow().is_empty()).then(|| {
1844 Icon::new(IconName::ArrowCircle)
1845 .size(IconSize::XSmall)
1846 .color(Color::Info)
1847 .with_animation(
1848 "arrow-circle",
1849 Animation::new(Duration::from_secs(2)).repeat(),
1850 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
1851 )
1852 .into_any_element()
1853 })
1854 }
1855
1856 pub fn render_overflow_menu(&self) -> impl IntoElement {
1857 PopoverMenu::new("overflow-menu")
1858 .trigger(IconButton::new("overflow-menu-trigger", IconName::Ellipsis))
1859 .menu(move |window, cx| Some(Self::panel_context_menu(window, cx)))
1860 .anchor(Corner::TopRight)
1861 }
1862
1863 pub fn render_sync_button(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
1864 let active_repository = self.project.read(cx).active_repository(cx);
1865 active_repository.as_ref().map(|_| {
1866 panel_filled_button("Fetch")
1867 .icon(IconName::ArrowCircle)
1868 .icon_size(IconSize::Small)
1869 .icon_color(Color::Muted)
1870 .icon_position(IconPosition::Start)
1871 .tooltip(Tooltip::for_action_title("git fetch", &git::Fetch))
1872 .on_click(
1873 cx.listener(move |this, _, window, cx| this.fetch(&git::Fetch, window, cx)),
1874 )
1875 .into_any_element()
1876 })
1877 }
1878
1879 pub fn render_pull_button(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
1880 let active_repository = self.project.read(cx).active_repository(cx);
1881 active_repository
1882 .as_ref()
1883 .and_then(|repo| repo.read(cx).current_branch())
1884 .and_then(|branch| {
1885 branch.upstream.as_ref().map(|upstream| {
1886 let status = &upstream.tracking;
1887
1888 let disabled = status.is_gone();
1889
1890 panel_filled_button(match status {
1891 git::repository::UpstreamTracking::Tracked(status) if status.behind > 0 => {
1892 format!("Pull ({})", status.behind)
1893 }
1894 _ => "Pull".to_string(),
1895 })
1896 .icon(IconName::ArrowDown)
1897 .icon_size(IconSize::Small)
1898 .icon_color(Color::Muted)
1899 .icon_position(IconPosition::Start)
1900 .disabled(status.is_gone())
1901 .tooltip(move |window, cx| {
1902 if disabled {
1903 Tooltip::simple("Upstream is gone", cx)
1904 } else {
1905 // TODO: Add <origin> and <branch> argument substitutions to this
1906 Tooltip::for_action("git pull", &git::Pull, window, cx)
1907 }
1908 })
1909 .on_click(
1910 cx.listener(move |this, _, window, cx| this.pull(&git::Pull, window, cx)),
1911 )
1912 .into_any_element()
1913 })
1914 })
1915 }
1916
1917 pub fn render_repository_selector(&self, cx: &mut Context<Self>) -> impl IntoElement {
1918 let active_repository = self.project.read(cx).active_repository(cx);
1919 let repository_display_name = active_repository
1920 .as_ref()
1921 .map(|repo| repo.read(cx).display_name(self.project.read(cx), cx))
1922 .unwrap_or_default();
1923
1924 RepositorySelectorPopoverMenu::new(
1925 self.repository_selector.clone(),
1926 ButtonLike::new("active-repository")
1927 .style(ButtonStyle::Subtle)
1928 .child(Label::new(repository_display_name).size(LabelSize::Small)),
1929 Tooltip::text("Select a repository"),
1930 )
1931 }
1932
1933 pub fn can_commit(&self) -> bool {
1934 (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
1935 }
1936
1937 pub fn can_stage_all(&self) -> bool {
1938 self.has_unstaged_changes()
1939 }
1940
1941 pub fn can_unstage_all(&self) -> bool {
1942 self.has_staged_changes()
1943 }
1944
1945 pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
1946 let potential_co_authors = self.potential_co_authors(cx);
1947 if potential_co_authors.is_empty() {
1948 None
1949 } else {
1950 Some(
1951 IconButton::new("co-authors", IconName::Person)
1952 .icon_color(Color::Disabled)
1953 .selected_icon_color(Color::Selected)
1954 .toggle_state(self.add_coauthors)
1955 .tooltip(move |_, cx| {
1956 let title = format!(
1957 "Add co-authored-by:{}{}",
1958 if potential_co_authors.len() == 1 {
1959 ""
1960 } else {
1961 "\n"
1962 },
1963 potential_co_authors
1964 .iter()
1965 .map(|(name, email)| format!(" {} <{}>", name, email))
1966 .join("\n")
1967 );
1968 Tooltip::simple(title, cx)
1969 })
1970 .on_click(cx.listener(|this, _, _, cx| {
1971 this.add_coauthors = !this.add_coauthors;
1972 cx.notify();
1973 }))
1974 .into_any_element(),
1975 )
1976 }
1977 }
1978
1979 pub fn render_commit_editor(
1980 &self,
1981 window: &mut Window,
1982 cx: &mut Context<Self>,
1983 ) -> impl IntoElement {
1984 let editor = self.commit_editor.clone();
1985 let can_commit = self.can_commit()
1986 && self.pending_commit.is_none()
1987 && !editor.read(cx).is_empty(cx)
1988 && self.has_write_access(cx);
1989
1990 let panel_editor_style = panel_editor_style(true, window, cx);
1991 let enable_coauthors = self.render_co_authors(cx);
1992
1993 let tooltip = if self.has_staged_changes() {
1994 "git commit"
1995 } else {
1996 "git commit --all"
1997 };
1998 let title = if self.has_staged_changes() {
1999 "Commit"
2000 } else {
2001 "Commit Tracked"
2002 };
2003 let editor_focus_handle = self.commit_editor.focus_handle(cx);
2004
2005 let commit_button = panel_filled_button(title)
2006 .tooltip(move |window, cx| {
2007 Tooltip::for_action_in(tooltip, &Commit, &editor_focus_handle, window, cx)
2008 })
2009 .disabled(!can_commit)
2010 .on_click({
2011 cx.listener(move |this, _: &ClickEvent, window, cx| this.commit_changes(window, cx))
2012 });
2013
2014 let branch = self
2015 .active_repository
2016 .as_ref()
2017 .and_then(|repo| repo.read(cx).current_branch().map(|b| b.name.clone()))
2018 .unwrap_or_else(|| "<no branch>".into());
2019
2020 let branch_selector = Button::new("branch-selector", branch)
2021 .color(Color::Muted)
2022 .style(ButtonStyle::Subtle)
2023 .icon(IconName::GitBranch)
2024 .icon_size(IconSize::Small)
2025 .icon_color(Color::Muted)
2026 .size(ButtonSize::Compact)
2027 .icon_position(IconPosition::Start)
2028 .tooltip(Tooltip::for_action_title(
2029 "Switch Branch",
2030 &zed_actions::git::Branch,
2031 ))
2032 .on_click(cx.listener(|_, _, window, cx| {
2033 window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
2034 }))
2035 .style(ButtonStyle::Transparent);
2036
2037 let footer_size = px(32.);
2038 let gap = px(16.0);
2039
2040 let max_height = window.line_height() * 6. + gap + footer_size;
2041
2042 panel_editor_container(window, cx)
2043 .id("commit-editor-container")
2044 .relative()
2045 .h(max_height)
2046 .w_full()
2047 .border_t_1()
2048 .border_color(cx.theme().colors().border)
2049 .bg(cx.theme().colors().editor_background)
2050 .cursor_text()
2051 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
2052 window.focus(&this.commit_editor.focus_handle(cx));
2053 }))
2054 .when(!self.modal_open, |el| {
2055 el.child(EditorElement::new(&self.commit_editor, panel_editor_style))
2056 .child(
2057 h_flex()
2058 .absolute()
2059 .bottom_0()
2060 .left_2()
2061 .h(footer_size)
2062 .flex_none()
2063 .child(branch_selector),
2064 )
2065 .child(
2066 h_flex()
2067 .absolute()
2068 .bottom_0()
2069 .right_2()
2070 .h(footer_size)
2071 .flex_none()
2072 .children(enable_coauthors)
2073 .child(commit_button),
2074 )
2075 })
2076 }
2077
2078 fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2079 let active_repository = self.active_repository.as_ref()?;
2080 let branch = active_repository.read(cx).current_branch()?;
2081 let commit = branch.most_recent_commit.as_ref()?.clone();
2082
2083 let this = cx.entity();
2084 Some(
2085 h_flex()
2086 .items_center()
2087 .py_1p5()
2088 .px(px(8.))
2089 .bg(cx.theme().colors().background)
2090 .border_t_1()
2091 .border_color(cx.theme().colors().border)
2092 .gap_1p5()
2093 .child(
2094 div()
2095 .flex_grow()
2096 .overflow_hidden()
2097 .max_w(relative(0.6))
2098 .h_full()
2099 .child(
2100 Label::new(commit.subject.clone())
2101 .size(LabelSize::Small)
2102 .text_ellipsis(),
2103 )
2104 .id("commit-msg-hover")
2105 .hoverable_tooltip(move |window, cx| {
2106 GitPanelMessageTooltip::new(
2107 this.clone(),
2108 commit.sha.clone(),
2109 window,
2110 cx,
2111 )
2112 .into()
2113 }),
2114 )
2115 .child(div().flex_1())
2116 .child(
2117 panel_filled_button("Uncommit")
2118 .icon(IconName::Undo)
2119 .icon_size(IconSize::Small)
2120 .icon_color(Color::Muted)
2121 .icon_position(IconPosition::Start)
2122 .tooltip(Tooltip::for_action_title(
2123 if self.has_staged_changes() {
2124 "git reset HEAD^ --soft"
2125 } else {
2126 "git reset HEAD^"
2127 },
2128 &git::Uncommit,
2129 ))
2130 .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
2131 )
2132 .child(self.render_push_button(branch, cx)),
2133 )
2134 }
2135
2136 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
2137 h_flex()
2138 .h_full()
2139 .flex_grow()
2140 .justify_center()
2141 .items_center()
2142 .child(
2143 v_flex()
2144 .gap_3()
2145 .child(if self.active_repository.is_some() {
2146 "No changes to commit"
2147 } else {
2148 "No Git repositories"
2149 })
2150 .text_ui_sm(cx)
2151 .mx_auto()
2152 .text_color(Color::Placeholder.color(cx)),
2153 )
2154 }
2155
2156 fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
2157 let scroll_bar_style = self.show_scrollbar(cx);
2158 let show_container = matches!(scroll_bar_style, ShowScrollbar::Always);
2159
2160 if !self.should_show_scrollbar(cx)
2161 || !(self.show_scrollbar || self.scrollbar_state.is_dragging())
2162 {
2163 return None;
2164 }
2165
2166 Some(
2167 div()
2168 .id("git-panel-vertical-scroll")
2169 .occlude()
2170 .flex_none()
2171 .h_full()
2172 .cursor_default()
2173 .when(show_container, |this| this.pl_1().px_1p5())
2174 .when(!show_container, |this| {
2175 this.absolute().right_1().top_1().bottom_1().w(px(12.))
2176 })
2177 .on_mouse_move(cx.listener(|_, _, _, cx| {
2178 cx.notify();
2179 cx.stop_propagation()
2180 }))
2181 .on_hover(|_, _, cx| {
2182 cx.stop_propagation();
2183 })
2184 .on_any_mouse_down(|_, _, cx| {
2185 cx.stop_propagation();
2186 })
2187 .on_mouse_up(
2188 MouseButton::Left,
2189 cx.listener(|this, _, window, cx| {
2190 if !this.scrollbar_state.is_dragging()
2191 && !this.focus_handle.contains_focused(window, cx)
2192 {
2193 this.hide_scrollbar(window, cx);
2194 cx.notify();
2195 }
2196
2197 cx.stop_propagation();
2198 }),
2199 )
2200 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
2201 cx.notify();
2202 }))
2203 .children(Scrollbar::vertical(
2204 // percentage as f32..end_offset as f32,
2205 self.scrollbar_state.clone(),
2206 )),
2207 )
2208 }
2209
2210 pub fn render_buffer_header_controls(
2211 &self,
2212 entity: &Entity<Self>,
2213 file: &Arc<dyn File>,
2214 _: &Window,
2215 cx: &App,
2216 ) -> Option<AnyElement> {
2217 let repo = self.active_repository.as_ref()?.read(cx);
2218 let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
2219 let ix = self.entry_by_path(&repo_path)?;
2220 let entry = self.entries.get(ix)?;
2221
2222 let is_staged = self.entry_is_staged(entry.status_entry()?);
2223
2224 let checkbox = Checkbox::new("stage-file", is_staged.into())
2225 .disabled(!self.has_write_access(cx))
2226 .fill()
2227 .elevation(ElevationIndex::Surface)
2228 .on_click({
2229 let entry = entry.clone();
2230 let git_panel = entity.downgrade();
2231 move |_, window, cx| {
2232 git_panel
2233 .update(cx, |this, cx| {
2234 this.toggle_staged_for_entry(&entry, window, cx);
2235 cx.stop_propagation();
2236 })
2237 .ok();
2238 }
2239 });
2240 Some(
2241 h_flex()
2242 .id("start-slot")
2243 .text_lg()
2244 .child(checkbox)
2245 .on_mouse_down(MouseButton::Left, |_, _, cx| {
2246 // prevent the list item active state triggering when toggling checkbox
2247 cx.stop_propagation();
2248 })
2249 .into_any_element(),
2250 )
2251 }
2252
2253 fn render_entries(
2254 &self,
2255 has_write_access: bool,
2256 _: &Window,
2257 cx: &mut Context<Self>,
2258 ) -> impl IntoElement {
2259 let entry_count = self.entries.len();
2260
2261 v_flex()
2262 .size_full()
2263 .flex_grow()
2264 .overflow_hidden()
2265 .child(
2266 uniform_list(cx.entity().clone(), "entries", entry_count, {
2267 move |this, range, window, cx| {
2268 let mut items = Vec::with_capacity(range.end - range.start);
2269
2270 for ix in range {
2271 match &this.entries.get(ix) {
2272 Some(GitListEntry::GitStatusEntry(entry)) => {
2273 items.push(this.render_entry(
2274 ix,
2275 entry,
2276 has_write_access,
2277 window,
2278 cx,
2279 ));
2280 }
2281 Some(GitListEntry::Header(header)) => {
2282 items.push(this.render_list_header(
2283 ix,
2284 header,
2285 has_write_access,
2286 window,
2287 cx,
2288 ));
2289 }
2290 None => {}
2291 }
2292 }
2293
2294 items
2295 }
2296 })
2297 .size_full()
2298 .with_sizing_behavior(ListSizingBehavior::Infer)
2299 .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
2300 .track_scroll(self.scroll_handle.clone()),
2301 )
2302 .on_mouse_down(
2303 MouseButton::Right,
2304 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
2305 this.deploy_panel_context_menu(event.position, window, cx)
2306 }),
2307 )
2308 .children(self.render_scrollbar(cx))
2309 }
2310
2311 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
2312 Label::new(label.into()).color(color).single_line()
2313 }
2314
2315 fn render_list_header(
2316 &self,
2317 ix: usize,
2318 header: &GitHeaderEntry,
2319 _: bool,
2320 _: &Window,
2321 _: &Context<Self>,
2322 ) -> AnyElement {
2323 div()
2324 .w_full()
2325 .child(
2326 ListItem::new(ix)
2327 .spacing(ListItemSpacing::Sparse)
2328 .disabled(true)
2329 .child(
2330 Label::new(header.title())
2331 .color(Color::Muted)
2332 .size(LabelSize::Small)
2333 .single_line(),
2334 ),
2335 )
2336 .into_any_element()
2337 }
2338
2339 fn load_commit_details(
2340 &self,
2341 sha: &str,
2342 cx: &mut Context<Self>,
2343 ) -> Task<Result<CommitDetails>> {
2344 let Some(repo) = self.active_repository.clone() else {
2345 return Task::ready(Err(anyhow::anyhow!("no active repo")));
2346 };
2347 repo.update(cx, |repo, cx| repo.show(sha, cx))
2348 }
2349
2350 fn deploy_entry_context_menu(
2351 &mut self,
2352 position: Point<Pixels>,
2353 ix: usize,
2354 window: &mut Window,
2355 cx: &mut Context<Self>,
2356 ) {
2357 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
2358 return;
2359 };
2360 let stage_title = if entry.status.is_staged() == Some(true) {
2361 "Unstage File"
2362 } else {
2363 "Stage File"
2364 };
2365 let revert_title = if entry.status.is_deleted() {
2366 "Restore file"
2367 } else if entry.status.is_created() {
2368 "Trash file"
2369 } else {
2370 "Discard changes"
2371 };
2372 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
2373 context_menu
2374 .action(stage_title, ToggleStaged.boxed_clone())
2375 .action(revert_title, git::RestoreFile.boxed_clone())
2376 .separator()
2377 .action("Open Diff", Confirm.boxed_clone())
2378 .action("Open File", SecondaryConfirm.boxed_clone())
2379 });
2380 self.selected_entry = Some(ix);
2381 self.set_context_menu(context_menu, position, window, cx);
2382 }
2383
2384 fn panel_context_menu(window: &mut Window, cx: &mut App) -> Entity<ContextMenu> {
2385 ContextMenu::build(window, cx, |context_menu, _, _| {
2386 context_menu
2387 .action("Stage All", StageAll.boxed_clone())
2388 .action("Unstage All", UnstageAll.boxed_clone())
2389 .separator()
2390 .action("Open Diff", project_diff::Diff.boxed_clone())
2391 .separator()
2392 .action("Discard Tracked Changes", RestoreTrackedFiles.boxed_clone())
2393 .action("Trash Untracked Files", TrashUntrackedFiles.boxed_clone())
2394 })
2395 }
2396
2397 fn deploy_panel_context_menu(
2398 &mut self,
2399 position: Point<Pixels>,
2400 window: &mut Window,
2401 cx: &mut Context<Self>,
2402 ) {
2403 let context_menu = Self::panel_context_menu(window, cx);
2404 self.set_context_menu(context_menu, position, window, cx);
2405 }
2406
2407 fn set_context_menu(
2408 &mut self,
2409 context_menu: Entity<ContextMenu>,
2410 position: Point<Pixels>,
2411 window: &Window,
2412 cx: &mut Context<Self>,
2413 ) {
2414 let subscription = cx.subscribe_in(
2415 &context_menu,
2416 window,
2417 |this, _, _: &DismissEvent, window, cx| {
2418 if this.context_menu.as_ref().is_some_and(|context_menu| {
2419 context_menu.0.focus_handle(cx).contains_focused(window, cx)
2420 }) {
2421 cx.focus_self(window);
2422 }
2423 this.context_menu.take();
2424 cx.notify();
2425 },
2426 );
2427 self.context_menu = Some((context_menu, position, subscription));
2428 cx.notify();
2429 }
2430
2431 fn render_entry(
2432 &self,
2433 ix: usize,
2434 entry: &GitStatusEntry,
2435 has_write_access: bool,
2436 window: &Window,
2437 cx: &Context<Self>,
2438 ) -> AnyElement {
2439 let display_name = entry
2440 .repo_path
2441 .file_name()
2442 .map(|name| name.to_string_lossy().into_owned())
2443 .unwrap_or_else(|| entry.repo_path.to_string_lossy().into_owned());
2444
2445 let repo_path = entry.repo_path.clone();
2446 let selected = self.selected_entry == Some(ix);
2447 let status_style = GitPanelSettings::get_global(cx).status_style;
2448 let status = entry.status;
2449 let has_conflict = status.is_conflicted();
2450 let is_modified = status.is_modified();
2451 let is_deleted = status.is_deleted();
2452
2453 let label_color = if status_style == StatusStyle::LabelColor {
2454 if has_conflict {
2455 Color::Conflict
2456 } else if is_modified {
2457 Color::Modified
2458 } else if is_deleted {
2459 // We don't want a bunch of red labels in the list
2460 Color::Disabled
2461 } else {
2462 Color::Created
2463 }
2464 } else {
2465 Color::Default
2466 };
2467
2468 let path_color = if status.is_deleted() {
2469 Color::Disabled
2470 } else {
2471 Color::Muted
2472 };
2473
2474 let id: ElementId = ElementId::Name(format!("entry_{}", display_name).into());
2475
2476 let mut is_staged: ToggleState = self.entry_is_staged(entry).into();
2477
2478 if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
2479 is_staged = ToggleState::Selected;
2480 }
2481
2482 let checkbox = Checkbox::new(id, is_staged)
2483 .disabled(!has_write_access)
2484 .fill()
2485 .placeholder(!self.has_staged_changes() && !self.has_conflicts())
2486 .elevation(ElevationIndex::Surface)
2487 .on_click({
2488 let entry = entry.clone();
2489 cx.listener(move |this, _, window, cx| {
2490 this.toggle_staged_for_entry(
2491 &GitListEntry::GitStatusEntry(entry.clone()),
2492 window,
2493 cx,
2494 );
2495 cx.stop_propagation();
2496 })
2497 });
2498
2499 let start_slot =
2500 h_flex()
2501 .id(("start-slot", ix))
2502 .gap(DynamicSpacing::Base04.rems(cx))
2503 .child(checkbox.tooltip(|window, cx| {
2504 Tooltip::for_action("Stage File", &ToggleStaged, window, cx)
2505 }))
2506 .child(git_status_icon(status, cx))
2507 .on_mouse_down(MouseButton::Left, |_, _, cx| {
2508 // prevent the list item active state triggering when toggling checkbox
2509 cx.stop_propagation();
2510 });
2511
2512 div()
2513 .w_full()
2514 .child(
2515 ListItem::new(ix)
2516 .spacing(ListItemSpacing::Sparse)
2517 .start_slot(start_slot)
2518 .toggle_state(selected)
2519 .focused(selected && self.focus_handle(cx).is_focused(window))
2520 .disabled(!has_write_access)
2521 .on_click({
2522 cx.listener(move |this, event: &ClickEvent, window, cx| {
2523 this.selected_entry = Some(ix);
2524 cx.notify();
2525 if event.modifiers().secondary() {
2526 this.open_file(&Default::default(), window, cx)
2527 } else {
2528 this.open_diff(&Default::default(), window, cx);
2529 }
2530 })
2531 })
2532 .on_secondary_mouse_down(cx.listener(
2533 move |this, event: &MouseDownEvent, window, cx| {
2534 this.deploy_entry_context_menu(event.position, ix, window, cx);
2535 cx.stop_propagation();
2536 },
2537 ))
2538 .child(
2539 h_flex()
2540 .when_some(repo_path.parent(), |this, parent| {
2541 let parent_str = parent.to_string_lossy();
2542 if !parent_str.is_empty() {
2543 this.child(
2544 self.entry_label(format!("{}/", parent_str), path_color)
2545 .when(status.is_deleted(), |this| this.strikethrough()),
2546 )
2547 } else {
2548 this
2549 }
2550 })
2551 .child(
2552 self.entry_label(display_name.clone(), label_color)
2553 .when(status.is_deleted(), |this| this.strikethrough()),
2554 ),
2555 ),
2556 )
2557 .into_any_element()
2558 }
2559
2560 fn render_push_button(&self, branch: &Branch, cx: &Context<Self>) -> AnyElement {
2561 let mut disabled = false;
2562
2563 // TODO: Add <origin> and <branch> argument substitutions to this
2564 let button: SharedString;
2565 let tooltip: SharedString;
2566 let action: Option<Push>;
2567 if let Some(upstream) = &branch.upstream {
2568 match upstream.tracking {
2569 UpstreamTracking::Gone => {
2570 button = "Republish".into();
2571 tooltip = "git push --set-upstream".into();
2572 action = Some(git::Push {
2573 options: Some(PushOptions::SetUpstream),
2574 });
2575 }
2576 UpstreamTracking::Tracked(tracking) => {
2577 if tracking.behind > 0 {
2578 disabled = true;
2579 button = "Push".into();
2580 tooltip = "Upstream is ahead of local branch".into();
2581 action = None;
2582 } else if tracking.ahead > 0 {
2583 button = format!("Push ({})", tracking.ahead).into();
2584 tooltip = "git push".into();
2585 action = Some(git::Push { options: None });
2586 } else {
2587 disabled = true;
2588 button = "Push".into();
2589 tooltip = "Upstream matches local branch".into();
2590 action = None;
2591 }
2592 }
2593 }
2594 } else {
2595 button = "Publish".into();
2596 tooltip = "git push --set-upstream".into();
2597 action = Some(git::Push {
2598 options: Some(PushOptions::SetUpstream),
2599 });
2600 };
2601
2602 panel_filled_button(button)
2603 .icon(IconName::ArrowUp)
2604 .icon_size(IconSize::Small)
2605 .icon_color(Color::Muted)
2606 .icon_position(IconPosition::Start)
2607 .disabled(disabled)
2608 .when_some(action, |this, action| {
2609 this.on_click(
2610 cx.listener(move |this, _, window, cx| this.push(&action, window, cx)),
2611 )
2612 })
2613 .tooltip(move |window, cx| {
2614 if let Some(action) = action.as_ref() {
2615 Tooltip::for_action(tooltip.clone(), action, window, cx)
2616 } else {
2617 Tooltip::simple(tooltip.clone(), cx)
2618 }
2619 })
2620 .into_any_element()
2621 }
2622
2623 fn has_write_access(&self, cx: &App) -> bool {
2624 !self.project.read(cx).is_read_only(cx)
2625 }
2626}
2627
2628impl Render for GitPanel {
2629 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2630 let project = self.project.read(cx);
2631 let has_entries = self.entries.len() > 0;
2632 let room = self
2633 .workspace
2634 .upgrade()
2635 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
2636
2637 let has_write_access = self.has_write_access(cx);
2638
2639 let has_co_authors = room.map_or(false, |room| {
2640 room.read(cx)
2641 .remote_participants()
2642 .values()
2643 .any(|remote_participant| remote_participant.can_write())
2644 });
2645
2646 v_flex()
2647 .id("git_panel")
2648 .key_context(self.dispatch_context(window, cx))
2649 .track_focus(&self.focus_handle)
2650 .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
2651 .when(has_write_access && !project.is_read_only(cx), |this| {
2652 this.on_action(cx.listener(|this, &ToggleStaged, window, cx| {
2653 this.toggle_staged_for_selected(&ToggleStaged, window, cx)
2654 }))
2655 .on_action(cx.listener(GitPanel::commit))
2656 })
2657 .on_action(cx.listener(Self::select_first))
2658 .on_action(cx.listener(Self::select_next))
2659 .on_action(cx.listener(Self::select_prev))
2660 .on_action(cx.listener(Self::select_last))
2661 .on_action(cx.listener(Self::close_panel))
2662 .on_action(cx.listener(Self::open_diff))
2663 .on_action(cx.listener(Self::open_file))
2664 .on_action(cx.listener(Self::revert_selected))
2665 .on_action(cx.listener(Self::focus_changes_list))
2666 .on_action(cx.listener(Self::focus_editor))
2667 .on_action(cx.listener(Self::toggle_staged_for_selected))
2668 .on_action(cx.listener(Self::stage_all))
2669 .on_action(cx.listener(Self::unstage_all))
2670 .on_action(cx.listener(Self::discard_tracked_changes))
2671 .on_action(cx.listener(Self::clean_all))
2672 .on_action(cx.listener(Self::fetch))
2673 .on_action(cx.listener(Self::pull))
2674 .on_action(cx.listener(Self::push))
2675 .when(has_write_access && has_co_authors, |git_panel| {
2676 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
2677 })
2678 // .on_action(cx.listener(|this, &OpenSelected, cx| this.open_selected(&OpenSelected, cx)))
2679 .on_hover(cx.listener(|this, hovered, window, cx| {
2680 if *hovered {
2681 this.show_scrollbar = true;
2682 this.hide_scrollbar_task.take();
2683 cx.notify();
2684 } else if !this.focus_handle.contains_focused(window, cx) {
2685 this.hide_scrollbar(window, cx);
2686 }
2687 }))
2688 .size_full()
2689 .overflow_hidden()
2690 .bg(ElevationIndex::Surface.bg(cx))
2691 .child(
2692 v_flex()
2693 .size_full()
2694 .children(self.render_panel_header(window, cx))
2695 .map(|this| {
2696 if has_entries {
2697 this.child(self.render_entries(has_write_access, window, cx))
2698 } else {
2699 this.child(self.render_empty_state(cx).into_any_element())
2700 }
2701 })
2702 .children(self.render_previous_commit(cx))
2703 .child(self.render_commit_editor(window, cx))
2704 .into_any_element(),
2705 )
2706 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
2707 deferred(
2708 anchored()
2709 .position(*position)
2710 .anchor(gpui::Corner::TopLeft)
2711 .child(menu.clone()),
2712 )
2713 .with_priority(1)
2714 }))
2715 }
2716}
2717
2718impl Focusable for GitPanel {
2719 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
2720 self.focus_handle.clone()
2721 }
2722}
2723
2724impl EventEmitter<Event> for GitPanel {}
2725
2726impl EventEmitter<PanelEvent> for GitPanel {}
2727
2728pub(crate) struct GitPanelAddon {
2729 pub(crate) workspace: WeakEntity<Workspace>,
2730}
2731
2732impl editor::Addon for GitPanelAddon {
2733 fn to_any(&self) -> &dyn std::any::Any {
2734 self
2735 }
2736
2737 fn render_buffer_header_controls(
2738 &self,
2739 excerpt_info: &ExcerptInfo,
2740 window: &Window,
2741 cx: &App,
2742 ) -> Option<AnyElement> {
2743 let file = excerpt_info.buffer.file()?;
2744 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
2745
2746 git_panel
2747 .read(cx)
2748 .render_buffer_header_controls(&git_panel, &file, window, cx)
2749 }
2750}
2751
2752impl Panel for GitPanel {
2753 fn persistent_name() -> &'static str {
2754 "GitPanel"
2755 }
2756
2757 fn position(&self, _: &Window, cx: &App) -> DockPosition {
2758 GitPanelSettings::get_global(cx).dock
2759 }
2760
2761 fn position_is_valid(&self, position: DockPosition) -> bool {
2762 matches!(position, DockPosition::Left | DockPosition::Right)
2763 }
2764
2765 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
2766 settings::update_settings_file::<GitPanelSettings>(
2767 self.fs.clone(),
2768 cx,
2769 move |settings, _| settings.dock = Some(position),
2770 );
2771 }
2772
2773 fn size(&self, _: &Window, cx: &App) -> Pixels {
2774 self.width
2775 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
2776 }
2777
2778 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
2779 self.width = size;
2780 self.serialize(cx);
2781 cx.notify();
2782 }
2783
2784 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
2785 Some(ui::IconName::GitBranch).filter(|_| GitPanelSettings::get_global(cx).button)
2786 }
2787
2788 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
2789 Some("Git Panel")
2790 }
2791
2792 fn toggle_action(&self) -> Box<dyn Action> {
2793 Box::new(ToggleFocus)
2794 }
2795
2796 fn activation_priority(&self) -> u32 {
2797 2
2798 }
2799}
2800
2801impl PanelHeader for GitPanel {}
2802
2803struct GitPanelMessageTooltip {
2804 commit_tooltip: Option<Entity<CommitTooltip>>,
2805}
2806
2807impl GitPanelMessageTooltip {
2808 fn new(
2809 git_panel: Entity<GitPanel>,
2810 sha: SharedString,
2811 window: &mut Window,
2812 cx: &mut App,
2813 ) -> Entity<Self> {
2814 cx.new(|cx| {
2815 cx.spawn_in(window, |this, mut cx| async move {
2816 let details = git_panel
2817 .update(&mut cx, |git_panel, cx| {
2818 git_panel.load_commit_details(&sha, cx)
2819 })?
2820 .await?;
2821
2822 let commit_details = editor::commit_tooltip::CommitDetails {
2823 sha: details.sha.clone(),
2824 committer_name: details.committer_name.clone(),
2825 committer_email: details.committer_email.clone(),
2826 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
2827 message: Some(editor::commit_tooltip::ParsedCommitMessage {
2828 message: details.message.clone(),
2829 ..Default::default()
2830 }),
2831 };
2832
2833 this.update_in(&mut cx, |this: &mut GitPanelMessageTooltip, window, cx| {
2834 this.commit_tooltip =
2835 Some(cx.new(move |cx| CommitTooltip::new(commit_details, window, cx)));
2836 cx.notify();
2837 })
2838 })
2839 .detach();
2840
2841 Self {
2842 commit_tooltip: None,
2843 }
2844 })
2845 }
2846}
2847
2848impl Render for GitPanelMessageTooltip {
2849 fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
2850 if let Some(commit_tooltip) = &self.commit_tooltip {
2851 commit_tooltip.clone().into_any_element()
2852 } else {
2853 gpui::Empty.into_any_element()
2854 }
2855 }
2856}