From 9c506fb7aa8af1c26576141be604528b28656991 Mon Sep 17 00:00:00 2001 From: semimikoh Date: Wed, 4 Nov 2026 11:25:08 +0900 Subject: [PATCH 1/7] fix(cli): reclaim stale Husky hooks paths after migration --- docs/guide/commit-hooks.md | 2 + .../cli/src/config/__tests__/hooks.spec.ts | 180 +++++++++++++++++- packages/cli/src/config/hooks.ts | 79 +++++++- 3 files changed, 258 insertions(+), 3 deletions(-) diff --git a/docs/guide/commit-hooks.md b/docs/guide/commit-hooks.md index 6de5dcbae8..ab872c2c8d 100644 --- a/docs/guide/commit-hooks.md +++ b/docs/guide/commit-hooks.md @@ -76,6 +76,8 @@ Use `--no-hooks` when you want `vp config` to leave the Git hook dispatcher unch If `core.hooksPath` points to another hook directory, `vp config` skips dispatcher installation to preserve the existing setup. Run `vp hooks status` to inspect the current configuration. +After migrating from Husky, existing clones can retain a local `core.hooksPath` of `.husky` or `.husky/_`. `vp config` and `vp hooks enable` automatically replace this stale setting when the Vite+ hooks directory contains a hook script, no hook scripts remain directly under `.husky/`, and the repository and ancestor package manifests no longer declare Husky dependencies, configuration, or scripts. The old Husky files are left unchanged. Global and worktree-scoped hook settings are preserved. + You can also set `VP_GIT_HOOKS=0` to disable hook installation from lifecycle scripts such as `prepare` or `postinstall`. Project-owned hook scripts such as `.vite-hooks/pre-commit` should be committed to the repository. The generated dispatcher and shims under `.vite-hooks/_` are ignored and recreated by `vp config` or `vp hooks enable`. Neither command creates or modifies project hook scripts or staged-file configuration. diff --git a/packages/cli/src/config/__tests__/hooks.spec.ts b/packages/cli/src/config/__tests__/hooks.spec.ts index e9230de2f8..c63746ec57 100644 --- a/packages/cli/src/config/__tests__/hooks.spec.ts +++ b/packages/cli/src/config/__tests__/hooks.spec.ts @@ -1,4 +1,4 @@ -import { execSync, spawn } from 'node:child_process'; +import { execFileSync, execSync, spawn, spawnSync } from 'node:child_process'; import { once } from 'node:events'; import { chmodSync, @@ -114,6 +114,9 @@ describe('install', () => { execSync('git config core.hooksPath .husky/_', { cwd: tmp }); mkdirSync(join(tmp, '.husky')); writeFileSync(join(tmp, '.husky', 'pre-commit'), 'npm test\n'); + writeFileSync(join(tmp, 'package.json'), '{}'); + mkdirSync(join(tmp, '.vite-hooks')); + writeFileSync(join(tmp, '.vite-hooks', 'pre-commit'), 'npm test\n'); process.chdir(tmp); expect(install()).toEqual({ @@ -124,13 +127,186 @@ describe('install', () => { '.husky/_', ); expect(readFileSync(join(tmp, '.husky', 'pre-commit'), 'utf8')).toBe('npm test\n'); - expect(existsSync(join(tmp, '.vite-hooks'))).toBe(false); + expect(existsSync(join(tmp, '.vite-hooks', '_'))).toBe(false); } finally { process.chdir(originalCwd); rmSync(tmp, { recursive: true, force: true }); } }); + it.each([ + ['.husky', '.vite-hooks'], + ['.husky/_', '.vite-hooks'], + ['./.husky/_/', '.vite-hooks'], + ['.husky/_', '.custom-hooks'], + ['.husky/_', 'packages/app/.vite-hooks'], + ])('takes over a stale local Husky path %s after migration to %s', (hooksPath, hooksDir) => { + const tmp = mkdtempSync(join(tmpdir(), 'hooks-husky-migration-')); + const originalCwd = process.cwd(); + try { + execFileSync('git', ['init'], { cwd: tmp, stdio: 'ignore' }); + execFileSync('git', ['config', 'core.hooksPath', hooksPath], { cwd: tmp }); + writeFileSync( + join(tmp, 'package.json'), + JSON.stringify({ scripts: { prepare: 'vp config' } }), + ); + mkdirSync(join(tmp, '.husky', '_'), { recursive: true }); + const oldDispatcher = join(tmp, '.husky', '_', 'h'); + writeFileSync(oldDispatcher, 'old husky dispatcher\n'); + mkdirSync(join(tmp, hooksDir), { recursive: true }); + writeFileSync(join(tmp, hooksDir, 'commit-msg'), 'exit 1\n'); + process.chdir(tmp); + + expect(install(hooksDir)).toEqual({ message: '', isError: false }); + expect( + execFileSync('git', ['config', '--get', 'core.hooksPath'], { encoding: 'utf8' }).trim(), + ).toBe(`${hooksDir}/_`); + expect(readFileSync(oldDispatcher, 'utf8')).toBe('old husky dispatcher\n'); + // A real commit must invoke the migrated hook, even in the old clone. + const commit = spawnSync( + 'git', + [ + '-c', + 'user.name=Test', + '-c', + 'user.email=test@example.invalid', + 'commit', + '--allow-empty', + '-m', + 'bad message', + ], + { encoding: 'utf8' }, + ); + expect(commit.status).toBe(1); + expect(commit.stdout + commit.stderr).toContain('commit-msg script failed'); + expect(enable().isError).toBe(false); + expect(install()).toEqual({ message: '', isError: false }); + } finally { + process.chdir(originalCwd); + rmSync(tmp, { recursive: true, force: true }); + } + }); + + it.each([ + ['production Husky dependency', { dependencies: { husky: '^9.0.0' } }], + ['Husky dependency', { devDependencies: { husky: '^9.0.0' } }], + ['optional Husky dependency', { optionalDependencies: { husky: '^9.0.0' } }], + ['peer Husky dependency', { peerDependencies: { husky: '^9.0.0' } }], + ['Husky prepare script', { scripts: { prepare: 'husky' } }], + ['legacy Husky config', { husky: { hooks: { 'pre-commit': 'npm test' } } }], + ])('preserves a Husky path with %s', (_name, pkg) => { + const tmp = mkdtempSync(join(tmpdir(), 'hooks-active-husky-')); + const originalCwd = process.cwd(); + try { + execFileSync('git', ['init'], { cwd: tmp, stdio: 'ignore' }); + execFileSync('git', ['config', 'core.hooksPath', '.husky/_'], { cwd: tmp }); + writeFileSync(join(tmp, 'package.json'), JSON.stringify(pkg)); + mkdirSync(join(tmp, '.vite-hooks')); + writeFileSync(join(tmp, '.vite-hooks', 'pre-commit'), 'exit 1\n'); + process.chdir(tmp); + + expect(install().message).toBe('core.hooksPath is already set to ".husky/_", skipping'); + expect(existsSync(join(tmp, '.vite-hooks', '_'))).toBe(false); + } finally { + process.chdir(originalCwd); + rmSync(tmp, { recursive: true, force: true }); + } + }); + + it.skipIf(process.platform === 'win32').each(['.husky', '.husky/_'])( + 'preserves a symlinked Husky directory at %s', + (linkedDir) => { + const tmp = mkdtempSync(join(tmpdir(), 'hooks-husky-symlink-')); + const originalCwd = process.cwd(); + try { + execFileSync('git', ['init'], { cwd: tmp, stdio: 'ignore' }); + execFileSync('git', ['config', 'core.hooksPath', '.husky/_'], { cwd: tmp }); + writeFileSync(join(tmp, 'package.json'), '{}'); + mkdirSync(join(tmp, '.vite-hooks')); + writeFileSync(join(tmp, '.vite-hooks', 'pre-commit'), 'exit 1\n'); + mkdirSync(join(tmp, 'external')); + if (linkedDir === '.husky/_') { + mkdirSync(join(tmp, '.husky')); + } + symlinkSync(join(tmp, 'external'), join(tmp, linkedDir), 'dir'); + process.chdir(tmp); + + expect(install().message).toBe('core.hooksPath is already set to ".husky/_", skipping'); + expect(existsSync(join(tmp, '.vite-hooks', '_'))).toBe(false); + } finally { + process.chdir(originalCwd); + rmSync(tmp, { recursive: true, force: true }); + } + }, + ); + + it.each([ + 'custom hooks path', + 'worktree-scoped Husky path', + 'global Husky path', + 'missing manifest', + 'invalid manifest', + 'no migrated hook', + 'disabled hooks', + 'Husky in an ancestor manifest', + ])('does not reclaim a Husky setup with %s', (scenario) => { + const tmp = mkdtempSync(join(tmpdir(), 'hooks-husky-preserve-')); + const originalCwd = process.cwd(); + const oldGlobal = process.env.GIT_CONFIG_GLOBAL; + try { + execFileSync('git', ['init'], { cwd: tmp, stdio: 'ignore' }); + let hooksPath = '.husky/_'; + if (scenario === 'custom hooks path') { + hooksPath = '.husky/custom'; + } + execFileSync('git', ['config', '--local', 'core.hooksPath', hooksPath], { cwd: tmp }); + writeFileSync(join(tmp, 'package.json'), '{}'); + mkdirSync(join(tmp, '.vite-hooks')); + writeFileSync(join(tmp, '.vite-hooks', 'pre-commit'), 'exit 1\n'); + process.chdir(tmp); + if (scenario === 'worktree-scoped Husky path') { + execFileSync('git', ['config', 'extensions.worktreeConfig', 'true']); + execFileSync('git', ['config', '--worktree', 'core.hooksPath', hooksPath]); + } else if (scenario === 'global Husky path') { + process.env.GIT_CONFIG_GLOBAL = join(tmp, 'global-config'); + execFileSync('git', ['config', '--global', 'core.hooksPath', hooksPath]); + execFileSync('git', ['config', '--local', '--unset', 'core.hooksPath']); + } else if (scenario === 'missing manifest') { + rmSync(join(tmp, 'package.json')); + } else if (scenario === 'invalid manifest') { + writeFileSync(join(tmp, 'package.json'), '{'); + } else if (scenario === 'no migrated hook') { + rmSync(join(tmp, '.vite-hooks', 'pre-commit')); + } else if (scenario === 'disabled hooks') { + execFileSync('git', ['config', 'vp.hooks.disabled', 'true']); + } else if (scenario === 'Husky in an ancestor manifest') { + writeFileSync( + join(tmp, 'package.json'), + JSON.stringify({ devDependencies: { husky: '*' } }), + ); + const sub = join(tmp, 'packages', 'app'); + mkdirSync(join(sub, '.vite-hooks'), { recursive: true }); + writeFileSync(join(sub, 'package.json'), '{}'); + writeFileSync(join(sub, '.vite-hooks', 'pre-commit'), 'exit 1\n'); + process.chdir(sub); + } + + expect(install().isError).toBe(false); + expect( + execFileSync('git', ['config', '--get', 'core.hooksPath'], { encoding: 'utf8' }).trim(), + ).toBe(hooksPath); + expect(existsSync(join(process.cwd(), '.vite-hooks', '_'))).toBe(false); + } finally { + if (oldGlobal === undefined) { + delete process.env.GIT_CONFIG_GLOBAL; + } else { + process.env.GIT_CONFIG_GLOBAL = oldGlobal; + } + process.chdir(originalCwd); + rmSync(tmp, { recursive: true, force: true }); + } + }); + it('refreshes an equivalent hooks path spelling', () => { const tmp = mkdtempSync(join(tmpdir(), 'hooks-equivalent-path-test-')); const originalCwd = process.cwd(); diff --git a/packages/cli/src/config/hooks.ts b/packages/cli/src/config/hooks.ts index a1232af7e0..72214deb08 100644 --- a/packages/cli/src/config/hooks.ts +++ b/packages/cli/src/config/hooks.ts @@ -5,6 +5,7 @@ import { lstatSync, mkdirSync, readdirSync, + readFileSync, realpathSync, rmSync, writeFileSync, @@ -507,6 +508,81 @@ function getScopedHooksPath(scope: 'local' | 'worktree'): string { return result.status === 0 ? result.stdout?.toString().trim() : ''; } +/** Only reclaim an abandoned, repository-local Husky setup after hooks were moved. */ +function canReplaceStaleHuskyPath(hooksPath: string, location: HooksLocation): boolean { + const normalized = normalizeHooksPath(hooksPath); + if (normalized !== '.husky' && normalized !== join('.husky', '_')) { + return false; + } + // Never override a global, worktree, or command-scoped hook policy. + const scoped = spawnSync('git', ['config', '--show-scope', '--get', 'core.hooksPath']); + if (scoped.status !== 0 || !scoped.stdout.toString().startsWith('local\t')) { + return false; + } + try { + const huskyDir = join(location.toplevel, '.husky'); + const huskyStats = lstatSync(huskyDir, { throwIfNoEntry: false }); + if ( + (huskyStats && (!huskyStats.isDirectory() || huskyStats.isSymbolicLink())) || + lstatSync(join(huskyDir, '_'), { throwIfNoEntry: false })?.isSymbolicLink() || + SUPPORTED_GIT_HOOK_NAMES.some((hook) => + lstatSync(join(huskyDir, hook), { throwIfNoEntry: false }), + ) + ) { + return false; + } + // A dispatcher alone is not evidence of a completed migration. + if ( + !SUPPORTED_GIT_HOOK_NAMES.some((hook) => + lstatSync(join(location.baseDir, location.dir, hook), { throwIfNoEntry: false })?.isFile(), + ) || + !existsSync(join(location.toplevel, 'package.json')) + ) { + return false; + } + // Include ancestor manifests when hooks are configured from a workspace package. + const relativeBase = relative(location.toplevel, location.baseDir); + const directories = [location.toplevel]; + for (const segment of relativeBase.split(sep).filter(Boolean)) { + directories.push(join(directories.at(-1)!, segment)); + } + for (const directory of directories) { + const manifest = join(directory, 'package.json'); + if (!existsSync(manifest)) { + continue; + } + const pkg = JSON.parse(readFileSync(manifest, 'utf8')) as Record; + if (!pkg || typeof pkg !== 'object' || Array.isArray(pkg) || 'husky' in pkg) { + return false; + } + for (const key of [ + 'dependencies', + 'devDependencies', + 'optionalDependencies', + 'peerDependencies', + ]) { + const dependencies = pkg[key]; + if (dependencies && typeof dependencies === 'object' && 'husky' in dependencies) { + return false; + } + } + if ( + pkg.scripts && + typeof pkg.scripts === 'object' && + Object.values(pkg.scripts).some( + (script) => typeof script === 'string' && /\bhusky\b/.test(script), + ) + ) { + return false; + } + } + } catch { + // Unreadable or invalid manifests are not evidence that Husky was removed. + return false; + } + return true; +} + function unsetScopedHooksPath(scope: 'local' | 'worktree'): InstallResult | null { const result = spawnSync('git', ['config', `--${scope}`, '--unset-all', 'core.hooksPath']); if (result.status == null) { @@ -598,7 +674,8 @@ export function install(dir?: string, options: InstallOptions = {}): InstallResu const existingHooksPath = getEffectiveHooksPath(); if ( existingHooksPath && - !hooksPathsEqual(existingHooksPath, location.target, location.toplevel) + !hooksPathsEqual(existingHooksPath, location.target, location.toplevel) && + !canReplaceStaleHuskyPath(existingHooksPath, location) ) { return { message: `core.hooksPath is already set to "${existingHooksPath}", skipping`, From 89cc04b992419ee3d3fd72233715fbd3bd4d0fac Mon Sep 17 00:00:00 2001 From: semimikoh Date: Thu, 5 Nov 2026 11:20:57 +0900 Subject: [PATCH 2/7] fix(cli): preserve remaining Husky hooks and shared worktree config --- docs/guide/commit-hooks.md | 2 +- .../cli/src/config/__tests__/hooks.spec.ts | 120 ++++++++++++++++++ packages/cli/src/config/hooks.ts | 28 +++- 3 files changed, 145 insertions(+), 5 deletions(-) diff --git a/docs/guide/commit-hooks.md b/docs/guide/commit-hooks.md index ab872c2c8d..922a86e9db 100644 --- a/docs/guide/commit-hooks.md +++ b/docs/guide/commit-hooks.md @@ -76,7 +76,7 @@ Use `--no-hooks` when you want `vp config` to leave the Git hook dispatcher unch If `core.hooksPath` points to another hook directory, `vp config` skips dispatcher installation to preserve the existing setup. Run `vp hooks status` to inspect the current configuration. -After migrating from Husky, existing clones can retain a local `core.hooksPath` of `.husky` or `.husky/_`. `vp config` and `vp hooks enable` automatically replace this stale setting when the Vite+ hooks directory contains a hook script, no hook scripts remain directly under `.husky/`, and the repository and ancestor package manifests no longer declare Husky dependencies, configuration, or scripts. The old Husky files are left unchanged. Global and worktree-scoped hook settings are preserved. +After migrating from Husky, existing clones can retain a local `core.hooksPath` of `.husky` or `.husky/_`. `vp config` and `vp hooks enable` automatically replace this stale setting when the Vite+ hooks directory contains a hook script, only generated dispatcher files remain under `.husky/`, and the repository and ancestor package manifests no longer declare Husky dependencies, configuration, or scripts. The old Husky files are left unchanged. Global and worktree-scoped hook settings are preserved. Automatic replacement is skipped when multiple worktrees are registered, because local Git configuration is shared and another checkout may still use Husky. You can also set `VP_GIT_HOOKS=0` to disable hook installation from lifecycle scripts such as `prepare` or `postinstall`. diff --git a/packages/cli/src/config/__tests__/hooks.spec.ts b/packages/cli/src/config/__tests__/hooks.spec.ts index c63746ec57..5ee2c84046 100644 --- a/packages/cli/src/config/__tests__/hooks.spec.ts +++ b/packages/cli/src/config/__tests__/hooks.spec.ts @@ -213,6 +213,126 @@ describe('install', () => { } }); + it.each([ + ['.husky', 'reference-transaction'], + ['.husky', 'post-index-change'], + ['.husky', 'custom-hook'], + ['.husky/_', 'reference-transaction'], + ['.husky/_', 'post-index-change'], + ['.husky/_', 'custom-hook'], + ])('preserves an existing %s/%s hook outside the supported-name list', (hooksPath, hook) => { + const tmp = mkdtempSync(join(tmpdir(), 'hooks-other-husky-hook-')); + const originalCwd = process.cwd(); + try { + execFileSync('git', ['init'], { cwd: tmp, stdio: 'ignore' }); + execFileSync('git', ['config', 'core.hooksPath', hooksPath], { cwd: tmp }); + writeFileSync(join(tmp, 'package.json'), '{}'); + mkdirSync(join(tmp, '.vite-hooks')); + writeFileSync(join(tmp, '.vite-hooks', 'pre-commit'), 'exit 0\n'); + mkdirSync(join(tmp, hooksPath), { recursive: true }); + const oldHook = join(tmp, hooksPath, hook); + writeFileSync(oldHook, '#!/bin/sh\necho "original hook rejected" >&2\nexit 1\n'); + chmodSync(oldHook, 0o755); + process.chdir(tmp); + + const runHook = () => spawnSync('git', ['hook', 'run', hook], { encoding: 'utf8' }); + expect(runHook().status).toBe(1); + expect(install()).toEqual({ + message: `core.hooksPath is already set to "${hooksPath}", skipping`, + isError: false, + }); + const after = runHook(); + expect(after.status).toBe(1); + expect(after.stderr).toContain('original hook rejected'); + expect(existsSync(join(tmp, '.vite-hooks', '_'))).toBe(false); + } finally { + process.chdir(originalCwd); + rmSync(tmp, { recursive: true, force: true }); + } + }); + + it.each(['original', 'linked'])( + 'does not replace shared Husky config from a migrated %s worktree', + (migratedWorktree) => { + const tmp = mkdtempSync(join(tmpdir(), 'hooks-husky-shared-config-')); + const original = join(tmp, 'original'); + const linked = join(tmp, 'linked'); + const originalCwd = process.cwd(); + try { + mkdirSync(original); + execFileSync('git', ['init'], { cwd: original, stdio: 'ignore' }); + execFileSync( + 'git', + [ + '-c', + 'user.name=Test', + '-c', + 'user.email=test@example.invalid', + '-c', + 'commit.gpgsign=false', + 'commit', + '--allow-empty', + '-m', + 'initial', + ], + { cwd: original, stdio: 'ignore' }, + ); + execFileSync('git', ['worktree', 'add', '-b', 'linked', linked], { + cwd: original, + stdio: 'ignore', + }); + const migrated = migratedWorktree === 'original' ? original : linked; + const unmigrated = migratedWorktree === 'original' ? linked : original; + execFileSync('git', ['config', '--local', 'core.hooksPath', '.husky'], { cwd: original }); + writeFileSync(join(migrated, 'package.json'), '{}'); + mkdirSync(join(migrated, '.vite-hooks')); + writeFileSync(join(migrated, '.vite-hooks', 'pre-commit'), 'exit 0\n'); + writeFileSync( + join(unmigrated, 'package.json'), + JSON.stringify({ devDependencies: { husky: '*' } }), + ); + mkdirSync(join(unmigrated, '.husky')); + const oldHook = join(unmigrated, '.husky', 'pre-commit'); + writeFileSync(oldHook, '#!/bin/sh\necho "unmigrated hook rejected" >&2\nexit 1\n'); + chmodSync(oldHook, 0o755); + const commit = () => + spawnSync( + 'git', + [ + '-c', + 'user.name=Test', + '-c', + 'user.email=test@example.invalid', + '-c', + 'commit.gpgsign=false', + 'commit', + '--allow-empty', + '-m', + 'rejected', + ], + { cwd: unmigrated, encoding: 'utf8' }, + ); + expect(commit().status).toBe(1); + process.chdir(migrated); + + expect(install()).toEqual({ + message: 'core.hooksPath is already set to ".husky", skipping', + isError: false, + }); + expect( + execFileSync('git', ['config', '--local', 'core.hooksPath'], { encoding: 'utf8' }).trim(), + ).toBe('.husky'); + const after = commit(); + expect(after.status).toBe(1); + expect(after.stderr).toContain('unmigrated hook rejected'); + expect(existsSync(join(migrated, '.vite-hooks', '_'))).toBe(false); + } finally { + process.chdir(originalCwd); + rmSync(tmp, { recursive: true, force: true }); + } + }, + ); + it.skipIf(process.platform === 'win32').each(['.husky', '.husky/_'])( 'preserves a symlinked Husky directory at %s', (linkedDir) => { diff --git a/packages/cli/src/config/hooks.ts b/packages/cli/src/config/hooks.ts index 72214deb08..76f48cc7b9 100644 --- a/packages/cli/src/config/hooks.ts +++ b/packages/cli/src/config/hooks.ts @@ -519,15 +519,35 @@ function canReplaceStaleHuskyPath(hooksPath: string, location: HooksLocation): b if (scoped.status !== 0 || !scoped.stdout.toString().startsWith('local\t')) { return false; } + // Local config is shared by linked worktrees. Inspecting only this checkout + // cannot establish whether the others have also migrated away from Husky. + const worktrees = spawnSync('git', ['worktree', 'list', '--porcelain', '-z']); + if ( + worktrees.status !== 0 || + worktrees.stdout + .toString() + .split('\0') + .filter((field) => field.startsWith('worktree ')).length !== 1 + ) { + return false; + } try { const huskyDir = join(location.toplevel, '.husky'); const huskyStats = lstatSync(huskyDir, { throwIfNoEntry: false }); + const dispatcherDir = join(huskyDir, '_'); + const dispatcherStats = lstatSync(dispatcherDir, { throwIfNoEntry: false }); if ( (huskyStats && (!huskyStats.isDirectory() || huskyStats.isSymbolicLink())) || - lstatSync(join(huskyDir, '_'), { throwIfNoEntry: false })?.isSymbolicLink() || - SUPPORTED_GIT_HOOK_NAMES.some((hook) => - lstatSync(join(huskyDir, hook), { throwIfNoEntry: false }), - ) + (dispatcherStats && (!dispatcherStats.isDirectory() || dispatcherStats.isSymbolicLink())) + ) { + return false; + } + // Git can execute hook names outside Vite+'s supported set (including + // arbitrary names through `git hook run`). Only ignore generated files. + const generatedFiles = new Set(['h', 'husky.sh', '.gitignore', ...SUPPORTED_GIT_HOOK_NAMES]); + if ( + (huskyStats && readdirSync(huskyDir).some((name) => name !== '_')) || + (dispatcherStats && readdirSync(dispatcherDir).some((name) => !generatedFiles.has(name))) ) { return false; } From 34f54a69998c2bda70bab852de54d06f43079731 Mon Sep 17 00:00:00 2001 From: semimikoh Date: Thu, 5 Nov 2026 12:48:00 +0900 Subject: [PATCH 3/7] test(cli): use native hook names for Git compatibility --- packages/cli/src/config/__tests__/hooks.spec.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/cli/src/config/__tests__/hooks.spec.ts b/packages/cli/src/config/__tests__/hooks.spec.ts index 5ee2c84046..94b0362a26 100644 --- a/packages/cli/src/config/__tests__/hooks.spec.ts +++ b/packages/cli/src/config/__tests__/hooks.spec.ts @@ -216,10 +216,10 @@ describe('install', () => { it.each([ ['.husky', 'reference-transaction'], ['.husky', 'post-index-change'], - ['.husky', 'custom-hook'], + ['.husky', 'pre-receive'], ['.husky/_', 'reference-transaction'], ['.husky/_', 'post-index-change'], - ['.husky/_', 'custom-hook'], + ['.husky/_', 'pre-receive'], ])('preserves an existing %s/%s hook outside the supported-name list', (hooksPath, hook) => { const tmp = mkdtempSync(join(tmpdir(), 'hooks-other-husky-hook-')); const originalCwd = process.cwd(); @@ -236,7 +236,9 @@ describe('install', () => { process.chdir(tmp); const runHook = () => spawnSync('git', ['hook', 'run', hook], { encoding: 'utf8' }); - expect(runHook().status).toBe(1); + const before = runHook(); + expect(before.status).toBe(1); + expect(before.stderr).toContain('original hook rejected'); expect(install()).toEqual({ message: `core.hooksPath is already set to "${hooksPath}", skipping`, isError: false, From 7131c454c7f1a68610d159e0d86b567795543c81 Mon Sep 17 00:00:00 2001 From: semimikoh Date: Mon, 9 Nov 2026 10:54:33 +0900 Subject: [PATCH 4/7] fix(cli): verify stale Husky generated files before takeover --- .../__tests__/fixtures/husky-9.1.7/LICENSE | 21 ++ .../config/__tests__/fixtures/husky-9.1.7/h | 22 +++ .../__tests__/fixtures/husky-9.1.7/husky.sh | 9 + .../cli/src/config/__tests__/hooks.spec.ts | 184 +++++++++++++----- packages/cli/src/config/hooks.ts | 35 +++- 5 files changed, 224 insertions(+), 47 deletions(-) create mode 100644 packages/cli/src/config/__tests__/fixtures/husky-9.1.7/LICENSE create mode 100644 packages/cli/src/config/__tests__/fixtures/husky-9.1.7/h create mode 100644 packages/cli/src/config/__tests__/fixtures/husky-9.1.7/husky.sh diff --git a/packages/cli/src/config/__tests__/fixtures/husky-9.1.7/LICENSE b/packages/cli/src/config/__tests__/fixtures/husky-9.1.7/LICENSE new file mode 100644 index 0000000000..049c9dc4e8 --- /dev/null +++ b/packages/cli/src/config/__tests__/fixtures/husky-9.1.7/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 typicode + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/cli/src/config/__tests__/fixtures/husky-9.1.7/h b/packages/cli/src/config/__tests__/fixtures/husky-9.1.7/h new file mode 100644 index 0000000000..bf7c896408 --- /dev/null +++ b/packages/cli/src/config/__tests__/fixtures/husky-9.1.7/h @@ -0,0 +1,22 @@ +#!/usr/bin/env sh +[ "$HUSKY" = "2" ] && set -x +n=$(basename "$0") +s=$(dirname "$(dirname "$0")")/$n + +[ ! -f "$s" ] && exit 0 + +if [ -f "$HOME/.huskyrc" ]; then + echo "husky - '~/.huskyrc' is DEPRECATED, please move your code to ~/.config/husky/init.sh" +fi +i="${XDG_CONFIG_HOME:-$HOME/.config}/husky/init.sh" +[ -f "$i" ] && . "$i" + +[ "${HUSKY-}" = "0" ] && exit 0 + +export PATH="node_modules/.bin:$PATH" +sh -e "$s" "$@" +c=$? + +[ $c != 0 ] && echo "husky - $n script failed (code $c)" +[ $c = 127 ] && echo "husky - command not found in PATH=$PATH" +exit $c diff --git a/packages/cli/src/config/__tests__/fixtures/husky-9.1.7/husky.sh b/packages/cli/src/config/__tests__/fixtures/husky-9.1.7/husky.sh new file mode 100644 index 0000000000..f9d0637909 --- /dev/null +++ b/packages/cli/src/config/__tests__/fixtures/husky-9.1.7/husky.sh @@ -0,0 +1,9 @@ +echo "husky - DEPRECATED + +Please remove the following two lines from $0: + +#!/usr/bin/env sh +. \"\$(dirname -- \"\$0\")/_/husky.sh\" + +They WILL FAIL in v10.0.0 +" \ No newline at end of file diff --git a/packages/cli/src/config/__tests__/hooks.spec.ts b/packages/cli/src/config/__tests__/hooks.spec.ts index 94b0362a26..aac97cf9ff 100644 --- a/packages/cli/src/config/__tests__/hooks.spec.ts +++ b/packages/cli/src/config/__tests__/hooks.spec.ts @@ -18,6 +18,7 @@ import { join, resolve } from 'node:path'; import { describe, expect, it } from 'vitest'; import { + HOOK_STUB_SCRIPT, disable, enable, hookScript, @@ -27,6 +28,9 @@ import { status, } from '../hooks.js'; +// Unmodified upstream dispatcher; retained to verify safe migration against real Husky output. +const HUSKY_DISPATCHER = readFileSync(new URL('./fixtures/husky-9.1.7/h', import.meta.url), 'utf8'); + function countDirnameCalls(script: string): number { // Count nested dirname calls in the `d=...` line const match = script.match(/^d=(.+)$/m); @@ -138,54 +142,144 @@ describe('install', () => { ['.husky', '.vite-hooks'], ['.husky/_', '.vite-hooks'], ['./.husky/_/', '.vite-hooks'], + ['.husky/_', '.vite-hooks', '\r\n'], ['.husky/_', '.custom-hooks'], ['.husky/_', 'packages/app/.vite-hooks'], - ])('takes over a stale local Husky path %s after migration to %s', (hooksPath, hooksDir) => { - const tmp = mkdtempSync(join(tmpdir(), 'hooks-husky-migration-')); - const originalCwd = process.cwd(); - try { - execFileSync('git', ['init'], { cwd: tmp, stdio: 'ignore' }); - execFileSync('git', ['config', 'core.hooksPath', hooksPath], { cwd: tmp }); - writeFileSync( - join(tmp, 'package.json'), - JSON.stringify({ scripts: { prepare: 'vp config' } }), - ); - mkdirSync(join(tmp, '.husky', '_'), { recursive: true }); - const oldDispatcher = join(tmp, '.husky', '_', 'h'); - writeFileSync(oldDispatcher, 'old husky dispatcher\n'); - mkdirSync(join(tmp, hooksDir), { recursive: true }); - writeFileSync(join(tmp, hooksDir, 'commit-msg'), 'exit 1\n'); - process.chdir(tmp); + ])( + 'takes over a stale local Husky path %s after migration to %s', + (hooksPath, hooksDir, newline = '\n') => { + const tmp = mkdtempSync(join(tmpdir(), 'hooks-husky-migration-')); + const originalCwd = process.cwd(); + try { + execFileSync('git', ['init'], { cwd: tmp, stdio: 'ignore' }); + execFileSync('git', ['config', 'core.hooksPath', hooksPath], { cwd: tmp }); + writeFileSync( + join(tmp, 'package.json'), + JSON.stringify({ scripts: { prepare: 'vp config' } }), + ); + mkdirSync(join(tmp, '.husky', '_'), { recursive: true }); + const oldDispatcher = join(tmp, '.husky', '_', 'h'); + const oldContents = HUSKY_DISPATCHER.replaceAll('\n', newline); + writeFileSync(oldDispatcher, oldContents); + writeFileSync( + join(tmp, '.husky', '_', 'pre-commit'), + HOOK_STUB_SCRIPT.replaceAll('\n', newline), + ); + writeFileSync(join(tmp, '.husky', '_', '.gitignore'), '*'); + writeFileSync( + join(tmp, '.husky', '_', 'husky.sh'), + readFileSync( + new URL('./fixtures/husky-9.1.7/husky.sh', import.meta.url), + 'utf8', + ).replaceAll('\n', newline), + ); + mkdirSync(join(tmp, hooksDir), { recursive: true }); + writeFileSync(join(tmp, hooksDir, 'commit-msg'), 'exit 1\n'); + process.chdir(tmp); - expect(install(hooksDir)).toEqual({ message: '', isError: false }); - expect( - execFileSync('git', ['config', '--get', 'core.hooksPath'], { encoding: 'utf8' }).trim(), - ).toBe(`${hooksDir}/_`); - expect(readFileSync(oldDispatcher, 'utf8')).toBe('old husky dispatcher\n'); - // A real commit must invoke the migrated hook, even in the old clone. - const commit = spawnSync( - 'git', - [ - '-c', - 'user.name=Test', - '-c', - 'user.email=test@example.invalid', - 'commit', - '--allow-empty', - '-m', - 'bad message', - ], - { encoding: 'utf8' }, - ); - expect(commit.status).toBe(1); - expect(commit.stdout + commit.stderr).toContain('commit-msg script failed'); - expect(enable().isError).toBe(false); - expect(install()).toEqual({ message: '', isError: false }); - } finally { - process.chdir(originalCwd); - rmSync(tmp, { recursive: true, force: true }); - } - }); + expect(install(hooksDir)).toEqual({ message: '', isError: false }); + expect( + execFileSync('git', ['config', '--get', 'core.hooksPath'], { encoding: 'utf8' }).trim(), + ).toBe(`${hooksDir}/_`); + expect(readFileSync(oldDispatcher, 'utf8')).toBe(oldContents); + // A real commit must invoke the migrated hook, even in the old clone. + const commit = spawnSync( + 'git', + [ + '-c', + 'user.name=Test', + '-c', + 'user.email=test@example.invalid', + 'commit', + '--allow-empty', + '-m', + 'bad message', + ], + { encoding: 'utf8' }, + ); + expect(commit.status).toBe(1); + expect(commit.stdout + commit.stderr).toContain('commit-msg script failed'); + expect(enable().isError).toBe(false); + expect(install()).toEqual({ message: '', isError: false }); + } finally { + process.chdir(originalCwd); + rmSync(tmp, { recursive: true, force: true }); + } + }, + ); + + it + .skipIf(process.platform === 'win32') + .each(['custom supported hook', 'symlinked hook', 'custom dispatcher'])( + 'preserves a rejecting %s during install and enable', + (kind) => { + const tmp = mkdtempSync(join(tmpdir(), 'hooks-custom-husky-')); + const originalCwd = process.cwd(); + try { + execFileSync('git', ['init'], { cwd: tmp, stdio: 'ignore' }); + execFileSync('git', ['config', 'core.hooksPath', '.husky/_'], { cwd: tmp }); + writeFileSync( + join(tmp, 'package.json'), + JSON.stringify({ scripts: { prepare: 'vp config' } }), + ); + const internal = join(tmp, '.husky', '_'); + mkdirSync(internal, { recursive: true }); + const rejectingScript = '#!/bin/sh\necho "original hook rejected" >&2\nexit 1\n'; + writeFileSync(join(internal, 'h'), HUSKY_DISPATCHER); + const hook = join(internal, 'pre-commit'); + if (kind === 'symlinked hook') { + const external = join(tmp, 'reject-commit'); + writeFileSync(external, rejectingScript, { mode: 0o755 }); + symlinkSync(external, hook); + } else if (kind === 'custom dispatcher') { + writeFileSync(hook, HOOK_STUB_SCRIPT, { mode: 0o755 }); + writeFileSync(join(internal, 'h'), rejectingScript); + } else { + writeFileSync(hook, rejectingScript, { mode: 0o755 }); + } + mkdirSync(join(tmp, '.vite-hooks')); + writeFileSync(join(tmp, '.vite-hooks', 'commit-msg'), 'exit 0\n'); + process.chdir(tmp); + const assertCommitRejected = () => { + const result = spawnSync( + 'git', + [ + '-c', + 'user.name=Test', + '-c', + 'user.email=test@example.invalid', + '-c', + 'commit.gpgsign=false', + 'commit', + '--allow-empty', + '-m', + 'test', + ], + { cwd: tmp, encoding: 'utf8' }, + ); + expect(result.status).toBe(1); + expect(result.stderr).toContain('original hook rejected'); + }; + assertCommitRejected(); + for (const setup of [install, enable]) { + expect(setup()).toEqual({ + message: 'core.hooksPath is already set to ".husky/_", skipping', + isError: false, + }); + expect( + execFileSync('git', ['config', '--get', 'core.hooksPath'], { + encoding: 'utf8', + }).trim(), + ).toBe('.husky/_'); + expect(existsSync(join(tmp, '.vite-hooks', '_'))).toBe(false); + assertCommitRejected(); + } + } finally { + process.chdir(originalCwd); + rmSync(tmp, { recursive: true, force: true }); + } + }, + ); it.each([ ['production Husky dependency', { dependencies: { husky: '^9.0.0' } }], diff --git a/packages/cli/src/config/hooks.ts b/packages/cli/src/config/hooks.ts index 76f48cc7b9..11a7264933 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 { createHash } from 'node:crypto'; import { chmodSync, existsSync, @@ -508,6 +509,36 @@ function getScopedHooksPath(scope: 'local' | 'worktree'): string { return result.status === 0 ? result.stdout?.toString().trim() : ''; } +// Exact Husky 9.1.7 generated contents, with CRLF and a final newline normalized. +// https://github.com/typicode/husky/blob/v9.1.7/husky +// https://github.com/typicode/husky/blob/v9.1.7/index.js +// Unknown versions are deliberately preserved rather than guessing that their +// dispatcher is safe to abandon. +const HUSKY_GENERATED_SCRIPT_HASHES: Readonly> = { + h: 'd80994934f440d579303d6590fa1ce7bc0d31c650179d2089dea5191d1ab10d1', + 'husky.sh': '21122903fca7209a13c991e5be68780636e28f1b8f0ae7ea07ed0065dfe37268', +}; + +function isUnmodifiedHuskyFile(directory: string, name: string): boolean { + const path = join(directory, name); + const stats = lstatSync(path); + if (!stats.isFile() || stats.isSymbolicLink() || stats.nlink !== 1) { + return false; + } + const contents = readFileSync(path, 'utf8').replace(/\r\n/g, '\n').replace(/\n$/, ''); + if (name === '.gitignore') { + return contents === '*'; + } + if (SUPPORTED_GIT_HOOK_NAMES.includes(name)) { + return contents === HOOK_STUB_SCRIPT; + } + const expectedHash = HUSKY_GENERATED_SCRIPT_HASHES[name]; + return ( + expectedHash !== undefined && + createHash('sha256').update(contents).digest('hex') === expectedHash + ); +} + /** Only reclaim an abandoned, repository-local Husky setup after hooks were moved. */ function canReplaceStaleHuskyPath(hooksPath: string, location: HooksLocation): boolean { const normalized = normalizeHooksPath(hooksPath); @@ -544,10 +575,10 @@ function canReplaceStaleHuskyPath(hooksPath: string, location: HooksLocation): b } // Git can execute hook names outside Vite+'s supported set (including // arbitrary names through `git hook run`). Only ignore generated files. - const generatedFiles = new Set(['h', 'husky.sh', '.gitignore', ...SUPPORTED_GIT_HOOK_NAMES]); if ( (huskyStats && readdirSync(huskyDir).some((name) => name !== '_')) || - (dispatcherStats && readdirSync(dispatcherDir).some((name) => !generatedFiles.has(name))) + (dispatcherStats && + readdirSync(dispatcherDir).some((name) => !isUnmodifiedHuskyFile(dispatcherDir, name))) ) { return false; } From c695c5400075e3083c3d9ec761b0f53ec1bc4b12 Mon Sep 17 00:00:00 2001 From: semimikoh Date: Mon, 16 Nov 2026 12:25:31 +0900 Subject: [PATCH 5/7] fix(cli): add explicit replacement for stale Husky hooks paths --- .../snapshots/command_hooks_help.global.md | 4 + .../snapshots/command_hooks_help.local.md | 4 + .../command_hooks_replace_husky/package.json | 7 + .../snapshots.toml | 32 +++ ...ommand_hooks_recover_empty_husky.global.md | 17 ++ ...command_hooks_recover_empty_husky.local.md | 17 ++ .../command_hooks_replace_husky.global.md | 125 +++++++++ .../command_hooks_replace_husky.local.md | 125 +++++++++ docs/guide/commit-hooks.md | 14 +- packages/cli/binding/index.d.cts | 1 + .../src/js_command_args/commands/hooks.rs | 38 ++- .../cli/src/__tests__/js-command-args.spec.ts | 5 + .../cli/src/config/__tests__/hooks.spec.ts | 263 +++++++++++++++--- packages/cli/src/config/hooks.ts | 141 ++++++---- packages/cli/src/hooks/bin.ts | 2 +- 15 files changed, 694 insertions(+), 101 deletions(-) create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/package.json create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots.toml create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_recover_empty_husky.global.md create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_recover_empty_husky.local.md create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_replace_husky.global.md create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_replace_husky.local.md diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_help/snapshots/command_hooks_help.global.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_help/snapshots/command_hooks_help.global.md index ef60f7dec4..40d75d923e 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_help/snapshots/command_hooks_help.global.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_help/snapshots/command_hooks_help.global.md @@ -23,6 +23,7 @@ Environment: Examples: vp hooks enable vp hooks enable --hooks-dir .custom-hooks + vp hooks enable --replace-husky vp hooks disable vp hooks status @@ -52,6 +53,7 @@ Environment: Examples: vp hooks enable vp hooks enable --hooks-dir .custom-hooks + vp hooks enable --replace-husky vp hooks disable vp hooks status @@ -70,6 +72,7 @@ Install or refresh the hook dispatcher (sets core.hooksPath) Options: --hooks-dir Custom hooks directory (default: .vite-hooks, or last used) -h, --help Show this help message + --replace-husky Replace a local Husky hooks path after migrating custom checks (old files are preserved but no longer run) Documentation: https://viteplus.dev/guide/commit-hooks ``` @@ -97,6 +100,7 @@ Environment: Examples: vp hooks enable vp hooks enable --hooks-dir .custom-hooks + vp hooks enable --replace-husky vp hooks disable vp hooks status diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_help/snapshots/command_hooks_help.local.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_help/snapshots/command_hooks_help.local.md index ef60f7dec4..40d75d923e 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_help/snapshots/command_hooks_help.local.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_help/snapshots/command_hooks_help.local.md @@ -23,6 +23,7 @@ Environment: Examples: vp hooks enable vp hooks enable --hooks-dir .custom-hooks + vp hooks enable --replace-husky vp hooks disable vp hooks status @@ -52,6 +53,7 @@ Environment: Examples: vp hooks enable vp hooks enable --hooks-dir .custom-hooks + vp hooks enable --replace-husky vp hooks disable vp hooks status @@ -70,6 +72,7 @@ Install or refresh the hook dispatcher (sets core.hooksPath) Options: --hooks-dir Custom hooks directory (default: .vite-hooks, or last used) -h, --help Show this help message + --replace-husky Replace a local Husky hooks path after migrating custom checks (old files are preserved but no longer run) Documentation: https://viteplus.dev/guide/commit-hooks ``` @@ -97,6 +100,7 @@ Environment: Examples: vp hooks enable vp hooks enable --hooks-dir .custom-hooks + vp hooks enable --replace-husky vp hooks disable vp hooks status diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/package.json new file mode 100644 index 0000000000..90baa89bb4 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/package.json @@ -0,0 +1,7 @@ +{ + "name": "hooks-replace-husky", + "private": true, + "scripts": { + "prepare": "vp config" + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots.toml new file mode 100644 index 0000000000..6827a9c90c --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots.toml @@ -0,0 +1,32 @@ +[[case]] +name = "command_hooks_replace_husky" +vp = ["local", "global"] +steps = [ + { argv = ["git", "init"], snapshot = false }, + { argv = ["git", "config", "core.hooksPath", ".husky/_"], snapshot = false }, + { argv = ["vpt", "write-file", ".husky/_/pre-commit", "#!/bin/sh\necho original-check-rejected >&2\nexit 1\n"], snapshot = false }, + { argv = ["vpt", "write-file", ".vite-hooks/commit-msg", "echo migrated-check-rejected >&2\nexit 1\n"], snapshot = false }, + { argv = ["vp", "config", "--no-agent"], tty = false, comment = "preserve non-empty Husky directory and explain recovery" }, + { argv = ["vp", "hooks", "enable"], comment = "ordinary enable also preserves old hooks" }, + { argv = ["git", "config", "--local", "core.hooksPath"], comment = "Husky remains active until explicit replacement" }, + { argv = ["vp", "hooks", "enable", "--replace-husky"], envs = [["VP_GIT_HOOKS", "0"]], comment = "explicit replacement honors environment opt-out" }, + { argv = ["git", "config", "--local", "core.hooksPath"], comment = "opt-out left the path unchanged" }, + { argv = ["vp", "hooks", "enable", "--replace-husky"], comment = "explicitly activate the migrated hooks, explaining the old hooks no longer run" }, + { argv = ["git", "config", "--local", "core.hooksPath"], comment = "Vite+ dispatcher is now active" }, + { argv = ["vpt", "print-file", ".husky/_/pre-commit"], comment = "old Husky script was preserved" }, + { argv = ["vpt", "print-file", "package.json"], comment = "prepare does not acquire the explicit replacement flag" }, + { argv = ["git", "-c", "user.name=Test", "-c", "user.email=test@example.invalid", "-c", "commit.gpgsign=false", "commit", "--allow-empty", "-m", "test"], comment = "the migrated check rejects the commit", continue-on-failure = true }, + { argv = ["vp", "hooks", "disable", "--replace-husky"], comment = "the replacement option is enable-only", continue-on-failure = true }, +] + +[[case]] +name = "command_hooks_recover_empty_husky" +vp = ["local", "global"] +steps = [ + { argv = ["git", "init"], snapshot = false }, + { argv = ["git", "config", "core.hooksPath", ".husky/_"], snapshot = false }, + { argv = ["vpt", "mkdir", ".husky/_"], snapshot = false }, + { argv = ["vpt", "write-file", ".vite-hooks/pre-commit", "exit 0\n"], snapshot = false }, + { argv = ["vp", "config", "--no-agent"], tty = false, comment = "recover an empty old directory automatically" }, + { argv = ["git", "config", "--local", "core.hooksPath"], comment = "Vite+ hooks are active without an explicit override" }, +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_recover_empty_husky.global.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_recover_empty_husky.global.md new file mode 100644 index 0000000000..c5f5b43b7c --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_recover_empty_husky.global.md @@ -0,0 +1,17 @@ +# command_hooks_recover_empty_husky + +## `git init` + + +## `git config core.hooksPath .husky/_` + + +## `vpt mkdir .husky/_` + +**Exit code:** 1 + +``` +No such file or directory (os error 2) +``` + +*(remaining steps skipped: step failed)* diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_recover_empty_husky.local.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_recover_empty_husky.local.md new file mode 100644 index 0000000000..c5f5b43b7c --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_recover_empty_husky.local.md @@ -0,0 +1,17 @@ +# command_hooks_recover_empty_husky + +## `git init` + + +## `git config core.hooksPath .husky/_` + + +## `vpt mkdir .husky/_` + +**Exit code:** 1 + +``` +No such file or directory (os error 2) +``` + +*(remaining steps skipped: step failed)* diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_replace_husky.global.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_replace_husky.global.md new file mode 100644 index 0000000000..8bcb997cf4 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_replace_husky.global.md @@ -0,0 +1,125 @@ +# command_hooks_replace_husky + +## `git init` + + +## `git config core.hooksPath .husky/_` + + +## `vpt write-file .husky/_/pre-commit '#'\!'/bin/sh +echo original-check-rejected >&2 +exit 1 +'` + + +## `vpt write-file .vite-hooks/commit-msg 'echo migrated-check-rejected >&2 +exit 1 +'` + + +## `vp config --no-agent` + +preserve non-empty Husky directory and explain recovery + +``` +core.hooksPath is already set to ".husky/_", skipping. Vite+ hooks at .vite-hooks are not active. Migrate any custom Husky checks, then run `vp hooks enable --replace-husky` (with the same --hooks-dir if customized). Switching stops running hooks from ".husky/_"; the old files are preserved. +``` + +## `vp hooks enable` + +ordinary enable also preserves old hooks + +``` +core.hooksPath is already set to ".husky/_", skipping. Vite+ hooks at .vite-hooks are not active. Migrate any custom Husky checks, then run `vp hooks enable --replace-husky` (with the same --hooks-dir if customized). Switching stops running hooks from ".husky/_"; the old files are preserved. +``` + +## `git config --local core.hooksPath` + +Husky remains active until explicit replacement + +``` +.husky/_ +``` + +## `VP_GIT_HOOKS=0 vp hooks enable --replace-husky` + +explicit replacement honors environment opt-out + +``` +skip install (git hooks disabled) +``` + +## `git config --local core.hooksPath` + +opt-out left the path unchanged + +``` +.husky/_ +``` + +## `vp hooks enable --replace-husky` + +explicitly activate the migrated hooks, explaining the old hooks no longer run + +``` +Git hook dispatcher installed at .vite-hooks/_. Replaced core.hooksPath ".husky/_". Old Husky files were preserved, but hooks from ".husky/_" no longer run. Custom checks must be migrated to .vite-hooks. +``` + +## `git config --local core.hooksPath` + +Vite+ dispatcher is now active + +``` +.vite-hooks/_ +``` + +## `vpt print-file .husky/_/pre-commit` + +old Husky script was preserved + +``` +#!/bin/sh +echo original-check-rejected >&2 +exit 1 +``` + +## `vpt print-file package.json` + +prepare does not acquire the explicit replacement flag + +``` +{ + "name": "hooks-replace-husky", + "private": true, + "scripts": { + "prepare": "vp config" + } +} +``` + +## `git -c user.name=Test -c user.email=test@example.invalid -c commit.gpgsign=false commit --allow-empty -m test` + +the migrated check rejects the commit + +**Exit code:** 1 + +``` +migrated-check-rejected +VITE+ - commit-msg script failed (code 1) +``` + +## `vp hooks disable --replace-husky` + +the replacement option is enable-only + +**Exit code:** 1 + +``` +VITE+ - The Unified Toolchain for the Web + +error: unexpected argument '--replace-husky' found + +Usage: vp hooks disable [OPTIONS] + +For more information, try '--help'. +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_replace_husky.local.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_replace_husky.local.md new file mode 100644 index 0000000000..8bcb997cf4 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_replace_husky.local.md @@ -0,0 +1,125 @@ +# command_hooks_replace_husky + +## `git init` + + +## `git config core.hooksPath .husky/_` + + +## `vpt write-file .husky/_/pre-commit '#'\!'/bin/sh +echo original-check-rejected >&2 +exit 1 +'` + + +## `vpt write-file .vite-hooks/commit-msg 'echo migrated-check-rejected >&2 +exit 1 +'` + + +## `vp config --no-agent` + +preserve non-empty Husky directory and explain recovery + +``` +core.hooksPath is already set to ".husky/_", skipping. Vite+ hooks at .vite-hooks are not active. Migrate any custom Husky checks, then run `vp hooks enable --replace-husky` (with the same --hooks-dir if customized). Switching stops running hooks from ".husky/_"; the old files are preserved. +``` + +## `vp hooks enable` + +ordinary enable also preserves old hooks + +``` +core.hooksPath is already set to ".husky/_", skipping. Vite+ hooks at .vite-hooks are not active. Migrate any custom Husky checks, then run `vp hooks enable --replace-husky` (with the same --hooks-dir if customized). Switching stops running hooks from ".husky/_"; the old files are preserved. +``` + +## `git config --local core.hooksPath` + +Husky remains active until explicit replacement + +``` +.husky/_ +``` + +## `VP_GIT_HOOKS=0 vp hooks enable --replace-husky` + +explicit replacement honors environment opt-out + +``` +skip install (git hooks disabled) +``` + +## `git config --local core.hooksPath` + +opt-out left the path unchanged + +``` +.husky/_ +``` + +## `vp hooks enable --replace-husky` + +explicitly activate the migrated hooks, explaining the old hooks no longer run + +``` +Git hook dispatcher installed at .vite-hooks/_. Replaced core.hooksPath ".husky/_". Old Husky files were preserved, but hooks from ".husky/_" no longer run. Custom checks must be migrated to .vite-hooks. +``` + +## `git config --local core.hooksPath` + +Vite+ dispatcher is now active + +``` +.vite-hooks/_ +``` + +## `vpt print-file .husky/_/pre-commit` + +old Husky script was preserved + +``` +#!/bin/sh +echo original-check-rejected >&2 +exit 1 +``` + +## `vpt print-file package.json` + +prepare does not acquire the explicit replacement flag + +``` +{ + "name": "hooks-replace-husky", + "private": true, + "scripts": { + "prepare": "vp config" + } +} +``` + +## `git -c user.name=Test -c user.email=test@example.invalid -c commit.gpgsign=false commit --allow-empty -m test` + +the migrated check rejects the commit + +**Exit code:** 1 + +``` +migrated-check-rejected +VITE+ - commit-msg script failed (code 1) +``` + +## `vp hooks disable --replace-husky` + +the replacement option is enable-only + +**Exit code:** 1 + +``` +VITE+ - The Unified Toolchain for the Web + +error: unexpected argument '--replace-husky' found + +Usage: vp hooks disable [OPTIONS] + +For more information, try '--help'. +``` diff --git a/docs/guide/commit-hooks.md b/docs/guide/commit-hooks.md index 922a86e9db..b11167c989 100644 --- a/docs/guide/commit-hooks.md +++ b/docs/guide/commit-hooks.md @@ -76,7 +76,19 @@ Use `--no-hooks` when you want `vp config` to leave the Git hook dispatcher unch If `core.hooksPath` points to another hook directory, `vp config` skips dispatcher installation to preserve the existing setup. Run `vp hooks status` to inspect the current configuration. -After migrating from Husky, existing clones can retain a local `core.hooksPath` of `.husky` or `.husky/_`. `vp config` and `vp hooks enable` automatically replace this stale setting when the Vite+ hooks directory contains a hook script, only generated dispatcher files remain under `.husky/`, and the repository and ancestor package manifests no longer declare Husky dependencies, configuration, or scripts. The old Husky files are left unchanged. Global and worktree-scoped hook settings are preserved. Automatic replacement is skipped when multiple worktrees are registered, because local Git configuration is shared and another checkout may still use Husky. +After migrating from Husky, existing clones can retain a local `core.hooksPath` of `.husky` or `.husky/_`. `vp config` and `vp hooks enable` automatically replace this stale setting only when the old directory is missing or empty, no Husky hook files remain, the Vite+ hooks directory contains a hook script, and the repository and ancestor package manifests no longer declare Husky dependencies, configuration, or scripts. + +If old files remain, both commands preserve the configuration and report that the migrated Vite+ hooks are not active. This includes unmodified Husky-generated files left in existing clones after pulling a migration commit. First migrate any custom checks you want to retain, remove Husky dependencies and lifecycle commands, then explicitly switch this clone: + +```bash +vp hooks enable --replace-husky +# If your migrated hooks use a custom directory: +vp hooks enable --replace-husky --hooks-dir .custom-hooks +``` + +The explicit option changes `core.hooksPath` and preserves the old files. **Hooks from the old directory no longer run after switching.** The replacement notice explains this change. Do not add `--replace-husky` to `prepare` or other lifecycle scripts; it is a one-time choice for the current clone. + +Both automatic and explicit replacement preserve global and worktree-scoped hook settings and refuse unsafe paths. Replacement is skipped when multiple worktrees are registered, because local Git configuration is shared and another checkout may still use Husky. Environment opt-outs such as `VP_GIT_HOOKS=0` and `HUSKY=0` remain effective even with `--replace-husky`. You can also set `VP_GIT_HOOKS=0` to disable hook installation from lifecycle scripts such as `prepare` or `postinstall`. diff --git a/packages/cli/binding/index.d.cts b/packages/cli/binding/index.d.cts index 42d608349c..feeff34dff 100644 --- a/packages/cli/binding/index.d.cts +++ b/packages/cli/binding/index.d.cts @@ -3811,6 +3811,7 @@ export declare function hasConfigKey(viteConfigPath: string, configKey: string): export interface HooksArgs { command: 'enable' | 'disable' | 'status'; hooksDir?: string; + replaceHusky: boolean; } /** Check inherited `.gitignore` rules without requiring the directory to exist. */ diff --git a/packages/cli/binding/src/js_command_args/commands/hooks.rs b/packages/cli/binding/src/js_command_args/commands/hooks.rs index 00599ba14b..f87d6d2874 100644 --- a/packages/cli/binding/src/js_command_args/commands/hooks.rs +++ b/packages/cli/binding/src/js_command_args/commands/hooks.rs @@ -14,7 +14,7 @@ struct HooksCliArgs { enum HooksSubcommand { /// Install or refresh the hook dispatcher (sets core.hooksPath) #[command(disable_help_flag = true)] - Enable(HooksActionArgs), + Enable(HooksEnableArgs), /// Disable hooks: unset core.hooksPath, remove /_, persist preference #[command(disable_help_flag = true)] Disable(HooksActionArgs), @@ -23,6 +23,18 @@ enum HooksSubcommand { Status(HooksActionArgs), } +#[derive(Debug, Args)] +struct HooksEnableArgs { + #[command(flatten)] + action: HooksActionArgs, + + #[arg( + long, + help = "Replace a local Husky hooks path after migrating custom checks (old files are preserved but no longer run)" + )] + replace_husky: bool, +} + #[derive(Debug, Args)] struct HooksActionArgs { #[arg( @@ -53,16 +65,17 @@ pub struct HooksArgs { #[napi(ts_type = "'enable' | 'disable' | 'status'")] pub command: String, pub hooks_dir: Option, + pub replace_husky: bool, } impl From for HooksArgs { fn from(value: HooksCliArgs) -> Self { - let (command, args) = match value.command { - HooksSubcommand::Enable(args) => ("enable", args), - HooksSubcommand::Disable(args) => ("disable", args), - HooksSubcommand::Status(args) => ("status", args), + let (command, args, replace_husky) = match value.command { + HooksSubcommand::Enable(args) => ("enable", args.action, args.replace_husky), + HooksSubcommand::Disable(args) => ("disable", args, false), + HooksSubcommand::Status(args) => ("status", args, false), }; - Self { command: command.into(), hooks_dir: args.hooks_dir } + Self { command: command.into(), hooks_dir: args.hooks_dir, replace_husky } } } @@ -111,6 +124,7 @@ pub fn parse_hooks_args(argv: Vec) -> ParseHooksArgsOutcome { lines: vec![ " vp hooks enable".into(), " vp hooks enable --hooks-dir .custom-hooks".into(), + " vp hooks enable --replace-husky".into(), " vp hooks disable".into(), " vp hooks status".into(), ], @@ -145,7 +159,19 @@ mod tests { let args = parsed(&[name, "--hooks-dir", ".custom"]); assert_eq!(args.command, name); assert_eq!(args.hooks_dir.as_deref(), Some(".custom")); + assert!(!args.replace_husky); + } + } + + #[test] + fn replacement_is_only_available_for_enable() { + let args = parsed(&["enable", "--replace-husky", "--hooks-dir", ".custom"]); + assert!(args.replace_husky); + assert_eq!(args.hooks_dir.as_deref(), Some(".custom")); + for name in ["disable", "status"] { + assert_eq!(parse_error(&[name, "--replace-husky"]).kind, "unknown-argument"); } + assert_eq!(parse_error(&["--replace-husky", "enable"]).kind, "unknown-argument"); } #[test] diff --git a/packages/cli/src/__tests__/js-command-args.spec.ts b/packages/cli/src/__tests__/js-command-args.spec.ts index c045d226ad..4cc3140457 100644 --- a/packages/cli/src/__tests__/js-command-args.spec.ts +++ b/packages/cli/src/__tests__/js-command-args.spec.ts @@ -60,6 +60,11 @@ describe('JavaScript command NAPI arguments', () => { expect(expectParsed(parseHooksArgs(['enable', '--hooks-dir', '.custom']))).toEqual({ command: 'enable', hooksDir: '.custom', + replaceHusky: false, + }); + expect(expectParsed(parseHooksArgs(['enable', '--replace-husky']))).toEqual({ + command: 'enable', + replaceHusky: true, }); }); diff --git a/packages/cli/src/config/__tests__/hooks.spec.ts b/packages/cli/src/config/__tests__/hooks.spec.ts index aac97cf9ff..f3af41354f 100644 --- a/packages/cli/src/config/__tests__/hooks.spec.ts +++ b/packages/cli/src/config/__tests__/hooks.spec.ts @@ -19,6 +19,7 @@ import { describe, expect, it } from 'vitest'; import { HOOK_STUB_SCRIPT, + SUPPORTED_GIT_HOOK_NAMES, disable, enable, hookScript, @@ -124,7 +125,7 @@ describe('install', () => { process.chdir(tmp); expect(install()).toEqual({ - message: 'core.hooksPath is already set to ".husky/_", skipping', + message: expect.stringContaining('core.hooksPath is already set to ".husky/_", skipping'), isError: false, }); expect(execSync('git config --local core.hooksPath', { cwd: tmp }).toString().trim()).toBe( @@ -139,15 +140,16 @@ describe('install', () => { }); it.each([ - ['.husky', '.vite-hooks'], - ['.husky/_', '.vite-hooks'], - ['./.husky/_/', '.vite-hooks'], - ['.husky/_', '.vite-hooks', '\r\n'], - ['.husky/_', '.custom-hooks'], - ['.husky/_', 'packages/app/.vite-hooks'], + ['.husky', '.vite-hooks', 'missing'], + ['.husky', '.vite-hooks', 'empty'], + ['.husky/_', '.vite-hooks', 'missing'], + ['.husky/_', '.vite-hooks', 'empty'], + ['./.husky/_/', '.vite-hooks', 'empty'], + ['.husky/_', '.custom-hooks', 'empty'], + ['.husky/_', 'packages/app/.vite-hooks', 'empty'], ])( - 'takes over a stale local Husky path %s after migration to %s', - (hooksPath, hooksDir, newline = '\n') => { + 'recovers %s after migration to %s when the old directory is %s', + (hooksPath, hooksDir, state) => { const tmp = mkdtempSync(join(tmpdir(), 'hooks-husky-migration-')); const originalCwd = process.cwd(); try { @@ -157,32 +159,18 @@ describe('install', () => { join(tmp, 'package.json'), JSON.stringify({ scripts: { prepare: 'vp config' } }), ); - mkdirSync(join(tmp, '.husky', '_'), { recursive: true }); - const oldDispatcher = join(tmp, '.husky', '_', 'h'); - const oldContents = HUSKY_DISPATCHER.replaceAll('\n', newline); - writeFileSync(oldDispatcher, oldContents); - writeFileSync( - join(tmp, '.husky', '_', 'pre-commit'), - HOOK_STUB_SCRIPT.replaceAll('\n', newline), - ); - writeFileSync(join(tmp, '.husky', '_', '.gitignore'), '*'); - writeFileSync( - join(tmp, '.husky', '_', 'husky.sh'), - readFileSync( - new URL('./fixtures/husky-9.1.7/husky.sh', import.meta.url), - 'utf8', - ).replaceAll('\n', newline), - ); + if (state === 'empty') { + mkdirSync(join(tmp, hooksPath), { recursive: true }); + } mkdirSync(join(tmp, hooksDir), { recursive: true }); writeFileSync(join(tmp, hooksDir, 'commit-msg'), 'exit 1\n'); process.chdir(tmp); - expect(install(hooksDir)).toEqual({ message: '', isError: false }); expect( - execFileSync('git', ['config', '--get', 'core.hooksPath'], { encoding: 'utf8' }).trim(), + execFileSync('git', ['config', '--get', 'core.hooksPath'], { + encoding: 'utf8', + }).trim(), ).toBe(`${hooksDir}/_`); - expect(readFileSync(oldDispatcher, 'utf8')).toBe(oldContents); - // A real commit must invoke the migrated hook, even in the old clone. const commit = spawnSync( 'git', [ @@ -190,10 +178,12 @@ describe('install', () => { 'user.name=Test', '-c', 'user.email=test@example.invalid', + '-c', + 'commit.gpgsign=false', 'commit', '--allow-empty', '-m', - 'bad message', + 'test', ], { encoding: 'utf8' }, ); @@ -208,6 +198,136 @@ describe('install', () => { }, ); + it.each(['\n', '\r\n'])( + 'preserves leftover generated Husky files with %j line endings until explicit replacement', + (newline) => { + const tmp = mkdtempSync(join(tmpdir(), 'hooks-husky-generated-')); + const originalCwd = process.cwd(); + try { + execFileSync('git', ['init'], { cwd: tmp, stdio: 'ignore' }); + execFileSync('git', ['config', 'core.hooksPath', '.husky/_'], { cwd: tmp }); + const manifest = JSON.stringify({ scripts: { prepare: 'vp config' } }); + writeFileSync(join(tmp, 'package.json'), manifest); + const internal = join(tmp, '.husky', '_'); + mkdirSync(internal, { recursive: true }); + const files: Record = { + h: HUSKY_DISPATCHER.replaceAll('\n', newline), + 'husky.sh': readFileSync( + new URL('./fixtures/husky-9.1.7/husky.sh', import.meta.url), + 'utf8', + ).replaceAll('\n', newline), + '.gitignore': '*', + ...Object.fromEntries( + SUPPORTED_GIT_HOOK_NAMES.map((name) => [ + name, + HOOK_STUB_SCRIPT.replaceAll('\n', newline), + ]), + ), + }; + for (const [name, contents] of Object.entries(files)) { + writeFileSync(join(internal, name), contents); + } + mkdirSync(join(tmp, '.vite-hooks')); + writeFileSync(join(tmp, '.vite-hooks', 'pre-commit'), 'exit 0\n'); + process.chdir(tmp); + for (const setup of [install, enable]) { + const skipped = setup(); + expect(skipped.isError).toBe(false); + expect(skipped.message).toContain('Vite+ hooks at .vite-hooks are not active'); + expect(skipped.message).toContain('vp hooks enable --replace-husky'); + expect(existsSync(join(tmp, '.vite-hooks', '_'))).toBe(false); + } + const replacement = enable(undefined, { replaceHusky: true }); + expect(replacement.isError).toBe(false); + expect(replacement.message).toContain('Old Husky files were preserved'); + expect(replacement.message).toContain('no longer run'); + expect( + execFileSync('git', ['config', '--get', 'core.hooksPath'], { encoding: 'utf8' }).trim(), + ).toBe('.vite-hooks/_'); + for (const [name, contents] of Object.entries(files)) { + expect(readFileSync(join(internal, name), 'utf8')).toBe(contents); + } + expect(readFileSync(join(tmp, 'package.json'), 'utf8')).toBe(manifest); + expect(install()).toEqual({ message: '', isError: false }); + } finally { + process.chdir(originalCwd); + rmSync(tmp, { recursive: true, force: true }); + } + }, + ); + + it('requires explicit replacement even for an empty nested directory under .husky', () => { + const tmp = mkdtempSync(join(tmpdir(), 'hooks-husky-nested-empty-')); + const originalCwd = process.cwd(); + try { + execFileSync('git', ['init'], { cwd: tmp, stdio: 'ignore' }); + execFileSync('git', ['config', 'core.hooksPath', '.husky'], { cwd: tmp }); + writeFileSync(join(tmp, 'package.json'), '{}'); + mkdirSync(join(tmp, '.husky', '_'), { recursive: true }); + mkdirSync(join(tmp, '.vite-hooks')); + writeFileSync(join(tmp, '.vite-hooks', 'pre-commit'), 'exit 0\n'); + process.chdir(tmp); + expect(install().message).toContain('Vite+ hooks at .vite-hooks are not active'); + expect(enable(undefined, { replaceHusky: true }).message).toContain( + 'Replaced core.hooksPath ".husky"', + ); + } finally { + process.chdir(originalCwd); + rmSync(tmp, { recursive: true, force: true }); + } + }); + + it.each(['.vite-hooks', '.custom-hooks'])( + 'explicitly replaces custom Husky checks with migrated checks in %s', + (dir) => { + const tmp = mkdtempSync(join(tmpdir(), 'hooks-husky-replace-')); + const originalCwd = process.cwd(); + try { + execFileSync('git', ['init'], { cwd: tmp, stdio: 'ignore' }); + execFileSync('git', ['config', 'core.hooksPath', '.husky/_'], { cwd: tmp }); + writeFileSync(join(tmp, 'package.json'), '{}'); + mkdirSync(join(tmp, '.husky', '_'), { recursive: true }); + const old = join(tmp, '.husky', '_', 'pre-commit'); + const original = '#!/bin/sh\necho original-check-rejected >&2\nexit 1\n'; + writeFileSync(old, original, { mode: 0o755 }); + mkdirSync(join(tmp, dir)); + writeFileSync(join(tmp, dir, 'commit-msg'), 'echo migrated-check-rejected >&2\nexit 1\n'); + process.chdir(tmp); + const runCommit = () => + spawnSync( + 'git', + [ + '-c', + 'user.name=Test', + '-c', + 'user.email=test@example.invalid', + '-c', + 'commit.gpgsign=false', + 'commit', + '--allow-empty', + '-m', + 'test', + ], + { cwd: tmp, encoding: 'utf8' }, + ); + const before = runCommit(); + expect(before.status).toBe(1); + expect(before.stderr).toContain('original-check-rejected'); + const replacement = enable(dir, { replaceHusky: true }); + expect(replacement.isError).toBe(false); + expect(replacement.message).toContain('no longer run'); + expect(readFileSync(old, 'utf8')).toBe(original); + const after = runCommit(); + expect(after.status).toBe(1); + expect(after.stderr).toContain('migrated-check-rejected'); + expect(after.stderr).not.toContain('original-check-rejected'); + } finally { + process.chdir(originalCwd); + rmSync(tmp, { recursive: true, force: true }); + } + }, + ); + it .skipIf(process.platform === 'win32') .each(['custom supported hook', 'symlinked hook', 'custom dispatcher'])( @@ -263,7 +383,9 @@ describe('install', () => { assertCommitRejected(); for (const setup of [install, enable]) { expect(setup()).toEqual({ - message: 'core.hooksPath is already set to ".husky/_", skipping', + message: expect.stringContaining( + 'core.hooksPath is already set to ".husky/_", skipping', + ), isError: false, }); expect( @@ -299,7 +421,8 @@ describe('install', () => { writeFileSync(join(tmp, '.vite-hooks', 'pre-commit'), 'exit 1\n'); process.chdir(tmp); - expect(install().message).toBe('core.hooksPath is already set to ".husky/_", skipping'); + expect(install().message).toContain('core.hooksPath is already set to ".husky/_", skipping'); + expect(enable(undefined, { replaceHusky: true }).message).toContain('skipping'); expect(existsSync(join(tmp, '.vite-hooks', '_'))).toBe(false); } finally { process.chdir(originalCwd); @@ -334,7 +457,9 @@ describe('install', () => { expect(before.status).toBe(1); expect(before.stderr).toContain('original hook rejected'); expect(install()).toEqual({ - message: `core.hooksPath is already set to "${hooksPath}", skipping`, + message: expect.stringContaining( + `core.hooksPath is already set to "${hooksPath}", skipping`, + ), isError: false, }); const after = runHook(); @@ -415,6 +540,7 @@ describe('install', () => { message: 'core.hooksPath is already set to ".husky", skipping', isError: false, }); + expect(enable(undefined, { replaceHusky: true }).message).toContain('skipping'); expect( execFileSync('git', ['config', '--local', 'core.hooksPath'], { encoding: 'utf8' }).trim(), ).toBe('.husky'); @@ -447,7 +573,9 @@ describe('install', () => { symlinkSync(join(tmp, 'external'), join(tmp, linkedDir), 'dir'); process.chdir(tmp); - expect(install().message).toBe('core.hooksPath is already set to ".husky/_", skipping'); + expect(install().message).toContain( + 'core.hooksPath is already set to ".husky/_", skipping', + ); expect(existsSync(join(tmp, '.vite-hooks', '_'))).toBe(false); } finally { process.chdir(originalCwd); @@ -508,6 +636,9 @@ describe('install', () => { } expect(install().isError).toBe(false); + if (scenario !== 'disabled hooks') { + expect(enable(undefined, { replaceHusky: true }).message).toContain('skipping'); + } expect( execFileSync('git', ['config', '--get', 'core.hooksPath'], { encoding: 'utf8' }).trim(), ).toBe(hooksPath); @@ -523,6 +654,70 @@ describe('install', () => { } }); + it.each(['HUSKY', 'VP_GIT_HOOKS', 'VITE_GIT_HOOKS'])( + 'explicit replacement honors %s=0', + (name) => { + const tmp = mkdtempSync(join(tmpdir(), 'hooks-husky-replace-disabled-')); + const originalCwd = process.cwd(); + const previous = process.env[name]; + try { + execFileSync('git', ['init'], { cwd: tmp, stdio: 'ignore' }); + execFileSync('git', ['config', 'core.hooksPath', '.husky/_'], { cwd: tmp }); + writeFileSync(join(tmp, 'package.json'), '{}'); + mkdirSync(join(tmp, '.vite-hooks')); + writeFileSync(join(tmp, '.vite-hooks', 'pre-commit'), 'exit 0\n'); + process.chdir(tmp); + process.env[name] = '0'; + expect(enable(undefined, { replaceHusky: true })).toEqual({ + message: 'skip install (git hooks disabled)', + isError: false, + }); + expect( + execFileSync('git', ['config', '--get', 'core.hooksPath'], { encoding: 'utf8' }).trim(), + ).toBe('.husky/_'); + expect(existsSync(join(tmp, '.vite-hooks', '_'))).toBe(false); + } finally { + if (previous === undefined) { + delete process.env[name]; + } else { + process.env[name] = previous; + } + process.chdir(originalCwd); + rmSync(tmp, { recursive: true, force: true }); + } + }, + ); + + it.each(['.husky', '.husky/_'])( + 'explicit replacement does not overwrite old files when --hooks-dir points into .husky (%s)', + (oldPath) => { + const tmp = mkdtempSync(join(tmpdir(), 'hooks-husky-replace-overlap-')); + const originalCwd = process.cwd(); + try { + execFileSync('git', ['init'], { cwd: tmp, stdio: 'ignore' }); + execFileSync('git', ['config', 'core.hooksPath', oldPath], { cwd: tmp }); + writeFileSync(join(tmp, 'package.json'), '{}'); + mkdirSync(join(tmp, '.husky', '_'), { recursive: true }); + writeFileSync(join(tmp, '.husky', 'pre-commit'), 'exit 1\n'); + const dispatcher = join(tmp, '.husky', '_', 'h'); + writeFileSync(dispatcher, 'custom dispatcher\n'); + process.chdir(tmp); + expect(enable('.husky', { replaceHusky: true })).toEqual({ + message: + 'Husky replacement requires a hooks directory outside .husky to preserve old files', + isError: true, + }); + expect(readFileSync(dispatcher, 'utf8')).toBe('custom dispatcher\n'); + expect( + execFileSync('git', ['config', '--get', 'core.hooksPath'], { encoding: 'utf8' }).trim(), + ).toBe(oldPath); + } finally { + process.chdir(originalCwd); + rmSync(tmp, { recursive: true, force: true }); + } + }, + ); + it('refreshes an equivalent hooks path spelling', () => { const tmp = mkdtempSync(join(tmpdir(), 'hooks-equivalent-path-test-')); const originalCwd = process.cwd(); diff --git a/packages/cli/src/config/hooks.ts b/packages/cli/src/config/hooks.ts index 11a7264933..75cfb6ff04 100644 --- a/packages/cli/src/config/hooks.ts +++ b/packages/cli/src/config/hooks.ts @@ -1,5 +1,4 @@ import { spawnSync } from 'node:child_process'; -import { createHash } from 'node:crypto'; import { chmodSync, existsSync, @@ -509,46 +508,22 @@ function getScopedHooksPath(scope: 'local' | 'worktree'): string { return result.status === 0 ? result.stdout?.toString().trim() : ''; } -// Exact Husky 9.1.7 generated contents, with CRLF and a final newline normalized. -// https://github.com/typicode/husky/blob/v9.1.7/husky -// https://github.com/typicode/husky/blob/v9.1.7/index.js -// Unknown versions are deliberately preserved rather than guessing that their -// dispatcher is safe to abandon. -const HUSKY_GENERATED_SCRIPT_HASHES: Readonly> = { - h: 'd80994934f440d579303d6590fa1ce7bc0d31c650179d2089dea5191d1ab10d1', - 'husky.sh': '21122903fca7209a13c991e5be68780636e28f1b8f0ae7ea07ed0065dfe37268', -}; - -function isUnmodifiedHuskyFile(directory: string, name: string): boolean { - const path = join(directory, name); - const stats = lstatSync(path); - if (!stats.isFile() || stats.isSymbolicLink() || stats.nlink !== 1) { - return false; - } - const contents = readFileSync(path, 'utf8').replace(/\r\n/g, '\n').replace(/\n$/, ''); - if (name === '.gitignore') { - return contents === '*'; - } - if (SUPPORTED_GIT_HOOK_NAMES.includes(name)) { - return contents === HOOK_STUB_SCRIPT; - } - const expectedHash = HUSKY_GENERATED_SCRIPT_HASHES[name]; - return ( - expectedHash !== undefined && - createHash('sha256').update(contents).digest('hex') === expectedHash - ); -} +type HuskyReplacement = 'automatic' | 'explicit' | 'non-empty' | null; -/** Only reclaim an abandoned, repository-local Husky setup after hooks were moved. */ -function canReplaceStaleHuskyPath(hooksPath: string, location: HooksLocation): boolean { +/** Only reclaim a repository-local Husky setup after hooks were moved. */ +function getHuskyReplacement( + hooksPath: string, + location: HooksLocation, + replaceHusky: boolean, +): HuskyReplacement { const normalized = normalizeHooksPath(hooksPath); if (normalized !== '.husky' && normalized !== join('.husky', '_')) { - return false; + return null; } // Never override a global, worktree, or command-scoped hook policy. const scoped = spawnSync('git', ['config', '--show-scope', '--get', 'core.hooksPath']); if (scoped.status !== 0 || !scoped.stdout.toString().startsWith('local\t')) { - return false; + return null; } // Local config is shared by linked worktrees. Inspecting only this checkout // cannot establish whether the others have also migrated away from Husky. @@ -560,8 +535,9 @@ function canReplaceStaleHuskyPath(hooksPath: string, location: HooksLocation): b .split('\0') .filter((field) => field.startsWith('worktree ')).length !== 1 ) { - return false; + return null; } + let hasFiles = false; try { const huskyDir = join(location.toplevel, '.husky'); const huskyStats = lstatSync(huskyDir, { throwIfNoEntry: false }); @@ -571,16 +547,30 @@ function canReplaceStaleHuskyPath(hooksPath: string, location: HooksLocation): b (huskyStats && (!huskyStats.isDirectory() || huskyStats.isSymbolicLink())) || (dispatcherStats && (!dispatcherStats.isDirectory() || dispatcherStats.isSymbolicLink())) ) { - return false; + return null; } - // Git can execute hook names outside Vite+'s supported set (including - // arbitrary names through `git hook run`). Only ignore generated files. - if ( - (huskyStats && readdirSync(huskyDir).some((name) => name !== '_')) || - (dispatcherStats && - readdirSync(dispatcherDir).some((name) => !isUnmodifiedHuskyFile(dispatcherDir, name))) - ) { - return false; + // Never inspect script contents or infer that leftover files are generated. + // An explicit replacement may stop custom checks, but must not bypass the + // path/link protections or write through any of the old files. + for (const directory of [huskyDir, dispatcherDir]) { + const stats = directory === huskyDir ? huskyStats : dispatcherStats; + if (!stats) { + continue; + } + const names = readdirSync(directory); + if (directory === resolve(location.toplevel, normalized) && names.length > 0) { + hasFiles = true; + } + for (const name of names) { + if (directory === huskyDir && name === '_') { + continue; + } + hasFiles = true; + const entry = lstatSync(join(directory, name)); + if (!entry.isFile() || entry.isSymbolicLink() || entry.nlink > 1) { + return null; + } + } } // A dispatcher alone is not evidence of a completed migration. if ( @@ -589,7 +579,7 @@ function canReplaceStaleHuskyPath(hooksPath: string, location: HooksLocation): b ) || !existsSync(join(location.toplevel, 'package.json')) ) { - return false; + return null; } // Include ancestor manifests when hooks are configured from a workspace package. const relativeBase = relative(location.toplevel, location.baseDir); @@ -604,7 +594,7 @@ function canReplaceStaleHuskyPath(hooksPath: string, location: HooksLocation): b } const pkg = JSON.parse(readFileSync(manifest, 'utf8')) as Record; if (!pkg || typeof pkg !== 'object' || Array.isArray(pkg) || 'husky' in pkg) { - return false; + return null; } for (const key of [ 'dependencies', @@ -614,7 +604,7 @@ function canReplaceStaleHuskyPath(hooksPath: string, location: HooksLocation): b ]) { const dependencies = pkg[key]; if (dependencies && typeof dependencies === 'object' && 'husky' in dependencies) { - return false; + return null; } } if ( @@ -624,14 +614,14 @@ function canReplaceStaleHuskyPath(hooksPath: string, location: HooksLocation): b (script) => typeof script === 'string' && /\bhusky\b/.test(script), ) ) { - return false; + return null; } } } catch { // Unreadable or invalid manifests are not evidence that Husky was removed. - return false; + return null; } - return true; + return replaceHusky ? 'explicit' : hasFiles ? 'non-empty' : 'automatic'; } function unsetScopedHooksPath(scope: 'local' | 'worktree'): InstallResult | null { @@ -689,6 +679,8 @@ export interface InstallOptions { * Still honors `VP_GIT_HOOKS=0` / `HUSKY=0`. */ ignoreUserPreference?: boolean; + /** Explicitly replace a local Husky path after migrating project checks. */ + replaceHusky?: boolean; } export function isGitHooksEnvDisabled(): boolean { @@ -719,19 +711,44 @@ export function install(dir?: string, options: InstallOptions = {}): InstallResu return { message: describeUnsafeHookInstallPath(unsafeInstallPath), isError: false }; } + if (options.replaceHusky) { + const oldRoot = resolveHooksPath('.husky', location.toplevel); + const targetRoot = resolveHooksPath(location.dir, location.baseDir); + const relativeTarget = relative(oldRoot, targetRoot); + if ( + relativeTarget === '' || + (!isAbsolute(relativeTarget) && + relativeTarget !== '..' && + !relativeTarget.startsWith(`..${sep}`)) + ) { + return { + message: + 'Husky replacement requires a hooks directory outside .husky to preserve old files', + isError: true, + }; + } + } + const internal = (x = '') => join(location.baseDir, location.dir, '_', x); // Read the effective value so a worktree-scoped setting cannot silently // override the local value we are about to write. const existingHooksPath = getEffectiveHooksPath(); + let replacement: HuskyReplacement = null; if ( existingHooksPath && - !hooksPathsEqual(existingHooksPath, location.target, location.toplevel) && - !canReplaceStaleHuskyPath(existingHooksPath, location) + !hooksPathsEqual(existingHooksPath, location.target, location.toplevel) ) { - return { - message: `core.hooksPath is already set to "${existingHooksPath}", skipping`, - isError: false, - }; + replacement = getHuskyReplacement(existingHooksPath, location, options.replaceHusky === true); + if (replacement === null || replacement === 'non-empty') { + const guidance = + replacement === 'non-empty' + ? `. Vite+ hooks at ${displayHooksDir(location)} are not active. Migrate any custom Husky checks, then run \`vp hooks enable --replace-husky\` (with the same --hooks-dir if customized). Switching stops running hooks from "${existingHooksPath}"; the old files are preserved.` + : ''; + return { + message: `core.hooksPath is already set to "${existingHooksPath}", skipping${guidance}`, + isError: false, + }; + } } rmSync(internal('husky.sh'), { force: true }); @@ -761,6 +778,12 @@ export function install(dir?: string, options: InstallOptions = {}): InstallResu return { message: storeDir.error || 'failed to store hooks directory', isError: true }; } + if (replacement === 'explicit') { + return { + message: `Git hook dispatcher installed at ${displayHooksDir(location)}/_. Replaced core.hooksPath "${existingHooksPath}". Old Husky files were preserved, but hooks from "${existingHooksPath}" no longer run. Custom checks must be migrated to ${displayHooksDir(location)}.`, + isError: false, + }; + } return { message: '', isError: false }; } @@ -768,17 +791,17 @@ export function install(dir?: string, options: InstallOptions = {}): InstallResu * Install (or refresh) the Vite+ hook dispatcher and mark hooks as enabled. * Clears a previous `vp hooks disable` preference. */ -export function enable(dir?: string): InstallResult { +export function enable(dir?: string, options: { replaceHusky?: boolean } = {}): InstallResult { const location = resolveHooksLocation(dir); if ('isError' in location) { return location; } - const result = install(dir, { ignoreUserPreference: true }); + const result = install(dir, { ignoreUserPreference: true, replaceHusky: options.replaceHusky }); if (result.isError) { return result; } if (result.message) { - // Non-error skip messages (env disabled, foreign hooksPath, unsafe path, etc.) + // Preserve skip messages and the explicit Husky replacement notice. return result; } return { diff --git a/packages/cli/src/hooks/bin.ts b/packages/cli/src/hooks/bin.ts index 8e4e6f3422..d21c5d8ef9 100644 --- a/packages/cli/src/hooks/bin.ts +++ b/packages/cli/src/hooks/bin.ts @@ -17,7 +17,7 @@ async function main() { switch (args.command) { case 'enable': - applyResult(enable(args.hooksDir)); + applyResult(enable(args.hooksDir, { replaceHusky: args.replaceHusky })); return; case 'disable': applyResult(disable(args.hooksDir)); From 4a05f48228e301ab3f2b0d5898900578ed32be71 Mon Sep 17 00:00:00 2001 From: MK Date: Tue, 17 Nov 2026 17:00:55 +0800 Subject: [PATCH 6/7] test(cli): exercise empty Husky recovery in snapshots --- .../snapshots.toml | 2 +- ...ommand_hooks_recover_empty_husky.global.md | 20 +++++++++++++++---- ...command_hooks_recover_empty_husky.local.md | 20 +++++++++++++++---- 3 files changed, 33 insertions(+), 9 deletions(-) diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots.toml index 6827a9c90c..beb443dc4a 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots.toml @@ -25,7 +25,7 @@ vp = ["local", "global"] steps = [ { argv = ["git", "init"], snapshot = false }, { argv = ["git", "config", "core.hooksPath", ".husky/_"], snapshot = false }, - { argv = ["vpt", "mkdir", ".husky/_"], snapshot = false }, + { argv = ["vpt", "mkdir", "-p", ".husky/_"], snapshot = false }, { argv = ["vpt", "write-file", ".vite-hooks/pre-commit", "exit 0\n"], snapshot = false }, { argv = ["vp", "config", "--no-agent"], tty = false, comment = "recover an empty old directory automatically" }, { argv = ["git", "config", "--local", "core.hooksPath"], comment = "Vite+ hooks are active without an explicit override" }, diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_recover_empty_husky.global.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_recover_empty_husky.global.md index c5f5b43b7c..66c7ce3b38 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_recover_empty_husky.global.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_recover_empty_husky.global.md @@ -6,12 +6,24 @@ ## `git config core.hooksPath .husky/_` -## `vpt mkdir .husky/_` +## `vpt mkdir -p .husky/_` -**Exit code:** 1 + +## `vpt write-file .vite-hooks/pre-commit 'exit 0 +'` + + +## `vp config --no-agent` + +recover an empty old directory automatically ``` -No such file or directory (os error 2) ``` -*(remaining steps skipped: step failed)* +## `git config --local core.hooksPath` + +Vite+ hooks are active without an explicit override + +``` +.vite-hooks/_ +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_recover_empty_husky.local.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_recover_empty_husky.local.md index c5f5b43b7c..66c7ce3b38 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_recover_empty_husky.local.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_hooks_replace_husky/snapshots/command_hooks_recover_empty_husky.local.md @@ -6,12 +6,24 @@ ## `git config core.hooksPath .husky/_` -## `vpt mkdir .husky/_` +## `vpt mkdir -p .husky/_` -**Exit code:** 1 + +## `vpt write-file .vite-hooks/pre-commit 'exit 0 +'` + + +## `vp config --no-agent` + +recover an empty old directory automatically ``` -No such file or directory (os error 2) ``` -*(remaining steps skipped: step failed)* +## `git config --local core.hooksPath` + +Vite+ hooks are active without an explicit override + +``` +.vite-hooks/_ +``` From 5290dbad3be132d881204d98e9af14ed9317bb60 Mon Sep 17 00:00:00 2001 From: MK Date: Tue, 17 Nov 2026 17:06:55 +0800 Subject: [PATCH 7/7] refactor(cli): simplify Husky replacement checks --- .../cli/src/config/__tests__/hooks.spec.ts | 117 +++++------------- packages/cli/src/config/hooks.ts | 44 +++---- 2 files changed, 48 insertions(+), 113 deletions(-) diff --git a/packages/cli/src/config/__tests__/hooks.spec.ts b/packages/cli/src/config/__tests__/hooks.spec.ts index f3af41354f..79f2078233 100644 --- a/packages/cli/src/config/__tests__/hooks.spec.ts +++ b/packages/cli/src/config/__tests__/hooks.spec.ts @@ -1,3 +1,4 @@ +import type { SpawnSyncReturns } from 'node:child_process'; import { execFileSync, execSync, spawn, spawnSync } from 'node:child_process'; import { once } from 'node:events'; import { @@ -32,6 +33,25 @@ import { // Unmodified upstream dispatcher; retained to verify safe migration against real Husky output. const HUSKY_DISPATCHER = readFileSync(new URL('./fixtures/husky-9.1.7/h', import.meta.url), 'utf8'); +function runCommit(cwd: string, message = 'test'): SpawnSyncReturns { + return spawnSync( + 'git', + [ + '-c', + 'user.name=Test', + '-c', + 'user.email=test@example.invalid', + '-c', + 'commit.gpgsign=false', + 'commit', + '--allow-empty', + '-m', + message, + ], + { cwd, encoding: 'utf8' }, + ); +} + function countDirnameCalls(script: string): number { // Count nested dirname calls in the `d=...` line const match = script.match(/^d=(.+)$/m); @@ -171,22 +191,7 @@ describe('install', () => { encoding: 'utf8', }).trim(), ).toBe(`${hooksDir}/_`); - const commit = spawnSync( - 'git', - [ - '-c', - 'user.name=Test', - '-c', - 'user.email=test@example.invalid', - '-c', - 'commit.gpgsign=false', - 'commit', - '--allow-empty', - '-m', - 'test', - ], - { encoding: 'utf8' }, - ); + const commit = runCommit(tmp); expect(commit.status).toBe(1); expect(commit.stdout + commit.stderr).toContain('commit-msg script failed'); expect(enable().isError).toBe(false); @@ -293,31 +298,14 @@ describe('install', () => { mkdirSync(join(tmp, dir)); writeFileSync(join(tmp, dir, 'commit-msg'), 'echo migrated-check-rejected >&2\nexit 1\n'); process.chdir(tmp); - const runCommit = () => - spawnSync( - 'git', - [ - '-c', - 'user.name=Test', - '-c', - 'user.email=test@example.invalid', - '-c', - 'commit.gpgsign=false', - 'commit', - '--allow-empty', - '-m', - 'test', - ], - { cwd: tmp, encoding: 'utf8' }, - ); - const before = runCommit(); + const before = runCommit(tmp); expect(before.status).toBe(1); expect(before.stderr).toContain('original-check-rejected'); const replacement = enable(dir, { replaceHusky: true }); expect(replacement.isError).toBe(false); expect(replacement.message).toContain('no longer run'); expect(readFileSync(old, 'utf8')).toBe(original); - const after = runCommit(); + const after = runCommit(tmp); expect(after.status).toBe(1); expect(after.stderr).toContain('migrated-check-rejected'); expect(after.stderr).not.toContain('original-check-rejected'); @@ -360,26 +348,11 @@ describe('install', () => { mkdirSync(join(tmp, '.vite-hooks')); writeFileSync(join(tmp, '.vite-hooks', 'commit-msg'), 'exit 0\n'); process.chdir(tmp); - const assertCommitRejected = () => { - const result = spawnSync( - 'git', - [ - '-c', - 'user.name=Test', - '-c', - 'user.email=test@example.invalid', - '-c', - 'commit.gpgsign=false', - 'commit', - '--allow-empty', - '-m', - 'test', - ], - { cwd: tmp, encoding: 'utf8' }, - ); + function assertCommitRejected(): void { + const result = runCommit(tmp); expect(result.status).toBe(1); expect(result.stderr).toContain('original hook rejected'); - }; + } assertCommitRejected(); for (const setup of [install, enable]) { expect(setup()).toEqual({ @@ -482,22 +455,7 @@ describe('install', () => { try { mkdirSync(original); execFileSync('git', ['init'], { cwd: original, stdio: 'ignore' }); - execFileSync( - 'git', - [ - '-c', - 'user.name=Test', - '-c', - 'user.email=test@example.invalid', - '-c', - 'commit.gpgsign=false', - 'commit', - '--allow-empty', - '-m', - 'initial', - ], - { cwd: original, stdio: 'ignore' }, - ); + expect(runCommit(original, 'initial').status).toBe(0); execFileSync('git', ['worktree', 'add', '-b', 'linked', linked], { cwd: original, stdio: 'ignore', @@ -516,24 +474,7 @@ describe('install', () => { const oldHook = join(unmigrated, '.husky', 'pre-commit'); writeFileSync(oldHook, '#!/bin/sh\necho "unmigrated hook rejected" >&2\nexit 1\n'); chmodSync(oldHook, 0o755); - const commit = () => - spawnSync( - 'git', - [ - '-c', - 'user.name=Test', - '-c', - 'user.email=test@example.invalid', - '-c', - 'commit.gpgsign=false', - 'commit', - '--allow-empty', - '-m', - 'rejected', - ], - { cwd: unmigrated, encoding: 'utf8' }, - ); - expect(commit().status).toBe(1); + expect(runCommit(unmigrated, 'rejected').status).toBe(1); process.chdir(migrated); expect(install()).toEqual({ @@ -544,7 +485,7 @@ describe('install', () => { expect( execFileSync('git', ['config', '--local', 'core.hooksPath'], { encoding: 'utf8' }).trim(), ).toBe('.husky'); - const after = commit(); + const after = runCommit(unmigrated, 'rejected'); expect(after.status).toBe(1); expect(after.stderr).toContain('unmigrated hook rejected'); expect(existsSync(join(migrated, '.vite-hooks', '_'))).toBe(false); diff --git a/packages/cli/src/config/hooks.ts b/packages/cli/src/config/hooks.ts index 75cfb6ff04..4d746c841f 100644 --- a/packages/cli/src/config/hooks.ts +++ b/packages/cli/src/config/hooks.ts @@ -537,35 +537,30 @@ function getHuskyReplacement( ) { return null; } - let hasFiles = false; + let hasEntries = false; try { const huskyDir = join(location.toplevel, '.husky'); - const huskyStats = lstatSync(huskyDir, { throwIfNoEntry: false }); - const dispatcherDir = join(huskyDir, '_'); - const dispatcherStats = lstatSync(dispatcherDir, { throwIfNoEntry: false }); - if ( - (huskyStats && (!huskyStats.isDirectory() || huskyStats.isSymbolicLink())) || - (dispatcherStats && (!dispatcherStats.isDirectory() || dispatcherStats.isSymbolicLink())) - ) { - return null; - } + const activeHooksDir = resolve(location.toplevel, normalized); // Never inspect script contents or infer that leftover files are generated. // An explicit replacement may stop custom checks, but must not bypass the // path/link protections or write through any of the old files. - for (const directory of [huskyDir, dispatcherDir]) { - const stats = directory === huskyDir ? huskyStats : dispatcherStats; + for (const directory of [huskyDir, join(huskyDir, '_')]) { + const stats = lstatSync(directory, { throwIfNoEntry: false }); if (!stats) { continue; } + if (!stats.isDirectory() || stats.isSymbolicLink()) { + return null; + } const names = readdirSync(directory); - if (directory === resolve(location.toplevel, normalized) && names.length > 0) { - hasFiles = true; + if (directory === activeHooksDir && names.length > 0) { + hasEntries = true; } for (const name of names) { if (directory === huskyDir && name === '_') { continue; } - hasFiles = true; + hasEntries = true; const entry = lstatSync(join(directory, name)); if (!entry.isFile() || entry.isSymbolicLink() || entry.nlink > 1) { return null; @@ -621,7 +616,10 @@ function getHuskyReplacement( // Unreadable or invalid manifests are not evidence that Husky was removed. return null; } - return replaceHusky ? 'explicit' : hasFiles ? 'non-empty' : 'automatic'; + if (replaceHusky) { + return 'explicit'; + } + return hasEntries ? 'non-empty' : 'automatic'; } function unsetScopedHooksPath(scope: 'local' | 'worktree'): InstallResult | null { @@ -716,10 +714,9 @@ export function install(dir?: string, options: InstallOptions = {}): InstallResu const targetRoot = resolveHooksPath(location.dir, location.baseDir); const relativeTarget = relative(oldRoot, targetRoot); if ( - relativeTarget === '' || - (!isAbsolute(relativeTarget) && - relativeTarget !== '..' && - !relativeTarget.startsWith(`..${sep}`)) + !isAbsolute(relativeTarget) && + relativeTarget !== '..' && + !relativeTarget.startsWith(`..${sep}`) ) { return { message: @@ -797,11 +794,8 @@ export function enable(dir?: string, options: { replaceHusky?: boolean } = {}): return location; } const result = install(dir, { ignoreUserPreference: true, replaceHusky: options.replaceHusky }); - if (result.isError) { - return result; - } - if (result.message) { - // Preserve skip messages and the explicit Husky replacement notice. + // Preserve errors, skip messages, and the explicit Husky replacement notice. + if (result.isError || result.message) { return result; } return {