Git 提交规范

  1. 前言
    在提交commit信息时,为了统一规范commit信息,可以在Git Hooks中编写修改commit-msg脚本来先 实现自定义commit信息校验规则

  1. git hooks 所在路径
    hooks脚本在git项目中的根目录下的.git目录,具体路径为:.git/hooks/
    目录内容如下图所示:


    图1.png

  1. 修改脚本内容
    本次为了校验commit信息是否符合提交规范,所以我们在commit-msg这个hook中编写脚本内容

    #! /usr/bin/env python
    # -*- encoding: utf-8 -*-
    import sys
    import re
    
    # 可以根据自己团队的需求来修改正则表达式
    pattern = re.compile(
    "^(feat|fix|polish|docs|style|refactor|perf|test|workflow|ci|chore|types)(\(.+\))?: .{1,50}")
    
    def validate_commit_msg(msg: str):   
        """ 
        校验git commit 内容格式是否满足要求    
        :param msg:    
        :return: void   
        """   
        if msg.startswith("Revert"):
            sys.exit(0)
        elif msg.startswith("Merge"):
            sys.exit(0)
        elif re.match(pattern, msg):
            sys.exit(0)    
        else:        
            print("invalid commit format")
            sys.exit(1)
    if __name__ == "__main__":   
        # 在commit-msg 这个hook运行时会传入一个保存commit信息的文件地址
        # 需要从这个文件中读取提交信息
        file_name = sys.argv[1]
        print(file_name)    
        commit_msg = ""   
        with open(file_name, encoding="utf-8") as file:
            for line in file.readlines():
                commit_msg += line    
        validate_commit_msg(commit_msg)
    

  1. IDEA插件
    可以在Jetbrain中安装Git Commit Template 插件配合使用


  2. 注意事项
    需要在环境变量中加入Python可执行目录,不然这个脚本会执行失败

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容