Skip to main content

钩子git-hook

前置知识

git-hook的目录结构

DIR:hooks                        # {项目}/.git/hooks 目录
|-- update.sample #
|-- prepare-commit-msg.sample #
|-- pre-receive.sample #
|-- pre-rebase.sample #
|-- pre-push.sample #
|-- pre-commit.sample #
|-- pre-applypatch.sample #
|-- post-update.sample #
|-- fsmonitor-watchman.sample #
|-- commit-msg.sample #
`-- applypatch-msg.sample #
  • 以上是默认的一个官方脚本模板
  • 以上脚本当去除.sample后,才可以在对应生命周期时生效

Git禁止大文件提交到仓库中

添加文件:.git/hooks/pre-commit

#!/bin/sh
hard_limit=$(git config hooks.filesizehardlimit)
soft_limit=$(git config hooks.filesizesoftlimit)
: ${hard_limit:=10000000} # 10M
: ${soft_limit:=1000000} # 1M

list_new_or_modified_files()
{
git diff --staged --name-status|sed -e '/^D/ d; /^D/! s/.\s\+//'
}

unmunge()
{
local result="${1#\"}"
result="${result%\"}"
env echo -e "$result"
}

check_file_size()
{
n=0
while read -r munged_filename
do
f="$(unmunge "$munged_filename")"
h=$(git ls-files -s "$f"|cut -d' ' -f 2)
s=$(git cat-file -s "$h")
if [ "$s" -gt $hard_limit ]
then
env echo -E 1>&2 "ERROR: hard size limit ($hard_limit) exceeded: $munged_filename ($s)"
n=$((n+1))
elif [ "$s" -gt $soft_limit ]
then
env echo -E 1>&2 "WARNING: soft size limit ($soft_limit) exceeded: $munged_filename ($s)"
fi
done

[ $n -eq 0 ]
}

list_new_or_modified_files | check_file_size

这里设置了soft_limithard_limit,默认的大小分别是1M和10M,当提交的某个文件超过1M时,会显示警告;当超过10M时,会显示错误,导致commit失败。

通过git config命令来设置soft_limithard_limit的值:

git config hooks.filesizehardlimit 20000000 # 20M
git config hooks.filesizesoftlimit 2000000 # 2M