diff --git a/crates/ide-host/tests/vcs_flow.rs b/crates/ide-host/tests/vcs_flow.rs index 2eb393e40..5e34a0f9d 100644 --- a/crates/ide-host/tests/vcs_flow.rs +++ b/crates/ide-host/tests/vcs_flow.rs @@ -207,3 +207,22 @@ async fn change_commit_branch_stash_and_merge_a_conflict() { assert!(f.status().await.is_empty()); assert_eq!(std::fs::read_to_string(&lib_path).unwrap(), resolved); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn checkout_reports_a_branch_held_by_another_worktree() { + let f = Flow::new("rust-app").await; + let linked = f._tmp.path().join("linked"); + git(&f.root, &["worktree", "add", "-q", "-b", "topic", linked.to_str().unwrap()]); + + let outcome = ops::vcs::vcs_checkout(&f.host, WINDOW, None, "topic".into(), false, None).await.unwrap(); + assert_eq!( + outcome, + ide_vcs::CheckoutOutcome::CheckedOutInWorktree { + branch: "topic".into(), + path: dunce::canonicalize(&linked).unwrap() + } + ); + // Nothing changed: the project is still on main. + let branches = ops::vcs::vcs_branches(&f.host, WINDOW, None).await.unwrap(); + assert!(branches.iter().any(|b| b.name == "main" && b.current), "{branches:?}"); +} diff --git a/crates/ide-vcs/src/lib.rs b/crates/ide-vcs/src/lib.rs index 6d903ae73..ff8e61565 100644 --- a/crates/ide-vcs/src/lib.rs +++ b/crates/ide-vcs/src/lib.rs @@ -496,6 +496,9 @@ pub struct CheckoutOptions { /// Required when checking out a remote branch whose local namesake is ahead of it. #[serde(default)] pub diverged: Option, + /// Check the branch out even though another worktree has it checked out. + #[serde(default)] + pub ignore_other_worktrees: bool, } /// Result of [`Repo::checkout_with`]; the non-`Done` variants other than `Conflicts` @@ -522,6 +525,12 @@ pub enum CheckoutOutcome { Conflicts { files: Vec, }, + /// Git refused: `branch` is checked out in the linked worktree at `path`. Nothing + /// changed; the branch can be worked on there. + CheckedOutInWorktree { + branch: String, + path: PathBuf, + }, } /// HEAD before and after a history rewrite, for its Undo. diff --git a/crates/ide-vcs/src/write.rs b/crates/ide-vcs/src/write.rs index a867975fc..1a02ecaf2 100644 --- a/crates/ide-vcs/src/write.rs +++ b/crates/ide-vcs/src/write.rs @@ -765,6 +765,18 @@ fn overwritten_untracked(stderr: &str) -> Option> { listed_files(stderr, "untracked working tree files would be") } +/// The branch git refused to check out or update because another worktree has it, from +/// its error message: a switch says `'' is already used by worktree at ''`, +/// a forced update says `cannot force update the branch '' used by worktree at +/// ''`; git before 2.42 says `'' is already checked out at ''`. +fn branch_of_other_worktree(stderr: &str) -> Option<(String, String)> { + const MARKERS: [&str; 3] = + ["' is already used by worktree at '", "' used by worktree at '", "' is already checked out at '"]; + let (before, path) = stderr.lines().find_map(|l| MARKERS.iter().find_map(|m| l.split_once(m)))?; + let branch = before.rsplit('\'').next()?.to_string(); + Some((branch, path.strip_suffix('\'').unwrap_or(path).to_string())) +} + fn listed_files(stderr: &str, header: &str) -> Option> { let mut lines = stderr.lines().skip_while(|l| !l.contains(header)); lines.next()?; @@ -805,12 +817,18 @@ pub(crate) fn checkout_with( if options.mode == CheckoutMode::Force { args.push("--discard-changes".into()); } + if options.ignore_other_worktrees { + args.push("--ignore-other-worktrees".into()); + } let argv: Vec<&str> = args.iter().map(String::as_str).collect(); let out = cli::run_raw(r.root(), &argv, None)?; if out.code == Some(0) { return Ok(CheckoutOutcome::Done); } let stderr = String::from_utf8_lossy(&out.stderr); + if let Some((branch, path)) = branch_of_other_worktree(&stderr) { + return Ok(CheckoutOutcome::CheckedOutInWorktree { branch, path: path.into() }); + } if let Some(files) = overwritten_untracked(&stderr) { return Ok(CheckoutOutcome::UntrackedFiles { files }); } @@ -893,7 +911,14 @@ pub(crate) fn create_branch( args.extend(["--", name]); } args.extend(start); - run(r.root(), &args, None).map(|_| ()) + let out = cli::run_raw(r.root(), &args, None)?; + if out.code == Some(0) { + return Ok(()); + } + if let Some((branch, path)) = branch_of_other_worktree(&String::from_utf8_lossy(&out.stderr)) { + return Err(IdeError::invalid(format!("branch '{branch}' is already checked out in worktree at '{path}'"))); + } + Err(cli::failure(&args, &out.stderr, &out.stdout, out.code)) } /// Whether `start` is a remote-tracking branch with another name than the new branch @@ -1479,7 +1504,22 @@ fn decode_diff(bytes: &[u8], encoding: TextEncoding) -> String { #[cfg(test)] mod tests { - use super::append_revision; + use super::{append_revision, branch_of_other_worktree}; + + #[test] + fn the_worktree_holding_a_branch_is_read_from_each_git_wording() { + let held = |b: &str, p: &str| Some((b.to_string(), p.to_string())); + assert_eq!( + branch_of_other_worktree("fatal: 'topic' is already used by worktree at '/w/t'\n"), + held("topic", "/w/t") + ); + assert_eq!( + branch_of_other_worktree("fatal: cannot force update the branch 'topic' used by worktree at '/w/t'"), + held("topic", "/w/t") + ); + assert_eq!(branch_of_other_worktree("fatal: 'a/b' is already checked out at '/w/t'"), held("a/b", "/w/t")); + assert_eq!(branch_of_other_worktree("fatal: invalid reference: x"), None); + } #[test] fn a_revision_is_appended_once_keeping_the_list() { diff --git a/crates/ide-vcs/tests/repo.rs b/crates/ide-vcs/tests/repo.rs index 6ecfcc4ae..5cd6e61d3 100644 --- a/crates/ide-vcs/tests/repo.rs +++ b/crates/ide-vcs/tests/repo.rs @@ -1070,7 +1070,7 @@ fn smart_and_force_checkout_with_local_changes_in_the_way() { fx.commit_all("other edit"); fx.git(&["checkout", "-q", "main"]); let repo = fx.repo(); - let opts = |mode| CheckoutOptions { mode, diverged: None }; + let opts = |mode| CheckoutOptions { mode, ..Default::default() }; // A non-conflicting local edit to a file the switch rewrites. fx.write("f.txt", "1\n2\n3\n4\nlocal\n"); @@ -1110,6 +1110,50 @@ fn smart_and_force_checkout_with_local_changes_in_the_way() { assert_eq!(fx.read("untouched.txt"), "new\n", "untracked files survive"); } +#[test] +fn checkout_of_a_branch_held_by_another_worktree_reports_it_and_changes_nothing() { + let fx = Fixture::new(); + fx.write("f.txt", "1\n"); + fx.commit_all("base"); + let linked = fx._tmp.path().join("linked"); + fx.git(&["worktree", "add", "-q", "-b", "topic", linked.to_str().unwrap()]); + let repo = fx.repo(); + let none = CheckoutOptions::default(); + let linked_path = std::fs::canonicalize(&linked).unwrap(); + + // From the main worktree, the branch the linked worktree has checked out. + let outcome = repo.checkout_with("topic", false, &none).unwrap(); + assert_eq!(outcome, CheckoutOutcome::CheckedOutInWorktree { branch: "topic".into(), path: linked_path.clone() }); + assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"), "nothing changed"); + + // With local changes in the way too: reported before any Smart Checkout stash. + fx.write("f.txt", "changed\n"); + let smart = CheckoutOptions { mode: CheckoutMode::Smart, ..Default::default() }; + let outcome = repo.checkout_with("topic", false, &smart).unwrap(); + assert_eq!(outcome, CheckoutOutcome::CheckedOutInWorktree { branch: "topic".into(), path: linked_path.clone() }); + assert_eq!(fx.read("f.txt"), "changed\n", "local changes untouched"); + assert!(repo.stashes().unwrap().is_empty()); + fx.git(&["reset", "-q", "--hard"]); + + // The same refusal from the linked worktree, for the main worktree's branch. + let linked_repo = Repo::discover(&linked).unwrap().unwrap(); + linked_repo.set_execution_allowed(true); + let outcome = linked_repo.checkout_with("main", false, &none).unwrap(); + let main_path = std::fs::canonicalize(&fx.dir).unwrap(); + assert_eq!(outcome, CheckoutOutcome::CheckedOutInWorktree { branch: "main".into(), path: main_path }); + assert_eq!(linked_repo.branch_info().unwrap().head.as_deref(), Some("topic")); + + // Overwriting such a branch (New Branch with Checkout) names the worktree, not raw stderr. + let error = repo.create_branch_with_overwrite("topic", Some("main"), true, true).unwrap_err(); + assert!(error.message.contains("branch 'topic' is already checked out in worktree"), "{error}"); + assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main")); + + // Checkout Anyway: both worktrees then have the branch. + let anyway = CheckoutOptions { ignore_other_worktrees: true, ..Default::default() }; + assert_eq!(repo.checkout_with("topic", false, &anyway).unwrap(), CheckoutOutcome::Done); + assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("topic")); +} + #[test] fn checkout_remote_branch_with_existing_local_namesake() { let (fx, bare) = with_remote(); @@ -1939,7 +1983,7 @@ fn smart_checkout_keeps_staged_changes_staged() { fx.write("f.txt", "1\n2\n3\n4\nlocal\n"); fx.write("s.txt", "staged\n"); fx.git(&["add", "s.txt"]); - let opts = CheckoutOptions { mode: CheckoutMode::Smart, diverged: None }; + let opts = CheckoutOptions { mode: CheckoutMode::Smart, ..Default::default() }; assert_eq!(repo.checkout_with("other", false, &opts).unwrap(), CheckoutOutcome::Done); assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("other")); assert_eq!(fx.read("f.txt"), "1\nother\n3\n4\nlocal\n"); @@ -1960,7 +2004,7 @@ fn checkout_reports_untracked_files_it_would_overwrite() { fx.write("dir/new.txt", "mine\n"); let repo = fx.repo(); for mode in [CheckoutMode::Normal, CheckoutMode::Smart] { - let opts = CheckoutOptions { mode, diverged: None }; + let opts = CheckoutOptions { mode, ..Default::default() }; let outcome = repo.checkout_with("other", false, &opts).unwrap(); assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["dir/new.txt".into()] }); assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main")); diff --git a/src/bindings.ts b/src/bindings.ts index 3b9aaba5e..81a4a2548 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -708,6 +708,8 @@ export const commands = { mode?: CheckoutMode, /** Required when checking out a remote branch whose local namesake is ahead of it. */ diverged?: DivergedLocal | null, + /** Check the branch out even though another worktree has it checked out. */ + ignoreOtherWorktrees?: boolean, } | null) => typedError(__TAURI_INVOKE("vcs_checkout", { repo, branch, create, options })), vcsDeleteBranch: (repo: string | null, branch: string) => typedError(__TAURI_INVOKE("vcs_delete_branch", { repo, branch })), /** "Restore" of the branch-deleted notification. */ @@ -2980,6 +2982,8 @@ export type CheckoutOptions = { mode?: CheckoutMode, /** Required when checking out a remote branch whose local namesake is ahead of it. */ diverged?: DivergedLocal | null, + /** Check the branch out even though another worktree has it checked out. */ + ignoreOtherWorktrees?: boolean, }; /** @@ -2997,7 +3001,12 @@ export type CheckoutOutcome = { kind: "done" } | * Switched, but restoring the local changes (Smart Checkout) or the rebase stopped * on conflicts in these files. */ -{ kind: "conflicts"; files: string[] }; +{ kind: "conflicts"; files: string[] } | +/** + * Git refused: `branch` is checked out in the linked worktree at `path`. Nothing + * changed; the branch can be worked on there. + */ +{ kind: "checkedOutInWorktree"; branch: string; path: string }; export type ChoiceOption = { value: string, diff --git a/src/features/vcs/__tests__/branchOps.test.ts b/src/features/vcs/__tests__/branchOps.test.ts index bfc11c247..9e36e16fa 100644 --- a/src/features/vcs/__tests__/branchOps.test.ts +++ b/src/features/vcs/__tests__/branchOps.test.ts @@ -10,12 +10,23 @@ const mocks = vi.hoisted(() => ({ restoreBranch: vi.fn(), branches: vi.fn(), rename: vi.fn(), + ask: vi.fn(), + checkout: vi.fn(), + executeAction: vi.fn(), })); vi.mock("../dialogs", async (original) => ({ ...(await original()), promptText: mocks.prompt, confirmDialog: mocks.confirm, })); +vi.mock("@/workbench/messages", async (original) => ({ + ...(await original()), + ask: mocks.ask, +})); +vi.mock("@/platform/actions", async (original) => ({ + ...(await original()), + executeAction: mocks.executeAction, +})); vi.mock("@/workbench/contributions", () => ({ notifications: () => ({ notify: mocks.notify, expire: vi.fn() }) })); vi.mock("@/platform/ipc", async (original) => { const real = await original(); @@ -29,10 +40,11 @@ vi.mock("@/platform/ipc", async (original) => { vcsRestoreBranch: mocks.restoreBranch, vcsBranches: mocks.branches, vcsRenameBranch: mocks.rename, + vcsCheckout: mocks.checkout, }, }; }); -import { deleteBranch, deleteBranches, newBranch, newBranchInRepos, renameBranch } from "../branchOps"; +import { checkoutBranch, deleteBranch, deleteBranches, newBranch, newBranchInRepos, renameBranch } from "../branchOps"; import { useVcs } from "../store"; import { useProject } from "@/platform/project"; @@ -175,6 +187,38 @@ it("deletes a worktree holding the branch before deleting it", async () => { expect(mocks.deleteBranch).toHaveBeenCalledWith("/p/front", "feature/wt"); }); +it("offers to open the worktree that has the branch checked out", async () => { + mocks.checkout.mockResolvedValue(ok({ kind: "checkedOutInWorktree", branch: "feature/wt", path: "/p/front-wt" })); + mocks.ask.mockResolvedValue({ button: "open" }); + await checkoutBranch("feature/wt"); + expect(mocks.checkout).toHaveBeenCalledWith("/p/front", "feature/wt", false, { mode: "normal", diverged: null }); + expect(mocks.ask.mock.calls[0]?.[0].title).toBe("Worktree Conflict"); + expect(mocks.ask.mock.calls[0]?.[0].body).toContain("already checked out in a worktree at:\n/p/front-wt"); + expect(mocks.executeAction).toHaveBeenCalledWith("file.openProjectPath", "/p/front-wt"); + expect(mocks.checkout).toHaveBeenCalledTimes(1); +}); + +it("checks the branch out anyway when asked, alongside the other worktree", async () => { + mocks.checkout + .mockResolvedValueOnce(ok({ kind: "checkedOutInWorktree", branch: "feature/wt", path: "/p/front-wt" })) + .mockResolvedValueOnce(ok({ kind: "done" })); + mocks.ask.mockResolvedValue({ button: "anyway" }); + await checkoutBranch("feature/wt"); + expect(mocks.checkout).toHaveBeenLastCalledWith("/p/front", "feature/wt", false, { + mode: "normal", + diverged: null, + ignoreOtherWorktrees: true, + }); + expect(mocks.executeAction).not.toHaveBeenCalled(); +}); + +it("does not open the worktree when the checkout offer is declined", async () => { + mocks.checkout.mockResolvedValue(ok({ kind: "checkedOutInWorktree", branch: "feature/wt", path: "/p/front-wt" })); + mocks.ask.mockResolvedValue({ button: "cancel" }); + await checkoutBranch("feature/wt"); + expect(mocks.executeAction).not.toHaveBeenCalled(); +}); + it("keeps the branch when the worktree question is turned down", async () => { mocks.worktrees.mockResolvedValue(ok([worktree("/p/front-feature-wt", "feature/wt")])); mocks.confirm.mockResolvedValue(false); diff --git a/src/features/vcs/branchOps.ts b/src/features/vcs/branchOps.ts index cc1449b6b..31b2097e9 100644 --- a/src/features/vcs/branchOps.ts +++ b/src/features/vcs/branchOps.ts @@ -132,6 +132,24 @@ async function performCheckout( options = { ...options, diverged: r.button }; continue; } + case "checkedOutInWorktree": { + const { branch, path } = outcome; + const r = await ask({ + title: "Worktree Conflict", + body: tx`Branch '${branch}' is already checked out in a worktree at:\n${path}`, + buttons: [ + { id: "anyway", label: "Checkout Anyway", primary: true }, + { id: "open", label: "Open Existing Worktree" }, + { id: "cancel", label: "Cancel" }, + ], + }); + if (r.button === "anyway") { + options = { ...options, ignoreOtherWorktrees: true }; + continue; + } + if (r.button === "open") await executeAction("file.openProjectPath", path); + return false; + } } } } diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 3686e82fa..aaf695433 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1,4 +1,8 @@ { + "Worktree Conflict": "Worktree Conflict", + "Branch '{branch}' is already checked out in a worktree at:\n{path}": "Branch '{branch}' is already checked out in a worktree at:\n{path}", + "Checkout Anyway": "Checkout Anyway", + "Open Existing Worktree": "Open Existing Worktree", "Favorites": "Favorites", "Add": "Add", "Cancel": "Cancel", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index c25e8e4e4..fae0814c9 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -1,4 +1,8 @@ { + "Worktree Conflict": "工作树冲突", + "Branch '{branch}' is already checked out in a worktree at:\n{path}": "分支 '{branch}' 已在以下位置的工作树中签出:\n{path}", + "Checkout Anyway": "仍然签出", + "Open Existing Worktree": "打开现有工作树", "Favorites": "收藏夹", "Fix ESLint Problems": "修复 ESLint 问题", "No ESLint problems to fix": "没有可修复的 ESLint 问题",