Shell脚本案例:Git规范commit-msg

6 篇文章 1 订阅

启用本地commit-msg检查

git本身自带hooks入口,支持用户通过脚本的方式在git命令执行前后进行一些检查工作,使用的脚本语言为Shell。相关hook脚本需放在本地.git/hooks目录下,打开该目录可以看到很多示例脚本,我们要用到的正是commit-msg这个。
在这里插入图片描述

只需要将对应脚本的后缀.sample去掉即可启动该脚本,然后我们将脚本内容修改为自己的脚本逻辑即可:

#!/bin/sh

COMMIT_MSG=`cat $1 | egrep "^(feat|fix|docs|chore)\(\w+\)?:\s(\S|\w)+"`

if [ "$COMMIT_MSG" = "" ]; then
  echo "Commit Message 不规范,请检查!\n"
  exit 1
fi

if [ ${#COMMIT_MSG} -lt 15 ]; then
  echo "Commit Message 太短了,请再详细点!\n"
  exit 1
fi

同步到远程仓库

git是无法将.git下的文件提交到仓库的,所以上述修改只能在本地生效,为了让团队可以共享这个检查规则,可以把上述脚本文件放在一个新建目录下,然后用gradle脚本同步到.git/hooks目录下:
比如在项目中新建ci这个目录:

ci
├── git-commit-msg.sh : 上面的脚本文件
└── script.gradle:用于安装sh脚本

其中script.gradle内容如下:

import java.security.MessageDigest

final def rootPath = rootProject.rootDir.path
final def oldFile = rootProject.file("$rootPath/.git/hooks/commit-msg")
final def newFile = rootProject.file("$rootPath/ci/git-commit-msg.sh")
if (!oldFile.exists() || !oldFile.isFile() || md5(oldFile) != md5(newFile)) {
    copy {
        from newFile
        into oldFile.parent
        rename {
            oldFile.name
        }
    }
}

static md5(File file){
    return MessageDigest.getInstance("MD5").digest(file.bytes).encodeHex().toString().toLowerCase()
}

参考资料

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值