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 1ef129181d..cb9d41023d 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, @@ -16,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'; @@ -67,6 +69,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,6 +120,130 @@ describe('install', () => { }, ); + 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 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); + expect( + readdirSync(join(tmp, '.vite-hooks', '_')).filter((name) => name.endsWith('.tmp')), + ).toEqual([]); + } finally { + process.chdir(originalCwd); + rmSync(tmp, { recursive: true, force: true }); + } + }, + ); + + it.skipIf(process.platform === 'win32')( + '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(); + let waitForHook: Promise> | undefined; + 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 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', '_', 'h'), + [ + '#!/usr/bin/env sh', + 'n=$(basename "$0")', + 's=$(dirname "$(dirname "$0")")/$n', + '[ ! -f "$s" ] && exit 0', + 'sh -e "$s" "$@"', + 'c=$?', + 'exit $c', + ].join('\n'), + ); + // 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'); + waitForHook = closed; + const deadline = Date.now() + 10_000; + while (!existsSync(join(tmp, '.git', 'hook-started')) && Date.now() < deadline) { + await delay(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 { + 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 }); + } + }, + 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); + } 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..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, @@ -6,6 +7,7 @@ import { mkdirSync, readdirSync, realpathSync, + renameSync, rmSync, writeFileSync, } from 'node:fs'; @@ -51,6 +53,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) +// +// 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 @@ -60,6 +69,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 @@ -92,11 +103,13 @@ c=$? [ $c != 0 ] && echo "VITE+ - $n script failed (code $c)" [ $c = 127 ] && echo "VITE+ - command not found in PATH=$PATH" -exit $c`; +exit $c +} +`; } /** 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 +225,36 @@ function describeUnsafeHookInstallPath(unsafePath: UnsafeHookInstallPath): strin return `hook path "${unsafePath.relativePath}" is not a file`; } +/** + * 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 { + // 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 }); + chmodSync(tempPath, 0o755); + renameSync(tempPath, filePath); + return; + } catch { + try { + rmSync(tempPath, { force: true }); + } catch { + // A temp file that Windows still locks stays behind. The fallback still runs. + } + } + 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 +808,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) {