Skip to content

Instantly share code, notes, and snippets.

@ainame
Last active December 22, 2015 17:08
Show Gist options
  • Save ainame/6503679 to your computer and use it in GitHub Desktop.
Save ainame/6503679 to your computer and use it in GitHub Desktop.
ある歴史(BASE_COMMIT)以降に新規追加されたファイルが150行を超えたときにcommitをしないための、決意のpre-commit hookを書きました。
#!/usr/bin/env perl
use strict;
use warnings;
use Perl::Metrics::Simple;
use constant {
EXIT_STATUS_SUCCESS => 0,
PERL_MODULE_FILENAME_PATTERN => qr/\.(pm|pl)$/,
LIMIT_LINES_OF_CODE => 150,
BASE_COMMIT => '9e732c2',
};
sub is_empty_git_history {
system "git rev-parse --verify HEAD >/dev/null 2>&1";
return $? != EXIT_STATUS_SUCCESS;
}
sub get_modified_files {
my $output = `git diff-index --cached --name-only HEAD`;
chomp($output);
return split /\n/, $output;
}
sub convert_analysis_object {
my $file = shift;
my $analyzer = Perl::Metrics::Simple->new;
my $analysis = $analyzer->analyze_files($file);
return $analysis;
}
sub is_new_added_file_since_base_history {
my $file = shift;
my $base_commit = BASE_COMMIT;
my $output =
`git log --after=$base_commit --diff-filter=A --pretty="%H,%ai" -- $file`;
return $output eq '';
}
sub extract_violation_files {
grep {
$_->lines > LIMIT_LINES_OF_CODE
} map {
convert_analysis_object($_)
} grep {
is_new_added_file_since_base_history($_);
} grep {
$_ =~ PERL_MODULE_FILENAME_PATTERN
} get_modified_files;
}
return exit 1 if is_empty_git_history;
my @violation_files = extract_violation_files;
for my $file (@violation_files) {
warn sprintf(
"%s %s lines: over limit of lines of code. (current limit is %d).\n",
$file->files->[0], $file->lines, LIMIT_LINES_OF_CODE
);
}
exit 1 unless scalar(@violation_files) == 0;
exit 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment