golang自动化git提交信息格式校验插件gommit的使用

Golang自动化Git提交信息格式校验插件Gommit的使用

Gommit是一个用于分析Git提交信息以确保其遵循定义模式的Golang工具。

安装

从发布页面下载适用于您架构的gommit二进制文件。

配置

定义.gommit.toml文件

在项目根目录创建.gommit.toml文件,例如:

[config]
exclude-merge-commits=true
check-summary-length=true
summary-length=50

[matchers]
all="(?:ref|feat|test|fix|style)\\(.*?\\) : .*?\n(?:\n?(?:\\* |  ).*?\n)*"

[examples]
a_simple_commit="""
[feat|test|ref|fix|style](module) : A commit message
"""
an_extended_commit="""
[feat|test|ref|fix|style](module) : A commit message

* first line
* second line
* and so on...
"""

配置项说明

  • exclude-merge-commits: 如果设置为true,将不检查合并提交的消息
  • check-summary-length: 如果设置为true,检查提交摘要长度,默认为50个字符
  • summary-length: 可以覆盖默认的摘要长度值(50),仅在check-summary-length为true时使用

匹配器(Matchers)

您可以定义任意数量的正则表达式匹配器,命名由您决定,它们都将与提交消息进行比较,直到一个匹配成功。

示例(Examples)

提供示例帮助用户理解问题所在,与匹配器一样,您可以定义任意数量的示例,如果发生错误,它们都将显示给用户。

使用方式

基本命令

确保您的提交信息保持一致

用法:
  gommit [command]

可用命令:
  check       检查确保消息遵循定义的模式
  version     显示应用版本

标志:
      --config string    (默认 ".gommit.toml")
  -h, --help            帮助信息

使用 "gommit [command] --help" 获取命令的更多信息

check命令

检查确保消息遵循定义的模式

用法:
  gommit check [flags]
  gommit check [command]

可用命令:
  commit      检查提交消息
  message     检查消息
  range       检查提交范围内的消息

标志:
  -h, --help   帮助信息

全局标志:
      --config string    (默认 ".gommit.toml")

使用 "gommit check [command] --help" 获取命令的更多信息

check commit

检查提交消息

用法:
  gommit check commit [id] [&path] [flags]

标志:
  -h, --help   帮助信息

全局标志:
      --config string    (默认 ".gommit.toml")

检查一个提交(目前不支持短ID): gommit check commit aeb603ba83614fae682337bdce9ee1bad1da6d6e

check message

检查消息

用法:
  gommit check message [message] [flags]

标志:
  -h, --help   帮助信息

全局标志:
      --config string    (默认 ".gommit.toml")

检查一条消息,在脚本中很有用,例如当您想将其与git钩子一起使用时: gommit check message "Hello"

check range

检查范围内的消息

用法:
  gommit check range [revisionfrom] [revisionTo] [&path] [flags]

标志:
  -h, --help   帮助信息

全局标志:
      --config string    (默认 ".gommit.toml")

检查提交范围,如果您想在CI中使用它来确保分支中的所有提交都遵循您的约定,这很有用:

  • 使用相对引用: gommit check range master~2^ master
  • 使用绝对引用: gommit check range dev test
  • 使用提交ID(目前不支持短ID): gommit check range 7bbb37ade3ff36e362d7e20bf34a1325a15b 09f25db7971c100a8c0cfc2b22ab7f872ff0c18d

实际应用

Git钩子

可以使用gommit在创建每个提交时验证它们。为此,您需要使用commit-msg钩子,您可以用以下脚本替换默认脚本:

#!/bin/sh

gommit check message "$(cat "$1")";

Travis CI

在Travis中,默认情况下不会克隆所有历史记录,默认深度为50次提交。首先,我们从发布页面下载二进制文件,并在.travis.yml中添加:

before_install:
  - wget -O /tmp/gommit https://github.com/antham/gommit/releases/download/v2.0.0/gommit_linux_386 && chmod 777 /tmp/gommit

然后我们可以添加一个Perl脚本来分析针对master的提交范围:

#!/bin/perl

`git ls-remote origin master` =~ /([a-f0-9]{40})/;

my $refHead = `git rev-parse HEAD`;
my $refTail = $1;

chomp($refHead);
chomp($refTail);

if ($refHead eq $refTail) {
    exit 0;
}

system "gommit check range $refTail $refHead";

if ($? > 0) {
    exit 1;
}

最后在.travis.yml中,使其在出错时崩溃:

script: perl test-branch-commit-messages-in-travis.pl

CircleCI

在CircleCI(2.0)中,有一个描述当前分支的环境变量:CIRCLE_BRANCH。首先,我们从发布页面下载二进制文件,并在.circleci/config.yml中添加:

- run:
    name: Get gommit binary
    command: |
      mkdir /home/circleci/bin
      wget -O ~/bin/gommit https://github.com/antham/gommit/releases/download/v2.0.0/gommit_linux_386 && chmod 777 ~/bin/gommit

然后我们可以针对master运行gommit:

- run:
    name: Run gommit
    command: |
      if [ $CIRCLE_BRANCH != 'master' ]; then ~/bin/gommit check range $(git rev-parse origin/master) $CIRCLE_BRANCH ; fi

第三方库

Nodejs

  • gommitjs: 一个Nodejs的gommit包装器

更多关于golang自动化git提交信息格式校验插件gommit的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang自动化git提交信息格式校验插件gommit的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


使用gommit进行Git提交信息格式校验

gommit是一个Go语言开发的Git提交信息格式校验工具,可以帮助团队规范提交信息的格式。下面我将详细介绍如何使用gommit。

安装gommit

首先安装gommit工具:

go install github.com/antham/gommit@latest

基本配置

在项目根目录下创建.gommit.yml配置文件,定义提交信息的校验规则:

# .gommit.yml
message:
  # 提交信息必须匹配的正则表达式
  pattern: '^(feat|fix|docs|style|refactor|test|chore)\([a-z]+\): [A-Z].*$'
  
  # 错误提示信息
  error: "提交信息格式不正确,请使用以下格式:<type>(<scope>): <description>"
  
  # 示例
  example: |
    feat(auth): 添加用户登录功能
    fix(api): 修复500错误

常用配置选项

message:
  # 必须包含的关键词
  required: ["JIRA-"]
  
  # 禁止包含的关键词
  forbidden: ["TODO", "FIXME"]
  
  # 最小长度限制
  minLength: 10
  
  # 最大长度限制
  maxLength: 100
  
  # 允许的提交类型
  allowedTypes: ["feat", "fix", "docs", "style", "refactor", "test", "chore"]

集成到Git钩子

可以将gommit集成到Git的pre-commit钩子中,在提交前自动校验:

  1. 在项目根目录创建.git/hooks/pre-commit文件(如果没有的话)
  2. 添加以下内容:
#!/bin/sh

# 运行gommit校验
gommit check
if [ $? -ne 0 ]; then
  echo "提交信息校验失败,请修改后重试"
  exit 1
fi
  1. 给钩子文件添加执行权限:
chmod +x .git/hooks/pre-commit

在CI/CD中集成

也可以在CI/CD流程中加入gommit检查,例如在GitHub Actions中:

name: Check Commit Messages

on: [push]

jobs:
  check-commits:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Install gommit
        run: go install github.com/antham/gommit@latest
      - name: Check commit messages
        run: gommit check

高级用法:自定义模板

可以创建更复杂的校验模板:

templates:
  - name: conventional
    title: Conventional Commits
    description: 遵循Conventional Commits规范的提交信息
    pattern: '^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(\([a-z]+\))?: [A-Z].*$'
    example: |
      feat: 添加新功能
      fix(server): 修复服务器崩溃问题
      docs: 更新README文件

忽略特定提交

可以通过.gommitignore文件忽略某些提交的校验:

# .gommitignore
^Merge branch
^Revert
^Initial commit

Go代码示例

如果你想在Go程序中集成gommit的校验功能,可以使用以下代码:

package main

import (
	"fmt"
	"os"

	"github.com/antham/gommit"
)

func main() {
	// 加载配置
	config, err := gommit.LoadConfiguration(".gommit.yml")
	if err != nil {
		fmt.Printf("加载配置失败: %v\n", err)
		os.Exit(1)
	}

	// 获取最近的提交信息
	message, err := gommit.GetMessage("HEAD")
	if err != nil {
		fmt.Printf("获取提交信息失败: %v\n", err)
		os.Exit(1)
	}

	// 校验提交信息
	match, err := gommit.MatchMessage(message, config)
	if err != nil {
		fmt.Printf("校验失败: %v\n", err)
		os.Exit(1)
	}

	if !match {
		fmt.Println("提交信息不符合规范:")
		fmt.Println(config.Message.Error)
		fmt.Println("示例:")
		fmt.Println(config.Message.Example)
		os.Exit(1)
	}

	fmt.Println("提交信息校验通过")
}

总结

gommit是一个强大的Git提交信息校验工具,通过合理配置可以:

  1. 强制团队使用统一的提交信息格式
  2. 提高代码提交的可读性和可追溯性
  3. 自动化校验流程,减少人工检查的工作量
  4. 与现有Git工作流无缝集成

建议团队在项目初期就引入gommit,建立良好的提交习惯,这对长期的项目维护非常有帮助。

回到顶部