Appearance
Hook 管理
Git Doctor 提供 Git Hook 管理功能,在提交前自动检查代码质量和安全风险。
支持的 Hook
| Hook 类型 | 触发时机 | 功能 |
|---|---|---|
| pre-commit | 提交前 | 敏感信息检测 |
| commit-msg | 编写消息后 | 提交消息规范检查 |
安装 Hook
安装所有 Hook
Git Doctor: 安装所有 Git Hook或点击仓库管理视图工具栏的盾牌图标。
单独安装
Git Doctor: 安装敏感信息检测 Hook # pre-commit
Git Doctor: 安装提交拦截 Hook # commit-msgPre-commit Hook
功能说明
在每次 git commit 前自动扫描暂存区文件:
敏感文件名检测
.env、.env.localid_rsa、id_dsa、id_ecdsacredentials.json
敏感扩展名检测
.pem、.key、.p12.jks、.keystore
敏感内容检测
- AWS Access Key / Secret Key
- GitHub Token
- 私钥文件内容
- 密码、API Key 等
检测示例
bash
$ git commit -m "add config"
Git Doctor: 敏感信息检测
━━━━━━━━━━━━━━━━━━━━━━━
🔴 发现 2 个高风险问题:
1. config/.env
└─ 敏感文件名: .env
2. src/api/client.ts:15
└─ AWS Access Key: AKIAIOSFODNN7EXAMPLE
提交已阻止。请移除敏感信息后重试。
提示:使用 --no-verify 跳过检查(不推荐)Commit-msg Hook
功能说明
检查提交消息是否符合 Conventional Commits 规范:
消息长度检查
- 最小长度:10 字符(可配置)
格式检查
type(scope): subject- type 必须是有效类型
内容检查
- subject 不能为空
- subject 首字母不能大写(可选)
有效的 type
| Type | 说明 |
|---|---|
| feat | 新功能 |
| fix | Bug 修复 |
| docs | 文档更新 |
| style | 代码格式(不影响功能) |
| refactor | 重构 |
| perf | 性能优化 |
| test | 测试相关 |
| build | 构建系统 |
| ci | CI 配置 |
| chore | 其他杂项 |
| revert | 回滚提交 |
检测示例
bash
$ git commit -m "update"
Git Doctor: 提交消息检查
━━━━━━━━━━━━━━━━━━━━━━━
❌ 提交消息不符合规范:
问题:缺少 type 前缀
正确格式:type(scope): subject
示例:feat(parser): add tree object support
提交已阻止。请修改提交消息后重试。卸载 Hook
卸载所有 Hook
Git Doctor: 卸载所有 Git Hook单独卸载
Git Doctor: 卸载敏感信息检测 Hook # pre-commit
Git Doctor: 卸载提交拦截 Hook # commit-msg切换 Hook 状态
临时禁用/启用 Hook:
Git Doctor: 切换敏感信息检测 Hook
Git Doctor: 切换提交消息检查 Hook临时跳过
在特殊情况下需要跳过 Hook 检查:
bash
# 跳过所有 Hook
git commit --no-verify -m "emergency fix"
# 简写
git commit -n -m "emergency fix"注意
--no-verify 会跳过所有 Hook 检查,请谨慎使用。
手动扫描
不提交,仅扫描暂存区:
Git Doctor: 扫描暂存区敏感信息配置选项
json
{
// 提交信息最小长度
"gitDoctor.commitMessageMinLength": 10,
// 是否检测 Conventional Commits 规范
"gitDoctor.enableConventionalCommits": true
}Hook 文件位置
Hook 脚本安装在 .git/hooks/ 目录:
.git/hooks/
├── pre-commit # 敏感信息检测
└── commit-msg # 消息规范检查与其他工具共存
Git Doctor 的 Hook 可以与其他工具(如 Husky、lint-staged)共存:
- Git Doctor Hook 会检查是否存在其他 Hook
- 如果存在,会在末尾追加而不是覆盖
- 卸载时只会移除 Git Doctor 添加的部分
最佳实践
1. 团队统一配置
在项目中提交 Hook 配置,确保团队统一:
bash
# 在 package.json 中添加 postinstall 脚本
{
"scripts": {
"postinstall": "git-doctor install-hooks"
}
}2. CI 中验证
在 CI 中重复检查,防止 --no-verify 绕过:
yaml
- name: Check Commit Messages
run: |
git log --format='%s' -1 | grep -E '^(feat|fix|docs|style|refactor|test|chore)'3. 渐进式采用
初期可以只启用 pre-commit(敏感信息检测),待团队适应后再启用 commit-msg。