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..beb443dc4a --- /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", "-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 new file mode 100644 index 0000000000..66c7ce3b38 --- /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,29 @@ +# command_hooks_recover_empty_husky + +## `git init` + + +## `git config core.hooksPath .husky/_` + + +## `vpt mkdir -p .husky/_` + + +## `vpt write-file .vite-hooks/pre-commit 'exit 0 +'` + + +## `vp config --no-agent` + +recover an empty old directory automatically + +``` +``` + +## `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 new file mode 100644 index 0000000000..66c7ce3b38 --- /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,29 @@ +# command_hooks_recover_empty_husky + +## `git init` + + +## `git config core.hooksPath .husky/_` + + +## `vpt mkdir -p .husky/_` + + +## `vpt write-file .vite-hooks/pre-commit 'exit 0 +'` + + +## `vp config --no-agent` + +recover an empty old directory automatically + +``` +``` + +## `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_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 6de5dcbae8..b11167c989 100644 --- a/docs/guide/commit-hooks.md +++ b/docs/guide/commit-hooks.md @@ -76,6 +76,20 @@ 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 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`. 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/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__/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 e9230de2f8..79f2078233 100644 --- a/packages/cli/src/config/__tests__/hooks.spec.ts +++ b/packages/cli/src/config/__tests__/hooks.spec.ts @@ -1,4 +1,5 @@ -import { execSync, spawn } from 'node:child_process'; +import type { SpawnSyncReturns } from 'node:child_process'; +import { execFileSync, execSync, spawn, spawnSync } from 'node:child_process'; import { once } from 'node:events'; import { chmodSync, @@ -18,6 +19,8 @@ import { join, resolve } from 'node:path'; import { describe, expect, it } from 'vitest'; import { + HOOK_STUB_SCRIPT, + SUPPORTED_GIT_HOOK_NAMES, disable, enable, hookScript, @@ -27,6 +30,28 @@ 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 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); @@ -114,23 +139,526 @@ 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({ - 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( '.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', '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'], + ])( + '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 { + 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' } }), + ); + 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(), + ).toBe(`${hooksDir}/_`); + const commit = runCommit(tmp); + 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(['\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 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(tmp); + 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'])( + '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); + 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({ + message: expect.stringContaining( + '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' } }], + ['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).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); + rmSync(tmp, { recursive: true, force: true }); + } + }); + + it.each([ + ['.husky', 'reference-transaction'], + ['.husky', 'post-index-change'], + ['.husky', 'pre-receive'], + ['.husky/_', 'reference-transaction'], + ['.husky/_', 'post-index-change'], + ['.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(); + 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' }); + const before = runHook(); + expect(before.status).toBe(1); + expect(before.stderr).toContain('original hook rejected'); + expect(install()).toEqual({ + message: expect.stringContaining( + `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' }); + expect(runCommit(original, 'initial').status).toBe(0); + 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); + expect(runCommit(unmigrated, 'rejected').status).toBe(1); + process.chdir(migrated); + + expect(install()).toEqual({ + 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'); + 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); + } 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).toContain( + '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); + if (scenario !== 'disabled hooks') { + expect(enable(undefined, { replaceHusky: true }).message).toContain('skipping'); + } + 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.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 a1232af7e0..4d746c841f 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,120 @@ function getScopedHooksPath(scope: 'local' | 'worktree'): string { return result.status === 0 ? result.stdout?.toString().trim() : ''; } +type HuskyReplacement = 'automatic' | 'explicit' | 'non-empty' | null; + +/** 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 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 null; + } + // 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 null; + } + let hasEntries = false; + try { + const huskyDir = join(location.toplevel, '.husky'); + 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, join(huskyDir, '_')]) { + const stats = lstatSync(directory, { throwIfNoEntry: false }); + if (!stats) { + continue; + } + if (!stats.isDirectory() || stats.isSymbolicLink()) { + return null; + } + const names = readdirSync(directory); + if (directory === activeHooksDir && names.length > 0) { + hasEntries = true; + } + for (const name of names) { + if (directory === huskyDir && name === '_') { + continue; + } + hasEntries = 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 ( + !SUPPORTED_GIT_HOOK_NAMES.some((hook) => + lstatSync(join(location.baseDir, location.dir, hook), { throwIfNoEntry: false })?.isFile(), + ) || + !existsSync(join(location.toplevel, 'package.json')) + ) { + return null; + } + // 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 null; + } + for (const key of [ + 'dependencies', + 'devDependencies', + 'optionalDependencies', + 'peerDependencies', + ]) { + const dependencies = pkg[key]; + if (dependencies && typeof dependencies === 'object' && 'husky' in dependencies) { + return null; + } + } + if ( + pkg.scripts && + typeof pkg.scripts === 'object' && + Object.values(pkg.scripts).some( + (script) => typeof script === 'string' && /\bhusky\b/.test(script), + ) + ) { + return null; + } + } + } catch { + // Unreadable or invalid manifests are not evidence that Husky was removed. + return null; + } + if (replaceHusky) { + return 'explicit'; + } + return hasEntries ? 'non-empty' : 'automatic'; +} + function unsetScopedHooksPath(scope: 'local' | 'worktree'): InstallResult | null { const result = spawnSync('git', ['config', `--${scope}`, '--unset-all', 'core.hooksPath']); if (result.status == null) { @@ -562,6 +677,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 { @@ -592,18 +709,43 @@ 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 ( + !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) ) { - 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 }); @@ -633,6 +775,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 }; } @@ -640,17 +788,14 @@ 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 }); - if (result.isError) { - return result; - } - if (result.message) { - // Non-error skip messages (env disabled, foreign hooksPath, unsafe path, etc.) + const result = install(dir, { ignoreUserPreference: true, replaceHusky: options.replaceHusky }); + // Preserve errors, skip messages, and the explicit Husky replacement notice. + if (result.isError || result.message) { 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));