likes
comments
collection
share

如何在git代码提交阶段统一处理修改类型

作者站长头像
站长
· 阅读数 21

背景

在我们评审代码时候,经常会听见有同事说,这个代码提交备注不清楚到底是新增的需求,还是迭代更新,还是构建工具的更新,每次查找代码,都需要点开代码,对代码的修改记录来分辨。相信这种情况在不少项目开发中都存在这个情况,今天就来简单说明一下,如何在代码提交阶段,限制代码提交的类型,从此告别找代码时候的难受。

操作流程

  1. 我们在项目中安装husky、@commitlint/config-conventional、@commitlint/cli
    npm i husky
    npm i @commitlint/config-conventional @commitlint/cli
    
  2. 在package.json里面,配置prepare如下
    "scripts": {
        "prepare": "husky install"
    },
    
  3. 在项目根目录,也就是package.json同级,创建一个文件commitlint.config.js,该文件用于配置提交代码的commit前缀,如下:
    module.exports = {
      extends: ["@commitlint/config-conventional"],
      rules: {
        "subject-empty": [2, "never"], // subject 不为空
        "type-empty": [2, "never"], // type 不为空
        "type-enum": [
          2,
          "always",
          [
            "perf", // 优化:提升性能、体验
            "fix", // 修复:修复Bug
            "feat", // 特性:新功能
            "ci", // 构建:自动化构建配置和脚本变更
            "util", // 工具:开发工具变动(构建、脚手架工具等)
            "chore", // 流程:非src test的修改
            "build", // 发布:构建或外部依赖变更
            "docs", // 文档:修改文档
            "style", // 格式:空格, 分号等格式修复
            "refactor", // 重构:重构(及不修复错误也不添加功能)
            "test", // 测试:添加测试(单元测试、集成测试等)
            "revert" // 回滚:代码回退
          ],
        ],
      },
    };
    
  4. 在控制台输入命令,生成.husky目录,该目录下commit-msg文件中,限制了在commit时候的校验
    npx husky add .husky/commit-msg "npx --no-install commitlint --edit "$1""
    
  5. 这时候,配置也就结束了,测试一下
    // 未添加类型
    admin@MacBook-Pro % git add .
    admin@MacBook-Pro % git commit -m "测试代码提交校验"
    ⧗   input: 测试代码提交校验
    ✖   subject may not be empty [subject-empty]
    ✖   type may not be empty [type-empty]
    ✖   found 2 problems, 0 warnings
    ⓘ  Get help: https://github.com/conventional-changelog/commitlint/#what-is-commitlint
    husky - commit-msg hook exited with code 1 (error)
    
    // 添加类型
    admin@MacBook-Pro % git commit -m "ci: 测试代码提交校验"
    [master 86ce061] ci: 测试代码提交校验
     1 file changed, 4 deletions(-)
    

总结一下

在我创建提交的过程中,也遇见了文件格式错误,导致无法提交代码,一直报错的情况,报错如下:

env: sh\r: No such file or directory

这个是因为LF文件格式和CRLF文件格式里面空格或回车的格式不一致,导致代码提交时候检测错误,这时候,只需要切换commit-msg文件的格式即可。

转载自:https://juejin.cn/post/7268682336689848359
评论
请登录