droboticflow/scripts/lib/git-hooks.mjs

34 lines
1.6 KiB
JavaScript

import { execFileSync } from "node:child_process";
import { accessSync, constants, existsSync } from "node:fs";
import { resolve } from "node:path";
export function ensureGitHooks(root, { install = false, env = process.env } = {}) {
if (env.CI || env.HUSKY === "0" || !existsSync(resolve(root, ".git"))) return "skipped";
const git = (...args) =>
execFileSync("git", args, { cwd: root, env, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
let configured = "";
try {
configured = git("config", "--get", "core.hooksPath");
} catch {}
const expected = resolve(root, ".husky/_");
if (configured && resolve(root, configured) !== expected) throw Error("Custom hooksPath detected; left unchanged");
if (install && configured && resolve(root, configured) === expected) {
try {
accessSync(resolve(root, ".husky/_/pre-commit"), constants.X_OK);
accessSync(resolve(root, ".husky/_/h"), constants.R_OK);
accessSync(resolve(root, ".husky/pre-commit"), constants.R_OK);
return "active";
} catch {}
}
if (install) {
execFileSync(process.execPath, [resolve(root, "node_modules/husky/bin.js")], { cwd: root, env, stdio: "pipe" });
configured = git("config", "--get", "core.hooksPath");
}
if (!configured || resolve(root, configured) !== expected)
throw Error("core.hooksPath must resolve to this checkout's .husky/_");
accessSync(resolve(root, ".husky/_/pre-commit"), constants.X_OK);
accessSync(resolve(root, ".husky/_/h"), constants.R_OK);
accessSync(resolve(root, ".husky/pre-commit"), constants.R_OK);
return "active";
}