diff --git a/src/git.ts b/src/git.ts index 5aee49f..84b1587 100644 --- a/src/git.ts +++ b/src/git.ts @@ -50,6 +50,15 @@ 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()}`) + } + } result = await $`git worktree add ${worktreePath} ${branch}`.cwd(cwd).nothrow().quiet() } else if (exists === "remote") { result = await $`git worktree add ${worktreePath} -b ${branch} origin/${branch}`.cwd(cwd).nothrow().quiet()