HelloWorld 发表于 2025-3-11 11:45:15

git 自动检测 config user.email 和 user.name 没设置终止 push 的方式

本帖最后由 HelloWorld 于 2025-3-11 11:47 编辑

如果你没设置过 user.email 和 user.name,git 本身不会阻止 push,但可能会把电脑系统的昵称和邮箱拿去作为 commit 的贡献者 push

如果你设置过 global 的 user.email,任何新项目,如果没有额外配置该项目的 user.email,git 会将 global 的 user.email 拿去 push

假设有一种场景,如果你设置了 global user.email,但是很多项目想分开用不同 email,如果你忘记对该项目单独配置,则 global user.email 会被 push,并永久保留在 commit 历史里

解决方法是不设置 global user.email,如果你设置了,可以删除掉 global user.email,然后写个 git 全局脚本,在每次 push 时检测项目里没有 user.email 时终止 push,并提示你配置 user.email 和 user.name

步骤 1:新建文件夹 mkdir -p ~/.git-templates/hooks
步骤 2:设置 git 使用上述文件夹里的模板 git config --global init.templatedir '~/.git-templates'
步骤 3:编写脚本 vim ~/.git-templates/hooks/pre-push #!/bin/bash
user_email=$(git config --get user.email)
user_name=$(git config --get user.name)

if [ -z "$user_name" ] || [ -z "$user_email" ]; then
echo "❌ Push terminated: Git user.name and user.email must be set."

if [ -z "$user.name" ]; then
    echo "👉 user.name is not set."
    echo "   Run: git config user.name 'Your Name'"
fi

if [ -z "$user_email" ]; then
    echo "👉 user.email is not set."
    echo "   Run: git config user.email '[email protected]'"
fi

exit 1
fi步骤 4:给脚本增加可执行权限 chmod +x .git/hooks/pre-push

以上设置仅对新 clone 或 init 的仓库自动生效。如果你有一个已经存在的仓库,需要手动复制一次:cp ~/.git-templates/hooks/pre-push your-existing-project/.git/hooks/

其它相关文章:
在一台 Mac 上管理多个 github 账号的方式
给 .ssh/id_rsa 设置密码或许是件蠢事

HackerTerry 发表于 2025-3-13 00:00:34

我是不同的项目代码存放在不同的git仓库,账号也不一样,所以一般不会全局配置
页: [1]
查看完整版本: git 自动检测 config user.email 和 user.name 没设置终止 push 的方式