fix: checkout main if branch active in worktree

This commit is contained in:
Chris Wanstrath 2026-03-08 22:49:00 -07:00
parent e8318f68b0
commit c09f7ced5f

View File

@ -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()