Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

git_ui: Show changes since a base branch in the git panel (#66482)

Smit Barmaseddc9eda92552
diff --git a/crates/git_ui/src/branch_diff.rs b/crates/git_ui/src/branch_diff.rs
index 31cf501dd66..03e09e507f3 100644
--- a/crates/git_ui/src/branch_diff.rs
+++ b/crates/git_ui/src/branch_diff.rs
@@ -1,6 +1,7 @@
use crate::{
branch_picker,
diff_multibuffer::DiffMultibuffer,
+ git_panel::GitStatusEntry,
project_diff::{
self, CompareWithBranch, DeployBranchDiff, ProjectDiff, ReviewDiff,
render_send_review_to_agent_button,
@@ -125,6 +126,7 @@ impl BranchDiff {
intended_repo,
base_ref,
branch_diff,
+ None,
window,
cx,
);
@@ -172,6 +174,7 @@ impl BranchDiff {
repository.clone(),
base_ref,
None,
+ None,
window,
cx,
);
@@ -198,6 +201,7 @@ impl BranchDiff {
intended_repo: Entity<Repository>,
base_ref: SharedString,
branch_diff: Option<Entity<diff_buffer_list::DiffBufferList>>,
+ entry: Option<GitStatusEntry>,
window: &mut Window,
cx: &mut Context<Workspace>,
) {
@@ -215,34 +219,32 @@ impl BranchDiff {
});
if let Some(existing) = existing {
workspace.activate_item(&existing, true, true, window, cx);
+ if let Some(entry) = entry {
+ existing.update(cx, |branch_diff, cx| {
+ branch_diff.move_to_entry(entry, window, cx);
+ });
+ }
return;
}
- let workspace = cx.entity();
- let workspace_weak = workspace.downgrade();
- window
- .spawn(cx, async move |cx| {
- let this = cx
- .update(|window, cx| {
- Self::new_with_branch_base(
- project,
- workspace.clone(),
- base_ref,
- intended_repo,
- branch_diff,
- window,
- cx,
- )
- })?
- .await?;
- workspace
- .update_in(cx, |workspace, window, cx| {
- workspace.add_item_to_active_pane(Box::new(this), None, true, window, cx);
- })
- .ok();
- anyhow::Ok(())
- })
- .detach_and_notify_err(workspace_weak, window, cx);
+ let workspace_handle = cx.entity();
+ let branch_diff = cx.new(|cx| {
+ Self::new_with_base_ref(
+ project,
+ workspace_handle,
+ base_ref,
+ Some(intended_repo),
+ branch_diff,
+ window,
+ cx,
+ )
+ });
+ workspace.add_item_to_active_pane(Box::new(branch_diff.clone()), None, true, window, cx);
+ if let Some(entry) = entry {
+ branch_diff.update(cx, |branch_diff, cx| {
+ branch_diff.move_to_entry(entry, window, cx);
+ });
+ }
}
#[cfg(any(test, feature = "test-support"))]
@@ -285,32 +287,6 @@ impl BranchDiff {
})
}
- pub(crate) fn new_with_branch_base(
- project: Entity<Project>,
- workspace: Entity<Workspace>,
- base_ref: SharedString,
- repo: Entity<Repository>,
- branch_diff: Option<Entity<diff_buffer_list::DiffBufferList>>,
- window: &mut Window,
- cx: &mut App,
- ) -> Task<Result<Entity<Self>>> {
- window.spawn(cx, async move |cx| {
- cx.update(|window, cx| {
- cx.new(|cx| {
- Self::new_with_base_ref(
- project,
- workspace,
- base_ref,
- Some(repo),
- branch_diff,
- window,
- cx,
- )
- })
- })
- })
- }
-
pub(crate) fn new_with_base_ref(
project: Entity<Project>,
workspace: Entity<Workspace>,
@@ -380,6 +356,24 @@ impl BranchDiff {
self.diff.read(cx).repo(cx)
}
+ pub(crate) fn branch_diff_list(&self, cx: &App) -> Entity<diff_buffer_list::DiffBufferList> {
+ self.diff.read(cx).branch_diff().clone()
+ }
+
+ pub(crate) fn move_to_entry(
+ &mut self,
+ entry: GitStatusEntry,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.diff
+ .update(cx, |diff, cx| diff.move_to_entry(entry, window, cx));
+ }
+
+ pub(crate) fn autoscroll(&self, cx: &mut Context<Self>) {
+ self.diff.update(cx, |diff, cx| diff.autoscroll(cx));
+ }
+
fn set_merge_base(&mut self, base_ref: SharedString, cx: &mut Context<Self>) {
self.diff.update(cx, |diff, cx| {
diff.branch_diff().update(cx, |branch_diff, cx| {
@@ -838,6 +832,7 @@ impl Render for BranchDiffToolbar {
repository,
base_ref,
None,
+ None,
window,
cx,
);
@@ -909,7 +904,6 @@ impl Render for BranchDiffToolbar {
#[cfg(test)]
mod tests {
- use anyhow::anyhow;
use collections::HashMap;
use editor::test::editor_test_context::assert_state_with_diff;
use git::status::{FileStatus, TrackedStatus, UnmergedStatus, UnmergedStatusCode};
@@ -1213,12 +1207,10 @@ mod tests {
cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
- let target_branch_diff = cx
- .update(|window, cx| {
- let Some(repository) = project.read(cx).active_repository(cx) else {
- return Task::ready(Err(anyhow!("No active repository")));
- };
- BranchDiff::new_with_branch_base(
+ let target_branch_diff = cx.update(|window, cx| {
+ let repository = project.read(cx).active_repository(cx);
+ cx.new(|cx| {
+ BranchDiff::new_with_base_ref(
project.clone(),
workspace.clone(),
"topic".into(),
@@ -1228,8 +1220,7 @@ mod tests {
cx,
)
})
- .await
- .unwrap();
+ });
workspace.update_in(cx, |workspace, window, cx| {
workspace.add_item_to_active_pane(
Box::new(target_branch_diff.clone()),
diff --git a/crates/git_ui/src/branch_picker.rs b/crates/git_ui/src/branch_picker.rs
index aefe0d41253..c47331731a6 100644
--- a/crates/git_ui/src/branch_picker.rs
+++ b/crates/git_ui/src/branch_picker.rs
@@ -123,6 +123,7 @@ pub fn select_popover(
repository,
BranchListStyle::Popover,
rems(20.),
+ false,
selected_branch,
on_select,
window,
@@ -146,6 +147,7 @@ pub fn select_modal(
repository,
BranchListStyle::Modal,
rems(34.),
+ false,
selected_branch,
on_select,
window,
@@ -155,6 +157,37 @@ pub fn select_modal(
list
}
+/// A branch selector for hosts that draw their own surface and handle
+/// dismissal, such as a context menu's submenu.
+pub fn select_embedded(
+ workspace: WeakEntity<Workspace>,
+ repository: Option<Entity<Repository>>,
+ selected_branch: Option<SharedString>,
+ on_select: SelectBranchCallback,
+ window: &mut Window,
+ cx: &mut Context<BranchList>,
+) -> BranchList {
+ let list = BranchList::new_select(
+ workspace,
+ repository,
+ BranchListStyle::Popover,
+ rems(20.),
+ true,
+ selected_branch,
+ on_select,
+ window,
+ cx,
+ );
+ // A popover opened from a submenu draws beneath it, so the filter gets no
+ // menu here. Without one, a saved filter couldn't be seen or changed.
+ list.picker.update(cx, |picker, cx| {
+ picker.delegate.has_filter_menu = false;
+ picker.delegate.branch_filter = BranchFilter::All;
+ picker.refresh(window, cx);
+ });
+ list
+}
+
pub type SelectBranchCallback = Arc<dyn Fn(Branch, &mut Window, &mut App)>;
pub fn create_embedded(
@@ -226,6 +259,7 @@ impl BranchList {
repository: Option<Entity<Repository>>,
style: BranchListStyle,
width: Rems,
+ embedded: bool,
selected_branch: Option<SharedString>,
on_select: SelectBranchCallback,
window: &mut Window,
@@ -236,7 +270,7 @@ impl BranchList {
repository,
style,
width,
- false,
+ embedded,
BranchSelectionBehavior::Select {
selected_branch,
on_select,
@@ -518,12 +552,11 @@ impl Render for BranchList {
)
.on_action(
cx.listener(|this, _: &branch_picker::ToggleFilterMenu, window, cx| {
- let menu_handle = this
- .picker
- .read(cx)
- .delegate
- .branch_filter_menu_handle
- .clone();
+ let delegate = &this.picker.read(cx).delegate;
+ if !delegate.has_filter_menu {
+ return;
+ }
+ let menu_handle = delegate.branch_filter_menu_handle.clone();
menu_handle.toggle(window, cx);
}),
)
@@ -669,6 +702,7 @@ pub struct BranchListDelegate {
modifiers: Modifiers,
branch_filter: BranchFilter,
branch_filter_menu_handle: PopoverMenuHandle<ContextMenu>,
+ has_filter_menu: bool,
state: PickerState,
branch_selection_behavior: BranchSelectionBehavior,
focus_handle: FocusHandle,
@@ -1023,6 +1057,7 @@ impl BranchListDelegate {
modifiers: Default::default(),
branch_filter,
branch_filter_menu_handle: PopoverMenuHandle::default(),
+ has_filter_menu: true,
state: PickerState::List,
branch_selection_behavior,
focus_handle: cx.focus_handle(),
@@ -1257,6 +1292,7 @@ impl PickerDelegate for BranchListDelegate {
fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
match self.state {
+ PickerState::List if self.is_select_only() => "Select a branch…",
PickerState::List | PickerState::NewRemote | PickerState::NewBranch => {
"Switch or type to create a branch…"
}
@@ -1310,7 +1346,7 @@ impl PickerDelegate for BranchListDelegate {
.flex_none()
.overflow_hidden()
.child(editor.clone())
- .map(|this| {
+ .when(self.has_filter_menu, |this| {
let branch_filter = self.branch_filter;
let focus_handle = self.focus_handle.clone();
@@ -3135,6 +3171,7 @@ mod tests {
Some(repository.clone()),
BranchListStyle::Modal,
rems(34.),
+ false,
Some("main".into()),
Arc::new(|_: Branch, _: &mut Window, _: &mut App| {}),
window,
diff --git a/crates/git_ui/src/diff_multibuffer.rs b/crates/git_ui/src/diff_multibuffer.rs
index 6c9aeb35cae..02d73bba295 100644
--- a/crates/git_ui/src/diff_multibuffer.rs
+++ b/crates/git_ui/src/diff_multibuffer.rs
@@ -624,11 +624,16 @@ impl DiffMultibuffer {
#[instrument(skip(this, cx))]
pub(crate) async fn refresh(this: WeakEntity<Self>, cx: &mut AsyncWindowContext) -> Result<()> {
- let entries = this.update(cx, |this, cx| {
- let (repo, buffers_to_load) = this.branch_diff.update(cx, |branch_diff, cx| {
- let load_buffers = branch_diff.load_buffers(cx);
- (branch_diff.repo().cloned(), load_buffers)
- });
+ let (entries, list_was_loading) = this.update(cx, |this, cx| {
+ let (repo, buffers_to_load, list_was_loading) =
+ this.branch_diff.update(cx, |branch_diff, cx| {
+ let load_buffers = branch_diff.load_buffers(cx);
+ (
+ branch_diff.repo().cloned(),
+ load_buffers,
+ branch_diff.is_awaiting_tree_diff(),
+ )
+ });
let mut previous_paths = this
.multibuffer
.read(cx)
@@ -679,7 +684,7 @@ impl DiffMultibuffer {
this.buffer_subscriptions
.retain(|repo_path, _| live_repo_paths.contains(repo_path));
- entries
+ (entries, list_was_loading)
})?;
let mut buffers_to_fold = Vec::new();
@@ -728,7 +733,11 @@ impl DiffMultibuffer {
.update(cx, |editor, cx| editor.fold_buffers(buffers_to_fold, cx));
});
}
- this.pending_scroll.take();
+ // A list still loading had no files to scroll to, so the scroll
+ // waits for the refresh that brings them.
+ if !list_was_loading {
+ this.pending_scroll.take();
+ }
cx.notify();
})?;
diff --git a/crates/git_ui/src/git_panel.rs b/crates/git_ui/src/git_panel.rs
index 346aa792bd0..688e49413a8 100644
--- a/crates/git_ui/src/git_panel.rs
+++ b/crates/git_ui/src/git_panel.rs
@@ -1,6 +1,9 @@
+mod branch_mode;
+
use git_ui_core::askpass_modal::AskPassModal;
pub(crate) use git_ui_core::notifications::{open_output, show_error_toast};
+use crate::branch_diff::BranchDiff;
use crate::commit_context_menu::{
CommitContextMenuData, CommitContextMenuSource, commit_context_menu,
};
@@ -8,7 +11,7 @@ use crate::commit_modal::CommitModal;
use crate::commit_tooltip::{CommitAvatar, CommitTooltip};
use crate::commit_view::CommitView;
use crate::git_panel_settings::GitPanelScrollbarAccessor;
-use crate::project_diff::{DeployBranchDiff, Diff, ProjectDiff};
+use crate::project_diff::{Diff, ProjectDiff};
use crate::remote_output::{self, RemoteAction, SuccessMessage};
use crate::solo_diff_view::SoloDiffView;
use crate::staged_diff::StagedDiff;
@@ -20,6 +23,7 @@ use crate::{
use agent_settings::{AgentSettings, UserAgentsMd};
use anyhow::Context as _;
use askpass::AskPassDelegate;
+use branch_mode::{BranchBase, ChangesMode};
use client::zed_urls;
use collections::{BTreeMap, HashMap, HashSet};
use db::kvp::KeyValueStore;
@@ -67,7 +71,9 @@ use project::git_store::GitAccess;
use project::{
Fs, Project, ProjectPath,
git_store::{
- CommitDataState, GitStoreEvent, Repository, RepositoryEvent, RepositoryId, pending_op,
+ CommitDataState, GitStoreEvent, Repository, RepositoryEvent, RepositoryId,
+ diff_buffer_list::{BranchDiffEvent, DiffBase, DiffBufferList},
+ pending_op,
},
project_settings::{GitPathStyle, ProjectSettings},
};
@@ -84,6 +90,7 @@ use std::future::Future;
use std::ops::Range;
use std::path::Path;
use std::rc::Rc;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::{sync::Arc, time::Duration};
use strum::{IntoEnumIterator, VariantNames};
use theme_settings::ThemeSettings;
@@ -164,6 +171,12 @@ actions!(
ActivateChangesTab,
/// Activates the History tab.
ActivateHistoryTab,
+ /// Shows the files changed on the current branch since its base branch.
+ ShowBranchChanges,
+ /// Shows the uncommitted changes.
+ ShowUncommittedChanges,
+ /// Picks a base branch and shows the files changed since it.
+ CompareAgainstBase,
]
);
@@ -404,6 +417,7 @@ fn git_panel_context_menu(
fn git_panel_view_options_menu(
focus_handle: FocusHandle,
+ show_group_by: bool,
window: &mut Window,
cx: &mut App,
) -> Entity<ContextMenu> {
@@ -479,51 +493,53 @@ fn git_panel_view_options_menu(
})
})
})
- .separator()
- .header("Group By")
- .item({
- let view_options_menu_state = view_options_menu_state.clone();
- ContextMenuEntry::new("None")
- .toggle(IconPosition::End, state.group_by == GitPanelGroupBy::None)
- .handler(move |window, cx| {
- if state.group_by != GitPanelGroupBy::None {
- view_options_menu_state.set(GitPanelViewOptionsMenuState {
- group_by: GitPanelGroupBy::None,
- ..state
- });
- window.dispatch_action(Box::new(SetGroupByNone), cx);
- }
+ .when(show_group_by, |this| {
+ this.separator()
+ .header("Group By")
+ .item({
+ let view_options_menu_state = view_options_menu_state.clone();
+ ContextMenuEntry::new("None")
+ .toggle(IconPosition::End, state.group_by == GitPanelGroupBy::None)
+ .handler(move |window, cx| {
+ if state.group_by != GitPanelGroupBy::None {
+ view_options_menu_state.set(GitPanelViewOptionsMenuState {
+ group_by: GitPanelGroupBy::None,
+ ..state
+ });
+ window.dispatch_action(Box::new(SetGroupByNone), cx);
+ }
+ })
})
- })
- .item({
- let view_options_menu_state = view_options_menu_state.clone();
- ContextMenuEntry::new("Tracked & Untracked")
- .toggle(IconPosition::End, state.group_by == GitPanelGroupBy::Status)
- .handler(move |window, cx| {
- if state.group_by != GitPanelGroupBy::Status {
- view_options_menu_state.set(GitPanelViewOptionsMenuState {
- group_by: GitPanelGroupBy::Status,
- ..state
- });
- window.dispatch_action(Box::new(SetGroupByStatus), cx);
- }
+ .item({
+ let view_options_menu_state = view_options_menu_state.clone();
+ ContextMenuEntry::new("Tracked & Untracked")
+ .toggle(IconPosition::End, state.group_by == GitPanelGroupBy::Status)
+ .handler(move |window, cx| {
+ if state.group_by != GitPanelGroupBy::Status {
+ view_options_menu_state.set(GitPanelViewOptionsMenuState {
+ group_by: GitPanelGroupBy::Status,
+ ..state
+ });
+ window.dispatch_action(Box::new(SetGroupByStatus), cx);
+ }
+ })
})
- })
- .item({
- let view_options_menu_state = view_options_menu_state.clone();
- ContextMenuEntry::new("Staged & Unstaged")
- .toggle(
- IconPosition::End,
- state.group_by == GitPanelGroupBy::Staging,
- )
- .handler(move |window, cx| {
- if state.group_by != GitPanelGroupBy::Staging {
- view_options_menu_state.set(GitPanelViewOptionsMenuState {
- group_by: GitPanelGroupBy::Staging,
- ..state
- });
- window.dispatch_action(Box::new(SetGroupByStaging), cx);
- }
+ .item({
+ let view_options_menu_state = view_options_menu_state.clone();
+ ContextMenuEntry::new("Staged & Unstaged")
+ .toggle(
+ IconPosition::End,
+ state.group_by == GitPanelGroupBy::Staging,
+ )
+ .handler(move |window, cx| {
+ if state.group_by != GitPanelGroupBy::Staging {
+ view_options_menu_state.set(GitPanelViewOptionsMenuState {
+ group_by: GitPanelGroupBy::Staging,
+ ..state
+ });
+ window.dispatch_action(Box::new(SetGroupByStaging), cx);
+ }
+ })
})
})
})
@@ -569,6 +585,25 @@ pub fn register(workspace: &mut Workspace) {
});
}
});
+ workspace.register_action(|workspace, action: &ShowBranchChanges, window, cx| {
+ if let Some(panel) = workspace.focus_panel::<GitPanel>(window, cx) {
+ panel.update(cx, |panel, cx| {
+ panel.show_branch_changes(action, window, cx)
+ });
+ }
+ });
+ workspace.register_action(|workspace, action: &ShowUncommittedChanges, window, cx| {
+ if let Some(panel) = workspace.focus_panel::<GitPanel>(window, cx) {
+ panel.update(cx, |panel, cx| {
+ panel.show_uncommitted_changes(action, window, cx)
+ });
+ }
+ });
+ workspace.register_action(|workspace, _: &CompareAgainstBase, window, cx| {
+ if let Some(panel) = workspace.focus_panel::<GitPanel>(window, cx) {
+ panel.update(cx, |panel, cx| panel.choose_branch_base(window, cx));
+ }
+ });
workspace.register_action(|workspace, _: &git::Init, window, cx| {
if let Some(panel) = workspace.panel::<GitPanel>(cx) {
panel.update(cx, |panel, cx| panel.git_init(window, cx));
@@ -655,6 +690,7 @@ enum Section {
New,
Staged,
Unstaged,
+ Branch,
}
#[derive(Debug, PartialEq, Eq, Clone)]
@@ -781,6 +817,7 @@ impl GitHeaderEntry {
!repo.had_conflict_on_last_merge_head_change(&status_entry.repo_path)
&& GitPanel::stage_status_for_entry(status_entry, repo).has_unstaged()
}
+ Section::Branch => false,
}
}
pub fn title(&self) -> &'static str {
@@ -790,6 +827,7 @@ impl GitHeaderEntry {
Section::New => "Untracked",
Section::Staged => "Staged",
Section::Unstaged => "Unstaged",
+ Section::Branch => "Branch Changes",
}
}
}
@@ -1198,6 +1236,41 @@ impl TruncatedPatch {
}
}
+struct EntryMenuTitles {
+ copy_path: &'static str,
+ copy_relative_path: &'static str,
+ open_diff: &'static str,
+ open_file_diff: &'static str,
+ view_file: &'static str,
+ view_file_history: &'static str,
+}
+
+impl EntryMenuTitles {
+ fn new(file_count: usize) -> Self {
+ let plural = file_count > 1;
+ Self {
+ copy_path: if plural { "Copy Paths" } else { "Copy Path" },
+ copy_relative_path: if plural {
+ "Copy Relative Paths"
+ } else {
+ "Copy Relative Path"
+ },
+ open_diff: if plural { "Open Diffs" } else { "Open Diff" },
+ open_file_diff: if plural {
+ "Open File Diffs"
+ } else {
+ "Open File Diff"
+ },
+ view_file: if plural { "View Files" } else { "View File" },
+ view_file_history: if plural {
+ "View File Histories"
+ } else {
+ "View File History"
+ },
+ }
+ }
+}
+
struct GitPanelContextMenu {
menu: Entity<ContextMenu>,
position: Point<Pixels>,
@@ -1277,6 +1350,14 @@ pub struct GitPanel {
commit_menu_handle: PopoverMenuHandle<ContextMenu>,
changes_actions_menu_handle: PopoverMenuHandle<ContextMenu>,
remote_action_menu_handle: PopoverMenuHandle<ContextMenu>,
+ changes_mode: ChangesMode,
+ changes_mode_menu_handle: PopoverMenuHandle<ContextMenu>,
+ branch_base: BranchBase,
+ /// Uncommitted files, one per path. Staging, discarding and committing
+ /// act on these regardless of which mode `entries` shows.
+ change_entries: Vec<GitStatusEntry>,
+ /// Diff editors look up a file's entry for every header they draw.
+ change_entry_indices: HashMap<RepoPath, usize>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -1418,9 +1499,12 @@ impl GitPanel {
let focus_handle = cx.focus_handle();
cx.on_focus(&focus_handle, window, Self::focus_in).detach();
- cx.subscribe(&workspace_entity, |this, _, event, cx| {
+ cx.subscribe_in(&workspace_entity, window, |this, _, event, window, cx| {
if let workspace::Event::ActiveItemChanged = event {
this.update_active_history_sha(cx);
+ let previous_base = this.branch_base.effective();
+ this.follow_active_branch_diff(window, cx);
+ this.update_entries_if_base_changed(previous_base, window, cx);
}
})
.detach();
@@ -1549,6 +1633,13 @@ impl GitPanel {
})
.ok();
}
+ GitStoreEvent::RepositoryUpdated(
+ _,
+ RepositoryEvent::BranchListChanged,
+ true,
+ ) => {
+ this.default_branch_may_have_changed(window, cx);
+ }
GitStoreEvent::RepositoryUpdated(_, _, _) => {}
GitStoreEvent::JobsUpdated
| GitStoreEvent::ConflictsUpdated
@@ -1623,6 +1714,11 @@ impl GitPanel {
commit_menu_handle: PopoverMenuHandle::default(),
changes_actions_menu_handle: PopoverMenuHandle::default(),
remote_action_menu_handle: PopoverMenuHandle::default(),
+ changes_mode: ChangesMode::Uncommitted,
+ changes_mode_menu_handle: PopoverMenuHandle::default(),
+ branch_base: BranchBase::new(),
+ change_entries: Vec::new(),
+ change_entry_indices: HashMap::default(),
};
this.schedule_update(window, cx);
@@ -1637,6 +1733,19 @@ impl GitPanel {
.map(|entry| entry.index)
}
+ fn change_entry_by_path(&self, path: &RepoPath) -> Option<&GitStatusEntry> {
+ self.change_entries
+ .get(*self.change_entry_indices.get(path)?)
+ }
+
+ /// Branch mode lists files added since the base as created, but once
+ /// committed they have history. Only uncommitted new files don't.
+ fn has_file_history(&self, entry: &GitStatusEntry) -> bool {
+ !self
+ .change_entry_by_path(&entry.repo_path)
+ .is_some_and(|change| change.status.is_created())
+ }
+
fn entry_by_path_in_section(&self, path: &RepoPath, section: Section) -> Option<usize> {
self.projected_entries_by_path
.get(path)?
@@ -2018,26 +2127,34 @@ impl GitPanel {
return;
};
- let section = repo
- .status_for_path(&repo_path)
- .map(|status| status.status)
- .map(|status| {
- if GitPanelSettings::get_global(cx).group_by == GitPanelGroupBy::Staging {
- if repo.had_conflict_on_last_merge_head_change(&repo_path) {
+ // Rows know their section even inside collapsed directories, and
+ // branch mode rows have no uncommitted status to derive it from.
+ let listed_section = self
+ .projected_entries_by_path
+ .get(&repo_path)
+ .and_then(|entries| entries.first())
+ .map(|entry| entry.section);
+ let section = listed_section.or_else(|| {
+ repo.status_for_path(&repo_path)
+ .map(|status| status.status)
+ .map(|status| {
+ if GitPanelSettings::get_global(cx).group_by == GitPanelGroupBy::Staging {
+ if repo.had_conflict_on_last_merge_head_change(&repo_path) {
+ Section::Conflict
+ } else if status.staging().has_staged() {
+ Section::Staged
+ } else {
+ Section::Unstaged
+ }
+ } else if repo.had_conflict_on_last_merge_head_change(&repo_path) {
Section::Conflict
- } else if status.staging().has_staged() {
- Section::Staged
+ } else if status.is_created() {
+ Section::New
} else {
- Section::Unstaged
+ Section::Tracked
}
- } else if repo.had_conflict_on_last_merge_head_change(&repo_path) {
- Section::Conflict
- } else if status.is_created() {
- Section::New
- } else {
- Section::Tracked
- }
- });
+ })
+ });
(repo_path, section)
};
@@ -2331,9 +2448,11 @@ impl GitPanel {
self.nearest_expanded_directory_key(directory.key.section, &directory.key.path)
}
Some(GitListEntry::TreeStatus(status)) => self
- .section_for_entry_index(selected_index)
- .and_then(|section| {
- self.nearest_expanded_directory_key(section, &status.entry.repo_path)
+ .projected_entries_by_path
+ .get(&status.entry.repo_path)
+ .and_then(|entries| entries.iter().find(|entry| entry.index == selected_index))
+ .and_then(|entry| {
+ self.nearest_expanded_directory_key(entry.section, &status.entry.repo_path)
}),
_ => None,
};
@@ -2574,6 +2693,10 @@ impl GitPanel {
/// Show diff view at selected entry, only if the diff view is open
fn move_diff_to_entry(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ if self.is_branch_mode() {
+ self.move_branch_diff_to_entry(window, cx);
+ return;
+ }
maybe!({
let workspace = self.workspace.upgrade()?;
let selected_index = self.selected_entry?;
@@ -2642,11 +2765,8 @@ impl GitPanel {
}
fn select_first_entry_if_none(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- let have_entries = self
- .active_repository
- .as_ref()
- .is_some_and(|active_repository| active_repository.read(cx).status_summary().count > 0);
- if have_entries && self.selected_entry.is_none() {
+ // Branch mode can list files while there are no uncommitted changes.
+ if !self.entries.is_empty() && self.selected_entry.is_none() {
self.select_first(&menu::SelectFirst, window, cx);
}
}
@@ -2673,16 +2793,9 @@ impl GitPanel {
self.selected_entry.and_then(|i| self.entries.get(i))
}
- fn change_entries_by_path(&self) -> impl Iterator<Item = &GitStatusEntry> {
- // A grouping can project one changed file into multiple list rows.
- self.entries
- .iter()
- .filter_map(GitListEntry::status_entry)
- .unique_by(|entry| entry.repo_path.clone())
- }
-
fn has_untracked_files(&self) -> bool {
- self.change_entries_by_path()
+ self.change_entries
+ .iter()
.any(|entry| entry.status.is_untracked())
}
@@ -2739,6 +2852,23 @@ impl GitPanel {
self.toggle_directory(&dir_entry.key, window, cx);
return;
}
+ if self.is_branch_mode() {
+ let entry = self
+ .selected_entry
+ .and_then(|index| self.entries.get(index))
+ .and_then(GitListEntry::status_entry)
+ .cloned();
+ if let Some(entry) = entry {
+ if let Some(branch_diff) = self.branch_diff_showing(&entry, cx) {
+ branch_diff.focus_handle(cx).focus(window, cx);
+ branch_diff.update(cx, |branch_diff, cx| branch_diff.autoscroll(cx));
+ return;
+ }
+ self.open_branch_diff(Some(entry), window, cx);
+ self.focus_handle.focus(window, cx);
+ }
+ return;
+ }
maybe!({
let selected_index = self.selected_entry?;
let entry = self.entries.get(selected_index)?.status_entry()?;
@@ -2786,6 +2916,12 @@ impl GitPanel {
window: &mut Window,
cx: &mut Context<Self>,
) {
+ // A file diff shows uncommitted changes, so branch rows open the
+ // branch diff instead.
+ if self.is_branch_mode() {
+ self.open_diff(&menu::Confirm, window, cx);
+ return;
+ }
let Some(repository) = self.active_repository.clone() else {
return;
};
@@ -2837,6 +2973,10 @@ impl GitPanel {
cx.propagate();
return;
}
+ let entries = entries
+ .into_iter()
+ .filter(|entry| self.has_file_history(entry))
+ .collect::<Vec<_>>();
let Some(repository) = self.active_repository.as_ref() else {
return;
};
@@ -2845,17 +2985,15 @@ impl GitPanel {
self.workspace
.update(cx, |workspace, cx| {
for entry in entries {
- if !entry.status.is_created() {
- crate::git_graph::open_or_reuse_graph(
- workspace,
- repository_id,
- git_store.clone(),
- LogSource::Path(entry.repo_path),
- None,
- window,
- cx,
- );
- }
+ crate::git_graph::open_or_reuse_graph(
+ workspace,
+ repository_id,
+ git_store.clone(),
+ LogSource::Path(entry.repo_path),
+ None,
+ window,
+ cx,
+ );
}
})
.log_err();
@@ -3371,7 +3509,7 @@ impl GitPanel {
let entries = self
.directory_context_descendants()
.map(Self::staged_tracked_entries)
- .unwrap_or_else(|| Self::staged_tracked_entries(self.change_entries_by_path()));
+ .unwrap_or_else(|| Self::staged_tracked_entries(self.change_entries.iter()));
match entries.len() {
0 => return,
@@ -3429,7 +3567,8 @@ impl GitPanel {
// Files added to the index are not untracked; trashing them would also
// discard their staged contents.
let to_delete = self
- .change_entries_by_path()
+ .change_entries
+ .iter()
.filter(|status_entry| status_entry.status.is_untracked())
.cloned()
.collect::<Vec<_>>();
@@ -3656,7 +3795,8 @@ impl GitPanel {
StageIntent::Toggle => !self.header_state(section.header).selected(),
};
let entries = self
- .change_entries_by_path()
+ .change_entries
+ .iter()
.filter(|status_entry| {
section.contains(status_entry, &repo)
&& GitPanel::stage_status_for_entry(status_entry, &repo).as_bool()
@@ -4177,7 +4317,8 @@ impl GitPanel {
cx.background_spawn(async move { commit_task.await? })
} else {
let changed_files = self
- .change_entries_by_path()
+ .change_entries
+ .iter()
.filter(|status_entry| !status_entry.status.is_created())
.map(|status_entry| status_entry.repo_path.clone())
.collect::<Vec<_>>();
@@ -5637,7 +5778,6 @@ impl GitPanel {
}
fn schedule_update(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- let handle = cx.entity().downgrade();
let new_active_repository = self.project.read(cx).active_repository(cx);
let active_repository_changed = self.active_repository.as_ref().map(Entity::entity_id)
!= new_active_repository.as_ref().map(Entity::entity_id);
@@ -5661,12 +5801,18 @@ impl GitPanel {
self.active_repository = new_active_repository;
if active_repository_changed {
self.update_active_history_sha(cx);
+ self.reset_branch_state(window, cx);
}
self.reopen_commit_buffer(window, cx);
self.preload_commit_history(cx);
if self.active_tab == GitPanelTab::History {
self.load_commit_history(cx);
}
+ self.schedule_visible_entries_update(window, cx);
+ }
+
+ fn schedule_visible_entries_update(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ let handle = cx.entity().downgrade();
self.update_visible_entries_task = cx.spawn_in(window, async move |_, cx| {
cx.background_executor().timer(UPDATE_DEBOUNCE).await;
if let Some(git_panel) = handle.upgrade() {
@@ -5804,8 +5950,12 @@ impl GitPanel {
self.active_repository = active_repository;
self.git_access = None;
self.clear_marks();
+ self.reset_branch_state(window, cx);
}
+ self.sync_branch_list(window, cx);
self.entries.clear();
+ self.change_entries.clear();
+ self.change_entry_indices.clear();
self.projected_entries_by_path.clear();
self.single_staged_entry.take();
self.single_tracked_entry.take();
@@ -5969,6 +6119,9 @@ impl GitPanel {
self.single_tracked_entry = tracked_entries.pop();
}
+ let is_branch_mode = self.is_branch_mode();
+ let mut branch_entries = self.branch_status_entries(cx);
+
if !is_tree_view {
let sort_entries = |entries: &mut Vec<GitStatusEntry>| match sort_by {
GitPanelSortBy::Path => entries.sort_by(|a, b| a.repo_path.cmp(&b.repo_path)),
@@ -5985,6 +6138,7 @@ impl GitPanel {
sort_entries(&mut new_entries);
sort_entries(&mut staged_entries);
sort_entries(&mut unstaged_entries);
+ sort_entries(&mut branch_entries);
}
let mut push_entry =
@@ -6033,6 +6187,30 @@ impl GitPanel {
(Section::New, std::mem::take(&mut new_entries)),
]
};
+ // Picks each file's first row in section order, matching which row a
+ // grouping that projects one file into several rows lists first.
+ self.change_entries = section_entries
+ .iter()
+ .flat_map(|(_, entries)| entries)
+ .unique_by(|entry| &entry.repo_path)
+ .cloned()
+ .collect();
+ self.change_entry_indices = self
+ .change_entries
+ .iter()
+ .enumerate()
+ .map(|(index, entry)| (entry.repo_path.clone(), index))
+ .collect();
+ let section_entries = if is_branch_mode {
+ vec![(Section::Branch, branch_entries)]
+ } else {
+ section_entries
+ };
+ let section_has_header = |section: Section| match section {
+ Section::Branch => false,
+ Section::Tracked => group_by != GitPanelGroupBy::None,
+ Section::Conflict | Section::New | Section::Staged | Section::Unstaged => true,
+ };
// Keep Staged/Unstaged headers pinned even when empty (as long as there's
// anything to show at all) so the layout stays stable while staging.
@@ -6064,12 +6242,11 @@ impl GitPanel {
continue;
}
- let section_has_header =
- section != Section::Tracked || group_by != GitPanelGroupBy::None;
+ let has_header = section_has_header(section);
let section_is_collapsed =
- section_has_header && self.collapsed_sections.contains(&section);
+ has_header && self.collapsed_sections.contains(&section);
- if section_has_header {
+ if has_header {
push_entry(
self,
GitListEntry::Header(GitHeaderEntry { header: section }),
@@ -6114,7 +6291,7 @@ impl GitPanel {
continue;
}
- if section != Section::Tracked || group_by != GitPanelGroupBy::None {
+ if section_has_header(section) {
push_entry(
self,
GitListEntry::Header(GitHeaderEntry { header: section }),
@@ -6149,7 +6326,8 @@ impl GitPanel {
.as_ref()
.filter(|op| op.repo_id == repo.id)
.and_then(|op| self.entry_by_path(&op.anchor));
- if bulk_staging_anchor_new_index == last_staged_path_prev_index
+ if !is_branch_mode
+ && bulk_staging_anchor_new_index == last_staged_path_prev_index
&& let Some(index) = bulk_staging_anchor_new_index
&& let Some(entry) = self.entries.get(index)
&& let Some(entry) = entry.status_entry()
@@ -6202,6 +6380,7 @@ impl GitPanel {
Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
Section::Staged => (self.entry_count, self.entry_count),
Section::Unstaged => (0, self.entry_count),
+ Section::Branch => (0, 0),
};
if staged_count == 0 {
ToggleState::Unselected
@@ -6304,7 +6483,7 @@ impl GitPanel {
self.entry_count = 0;
self.diff_stat_total = DiffStat::default();
- let change_entries = self.change_entries_by_path().cloned().collect::<Vec<_>>();
+ let change_entries = self.change_entries.iter().cloned().collect::<Vec<_>>();
for status_entry in change_entries {
self.entry_count += 1;
if let Some(diff_stat) = status_entry.diff_stat {
@@ -6344,7 +6523,8 @@ impl GitPanel {
}
pub(crate) fn has_unstaged_changes(&self) -> bool {
- self.change_entries_by_path()
+ self.change_entries
+ .iter()
.any(|entry| entry.staging.has_unstaged())
}
@@ -6357,11 +6537,12 @@ impl GitPanel {
}
fn has_staged_tracked_changes(&self) -> bool {
- Self::contains_staged_tracked_entry(self.change_entries_by_path())
+ Self::contains_staged_tracked_entry(self.change_entries.iter())
}
pub fn has_unstaged_conflicts(&self) -> bool {
- self.change_entries_by_path()
+ self.change_entries
+ .iter()
.any(|entry| entry.status.is_conflicted() && entry.staging.has_unstaged())
}
@@ -6606,6 +6787,8 @@ impl GitPanel {
fn render_view_options_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
let focus_handle = self.focus_handle.clone();
+ // The branch list has a single section, so grouping doesn't apply.
+ let show_group_by = !self.is_branch_mode();
PopoverMenu::new(id.into())
.trigger_with_tooltip(
@@ -6616,6 +6799,7 @@ impl GitPanel {
.menu(move |window, cx| {
Some(git_panel_view_options_menu(
focus_handle.clone(),
+ show_group_by,
window,
cx,
))
@@ -7000,7 +7184,12 @@ impl GitPanel {
self.active_repository.as_ref()?;
+ let is_branch_mode = self.is_branch_mode();
let diff_stat_total = self.diff_stat_total;
+ let show_diff_stat = !is_branch_mode
+ && GitPanelSettings::get_global(cx).diff_stats
+ && diff_stat_total != DiffStat::default();
+ let focus_handle = self.focus_handle.clone();
Some(
h_flex()
@@ -7013,48 +7202,62 @@ impl GitPanel {
.gap_1()
.justify_between()
.child(
- ButtonLike::new("diff-button")
+ h_flex()
+ .gap_1()
+ .child(self.render_changes_mode_menu(cx))
.child(
- h_flex()
- .gap_1()
+ ButtonLike::new("diff-button")
.child(
- Icon::new(IconName::Diff)
- .size(IconSize::Small)
- .color(Color::Muted),
- )
- .child(
- Label::new("View Diff")
- .size(LabelSize::Small)
- .color(Color::Muted),
+ h_flex()
+ .gap_1()
+ .child(
+ Icon::new(IconName::Diff)
+ .size(IconSize::Small)
+ .color(Color::Muted),
+ )
+ .child(
+ Label::new("View Diff")
+ .size(LabelSize::Small)
+ .color(Color::Muted),
+ )
+ .when(show_diff_stat, |this| {
+ this.child(ui::DiffStat::new(
+ "changes-diff-stat-total",
+ diff_stat_total.added as usize,
+ diff_stat_total.deleted as usize,
+ ))
+ }),
)
- .when(
- GitPanelSettings::get_global(cx).diff_stats
- && diff_stat_total != DiffStat::default(),
- |this| {
- this.child(ui::DiffStat::new(
- "changes-diff-stat-total",
- diff_stat_total.added as usize,
- diff_stat_total.deleted as usize,
- ))
- },
- ),
- )
- .tooltip(Tooltip::for_action_title_in(
- "View Diff",
- &Diff,
- &self.focus_handle,
- ))
- .on_click(|_, _, cx| {
- cx.defer(|cx| {
- cx.dispatch_action(&Diff);
- })
- }),
+ .tooltip(move |_window, cx| {
+ if is_branch_mode {
+ Tooltip::simple("View Branch Diff", cx)
+ } else {
+ Tooltip::for_action_in(
+ "View Diff",
+ &Diff,
+ &focus_handle,
+ cx,
+ )
+ }
+ })
+ .on_click(cx.listener(move |this, _, window, cx| {
+ if this.is_branch_mode() {
+ this.open_branch_diff(None, window, cx);
+ } else {
+ cx.defer(|cx| {
+ cx.dispatch_action(&Diff);
+ })
+ }
+ })),
+ ),
)
.child(
h_flex()
.gap_1()
.child(self.render_view_options_menu("view_options_menu"))
- .child(self.render_git_changes_actions_button(cx)),
+ .when(!is_branch_mode, |this| {
+ this.child(self.render_git_changes_actions_button(cx))
+ }),
),
)
}
@@ -7501,6 +7704,14 @@ impl GitPanel {
fn render_tab_bar(&self, cx: &mut Context<Self>) -> impl IntoElement {
let active_tab = self.active_tab;
+ let changes_count = if self.is_branch_mode() {
+ self.section_file_counts
+ .get(&Section::Branch)
+ .copied()
+ .unwrap_or_default()
+ } else {
+ self.changes_count
+ };
let focus_handle = self.focus_handle.clone();
let tab = |id: ElementId,
@@ -7526,9 +7737,9 @@ impl GitPanel {
.border_color(cx.theme().colors().border.opacity(0.6))
})
.child(Label::new(label.clone()).when(!active, |this| this.color(Color::Muted)))
- .when(show_changes && self.changes_count > 0, |this| {
+ .when(show_changes && changes_count > 0, |this| {
this.child(
- Label::new(format!("({})", self.changes_count))
+ Label::new(format!("({})", changes_count))
.size(LabelSize::Small)
.color(Color::Muted),
)
@@ -7749,6 +7960,7 @@ impl GitPanel {
self.activation_focus_handle(cx).focus(window, cx);
match tab {
GitPanelTab::History => {
+ self.cancel_pending_branch_changes();
self.load_commit_history(cx);
}
GitPanelTab::Changes => {
@@ -8213,6 +8425,7 @@ impl GitPanel {
let content = match (self.git_access, &self.active_repository) {
(Some(GitAccess::No), Some(repository)) => self.render_unsafe_repo_ui(repository, cx),
(_, None) => self.render_uninitialized_ui(cx),
+ (_, Some(_)) if self.is_branch_mode() => self.render_no_branch_changes_ui(cx),
(_, Some(_)) => self.render_no_changes_ui(cx),
};
@@ -8236,11 +8449,9 @@ impl GitPanel {
Button::new("view_branch_diff", "View Branch Diff")
.label_size(LabelSize::Small)
.style(ButtonStyle::Outlined)
- .on_click(move |_, _, cx| {
- cx.defer(move |cx| {
- cx.dispatch_action(&DeployBranchDiff);
- })
- }),
+ .on_click(cx.listener(|this, _, window, cx| {
+ this.show_branch_changes_and_open_diff(window, cx);
+ })),
)
})
.into_any_element()
@@ -8369,8 +8580,7 @@ impl GitPanel {
let repo = self.active_repository.as_ref()?.read(cx);
let project_path = (file.worktree_id(cx), file.path().clone()).into();
let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
- let ix = self.entry_by_path(&repo_path)?;
- let entry = self.entries.get(ix)?;
+ let entry = GitListEntry::Status(self.change_entry_by_path(&repo_path)?.clone());
let is_staging_or_staged = repo
.pending_ops_for_path(&repo_path)
@@ -8391,7 +8601,6 @@ impl GitPanel {
.fill()
.elevation(ElevationIndex::Surface)
.on_click({
- let entry = entry.clone();
let git_panel = entity.downgrade();
move |_, window, cx| {
git_panel
@@ -8427,6 +8636,7 @@ impl GitPanel {
GitPanelViewMode::Flat => (false, self.visible_flat_entry_indices().len()),
};
let repo = repo.downgrade();
+ let show_checkbox = !self.is_branch_mode();
v_flex()
.flex_1()
@@ -8470,6 +8680,7 @@ impl GitPanel {
entry,
0,
has_write_access,
+ show_checkbox,
repo,
window,
cx,
@@ -8481,6 +8692,7 @@ impl GitPanel {
&entry.entry,
entry.depth,
has_write_access,
+ show_checkbox,
repo,
window,
cx,
@@ -8491,6 +8703,7 @@ impl GitPanel {
ix,
entry,
has_write_access,
+ show_checkbox,
window,
cx,
));
@@ -8754,24 +8967,7 @@ impl GitPanel {
let is_file_or_bulk = !matches!(target_kind, SelectionTargetKind::Directory);
let has_tracked = !all_created;
let plural = file_count > 1;
- let copy_path_title = if plural { "Copy Paths" } else { "Copy Path" };
- let copy_relative_path_title = if plural {
- "Copy Relative Paths"
- } else {
- "Copy Relative Path"
- };
- let open_file_diff_title = if plural {
- "Open File Diffs"
- } else {
- "Open File Diff"
- };
- let view_file_title = if plural { "View Files" } else { "View File" };
- let open_diff_title = if plural { "Open Diffs" } else { "Open Diff" };
- let view_file_history_title = if plural {
- "View File Histories"
- } else {
- "View File History"
- };
+ let titles = EntryMenuTitles::new(file_count);
ContextMenu::build(window, cx, |context_menu, _, _| {
context_menu
.context(self.focus_handle.clone())
@@ -8781,8 +8977,8 @@ impl GitPanel {
.action("Unstaged Changes", ViewUnstagedChanges.boxed_clone())
.action("Staged Changes", ViewStagedChanges.boxed_clone())
.separator()
- .action(copy_path_title, CopyPath.boxed_clone())
- .action(copy_relative_path_title, CopyRelativePath.boxed_clone())
+ .action(titles.copy_path, CopyPath.boxed_clone())
+ .action(titles.copy_relative_path, CopyRelativePath.boxed_clone())
.separator()
.action_disabled_when(
!all_created,
@@ -8805,14 +9001,14 @@ impl GitPanel {
.when(is_file_or_bulk, |context_menu| {
context_menu
.separator()
- .action(open_diff_title, menu::Confirm.boxed_clone())
- .action(open_file_diff_title, menu::SecondaryConfirm.boxed_clone())
- .action(view_file_title, ViewFile.boxed_clone())
+ .action(titles.open_diff, menu::Confirm.boxed_clone())
+ .action(titles.open_file_diff, menu::SecondaryConfirm.boxed_clone())
+ .action(titles.view_file, ViewFile.boxed_clone())
})
.when(is_file_or_bulk && has_tracked, |context_menu| {
context_menu
.separator()
- .action(view_file_history_title, Box::new(git::FileHistory))
+ .action(titles.view_file_history, Box::new(git::FileHistory))
})
})
}
@@ -8840,6 +9036,18 @@ impl GitPanel {
return;
}
+ if self.is_branch_mode() {
+ let has_history = entries.iter().any(|entry| self.has_file_history(entry));
+ self.set_context_menu(
+ self.build_branch_context_menu(entries.len(), target_kind, has_history, window, cx),
+ position,
+ None,
+ window,
+ cx,
+ );
+ return;
+ }
+
let all_created = entries.iter().all(|entry| entry.status.is_created());
let all_deleted = entries.iter().all(|entry| entry.status.is_deleted());
let will_unstage = self.should_unstage(target_kind, &entries, cx);
@@ -8872,6 +9080,11 @@ impl GitPanel {
window: &mut Window,
cx: &mut Context<Self>,
) {
+ // Every action in this menu acts on uncommitted changes, which the
+ // branch list doesn't show.
+ if self.is_branch_mode() {
+ return;
+ }
let has_stash_items = self.stash_entries.entries.len() > 0;
let has_tracked_changes = self.has_tracked_changes();
let has_staged_changes = self.has_staged_changes();
@@ -8947,6 +9160,7 @@ impl GitPanel {
entry: &GitStatusEntry,
depth: usize,
has_write_access: bool,
+ show_checkbox: bool,
repo: &Repository,
window: &Window,
cx: &Context<Self>,
@@ -9128,34 +9342,36 @@ impl GitPanel {
))
})
})
- .child(
- div()
- .id(checkbox_wrapper_id)
- .flex_none()
- .occlude()
- .cursor_pointer()
- .child(
- Checkbox::new(checkbox_id, toggle_state)
- .fill()
- .elevation(ElevationIndex::Surface)
- .disabled(!has_write_access || resolved_conflict)
- .on_click_ext({
- let entry = entry.clone();
- let this = cx.weak_entity();
- move |_, click, window, cx| {
- this.update(cx, |this, cx| {
- if !has_write_access || resolved_conflict {
- return;
- }
- if click.modifiers().shift {
- this.stage_bulk(
- ix,
- stage_intent != StageIntent::Unstage,
- cx,
- );
- } else {
- let list_entry =
- if GitPanelSettings::get_global(cx).tree_view {
+ .when(show_checkbox, |this| {
+ this.child(
+ div()
+ .id(checkbox_wrapper_id)
+ .flex_none()
+ .occlude()
+ .cursor_pointer()
+ .child(
+ Checkbox::new(checkbox_id, toggle_state)
+ .fill()
+ .elevation(ElevationIndex::Surface)
+ .disabled(!has_write_access || resolved_conflict)
+ .on_click_ext({
+ let entry = entry.clone();
+ let this = cx.weak_entity();
+ move |_, click, window, cx| {
+ this.update(cx, |this, cx| {
+ if !has_write_access || resolved_conflict {
+ return;
+ }
+ if click.modifiers().shift {
+ this.stage_bulk(
+ ix,
+ stage_intent != StageIntent::Unstage,
+ cx,
+ );
+ } else {
+ let list_entry = if GitPanelSettings::get_global(cx)
+ .tree_view
+ {
GitListEntry::TreeStatus(GitTreeStatusEntry {
entry: entry.clone(),
depth,
@@ -9163,28 +9379,29 @@ impl GitPanel {
} else {
GitListEntry::Status(entry.clone())
};
- this.toggle_staged_for_entry(
- &list_entry,
- stage_intent,
- window,
- cx,
- );
- }
- cx.stop_propagation();
- })
- .ok();
- }
- })
- .tooltip(move |_window, cx| {
- if resolved_conflict {
- Tooltip::simple("Conflict marked as resolved", cx)
- } else {
- let action = stage_intent.label(|| stage_status);
- Tooltip::for_action(action, &ToggleStaged, cx)
- }
- }),
- ),
- )
+ this.toggle_staged_for_entry(
+ &list_entry,
+ stage_intent,
+ window,
+ cx,
+ );
+ }
+ cx.stop_propagation();
+ })
+ .ok();
+ }
+ })
+ .tooltip(move |_window, cx| {
+ if resolved_conflict {
+ Tooltip::simple("Conflict marked as resolved", cx)
+ } else {
+ let action = stage_intent.label(|| stage_status);
+ Tooltip::for_action(action, &ToggleStaged, cx)
+ }
+ }),
+ ),
+ )
+ })
.when_some(dragged_selection, |this, dragged_selection| {
this.on_drag(dragged_selection, move |selection, click_offset, _, cx| {
cx.new(|_| DraggedGitEntryView {
@@ -9235,6 +9452,7 @@ impl GitPanel {
ix: usize,
entry: &GitTreeDirEntry,
has_write_access: bool,
+ show_checkbox: bool,
window: &Window,
cx: &Context<Self>,
) -> AnyElement {
@@ -9353,53 +9571,55 @@ impl GitPanel {
.hover(|s| s.bg(hover_bg))
.active(|s| s.bg(active_bg))
.child(name_row)
- .child(
- div()
- .id(checkbox_wrapper_id)
- .flex_none()
- .occlude()
- .cursor_pointer()
- .child(
- Checkbox::new(checkbox_id, toggle_state)
- .disabled(!has_write_access || resolved_conflict)
- .fill()
- .elevation(ElevationIndex::Surface)
- .on_click({
- let entry = entry.clone();
- let this = cx.weak_entity();
- move |_, window, cx| {
- this.update(cx, |this, cx| {
- if !has_write_access || resolved_conflict {
- return;
- }
- this.toggle_staged_for_entry(
- &GitListEntry::Directory(entry.clone()),
- stage_intent,
- window,
- cx,
- );
- cx.stop_propagation();
- })
- .ok();
- }
- })
- .tooltip(move |_window, cx| {
- if resolved_conflict {
- Tooltip::simple("Conflicts marked as resolved", cx)
- } else {
- let action = stage_intent.label(|| stage_status);
- Tooltip::simple(format!("{action} Folder"), cx)
- }
- }),
- ),
- )
- .on_click({
- let key = entry.key.clone();
- cx.listener(move |this, event: &ClickEvent, window, cx| {
- if event.modifiers().shift {
- let anchor_ix = this.selected_entry.unwrap_or(ix);
- this.apply_range_gesture(anchor_ix, ix);
- this.selected_entry = Some(ix);
+ .when(show_checkbox, |this| {
+ this.child(
+ div()
+ .id(checkbox_wrapper_id)
+ .flex_none()
+ .occlude()
+ .cursor_pointer()
+ .child(
+ Checkbox::new(checkbox_id, toggle_state)
+ .disabled(!has_write_access || resolved_conflict)
+ .fill()
+ .elevation(ElevationIndex::Surface)
+ .on_click({
+ let entry = entry.clone();
+ let this = cx.weak_entity();
+ move |_, window, cx| {
+ this.update(cx, |this, cx| {
+ if !has_write_access || resolved_conflict {
+ return;
+ }
+ this.toggle_staged_for_entry(
+ &GitListEntry::Directory(entry.clone()),
+ stage_intent,
+ window,
+ cx,
+ );
+ cx.stop_propagation();
+ })
+ .ok();
+ }
+ })
+ .tooltip(move |_window, cx| {
+ if resolved_conflict {
+ Tooltip::simple("Conflicts marked as resolved", cx)
+ } else {
+ let action = stage_intent.label(|| stage_status);
+ Tooltip::simple(format!("{action} Folder"), cx)
+ }
+ }),
+ ),
+ )
+ })
+ .on_click({
+ let key = entry.key.clone();
+ cx.listener(move |this, event: &ClickEvent, window, cx| {
+ if event.modifiers().shift {
+ let anchor_ix = this.selected_entry.unwrap_or(ix);
+ this.apply_range_gesture(anchor_ix, ix);
+ this.selected_entry = Some(ix);
cx.notify();
} else if event.modifiers().secondary(cx) {
this.toggle_mark(ix, cx);
@@ -9678,7 +9898,7 @@ impl GitPanel {
pub fn selected_file_history_target(&self) -> Option<(Entity<Repository>, RepoPath)> {
let entry = self.get_selected_entry()?.status_entry()?;
let repository = self.active_repository.clone()?;
- if entry.status.is_created() {
+ if !self.has_file_history(entry) {
return None;
}
Some((repository, entry.repo_path.clone()))
@@ -9705,6 +9925,10 @@ impl Render for GitPanel {
let project = self.project.read(cx);
let has_entries = !self.entries.is_empty();
let has_write_access = self.has_write_access(cx);
+ // Branch rows are read-only, so actions on the selected rows only
+ // apply to the uncommitted list.
+ let can_stage_rows =
+ has_write_access && !project.is_read_only(cx) && !self.is_branch_mode();
#[cfg(feature = "call")]
let has_co_authors = self
@@ -9728,22 +9952,13 @@ impl Render for GitPanel {
.key_context(self.dispatch_context(window, cx))
.track_focus(&self.focus_handle)
.when(has_write_access && !project.is_read_only(cx), |this| {
- this.on_action(cx.listener(Self::toggle_staged_for_selected))
- .on_action(cx.listener(Self::stage_range))
- .on_action(cx.listener(GitPanel::on_commit))
+ this.on_action(cx.listener(GitPanel::on_commit))
.on_action(cx.listener(GitPanel::toggle_skip_hooks))
.on_action(cx.listener(GitPanel::on_amend))
.on_action(cx.listener(GitPanel::toggle_signoff_enabled))
.on_action(cx.listener(Self::stage_all))
.on_action(cx.listener(Self::unstage_all))
- .on_action(cx.listener(Self::stage_selected))
- .on_action(cx.listener(Self::unstage_selected))
- .on_action(cx.listener(Self::stage_section))
- .on_action(cx.listener(Self::unstage_section))
.on_action(cx.listener(Self::restore_tracked_files))
- .on_action(cx.listener(Self::revert_selected))
- .on_action(cx.listener(Self::add_to_gitignore))
- .on_action(cx.listener(Self::add_to_git_info_exclude))
.on_action(cx.listener(Self::clean_all))
.on_action(cx.listener(Self::generate_commit_message_action))
.on_action(cx.listener(Self::stash_all))
@@ -9751,6 +9966,17 @@ impl Render for GitPanel {
.on_action(cx.listener(Self::stash_staged))
.on_action(cx.listener(Self::stash_pop))
})
+ .when(can_stage_rows, |this| {
+ this.on_action(cx.listener(Self::toggle_staged_for_selected))
+ .on_action(cx.listener(Self::stage_range))
+ .on_action(cx.listener(Self::stage_selected))
+ .on_action(cx.listener(Self::unstage_selected))
+ .on_action(cx.listener(Self::stage_section))
+ .on_action(cx.listener(Self::unstage_section))
+ .on_action(cx.listener(Self::revert_selected))
+ .on_action(cx.listener(Self::add_to_gitignore))
+ .on_action(cx.listener(Self::add_to_git_info_exclude))
+ })
.on_action(cx.listener(Self::cancel))
.on_action(cx.listener(Self::collapse_selected_entry))
.on_action(cx.listener(Self::expand_selected_entry))
@@ -11910,7 +12136,8 @@ mod tests {
assert_eq!(panel.entry_count, 6);
assert_eq!(
panel
- .change_entries_by_path()
+ .change_entries
+ .iter()
.filter(|entry| entry.status.is_created())
.map(|entry| &*entry.repo_path)
.sorted()
@@ -12311,7 +12538,8 @@ mod tests {
.expect("active repository should exist")
.read(cx);
let entry = panel
- .change_entries_by_path()
+ .change_entries
+ .iter()
.find(|entry| entry.repo_path == repo_path(path))
.expect("entry should exist")
.clone();
@@ -12432,7 +12660,8 @@ mod tests {
// A shift-click range sweep anchored at the conflict must skip it too.
let staged_entry = panel.read_with(&cx, |panel, _| {
panel
- .change_entries_by_path()
+ .change_entries
+ .iter()
.find(|entry| entry.repo_path == repo_path("staged.rs"))
.cloned()
.expect("staged entry should exist")
@@ -17377,4 +17606,957 @@ mod tests {
);
});
}
+
+ struct BranchModeTest {
+ fs: Arc<FakeFs>,
+ project: Entity<Project>,
+ workspace: Entity<Workspace>,
+ panel: Entity<GitPanel>,
+ }
+
+ /// A branch whose merge base has `a.txt`, `c.txt` and `d.txt`: `a.txt`
+ /// changed in a commit, `d.txt` has an uncommitted change, `b.txt` is
+ /// untracked, and `c.txt` is unchanged.
+ async fn setup_branch_mode_test(
+ cx: &mut TestAppContext,
+ default_branch_ref: Option<&str>,
+ ) -> (BranchModeTest, VisualTestContext) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.background_executor.clone());
+ fs.insert_tree(
+ path!("/project"),
+ json!({
+ ".git": {},
+ "a.txt": "A2",
+ "b.txt": "B",
+ "c.txt": "C",
+ "d.txt": "D2",
+ }),
+ )
+ .await;
+ let dot_git = Path::new(path!("/project/.git"));
+ fs.with_git_state(dot_git, true, |state| {
+ state.default_branch_ref = default_branch_ref.map(str::to_owned);
+ })
+ .unwrap();
+ fs.set_head_and_index_for_repo(
+ dot_git,
+ &[
+ ("a.txt", "A2".into()),
+ ("c.txt", "C".into()),
+ ("d.txt", "D".into()),
+ ],
+ );
+ fs.set_merge_base_content_for_repo(
+ dot_git,
+ &[
+ ("a.txt", "A1".into()),
+ ("c.txt", "C".into()),
+ ("d.txt", "D".into()),
+ ],
+ );
+
+ let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
+ let window_handle =
+ cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
+ let workspace = window_handle
+ .read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone())
+ .unwrap();
+ let mut cx = VisualTestContext::from_window(window_handle.into(), cx);
+ cx.run_until_parked();
+
+ let panel = workspace.update_in(&mut cx, GitPanel::new);
+ settle_branch_mode(&mut cx);
+
+ (
+ BranchModeTest {
+ fs,
+ project,
+ workspace,
+ panel,
+ },
+ cx,
+ )
+ }
+
+ fn settle_branch_mode(cx: &mut VisualTestContext) {
+ for _ in 0..3 {
+ cx.run_until_parked();
+ cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
+ }
+ cx.run_until_parked();
+ }
+
+ fn branch_base(panel: &Entity<GitPanel>, cx: &mut VisualTestContext) -> Option<String> {
+ panel.read_with(cx, |panel, _| {
+ panel.branch_base.effective().map(|base| base.to_string())
+ })
+ }
+
+ fn listed_paths(panel: &Entity<GitPanel>, cx: &mut VisualTestContext) -> Vec<String> {
+ panel.read_with(cx, |panel, _| {
+ panel
+ .entries
+ .iter()
+ .filter_map(|entry| entry.status_entry())
+ .map(|entry| entry.repo_path.as_unix_str().to_owned())
+ .collect()
+ })
+ }
+
+ fn uncommitted_paths(panel: &Entity<GitPanel>, cx: &mut VisualTestContext) -> Vec<String> {
+ panel.read_with(cx, |panel, _| {
+ panel
+ .change_entries
+ .iter()
+ .map(|entry| entry.repo_path.as_unix_str().to_owned())
+ .sorted()
+ .collect()
+ })
+ }
+
+ fn branch_diff_bases(workspace: &Entity<Workspace>, cx: &mut VisualTestContext) -> Vec<String> {
+ workspace.read_with(cx, |workspace, cx| {
+ workspace
+ .items_of_type::<BranchDiff>(cx)
+ .filter_map(|branch_diff| match branch_diff.read(cx).diff_base(cx) {
+ DiffBase::Merge { base_ref } => Some(base_ref.to_string()),
+ DiffBase::Head | DiffBase::Index | DiffBase::Staged => None,
+ })
+ .collect()
+ })
+ }
+
+ fn open_branch_diff_tab(test: &BranchModeTest, base_ref: &str, cx: &mut VisualTestContext) {
+ let repo = test
+ .project
+ .read_with(cx, |project, cx| project.active_repository(cx))
+ .unwrap();
+ let project = test.project.clone();
+ let base_ref = SharedString::from(base_ref.to_owned());
+ test.workspace.update_in(cx, |workspace, window, cx| {
+ BranchDiff::deploy_branch_diff_with_base_ref(
+ workspace, project, repo, base_ref, None, None, window, cx,
+ );
+ });
+ settle_branch_mode(cx);
+ }
+
+ #[gpui::test]
+ async fn test_branch_mode_lists_all_changes_since_base(cx: &mut TestAppContext) {
+ let (test, mut cx) = setup_branch_mode_test(cx, Some("refs/remotes/origin/main")).await;
+ let cx = &mut cx;
+ let panel = test.panel;
+
+ assert_eq!(listed_paths(&panel, cx), ["d.txt", "b.txt"]);
+
+ panel.update_in(cx, |panel, window, cx| {
+ panel.enter_branch_mode(window, cx);
+ });
+ settle_branch_mode(cx);
+
+ assert_eq!(listed_paths(&panel, cx), ["a.txt", "b.txt", "d.txt"]);
+ panel.read_with(cx, |panel, _| {
+ assert_eq!(
+ panel.branch_base.effective().as_deref(),
+ Some("origin/main")
+ );
+ assert_eq!(panel.section_file_counts.get(&Section::Branch), Some(&3));
+ assert_eq!(panel.changes_count, 2);
+ assert!(
+ !panel
+ .entries
+ .iter()
+ .any(|entry| matches!(entry, GitListEntry::Header(_))),
+ "the branch list has no section headers",
+ );
+ });
+ assert_eq!(
+ uncommitted_paths(&panel, cx),
+ ["b.txt", "d.txt"],
+ "committing still acts on the uncommitted files",
+ );
+
+ panel.update_in(cx, |panel, window, cx| {
+ panel.enter_uncommitted_mode(window, cx);
+ });
+ settle_branch_mode(cx);
+ assert_eq!(listed_paths(&panel, cx), ["d.txt", "b.txt"]);
+ panel.read_with(cx, |panel, _| assert!(panel.branch_list().is_none()));
+
+ panel.update_in(cx, |panel, window, cx| {
+ panel.show_branch_changes_since("develop".into(), window, cx);
+ });
+ settle_branch_mode(cx);
+ // The fake repository lists the same files for every base, so check
+ // that the list itself moved to the new base.
+ panel.read_with(cx, |panel, cx| {
+ assert!(panel.is_branch_mode());
+ assert_eq!(panel.branch_base.effective().as_deref(), Some("develop"));
+ assert_eq!(
+ panel.branch_list().unwrap().read(cx).diff_base(),
+ &DiffBase::Merge {
+ base_ref: "develop".into()
+ }
+ );
+ });
+ }
+
+ #[gpui::test]
+ async fn test_branch_mode_rows_across_base_switches(cx: &mut TestAppContext) {
+ let (test, mut cx) = setup_branch_mode_test(cx, Some("refs/remotes/origin/main")).await;
+ let cx = &mut cx;
+ let panel = test.panel.clone();
+ let dot_git = Path::new(path!("/project/.git"));
+ let switch_base = |base: &'static str, cx: &mut VisualTestContext| {
+ panel.update_in(cx, |panel, window, cx| {
+ panel.show_branch_changes_since(base.into(), window, cx);
+ });
+ };
+ let tree_diff_failed = |cx: &mut VisualTestContext| {
+ panel.read_with(cx, |panel, cx| {
+ panel
+ .branch_list()
+ .is_some_and(|list| list.read(cx).tree_diff_error().is_some())
+ })
+ };
+
+ panel.update_in(cx, |panel, window, cx| {
+ panel.enter_branch_mode(window, cx);
+ });
+ settle_branch_mode(cx);
+ assert_eq!(listed_paths(&panel, cx), ["a.txt", "b.txt", "d.txt"]);
+
+ // The fake repository has one merge base for every ref, so change it
+ // without a git event before switching.
+ let origin_main_merge_base = test
+ .fs
+ .with_git_state(dot_git, false, |state| {
+ let merge_base = state.merge_base_contents.clone();
+ state.merge_base_contents.remove(&repo_path("c.txt"));
+ merge_base
+ })
+ .unwrap();
+ switch_base("develop", cx);
+ settle_branch_mode(cx);
+ assert_eq!(
+ listed_paths(&panel, cx),
+ ["a.txt", "b.txt", "c.txt", "d.txt"]
+ );
+
+ // A merge base blob that can't be read makes the reload fail. Reloads
+ // only run when statuses change, so stage a file to start one.
+ test.fs
+ .with_git_state(dot_git, false, |state| {
+ state
+ .merge_base_contents
+ .insert(repo_path("a.txt"), Oid::from_bytes(&[1; 20]).unwrap());
+ })
+ .unwrap();
+ test.fs.set_index_for_repo(
+ dot_git,
+ &[
+ ("a.txt", "A2".into()),
+ ("c.txt", "C".into()),
+ ("d.txt", "D2".into()),
+ ],
+ );
+ settle_branch_mode(cx);
+ assert!(tree_diff_failed(cx));
+ assert!(
+ listed_paths(&panel, cx).is_empty(),
+ "a failed reload hides the rows from the last load",
+ );
+
+ test.fs
+ .with_git_state(dot_git, false, |state| {
+ state.merge_base_contents = origin_main_merge_base;
+ })
+ .unwrap();
+ switch_base("origin/main", cx);
+ assert!(
+ listed_paths(&panel, cx).is_empty(),
+ "switching away from a failed base doesn't bring its rows back",
+ );
+ settle_branch_mode(cx);
+ assert!(!tree_diff_failed(cx));
+ assert_eq!(listed_paths(&panel, cx), ["a.txt", "b.txt", "d.txt"]);
+ }
+
+ #[gpui::test]
+ async fn test_branch_mode_ignores_staging_actions(cx: &mut TestAppContext) {
+ let (test, mut cx) = setup_branch_mode_test(cx, Some("refs/remotes/origin/main")).await;
+ let cx = &mut cx;
+ let panel = test.panel.clone();
+ test.workspace.update_in(cx, |workspace, window, cx| {
+ workspace.add_panel(panel.clone(), window, cx);
+ workspace.open_panel::<GitPanel>(window, cx);
+ });
+
+ panel.update_in(cx, |panel, window, cx| {
+ panel.enter_branch_mode(window, cx);
+ });
+ settle_branch_mode(cx);
+
+ let d_index = panel.read_with(cx, |panel, _| {
+ panel.entry_by_path(&repo_path("d.txt")).unwrap()
+ });
+ panel.update_in(cx, |panel, window, cx| {
+ panel.selected_entry = Some(d_index);
+ panel.focus_handle.focus(window, cx);
+ });
+ // Actions only reach the panel's handlers once it has been drawn.
+ cx.update(|window, cx| window.draw(cx).clear(cx));
+ cx.dispatch_action(ToggleStaged);
+ settle_branch_mode(cx);
+
+ let staging = test.project.read_with(cx, |project, cx| {
+ project
+ .active_repository(cx)
+ .unwrap()
+ .read(cx)
+ .status_for_path(&repo_path("d.txt"))
+ .unwrap()
+ .status
+ .staging()
+ });
+ assert_eq!(staging, StageStatus::Unstaged);
+ let index = test
+ .fs
+ .with_git_state(Path::new(path!("/project/.git")), false, |state| {
+ state.index_contents.get(&repo_path("d.txt")).cloned()
+ })
+ .unwrap();
+ assert_eq!(index, Some(b"D".to_vec()));
+ }
+
+ #[gpui::test]
+ async fn test_branch_mode_follows_active_branch_diff(cx: &mut TestAppContext) {
+ let (test, mut cx) = setup_branch_mode_test(cx, Some("refs/remotes/origin/main")).await;
+ let cx = &mut cx;
+ let panel = test.panel.clone();
+ let base = |cx: &mut VisualTestContext| {
+ panel.read_with(cx, |panel, _| {
+ panel.branch_base.effective().map(|base| base.to_string())
+ })
+ };
+
+ open_branch_diff_tab(&test, "release", cx);
+ assert_eq!(base(cx), None);
+
+ panel.update_in(cx, |panel, window, cx| {
+ panel.show_branch_changes(&ShowBranchChanges, window, cx);
+ });
+ settle_branch_mode(cx);
+ panel.read_with(cx, |panel, cx| {
+ let branch_list = panel.branch_list().unwrap().read(cx);
+ assert_eq!(
+ branch_list.diff_base(),
+ &DiffBase::Merge {
+ base_ref: "release".into()
+ }
+ );
+ });
+
+ open_branch_diff_tab(&test, "develop", cx);
+ assert_eq!(base(cx).as_deref(), Some("develop"));
+
+ panel.update_in(cx, |panel, window, cx| {
+ panel.set_branch_base("feature".into(), window, cx);
+ });
+ settle_branch_mode(cx);
+ assert_eq!(base(cx).as_deref(), Some("feature"));
+ assert_eq!(
+ branch_diff_bases(&test.workspace, cx),
+ ["release", "develop"]
+ );
+
+ let release_tab = test.workspace.read_with(cx, |workspace, cx| {
+ workspace.items_of_type::<BranchDiff>(cx).next().unwrap()
+ });
+ test.workspace.update_in(cx, |workspace, window, cx| {
+ workspace.activate_item(&release_tab, true, true, window, cx);
+ });
+ settle_branch_mode(cx);
+ assert_eq!(base(cx).as_deref(), Some("release"));
+
+ let release_list =
+ release_tab.read_with(cx, |branch_diff, cx| branch_diff.branch_diff_list(cx));
+ release_list.update(cx, |branch_list, cx| {
+ branch_list.set_diff_base(
+ DiffBase::Merge {
+ base_ref: "hotfix".into(),
+ },
+ cx,
+ );
+ });
+ settle_branch_mode(cx);
+ assert_eq!(base(cx).as_deref(), Some("hotfix"));
+ }
+
+ #[gpui::test]
+ async fn test_following_another_branch_diff_drops_previous_rows(cx: &mut TestAppContext) {
+ let (test, mut cx) = setup_branch_mode_test(cx, Some("refs/remotes/origin/main")).await;
+ let cx = &mut cx;
+ let panel = test.panel.clone();
+
+ open_branch_diff_tab(&test, "release", cx);
+ open_branch_diff_tab(&test, "develop", cx);
+ panel.update_in(cx, |panel, window, cx| {
+ panel.show_branch_changes(&ShowBranchChanges, window, cx);
+ });
+ settle_branch_mode(cx);
+ assert_eq!(listed_paths(&panel, cx), ["a.txt", "b.txt", "d.txt"]);
+
+ let release_tab = test.workspace.read_with(cx, |workspace, cx| {
+ workspace.items_of_type::<BranchDiff>(cx).next().unwrap()
+ });
+ test.workspace.update_in(cx, |workspace, window, cx| {
+ workspace.activate_item(&release_tab, true, true, window, cx);
+ });
+ assert_eq!(branch_base(&panel, cx).as_deref(), Some("release"));
+ assert!(
+ listed_paths(&panel, cx).is_empty(),
+ "rows from the previous base are dropped without waiting for the debounce",
+ );
+
+ settle_branch_mode(cx);
+ assert_eq!(listed_paths(&panel, cx), ["a.txt", "b.txt", "d.txt"]);
+ }
+
+ #[gpui::test]
+ async fn test_followed_tab_base_change_drops_previous_rows(cx: &mut TestAppContext) {
+ let (test, mut cx) = setup_branch_mode_test(cx, Some("refs/remotes/origin/main")).await;
+ let cx = &mut cx;
+ let panel = test.panel.clone();
+
+ open_branch_diff_tab(&test, "develop", cx);
+ panel.update_in(cx, |panel, window, cx| {
+ panel.show_branch_changes(&ShowBranchChanges, window, cx);
+ });
+ settle_branch_mode(cx);
+ assert_eq!(listed_paths(&panel, cx), ["a.txt", "b.txt", "d.txt"]);
+
+ let tab_list = test.workspace.read_with(cx, |workspace, cx| {
+ let tab = workspace.items_of_type::<BranchDiff>(cx).next().unwrap();
+ tab.read(cx).branch_diff_list(cx)
+ });
+ tab_list.update(cx, |list, cx| {
+ list.set_diff_base(
+ DiffBase::Merge {
+ base_ref: "hotfix".into(),
+ },
+ cx,
+ );
+ });
+ assert_eq!(branch_base(&panel, cx).as_deref(), Some("hotfix"));
+ assert!(
+ listed_paths(&panel, cx).is_empty(),
+ "rows from the previous base are dropped without waiting for the debounce",
+ );
+ }
+
+ #[gpui::test]
+ async fn test_new_default_branch_drops_previous_rows(cx: &mut TestAppContext) {
+ let (test, mut cx) = setup_branch_mode_test(cx, Some("refs/remotes/origin/main")).await;
+ let cx = &mut cx;
+ let panel = test.panel.clone();
+
+ panel.update_in(cx, |panel, window, cx| {
+ panel.enter_branch_mode(window, cx);
+ });
+ settle_branch_mode(cx);
+ assert_eq!(listed_paths(&panel, cx), ["a.txt", "b.txt", "d.txt"]);
+
+ test.fs
+ .with_git_state(Path::new(path!("/project/.git")), false, |state| {
+ state.default_branch_ref = Some("refs/remotes/origin/develop".to_owned());
+ })
+ .unwrap();
+ panel.update_in(cx, |panel, window, cx| {
+ panel.default_branch_may_have_changed(window, cx);
+ });
+ // Runs the lookup without advancing the clock to the debounce.
+ while cx.executor().tick() {}
+ assert_eq!(branch_base(&panel, cx).as_deref(), Some("origin/develop"));
+ assert!(
+ listed_paths(&panel, cx).is_empty(),
+ "rows from the previous base are dropped without waiting for the debounce",
+ );
+ }
+
+ #[gpui::test]
+ async fn test_show_branch_changes_drops_rows_of_previous_base(cx: &mut TestAppContext) {
+ let (test, mut cx) = setup_branch_mode_test(cx, Some("refs/remotes/origin/main")).await;
+ let cx = &mut cx;
+ let panel = test.panel.clone();
+
+ open_branch_diff_tab(&test, "develop", cx);
+ panel.update_in(cx, |panel, window, cx| {
+ panel.show_branch_changes_since("feature".into(), window, cx);
+ });
+ settle_branch_mode(cx);
+ assert_eq!(listed_paths(&panel, cx), ["a.txt", "b.txt", "d.txt"]);
+
+ panel.update_in(cx, |panel, window, cx| {
+ panel.show_branch_changes(&ShowBranchChanges, window, cx);
+ });
+ assert_eq!(branch_base(&panel, cx).as_deref(), Some("develop"));
+ assert!(
+ listed_paths(&panel, cx).is_empty(),
+ "rows from the previous base are dropped without waiting for the debounce",
+ );
+ }
+
+ #[gpui::test]
+ async fn test_branch_mode_opens_branch_diff_at_panel_base(cx: &mut TestAppContext) {
+ let (test, mut cx) = setup_branch_mode_test(cx, Some("refs/remotes/origin/main")).await;
+ let cx = &mut cx;
+ let panel = test.panel.clone();
+
+ panel.update_in(cx, |panel, window, cx| {
+ panel.enter_branch_mode(window, cx);
+ });
+ settle_branch_mode(cx);
+
+ let d_index = panel.read_with(cx, |panel, _| {
+ panel.entry_by_path(&repo_path("d.txt")).unwrap()
+ });
+ for _ in 0..2 {
+ panel.update_in(cx, |panel, window, cx| {
+ panel.selected_entry = Some(d_index);
+ panel.open_diff(&menu::Confirm, window, cx);
+ });
+ settle_branch_mode(cx);
+ }
+
+ assert_eq!(
+ branch_diff_bases(&test.workspace, cx),
+ ["origin/main"],
+ "opening a row reuses the tab at the panel's base",
+ );
+ let active_base = test.workspace.read_with(cx, |workspace, cx| {
+ workspace
+ .active_item_as::<BranchDiff>(cx)
+ .map(|branch_diff| branch_diff.read(cx).diff_base(cx).clone())
+ });
+ assert_eq!(
+ active_base,
+ Some(DiffBase::Merge {
+ base_ref: "origin/main".into()
+ })
+ );
+ }
+
+ #[gpui::test]
+ async fn test_branch_mode_row_open_in_new_tab_shows_that_row(cx: &mut TestAppContext) {
+ let (test, mut cx) = setup_branch_mode_test(cx, Some("refs/remotes/origin/main")).await;
+ let cx = &mut cx;
+ let panel = test.panel.clone();
+
+ panel.update_in(cx, |panel, window, cx| {
+ panel.enter_branch_mode(window, cx);
+ });
+ settle_branch_mode(cx);
+
+ let d_index = panel.read_with(cx, |panel, _| {
+ panel.entry_by_path(&repo_path("d.txt")).unwrap()
+ });
+ panel.update_in(cx, |panel, window, cx| {
+ panel.selected_entry = Some(d_index);
+ panel.open_diff(&menu::Confirm, window, cx);
+ });
+ settle_branch_mode(cx);
+
+ let shown_path = test.workspace.read_with(cx, |workspace, cx| {
+ let branch_diff = workspace.active_item_as::<BranchDiff>(cx)?;
+ branch_diff.read(cx).active_project_path(cx)
+ });
+ assert_eq!(
+ shown_path.map(|project_path| project_path.path.as_unix_str().to_owned()),
+ Some("d.txt".to_owned()),
+ "the new tab waits for its files to load before scrolling to the row",
+ );
+ }
+
+ #[gpui::test]
+ async fn test_branch_mode_row_open_focuses_like_uncommitted_mode(cx: &mut TestAppContext) {
+ let (test, mut cx) = setup_branch_mode_test(cx, Some("refs/remotes/origin/main")).await;
+ let cx = &mut cx;
+ let panel = test.panel.clone();
+
+ // Focus only stays on a drawn panel; otherwise the workspace takes
+ // it back for the active item.
+ test.workspace.update_in(cx, |workspace, window, cx| {
+ workspace.add_panel(panel.clone(), window, cx);
+ workspace.open_panel::<GitPanel>(window, cx);
+ });
+ panel.update_in(cx, |panel, window, cx| {
+ panel.enter_branch_mode(window, cx);
+ panel.focus_handle.focus(window, cx);
+ });
+ settle_branch_mode(cx);
+
+ let open_row = |path: &str, cx: &mut VisualTestContext| {
+ let index = panel.read_with(cx, |panel, _| {
+ panel.entry_by_path(&repo_path(path)).unwrap()
+ });
+ panel.update_in(cx, |panel, window, cx| {
+ panel.selected_entry = Some(index);
+ panel.open_diff(&menu::Confirm, window, cx);
+ });
+ settle_branch_mode(cx);
+ };
+ let focus = |cx: &mut VisualTestContext| {
+ let branch_diff = test.workspace.read_with(cx, |workspace, cx| {
+ workspace.active_item_as::<BranchDiff>(cx).unwrap()
+ });
+ cx.update(|window, cx| {
+ (
+ panel.read(cx).focus_handle.is_focused(window),
+ branch_diff.focus_handle(cx).contains_focused(window, cx),
+ )
+ })
+ };
+
+ open_row("d.txt", cx);
+ assert_eq!(
+ focus(cx),
+ (true, false),
+ "opening a row in a new tab keeps focus in the panel",
+ );
+
+ open_row("a.txt", cx);
+ assert_eq!(
+ focus(cx),
+ (true, false),
+ "opening another row in the existing tab keeps focus in the panel",
+ );
+
+ open_row("a.txt", cx);
+ assert_eq!(
+ focus(cx),
+ (false, true),
+ "opening the row the tab already shows focuses the tab",
+ );
+ }
+
+ struct MenuHost(Entity<ContextMenu>);
+
+ impl Render for MenuHost {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ div().size_full().child(self.0.clone())
+ }
+ }
+
+ #[gpui::test]
+ async fn test_compare_against_base_submenu_picks_base(cx: &mut TestAppContext) {
+ let (test, mut cx) = setup_branch_mode_test(cx, Some("refs/remotes/origin/main")).await;
+ let cx = &mut cx;
+ let panel = test.panel.clone();
+ test.fs.insert_branches(
+ Path::new(path!("/project/.git")),
+ &["feature", "develop", "release"],
+ );
+ settle_branch_mode(cx);
+
+ // The submenu is placed using its trigger's bounds from the previous
+ // frame, so it takes a couple of frames to appear.
+ let draw = |cx: &mut VisualTestContext| {
+ for _ in 0..3 {
+ cx.update(|window, cx| window.draw(cx).clear(cx));
+ cx.run_until_parked();
+ }
+ };
+ // Hosts the menu in its own window so the test can focus it directly;
+ // a popover only takes focus on a later platform frame.
+ let open_menu = |cx: &mut VisualTestContext| {
+ let panel = panel.downgrade();
+ let mut menu = None;
+ let window = cx.cx.add_window(|window, cx| {
+ let context_menu = GitPanel::changes_mode_menu(panel, window, cx);
+ menu = Some(context_menu.clone());
+ MenuHost(context_menu)
+ });
+ let menu = menu.unwrap();
+ let mut menu_cx = VisualTestContext::from_window(window.into(), &cx.cx);
+ menu_cx.update(|window, cx| window.focus(&menu.focus_handle(cx), cx));
+ draw(&mut menu_cx);
+ // "Compare Against Base" is the last item; opening it from the
+ // keyboard must hand focus to the picker's search field.
+ menu_cx.dispatch_action(menu::SelectLast);
+ menu_cx.dispatch_action(menu::SelectChild);
+ draw(&mut menu_cx);
+ (menu, menu_cx)
+ };
+
+ let (menu, mut menu_cx) = open_menu(cx);
+ menu_cx.dispatch_action(menu::Cancel);
+ draw(&mut menu_cx);
+ let parent_focused = menu_cx.update(|window, cx| menu.focus_handle(cx).is_focused(window));
+ assert!(parent_focused, "escape returns to the parent menu");
+
+ let (_menu, mut menu_cx) = open_menu(cx);
+ menu_cx.simulate_input("develop");
+ draw(&mut menu_cx);
+ menu_cx.dispatch_action(menu::Confirm);
+ settle_branch_mode(cx);
+
+ panel.read_with(cx, |panel, _| {
+ assert!(panel.is_branch_mode());
+ assert_eq!(panel.branch_base.effective().as_deref(), Some("develop"));
+ });
+ }
+
+ #[gpui::test]
+ async fn test_compare_against_base_action_opens_picker(cx: &mut TestAppContext) {
+ let (test, mut cx) = setup_branch_mode_test(cx, Some("refs/remotes/origin/main")).await;
+ let cx = &mut cx;
+ let panel = test.panel.clone();
+ test.workspace.update_in(cx, |workspace, window, cx| {
+ workspace.add_panel(panel.clone(), window, cx);
+ });
+
+ // Workspace actions run while the workspace is being updated, so
+ // opening the picker must not update the workspace again.
+ cx.dispatch_action(CompareAgainstBase);
+ cx.run_until_parked();
+
+ let picker_opened = test.workspace.read_with(cx, |workspace, cx| {
+ workspace
+ .active_modal::<branch_picker::BranchList>(cx)
+ .is_some()
+ });
+ assert!(picker_opened);
+ }
+
+ #[gpui::test]
+ async fn test_branch_mode_needs_a_base(cx: &mut TestAppContext) {
+ let (test, mut cx) = setup_branch_mode_test(cx, None).await;
+ let cx = &mut cx;
+ let panel = test.panel.clone();
+
+ panel.update_in(cx, |panel, window, cx| {
+ panel.show_branch_changes(&ShowBranchChanges, window, cx);
+ });
+ cx.run_until_parked();
+ panel.read_with(cx, |panel, _| {
+ assert!(!panel.is_branch_mode());
+ });
+ let picker_opened = test.workspace.read_with(cx, |workspace, cx| {
+ workspace
+ .active_modal::<branch_picker::BranchList>(cx)
+ .is_some()
+ });
+ assert!(
+ picker_opened,
+ "without a base, the base picker opens instead"
+ );
+ cx.dispatch_action(menu::Cancel);
+
+ open_branch_diff_tab(&test, "release", cx);
+ panel.update_in(cx, |panel, window, cx| {
+ panel.show_branch_changes(&ShowBranchChanges, window, cx);
+ });
+ settle_branch_mode(cx);
+ assert_eq!(listed_paths(&panel, cx), ["a.txt", "b.txt", "d.txt"]);
+ }
+
+ fn base_picker_open(workspace: &Entity<Workspace>, cx: &mut VisualTestContext) -> bool {
+ workspace.read_with(cx, |workspace, cx| {
+ workspace
+ .active_modal::<branch_picker::BranchList>(cx)
+ .is_some()
+ })
+ }
+
+ // Without a default branch, a request still pending when the lookup
+ // finishes opens the base picker, so each case would end with one open.
+ // Marking the default stale makes the next request wait on a new lookup.
+ #[gpui::test]
+ async fn test_newer_navigation_drops_pending_branch_changes(cx: &mut TestAppContext) {
+ let (test, mut cx) = setup_branch_mode_test(cx, None).await;
+ let cx = &mut cx;
+ let panel = test.panel.clone();
+ test.fs
+ .insert_branches(Path::new(path!("/project/.git")), &["develop"]);
+ settle_branch_mode(cx);
+
+ panel.update_in(cx, |panel, window, cx| {
+ panel.show_branch_changes(&ShowBranchChanges, window, cx);
+ panel.show_uncommitted_changes(&ShowUncommittedChanges, window, cx);
+ });
+ settle_branch_mode(cx);
+ assert!(!base_picker_open(&test.workspace, cx));
+ panel.read_with(cx, |panel, _| assert!(!panel.is_branch_mode()));
+
+ panel.update_in(cx, |panel, window, cx| {
+ panel.default_branch_may_have_changed(window, cx);
+ panel.show_branch_changes(&ShowBranchChanges, window, cx);
+ panel.activate_history_tab(&ActivateHistoryTab, window, cx);
+ });
+ settle_branch_mode(cx);
+ assert!(!base_picker_open(&test.workspace, cx));
+ panel.read_with(cx, |panel, _| {
+ assert_eq!(panel.active_tab, GitPanelTab::History);
+ });
+
+ panel.update_in(cx, |panel, window, cx| {
+ panel.default_branch_may_have_changed(window, cx);
+ panel.show_branch_changes(&ShowBranchChanges, window, cx);
+ panel.choose_branch_base(window, cx);
+ });
+ settle_branch_mode(cx);
+ assert!(
+ base_picker_open(&test.workspace, cx),
+ "the pending request must not toggle the picker closed"
+ );
+ cx.dispatch_action(menu::Cancel);
+ cx.run_until_parked();
+ assert!(!base_picker_open(&test.workspace, cx));
+
+ panel.update_in(cx, |panel, window, cx| {
+ panel.default_branch_may_have_changed(window, cx);
+ panel.show_branch_changes_and_open_diff(window, cx);
+ panel.show_branch_changes_since("develop".into(), window, cx);
+ });
+ settle_branch_mode(cx);
+ assert!(!base_picker_open(&test.workspace, cx));
+ assert!(branch_diff_bases(&test.workspace, cx).is_empty());
+ panel.read_with(cx, |panel, _| {
+ assert!(panel.is_branch_mode());
+ assert_eq!(panel.branch_base.effective().as_deref(), Some("develop"));
+ });
+ }
+
+ #[gpui::test]
+ async fn test_dropping_pending_branch_changes_drops_its_adopted_base(cx: &mut TestAppContext) {
+ let (test, mut cx) = setup_branch_mode_test(cx, None).await;
+ let cx = &mut cx;
+ let panel = test.panel.clone();
+ let repo = test
+ .project
+ .read_with(cx, |project, cx| project.active_repository(cx))
+ .unwrap();
+
+ // Each step runs before the lookup the first request started can
+ // finish, so the second request adopts the tab's base and then waits.
+ panel.update_in(cx, |panel, window, cx| {
+ panel.show_branch_changes(&ShowBranchChanges, window, cx);
+ });
+ let project = test.project.clone();
+ test.workspace.update_in(cx, |workspace, window, cx| {
+ BranchDiff::deploy_branch_diff_with_base_ref(
+ workspace,
+ project,
+ repo,
+ "release".into(),
+ None,
+ None,
+ window,
+ cx,
+ );
+ });
+ panel.update_in(cx, |panel, window, cx| {
+ panel.show_branch_changes(&ShowBranchChanges, window, cx);
+ panel.show_uncommitted_changes(&ShowUncommittedChanges, window, cx);
+ });
+ settle_branch_mode(cx);
+
+ panel.read_with(cx, |panel, _| {
+ assert!(!panel.is_branch_mode());
+ assert_eq!(
+ panel.branch_base.effective(),
+ None,
+ "uncommitted mode keeps no base from the dropped request",
+ );
+ });
+ }
+
+ #[gpui::test]
+ async fn test_lookup_woken_before_a_repository_switch_is_ignored(cx: &mut TestAppContext) {
+ let (test, mut cx) = setup_branch_mode_test(cx, Some("refs/remotes/origin/main")).await;
+ let cx = &mut cx;
+ let panel = test.panel;
+ let repo = test
+ .project
+ .read_with(cx, |project, cx| project.active_repository(cx).unwrap());
+
+ // A git job notifies right before sending its result, so a switch queued
+ // on that notify runs after the lookup wakes but before it runs.
+ let mut checked_switches = 0;
+ for switch_on_notify in 0.. {
+ let notifies = Rc::new(Cell::new(0));
+ let switched = Rc::new(Cell::new(None));
+ let _subscription = cx.update(|window, cx| {
+ let window_handle = window.window_handle();
+ let panel = panel.clone();
+ let notifies = notifies.clone();
+ let switched = switched.clone();
+ cx.observe(&repo, move |_, cx| {
+ let notify = notifies.get();
+ notifies.set(notify + 1);
+ if notify != switch_on_notify {
+ return;
+ }
+ let panel = panel.clone();
+ let switched = switched.clone();
+ cx.spawn(async move |cx| {
+ cx.update_window(window_handle, |_, window, cx| {
+ panel.update(cx, |panel, cx| {
+ switched.set(Some(panel.is_branch_mode()));
+ panel.reset_branch_state(window, cx);
+ });
+ })
+ .ok();
+ })
+ .detach();
+ })
+ });
+ panel.update_in(cx, |panel, window, cx| {
+ panel.show_branch_changes(&ShowBranchChanges, window, cx);
+ });
+ settle_branch_mode(cx);
+ // Past the last notify, or the request finished before the switch.
+ let Some(false) = switched.get() else {
+ break;
+ };
+ checked_switches += 1;
+ panel.read_with(cx, |panel, _| {
+ assert_eq!(
+ panel.branch_base.effective(),
+ None,
+ "a switch on notify {switch_on_notify} kept the previous repository's default",
+ );
+ });
+ }
+ assert!(checked_switches > 0);
+ }
+
+ #[gpui::test]
+ async fn test_newer_branch_changes_request_replaces_pending_one(cx: &mut TestAppContext) {
+ let (test, mut cx) = setup_branch_mode_test(cx, None).await;
+ let cx = &mut cx;
+ let panel = test.panel.clone();
+
+ panel.update_in(cx, |panel, window, cx| {
+ panel.show_branch_changes(&ShowBranchChanges, window, cx);
+ });
+ settle_branch_mode(cx);
+ cx.dispatch_action(menu::Cancel);
+ cx.run_until_parked();
+ assert!(!base_picker_open(&test.workspace, cx));
+
+ // The first request starts a refresh of the missing default. The second
+ // must wait on it too, or it opens the picker now and the first one
+ // toggles it closed when the refresh finishes.
+ panel.update_in(cx, |panel, window, cx| {
+ panel.default_branch_may_have_changed(window, cx);
+ panel.show_branch_changes(&ShowBranchChanges, window, cx);
+ panel.show_branch_changes(&ShowBranchChanges, window, cx);
+ });
+ settle_branch_mode(cx);
+ assert!(base_picker_open(&test.workspace, cx));
+ }
}
diff --git a/crates/git_ui/src/git_panel/branch_mode.rs b/crates/git_ui/src/git_panel/branch_mode.rs
new file mode 100644
index 00000000000..5caee10b207
--- /dev/null
+++ b/crates/git_ui/src/git_panel/branch_mode.rs
@@ -0,0 +1,893 @@
+use super::*;
+use futures::future::{FutureExt as _, Shared};
+use settings::GitDiffBaseSetting;
+
+pub(super) enum ChangesMode {
+ Uncommitted,
+ /// `None` until a base is known. The list only exists in branch mode, so
+ /// the panel runs no tree diffs otherwise.
+ Branch(Option<BranchList>),
+}
+
+pub(super) struct BranchList {
+ list: Entity<DiffBufferList>,
+ _subscription: Subscription,
+}
+
+impl BranchList {
+ /// A failed reload keeps the files from the last base that loaded, so
+ /// they're hidden to show the error instead.
+ fn shown_files(&self, cx: &App) -> Option<Vec<GitStatusEntry>> {
+ let list = self.list.read(cx);
+ if list.tree_diff_error().is_some() {
+ return None;
+ }
+ listed_files(list)
+ }
+}
+
+#[derive(Debug, PartialEq, Eq, Clone)]
+enum DefaultBranch {
+ NotLoaded,
+ Loading,
+ Found(SharedString),
+ Missing,
+}
+
+pub(super) struct BranchBase {
+ /// Picked in the panel, or adopted from the active branch diff tab while
+ /// in branch mode. Cleared on leaving branch mode.
+ picked: Option<SharedString>,
+ /// Looked up only when needed, because the branch list changes on every
+ /// commit, fetch and push.
+ default: DefaultBranch,
+ default_is_stale: bool,
+ /// Requests waiting on the default branch await clones of this, so
+ /// dropping one of them leaves the lookup running.
+ default_lookup: Shared<Task<()>>,
+ /// Bumped by every lookup and reset. A lookup only writes while the count
+ /// is still its own, since a cancelled request's clone can keep it running.
+ default_lookup_count: usize,
+ pending_show: Option<PendingShow>,
+ followed: Option<FollowedBranchDiff>,
+}
+
+/// A request to show branch changes that waits for the default branch to
+/// know between switching modes and opening the base picker.
+struct PendingShow {
+ request: ShowBranchChangesRequest,
+ wait: Task<()>,
+}
+
+/// The active branch diff tab. Branch mode adopts its base and follows base
+/// changes made in the tab's own picker.
+struct FollowedBranchDiff {
+ list: WeakEntity<DiffBufferList>,
+ _subscription: Subscription,
+}
+
+#[derive(Clone, Copy)]
+struct ShowBranchChangesRequest {
+ /// The empty state's button, which also opens the diff. It uses the
+ /// default branch, or the picked base when there is none.
+ from_empty_state: bool,
+}
+
+impl BranchBase {
+ pub(super) fn new() -> Self {
+ Self {
+ picked: None,
+ default: DefaultBranch::NotLoaded,
+ default_is_stale: false,
+ default_lookup: Task::ready(()).shared(),
+ default_lookup_count: 0,
+ pending_show: None,
+ followed: None,
+ }
+ }
+
+ pub(super) fn effective(&self) -> Option<SharedString> {
+ self.picked.clone().or_else(|| match &self.default {
+ DefaultBranch::Found(default_branch) => Some(default_branch.clone()),
+ DefaultBranch::NotLoaded | DefaultBranch::Loading | DefaultBranch::Missing => None,
+ })
+ }
+
+ fn is_resolving(&self) -> bool {
+ self.picked.is_none()
+ && matches!(
+ self.default,
+ DefaultBranch::NotLoaded | DefaultBranch::Loading
+ )
+ }
+
+ fn is_unavailable(&self) -> bool {
+ self.picked.is_none() && self.default == DefaultBranch::Missing
+ }
+
+ /// Whether showing branch changes has to wait for a lookup to know
+ /// between switching modes and opening the base picker.
+ fn needs_lookup_to_decide(&self) -> bool {
+ self.picked.is_none()
+ && match self.default {
+ DefaultBranch::NotLoaded | DefaultBranch::Loading => true,
+ DefaultBranch::Missing => self.default_is_stale,
+ DefaultBranch::Found(_) => false,
+ }
+ }
+
+ fn needs_lookup(&self) -> bool {
+ self.picked.is_none()
+ && match self.default {
+ DefaultBranch::NotLoaded => true,
+ DefaultBranch::Loading => false,
+ DefaultBranch::Found(_) | DefaultBranch::Missing => self.default_is_stale,
+ }
+ }
+}
+
+impl GitPanel {
+ pub(super) fn is_branch_mode(&self) -> bool {
+ matches!(self.changes_mode, ChangesMode::Branch(_))
+ }
+
+ pub(super) fn branch_list(&self) -> Option<&Entity<DiffBufferList>> {
+ match &self.changes_mode {
+ ChangesMode::Branch(Some(branch_list)) => Some(&branch_list.list),
+ ChangesMode::Uncommitted | ChangesMode::Branch(None) => None,
+ }
+ }
+
+ pub(super) fn enter_branch_mode(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ if self.is_branch_mode() {
+ return;
+ }
+ self.ensure_default_branch(window, cx);
+ self.changes_mode = ChangesMode::Branch(None);
+ self.changes_mode_changed(window, cx);
+ }
+
+ pub(super) fn enter_uncommitted_mode(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ // A request waiting on the lookup usually leaves the panel in
+ // uncommitted mode, so this drops it before the early return.
+ self.cancel_pending_branch_changes();
+ if !self.is_branch_mode() {
+ return;
+ }
+ self.changes_mode = ChangesMode::Uncommitted;
+ // The next switch to branch mode starts again from the active tab or
+ // the default branch, rather than from a base picked long ago.
+ self.branch_base.picked = None;
+ self.changes_mode_changed(window, cx);
+ }
+
+ fn changes_mode_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ self.clear_marks();
+ self.bulk_staging.take();
+ self.context_menu.take();
+ self.selected_entry = None;
+ self.update_visible_entries(window, cx);
+ }
+
+ pub(super) fn set_branch_base(
+ &mut self,
+ base_ref: SharedString,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if self.branch_base.picked.as_ref() == Some(&base_ref) {
+ return;
+ }
+ self.branch_base.picked = Some(base_ref);
+ if self.is_branch_mode() {
+ self.schedule_visible_entries_update(window, cx);
+ }
+ cx.notify();
+ }
+
+ /// Rows from the previous base would open the new base's diff with their
+ /// old statuses, so they can't wait for the update debounce.
+ pub(super) fn update_entries_if_base_changed(
+ &mut self,
+ previous_base: Option<SharedString>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if self.is_branch_mode() && self.branch_base.effective() != previous_base {
+ self.update_visible_entries(window, cx);
+ }
+ }
+
+ pub(super) fn show_branch_changes(
+ &mut self,
+ _: &ShowBranchChanges,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.show_branch_changes_for(
+ ShowBranchChangesRequest {
+ from_empty_state: false,
+ },
+ window,
+ cx,
+ );
+ }
+
+ pub(super) fn show_branch_changes_and_open_diff(
+ &mut self,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.show_branch_changes_for(
+ ShowBranchChangesRequest {
+ from_empty_state: true,
+ },
+ window,
+ cx,
+ );
+ }
+
+ fn show_branch_changes_for(
+ &mut self,
+ request: ShowBranchChangesRequest,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.set_active_tab(GitPanelTab::Changes, window, cx);
+ if self.active_repository.is_none() {
+ return;
+ }
+ // The empty state's button opens the default branch's diff, as it
+ // did before branch mode existed.
+ if !request.from_empty_state {
+ let previous_base = self.branch_base.effective();
+ self.adopt_followed_branch_diff_base(window, cx);
+ self.update_entries_if_base_changed(previous_base, window, cx);
+ }
+ // A pending request means a lookup is already running, so this one
+ // replaces it rather than acting on a default that's being refreshed
+ // and then having the stale request run on top of it.
+ if self.branch_base.pending_show.is_some() || self.branch_base.needs_lookup_to_decide() {
+ self.ensure_default_branch(window, cx);
+ self.show_after_lookup(request, window, cx);
+ return;
+ }
+ if self.branch_base.is_unavailable() {
+ self.choose_branch_base_for(request, window, cx);
+ return;
+ }
+ self.enter_branch_mode(window, cx);
+ if request.from_empty_state {
+ self.open_branch_diff(None, window, cx);
+ }
+ }
+
+ pub(super) fn show_branch_changes_since(
+ &mut self,
+ base_ref: SharedString,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.cancel_pending_branch_changes();
+ self.set_active_tab(GitPanelTab::Changes, window, cx);
+ let was_branch_mode = self.is_branch_mode();
+ self.set_branch_base(base_ref, window, cx);
+ if was_branch_mode {
+ // Sync now rather than after the update debounce, so the new base
+ // starts loading right away.
+ self.update_visible_entries(window, cx);
+ } else {
+ self.enter_branch_mode(window, cx);
+ }
+ }
+
+ fn on_base_picked(
+ panel: WeakEntity<GitPanel>,
+ request: ShowBranchChangesRequest,
+ ) -> impl Fn(Branch, &mut Window, &mut App) + 'static {
+ move |branch, window, cx| {
+ let base_ref: SharedString = branch.name().to_owned().into();
+ panel
+ .update(cx, |panel, cx| {
+ panel.show_branch_changes_since(base_ref, window, cx);
+ if request.from_empty_state {
+ panel.open_branch_diff(None, window, cx);
+ }
+ })
+ .ok();
+ }
+ }
+
+ pub(super) fn choose_branch_base(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ // Otherwise the pending request could open its own picker once the
+ // lookup finishes, which toggles this one closed.
+ self.cancel_pending_branch_changes();
+ self.choose_branch_base_for(
+ ShowBranchChangesRequest {
+ from_empty_state: false,
+ },
+ window,
+ cx,
+ );
+ }
+
+ fn choose_branch_base_for(
+ &mut self,
+ request: ShowBranchChangesRequest,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ let Some(repository) = self.active_repository.clone() else {
+ return;
+ };
+ let selected_branch = self.branch_base.effective();
+ let on_select: branch_picker::SelectBranchCallback =
+ Arc::new(Self::on_base_picked(cx.weak_entity(), request));
+ let workspace = self.workspace.clone();
+ // Workspace actions call this while the workspace is being updated, so
+ // the modal opens once that update has finished.
+ window.defer(cx, move |window, cx| {
+ let workspace_handle = workspace.clone();
+ workspace
+ .update(cx, |workspace, cx| {
+ workspace.toggle_modal(window, cx, |window, cx| {
+ branch_picker::select_modal(
+ workspace_handle,
+ Some(repository),
+ selected_branch,
+ on_select,
+ window,
+ cx,
+ )
+ });
+ })
+ .ok();
+ });
+ }
+
+ /// A request waiting on the default branch lookup runs once the lookup
+ /// finishes, so anything the user does in the meantime that it would undo
+ /// has to drop it. The lookup itself keeps running.
+ pub(super) fn cancel_pending_branch_changes(&mut self) {
+ // A request can adopt the active tab's base before it waits, and
+ // outside branch mode that base would outlive it.
+ if self.branch_base.pending_show.take().is_some() && !self.is_branch_mode() {
+ self.branch_base.picked = None;
+ }
+ }
+
+ fn show_after_lookup(
+ &mut self,
+ request: ShowBranchChangesRequest,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ let lookup = self.branch_base.default_lookup.clone();
+ let wait = cx.spawn_in(window, async move |this, cx| {
+ lookup.await;
+ this.update_in(cx, |this, window, cx| {
+ // This task is the pending one, and dropping a task's handle
+ // while it runs would cancel it.
+ if let Some(pending) = this.branch_base.pending_show.take() {
+ pending.wait.detach();
+ }
+ this.show_branch_changes_for(request, window, cx);
+ })
+ .ok();
+ });
+ self.branch_base.pending_show = Some(PendingShow { request, wait });
+ }
+
+ pub(super) fn show_uncommitted_changes(
+ &mut self,
+ _: &ShowUncommittedChanges,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.set_active_tab(GitPanelTab::Changes, window, cx);
+ self.enter_uncommitted_mode(window, cx);
+ }
+
+ /// Branch names don't carry over between repositories, so switching
+ /// repositories starts again from the new one's default branch.
+ pub(super) fn reset_branch_state(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ let default_lookup_count = self.branch_base.default_lookup_count + 1;
+ self.branch_base = BranchBase::new();
+ self.branch_base.default_lookup_count = default_lookup_count;
+ // The active tab may have become active before the repository switch,
+ // when it didn't belong to the active repository yet.
+ self.follow_active_branch_diff(window, cx);
+ if self.is_branch_mode() {
+ self.ensure_default_branch(window, cx);
+ }
+ }
+
+ pub(super) fn default_branch_may_have_changed(
+ &mut self,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.branch_base.default_is_stale = true;
+ if self.is_branch_mode() {
+ self.ensure_default_branch(window, cx);
+ }
+ }
+
+ fn ensure_default_branch(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ if self.branch_base.needs_lookup() {
+ self.resolve_default_branch(window, cx);
+ }
+ }
+
+ fn resolve_default_branch(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ self.branch_base.default_lookup_count += 1;
+ let lookup_id = self.branch_base.default_lookup_count;
+ self.branch_base.default_is_stale = false;
+ let Some(repo) = self.active_repository.clone() else {
+ self.branch_base.default = DefaultBranch::Missing;
+ return;
+ };
+ if self.branch_base.default == DefaultBranch::NotLoaded {
+ self.branch_base.default = DefaultBranch::Loading;
+ }
+ let default_branch = repo.update(cx, |repo, _| repo.default_branch(true));
+ let lookup = cx.spawn_in(window, async move |this, cx| {
+ let default_branch = match default_branch.await.ok().and_then(ResultExt::log_err) {
+ Some(Some(default_branch)) => DefaultBranch::Found(default_branch),
+ Some(None) | None => DefaultBranch::Missing,
+ };
+ this.update_in(cx, |this, window, cx| {
+ if this.branch_base.default_lookup_count != lookup_id {
+ return;
+ }
+ if this.branch_base.default != default_branch {
+ let previous_base = this.branch_base.effective();
+ this.branch_base.default = default_branch;
+ this.schedule_visible_entries_update(window, cx);
+ this.update_entries_if_base_changed(previous_base, window, cx);
+ cx.notify();
+ }
+ })
+ .ok();
+ });
+ self.branch_base.default_lookup = lookup.shared();
+ // A request left on the old lookup would decide before this one answers.
+ if let Some(pending) = self.branch_base.pending_show.take() {
+ self.show_after_lookup(pending.request, window, cx);
+ }
+ }
+
+ /// Runs at the start of every entries update, so changes to the mode,
+ /// repository or base only need to schedule one.
+ pub(super) fn sync_branch_list(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ let target = self
+ .active_repository
+ .clone()
+ .zip(self.branch_base.effective());
+ let git_store = self.project.read(cx).git_store().clone();
+ let ChangesMode::Branch(branch_list) = &mut self.changes_mode else {
+ return;
+ };
+ let Some((repo, base_ref)) = target else {
+ *branch_list = None;
+ return;
+ };
+ let diff_base = DiffBase::Merge { base_ref };
+
+ if let Some(branch_list) = branch_list {
+ branch_list.list.update(cx, |list, cx| {
+ list.set_repo(Some(repo), cx);
+ if list.diff_base() != &diff_base {
+ list.set_diff_base(diff_base, cx);
+ }
+ });
+ return;
+ }
+
+ let list = cx.new(|cx| DiffBufferList::new(diff_base, git_store, Some(repo), cx));
+ let subscription = cx.subscribe_in(
+ &list,
+ window,
+ |this, _, event: &BranchDiffEvent, window, cx| match event {
+ BranchDiffEvent::FileListChanged | BranchDiffEvent::DiffBaseChanged => {
+ this.schedule_visible_entries_update(window, cx);
+ }
+ },
+ );
+ *branch_list = Some(BranchList {
+ list,
+ _subscription: subscription,
+ });
+ }
+
+ pub(super) fn branch_status_entries(&self, cx: &App) -> Vec<GitStatusEntry> {
+ let ChangesMode::Branch(Some(branch_list)) = &self.changes_mode else {
+ return Vec::new();
+ };
+ branch_list.shown_files(cx).unwrap_or_default()
+ }
+
+ pub(super) fn follow_active_branch_diff(
+ &mut self,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ let Some(workspace) = self.workspace.upgrade() else {
+ return;
+ };
+ let Some(branch_diff) = workspace.read(cx).active_item_as::<BranchDiff>(cx) else {
+ self.branch_base.followed = None;
+ return;
+ };
+ let list = branch_diff.read(cx).branch_diff_list(cx);
+ if self
+ .branch_base
+ .followed
+ .as_ref()
+ .is_some_and(|followed| followed.list.entity_id() == list.entity_id())
+ {
+ return;
+ }
+
+ // Uncommitted mode only watches the tab, so a tab looked at long ago
+ // doesn't decide the base the next time branch mode opens.
+ let subscription = cx.subscribe_in(
+ &list,
+ window,
+ |this, list, event: &BranchDiffEvent, window, cx| {
+ if matches!(event, BranchDiffEvent::DiffBaseChanged) && this.is_branch_mode() {
+ let previous_base = this.branch_base.effective();
+ this.adopt_branch_diff_base(list, window, cx);
+ this.update_entries_if_base_changed(previous_base, window, cx);
+ }
+ },
+ );
+ self.branch_base.followed = Some(FollowedBranchDiff {
+ list: list.downgrade(),
+ _subscription: subscription,
+ });
+ if self.is_branch_mode() {
+ self.adopt_branch_diff_base(&list, window, cx);
+ }
+ }
+
+ /// Reads the watched tab rather than the workspace, because the panel's
+ /// actions run while the workspace is being updated.
+ fn adopt_followed_branch_diff_base(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ if let Some(list) = self
+ .branch_base
+ .followed
+ .as_ref()
+ .and_then(|followed| followed.list.upgrade())
+ {
+ self.adopt_branch_diff_base(&list, window, cx);
+ }
+ }
+
+ fn adopt_branch_diff_base(
+ &mut self,
+ list: &Entity<DiffBufferList>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ let list = list.read(cx);
+ let DiffBase::Merge { base_ref } = list.diff_base() else {
+ return;
+ };
+ let is_active_repository = list
+ .repo()
+ .zip(self.active_repository.as_ref())
+ .is_some_and(|(repo, active_repo)| repo.read(cx).id == active_repo.read(cx).id);
+ if !is_active_repository {
+ return;
+ }
+ let base_ref = base_ref.clone();
+ self.set_branch_base(base_ref, window, cx);
+ }
+
+ pub(super) fn open_branch_diff(
+ &mut self,
+ entry: Option<GitStatusEntry>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ let (Some(repo), Some(base_ref)) =
+ (self.active_repository.clone(), self.branch_base.effective())
+ else {
+ return;
+ };
+ let list = self
+ .branch_diff_tab(&base_ref, cx)
+ .map(|branch_diff| branch_diff.read(cx).branch_diff_list(cx))
+ .or_else(|| self.display_diff_at(&repo, &base_ref, cx));
+ let project = self.project.clone();
+ self.workspace
+ .update(cx, |workspace, cx| {
+ BranchDiff::deploy_branch_diff_with_base_ref(
+ workspace, project, repo, base_ref, list, entry, window, cx,
+ );
+ })
+ .ok();
+ }
+
+ /// The active branch diff tab, if it's at the panel's base and already
+ /// showing this entry.
+ pub(super) fn branch_diff_showing(
+ &self,
+ entry: &GitStatusEntry,
+ cx: &App,
+ ) -> Option<Entity<BranchDiff>> {
+ let base_ref = self.branch_base.effective()?;
+ let active = self
+ .workspace
+ .upgrade()?
+ .read(cx)
+ .active_item_as::<BranchDiff>(cx)?;
+ let project_path = active.read(cx).active_project_path(cx)?;
+ let repo_path = self
+ .active_repository
+ .as_ref()?
+ .read(cx)
+ .project_path_to_repo_path(&project_path, cx)?;
+ (self.is_branch_diff_at(&active, &base_ref, cx) && repo_path == entry.repo_path)
+ .then_some(active)
+ }
+
+ fn branch_diff_tab(&self, base_ref: &SharedString, cx: &App) -> Option<Entity<BranchDiff>> {
+ self.workspace
+ .upgrade()?
+ .read(cx)
+ .items_of_type::<BranchDiff>(cx)
+ .find(|branch_diff| self.is_branch_diff_at(branch_diff, base_ref, cx))
+ }
+
+ fn is_branch_diff_at(
+ &self,
+ branch_diff: &Entity<BranchDiff>,
+ base_ref: &SharedString,
+ cx: &App,
+ ) -> bool {
+ let Some(repo) = self.active_repository.as_ref() else {
+ return false;
+ };
+ let branch_diff = branch_diff.read(cx);
+ matches!(
+ branch_diff.diff_base(cx),
+ DiffBase::Merge { base_ref: existing } if existing == base_ref
+ ) && branch_diff
+ .repo(cx)
+ .is_some_and(|branch_diff_repo| branch_diff_repo.read(cx).id == repo.read(cx).id)
+ }
+
+ /// `DeployBranchDiff` only reuses a tab that holds the display diff's
+ /// list, so a new tab at the same base shares it. It's only read here:
+ /// `ensure_display_diff` would move the gutter to the panel's base.
+ fn display_diff_at(
+ &self,
+ repo: &Entity<Repository>,
+ base_ref: &SharedString,
+ cx: &App,
+ ) -> Option<Entity<DiffBufferList>> {
+ let git_store = self.project.read(cx).git_store().read(cx);
+ if git_store.diff_base() != GitDiffBaseSetting::DefaultBranch {
+ return None;
+ }
+ git_store
+ .display_diff_for_repo(repo.read(cx).id)
+ .filter(|list| {
+ matches!(
+ list.read(cx).diff_base(),
+ DiffBase::Merge { base_ref: display_base } if display_base == base_ref
+ )
+ })
+ }
+
+ pub(super) fn move_branch_diff_to_entry(
+ &mut self,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ maybe!({
+ let entry = self
+ .entries
+ .get(self.selected_entry?)?
+ .status_entry()?
+ .clone();
+ let base_ref = self.branch_base.effective()?;
+ let branch_diff = self.branch_diff_tab(&base_ref, cx)?;
+ branch_diff.update(cx, |branch_diff, cx| {
+ branch_diff.move_to_entry(entry, window, cx);
+ });
+ Some(())
+ });
+ }
+
+ pub(super) fn render_changes_mode_menu(&self, cx: &mut Context<Self>) -> impl IntoElement {
+ let label: SharedString = match (self.is_branch_mode(), self.branch_base.effective()) {
+ (true, Some(base_ref)) => format!("Since {base_ref}").into(),
+ (true, None) => "Branch Changes".into(),
+ (false, _) => "Uncommitted".into(),
+ };
+ let panel = cx.weak_entity();
+
+ PopoverMenu::new("git-panel-changes-mode")
+ .with_handle(self.changes_mode_menu_handle.clone())
+ .trigger_with_tooltip(
+ Button::new("git-panel-changes-mode-trigger", label)
+ .label_size(LabelSize::Small)
+ .end_icon(
+ Icon::new(IconName::ChevronDown)
+ .size(IconSize::XSmall)
+ .color(Color::Muted),
+ ),
+ Tooltip::text("Choose Which Changes to Show"),
+ )
+ .menu(move |window, cx| Some(Self::changes_mode_menu(panel.clone(), window, cx)))
+ .anchor(Anchor::TopLeft)
+ }
+
+ pub(super) fn changes_mode_menu(
+ panel: WeakEntity<GitPanel>,
+ window: &mut Window,
+ cx: &mut App,
+ ) -> Entity<ContextMenu> {
+ let is_branch_mode = panel
+ .read_with(cx, |panel, _| panel.is_branch_mode())
+ .unwrap_or(false);
+ ContextMenu::build(window, cx, move |menu, _, _| {
+ // The check goes at the end so "Uncommitted" lines up with the
+ // submenu trigger, which has no check slot.
+ menu.toggleable_entry(
+ "Uncommitted",
+ !is_branch_mode,
+ IconPosition::End,
+ Some(ShowUncommittedChanges.boxed_clone()),
+ {
+ let panel = panel.clone();
+ move |window, cx| {
+ panel
+ .update(cx, |panel, cx| {
+ panel.enter_uncommitted_mode(window, cx);
+ })
+ .ok();
+ }
+ },
+ )
+ .submenu("Compare Against Base", move |menu, window, cx| {
+ Self::compare_against_base_submenu(menu, panel.clone(), window, cx)
+ })
+ })
+ }
+
+ fn compare_against_base_submenu(
+ menu: ContextMenu,
+ panel: WeakEntity<GitPanel>,
+ window: &mut Window,
+ cx: &mut Context<ContextMenu>,
+ ) -> ContextMenu {
+ let Ok((workspace, repository, selected_branch, menu_handle)) =
+ panel.update(cx, |panel, _| {
+ // The user is choosing the base now, so a waiting request shouldn't.
+ panel.cancel_pending_branch_changes();
+ (
+ panel.workspace.clone(),
+ panel.active_repository.clone(),
+ panel.branch_base.effective(),
+ panel.changes_mode_menu_handle.clone(),
+ )
+ })
+ else {
+ return menu;
+ };
+ let picked = Arc::new(AtomicBool::new(false));
+ let on_select: branch_picker::SelectBranchCallback = Arc::new({
+ let picked = picked.clone();
+ let show_branch_changes_since = Self::on_base_picked(
+ panel,
+ ShowBranchChangesRequest {
+ from_empty_state: false,
+ },
+ );
+ move |branch: Branch, window: &mut Window, cx: &mut App| {
+ picked.store(true, Ordering::Relaxed);
+ show_branch_changes_since(branch, window, cx);
+ }
+ });
+ let branch_list = cx.new(|cx| {
+ branch_picker::select_embedded(
+ workspace,
+ repository,
+ selected_branch,
+ on_select,
+ window,
+ cx,
+ )
+ });
+
+ cx.subscribe_in(
+ &branch_list,
+ window,
+ move |menu, _, _: &DismissEvent, window, cx| {
+ if picked.load(Ordering::Relaxed) {
+ menu_handle.hide(cx);
+ } else {
+ menu.select_submenu_parent(&menu::SelectParent, window, cx);
+ }
+ },
+ )
+ .detach();
+
+ let picker_focus_handle = branch_list.focus_handle(cx);
+ menu.embedded_view(branch_list)
+ .focus_content(picker_focus_handle)
+ }
+
+ pub(super) fn render_no_branch_changes_ui(&self, cx: &Context<Self>) -> AnyElement {
+ let branch_list = self.branch_list().map(|branch_list| branch_list.read(cx));
+ let message: SharedString = if branch_list
+ .is_some_and(|branch_list| branch_list.tree_diff_error().is_some())
+ {
+ "Couldn't load branch changes".into()
+ } else if branch_list.is_some_and(|branch_list| branch_list.statuses_by_path().is_none())
+ || self.branch_base.is_resolving()
+ {
+ // Only the first load for a base shows this, so refreshes after
+ // every status change don't flicker.
+ "Loading branch changes…".into()
+ } else if let Some(base_ref) = self.branch_base.effective() {
+ format!("No changes since {base_ref}").into()
+ } else {
+ "No default branch found. Pick a base branch.".into()
+ };
+
+ h_flex()
+ .px_4()
+ .child(Label::new(message).color(Color::Muted))
+ .into_any_element()
+ }
+
+ pub(super) fn build_branch_context_menu(
+ &self,
+ file_count: usize,
+ target_kind: SelectionTargetKind,
+ has_history: bool,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) -> Entity<ContextMenu> {
+ let is_file_or_bulk = !matches!(target_kind, SelectionTargetKind::Directory);
+ let titles = EntryMenuTitles::new(file_count);
+ ContextMenu::build(window, cx, |context_menu, _, _| {
+ context_menu
+ .context(self.focus_handle.clone())
+ .when(is_file_or_bulk, |context_menu| {
+ context_menu
+ .action("Open Diff", menu::Confirm.boxed_clone())
+ .action(titles.view_file, ViewFile.boxed_clone())
+ .separator()
+ })
+ .action(titles.copy_path, CopyPath.boxed_clone())
+ .action(titles.copy_relative_path, CopyRelativePath.boxed_clone())
+ .when(is_file_or_bulk && has_history, |context_menu| {
+ context_menu
+ .separator()
+ .action(titles.view_file_history, Box::new(git::FileHistory))
+ })
+ })
+ }
+}
+
+fn listed_files(list: &DiffBufferList) -> Option<Vec<GitStatusEntry>> {
+ let statuses = list.statuses_by_path()?;
+ Some(
+ statuses
+ .iter()
+ .map(|status_entry| GitStatusEntry {
+ repo_path: status_entry.repo_path.clone(),
+ status: status_entry.status,
+ staging: status_entry.status.staging(),
+ // Per-file stats against the merge base aren't computed yet.
+ diff_stat: None,
+ })
+ .collect(),
+ )
+}
diff --git a/crates/project/src/git_store.rs b/crates/project/src/git_store.rs
index 798c913951b..1d8bb4ece0b 100644
--- a/crates/project/src/git_store.rs
+++ b/crates/project/src/git_store.rs
@@ -11904,6 +11904,71 @@ mod tests {
});
}
+ #[gpui::test]
+ async fn test_merge_base_list_announces_a_repeated_reload_failure_once(
+ cx: &mut TestAppContext,
+ ) {
+ use diff_buffer_list::{BranchDiffEvent, DiffBase, DiffBufferList};
+ use std::{cell::Cell, rc::Rc};
+ use util::path;
+
+ init_test(cx);
+
+ let project_root = Path::new(path!("/project"));
+ let dot_git = project_root.join(".git");
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(project_root, json!({ ".git": {}, "file.txt": "head\n" }))
+ .await;
+ fs.set_head_and_index_for_repo(&dot_git, &[("file.txt", "head\n".into())]);
+ // A merge base blob that can't be read makes every tree diff fail.
+ fs.with_git_state(&dot_git, false, |state| {
+ state
+ .merge_base_contents
+ .insert(repo_path("file.txt"), Oid::from_bytes(&[1; 20]).unwrap());
+ })
+ .unwrap();
+
+ let project = Project::test(fs.clone(), [project_root], cx).await;
+ project
+ .update(cx, |project, cx| project.git_scans_complete(cx))
+ .await;
+ let git_store = project.read_with(cx, |project, _| project.git_store().clone());
+ let list = cx.new(|cx| {
+ DiffBufferList::new(
+ DiffBase::Merge {
+ base_ref: "origin/main".into(),
+ },
+ git_store,
+ None,
+ cx,
+ )
+ });
+ let file_list_changes = Rc::new(Cell::new(0));
+ cx.update(|cx| {
+ let file_list_changes = file_list_changes.clone();
+ cx.subscribe(&list, move |_, event, _| {
+ if matches!(event, BranchDiffEvent::FileListChanged) {
+ file_list_changes.set(file_list_changes.get() + 1);
+ }
+ })
+ .detach();
+ });
+ cx.run_until_parked();
+ list.read_with(cx, |list, _| assert!(list.tree_diff_error().is_some()));
+ assert_eq!(file_list_changes.get(), 1);
+
+ for index_contents in ["staged\n", "head\n"] {
+ fs.set_index_for_repo(&dot_git, &[("file.txt", index_contents.into())]);
+ cx.run_until_parked();
+ }
+ list.read_with(cx, |list, _| assert!(list.tree_diff_error().is_some()));
+ assert_eq!(
+ file_list_changes.get(),
+ 1,
+ "reloads that fail the same way again must not announce a new file list"
+ );
+ }
+
#[gpui::test]
async fn test_merge_base_status_uses_worktree_contents(cx: &mut TestAppContext) {
use util::{path, rel_path::rel_path};
diff --git a/crates/project/src/git_store/diff_buffer_list.rs b/crates/project/src/git_store/diff_buffer_list.rs
index b338f69a4ce..fb01d814cd3 100644
--- a/crates/project/src/git_store/diff_buffer_list.rs
+++ b/crates/project/src/git_store/diff_buffer_list.rs
@@ -45,6 +45,7 @@ pub struct DiffBufferList {
tree_diff: Option<TreeDiff>,
statuses_by_path: Option<SumTree<StatusEntry>>,
tree_diff_base_task: Option<Task<()>>,
+ tree_diff_error: Option<SharedString>,
_subscription: Subscription,
update_needed: postage::watch::Sender<()>,
_task: Task<()>,
@@ -105,6 +106,7 @@ impl DiffBufferList {
tree_diff: None,
statuses_by_path: None,
tree_diff_base_task: None,
+ tree_diff_error: None,
_subscription: git_store_subscription,
_task: worker,
update_needed: send,
@@ -130,6 +132,7 @@ impl DiffBufferList {
self.tree_diff = None;
self.statuses_by_path = None;
self.tree_diff_base_task = None;
+ self.tree_diff_error = None;
cx.emit(BranchDiffEvent::FileListChanged);
*self.update_needed.borrow_mut() = ();
}
@@ -144,6 +147,7 @@ impl DiffBufferList {
self.tree_diff = None;
self.statuses_by_path = None;
self.tree_diff_base_task = None;
+ self.tree_diff_error = None;
self.diff_base = diff_base;
cx.emit(BranchDiffEvent::DiffBaseChanged);
@@ -230,13 +234,42 @@ impl DiffBufferList {
}
let task = cx.spawn(async move |this, cx| {
- Self::reload_tree_diff(this, cx).await.log_err();
+ let Err(error) = Self::reload_tree_diff(this.clone(), cx).await else {
+ return;
+ };
+ log::error!("failed to load tree diff: {error:#}");
+ let error = SharedString::from(format!("{error:#}"));
+ this.update(cx, |this, cx| {
+ // Reloads retry on every status change. Announcing the same
+ // failure each time would refresh every consumer, including
+ // editor gutters when this is the display diff.
+ if this.tree_diff_error.as_ref() != Some(&error) {
+ this.tree_diff_error = Some(error);
+ cx.emit(BranchDiffEvent::FileListChanged);
+ }
+ })
+ .log_err();
});
self.tree_diff_base_task = Some(task);
cx.notify();
}
+ /// The error from the last failed tree diff reload, such as a base ref
+ /// that no longer exists.
+ pub fn tree_diff_error(&self) -> Option<&SharedString> {
+ self.tree_diff_error.as_ref()
+ }
+
+ /// Whether a merge-base list is still waiting for its first tree diff, so
+ /// `load_buffers` can't list any files yet.
+ pub fn is_awaiting_tree_diff(&self) -> bool {
+ self.diff_base.is_merge_base()
+ && self.repo.is_some()
+ && self.tree_diff.is_none()
+ && self.tree_diff_error.is_none()
+ }
+
pub fn is_tree_base_loading(&self) -> bool {
self.tree_diff_base_task
.as_ref()
@@ -281,6 +314,7 @@ impl DiffBufferList {
this.committed_tree_diff = Some(committed_tree_diff);
this.tree_diff = Some(tree_diff);
this.statuses_by_path = statuses_by_path;
+ this.tree_diff_error = None;
cx.emit(BranchDiffEvent::FileListChanged);
cx.notify();
})