Prevent worktree creation on main branch

This commit is contained in:
Chris Wanstrath 2026-03-08 23:26:31 -07:00
parent 1f1b3f2a0d
commit 4b8f5a61a1

View File

@ -51,12 +51,16 @@ export async function createWorktree(branch: string, worktreePath: string, cwd:
let result
let switchedFromBranch = false
if (exists === "local") {
const main = await mainBranch(cwd)
if (branch === main) {
throw new Error(`Cannot create a worktree for the main branch "${main}".`)
}
// If the branch is checked out in the main worktree, switch it to main first
if (await currentBranch(cwd) === branch) {
if (await isDirty(cwd)) {
throw new Error(`Cannot move branch "${branch}" to a worktree: the main worktree has uncommitted changes. Commit or stash them first.`)
}
await checkout(await mainBranch(cwd), cwd)
await checkout(main, cwd)
switchedFromBranch = true
}
result = await $`git worktree add ${worktreePath} ${branch}`.cwd(cwd).nothrow().quiet()