有没有人知道一个好的git hook,可以在提交时检查二进制文件并报错?我想防止二进制文件被提交到我的代码库中,但有时候人们会犯错误。
谢谢!
有没有人知道一个好的git hook,可以在提交时检查二进制文件并报错?我想防止二进制文件被提交到我的代码库中,但有时候人们会犯错误。
谢谢!
.git/hooks/pre-commit.sample
。EMPTY_TREE
的来源):#! /bin/sh
stop_binaries=$(git config --get hooks.stop_binaries)
exec 1>&2
if [ "$stop_binaries" = true ]; then
EMPTY_TREE=$(git hash-object -t tree /dev/null)
# or: EMPTY_TREE=4b825dc642cb6eb9a060e54bf8d69288fbee4904
if git diff --cached --numstat $EMPTY_TREE | grep -e '^-' >/dev/null; then
echo Error: commit would add binary files:
git diff --cached --numstat $EMPTY_TREE | grep -e '^-' | cut -f3-
exit 1
fi
fi
git diff --cached
来查看将被提交的内容,并将其与初始空树进行比较。请注意,它会拒绝具有已存在(但未更改)二进制文件的提交;要使其仅拒绝新或更改的二进制文件,请从非ASCII名称钩子中添加against=
逻辑。如果要仅拒绝新二进制文件,则还需添加--diff-filter=A
参数。
如果需要,可以使用其他错误消息文本来提高可读性。您还可以反转测试(而不是必须断言“停止二进制文件”),使其默认停止,您必须设置“allowbinaries”以添加二进制文件等。当然,您还可以通过对diff-index输出进行其他过滤来允许特定目录中的二进制文件等。
不好意思,这里要做一个自我推销,但是我写了一个pre-receive hook,可以更加智能和可配置地实现这个功能。在查找了很多没有完全符合需求的现成Git管理系统之后,我终于成功地为stock Git提供了这个功能,而且不需要安装一些较大的Git管理系统。
README
重命名为 README.md
将非常有用! - Steve Lorimer#!/usr/bin/perl
# The hook should exit with non-zero status after issuing an appropriate
# message if it wants to stop the commit.
use strict;
use warnings;
my $file;
my $MAX_SIZE = 100000; # Limit files to 100KB
# Only check binary and file size when files are added otherwise users
# get an error every time they modify they file. This has the dissadvantage
# of not catching if a file grows too large after the initial commit
#
# Get list of added files only (i.e. new files)
my @new_file_list = `git diff --cached --name-only --diff-filter=A`;
foreach $file (@new_file_list)
{
chomp($file);
# Check if file is binary
if (-B $file)
{
print STDERR "WARNING: $file is binary.\n";
print STDERR "Please check with repo owner before committing binary files.\n";
print STDERR "To bypass this warning re-run your commit with the '--no-verify' option\n";
exit 1;
}
# Check if file is very large
if (-s $file > $MAX_SIZE)
{
print STDERR "WARNING: $file is greater than $MAX_SIZE bytes.\n";
print STDERR "Please check with repo owner before committing very large files.\n";
print STDERR "To bypass this warning re-run your commit with the '--no-verify' option\n";
exit 1;
}
}