Skip to content

yorkie 管理 git 钩子

yorkie 是尤大神 fork Husky 的一个分支,有如下特点:

  1. 优先考虑 package.json 位于目录旁边的位置.git,而不是硬编码向上搜索。这避免了当 lerna monorepo 中的根包和子包都依赖于 husky 时出现的问题,它会感到困惑并使用错误路径重复更新根 git hooks。
  2. 更改了读取钩子的位置 package.json

vue 创建的项目默认自带了 yorkie

安装

bash
npm i -D yorkie lint-staged chalk

各个依赖的版本(node >= 16)

json
"devDependencies": {
  "chalk": "^5.3.0",
  "lint-staged": "^15.2.5",
  "yorkie": "^2.0.0"
}

配置

package.json 文件内添加

json
  "gitHooks": {
    "pre-commit": "lint-staged",
    "commit-msg": "node ./commit-msg"
  },
  "lint-staged": {
    "*.{vue,js,jsx}": [
      "npm run lint -- --fix",
      "git add"
    ]
  }

新建 commit-msg 文件

node >= 16 若是低版本的 node 环境,建议降低依赖包版本

js
#! /usr/bin/env node
const { execSync } = require("child_process");
(async () => {
  const { Chalk } = await import("chalk");
  const chalk = new Chalk();

  // 分支校验
  const res = execSync("git rev-parse --abbrev-ref HEAD");
  if (res.toString().trim() === "master") {
    console.error(
      `\n\n${chalk.bgRed.white(" ERROR ")} ${chalk.red(
        "禁止直接往master分支上提交代码,请在特性分支上操作."
      )}\n\n`
    );
    process.exit(1);
  }

  // commit-msg格式校验

  const msgPath = process.env.GIT_PARAMS;
  const msg = require("fs").readFileSync(msgPath, "utf-8").trim();

  const commitRE =
    /^(revert: )?(feat|fix|polish|docs|style|refactor|perf|test|workflow|ci|chore|types|build)(\(.+\))?: .{1,50}/;

  if (!commitRE.test(msg)) {
    console.log();
    console.error(
      `${chalk.bgRed.white(" ERROR ")} ${chalk.red(
        "invalid commit message format."
      )}\n\n` +
        `${chalk.red(
          "  Proper commit message format is required for automated changelog generation. Examples:\n\n"
        )}` +
        `${chalk.green("    feat(compiler): add 'comments' option")}\n` +
        `${chalk.green(
          "    fix(v-model): handle events on blur (close #28)"
        )}\n\n` +
        `${chalk.red(
          "  See https://github.com/vuejs/vue/blob/dev/.github/COMMIT_CONVENTION.md for more details.\n"
        )}` +
        `${chalk.red(
          " You can also use " +
            chalk.cyan("npm run commit") +
            " to interactively generate a commit message.\n"
        )}`
    );
    process.exit(1);
  }
})();

效果