Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
git_ui: Fix history tab empty and detached HEAD states (#57959)
Revantark35ffa8f48083
diff --git a/crates/fs/src/fake_git_repo.rs b/crates/fs/src/fake_git_repo.rsindex ba23efb166b..00e91cb7998 100644--- a/crates/fs/src/fake_git_repo.rs+++ b/crates/fs/src/fake_git_repo.rs@@ -262,7 +262,18 @@ impl GitRepository for FakeGitRepository {fn show(&self, commit: String) -> BoxFuture<'_, Result<CommitDetails>> {self.with_state_async(false, move |state| {- let sha = state.refs.get(&commit).cloned().unwrap_or(commit);+ let sha = match state.refs.get(&commit) {+ Some(sha) => sha.clone(),+ // Real git fails to show an unresolvable revision (e.g. HEAD on an+ // unborn branch), so only fall back to treating the input as a sha.+ None => {+ anyhow::ensure!(+ commit.parse::<Oid>().is_ok(),+ "unable to resolve revision: {commit}"+ );+ commit+ }+ };Ok(CommitDetails {sha: sha.into(),message: "initial commit".into(),diff --git a/crates/git/src/repository.rs b/crates/git/src/repository.rsindex 6c88ee4e688..7bea8283d70 100644--- a/crates/git/src/repository.rs+++ b/crates/git/src/repository.rs@@ -18,6 +18,7 @@ use smallvec::SmallVec;use smol::io::{AsyncBufReadExt, AsyncReadExt, BufReader};use text::LineEnding;+use std::borrow::Cow;use std::collections::HashSet;use std::ffi::{OsStr, OsString};use std::sync::atomic::AtomicBool;@@ -757,20 +758,22 @@ pub enum LogSource {}impl LogSource {- fn get_args(&self) -> Result<Vec<&str>> {+ fn get_args(&self) -> Vec<Cow<'_, str>> {match self {- LogSource::All => Ok(vec![- "--ignore-missing", // needed in case of unborn HEAD- "--branches",- "--remotes",- "--tags",- "HEAD",- ]),- LogSource::Branch(branch) => Ok(vec![branch.as_str()]),- LogSource::Sha(oid) => Ok(vec![- str::from_utf8(oid.as_bytes()).context("Failed to build str from sha")?,- ]),- LogSource::Path(path) => Ok(vec!["--follow", "--", path.as_unix_str()]),+ LogSource::All => vec![+ Cow::Borrowed("--ignore-missing"), // needed in case of unborn HEAD+ Cow::Borrowed("--branches"),+ Cow::Borrowed("--remotes"),+ Cow::Borrowed("--tags"),+ Cow::Borrowed("HEAD"),+ ],+ LogSource::Branch(branch) => vec![Cow::Borrowed(branch.as_str())],+ LogSource::Sha(oid) => vec![Cow::Owned(oid.to_string())],+ LogSource::Path(path) => vec![+ Cow::Borrowed("--follow"),+ Cow::Borrowed("--"),+ Cow::Borrowed(path.as_unix_str()),+ ],}}}@@ -3111,8 +3114,9 @@ impl GitRepository for RealGitRepository {let git = self.git_binary();async move {+ let log_source_args = log_source.get_args();let mut git_log_command = vec!["log", GRAPH_COMMIT_FORMAT, log_order.as_arg()];- git_log_command.extend(log_source.get_args()?);+ git_log_command.extend(log_source_args.iter().map(|arg| arg.as_ref()));let mut command = git.build_command(&git_log_command);command.stdout(Stdio::piped());command.stderr(Stdio::piped());@@ -3182,6 +3186,7 @@ impl GitRepository for RealGitRepository {let git = self.git_binary();async move {+ let log_source_args = log_source.get_args();let mut args = vec!["log", SEARCH_COMMIT_FORMAT];let hash_query = commit_hash_search_query(search_args.query.as_str()).map(|query| query.to_ascii_lowercase());@@ -3197,7 +3202,7 @@ impl GitRepository for RealGitRepository {args.push(search_args.query.as_str());}- args.extend(log_source.get_args()?);+ args.extend(log_source_args.iter().map(|arg| arg.as_ref()));let mut command = git.build_command(&args);command.stdout(Stdio::piped());command.stderr(Stdio::null());@@ -3942,7 +3947,7 @@ mod tests {#[allow(clippy::disallowed_methods)]#[track_caller]- fn git_command<I, S>(working_directory: &Path, arguments: I)+ fn git_command_output<I, S>(working_directory: &Path, arguments: I) -> StringwhereI: IntoIterator<Item = S>,S: AsRef<OsStr>,@@ -3963,6 +3968,19 @@ mod tests {"git command failed: {}",String::from_utf8_lossy(&output.stderr));+ String::from_utf8(output.stdout)+ .expect("git command output was not valid UTF-8")+ .trim()+ .to_string()+ }++ #[track_caller]+ fn git_command<I, S>(working_directory: &Path, arguments: I)+ where+ I: IntoIterator<Item = S>,+ S: AsRef<OsStr>,+ {+ git_command_output(working_directory, arguments);}fn git_init_repo(path: &Path) {@@ -4481,6 +4499,42 @@ mod tests {);}+ #[gpui::test]+ async fn test_initial_graph_data_accepts_sha_log_source(cx: &mut TestAppContext) {+ disable_git_global_config();++ cx.executor().allow_parking();++ let repo_dir = tempfile::tempdir().unwrap();++ git_init_repo(repo_dir.path());+ fs::write(repo_dir.path().join("file"), "initial").unwrap();+ git_command(repo_dir.path(), ["add", "file"]);+ git_command(repo_dir.path(), ["commit", "-m", "Initial commit"]);++ let commit_sha: Oid = git_command_output(repo_dir.path(), ["rev-parse", "HEAD"])+ .parse()+ .unwrap();++ let repo = RealGitRepository::new(+ &repo_dir.path().join(".git"),+ None,+ Some("git".into()),+ cx.executor(),+ )+ .unwrap();++ let (request_tx, request_rx) = async_channel::unbounded();++ repo.initial_graph_data(LogSource::Sha(commit_sha), LogOrder::DateOrder, request_tx)+ .await+ .unwrap();++ let graph_data = request_rx.recv().await.unwrap();+ assert_eq!(graph_data.len(), 1);+ assert_eq!(graph_data[0].sha, commit_sha);+ }+#[gpui::test]async fn test_build_command_untrusted_includes_both_safety_args(cx: &mut TestAppContext) {cx.executor().allow_parking();diff --git a/crates/git_ui/src/git_panel.rs b/crates/git_ui/src/git_panel.rsindex 6c0375fcbfa..781dd31b896 100644--- a/crates/git_ui/src/git_panel.rs+++ b/crates/git_ui/src/git_panel.rs@@ -406,6 +406,31 @@ enum GitPanelTab {History,}+#[derive(Debug, PartialEq, Eq, Clone)]+enum CommitHistory {+ Loading,+ /// A non-empty list can still grow on later fetches.+ /// An empty list means the repository has no commits.+ Loaded(Rc<[CommitHistoryEntry]>),+ Error(SharedString),+}++fn commit_history_from_response(+ entries: Rc<[CommitHistoryEntry]>,+ is_loading: bool,+ error: Option<SharedString>,+) -> CommitHistory {+ if !entries.is_empty() {+ CommitHistory::Loaded(entries)+ } else if let Some(error) = error {+ CommitHistory::Error(error)+ } else if is_loading {+ CommitHistory::Loading+ } else {+ CommitHistory::Loaded(Rc::from([]))+ }+}+#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]enum Section {Conflict,@@ -806,7 +831,7 @@ pub struct GitPanel {stash_entries: GitStash,active_tab: GitPanelTab,commit_history_scroll_handle: UniformListScrollHandle,- commit_history_entries: Option<Rc<[CommitHistoryEntry]>>,+ commit_history: CommitHistory,focused_history_entry: Option<usize>,history_keyboard_nav: bool,_commit_message_buffer_subscription: Option<Subscription>,@@ -824,7 +849,7 @@ struct BulkStaging {anchor: RepoPath,}-#[derive(Clone)]+#[derive(Clone, Debug, PartialEq, Eq)]struct CommitHistoryEntry {sha: Oid,tag_names: Vec<SharedString>,@@ -1108,7 +1133,7 @@ impl GitPanel {stash_entries: Default::default(),active_tab: GitPanelTab::Changes,commit_history_scroll_handle: UniformListScrollHandle::new(),- commit_history_entries: None,+ commit_history: CommitHistory::Loading,focused_history_entry: None,history_keyboard_nav: false,_commit_message_buffer_subscription: None,@@ -4070,13 +4095,20 @@ impl GitPanel {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);- if active_repository_changed && self.amend_pending {- // Leaving a repository with a pending amend: undo it so the amend- // state doesn't carry over to the newly active repository. The- // commit editor still holds the previous repository's buffer here- // (`reopen_commit_buffer` swaps it asynchronously below), so this- // restores the pre-amend draft into that repository's buffer.- self.set_amend_pending(false, cx);+ if active_repository_changed {+ if self.amend_pending {+ // Leaving a repository with a pending amend: undo it so the amend+ // state doesn't carry over to the newly active repository. The+ // commit editor still holds the previous repository's buffer here+ // (`reopen_commit_buffer` swaps it asynchronously below), so this+ // restores the pre-amend draft into that repository's buffer.+ self.set_amend_pending(false, cx);+ }+ self.git_access = None;+ self._repo_subscriptions.clear();+ if self.active_tab == GitPanelTab::History {+ self.set_commit_history(CommitHistory::Loading, cx);+ }}self.active_repository = new_active_repository;self.reopen_commit_buffer(window, cx);@@ -4198,11 +4230,6 @@ impl GitPanel {.as_ref().and_then(|op| self.entry_by_path(&op.anchor));- let active_repository = self.project.read(cx).active_repository(cx);- if active_repository != self.active_repository {- self.active_repository = active_repository;- self.git_access = None;- }self.entries.clear();self.entries_indices.clear();self.single_staged_entry.take();@@ -5705,44 +5732,43 @@ impl GitPanel {fn render_history_tab(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {v_flex().flex_1().size_full().overflow_hidden().map(|this| {let has_repo = self.active_repository.is_some();- let has_commits = self- .commit_history_entries- .as_ref()- .map_or(false, |entries| !entries.is_empty());- let is_loading = self.commit_history_entries.is_none() && has_repo;- if is_loading {- this.child(- h_flex()- .flex_1()- .justify_center()- .child(Label::new("Loading Commit History…").color(Color::Muted)),- )- } else if !has_repo || !has_commits {- this.child(- h_flex()- .flex_1()- .justify_center()- .child(Label::new("No commits yet").color(Color::Muted)),- )- } else {- match self.render_commit_history(window, cx) {- Some(history) => this.child(history),- None => this.child(- h_flex()- .flex_1()- .justify_center()- .child(Label::new("Failed to load commits").color(Color::Muted)),- ),+ match &self.commit_history {+ _ if !has_repo => {+ this.child(Self::render_history_placeholder("No repository found"))}+ CommitHistory::Error(_) => this.child(Self::render_history_placeholder(+ "Failed to load commit history",+ )),+ CommitHistory::Loading => {+ this.child(Self::render_history_placeholder("Loading Commit History…"))+ }+ CommitHistory::Loaded(entries) if entries.is_empty() => {+ this.child(Self::render_history_placeholder("No commits yet"))+ }+ CommitHistory::Loaded(_) => match self.render_commit_history(window, cx) {+ Some(history) => this.child(history),+ None => this.child(Self::render_history_placeholder("Failed to load commits")),+ },}})}+ fn render_history_placeholder(message: &'static str) -> impl IntoElement {+ h_flex()+ .flex_1()+ .justify_center()+ .child(Label::new(message).color(Color::Muted))+ }++ fn commit_history_entries(&self) -> &[CommitHistoryEntry] {+ match &self.commit_history {+ CommitHistory::Loaded(entries) => entries,+ CommitHistory::Loading | CommitHistory::Error(_) => &[],+ }+ }+fn select_next_history_entry(&mut self, cx: &mut Context<Self>) {- let count = self- .commit_history_entries- .as_ref()- .map_or(0, |entries| entries.len());+ let count = self.commit_history_entries().len();if count == 0 {return;}@@ -5758,10 +5784,7 @@ impl GitPanel {}fn select_previous_history_entry(&mut self, cx: &mut Context<Self>) {- let count = self- .commit_history_entries- .as_ref()- .map_or(0, |entries| entries.len());+ let count = self.commit_history_entries().len();if count == 0 {return;}@@ -5780,11 +5803,7 @@ impl GitPanel {let Some(index) = self.focused_history_entry else {return;};- let Some(entry) = self- .commit_history_entries- .as_ref()- .and_then(|entries| entries.get(index))- else {+ let Some(entry) = self.commit_history_entries().get(index) else {return;};let Some(active_repository) = self.active_repository.as_ref() else {@@ -5828,12 +5847,10 @@ impl GitPanel {GitPanelTab::History => {self.focus_handle.focus(window, cx);self.load_commit_history(cx);- self.focused_history_entry = Some(0);}GitPanelTab::Changes => {self.focus_handle.focus(window, cx);- self.commit_history_entries.take();- self.focused_history_entry = None;+ self.set_commit_history(CommitHistory::Loading, cx);self._repo_subscriptions.clear();}}@@ -5845,12 +5862,9 @@ impl GitPanel {return;};- let Some(branch) = active_repository.read(cx).branch.as_ref() else {+ let Some(log_source) = Self::commit_history_log_source(active_repository, cx) else {return;};-- let branch_name = branch.name().to_string();- let log_source = LogSource::Branch(branch_name.into());let log_order = LogOrder::DateOrder;// Kick off the git log fetch so data is ready when the user switches to History.@@ -5861,13 +5875,13 @@ impl GitPanel {}fn load_commit_history(&mut self, cx: &mut Context<Self>) {- let Some(active_repository) = self.active_repository.as_ref() else {+ let Some(active_repository) = self.active_repository.clone() else {return;};if self._repo_subscriptions.is_empty() {self._repo_subscriptions.push(cx.subscribe(- active_repository,+ &active_repository,|this, _repo, event, cx| {if let RepositoryEvent::GraphEvent(_, _) = event {if this.active_tab == GitPanelTab::History {@@ -5877,7 +5891,7 @@ impl GitPanel {},));self._repo_subscriptions- .push(cx.observe(active_repository, |_this, _repo, cx| {+ .push(cx.observe(&active_repository, |_this, _repo, cx| {cx.notify();}));}@@ -5886,26 +5900,53 @@ impl GitPanel {}fn fetch_commit_history_entries(&mut self, cx: &mut Context<Self>) {- let Some(active_repository) = self.active_repository.as_ref() else {+ let Some(active_repository) = self.active_repository.clone() else {return;};- let Some(branch) = active_repository.read(cx).branch.as_ref() else {+ let Some(log_source) = Self::commit_history_log_source(&active_repository, cx) else {+ // No HEAD commit at all (unborn/empty repository).+ self.set_commit_history(CommitHistory::Loaded(Rc::from([])), cx);return;};-- let branch_name = branch.name().to_string();- let log_source = LogSource::Branch(branch_name.into());let log_order = LogOrder::DateOrder;- self.commit_history_entries = Some(active_repository.update(cx, |repository, cx| {+ let (entries, is_loading, error) = active_repository.update(cx, |repository, cx| {let response = repository.graph_data(log_source, log_order, 0..usize::MAX, cx);- response+ let entries: Rc<[CommitHistoryEntry]> = response.commits.iter().map(CommitHistoryEntry::from)- .collect()- }));+ .collect();+ (entries, response.is_loading, response.error)+ });++ self.set_commit_history(commit_history_from_response(entries, is_loading, error), cx);+ }++ fn set_commit_history(&mut self, commit_history: CommitHistory, cx: &mut Context<Self>) {+ let changed = self.commit_history != commit_history;+ self.commit_history = commit_history;+ // Keep the focused entry within range as the history grows or clears.+ let count = self.commit_history_entries().len();+ let focused = self.focused_history_entry.unwrap_or(0);+ self.focused_history_entry = (count > 0).then(|| focused.min(count - 1));+ if changed {+ cx.notify();+ }+ }++ fn commit_history_log_source(+ active_repository: &Entity<Repository>,+ cx: &App,+ ) -> Option<LogSource> {+ let repository = active_repository.read(cx);+ let head_commit = repository.head_commit.as_ref()?;+ if let Some(branch) = repository.branch.as_ref() {+ Some(LogSource::Branch(branch.name().to_string().into()))+ } else {+ Some(LogSource::Sha(head_commit.sha.as_ref().parse().ok()?))+ }}fn git_remote(&self, cx: &mut App) -> Option<GitRemote> {@@ -5925,7 +5966,10 @@ impl GitPanel {window: &mut Window,cx: &mut Context<Self>,) -> Option<impl IntoElement> {- let entries = self.commit_history_entries.clone()?;+ let CommitHistory::Loaded(entries) = &self.commit_history else {+ return None;+ };+ let entries = entries.clone();let active_repository = self.active_repository.as_ref()?;let workspace = self.workspace.clone();let repo_weak = active_repository.downgrade();@@ -8515,6 +8559,47 @@ mod tests {assert_editor_opened_with_path(&workspace, Path::new("src/a/foo.rs"), &mut cx);}+ async fn history_panel_for_project(+ fs: Arc<FakeFs>,+ cx: &mut TestAppContext,+ ) -> Entity<GitPanel> {+ let project = Project::test(fs, [Path::new(path!("/root/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, |mw, _| mw.workspace().clone())+ .unwrap();+ let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);++ cx.read(|cx| {+ project+ .read(cx)+ .worktrees(cx)+ .next()+ .unwrap()+ .read(cx)+ .as_local()+ .unwrap()+ .scan_complete()+ })+ .await;+ cx.executor().run_until_parked();++ let panel = workspace.update_in(cx, GitPanel::new);+ panel.update_in(cx, |panel, window, cx| {+ panel.activate_history_tab(&ActivateHistoryTab, window, cx);+ });+ cx.run_until_parked();+ panel+ }++ async fn wait_for_commit_history_to_settle(panel: &Entity<GitPanel>, cx: &mut TestAppContext) {+ cx.condition(panel, |panel, _| {+ !matches!(panel.commit_history, CommitHistory::Loading)+ })+ .await;+ }+#[test]fn test_format_git_error_toast_message_prefers_raw_rpc_message() {let rpc_error = RpcError::from_proto(@@ -8556,6 +8641,154 @@ mod tests {);}+ #[gpui::test]+ async fn test_history_tab_stops_loading_for_unborn_branch(cx: &mut TestAppContext) {+ init_test(cx);++ let fs = FakeFs::new(cx.background_executor.clone());+ fs.insert_tree("/root", json!({ "project": { ".git": {} } }))+ .await;++ let dot_git = Path::new(path!("/root/project/.git"));+ fs.set_branch_name(dot_git, Some("main"));+ fs.with_git_state(dot_git, false, |state| {+ state.refs.remove("HEAD");+ })+ .unwrap();++ let panel = history_panel_for_project(fs.clone(), cx).await;++ wait_for_commit_history_to_settle(&panel, cx).await;+ panel.read_with(cx, |panel, _| {+ assert_eq!(panel.commit_history, CommitHistory::Loaded(Rc::from([])));+ });+ }++ #[gpui::test]+ async fn test_history_tab_loads_detached_head(cx: &mut TestAppContext) {+ init_test(cx);++ let fs = FakeFs::new(cx.background_executor.clone());+ fs.insert_tree("/root", json!({ "project": { ".git": {} } }))+ .await;++ let dot_git = Path::new(path!("/root/project/.git"));+ let sha: Oid = "0123456789012345678901234567890123456789".parse().unwrap();+ fs.with_git_state(dot_git, false, |state| {+ state.current_branch_name = None;+ state.refs.insert("HEAD".into(), sha.to_string());+ state.graph_commits = vec![Arc::new(git::repository::InitialGraphCommitData {+ sha,+ parents: SmallVec::new(),+ ref_names: Vec::new(),+ })];+ })+ .unwrap();++ let panel = history_panel_for_project(fs.clone(), cx).await;++ wait_for_commit_history_to_settle(&panel, cx).await;+ panel.read_with(cx, |panel, _| {+ assert_eq!(+ panel.commit_history,+ CommitHistory::Loaded(Rc::from([CommitHistoryEntry {+ sha,+ tag_names: Vec::new(),+ }]))+ );+ });+ }++ #[gpui::test]+ async fn test_history_tab_surfaces_load_error(cx: &mut TestAppContext) {+ init_test(cx);++ let fs = FakeFs::new(cx.background_executor.clone());+ fs.insert_tree("/root", json!({ "project": { ".git": {} } }))+ .await;++ let dot_git = Path::new(path!("/root/project/.git"));+ let sha: Oid = "0123456789012345678901234567890123456789".parse().unwrap();+ fs.with_git_state(dot_git, false, |state| {+ state.current_branch_name = None;+ state.refs.insert("HEAD".into(), sha.to_string());+ state.graph_commits = vec![Arc::new(git::repository::InitialGraphCommitData {+ sha,+ parents: SmallVec::new(),+ ref_names: Vec::new(),+ })];+ })+ .unwrap();+ fs.set_graph_error(dot_git, Some("simulated git log failure".into()));++ let panel = history_panel_for_project(fs.clone(), cx).await;++ wait_for_commit_history_to_settle(&panel, cx).await;+ panel.read_with(cx, |panel, _| {+ assert!(matches!(panel.commit_history, CommitHistory::Error(_)));+ });+ }++ #[gpui::test]+ async fn test_history_tab_without_repository(cx: &mut TestAppContext) {+ init_test(cx);++ let fs = FakeFs::new(cx.background_executor.clone());+ fs.insert_tree("/root", json!({ "project": {} })).await;++ let panel = history_panel_for_project(fs.clone(), cx).await;++ panel.read_with(cx, |panel, _| {+ assert_eq!(panel.commit_history, CommitHistory::Loading);+ });+ }++ #[test]+ fn test_commit_history_from_response() {+ let sha: Oid = "0123456789012345678901234567890123456789".parse().unwrap();+ let error = SharedString::from("git log failed");+ let entries: Rc<[CommitHistoryEntry]> = Rc::from([CommitHistoryEntry {+ sha,+ tag_names: Vec::new(),+ }]);+ let no_entries: Rc<[CommitHistoryEntry]> = Rc::from([]);++ // Commits win even while the fetch task still reports `is_loading`.+ assert_eq!(+ commit_history_from_response(entries.clone(), true, None),+ CommitHistory::Loaded(entries.clone())+ );+ assert_eq!(+ commit_history_from_response(entries.clone(), false, None),+ CommitHistory::Loaded(entries.clone())+ );+ // Commits also take precedence over a concurrently reported error.+ assert_eq!(+ commit_history_from_response(entries.clone(), true, Some(error.clone())),+ CommitHistory::Loaded(entries)+ );++ // With no commits a terminal error beats the loading state.+ assert_eq!(+ commit_history_from_response(no_entries.clone(), true, Some(error.clone())),+ CommitHistory::Error(error.clone())+ );+ assert_eq!(+ commit_history_from_response(no_entries.clone(), false, Some(error.clone())),+ CommitHistory::Error(error)+ );++ // When no commits and no error, loading vs. finished-empty hinges on `is_loading`.+ assert_eq!(+ commit_history_from_response(no_entries.clone(), true, None),+ CommitHistory::Loading+ );+ assert_eq!(+ commit_history_from_response(no_entries.clone(), false, None),+ CommitHistory::Loaded(no_entries)+ );+ }+#[gpui::test]async fn test_entry_worktree_paths(cx: &mut TestAppContext) {init_test(cx);