🐛 fix(vscode): 完成列/删 worktree 时自动杀掉占用进程再删目录
This commit is contained in:
1 parent
23e6f67373
commit
29aaabdabf
4 files changed
+133
-41
No files matched your search
@@ -3,7 +3,7 @@ import { existsSync, mkdtempSync, rmSync } from 'node:fs'
|
||||
import * as os from 'node:os'
|
||||
import * as path from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { findProcessesUsingWorktree, resolveWorktreePath } from './worktree'
|
||||
import { findProcessesUsingWorktree, killProcessesUsingWorktree, resolveWorktreePath } from './worktree'
|
||||
|
||||
describe('resolveWorktreePath', () => {
|
||||
const workspaceRoot = '/workspace/project'
|
||||
@@ -55,3 +55,60 @@ describe.runIf(existsSync('/proc'))('findProcessesUsingWorktree', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
// 杀占用进程:与 find 同依赖 /proc,非 Linux 跳过。
|
||||
describe.runIf(existsSync('/proc'))('killProcessesUsingWorktree', () => {
|
||||
it('杀掉 cwd 落在 worktree 下的进程,find 结果变空', async () => {
|
||||
const dir = mkdtempSync(path.join(os.tmpdir(), 'wt-kill-'))
|
||||
const child = spawn('sleep', ['30'], { cwd: dir, stdio: 'ignore' })
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
child.on('spawn', () => resolve())
|
||||
child.on('error', reject)
|
||||
})
|
||||
expect(findProcessesUsingWorktree(dir).some(h => h.pid === String(child.pid))).toBe(true)
|
||||
|
||||
const killed = killProcessesUsingWorktree(dir)
|
||||
expect(killed.some(h => h.pid === String(child.pid))).toBe(true)
|
||||
|
||||
// 等子进程真正退出(kill 函数已等 300–500ms,这里再兜底)
|
||||
await new Promise<void>((resolve) => {
|
||||
if (child.killed || child.exitCode !== null)
|
||||
resolve()
|
||||
else
|
||||
child.on('exit', () => resolve())
|
||||
setTimeout(resolve, 1000)
|
||||
})
|
||||
expect(findProcessesUsingWorktree(dir).some(h => h.pid === String(child.pid))).toBe(false)
|
||||
}
|
||||
finally {
|
||||
try {
|
||||
child.kill('SIGKILL')
|
||||
}
|
||||
catch {}
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('不杀 process.pid / process.ppid(命中时跳过)', () => {
|
||||
// chdir 到独占临时目录,让 find 能命中本进程 cwd,又不会扫到 vitest/项目其它进程。
|
||||
const dir = mkdtempSync(path.join(os.tmpdir(), 'wt-self-'))
|
||||
const prev = process.cwd()
|
||||
const selfPid = String(process.pid)
|
||||
const parentPid = String(process.ppid)
|
||||
try {
|
||||
process.chdir(dir)
|
||||
// find 应能看到自身(cwd=dir);kill 必须跳过 self/ppid
|
||||
expect(findProcessesUsingWorktree(dir).some(h => h.pid === selfPid)).toBe(true)
|
||||
|
||||
const killed = killProcessesUsingWorktree(dir)
|
||||
expect(killed.some(h => h.pid === selfPid)).toBe(false)
|
||||
expect(killed.some(h => h.pid === parentPid)).toBe(false)
|
||||
expect(process.kill(process.pid, 0)).toBe(true)
|
||||
}
|
||||
finally {
|
||||
process.chdir(prev)
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user