|
| 1 | +#!/usr/bin/env bun |
| 2 | +import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs" |
| 3 | +import { EOL } from "node:os" |
| 4 | +import { isAbsolute, join, resolve } from "node:path" |
| 5 | +import { execFileSync } from "node:child_process" |
| 6 | + |
| 7 | +const BEGIN_MARKER = "# >>> fission biome pre-commit (bun run hooks:install) >>>" |
| 8 | +const END_MARKER = "# <<< fission biome pre-commit <<<" |
| 9 | + |
| 10 | +const HOOK_BLOCK = [ |
| 11 | + BEGIN_MARKER, |
| 12 | + '"$(git rev-parse --show-toplevel)/fission/scripts/hooks/pre-commit" "$@" || exit $?', |
| 13 | + END_MARKER, |
| 14 | +].join("\n") |
| 15 | + |
| 16 | +function git(...args: string[]): string { |
| 17 | + return execFileSync("git", args, { encoding: "utf8" }).trim() |
| 18 | +} |
| 19 | + |
| 20 | +function resolveHooksDir(): string { |
| 21 | + let configuredPath: string | undefined |
| 22 | + try { |
| 23 | + configuredPath = git("config", "--get", "core.hooksPath") |
| 24 | + } catch { |
| 25 | + // no-op |
| 26 | + } |
| 27 | + |
| 28 | + if (configuredPath) { |
| 29 | + return isAbsolute(configuredPath) |
| 30 | + ? configuredPath |
| 31 | + : resolve(git("rev-parse", "--show-toplevel"), configuredPath) |
| 32 | + } |
| 33 | + |
| 34 | + return join(resolve(git("rev-parse", "--git-common-dir")), "hooks") |
| 35 | +} |
| 36 | + |
| 37 | +const hooksDir = resolveHooksDir() |
| 38 | +const hookFile = join(hooksDir, "pre-commit") |
| 39 | + |
| 40 | +const existing = existsSync(hookFile) ? readFileSync(hookFile, "utf8") : undefined |
| 41 | + |
| 42 | +if (existing?.includes(BEGIN_MARKER)) { |
| 43 | + console.log(`Biome pre-commit hook already installed in ${hookFile}`) |
| 44 | + process.exit(0) |
| 45 | +} |
| 46 | + |
| 47 | +mkdirSync(hooksDir, { recursive: true }) |
| 48 | + |
| 49 | +const contents = |
| 50 | + existing === undefined |
| 51 | + ? `#!/usr/bin/env sh\n\n${HOOK_BLOCK}\n` |
| 52 | + : `${existing.replace(/\n*$/, "\n")}\n${HOOK_BLOCK}\n` |
| 53 | + |
| 54 | +writeFileSync(hookFile, contents) |
| 55 | +chmodSync(hookFile, 0o755) |
| 56 | + |
| 57 | +console.log( |
| 58 | + [ |
| 59 | + existing === undefined |
| 60 | + ? `Installed Biome pre-commit hook at ${hookFile}` |
| 61 | + : `Appended Biome pre-commit hook to the existing ${hookFile}`, |
| 62 | + "Bypass it for a single commit with: git commit --no-verify", |
| 63 | + `Uninstall it by deleting the block between the "${BEGIN_MARKER.slice(2)}" markers.`, |
| 64 | + ].join(EOL) |
| 65 | +) |
0 commit comments