Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
git: Recover branch refs when metadata lookup fails (#57285)
Mikhail Pertsev786eb245214f
diff --git a/crates/collab/src/db/queries/projects.rs b/crates/collab/src/db/queries/projects.rsindex 5afcd69db0f..cae1f238b1d 100644--- a/crates/collab/src/db/queries/projects.rs+++ b/crates/collab/src/db/queries/projects.rs@@ -891,6 +891,7 @@ impl Database {branch_summary,head_commit_details,branch_list: Vec::new(),+ branch_list_error: None,scan_id: db_repository_entry.scan_id as u64,is_last_update: true,merge_message: db_repository_entry.merge_message,diff --git a/crates/collab/src/db/queries/rooms.rs b/crates/collab/src/db/queries/rooms.rsindex b86a0a4206a..6e43b34507f 100644--- a/crates/collab/src/db/queries/rooms.rs+++ b/crates/collab/src/db/queries/rooms.rs@@ -791,6 +791,7 @@ impl Database {branch_summary,head_commit_details,branch_list: Vec::new(),+ branch_list_error: None,project_id: project_id.to_proto(),id: db_repository.id as u64,abs_path: db_repository.abs_path.clone(),diff --git a/crates/collab/tests/integration/integration_tests.rs b/crates/collab/tests/integration/integration_tests.rsindex b18a70d242c..dcdb346be82 100644--- a/crates/collab/tests/integration/integration_tests.rs+++ b/crates/collab/tests/integration/integration_tests.rs@@ -7142,6 +7142,7 @@ async fn test_remote_git_branches(let new_branch = branches[2];let branches_b = branches_b+ .branches.into_iter().map(|branch| branch.name().to_string()).collect::<HashSet<_>>();diff --git a/crates/collab/tests/integration/remote_editing_collaboration_tests.rs b/crates/collab/tests/integration/remote_editing_collaboration_tests.rsindex d478402a9d6..df4a219597c 100644--- a/crates/collab/tests/integration/remote_editing_collaboration_tests.rs+++ b/crates/collab/tests/integration/remote_editing_collaboration_tests.rs@@ -300,6 +300,7 @@ async fn test_ssh_collaboration_git_branches(let new_branch = branches[2];let branches_b = branches_b+ .branches.into_iter().map(|branch| branch.name().to_string()).collect::<HashSet<_>>();diff --git a/crates/fs/src/fake_git_repo.rs b/crates/fs/src/fake_git_repo.rsindex 13daed845c5..fc7f7357dca 100644--- a/crates/fs/src/fake_git_repo.rs+++ b/crates/fs/src/fake_git_repo.rs@@ -493,7 +493,7 @@ impl GitRepository for FakeGitRepository {self.with_state_async(false, |state| Ok(state.stash_entries.clone()))}- fn branches(&self) -> BoxFuture<'_, Result<Vec<Branch>>> {+ fn branches(&self) -> BoxFuture<'_, Result<git::repository::BranchesScanResult>> {self.with_state_async(false, move |state| {let current_branch = &state.current_branch_name;let mut branches = state@@ -518,7 +518,7 @@ impl GitRepository for FakeGitRepository {// compute snapshot expects these to be sorted by ref_name// because that's what git itself doesbranches.sort_by(|a, b| a.ref_name.cmp(&b.ref_name));- Ok(branches)+ Ok(branches.into())})}diff --git a/crates/git/src/repository.rs b/crates/git/src/repository.rsindex 320fe2e5bf5..348d0d49c79 100644--- a/crates/git/src/repository.rs+++ b/crates/git/src/repository.rs@@ -23,7 +23,7 @@ use std::collections::HashSet;use std::ffi::{OsStr, OsString};use std::sync::atomic::AtomicBool;-use std::process::ExitStatus;+use std::process::{ExitStatus, Output};use std::str::FromStr;use std::{cmp::Ordering,@@ -218,6 +218,21 @@ pub struct Branch {pub most_recent_commit: Option<CommitSummary>,}+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct BranchesScanResult {+ pub branches: Vec<Branch>,+ pub error: Option<SharedString>,+}++impl From<Vec<Branch>> for BranchesScanResult {+ fn from(branches: Vec<Branch>) -> Self {+ Self {+ branches,+ error: None,+ }+ }+}+impl Branch {pub fn name(&self) -> &str {self.ref_name@@ -794,7 +809,7 @@ pub trait GitRepository: Send + Sync {fn stash_entries(&self) -> BoxFuture<'_, Result<GitStash>>;- fn branches(&self) -> BoxFuture<'_, Result<Vec<Branch>>>;+ fn branches(&self) -> BoxFuture<'_, Result<BranchesScanResult>>;fn change_branch(&self, name: String) -> BoxFuture<'_, Result<()>>;fn create_branch(&self, name: String, base_branch: Option<String>)@@ -1792,7 +1807,7 @@ impl GitRepository for RealGitRepository {.boxed()}- fn branches(&self) -> BoxFuture<'_, Result<Vec<Branch>>> {+ fn branches(&self) -> BoxFuture<'_, Result<BranchesScanResult>> {let git = self.git_binary();self.executor.spawn(async move {@@ -1817,14 +1832,15 @@ impl GitRepository for RealGitRepository {];let output = git.build_command(&args).output().await?;- anyhow::ensure!(- output.status.success(),- "Failed to git git branches:\n{}",- String::from_utf8_lossy(&output.stderr)- );+ let error = if output.status.success() {+ None+ } else {+ let error = format_branch_scan_error(&output);+ log::warn!("failed to get git branches with commit metadata: {error}");+ Some(error.into())+ };let input = String::from_utf8_lossy(&output.stdout);-let mut branches = parse_branch_input(&input)?;if branches.is_empty() {let args = vec!["symbolic-ref", "--quiet", "HEAD"];@@ -1845,7 +1861,7 @@ impl GitRepository for RealGitRepository {}}- Ok(branches)+ Ok(BranchesScanResult { branches, error })}).boxed()}@@ -3647,6 +3663,17 @@ fn parse_branch_input(input: &str) -> Result<Vec<Branch>> {Ok(branches)}+fn format_branch_scan_error(output: &Output) -> String {+ let stderr = String::from_utf8_lossy(&output.stderr)+ .trim()+ .replace('\n', " ");+ if stderr.is_empty() {+ format!("git for-each-ref exited with {}", output.status)+ } else {+ stderr+ }+}+fn parse_upstream_track(upstream_track: &str) -> Result<UpstreamTracking> {if upstream_track.is_empty() {return Ok(UpstreamTracking::Tracked(UpstreamTrackingStatus {@@ -3926,7 +3953,7 @@ mod tests {let checkpoint = repo.checkpoint().await.unwrap();// Ensure the user can't see any branches after creating a checkpoint.- assert_eq!(repo.branches().await.unwrap().len(), 1);+ assert_eq!(repo.branches().await.unwrap().branches.len(), 1);smol::fs::write(&file_path, "modified after checkpoint").await@@ -3996,7 +4023,7 @@ mod tests {let checkpoint_sha = repo.checkpoint().await.unwrap();// Ensure the user can't see any branches after creating a checkpoint.- assert_eq!(repo.branches().await.unwrap().len(), 1);+ assert_eq!(repo.branches().await.unwrap().branches.len(), 1);smol::fs::write(repo_dir.path().join("foo"), "bar").await@@ -4020,6 +4047,64 @@ mod tests {// );}+ #[gpui::test]+ async fn test_branches_return_head_when_commit_metadata_cannot_be_read(+ cx: &mut TestAppContext,+ ) {+ disable_git_global_config();++ cx.executor().allow_parking();++ let repo_dir = tempfile::tempdir().unwrap();+ git2::Repository::init(repo_dir.path()).unwrap();+ let repo = RealGitRepository::new(+ &repo_dir.path().join(".git"),+ None,+ Some("git".into()),+ cx.executor(),+ )+ .unwrap();++ smol::fs::write(repo_dir.path().join("file.txt"), "content")+ .await+ .unwrap();+ repo.stage_paths(vec![repo_path("file.txt")], Arc::new(HashMap::default()))+ .await+ .unwrap();+ repo.commit(+ "Initial commit".into(),+ None,+ CommitOptions::default(),+ AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),+ Arc::new(checkpoint_author_envs()),+ )+ .await+ .unwrap();++ smol::fs::write(+ repo_dir.path().join(".git").join("refs/heads/broken"),+ "0a103ede22f159c792dc6405e0c8304d9bd4dc29\n",+ )+ .await+ .unwrap();++ let branches_scan = repo.branches().await.unwrap();+ assert!(branches_scan.error.is_some());+ let head_branch = branches_scan+ .branches+ .iter()+ .find(|branch| branch.is_head)+ .expect("branch list should include HEAD");+ assert!(head_branch.ref_name.starts_with("refs/heads/"));++ assert!(+ branches_scan+ .branches+ .iter()+ .all(|branch| branch.ref_name.as_ref() != "refs/heads/broken")+ );+ }+#[gpui::test]async fn test_compare_checkpoints(cx: &mut TestAppContext) {disable_git_global_config();diff --git a/crates/git_ui/src/branch_picker.rs b/crates/git_ui/src/branch_picker.rsindex 63c9bd59b16..11e4e2a59d0 100644--- a/crates/git_ui/src/branch_picker.rs+++ b/crates/git_ui/src/branch_picker.rs@@ -16,7 +16,10 @@ use project::project_settings::ProjectSettings;use settings::Settings;use std::sync::Arc;use time::OffsetDateTime;-use ui::{Divider, HighlightedLabel, KeyBinding, ListItem, ListItemSpacing, Tooltip, prelude::*};+use ui::{+ Banner, Divider, HighlightedLabel, KeyBinding, ListItem, ListItemSpacing, Severity, Tooltip,+ prelude::*,+};use ui_input::ErasedEditor;use util::ResultExt;use workspace::notifications::DetachAndPromptErr;@@ -233,6 +236,9 @@ impl BranchList {)}).unwrap_or_default();+ let branch_list_error = repository+ .as_ref()+ .and_then(|repo| repo.read(cx).branch_list_error.clone());let default_branch_request = repository.clone().map(|repository| {repository.update(cx, |repository, _| repository.default_branch(false))@@ -246,6 +252,7 @@ impl BranchList {cx,);delegate.all_branches = all_branches;+ delegate.branch_list_error = branch_list_error;let picker = cx.new(|cx| {Picker::uniform_list(delegate, window, cx)@@ -267,7 +274,9 @@ impl BranchList {window,move |this, repo, event, window, cx| {if matches!(event, RepositoryEvent::BranchListChanged) {- let branch_list = repo.read(cx).branch_list.clone();+ let snapshot = repo.read(cx);+ let branch_list = snapshot.branch_list.clone();+ let branch_list_error = snapshot.branch_list_error.clone();this.picker.update(cx, |picker, cx| {picker.delegate.restore_selected_branch = picker.delegate@@ -278,6 +287,7 @@ impl BranchList {&branch_list,picker.delegate.branch_selection_behavior.selected_branch(),);+ picker.delegate.branch_list_error = branch_list_error;picker.refresh(window, cx);});}@@ -497,6 +507,7 @@ pub struct BranchListDelegate {workspace: WeakEntity<Workspace>,matches: Vec<Entry>,all_branches: Vec<Branch>,+ branch_list_error: Option<SharedString>,default_branch: Option<SharedString>,repo: Option<Entity<Repository>>,style: BranchListStyle,@@ -815,6 +826,7 @@ impl BranchListDelegate {repo,style,all_branches: Vec::new(),+ branch_list_error: None,default_branch: None,selected_index: 0,last_query: Default::default(),@@ -1046,6 +1058,23 @@ impl PickerDelegate for BranchListDelegate {self.editor_position() == PickerEditorPosition::End,|this| this.child(Divider::horizontal()),)+ .when_some(self.branch_list_error.clone(), |this, error| {+ let message = format!("Some branches could not be loaded: {error}");+ this.child(+ div()+ .id("branch-list-error")+ .p_1p5()+ .child(+ Banner::new().severity(Severity::Warning).child(+ Label::new(message.clone())+ .size(LabelSize::Small)+ .single_line()+ .truncate(),+ ),+ )+ .tooltip(Tooltip::text(message)),+ )+ }).child(h_flex().overflow_hidden()@@ -2191,7 +2220,8 @@ mod tests {}).await.unwrap()- .unwrap();+ .unwrap()+ .branches;let repo_branches = repo_branches.iter().map(|b| b.name())@@ -2276,7 +2306,8 @@ mod tests {}).await.unwrap()- .unwrap();+ .unwrap()+ .branches;assert!(repo_branches.iter()@@ -2355,7 +2386,8 @@ mod tests {}).await.unwrap()- .unwrap();+ .unwrap()+ .branches;assert!(repo_branches.iter()@@ -2436,7 +2468,8 @@ mod tests {}).await.unwrap()- .unwrap();+ .unwrap()+ .branches;assert!(repo_branches.iter()@@ -2514,7 +2547,8 @@ mod tests {}).await.unwrap()- .unwrap();+ .unwrap()+ .branches;let repo_branches = repo_branches.iter().map(|b| b.name())@@ -2698,7 +2732,8 @@ mod tests {}).await.unwrap()- .unwrap();+ .unwrap()+ .branches;let new_branch = branches.into_iter()diff --git a/crates/project/src/git_store.rs b/crates/project/src/git_store.rsindex ad5174ec365..4e927978497 100644--- a/crates/project/src/git_store.rs+++ b/crates/project/src/git_store.rs@@ -34,11 +34,11 @@ use git::{blame::Blame,parse_git_remote_url,repository::{- Branch, CommitData, CommitDetails, CommitDiff, CommitFile, CommitOptions,- CreateWorktreeTarget, DiffType, FetchOptions, GitCommitTemplate, GitRepository,- GitRepositoryCheckpoint, InitialGraphCommitData, LogOrder, LogSource, PushOptions, Remote,- RemoteCommandOutput, RepoPath, ResetMode, SearchCommitArgs, UpstreamTrackingStatus,- Worktree as GitWorktree, delete_branch_flag,+ Branch, BranchesScanResult, CommitData, CommitDetails, CommitDiff, CommitFile,+ CommitOptions, CreateWorktreeTarget, DiffType, FetchOptions, GitCommitTemplate,+ GitRepository, GitRepositoryCheckpoint, InitialGraphCommitData, LogOrder, LogSource,+ PushOptions, Remote, RemoteCommandOutput, RepoPath, ResetMode, SearchCommitArgs,+ UpstreamTrackingStatus, Worktree as GitWorktree, delete_branch_flag,},stash::{GitStash, StashEntry},status::{@@ -317,6 +317,7 @@ pub struct RepositorySnapshot {pub path_style: PathStyle,pub branch: Option<Branch>,pub branch_list: Arc<[Branch]>,+ pub branch_list_error: Option<SharedString>,pub head_commit: Option<CommitDetails>,pub scan_id: u64,pub merge: MergeDetails,@@ -2877,15 +2878,17 @@ impl GitStore {let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;- let branches = repository_handle+ let branches_scan = repository_handle.update(&mut cx, |repository_handle, _| repository_handle.branches()).await??;Ok(proto::GitBranchesResponse {- branches: branches+ branches: branches_scan+ .branches.into_iter().map(|branch| branch_to_proto(&branch)).collect::<Vec<_>>(),+ error: branches_scan.error.map(|error| error.to_string()),})}async fn handle_get_default_branch(@@ -4120,6 +4123,7 @@ impl RepositorySnapshot {work_directory_abs_path,branch: None,branch_list: Arc::from([]),+ branch_list_error: None,head_commit: None,scan_id: 0,merge: Default::default(),@@ -4135,6 +4139,10 @@ impl RepositorySnapshot {proto::UpdateRepository {branch_summary: self.branch.as_ref().map(branch_to_proto),branch_list: self.branch_list.iter().map(branch_to_proto).collect(),+ branch_list_error: self+ .branch_list_error+ .as_ref()+ .map(|error| error.to_string()),head_commit_details: self.head_commit.as_ref().map(commit_details_to_proto),updated_statuses: self.statuses_by_path@@ -4222,6 +4230,10 @@ impl RepositorySnapshot {proto::UpdateRepository {branch_summary: self.branch.as_ref().map(branch_to_proto),branch_list: self.branch_list.iter().map(branch_to_proto).collect(),+ branch_list_error: self+ .branch_list_error+ .as_ref()+ .map(|error| error.to_string()),head_commit_details: self.head_commit.as_ref().map(commit_details_to_proto),updated_statuses,removed_statuses,@@ -6516,12 +6528,23 @@ impl Repository {.await;// TODO would be nice to not have to do this manuallyif result.is_ok() {- let branches = backend.branches().await?;- let branch = branches.into_iter().find(|branch| branch.is_head);+ let branches_scan = backend.branches().await?;+ let branch_list_error = branches_scan.error;+ let branch_list: Arc<[Branch]> = branches_scan.branches.into();+ let branch = branch_list.iter().find(|branch| branch.is_head).cloned();log::info!("head branch after scan is {branch:?}");let snapshot = this.update(&mut cx, |this, cx| {+ let branch_list_changed =+ *branch_list != *this.snapshot.branch_list;+ let branch_list_error_changed =+ this.snapshot.branch_list_error != branch_list_error;this.snapshot.branch = branch;+ this.snapshot.branch_list = branch_list;+ this.snapshot.branch_list_error = branch_list_error;cx.emit(RepositoryEvent::HeadChanged);+ if branch_list_changed || branch_list_error_changed {+ cx.emit(RepositoryEvent::BranchListChanged);+ }this.snapshot.clone()})?;if let Some(updates_tx) = updates_tx {@@ -6820,7 +6843,7 @@ impl Repository {})}- pub fn branches(&mut self) -> oneshot::Receiver<Result<Vec<Branch>>> {+ pub fn branches(&mut self) -> oneshot::Receiver<Result<BranchesScanResult>> {let id = self.id;self.send_job("branches", None, move |repo, _| async move {match repo {@@ -6841,7 +6864,10 @@ impl Repository {.map(|branch| proto_to_branch(&branch)).collect();- Ok(branches)+ Ok(BranchesScanResult {+ branches,+ error: response.error.map(SharedString::from),+ })}}})@@ -7608,10 +7634,14 @@ impl Repository {if update.is_last_update {let new_branch_list: Arc<[Branch]> =update.branch_list.iter().map(proto_to_branch).collect();- if *self.snapshot.branch_list != *new_branch_list {+ let new_branch_list_error = update.branch_list_error.map(SharedString::from);+ if *self.snapshot.branch_list != *new_branch_list+ || self.snapshot.branch_list_error != new_branch_list_error+ {cx.emit(RepositoryEvent::BranchListChanged);}self.snapshot.branch_list = new_branch_list;+ self.snapshot.branch_list_error = new_branch_list_error;}// We don't store any merge head state for downstream projects; the upstream@@ -9164,7 +9194,7 @@ async fn compute_snapshot(})}};- let (branches, head_commit, all_worktrees) = cx+ let (branches_scan, head_commit, all_worktrees) = cx.background_spawn({let backend = backend.clone();async move {@@ -9178,8 +9208,13 @@ async fn compute_snapshot(}).await?;log::debug!("fetched branches, head commit, worktrees");- let branch = branches.iter().find(|branch| branch.is_head).cloned();- let branch_list: Arc<[Branch]> = branches.into();+ let branch_list_error = branches_scan.error;+ let branch = branches_scan+ .branches+ .iter()+ .find(|branch| branch.is_head)+ .cloned();+ let branch_list: Arc<[Branch]> = branches_scan.branches.into();let linked_worktrees: Arc<[GitWorktree]> = all_worktrees.into_iter()@@ -9207,6 +9242,7 @@ async fn compute_snapshot(let head_changed =branch != this.snapshot.branch || head_commit != this.snapshot.head_commit;let branch_list_changed = *branch_list != *this.snapshot.branch_list;+ let branch_list_error_changed = branch_list_error != this.snapshot.branch_list_error;let worktrees_changed = *linked_worktrees != *this.snapshot.linked_worktrees;this.snapshot = RepositorySnapshot {@@ -9214,6 +9250,7 @@ async fn compute_snapshot(work_directory_abs_path,branch,branch_list: branch_list.clone(),+ branch_list_error,head_commit,remote_origin_url,remote_upstream_url,@@ -9226,7 +9263,7 @@ async fn compute_snapshot(cx.emit(RepositoryEvent::HeadChanged);}- if branch_list_changed {+ if branch_list_changed || branch_list_error_changed {cx.emit(RepositoryEvent::BranchListChanged);}diff --git a/crates/proto/proto/git.proto b/crates/proto/proto/git.protoindex 8c7d09eb4b0..ac7e39a83d9 100644--- a/crates/proto/proto/git.proto+++ b/crates/proto/proto/git.proto@@ -6,6 +6,7 @@ import "worktree.proto";message GitBranchesResponse {repeated Branch branches = 1;+ optional string error = 2;}message UpdateDiffBases {@@ -130,6 +131,7 @@ message UpdateRepository {repeated Branch branch_list = 18;optional string repository_dir_abs_path = 19;optional string common_dir_abs_path = 20;+ optional string branch_list_error = 21;}message RemoveRepository {diff --git a/crates/proto/src/proto.rs b/crates/proto/src/proto.rsindex 49b9db0d5c3..044415dbfda 100644--- a/crates/proto/src/proto.rs+++ b/crates/proto/src/proto.rs@@ -926,6 +926,7 @@ pub fn split_repository_update(let mut updated_statuses_iter = mem::take(&mut update.updated_statuses).into_iter().fuse();let mut removed_statuses_iter = mem::take(&mut update.removed_statuses).into_iter().fuse();let branch_list = mem::take(&mut update.branch_list);+ let branch_list_error = update.branch_list_error.take();std::iter::from_fn({let update = update.clone();move || {@@ -944,6 +945,7 @@ pub fn split_repository_update(updated_statuses,removed_statuses,branch_list: Vec::new(),+ branch_list_error: None,is_last_update: false,..update.clone()})@@ -953,6 +955,7 @@ pub fn split_repository_update(updated_statuses: Vec::new(),removed_statuses: Vec::new(),branch_list,+ branch_list_error,is_last_update: true,..update}])@@ -1023,6 +1026,7 @@ mod tests {ref_name: "refs/heads/main".into(),..Default::default()}],+ branch_list_error: Some("partial branch scan".into()),..Default::default()};@@ -1033,6 +1037,12 @@ mod tests {assert!(chunks[1].branch_list.is_empty());assert_eq!(chunks[2].branch_list.len(), 1);assert_eq!(chunks[2].branch_list[0].ref_name, "refs/heads/main");+ assert_eq!(chunks[0].branch_list_error, None);+ assert_eq!(chunks[1].branch_list_error, None);+ assert_eq!(+ chunks[2].branch_list_error.as_deref(),+ Some("partial branch scan")+ );assert!(!chunks[0].is_last_update);assert!(!chunks[1].is_last_update);assert!(chunks[2].is_last_update);diff --git a/crates/remote_server/src/remote_editing_tests.rs b/crates/remote_server/src/remote_editing_tests.rsindex ff604da9de7..a91be89be0b 100644--- a/crates/remote_server/src/remote_editing_tests.rs+++ b/crates/remote_server/src/remote_editing_tests.rs@@ -2121,7 +2121,8 @@ async fn test_remote_git_branches(cx: &mut TestAppContext, server_cx: &mut TestA.update(cx, |repository, _| repository.branches()).await.unwrap()- .unwrap();+ .unwrap()+ .branches;let new_branch = branches[2];