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