git内置了九个hook,详细请man hooks
其中prepare-commit-msg这个hook是在git commit准备好默认的log信息之后, 在启用editor之前调用的,使用这个信息我们可以对commit信息可以进行编辑,通常的需求是commit的信息需要合乎一定的规范,但是这个规范的动作每次都要自己填写会很麻烦,这就情况下就可以使用这个hook对消息进行编辑。这里假定有这么一个需求,我们将upstream的patch拿到自己维护的版本时需要将upstream的信息附上。通常我们的做法是从upstream拿来patch
alloc@bash-4.3> git format-patch -1 597f22d6aa46105d69648a5c042d1fabe182c6f6
然后将patch打到自己的版本
bash-4.3> git am ~/patch-me/0001-ixgbe-add-support-for-interrupts-from-X550-external-.patch
然后再修改添加必要的规范信息
bash-4.3> git commit --amend -s
如果patch基本没啥问题的话,每次这样操作一遍也很费时,因此我们要使用hook来自动完成这个任务。下面是prepare-commit-msg的代码片段,主要是完成插入规范信息的动作。
case "$2,$3" in
merge,)
/usr/bin/env perl -i.bak -ne 's/^/# /, s/^# #/#/ if /^Conflicts/ .. /#/; print' "$1" ;;
# ,|template,)
# /usr/bin/env perl -i.bak -pe '
# print "\n" . `git diff --cached --name-status -r`
# if /^#/ && $first++ == 0' "$1" ;;
commit,*)
name=$(cat ~/patch-me/name)
file=~/patch-me/$name
commit=$(head -1 $file | cut -d ' ' -f2)
sed -i "1a\\\ncommit $commit upstream" $1;;
*) ;;
esac
下面这个脚本是apply patch,然后commit,注意git commit的时候加了个–no-edit的参数,这样就不会再启动editor session了。
#! /bin/bash
filename=$(cat ~/patch-me/name)
file=~/patch-me/$filename
echo $file
[ ! -e $file ] && echo "file no exit" && exit 2
git am $file
if [ $? != 0 ]
then
echo "failed to apply patch, please apply it manually"
exit 1
fi
git commit --amend -s --no-edit
版权声明:本文为alloc_young原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。