repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/git-safe/git-wrapper.cjs

Raw
#!/usr/bin/env node

const { spawnSync } = require("node:child_process");

const realGit = "__PI_GIT_SAFE_REAL_GIT__";
const protectedCommands = new Set([
	"am",
	"commit",
	"merge",
	"pull",
	"push",
	"rebase",
]);
const globalValueOptions = new Set([
	"-C",
	"-c",
	"--config-env",
	"--exec-path",
	"--git-dir",
	"--namespace",
	"--super-prefix",
	"--work-tree",
]);
const commandValueOptions = {
	am: new Set([
		"-C",
		"-p",
		"--directory",
		"--empty",
		"--exclude",
		"--include",
		"--patch-format",
		"--quoted-cr",
		"--resolvemsg",
		"--whitespace",
	]),
	commit: new Set([
		"-C",
		"-F",
		"-c",
		"-m",
		"--author",
		"--cleanup",
		"--date",
		"--file",
		"--fixup",
		"--message",
		"--pathspec-from-file",
		"--reedit-message",
		"--reuse-message",
		"--squash",
		"--template",
		"--trailer",
	]),
	merge: new Set([
		"-F",
		"-m",
		"-s",
		"-X",
		"--cleanup",
		"--file",
		"--into-name",
		"--message",
		"--strategy",
		"--strategy-option",
	]),
	pull: new Set([
		"-s",
		"-X",
		"--cleanup",
		"--depth",
		"--deepen",
		"--negotiation-tip",
		"--server-option",
		"--shallow-exclude",
		"--shallow-since",
		"--strategy",
		"--strategy-option",
		"--upload-pack",
	]),
	push: new Set(["-o", "--exec", "--push-option", "--receive-pack", "--repo"]),
	rebase: new Set([
		"-s",
		"-X",
		"-x",
		"--empty",
		"--exec",
		"--onto",
		"--strategy",
		"--strategy-option",
		"--trailer",
		"--whitespace",
	]),
};
const shortValueOptions = {
	am: new Set(["C", "p"]),
	commit: new Set(["C", "F", "c", "m", "t"]),
	merge: new Set(["F", "m", "s", "X"]),
	pull: new Set(["o", "s", "X"]),
	push: new Set(["o"]),
	rebase: new Set(["s", "X", "x"]),
};
const shortAttachedValueOptions = {
	am: new Set(),
	commit: new Set(["S", "u"]),
	merge: new Set(),
	pull: new Set(),
	push: new Set(),
	rebase: new Set(),
};

function optionName(argument) {
	const equals = argument.indexOf("=");
	return equals < 0 ? argument : argument.slice(0, equals);
}

function consumesNext(argument, options) {
	return !argument.includes("=") && options.has(optionName(argument));
}

function consumesCommandValue(argument, options) {
	if (argument.includes("=")) return false;
	if (options.has(argument)) return true;
	if (!argument.startsWith("--")) return false;
	return [...options].filter((option) => option.startsWith(argument)).length === 1;
}

function commandPosition(args) {
	for (let index = 0; index < args.length; index++) {
		const argument = args[index];
		if (argument === "--") return index + 1;
		if (!argument.startsWith("-")) return index;
		if (consumesNext(argument, globalValueOptions)) index++;
	}
	return -1;
}

function addAlias(aliases, config) {
	const match = config.match(/^alias\.([^=]+)=(.*)$/isu);
	if (match) aliases.set(match[1].toLowerCase(), match[2]);
}

function addArgumentAliases(aliases, args, commandIndex) {
	for (let index = 0; index < commandIndex; index++) {
		const argument = args[index];
		if (argument === "-c") {
			addAlias(aliases, args[++index] ?? "");
			continue;
		}
		if (argument.startsWith("-c") && argument.length > 2) {
			addAlias(aliases, argument.slice(2));
			continue;
		}
		const configEnv = argument.startsWith("--config-env=")
			? argument.slice("--config-env=".length)
			: argument === "--config-env"
				? (args[++index] ?? "")
				: undefined;
		if (configEnv !== undefined) {
			const equals = configEnv.indexOf("=");
			if (equals >= 0) {
				const name = configEnv.slice(0, equals);
				const variable = configEnv.slice(equals + 1);
				addAlias(aliases, `${name}=${process.env[variable] ?? ""}`);
			}
		}
	}
}

function temporaryAliases(args, commandIndex) {
	const aliases = new Map();
	const count = Number.parseInt(process.env.GIT_CONFIG_COUNT ?? "0", 10);
	for (let index = 0; index < count; index++) {
		const key = process.env[`GIT_CONFIG_KEY_${index}`] ?? "";
		const value = process.env[`GIT_CONFIG_VALUE_${index}`] ?? "";
		addAlias(aliases, `${key}=${value}`);
	}
	addArgumentAliases(aliases, args, commandIndex);
	return aliases;
}

function splitAlias(value) {
	const words = [];
	let word = "";
	let quote = "";
	let escaped = false;
	let started = false;
	for (const character of value.trim()) {
		if (escaped) {
			word += character;
			escaped = false;
			started = true;
			continue;
		}
		if (character === "\\" && quote !== "'") {
			escaped = true;
			continue;
		}
		if ((character === "'" || character === '"') && !quote) {
			quote = character;
			started = true;
			continue;
		}
		if (character === quote) {
			quote = "";
			continue;
		}
		if (/\s/u.test(character) && !quote) {
			if (started) words.push(word);
			word = "";
			started = false;
			continue;
		}
		word += character;
		started = true;
	}
	if (escaped) {
		word += "\\";
		started = true;
	}
	if (started) words.push(word);
	return words;
}

function configuredAlias(globalArgs, command) {
	const result = spawnSync(
		realGit,
		[...globalArgs, "config", "--get", `alias.${command}`],
		{
			encoding: "utf8",
			env: process.env,
		},
	);
	return result.status === 0 ? result.stdout.trim() : undefined;
}

function isBuiltinCommand(command) {
	const result = spawnSync(realGit, ["--list-cmds=builtins"], {
		encoding: "utf8",
		env: process.env,
	});
	return result.status === 0 && result.stdout.split(/\s+/u).includes(command);
}

function resolveCommand(args) {
	const position = commandPosition(args);
	if (position < 0 || position >= args.length) return undefined;
	const globalArgs = args.slice(0, position);
	const aliases = temporaryAliases(args, position);
	const seen = new Set();
	let command = args[position];
	let commandArgs = args.slice(position + 1);
	while (!protectedCommands.has(command)) {
		const key = command.toLowerCase();
		if (seen.has(key)) break;
		seen.add(key);
		const alias = aliases.get(key) ?? configuredAlias(globalArgs, command);
		if (!alias || alias.startsWith("!") || isBuiltinCommand(command)) break;
		const expansion = [...splitAlias(alias), ...commandArgs];
		const expandedPosition = commandPosition(expansion);
		if (expandedPosition < 0 || expandedPosition >= expansion.length) break;
		addArgumentAliases(aliases, expansion, expandedPosition);
		globalArgs.push(...expansion.slice(0, expandedPosition));
		command = expansion[expandedPosition];
		commandArgs = expansion.slice(expandedPosition + 1);
	}
	return { command, args: commandArgs };
}

function isNoVerifyLongOption(command, argument) {
	const minimum = command === "am" ? "--no-v" : "--no-veri";
	return argument.length >= minimum.length && "--no-verify".startsWith(argument);
}

function inspectShortOptions(command, argument) {
	if (!/^-[^-]/u.test(argument)) return { blocked: false, consumesNext: false };
	const options = argument.slice(1);
	const values = shortValueOptions[command];
	const attachedValues = shortAttachedValueOptions[command];
	for (let index = 0; index < options.length; index++) {
		const option = options[index];
		if ((command === "am" || command === "commit") && option === "n") {
			return { blocked: true, consumesNext: false };
		}
		if (values.has(option)) {
			return {
				blocked: false,
				consumesNext: index === options.length - 1,
			};
		}
		if (attachedValues.has(option)) {
			return { blocked: false, consumesNext: false };
		}
	}
	return { blocked: false, consumesNext: false };
}

function hasNoVerifyOption(args) {
	const resolved = resolveCommand(args);
	if (!resolved || !protectedCommands.has(resolved.command)) return false;
	const valueOptions = commandValueOptions[resolved.command];
	for (let index = 0; index < resolved.args.length; index++) {
		const argument = resolved.args[index];
		if (argument === "--" || argument === "--end-of-options") return false;
		if (isNoVerifyLongOption(resolved.command, argument)) return true;
		const short = inspectShortOptions(resolved.command, argument);
		if (short.blocked) return true;
		if (short.consumesNext || consumesCommandValue(argument, valueOptions)) index++;
	}
	return false;
}

const args = process.argv.slice(2);
if (hasNoVerifyOption(args)) {
	console.error(
		"git-safe blocked --no-verify. Fix the hook failure or ask the user for help.",
	);
	process.exit(126);
}

const editorQuery =
	args[commandPosition(args)] === "var" &&
	(args[commandPosition(args) + 1] === "GIT_EDITOR" ||
		args[commandPosition(args) + 1] === "GIT_SEQUENCE_EDITOR");
const env = { ...process.env };
if (!editorQuery) {
	env.GIT_EDITOR = "true";
	env.GIT_SEQUENCE_EDITOR = "true";
	env.GIT_MERGE_AUTOEDIT = "no";
}
const result = spawnSync(realGit, args, { stdio: "inherit", env });
if (result.error) {
	console.error(result.error.message);
	process.exit(127);
}
if (result.signal) process.kill(process.pid, result.signal);
process.exit(result.status ?? 1);