diff --git a/src/git.ts b/src/git.ts index 84b1587..02ecfa1 100644 --- a/src/git.ts +++ b/src/git.ts @@ -51,13 +51,14 @@ export async function createWorktree(branch: string, worktreePath: string, cwd: let result if (exists === "local") { // If the branch is checked out in the main worktree, switch it to main first - const current = await $`git -C ${cwd} rev-parse --abbrev-ref HEAD`.nothrow().quiet().text() - if (current.trim() === branch) { - const main = await mainBranch(cwd) - const sw = await $`git -C ${cwd} checkout ${main}`.nothrow().quiet() - if (sw.exitCode !== 0) { - throw new Error(`Cannot move "${cwd}" off branch "${branch}": ${sw.stderr.toString().trim()}`) + if (await currentBranch(cwd) === branch) { + await checkout(await mainBranch(cwd), cwd) + result = await $`git worktree add ${worktreePath} ${branch}`.cwd(cwd).nothrow().quiet() + if (result.exitCode !== 0) { + await $`git checkout ${branch}`.cwd(cwd).nothrow().quiet() + throw new Error(`Failed to create worktree for "${branch}": ${result.stderr.toString().trim()}`) } + return } result = await $`git worktree add ${worktreePath} ${branch}`.cwd(cwd).nothrow().quiet() } else if (exists === "remote") {