git push 前自动检查版本号

在做平时开发的时候,经常会遇到需要在 git push 的时候顺便更新版本号的情况,当版本号没有修改就 git push 的提醒用户修改,并 git amend 生效。一般这种情况会在版本号满足和 push 相关的时候发生,比如说版本号是 major.minor.patch-commit 的形式,这样的话,可以通过自定义的 push-hook 来实现功能。

比如说在本地根目录下创建一个 hook 文件 hooks/pre-push

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#! /bin/sh

set -o nounset
set -o errexit

# The version file to be update.
VERSION_FILE=package.json
# The version pattern in the version file.
VERSION_FILTER='"version": '


CODE_BASE=$(git rev-parse --show-toplevel)
BRANCH=$(git branch | cut -d ' ' -f 2)
BRANCH_TO_UPDATE_VERSION=master
# If there is multiple remotes to be set in the repository, considering hard coded the next line to origin/master or similar.
# Actually we need to filter the branch mapping by `git remote -v` if the branch is not mapped by name.
REMOTE=$(git remote)/$BRANCH

if [ "$BRANCH" = "$BRANCH_TO_UPDATE_VERSION" ]; then
CHANGES=$(git diff "$BRANCH".."$REMOTE" | wc -l)

if [ "$CHANGES" -gt "0" ]; then
VERSION_CHANGED=$(git diff "$BRANCH".."$REMOTE" \
-G ${VERSION_FILTER} -- ${CODE_BASE}/${VERSION_FILE} | wc -l)

if [ "$VERSION_CHANGED" -gt "0" ]; then
# In this case, the vesion was already updated.
exit 0
else
# if you wan to directly print error output, using this line.
printf "\033[0;31mERROR: the version in file ${VERSION_FILE} was not updated.\033[0m\n"
exit 1
fi
fi
fi

并将这个 hook 直接软链接到当前项目的 hooks 目录中

1
ln -fs $PWD/hooks/pre-push $PWD/.git/hooks/