From 8cf1a3460d6d5fe04d27cf9cfbf8a3595eec181c Mon Sep 17 00:00:00 2001 From: "voidzero-bot[bot]" <348775505+voidzero-bot[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:11:00 +0000 Subject: [PATCH 1/4] fix(cli): newline-terminate and atomically replace git hook dispatcher files --- .../cli/src/config/__tests__/hooks.spec.ts | 88 +++++++++++++++++++ packages/cli/src/config/hooks.ts | 34 +++++-- 2 files changed, 116 insertions(+), 6 deletions(-) diff --git a/packages/cli/src/config/__tests__/hooks.spec.ts b/packages/cli/src/config/__tests__/hooks.spec.ts index 1ef129181d..1de5148fe5 100644 --- a/packages/cli/src/config/__tests__/hooks.spec.ts +++ b/packages/cli/src/config/__tests__/hooks.spec.ts @@ -93,6 +93,94 @@ describe('install', () => { }, ); + it('ends the generated dispatcher and hook stubs with a newline', () => { + const tmp = mkdtempSync(join(tmpdir(), 'hooks-newline-')); + const originalCwd = process.cwd(); + try { + execSync('git init', { cwd: tmp, stdio: 'ignore' }); + process.chdir(tmp); + + expect(install('.vite-hooks').isError).toBe(false); + const internal = join(tmp, '.vite-hooks', '_'); + // Shells re-read a sourced file past its old EOF when the final line is + // unterminated, so a mid-hook rewrite corrupts a running hook (#3567). + expect(readFileSync(join(internal, 'h'), 'utf8')).toMatch(/\n$/); + for (const hook of SUPPORTED_GIT_HOOK_NAMES) { + expect(readFileSync(join(internal, hook), 'utf8')).toMatch(/\n$/); + } + } finally { + process.chdir(originalCwd); + rmSync(tmp, { recursive: true, force: true }); + } + }); + + it.skipIf(process.platform === 'win32')( + 'replaces the dispatcher with a new file instead of rewriting it in place', + () => { + const tmp = mkdtempSync(join(tmpdir(), 'hooks-atomic-')); + const originalCwd = process.cwd(); + try { + execSync('git init', { cwd: tmp, stdio: 'ignore' }); + process.chdir(tmp); + + const dispatcherPath = join(tmp, '.vite-hooks', '_', 'h'); + expect(install('.vite-hooks').isError).toBe(false); + const firstInode = statSync(dispatcherPath).ino; + + // A second install must hand a running shell the old bytes until the + // new file replaces the path: rewrites in place feed the shell the new + // content past the old EOF (#3567). + expect(install('.vite-hooks').isError).toBe(false); + expect(statSync(dispatcherPath).ino).not.toBe(firstInode); + } finally { + process.chdir(originalCwd); + rmSync(tmp, { recursive: true, force: true }); + } + }, + ); + + it.skipIf(process.platform === 'win32')( + 'keeps a running hook shell healthy when the dispatcher is rewritten mid-hook', + () => { + const tmp = mkdtempSync(join(tmpdir(), 'hooks-rewrite-')); + const originalCwd = process.cwd(); + try { + execSync('git init', { cwd: tmp, stdio: 'ignore' }); + process.chdir(tmp); + expect(install('.vite-hooks').isError).toBe(false); + + // Stand-in for `pnpm install` whose `prepare: vp config` writes a + // longer dispatcher, as when switching between branches that pin + // different vite-plus versions (#3567). + writeFileSync( + join(tmp, '.vite-hooks', 'post-checkout'), + [ + '#!/usr/bin/env sh', + String.raw`{ printf '# simulated newer dispatcher\n'; cat .vite-hooks/_/h; } > .vite-hooks/_/h.new`, + 'cat .vite-hooks/_/h.new > .vite-hooks/_/h', + '', + ].join('\n'), + { mode: 0o755 }, + ); + execSync('git add -A', { cwd: tmp, stdio: 'ignore' }); + // A real commit is required: on an unborn HEAD, `git checkout -b` + // creates the branch without updating the worktree and never runs + // the post-checkout hook. + expect(runCommit(tmp, 'init').status).toBe(0); + + const checkout = spawnSync('git', ['checkout', '-b', 'other'], { + cwd: tmp, + encoding: 'utf8', + }); + expect(checkout.status).toBe(0); + expect(checkout.stderr).not.toMatch(/Syntax error/i); + } finally { + process.chdir(originalCwd); + rmSync(tmp, { recursive: true, force: true }); + } + }, + ); + it('skips install when VP_GIT_HOOKS=0', () => { const prev = process.env.VP_GIT_HOOKS; process.env.VP_GIT_HOOKS = '0'; diff --git a/packages/cli/src/config/hooks.ts b/packages/cli/src/config/hooks.ts index db249256de..526cfa95a1 100644 --- a/packages/cli/src/config/hooks.ts +++ b/packages/cli/src/config/hooks.ts @@ -6,6 +6,7 @@ import { mkdirSync, readdirSync, realpathSync, + renameSync, rmSync, writeFileSync, } from 'node:fs'; @@ -51,6 +52,9 @@ function nestedDirname(depth: number): string { // The shell script that dispatches to user-defined hooks in / // `depth` = number of path segments in `dir` + 2 (for `_` subdir + hook filename) +// The script must end with a newline: shells (dash) re-read the sourced file +// past its old EOF when the final line is unterminated, so an in-flight rewrite +// that appends bytes corrupts a running hook (see #3567). export function hookScript(dir: string): string { // Count segments: ".vite-hooks" → 1, ".config/husky" → 2 // Git accepts forward slashes on every platform; Windows also accepts its @@ -92,11 +96,11 @@ c=$? [ $c != 0 ] && echo "VITE+ - $n script failed (code $c)" [ $c = 127 ] && echo "VITE+ - command not found in PATH=$PATH" -exit $c`; +exit $c\n`; } /** The per-hook stub written to `/_/`; it sources the `h` dispatcher. */ -export const HOOK_STUB_SCRIPT = '#!/usr/bin/env sh\n. "$(dirname "$0")/h"'; +export const HOOK_STUB_SCRIPT = '#!/usr/bin/env sh\n. "$(dirname "$0")/h"\n'; export interface InstallResult { message: string; @@ -212,6 +216,26 @@ function describeUnsafeHookInstallPath(unsafePath: UnsafeHookInstallPath): strin return `hook path "${unsafePath.relativePath}" is not a file`; } +/** + * Write a generated hook file without disturbing a shell that still has the + * old file open: `writeFileSync` truncates in place, so a hook shell that + * sourced the dispatcher and re-reads past the old EOF sees the new bytes + * (see #3567). Renaming a fully written temp file over the target replaces + * the inode on POSIX instead. Fall back to an in-place write when the rename + * cannot replace the target (e.g. a locked destination on Windows). + */ +function writeGeneratedHookFile(filePath: string, content: string): void { + const tempPath = `${filePath}.${process.pid}.tmp`; + writeFileSync(tempPath, content, { mode: 0o755 }); + try { + renameSync(tempPath, filePath); + } catch { + rmSync(tempPath, { force: true }); + writeFileSync(filePath, content, { mode: 0o755 }); + } + chmodSync(filePath, 0o755); +} + function gitConfigGet(key: string, options?: { local?: boolean; bool?: boolean }): string | null { const args = ['config']; if (options?.local) { @@ -765,11 +789,9 @@ export function install(dir?: string, options: InstallOptions = {}): InstallResu rmSync(internal('husky.sh'), { force: true }); mkdirSync(internal(), { recursive: true }); writeFileSync(internal('.gitignore'), '*'); - writeFileSync(internal('h'), hookScript(location.dir), { mode: 0o755 }); - chmodSync(internal('h'), 0o755); + writeGeneratedHookFile(internal('h'), hookScript(location.dir)); for (const hook of SUPPORTED_GIT_HOOK_NAMES) { - writeFileSync(internal(hook), HOOK_STUB_SCRIPT, { mode: 0o755 }); - chmodSync(internal(hook), 0o755); + writeGeneratedHookFile(internal(hook), HOOK_STUB_SCRIPT); } const storeHooksPath = gitConfigSet('core.hooksPath', location.target); if (!storeHooksPath.ok) { From d0e211e6573d3805cc5456ddf8e63c56576eedc7 Mon Sep 17 00:00:00 2001 From: "MK (fengmk2)" Date: Wed, 25 Nov 2026 15:20:18 +0800 Subject: [PATCH 2/4] fix(cli): parse the whole hook dispatcher before the hook runs The final newline alone does not stop the failure in #3567 when the shell reads the dispatcher in blocks smaller than the file. macOS /bin/dash and BusyBox builds with the default config read 1 KiB at a time, and the dispatcher is larger. Put the dispatcher body in a brace group, so the shell parses the whole file before it runs the hook. Create the temp file with `wx` and set its mode before the rename. Run the hook tests with dash where it exists, and add a test that runs `install()` while a hook runs a dispatcher from vite-plus 1.8.0. Co-Authored-By: Claude Opus 5.5 --- .../snapshots/migration_add_git_hooks.md | 3 + .../cli/src/config/__tests__/hooks.spec.ts | 135 ++++++++++++------ packages/cli/src/config/hooks.ts | 42 ++++-- 3 files changed, 125 insertions(+), 55 deletions(-) diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_add_git_hooks/snapshots/migration_add_git_hooks.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_add_git_hooks/snapshots/migration_add_git_hooks.md index 35d1352c31..874346ebb0 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_add_git_hooks/snapshots/migration_add_git_hooks.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_add_git_hooks/snapshots/migration_add_git_hooks.md @@ -83,6 +83,8 @@ hook dispatcher script content ``` #!/usr/bin/env sh +# Read the whole file before the hook runs. A hook that runs vp config can rewrite it. +{ { [ "$HUSKY" = "2" ] || [ "$VP_GIT_HOOKS" = "2" ] || [ "$VITE_GIT_HOOKS" = "2" ]; } && set -x n=$(basename "$0") s=$(dirname "$(dirname "$0")")/$n @@ -116,6 +118,7 @@ c=$? [ $c != 0 ] && echo "VITE+ - $n script failed (code $c)" [ $c = 127 ] && echo "VITE+ - command not found in PATH=$PATH" exit $c +} ``` ## `vpt print-file .vite-hooks/_/pre-commit` diff --git a/packages/cli/src/config/__tests__/hooks.spec.ts b/packages/cli/src/config/__tests__/hooks.spec.ts index 1de5148fe5..09ebfab4bc 100644 --- a/packages/cli/src/config/__tests__/hooks.spec.ts +++ b/packages/cli/src/config/__tests__/hooks.spec.ts @@ -67,6 +67,31 @@ function countDirnameCalls(script: string): number { return (match[1].match(/dirname/g) ?? []).length; } +// bash reads a sourced file whole, so it never shows #3567. Run hooks with dash +// where it exists: macOS has /bin/dash, and Debian or Ubuntu use it as /bin/sh. +function envWithDashAsSh(tmp: string): NodeJS.ProcessEnv { + const dash = ['/bin/dash', '/usr/bin/dash'].find((path) => existsSync(path)); + if (!dash) { + return process.env; + } + const bin = join(tmp, '.git', 'test-bin'); + mkdirSync(bin); + symlinkSync(dash, join(bin, 'sh')); + return { ...process.env, PATH: `${bin}:${process.env.PATH}` }; +} + +function commitPostCheckoutHook(tmp: string, lines: Array): void { + writeFileSync( + join(tmp, '.vite-hooks', 'post-checkout'), + ['#!/usr/bin/env sh', ...lines, ''].join('\n'), + { mode: 0o755 }, + ); + execSync('git add -A', { cwd: tmp, stdio: 'ignore' }); + // On an unborn HEAD, `git checkout -b` does not update the worktree and + // does not run post-checkout. + expect(runCommit(tmp, 'init').status).toBe(0); +} + describe('install', () => { it.skipIf(process.platform === 'win32')( 'should create _/pre-commit but not pre-commit in hooks dir root', @@ -93,27 +118,6 @@ describe('install', () => { }, ); - it('ends the generated dispatcher and hook stubs with a newline', () => { - const tmp = mkdtempSync(join(tmpdir(), 'hooks-newline-')); - const originalCwd = process.cwd(); - try { - execSync('git init', { cwd: tmp, stdio: 'ignore' }); - process.chdir(tmp); - - expect(install('.vite-hooks').isError).toBe(false); - const internal = join(tmp, '.vite-hooks', '_'); - // Shells re-read a sourced file past its old EOF when the final line is - // unterminated, so a mid-hook rewrite corrupts a running hook (#3567). - expect(readFileSync(join(internal, 'h'), 'utf8')).toMatch(/\n$/); - for (const hook of SUPPORTED_GIT_HOOK_NAMES) { - expect(readFileSync(join(internal, hook), 'utf8')).toMatch(/\n$/); - } - } finally { - process.chdir(originalCwd); - rmSync(tmp, { recursive: true, force: true }); - } - }); - it.skipIf(process.platform === 'win32')( 'replaces the dispatcher with a new file instead of rewriting it in place', () => { @@ -127,11 +131,10 @@ describe('install', () => { expect(install('.vite-hooks').isError).toBe(false); const firstInode = statSync(dispatcherPath).ino; - // A second install must hand a running shell the old bytes until the - // new file replaces the path: rewrites in place feed the shell the new - // content past the old EOF (#3567). + // A hook shell that has the old file open keeps reading the old file. expect(install('.vite-hooks').isError).toBe(false); expect(statSync(dispatcherPath).ino).not.toBe(firstInode); + expect(statSync(dispatcherPath).mode & 0o777).toBe(0o755); } finally { process.chdir(originalCwd); rmSync(tmp, { recursive: true, force: true }); @@ -140,40 +143,88 @@ describe('install', () => { ); it.skipIf(process.platform === 'win32')( - 'keeps a running hook shell healthy when the dispatcher is rewritten mid-hook', - () => { - const tmp = mkdtempSync(join(tmpdir(), 'hooks-rewrite-')); + 'keeps a hook running when vp config replaces an older dispatcher during the hook', + async () => { + const tmp = mkdtempSync(join(tmpdir(), 'hooks-replace-old-')); const originalCwd = process.cwd(); try { execSync('git init', { cwd: tmp, stdio: 'ignore' }); process.chdir(tmp); expect(install('.vite-hooks').isError).toBe(false); - - // Stand-in for `pnpm install` whose `prepare: vp config` writes a - // longer dispatcher, as when switching between branches that pin - // different vite-plus versions (#3567). + // vite-plus 1.8.0 and earlier wrote a dispatcher without the brace group + // and without a final newline. A shell reads more of it after the hook. writeFileSync( - join(tmp, '.vite-hooks', 'post-checkout'), + join(tmp, '.vite-hooks', '_', 'h'), [ '#!/usr/bin/env sh', - String.raw`{ printf '# simulated newer dispatcher\n'; cat .vite-hooks/_/h; } > .vite-hooks/_/h.new`, - 'cat .vite-hooks/_/h.new > .vite-hooks/_/h', - '', + 'n=$(basename "$0")', + 's=$(dirname "$(dirname "$0")")/$n', + '[ ! -f "$s" ] && exit 0', + 'sh -e "$s" "$@"', + 'c=$?', + 'exit $c', ].join('\n'), - { mode: 0o755 }, ); - execSync('git add -A', { cwd: tmp, stdio: 'ignore' }); - // A real commit is required: on an unborn HEAD, `git checkout -b` - // creates the branch without updating the worktree and never runs - // the post-checkout hook. - expect(runCommit(tmp, 'init').status).toBe(0); + // The hook stops until the test runs `vp config`, as `pnpm install` + // with `prepare: vp config` does in a post-checkout hook. + commitPostCheckoutHook(tmp, [ + ': > .git/hook-started', + 'i=0', + 'while [ ! -f .git/hook-release ] && [ "$i" -lt 100 ]; do sleep 0.1; i=$((i + 1)); done', + ]); + + const checkout = spawn('git', ['checkout', '-b', 'other'], { + cwd: tmp, + env: envWithDashAsSh(tmp), + stdio: ['ignore', 'ignore', 'pipe'], + }); + let stderr = ''; + checkout.stderr.setEncoding('utf8').on('data', (chunk: string) => { + stderr += chunk; + }); + const closed = once(checkout, 'close'); + const deadline = Date.now() + 10_000; + while (!existsSync(join(tmp, '.git', 'hook-started')) && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 20)); + } + expect(existsSync(join(tmp, '.git', 'hook-started'))).toBe(true); + + expect(install('.vite-hooks').isError).toBe(false); + writeFileSync(join(tmp, '.git', 'hook-release'), ''); + const [code] = await closed; + + expect(stderr).not.toMatch(/error|illegal/i); + expect(code).toBe(0); + } finally { + process.chdir(originalCwd); + rmSync(tmp, { recursive: true, force: true }); + } + }, + 15_000, + ); + + it.skipIf(process.platform === 'win32')( + 'keeps a hook running when an older vp config rewrites the dispatcher in place', + () => { + const tmp = mkdtempSync(join(tmpdir(), 'hooks-rewrite-')); + const originalCwd = process.cwd(); + try { + execSync('git init', { cwd: tmp, stdio: 'ignore' }); + process.chdir(tmp); + expect(install('.vite-hooks').isError).toBe(false); + + // vite-plus 1.8.0 and earlier write in place, for example after a checkout + // of a branch that pins one. The new bytes are not valid shell, so the + // checkout fails if the shell reads the dispatcher after the hook. + commitPostCheckoutHook(tmp, ["printf '%2048s' '' | tr ' ' ')' > .vite-hooks/_/h"]); const checkout = spawnSync('git', ['checkout', '-b', 'other'], { cwd: tmp, encoding: 'utf8', + env: envWithDashAsSh(tmp), }); + expect(checkout.stderr).not.toMatch(/error|illegal/i); expect(checkout.status).toBe(0); - expect(checkout.stderr).not.toMatch(/Syntax error/i); } finally { process.chdir(originalCwd); rmSync(tmp, { recursive: true, force: true }); diff --git a/packages/cli/src/config/hooks.ts b/packages/cli/src/config/hooks.ts index 526cfa95a1..eb391ff683 100644 --- a/packages/cli/src/config/hooks.ts +++ b/packages/cli/src/config/hooks.ts @@ -52,9 +52,13 @@ function nestedDirname(depth: number): string { // The shell script that dispatches to user-defined hooks in / // `depth` = number of path segments in `dir` + 2 (for `_` subdir + hook filename) -// The script must end with a newline: shells (dash) re-read the sourced file -// past its old EOF when the final line is unterminated, so an in-flight rewrite -// that appends bytes corrupts a running hook (see #3567). +// +// A hook can run `vp config` (for example `pnpm install` with `prepare: vp config` +// in post-checkout), and vite-plus 1.8.0 and earlier rewrite this file in place. +// dash and BusyBox ash read a sourced file in blocks of 1–8 KiB and read the next +// block only when they need it, so they can parse bytes of the new file after the +// hook (#3567). The brace group makes the shell parse the whole script before the +// hook runs. export function hookScript(dir: string): string { // Count segments: ".vite-hooks" → 1, ".config/husky" → 2 // Git accepts forward slashes on every platform; Windows also accepts its @@ -64,6 +68,8 @@ export function hookScript(dir: string): string { const depth = segments + 2; // +2 for _ subdir and hook filename const rootExpr = nestedDirname(depth); return `#!/usr/bin/env sh +# Read the whole file before the hook runs. A hook that runs vp config can rewrite it. +{ { [ "$HUSKY" = "2" ] || [ "$VP_GIT_HOOKS" = "2" ] || [ "$VITE_GIT_HOOKS" = "2" ]; } && set -x n=$(basename "$0") s=$(dirname "$(dirname "$0")")/$n @@ -96,7 +102,9 @@ c=$? [ $c != 0 ] && echo "VITE+ - $n script failed (code $c)" [ $c = 127 ] && echo "VITE+ - command not found in PATH=$PATH" -exit $c\n`; +exit $c +} +`; } /** The per-hook stub written to `/_/`; it sources the `h` dispatcher. */ @@ -217,22 +225,30 @@ function describeUnsafeHookInstallPath(unsafePath: UnsafeHookInstallPath): strin } /** - * Write a generated hook file without disturbing a shell that still has the - * old file open: `writeFileSync` truncates in place, so a hook shell that - * sourced the dispatcher and re-reads past the old EOF sees the new bytes - * (see #3567). Renaming a fully written temp file over the target replaces - * the inode on POSIX instead. Fall back to an in-place write when the rename - * cannot replace the target (e.g. a locked destination on Windows). + * Replace a generated hook file with a new file. A hook shell that sourced an + * older dispatcher keeps that file open and can read more of it after the hook + * runs `vp config` (#3567). An in-place write would give that shell bytes of the + * new file. A rename leaves the shell on the old file. Fall back to an in-place + * write when the temp file or the rename fails, for example when Windows locks + * the target. */ function writeGeneratedHookFile(filePath: string, content: string): void { const tempPath = `${filePath}.${process.pid}.tmp`; - writeFileSync(tempPath, content, { mode: 0o755 }); + let tempCreated = false; try { + // `wx` refuses an existing path, so the write never follows a link at the + // temp path. `findUnsafeHookInstallPath` checks only the final names. + writeFileSync(tempPath, content, { flag: 'wx', mode: 0o755 }); + tempCreated = true; + chmodSync(tempPath, 0o755); renameSync(tempPath, filePath); + return; } catch { - rmSync(tempPath, { force: true }); - writeFileSync(filePath, content, { mode: 0o755 }); + if (tempCreated) { + rmSync(tempPath, { force: true }); + } } + writeFileSync(filePath, content, { mode: 0o755 }); chmodSync(filePath, 0o755); } From d7457068ee93faee3fe8613f0e1868647b569693 Mon Sep 17 00:00:00 2001 From: "MK (fengmk2)" Date: Wed, 25 Nov 2026 16:29:26 +0800 Subject: [PATCH 3/4] fix(cli): keep the hook file fallback when temp cleanup fails On Windows, a temp file that another process locks can make the rename and the cleanup both fail. The cleanup error then left the write helper, and the in-place fallback did not run. A temp name with the pid can also match a file from a crashed run, which forces the in-place write. Use a random temp name, and make the cleanup best-effort so that the fallback always runs. The tests now check that no temp file stays, and release the waiting hook when an assertion fails. Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/config/__tests__/hooks.spec.ts | 11 +++++++++++ packages/cli/src/config/hooks.ts | 11 +++++++---- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/packages/cli/src/config/__tests__/hooks.spec.ts b/packages/cli/src/config/__tests__/hooks.spec.ts index 09ebfab4bc..174f6d0489 100644 --- a/packages/cli/src/config/__tests__/hooks.spec.ts +++ b/packages/cli/src/config/__tests__/hooks.spec.ts @@ -7,6 +7,7 @@ import { linkSync, mkdirSync, mkdtempSync, + readdirSync, readFileSync, realpathSync, rmSync, @@ -135,6 +136,9 @@ describe('install', () => { expect(install('.vite-hooks').isError).toBe(false); expect(statSync(dispatcherPath).ino).not.toBe(firstInode); expect(statSync(dispatcherPath).mode & 0o777).toBe(0o755); + expect( + readdirSync(join(tmp, '.vite-hooks', '_')).filter((name) => name.endsWith('.tmp')), + ).toEqual([]); } finally { process.chdir(originalCwd); rmSync(tmp, { recursive: true, force: true }); @@ -147,6 +151,7 @@ describe('install', () => { async () => { const tmp = mkdtempSync(join(tmpdir(), 'hooks-replace-old-')); const originalCwd = process.cwd(); + let waitForHook: Promise> | undefined; try { execSync('git init', { cwd: tmp, stdio: 'ignore' }); process.chdir(tmp); @@ -183,6 +188,7 @@ describe('install', () => { stderr += chunk; }); const closed = once(checkout, 'close'); + waitForHook = closed; const deadline = Date.now() + 10_000; while (!existsSync(join(tmp, '.git', 'hook-started')) && Date.now() < deadline) { await new Promise((resolve) => setTimeout(resolve, 20)); @@ -196,6 +202,11 @@ describe('install', () => { expect(stderr).not.toMatch(/error|illegal/i); expect(code).toBe(0); } finally { + if (waitForHook) { + // When an assertion fails before the release, end the hook before the cleanup. + writeFileSync(join(tmp, '.git', 'hook-release'), ''); + await waitForHook; + } process.chdir(originalCwd); rmSync(tmp, { recursive: true, force: true }); } diff --git a/packages/cli/src/config/hooks.ts b/packages/cli/src/config/hooks.ts index eb391ff683..147edf3a1a 100644 --- a/packages/cli/src/config/hooks.ts +++ b/packages/cli/src/config/hooks.ts @@ -1,4 +1,5 @@ import { spawnSync } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; import { chmodSync, existsSync, @@ -233,19 +234,21 @@ function describeUnsafeHookInstallPath(unsafePath: UnsafeHookInstallPath): strin * the target. */ function writeGeneratedHookFile(filePath: string, content: string): void { - const tempPath = `${filePath}.${process.pid}.tmp`; - let tempCreated = false; + // A random name cannot match a temp file from a crashed run, or from a run in + // another container that has the same pid. + const tempPath = `${filePath}.${randomBytes(6).toString('hex')}.tmp`; try { // `wx` refuses an existing path, so the write never follows a link at the // temp path. `findUnsafeHookInstallPath` checks only the final names. writeFileSync(tempPath, content, { flag: 'wx', mode: 0o755 }); - tempCreated = true; chmodSync(tempPath, 0o755); renameSync(tempPath, filePath); return; } catch { - if (tempCreated) { + try { rmSync(tempPath, { force: true }); + } catch { + // A temp file that Windows still locks stays behind. The fallback still runs. } } writeFileSync(filePath, content, { mode: 0o755 }); From 905dd2ae64bd5ed1cbfb9830c0d3c406a6da7ff8 Mon Sep 17 00:00:00 2001 From: "MK (fengmk2)" Date: Wed, 25 Nov 2026 16:35:03 +0800 Subject: [PATCH 4/4] test(cli): wait for the hook without a Promise executor `no-promise-executor-return` rejects `new Promise((resolve) => setTimeout(resolve, 20))` because the arrow returns the timer. Use `setTimeout` from `node:timers/promises`. Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/config/__tests__/hooks.spec.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/cli/src/config/__tests__/hooks.spec.ts b/packages/cli/src/config/__tests__/hooks.spec.ts index 174f6d0489..cb9d41023d 100644 --- a/packages/cli/src/config/__tests__/hooks.spec.ts +++ b/packages/cli/src/config/__tests__/hooks.spec.ts @@ -17,6 +17,7 @@ import { } from 'node:fs'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; import { describe, expect, it } from 'vitest'; @@ -191,7 +192,7 @@ describe('install', () => { waitForHook = closed; const deadline = Date.now() + 10_000; while (!existsSync(join(tmp, '.git', 'hook-started')) && Date.now() < deadline) { - await new Promise((resolve) => setTimeout(resolve, 20)); + await delay(20); } expect(existsSync(join(tmp, '.git', 'hook-started'))).toBe(true);