使用githook个性化处理提交注释实现与原理

一、一些shell命令基础

1、$1

Test.sh如下:

#!/bin/sh
echo "shell脚本本身的名字: $0"
echo "传给shell的第一个参数: $1"
echo "传给shell的第二个参数: $2"

执行

bash Test.sh 1 2

结果

$1代表第一个参数

2、cat

cat(英文全拼:concatenate)命令用于连接文件并打印到标准输出设备上。

二、githook

项目根目录下,有.git/hooks目录。

里面是是各种hook的模板,

默认不执行,去掉.sample才执行。

以commit-msg为例:

#!/bin/sh
#
# An example hook script to check the commit log message.
# Called by "git commit" with one argument, the name of the file
# that has the commit message.  The hook should exit with non-zero
# status after issuing an appropriate message if it wants to stop the
# commit.  The hook is allowed to edit the commit message file.
#
# To enable this hook, rename this file to "commit-msg".

# Uncomment the below to add a Signed-off-by line to the message.
# Doing this in a hook is a bad idea in general, but the prepare-commit-msg
# hook is more suited to it.
#
# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
# grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1"

# This example catches duplicate Signed-off-by lines.

test "" = "$(grep '^Signed-off-by: ' "$1" |
	 sort | uniq -c | sed -e '/^[ 	]*1[ 	]/d')" || {
	echo >&2 Duplicate Signed-off-by lines.
	exit 1
}

其实,不仅仅可以运行#!/bin/sh

还可以运行,python与nodejs脚本,这样,就可以用熟悉的语言了,当然默认shell是改动最小的。

三、husky

一个npm包,安装后它会自动改造上述hook脚本,并提供我们方便使用的hook配置接口。

简单使用是基于,package.json

{
  "scripts": {
-   "precommit": "npm test",
-   "commitmsg": "commitlint -E GIT_PARAMS"
  },
+ "husky": {
+   "hooks": {
+     "pre-commit": "npm test",
+     "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
+   }
+ }
}

其实,从1.0开始,还可以使用单独配置文件的方式,是

.huskyrc.huskyrc.json.huskyrc.yaml.huskyrc.yml.huskyrc.js or husky.config.js file.

其中,下面俩种都是取git参数方案,区别是,一个是从husky取,一个是从git取。

commitlint -E HUSKY_GIT_PARAMS

commitlint -E GIT_PARAMS

四、主角来了,怎么写这个代码,实现个性化处理提交注释

方案有四:

1、直接改commit-msg文件

在上面加

echo "自定义前缀"$(cat $1) >"$1"

2、基于husky改

{
  "scripts": {
-   "precommit": "npm test",
-   "commitmsg": "commitlint -E GIT_PARAMS"
  },
+ "husky": {
+   "hooks": {
+     "pre-commit": "npm test",
+     "commit-msg": "echo 自定义前缀$(cat $HUSKY_GIT_PARAMS) >$HUSKY_GIT_PARAMS && commitlint -E HUSKY_GIT_PARAMS"
+   }
+ }
}

3、提取githook模板

使用git config  模板dir配置,整体覆盖

4、提取githook模板

编写自己使用模板的初始化hook的脚本

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值