2019 05 10 19 02 [git] hook git commit-msg

根據這個網站所描述的git comment的寫法
https://chris.beams.io/posts/git-commit/
寫了一個git hook, 來檢查commit的message.
基本原理很簡單, 第一個參數就是commit 的 message,
所以只要檢查這個檔案內容就可以了.
成功回傳值給0,失敗給非0值.

因為是用perl寫的,所以要先確定所用的環境有perl.
然後把這個檔案放到 .git/hooks/commit-msg
應該就可以用了.


 

#!perl

sub get_line_without_comment
{
  my $fin = shift;
  while ($_=<$fin>) {
    if ($_ !~/^#/) {
      $_ =~ s/[\r\n]$//g;
      last; 
    }
  }
  return $_;
}

#print "0", $ARGV[0],"\n";

open($fin,$ARGV[0]);
$_=get_line_without_comment($fin);

if (length($_) > 50 || length($_) == 0) {
   print "Rule 2: Limit the subject line to 50 characters\n";
   print "Ref: https://chris.beams.io/posts/git-commit/\n";
   exit(1);
}
if ($_ =~ /\.\s*$/) {
   print "Rule 4: Do not end the subject line with a period\n";
   print "Ref: https://chris.beams.io/posts/git-commit/\n";
   exit(1);
}
if ($_ =~ /^\s*$/) {
   print "The subject line should not be empty\n";
   exit(1);
}
if ($_ !~ /^[A-Z0-9]/) {
   print "Rule 3: Capitalize the subject line\n";
   print "Ref: https://chris.beams.io/posts/git-commit/\n";
   exit(1);    
}
$_=get_line_without_comment($fin);
if (length($_) != 0) {
   print "Rule 1: Separate subject from body with a blank line\n";
   print "Ref: https://chris.beams.io/posts/git-commit/\n";
   exit(1);
}
while ($_=get_line_without_comment($fin))
{
   if (length($_) > 72) {
     print "Rule 6: Wrap the body at 72 characters\n";
     print "Ref: https://chris.beams.io/posts/git-commit/\n";
     exit(1);
  }
}

exit(0);