当 githooks 集成 Gerrit 没有生成 Change-Id

907 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第 1 天,点击查看活动详情

Gerrit 的 Change-Id

每次 commit Gerrit 都会为我们生成一个 Change-Id,类似 UUID 的概念,需要有这个 Change-Id 我们才能 push 到 Gerrit 服务器。

生成方法有两种:

$ curl -Lo .git/hooks/commit-msg http://review.example.com/tools/hooks/commit-msg

or:

$ scp -p -P 29418 john.doe@review.example.com:hooks/commit-msg .git/hooks/

这时候在项目根目录就能找到 .git/hooks/commit-msg 文件,一次 commit 就会有一个 Change-Id。

Gerrit 的 Change-Id

详情参考 Gerrit Code Review - Change-Ids

Husky 结合 Gerrit

一般项目 commit 之前会对代码进行 lint,所以常用的配置工具是 husky + lint-staged。

但是 husky install 之后会有一个问题,husky 改变了 githooks 文件的目录,通过 git config core.hooksPath(默认在 $GIT_DIR/hooks/*) 可以查看到:

core.hooksPath

这就导致.git/hooks/commit-msg 不能执行也就不能生成 Change-Id 了,代码无法 push 到 Gerrit 服务器上了。

我们当然可以改变 Gerrit 生成 commit-msg 的目录,来实现 Husky 结合 Gerrit 完美运行。但我认为改变 githooks 目录方式并不好。

simple-git-hooks

我在 vitest 发现了一个好的 githooks 库 —— simple-git-hooks

Lightweight:

主要比 Husky 轻量,对我来讲就是没有改动默认的 githooks 目录,这个使用很简单:

  1. 安装
npm install simple-git-hooks --save-dev
  1. 在 package.json 里添加 simple-git-hooks
{
  "simple-git-hooks": {
    "pre-commit": "npx lint-staged",
    "pre-push": "cd ../../ && npm run format",

    // All unused hooks will be removed automatically by default
    // but you can use the `preserveUnused` option like following to prevent this behavior

    // if you'd prefer preserve all unused hooks
    "preserveUnused": true,

    // if you'd prefer preserve specific unused hooks
    "preserveUnused": ["commit-msg"]
  }
}
  1. 在 package.json 里添加 postinstall 脚本。
"scripts": {
    "postinstall": "simple-git-hooks"
  },
  1. 注册命令
npm i
// or
npx simple-git-hooks

需要注册默认情况下 simple-git-hooks 会删除无用的 hooks,为了保留 Gerrit 的 commit-msg hook 我们需要增加参数 preserveUnused

"simple-git-hooks": {
    "pre-commit": "npx lint-staged",
    "preserveUnused": [
      "commit-msg"
    ]
  },

真实项目应用

三步配置完成 simple-git-hooks 非常好用👍🏻。

结束

19 年我入职就一直想完美解决这个问题,这下我终于圆满了,花费两天公司主打的产品项目我也升级了,适配了 React18 和 CRA5 以及我最想要的 TypeScript 和 TailWind CSS,这个机会真是难得,所以免费加班也不累。

13031659853676_.pic.jpg