feat(vscode): ensureWorktreeFromRemote 从远端分支重建 worktree

Claude-Session: https://claude.ai/code/session_011cEyL6k351U2BzX1Qmygph
This commit is contained in:
2026-08-26 15:37:49 +08:00
parent 24fc09cb0e
commit ad82808dd0
2 changed files with 120 additions and 2 deletions
+32 -2
View File
@@ -34,7 +34,7 @@ export interface WorktreeOpts {
branch: string
}
function runGit(workspaceRoot: string, args: string[], failLabel?: string): Promise<string> {
export function runGit(workspaceRoot: string, args: string[], failLabel?: string): Promise<string> {
return new Promise((resolve, reject) => {
execFile('git', ['-C', workspaceRoot, ...args], { timeout: 30_000 }, (err, stdout, stderr) => {
if (err) {
@@ -94,7 +94,7 @@ function parseWorktreePorcelain(stdout: string): Array<{ path: string, branch: s
return entries
}
async function findLiveWorktreeForBranch(workspaceRoot: string, branch: string): Promise<string | undefined> {
export async function findLiveWorktreeForBranch(workspaceRoot: string, branch: string): Promise<string | undefined> {
const stdout = await runGit(workspaceRoot, ['worktree', 'list', '--porcelain'])
for (const entry of parseWorktreePorcelain(stdout)) {
if (entry.prunable || entry.branch !== branch)
@@ -135,6 +135,36 @@ export async function ensureWorktree(opts: WorktreeOpts): Promise<string> {
return worktreePath
}
/**
* 接管方重建 worktree:分支已在 origin 上,本机从远端 checkout。
* `-B` 让本地同名残留分支直接对齐远端(发送方移交前已校验全部 push)。
*/
export async function ensureWorktreeFromRemote(opts: WorktreeOpts): Promise<string> {
const { workspaceRoot, branch } = opts
const worktreePath = path.resolve(opts.worktreePath)
await runGit(workspaceRoot, ['fetch', 'origin', branch], `拉取远端分支 ${branch}`)
// ① 已经有 live worktree → 复用,不动模板路径
const live = await findLiveWorktreeForBranch(workspaceRoot, branch)
if (live)
return live
// ② 模板路径被垃圾目录占着 → kill + 删,否则 add 撞路径
if (await pathExists(worktreePath)) {
killProcessesUsingWorktree(worktreePath)
await removeWorktreeDir(workspaceRoot, worktreePath)
}
await fsp.mkdir(path.dirname(worktreePath), { recursive: true })
await runGit(
workspaceRoot,
['worktree', 'add', '-B', branch, worktreePath, `origin/${branch}`],
'git worktree add',
)
return worktreePath
}
/**
* 删除一个 worktree 目录并清掉 git 侧注册。
*