Code

git-notify: Make showing the committer optional
[nagiosplug.git] / tools / git-notify
1 #!/usr/bin/perl -w
2 #
3 # Tool to send git commit notifications
4 #
5 # Copyright 2005 Alexandre Julliard
6 # Copyright 2009 Nagios Plugins Development Team
7 #
8 # This program is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU General Public License as
10 # published by the Free Software Foundation; either version 2 of
11 # the License, or (at your option) any later version.
12 #
13 #
14 # This script is meant to be called from .git/hooks/post-receive.
15 #
16 # Usage: git-notify [options] [--] old-sha1 new-sha1 refname
17 #
18 #   -C        Show committer in the body if different from the author
19 #   -c name   Send CIA notifications under specified project name
20 #   -m addr   Send mail notifications to specified address
21 #   -n max    Set max number of individual mails to send
22 #   -r name   Set the git repository name
23 #   -s bytes  Set the maximum diff size in bytes (-1 for no limit)
24 #   -t file   Prevent duplicate notifications by saving state to this file
25 #   -U mask   Set the umask for creating the state file
26 #   -u url    Set the URL to the gitweb browser
27 #   -i branch If at least one -i is given, report only for specified branches
28 #   -x branch Exclude changes to the specified branch from reports
29 #   -X        Exclude merge commits
30 #
32 use strict;
33 use Fcntl ':flock';
34 use Encode qw(encode decode);
35 use Cwd 'realpath';
37 sub git_config($);
38 sub get_repos_name();
40 # some parameters you may want to change
42 # set this to something that takes "-s"
43 my $mailer = "/usr/bin/mail";
45 # CIA notification address
46 my $cia_address = "cia\@cia.navi.cx";
48 # debug mode
49 my $debug = 0;
51 # configuration parameters
53 # show the committer if different from the author (can be set with the -C option)
54 my $show_committer = git_config( "notify.showcommitter" );
56 # base URL of the gitweb repository browser (can be set with the -u option)
57 my $gitweb_url = git_config( "notify.baseurl" );
59 # default repository name (can be changed with the -r option)
60 my $repos_name = git_config( "notify.repository" ) || get_repos_name();
62 # max size of diffs in bytes (can be changed with the -s option)
63 my $max_diff_size = git_config( "notify.maxdiff" ) || 10000;
65 # address for mail notices (can be set with -m option)
66 my $commitlist_address = git_config( "notify.mail" );
68 # project name for CIA notices (can be set with -c option)
69 my $cia_project_name = git_config( "notify.cia" );
71 # max number of individual notices before falling back to a single global notice (can be set with -n option)
72 my $max_individual_notices = git_config( "notify.maxnotices" ) || 100;
74 # branches to include
75 my @include_list = split /\s+/, git_config( "notify.include" ) || "";
77 # branches to exclude
78 my @exclude_list = split /\s+/, git_config( "notify.exclude" ) || "";
80 # the state file we use (can be set with the -t option)
81 my $state_file = git_config( "notify.statefile" );
83 # umask for creating the state file (can be set with -U option)
84 my $mode_mask = git_config( "notify.umask" ) || 002;
86 # Extra options to git rev-list
87 my @revlist_options;
89 sub usage()
90 {
91     print "Usage: $0 [options] [--] old-sha1 new-sha1 refname\n";
92     print "   -C        Show committer in the body if different from the author\n";
93     print "   -c name   Send CIA notifications under specified project name\n";
94     print "   -m addr   Send mail notifications to specified address\n";
95     print "   -n max    Set max number of individual mails to send\n";
96     print "   -r name   Set the git repository name\n";
97     print "   -s bytes  Set the maximum diff size in bytes (-1 for no limit)\n";
98     print "   -t file   Prevent duplicate notifications by saving state to this file\n";
99     print "   -U mask   Set the umask for creating the state file\n";
100     print "   -u url    Set the URL to the gitweb browser\n";
101     print "   -i branch If at least one -i is given, report only for specified branches\n";
102     print "   -x branch Exclude changes to the specified branch from reports\n";
103     print "   -X        Exclude merge commits\n";
104     exit 1;
107 sub xml_escape($)
109     my $str = shift;
110     $str =~ s/&/&/g;
111     $str =~ s/</&lt;/g;
112     $str =~ s/>/&gt;/g;
113     my @chars = unpack "U*", $str;
114     $str = join "", map { ($_ > 127) ? sprintf "&#%u;", $_ : chr($_); } @chars;
115     return $str;
118 # execute git-rev-list(1) with the given parameters and return the output
119 sub git_rev_list(@)
121     my @args = @_;
122     my $revlist = [];
123     my $pid = open REVLIST, "-|";
125     die "Cannot open pipe: $!" if not defined $pid;
126     if (!$pid)
127     {
128         exec "git", "rev-list", @revlist_options, @args or die "Cannot execute rev-list: $!";
129     }
130     while (<REVLIST>)
131     {
132         chomp;
133         die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
134         push @$revlist, $_;
135     }
136     close REVLIST or die $! ? "Cannot execute rev-list: $!" : "rev-list exited with status: $?";
137     return $revlist;
140 # append the given commit hashes to the state file
141 sub save_commits($)
143     my $commits = shift;
145     open STATE, ">>", $state_file or die "Cannot open $state_file: $!";
146     flock STATE, LOCK_EX or die "Cannot lock $state_file";
147     print STATE "$_\n" for @$commits;
148     flock STATE, LOCK_UN or die "Cannot unlock $state_file";
149     close STATE or die "Cannot close $state_file: $!";
152 # for the given range, return the new hashes (and append them to the state file)
153 sub get_new_commits($$)
155     my ($old_sha1, $new_sha1) = @_;
156     my ($seen, @args);
157     my $newrevs = [];
159     @args = ( "^$old_sha1" ) unless $old_sha1 eq '0' x 40;
160     push @args, $new_sha1, @exclude_list;
162     my $revlist = git_rev_list(@args);
164     if (not defined $state_file or not -e $state_file)
165     {
166         save_commits(git_rev_list("--all", "--full-history")) if defined $state_file;
167         return $revlist;
168     }
170     open STATE, $state_file or die "Cannot open $state_file: $!";
171     flock STATE, LOCK_SH or die "Cannot lock $state_file";
172     while (<STATE>)
173     {
174         chomp;
175         die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
176         $seen->{$_} = 1;
177     }
178     flock STATE, LOCK_UN or die "Cannot unlock $state_file";
179     close STATE or die "Cannot close $state_file: $!";
181     # FIXME: if another git-notify process reads the $state_file at *this*
182     # point, that process might generate duplicates of our notifications.
184     save_commits($revlist);
186     foreach my $commit (@$revlist)
187     {
188         push @$newrevs, $commit unless $seen->{$commit};
189     }
190     return $newrevs;
193 # truncate the given string if it exceeds the specified number of characters
194 sub truncate_str($$)
196     my ($str, $max) = @_;
198     if (length($str) > $max)
199     {
200         $str = substr($str, 0, $max);
201         $str =~ s/\s+\S+$//;
202         $str .= " ...";
203     }
204     return $str;
207 # right-justify the left column of "left: right" elements, omit undefined elements
208 sub format_table(@)
210     my @lines = @_;
211     my @table;
212     my $max = 0;
214     foreach my $line (@lines)
215     {
216        next if not defined $line;
217        my $pos = index($line, ":");
219        $max = $pos if $pos > $max;
220     }
222     foreach my $line (@lines)
223     {
224        next if not defined $line;
225        my ($left, $right) = split(/: */, $line, 2);
227        push @table, (defined $left and defined $right)
228            ? sprintf("%*s: %s", $max + 1, $left, $right)
229            : $line;
230     }
231     return @table;
234 # format an integer date + timezone as string
235 # algorithm taken from git's date.c
236 sub format_date($$)
238     my ($time,$tz) = @_;
240     if ($tz < 0)
241     {
242         my $minutes = (-$tz / 100) * 60 + (-$tz % 100);
243         $time -= $minutes * 60;
244     }
245     else
246     {
247         my $minutes = ($tz / 100) * 60 + ($tz % 100);
248         $time += $minutes * 60;
249     }
250     return gmtime($time) . sprintf " %+05d", $tz;
253 # fetch a parameter from the git config file
254 sub git_config($)
256     my ($param) = @_;
258     open CONFIG, "-|" or exec "git", "config", $param;
259     my $ret = <CONFIG>;
260     chomp $ret if $ret;
261     close CONFIG or $ret = undef;
262     return $ret;
265 # parse command line options
266 sub parse_options()
268     while (@ARGV && $ARGV[0] =~ /^-/)
269     {
270         my $arg = shift @ARGV;
272         if ($arg eq '--') { last; }
273         elsif ($arg eq '-C') { $show_committer = 1; }
274         elsif ($arg eq '-c') { $cia_project_name = shift @ARGV; }
275         elsif ($arg eq '-m') { $commitlist_address = shift @ARGV; }
276         elsif ($arg eq '-n') { $max_individual_notices = shift @ARGV; }
277         elsif ($arg eq '-r') { $repos_name = shift @ARGV; }
278         elsif ($arg eq '-s') { $max_diff_size = shift @ARGV; }
279         elsif ($arg eq '-t') { $state_file = shift @ARGV; }
280         elsif ($arg eq '-U') { $mode_mask = shift @ARGV; }
281         elsif ($arg eq '-u') { $gitweb_url = shift @ARGV; }
282         elsif ($arg eq '-i') { push @include_list, shift @ARGV; }
283         elsif ($arg eq '-x') { push @exclude_list, shift @ARGV; }
284         elsif ($arg eq '-X') { push @revlist_options, "--no-merges"; }
285         elsif ($arg eq '-d') { $debug++; }
286         else { usage(); }
287     }
288     if (@ARGV && $#ARGV != 2) { usage(); }
289     @exclude_list = map { "^$_"; } @exclude_list;
292 # send an email notification
293 sub mail_notification($$$@)
295     my ($name, $subject, $content_type, @text) = @_;
296     $subject = encode("MIME-Q",$subject);
297     if ($debug)
298     {
299         binmode STDOUT, ":utf8";
300         print "---------------------\n";
301         print "To: $name\n";
302         print "Subject: $subject\n";
303         print "Content-Type: $content_type\n";
304         print "\n", join("\n", @text), "\n";
305     }
306     else
307     {
308         my $pid = open MAIL, "|-";
309         return unless defined $pid;
310         if (!$pid)
311         {
312             exec $mailer, "-s", $subject, "-a", "Content-Type: $content_type", $name or die "Cannot exec $mailer";
313         }
314         binmode MAIL, ":utf8";
315         print MAIL join("\n", @text), "\n";
316         close MAIL or warn $! ? "Cannot execute $mailer: $!" : "$mailer exited with status: $?";
317     }
320 # get the default repository name
321 sub get_repos_name()
323     my $dir = `git rev-parse --git-dir`;
324     chomp $dir;
325     my $repos = realpath($dir);
326     $repos =~ s/(.*?)((\.git\/)?\.git)$/$1/;
327     $repos =~ s/(.*)\/([^\/]+)\/?$/$2/;
328     return $repos;
331 # extract the information from a commit or tag object and return a hash containing the various fields
332 sub get_object_info($)
334     my $obj = shift;
335     my %info = ();
336     my @log = ();
337     my $do_log = 0;
339     $info{"encoding"} = "utf-8";
341     open TYPE, "-|" or exec "git", "cat-file", "-t", $obj or die "cannot run git-cat-file";
342     my $type = <TYPE>;
343     chomp $type;
344     close TYPE or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
346     open OBJ, "-|" or exec "git", "cat-file", $type, $obj or die "cannot run git-cat-file";
347     while (<OBJ>)
348     {
349         chomp;
350         if ($do_log)
351         {
352             last if /^-----BEGIN PGP SIGNATURE-----/;
353             push @log, $_;
354         }
355         elsif (/^(author|committer|tagger) ((.*) (<.*>)) (\d+) ([+-]\d+)$/)
356         {
357             $info{$1} = $2;
358             $info{$1 . "_name"} = $3;
359             $info{$1 . "_email"} = $4;
360             $info{$1 . "_date"} = $5;
361             $info{$1 . "_tz"} = $6;
362         }
363         elsif (/^tag (.+)/)
364         {
365             $info{"tag"} = $1;
366         }
367         elsif (/^encoding (.+)/)
368         {
369             $info{"encoding"} = $1;
370         }
371         elsif (/^$/) { $do_log = 1; }
372     }
373     close OBJ or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
375     $info{"type"} = $type;
376     $info{"log"} = \@log;
377     return %info;
380 # send a ref change notice to a mailing list
381 sub send_ref_notice($$@)
383     my ($ref, $action, @notice) = @_;
384     my ($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/);
386     $reftype =~ s/^head$/branch/;
388     @notice = (format_table(
389         "Module: $repos_name",
390         ($reftype eq "tag" ? "Tag:" : "Branch:") . $refname,
391         @notice,
392         ($action ne "removed" and $gitweb_url)
393             ? "URL: $gitweb_url/?a=shortlog;h=$ref" : undef),
394         "",
395         "The $refname $reftype has been $action.");
397     mail_notification($commitlist_address, "$refname $reftype $action",
398         "text/plain; charset=us-ascii", @notice);
401 # send a commit notice to a mailing list
402 sub send_commit_notice($$)
404     my ($ref,$obj) = @_;
405     my %info = get_object_info($obj);
406     my @notice = ();
407     my ($url,$subject);
409     if ($gitweb_url)
410     {
411         open REVPARSE, "-|" or exec "git", "rev-parse", "--short", $obj or die "cannot exec git-rev-parse";
412         my $short_obj = <REVPARSE>;
413         close REVPARSE or die $! ? "Cannot execute rev-parse: $!" : "rev-parse exited with status: $?";
415         $short_obj = $obj if not defined $short_obj;
416         chomp $short_obj;
417         $url = "$gitweb_url/?a=$info{type};h=$short_obj";
418     }
420     if ($info{"type"} eq "tag")
421     {
422         push @notice, format_table(
423           "Module: $repos_name",
424           "Branch: $ref",
425           "Tag: $obj",
426           "Tagger:" . $info{"tagger"},
427           "Date:" . format_date($info{"tagger_date"},$info{"tagger_tz"}),
428           $url ? "URL: $url" : undef),
429           "",
430           join "\n", @{$info{"log"}};
432         $subject = "Tag " . $info{"tag"} . ": " . $info{"tagger_name"};
433     }
434     else
435     {
436         push @notice, format_table(
437           "Module: $repos_name",
438           "Branch: $ref",
439           "Commit: $obj",
440           "Author:" . $info{"author"},
441           $show_committer && $info{"committer"} ne $info{"author"} ? "Committer:" . $info{"committer"} : undef,
442           "Date:" . format_date($info{"author_date"},$info{"author_tz"}),
443           $url ? "URL: $url" : undef),
444           "",
445           @{$info{"log"}},
446           "",
447           "---",
448           "";
450         open STAT, "-|" or exec "git", "diff-tree", "--stat", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
451         push @notice, join("", <STAT>);
452         close STAT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
454         open DIFF, "-|" or exec "git", "diff-tree", "-p", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
455         my $diff = join("", <DIFF>);
456         close DIFF or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
458         if (($max_diff_size == -1) || (length($diff) < $max_diff_size))
459         {
460             push @notice, $diff;
461         }
462         else
463         {
464             push @notice, "Diff:   $gitweb_url/?a=commitdiff;h=$obj" if $gitweb_url;
465         }
466         $subject = $info{"author_name"};
467     }
469     $subject .= ": " . truncate_str(${$info{"log"}}[0],50);
470     $_ = decode($info{"encoding"}, $_) for @notice;
471     mail_notification($commitlist_address, $subject, "text/plain; charset=UTF-8", @notice);
474 # send a commit notice to the CIA server
475 sub send_cia_notice($$)
477     my ($ref,$commit) = @_;
478     my %info = get_object_info($commit);
479     my @cia_text = ();
481     return if $info{"type"} ne "commit";
483     push @cia_text,
484         "<message>",
485         "  <generator>",
486         "    <name>git-notify script for CIA</name>",
487         "  </generator>",
488         "  <source>",
489         "    <project>" . xml_escape($cia_project_name) . "</project>",
490         "    <module>" . xml_escape($repos_name) . "</module>",
491         "    <branch>" . xml_escape($ref). "</branch>",
492         "  </source>",
493         "  <body>",
494         "    <commit>",
495         "      <revision>" . substr($commit,0,10) . "</revision>",
496         "      <author>" . xml_escape($info{"author"}) . "</author>",
497         "      <log>" . xml_escape(join "\n", @{$info{"log"}}) . "</log>",
498         "      <files>";
500     open COMMIT, "-|" or exec "git", "diff-tree", "--name-status", "-r", "-M", $commit or die "cannot run git-diff-tree";
501     while (<COMMIT>)
502     {
503         chomp;
504         if (/^([AMD])\t(.*)$/)
505         {
506             my ($action, $file) = ($1, $2);
507             my %actions = ( "A" => "add", "M" => "modify", "D" => "remove" );
508             next unless defined $actions{$action};
509             push @cia_text, "        <file action=\"$actions{$action}\">" . xml_escape($file) . "</file>";
510         }
511         elsif (/^R\d+\t(.*)\t(.*)$/)
512         {
513             my ($old, $new) = ($1, $2);
514             push @cia_text, "        <file action=\"rename\" to=\"" . xml_escape($new) . "\">" . xml_escape($old) . "</file>";
515         }
516     }
517     close COMMIT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
519     push @cia_text,
520         "      </files>",
521         $gitweb_url ? "      <url>" . xml_escape("$gitweb_url/?a=commit;h=$commit") . "</url>" : "",
522         "    </commit>",
523         "  </body>",
524         "  <timestamp>" . $info{"author_date"} . "</timestamp>",
525         "</message>";
527     mail_notification($cia_address, "DeliverXML", "text/xml", @cia_text);
530 # send a global commit notice when there are too many commits for individual mails
531 sub send_global_notice($$$)
533     my ($ref, $old_sha1, $new_sha1) = @_;
534     my $notice = git_rev_list("--pretty", "^$old_sha1", "$new_sha1", @exclude_list);
536     foreach my $rev (@$notice)
537     {
538         $rev =~ s/^commit /URL:    $gitweb_url\/?a=commit;h=/ if $gitweb_url;
539     }
541     mail_notification($commitlist_address, "New commits on branch $ref", "text/plain; charset=UTF-8", @$notice);
544 # send all the notices
545 sub send_all_notices($$$)
547     my ($old_sha1, $new_sha1, $ref) = @_;
548     my ($reftype, $refname, $action, @notice);
550     return if ($ref =~ /^refs\/remotes\//
551         or (@include_list && !grep {$_ eq $ref} @include_list));
552     die "The name \"$ref\" doesn't sound like a local branch or tag"
553         if not (($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/));
555     if ($new_sha1 eq '0' x 40)
556     {
557         $action = "removed";
558         @notice = ( "Old SHA1: $old_sha1" );
559     }
560     elsif ($old_sha1 eq '0' x 40)
561     {
562         $action = "created";
563         @notice = ( "SHA1: $new_sha1" );
564     }
565     elsif ($reftype eq "tag")
566     {
567         $action = "updated";
568         @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
569     }
570     elsif (not grep( $_ eq $old_sha1, @{ git_rev_list( $new_sha1, "--full-history" ) } ))
571     {
572         $action = "rewritten";
573         @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
574     }
576     send_ref_notice( $ref, $action, @notice ) if ($commitlist_address and $action);
578     unless ($reftype eq "tag" or $new_sha1 eq '0' x 40)
579     {
580         my $commits = get_new_commits ( $old_sha1, $new_sha1 );
582         if (@$commits > $max_individual_notices)
583         {
584             send_global_notice( $refname, $old_sha1, $new_sha1 ) if $commitlist_address;
585         }
586         elsif (@$commits > 0)
587         {
588             foreach my $commit (@$commits)
589             {
590                 send_commit_notice( $refname, $commit ) if $commitlist_address;
591                 send_cia_notice( $refname, $commit ) if $cia_project_name;
592             }
593         }
594         elsif ($commitlist_address)
595         {
596             @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
597             send_ref_notice( $ref, "modified", @notice );
598         }
599     }
602 parse_options();
604 umask( $mode_mask );
606 # append repository path to URL
607 $gitweb_url .= "/$repos_name.git" if $gitweb_url;
609 if (@ARGV)
611     send_all_notices( $ARGV[0], $ARGV[1], $ARGV[2] );
613 else  # read them from stdin
615     while (<>)
616     {
617         chomp;
618         if (/^([0-9a-f]{40}) ([0-9a-f]{40}) (.*)$/) { send_all_notices( $1, $2, $3 ); }
619     }
622 exit 0;