找回密码
 注册免广告
搜索
长桥证券羊毛 📈熊猫速汇 50 元券 🔥ByBit 交易所羊毛🐑MyFin 5 欧元羊毛 🔥
人人必备的 Wise 💳英、德、香港转运 📦,送 $25币安手续费 9 折Ledger 硬件钱包送比特币
最便宜的 eSIM 流量手机号 📱数字货币银行卡,注册送 7 美元💲IBKR开户送 $1000 股票 
查看: 175|回复: 1

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

[复制链接]
HelloWorld 发表于 2025-3-11 11:45:15 | 显示全部楼层 |阅读模式

注册免广告

您需要 登录 才可以下载或查看,没有账号?注册免广告

×
本帖最后由 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
  1. #!/bin/bash
  2. user_email=$(git config --get user.email)
  3. user_name=$(git config --get user.name)

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

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

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

  14.   exit 1
  15. 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仓库,账号也不一样,所以一般不会全局配置
如果帖子/回帖帮助到你,请给作者评分/点赞
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册免广告

本版积分规则

排行榜|意见建议|数字居民论坛

GMT+8, 2025-4-2 14:36

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表