Skip to content

Instantly share code, notes, and snippets.

@ainame
Last active December 22, 2015 15:49
Show Gist options
  • Save ainame/6495074 to your computer and use it in GitHub Desktop.
Save ainame/6495074 to your computer and use it in GitHub Desktop.
git pre-commit hook。このままだと150行超えてる既存ファイルがコミットできなくなるので、どっかの歴史以降に新規追加されたファイルかどうかをチェックする処理をあとで追加。 
#!/usr/bin/env perl
use strict;
use warnings;
use Perl::Metrics::Simple;
use constant {
EXIT_STATUS_SUCCESS => 0,
PERL_MODULE_FILENAME_PATTERN => qr/\.pm$/,
LIMIT_LINES_OF_CODE => 150,
};
# .git/hooks/pre-commit.sample に書いてあるおなじみの処理
system "git rev-parse --verify HEAD >/dev/null 2>&1";
my $against = $? == EXIT_STATUS_SUCCESS ? 'HEAD' : exit 1;
my $output = `git diff-index --cached --name-only $against`;
my @files = split /\n/, $output;
my $is_over_limit;
for my $file (@files) {
next unless ($file =~ PERL_MODULE_FILENAME_PATTERN);
my $analyzer = Perl::Metrics::Simple->new;
my $analysis = $analyzer->analyze_files($file);
if ($analysis->lines > LIMIT_LINES_OF_CODE) {
warn sprintf(
"%s: over limit(150) of lines of code(%s).\n",
$file, $analysis->lines,
);
$is_over_limit = 1;
}
}
exit 1 if $is_over_limit;
exit 0;
@yoshikazusawa
Copy link

L14は、exitの条件判定のために三項演算子を使うのは適切ではないので、以下のようにすると良いかと思います。

exit 1 unless $? == EXIT_STATUS_SUCCESS;
my $output = `git diff-index --cached --name-only HEAD`;

あと $is_over_limitですが、pre-commitの文脈だと$found_excess_limit_fileとかが自明でしょうか。

@yoshikazusawa
Copy link

単に新規ファイルかどうかでふりわけるなら git diff-index --name-status HEADでstatusを確認することができるかも。

@ainame
Copy link
Author

ainame commented Sep 9, 2013

とりあえず map grep版作成 https://gist.github.com/ainame/6502426

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment