Git Commit pre-commit检查

记录一个pre-commit检查,判断当前项目是否使用正确的用户名来提交Commit。

如果使用的IDE是VS Code,默认情况.git文件夹是被隐藏的,需要打开设置,然后搜索“exclude”,取消隐藏.git 文件夹。然后添加一个pre-commit文件,并允许执行这个文件。

touch .git/hooks/pre-commit
touch .git/hooks/pre-commit.mjs
chmod +x .git/hooks/pre-commit

因为我想用Node.js写,所有在这里再调用pre-commit.mjs文件。

#!/bin/sh

# This shell script simply triggers your Node ESM script.
node .git/hooks/pre-commit.mjs

接下来添加我们需要检查的git用户名和邮箱地址。

#!/usr/bin/env node

import { execSync } from "node:child_process";

const REQUIRED_NAME = "Brandon Zhang";
const REQUIRED_EMAIL = "[email protected]";

try {
	const actualName = execSync("git config user.name").toString().trim();
	const actualEmail = execSync("git config user.email").toString().trim();

	if (actualName !== REQUIRED_NAME || actualEmail !== REQUIRED_EMAIL) {
		console.error(
			"\x1b[31m%s\x1b[0m",
			"--------------------------------------------------",
		);
		console.error("\x1b[31m%s\x1b[0m", "❌ GIT IDENTITY ERROR");
		console.error(`Expected: ${REQUIRED_NAME} <${REQUIRED_EMAIL}>`);
		console.error(`Found:    ${actualName} <${actualEmail}>`);
		console.error(
			"\x1b[31m%s\x1b[0m",
			"--------------------------------------------------",
		);
		console.log("To fix, run:");
		console.log(`  git config user.name "${REQUIRED_NAME}"`);
		console.log(`  git config user.email "${REQUIRED_EMAIL}"`);

		// Exit with non-zero to block the commit.
		process.exit(1);
	}

	console.log("\x1b[32m%s\x1b[0m", "✅ Identity verified.");
	process.exit(0);
} catch (error) {
	console.log(error);
	process.exit(1);
}

然后现在可以直接跑一下.git/hooks/pre-commit来测试代码。如果代码无误且你当前项目用的git用户不是你想使用的,那么终端将会报错提示你更改git用户。