Git hook不会阻止二进制文件

时间:2017-06-20 09:55:49

标签: git perl

我在服务器端完成了预接收 git挂钩。它不允许推送大文件,也不允许推送二进制文件。

这是代码的一部分,有问题。

my @new_file_list =  `git diff --name-only $old..$new`;;
foreach $file (@new_file_list)
{
  $size = `git cat-file -s $new:$file`;
  print "!!! file $file";
  print "!!! size $size";
  chomp($file);

  # Check if file is binary
  if (-B $file)
  {
    print STDERR "ERROR: $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 too large
  if ($size > $limit)
  {
    my $hsize = hsize($size);
    my $hlimit = hsize($limit);
    print STDERR "ERROR: $file is greater than $hlimit bytes. Size of file is $hsize\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;
  }
}

检查大小限制是否正常,但它根本不会阻止二进制文件。你能告诉我,我的代码有什么问题吗?感谢。

这是一个输出

remote: !!! file Chrysanthemum.jpg
remote: !!! size 879394
remote: !!! file Koala.jpg
remote: !!! size 780831

2 个答案:

答案 0 :(得分:1)

有关挂钩的示例,请参阅Is there a git hook which can prevent binary check-ins以防止检入二进制文件。

您正在检查新提交中的文件大小:

$size = `git cat-file -s $new:$file`;

然后使用本地文件系统进行二进制检查:

if (-B $file)

你可能希望这是git cat-file $new:$file的结果,而是使用(How can I read the output from external commands in real time in Perl?)类似的东西:

open my $fh, '-|', 'git', 'cat-file', "$new:$file";

if (-B $fh)
{
    exit 1;
}

答案 1 :(得分:0)

不是答案,而是重要评论。

`git diff --name-only $old..$new`

`git cat-file -s $new:$file`

遭受贝壳注射虫。例如,考虑如果将具有空格的文件添加到存储库中会发生什么。

修正:

use String::ShellQuote qw( shell_quote );

my $cmd = shell_quote('git', 'diff', '--name-only', "$old..$new");
`$cmd`

my $cmd = shell_quote('git', 'cat-file', '-s', "$new:$file");
`$cmd`