Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
git: Implement compare with branch action (#57886)
Alvaro Parker83c52e38785e
diff --git a/crates/git_ui/src/branch_picker.rs b/crates/git_ui/src/branch_picker.rsindex 11e4e2a59d0..6f2276b63fa 100644--- a/crates/git_ui/src/branch_picker.rs+++ b/crates/git_ui/src/branch_picker.rs@@ -122,7 +122,29 @@ pub fn select_popover(})}-pub type SelectBranchCallback = Arc<dyn Fn(Branch, &mut App)>;+pub fn select_modal(+ 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::Modal,+ rems(34.),+ selected_branch,+ on_select,+ window,+ cx,+ );+ list.focus_handle(cx).focus(window, cx);+ list+}++pub type SelectBranchCallback = Arc<dyn Fn(Branch, &mut Window, &mut App)>;pub fn create_embedded(workspace: WeakEntity<Workspace>,@@ -1288,7 +1310,7 @@ impl PickerDelegate for BranchListDelegate {if let BranchSelectionBehavior::Select { on_select, .. } =&self.branch_selection_behavior{- on_select(branch.clone(), cx);+ on_select(branch.clone(), window, cx);cx.emit(DismissEvent);return;}diff --git a/crates/git_ui/src/project_diff.rs b/crates/git_ui/src/project_diff.rsindex 6a729aee442..1129b8f5f59 100644--- a/crates/git_ui/src/project_diff.rs+++ b/crates/git_ui/src/project_diff.rs@@ -66,6 +66,8 @@ actions!(/// Opens a new agent thread with the branch diff for review.ReviewDiff,LeaderAndFollower,+ /// Compare with a specific branch+ CompareWithBranch,]);@@ -98,6 +100,7 @@ impl ProjectDiff {pub(crate) fn register(workspace: &mut Workspace, cx: &mut Context<Workspace>) {workspace.register_action(Self::deploy);workspace.register_action(Self::deploy_branch_diff);+ workspace.register_action(Self::compare_with_branch);workspace.register_action(|workspace, _: &Add, window, cx| {Self::deploy(workspace, &Diff, window, cx);});@@ -121,61 +124,150 @@ impl ProjectDiff {) {telemetry::event!("Git Branch Diff Opened");let project = workspace.project().clone();- let intended_repo = project.read(cx).active_repository(cx);+ let Some(intended_repo) = project.read(cx).active_repository(cx) else {+ let workspace = cx.entity().downgrade();+ window+ .spawn(cx, async |_cx| {+ let result: Result<()> = Err(anyhow!("No active repository"));+ result+ })+ .detach_and_notify_err(workspace, window, cx);+ return;+ };- let existing = workspace- .items_of_type::<Self>(cx)- .find(|item| matches!(item.read(cx).diff_base(cx), DiffBase::Merge { .. }));+ let default_branch = intended_repo.update(cx, |repo, _| repo.default_branch(true));+ let workspace = cx.entity();+ let workspace_weak = workspace.downgrade();+ window+ .spawn(cx, async move |cx| {+ let base_ref = default_branch+ .await??+ .context("Could not determine default branch")?;++ workspace.update_in(cx, |workspace, window, cx| {+ Self::deploy_branch_diff_with_base_ref(+ workspace,+ project,+ intended_repo,+ base_ref,+ window,+ cx,+ );+ })?;++ anyhow::Ok(())+ })+ .detach_and_notify_err(workspace_weak, window, cx);+ }++ fn compare_with_branch(+ workspace: &mut Workspace,+ _: &CompareWithBranch,+ window: &mut Window,+ cx: &mut Context<Workspace>,+ ) {+ let project = workspace.project().clone();+ let Some(repository) = project.read(cx).active_repository(cx) else {+ let workspace = cx.entity().downgrade();+ window+ .spawn(cx, async |_cx| {+ let result: Result<()> = Err(anyhow!("No active repository"));+ result+ })+ .detach_and_notify_err(workspace, window, cx);+ return;+ };+ let selected_branch = workspace.active_item_as::<Self>(cx).and_then(|item| {+ match item.read(cx).diff_base(cx) {+ DiffBase::Merge { base_ref } => Some(base_ref.clone()),+ DiffBase::Head => None,+ }+ });+ let workspace_handle = workspace.weak_handle();+ let on_select = Arc::new({+ let repository = repository.clone();+ let workspace = workspace_handle.clone();+ move |branch: git::repository::Branch, window: &mut Window, cx: &mut App| {+ let base_ref: SharedString = branch.name().to_owned().into();+ workspace+ .update(cx, |workspace, cx| {+ Self::deploy_branch_diff_with_base_ref(+ workspace,+ project.clone(),+ repository.clone(),+ base_ref,+ window,+ cx,+ );+ })+ .ok();+ }+ });++ workspace.toggle_modal(window, cx, |window, cx| {+ branch_picker::select_modal(+ workspace_handle,+ Some(repository),+ selected_branch,+ on_select,+ window,+ cx,+ )+ });+ }++ fn deploy_branch_diff_with_base_ref(+ workspace: &mut Workspace,+ project: Entity<Project>,+ intended_repo: Entity<Repository>,+ base_ref: SharedString,+ window: &mut Window,+ cx: &mut Context<Workspace>,+ ) {+ let existing = workspace.items_of_type::<Self>(cx).find(|item| {+ let item = item.read(cx);+ matches!(+ item.diff_base(cx),+ DiffBase::Merge { base_ref: existing_base_ref } if existing_base_ref == &base_ref+ )+ });if let Some(existing) = existing {workspace.activate_item(&existing, true, true, window, cx);- if let Some(intended_repo) = intended_repo {- let needs_switch = existing- .read(cx)- .branch_diff- .read(cx)- .repo()- .map_or(true, |current| {- current.read(cx).id != intended_repo.read(cx).id- });+ let needs_switch = existing+ .read(cx)+ .branch_diff+ .read(cx)+ .repo()+ .map_or(true, |current| {+ current.read(cx).id != intended_repo.read(cx).id+ });- if needs_switch {- let default_branch =- intended_repo.update(cx, |repo, _| repo.default_branch(true));- let existing = existing.downgrade();- let workspace = cx.entity().downgrade();- window- .spawn(cx, async move |cx| {- let default_branch = default_branch- .await??- .context("Could not determine default branch")?;-- existing.update(cx, |project_diff, cx| {- project_diff.branch_diff.update(cx, |branch_diff, cx| {- branch_diff.set_repo(Some(intended_repo), cx);- branch_diff.set_diff_base(- DiffBase::Merge {- base_ref: default_branch,- },- cx,- );- });- })?;- anyhow::Ok(())- })- .detach_and_notify_err(workspace, window, cx);- }+ if needs_switch {+ existing.update(cx, |project_diff, cx| {+ project_diff.branch_diff.update(cx, |branch_diff, cx| {+ branch_diff.set_repo(Some(intended_repo), 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_default_branch(project, workspace.clone(), window, cx)+ Self::new_with_branch_base(+ project,+ workspace.clone(),+ base_ref,+ intended_repo,+ window,+ cx,+ )})?.await?;workspace@@ -336,6 +428,8 @@ impl ProjectDiff {})}+ #[cfg(test)]+ #[allow(dead_code)]fn new_with_default_branch(project: Entity<Project>,workspace: Entity<Workspace>,@@ -352,14 +446,41 @@ impl ProjectDiff {.context("Could not determine default branch")?;let branch_diff = cx.new_window_entity(|window, cx| {- branch_diff::BranchDiff::new(+ let mut branch_diff = branch_diff::BranchDiff::new(DiffBase::Merge {base_ref: main_branch,},project.clone(),window,cx,- )+ );+ branch_diff.set_repo(Some(repo.clone()), cx);+ branch_diff+ })?;+ cx.new_window_entity(|window, cx| {+ Self::new_impl(branch_diff, project, workspace, window, cx)+ })+ })+ }++ fn new_with_branch_base(+ project: Entity<Project>,+ workspace: Entity<Workspace>,+ base_ref: SharedString,+ repo: Entity<Repository>,+ window: &mut Window,+ cx: &mut App,+ ) -> Task<Result<Entity<Self>>> {+ window.spawn(cx, async move |cx| {+ let branch_diff = cx.new_window_entity(|window, cx| {+ let mut branch_diff = branch_diff::BranchDiff::new(+ DiffBase::Merge { base_ref },+ project.clone(),+ window,+ cx,+ );+ branch_diff.set_repo(Some(repo.clone()), cx);+ branch_diff})?;cx.new_window_entity(|window, cx| {Self::new_impl(branch_diff, project, workspace, window, cx)@@ -1734,8 +1855,10 @@ impl Render for BranchDiffToolbar {PopoverMenu::new("branch-diff-base-branch-picker").menu(move |window, cx| {let project_diff = project_diff_for_picker.clone();- let on_select =- Arc::new(move |branch: git::repository::Branch, cx: &mut App| {+ let on_select = Arc::new(+ move |branch: git::repository::Branch,+ _window: &mut Window,+ cx: &mut App| {let base_ref: SharedString = branch.name().to_owned().into();project_diff.update(cx, |project_diff, cx| {@@ -1747,7 +1870,8 @@ impl Render for BranchDiffToolbar {cx.notify();}).ok();- });+ },+ );Some(branch_picker::select_popover(workspace.clone(),repository.clone(),@@ -2754,6 +2878,78 @@ mod tests {);}+ #[gpui::test]+ async fn test_branch_diff_action_matches_existing_item_by_base_ref(cx: &mut TestAppContext) {+ init_test(cx);++ let fs = FakeFs::new(cx.executor());+ fs.insert_tree(+ path!("/project"),+ json!({+ ".git": {},+ "a.txt": "changed",+ }),+ )+ .await;+ let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;+ let (multi_workspace, cx) =+ 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")));+ };+ ProjectDiff::new_with_branch_base(+ project.clone(),+ workspace.clone(),+ "topic".into(),+ repository,+ window,+ cx,+ )+ })+ .await+ .unwrap();+ workspace.update_in(cx, |workspace, window, cx| {+ workspace.add_item_to_active_pane(+ Box::new(target_branch_diff.clone()),+ None,+ true,+ window,+ cx,+ );+ });+ cx.run_until_parked();++ cx.focus(&workspace);+ cx.update(|window, cx| {+ window.dispatch_action(BranchDiff.boxed_clone(), cx);+ });+ cx.run_until_parked();++ let (active_base_ref, mut base_refs) = workspace.update(cx, |workspace, cx| {+ let active_item = workspace.active_item_as::<ProjectDiff>(cx).unwrap();+ let active_base_ref = match active_item.read(cx).diff_base(cx) {+ DiffBase::Merge { base_ref } => base_ref.to_string(),+ DiffBase::Head => panic!("expected active item to be a branch diff"),+ };+ let base_refs = workspace+ .items_of_type::<ProjectDiff>(cx)+ .filter_map(|item| match item.read(cx).diff_base(cx) {+ DiffBase::Merge { base_ref } => Some(base_ref.to_string()),+ DiffBase::Head => None,+ })+ .collect::<Vec<_>>();+ (active_base_ref, base_refs)+ });+ base_refs.sort();++ assert_eq!(active_base_ref, "origin/main");+ assert_eq!(base_refs, vec!["origin/main", "topic"]);+ }+#[gpui::test]async fn test_update_on_uncommit(cx: &mut TestAppContext) {init_test(cx);