在 macos 终端中配置 git 提交模板需三步:创建 ~/.gitmessage.txt 模板文件、执行 git config --global commit.template ~/.gitmessage.txt 全局启用、用 git config --global core.editor 配置编辑器后运行 git commit 验证生效。
在 macos 终端中配置 git 提交模板,让每次 git commit 自动加载规范格式,核心是三步:创建模板文件、配置 git 使用它、验证生效。整个过程不依赖 ide,纯命令行完成,适配所有项目。
创建规范的提交模板文件
推荐在用户主目录下新建统一模板(全局可用),例如 ~/.gitmessage.txt:
# <type>(<scope>): <subject> # 例:feat(auth): add email validation # fix(api): handle null response <h1>Type (必填): feat|fix|docs|style|refactor|test|chore</h1> <h1>Scope (可选): 模块名,如 auth、api、ui</h1> <h1>Subject (必填): ≤50 字,动词开头,不加句号</h1> <h1>Body (可选):</h1> <h1>- 描述变更原因、方案、影响范围</h1> <h1>- 每行不超过 72 字符</h1> <h1>Footer (可选):</h1> <h1>BREAKING CHANGE: ...</h1> <h1>Closes #123</h1> <h1>Ref #456</h1></subject></scope></type>
用以下命令一键创建并写入(复制粘贴即可):
cat > ~/.gitmessage.txt (<scope>): <subject> # 例:feat(auth): add email validation # fix(api): handle null response <h1>Type (必填): feat|fix|docs|style|refactor|test|chore</h1> <h1>Scope (可选): 模块名,如 auth、api、ui</h1> <h1>Subject (必填): ≤50 字,动词开头,不加句号</h1> <h1>Body (可选):</h1> <h1>- 描述变更原因、方案、影响范围</h1> <h1>- 每行不超过 72 字符</h1> <h1>Footer (可选):</h1> <h1>BREAKING CHANGE: ...</h1> <h1>Closes #123</h1> <h1>Ref #456</h1> <p>EOF</p></subject></scope>
配置 Git 全局使用该模板
执行命令让所有仓库默认加载这个模板:
git config --global commit.template ~/.gitmessage.txt
如果只想对当前项目生效(比如团队强制要求),进入项目根目录后运行:
-
git config commit.template .gitmessage.txt(需先将模板复制到项目根目录)
设置好编辑器并验证效果
确保 Git 能打开编辑器填写内容。macOS 推荐用 VS Code 或系统自带的 nano:
- 用 VS Code:
git config --global core.editor "code --wait" - 用 nano(免安装):
git config --global core.editor nano
验证是否生效:
- 执行
git commit(暂存区需有改动) - 编辑器应自动打开,并显示你刚创建的模板内容
- 按规范填写后保存退出,提交即完成
进阶:加一层校验防误提交
仅靠模板不能阻止随意提交。可在项目中启用 commit-msg 钩子做基础校验(推荐放在团队项目里):
- 在项目
.git/hooks/commit-msg中创建脚本(需chmod +x) - 检查首行是否含
feat:、fix:等前缀,且长度 ≤50 字 - CI 流水线中再用
commitlint做最终把关
这样既保持本地轻量,又守住规范底线。











