fix: Handle existing branch in worktree creation
When re-dispatching tasks, the branch from a previous run may still exist. Instead of failing with "a branch named X already exists", reset the existing branch to the base and check it out.
This commit is contained in:
@@ -61,16 +61,16 @@ export class SimpleGitWorktreeManager implements WorktreeManager {
|
||||
const worktreePath = path.join(this.worktreesDir, id);
|
||||
log.info({ id, branch, baseBranch }, 'creating worktree');
|
||||
|
||||
// Create worktree with new branch
|
||||
// Create worktree — reuse existing branch or create new one
|
||||
const branchExists = await this.branchExists(branch);
|
||||
if (branchExists) {
|
||||
// Branch exists from a previous run — reset it to baseBranch and check it out
|
||||
await this.git.raw(['branch', '-f', branch, baseBranch]);
|
||||
await this.git.raw(['worktree', 'add', worktreePath, branch]);
|
||||
} else {
|
||||
// git worktree add -b <branch> <path> <base-branch>
|
||||
await this.git.raw([
|
||||
'worktree',
|
||||
'add',
|
||||
'-b',
|
||||
branch,
|
||||
worktreePath,
|
||||
baseBranch,
|
||||
]);
|
||||
await this.git.raw(['worktree', 'add', '-b', branch, worktreePath, baseBranch]);
|
||||
}
|
||||
|
||||
const worktree: Worktree = {
|
||||
id,
|
||||
@@ -327,6 +327,18 @@ export class SimpleGitWorktreeManager implements WorktreeManager {
|
||||
return worktrees;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a local branch exists in the repository.
|
||||
*/
|
||||
private async branchExists(branch: string): Promise<boolean> {
|
||||
try {
|
||||
await this.git.raw(['rev-parse', '--verify', `refs/heads/${branch}`]);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the output of git diff --name-status.
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user