Code

git-notify: Optionally omit the author name
[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 #   -A        Omit the author name from the mail subject
19 #   -C        Show committer in the body if different from the author
20 #   -c name   Send CIA notifications under specified project name
21 #   -m addr   Send mail notifications to specified address
22 #   -n max    Set max number of individual mails to send
23 #   -r name   Set the git repository name
24 #   -s bytes  Set the maximum diff size in bytes (-1 for no limit)
25 #   -t file   Prevent duplicate notifications by saving state to this file
26 #   -U mask   Set the umask for creating the state file
27 #   -u url    Set the URL to the gitweb browser
28 #   -i branch If at least one -i is given, report only for specified branches
29 #   -x branch Exclude changes to the specified branch from reports
30 #   -X        Exclude merge commits
31 #   -z        Try to abbreviate the SHA1 name within gitweb URLs (unsafe)
32 #
34 use strict;
35 use Fcntl ':flock';
36 use Encode qw(encode decode);
37 use Cwd 'realpath';
39 sub git_config($);
40 sub get_repos_name();
42 # some parameters you may want to change
44 # set this to something that takes "-s"
45 my $mailer = "/usr/bin/mail";
47 # CIA notification address
48 my $cia_address = "cia\@cia.navi.cx";
50 # debug mode
51 my $debug = 0;
53 # configuration parameters
55 # omit the author from the mail subject (can be set with the -A option)
56 my $omit_author = git_config( "notify.omitauthor" );
58 # show the committer if different from the author (can be set with the -C option)
59 my $show_committer = git_config( "notify.showcommitter" );
61 # base URL of the gitweb repository browser (can be set with the -u option)
62 my $gitweb_url = git_config( "notify.baseurl" );
64 # abbreviate the SHA1 name within gitweb URLs (can be set with the -z option)
65 my $abbreviate_url = git_config( "notify.shorturls" );
67 # default repository name (can be changed with the -r option)
68 my $repos_name = git_config( "notify.repository" ) || get_repos_name();
70 # max size of diffs in bytes (can be changed with the -s option)
71 my $max_diff_size = git_config( "notify.maxdiff" ) || 10000;
73 # address for mail notices (can be set with -m option)
74 my $commitlist_address = git_config( "notify.mail" );
76 # project name for CIA notices (can be set with -c option)
77 my $cia_project_name = git_config( "notify.cia" );
79 # max number of individual notices before falling back to a single global notice (can be set with -n option)
80 my $max_individual_notices = git_config( "notify.maxnotices" ) || 100;
82 # branches to include
83 my @include_list = split /\s+/, git_config( "notify.include" ) || "";
85 # branches to exclude
86 my @exclude_list = split /\s+/, git_config( "notify.exclude" ) || "";
88 # the state file we use (can be set with the -t option)
89 my $state_file = git_config( "notify.statefile" );
91 # umask for creating the state file (can be set with -U option)
92 my $mode_mask = git_config( "notify.umask" ) || 002;
94 # Extra options to git rev-list
95 my @revlist_options;
97 sub usage()
98 {
99     print "Usage: $0 [options] [--] old-sha1 new-sha1 refname\n";
100     print "   -A        Omit the author name from the mail subject\n";
101     print "   -C        Show committer in the body if different from the author\n";
102     print "   -c name   Send CIA notifications under specified project name\n";
103     print "   -m addr   Send mail notifications to specified address\n";
104     print "   -n max    Set max number of individual mails to send\n";
105     print "   -r name   Set the git repository name\n";
106     print "   -s bytes  Set the maximum diff size in bytes (-1 for no limit)\n";
107     print "   -t file   Prevent duplicate notifications by saving state to this file\n";
108     print "   -U mask   Set the umask for creating the state file\n";
109     print "   -u url    Set the URL to the gitweb browser\n";
110     print "   -i branch If at least one -i is given, report only for specified branches\n";
111     print "   -x branch Exclude changes to the specified branch from reports\n";
112     print "   -X        Exclude merge commits\n";
113     print "   -z        Try to abbreviate the SHA1 name within gitweb URLs (unsafe)\n";
114     exit 1;
117 sub xml_escape($)
119     my $str = shift;
120     $str =~ s/&/&/g;
121     $str =~ s/</&lt;/g;
122     $str =~ s/>/&gt;/g;
123     my @chars = unpack "U*", $str;
124     $str = join "", map { ($_ > 127) ? sprintf "&#%u;", $_ : chr($_); } @chars;
125     return $str;
128 # execute git-rev-list(1) with the given parameters and return the output
129 sub git_rev_list(@)
131     my @args = @_;
132     my $revlist = [];
133     my $pid = open REVLIST, "-|";
135     die "Cannot open pipe: $!" if not defined $pid;
136     if (!$pid)
137     {
138         exec "git", "rev-list", @revlist_options, @args or die "Cannot execute rev-list: $!";
139     }
140     while (<REVLIST>)
141     {
142         chomp;
143         die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
144         push @$revlist, $_;
145     }
146     close REVLIST or die $! ? "Cannot execute rev-list: $!" : "rev-list exited with status: $?";
147     return $revlist;
150 # append the given commit hashes to the state file
151 sub save_commits($)
153     my $commits = shift;
155     open STATE, ">>", $state_file or die "Cannot open $state_file: $!";
156     flock STATE, LOCK_EX or die "Cannot lock $state_file";
157     print STATE "$_\n" for @$commits;
158     flock STATE, LOCK_UN or die "Cannot unlock $state_file";
159     close STATE or die "Cannot close $state_file: $!";
162 # for the given range, return the new hashes (and append them to the state file)
163 sub get_new_commits($$)
165     my ($old_sha1, $new_sha1) = @_;
166     my ($seen, @args);
167     my $newrevs = [];
169     @args = ( "^$old_sha1" ) unless $old_sha1 eq '0' x 40;
170     push @args, $new_sha1, @exclude_list;
172     my $revlist = git_rev_list(@args);
174     if (not defined $state_file or not -e $state_file)
175     {
176         save_commits(git_rev_list("--all", "--full-history")) if defined $state_file;
177         return $revlist;
178     }
180     open STATE, $state_file or die "Cannot open $state_file: $!";
181     flock STATE, LOCK_SH or die "Cannot lock $state_file";
182     while (<STATE>)
183     {
184         chomp;
185         die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
186         $seen->{$_} = 1;
187     }
188     flock STATE, LOCK_UN or die "Cannot unlock $state_file";
189     close STATE or die "Cannot close $state_file: $!";
191     # FIXME: if another git-notify process reads the $state_file at *this*
192     # point, that process might generate duplicates of our notifications.
194     save_commits($revlist);
196     foreach my $commit (@$revlist)
197     {
198         push @$newrevs, $commit unless $seen->{$commit};
199     }
200     return $newrevs;
203 # truncate the given string if it exceeds the specified number of characters
204 sub truncate_str($$)
206     my ($str, $max) = @_;
208     if (length($str) > $max)
209     {
210         $str = substr($str, 0, $max);
211         $str =~ s/\s+\S+$//;
212         $str .= " ...";
213     }
214     return $str;
217 # right-justify the left column of "left: right" elements, omit undefined elements
218 sub format_table(@)
220     my @lines = @_;
221     my @table;
222     my $max = 0;
224     foreach my $line (@lines)
225     {
226        next if not defined $line;
227        my $pos = index($line, ":");
229        $max = $pos if $pos > $max;
230     }
232     foreach my $line (@lines)
233     {
234        next if not defined $line;
235        my ($left, $right) = split(/: */, $line, 2);
237        push @table, (defined $left and defined $right)
238            ? sprintf("%*s: %s", $max + 1, $left, $right)
239            : $line;
240     }
241     return @table;
244 # format an integer date + timezone as string
245 # algorithm taken from git's date.c
246 sub format_date($$)
248     my ($time,$tz) = @_;
250     if ($tz < 0)
251     {
252         my $minutes = (-$tz / 100) * 60 + (-$tz % 100);
253         $time -= $minutes * 60;
254     }
255     else
256     {
257         my $minutes = ($tz / 100) * 60 + ($tz % 100);
258         $time += $minutes * 60;
259     }
260     return gmtime($time) . sprintf " %+05d", $tz;
263 # fetch a parameter from the git config file
264 sub git_config($)
266     my ($param) = @_;
268     open CONFIG, "-|" or exec "git", "config", $param;
269     my $ret = <CONFIG>;
270     chomp $ret if $ret;
271     close CONFIG or $ret = undef;
272     return $ret;
275 # parse command line options
276 sub parse_options()
278     while (@ARGV && $ARGV[0] =~ /^-/)
279     {
280         my $arg = shift @ARGV;
282         if ($arg eq '--') { last; }
283         elsif ($arg eq '-A') { $omit_author = 1; }
284         elsif ($arg eq '-C') { $show_committer = 1; }
285         elsif ($arg eq '-c') { $cia_project_name = shift @ARGV; }
286         elsif ($arg eq '-m') { $commitlist_address = shift @ARGV; }
287         elsif ($arg eq '-n') { $max_individual_notices = shift @ARGV; }
288         elsif ($arg eq '-r') { $repos_name = shift @ARGV; }
289         elsif ($arg eq '-s') { $max_diff_size = shift @ARGV; }
290         elsif ($arg eq '-t') { $state_file = shift @ARGV; }
291         elsif ($arg eq '-U') { $mode_mask = shift @ARGV; }
292         elsif ($arg eq '-u') { $gitweb_url = shift @ARGV; }
293         elsif ($arg eq '-i') { push @include_list, shift @ARGV; }
294         elsif ($arg eq '-x') { push @exclude_list, shift @ARGV; }
295         elsif ($arg eq '-X') { push @revlist_options, "--no-merges"; }
296         elsif ($arg eq '-z') { $abbreviate_url = 1; }
297         elsif ($arg eq '-d') { $debug++; }
298         else { usage(); }
299     }
300     if (@ARGV && $#ARGV != 2) { usage(); }
301     @exclude_list = map { "^$_"; } @exclude_list;
304 # send an email notification
305 sub mail_notification($$$@)
307     my ($name, $subject, $content_type, @text) = @_;
308     $subject = encode("MIME-Q",$subject);
309     if ($debug)
310     {
311         binmode STDOUT, ":utf8";
312         print "---------------------\n";
313         print "To: $name\n";
314         print "Subject: $subject\n";
315         print "Content-Type: $content_type\n";
316         print "\n", join("\n", @text), "\n";
317     }
318     else
319     {
320         my $pid = open MAIL, "|-";
321         return unless defined $pid;
322         if (!$pid)
323         {
324             exec $mailer, "-s", $subject, "-a", "Content-Type: $content_type", $name or die "Cannot exec $mailer";
325         }
326         binmode MAIL, ":utf8";
327         print MAIL join("\n", @text), "\n";
328         close MAIL or warn $! ? "Cannot execute $mailer: $!" : "$mailer exited with status: $?";
329     }
332 # get the default repository name
333 sub get_repos_name()
335     my $dir = `git rev-parse --git-dir`;
336     chomp $dir;
337     my $repos = realpath($dir);
338     $repos =~ s/(.*?)((\.git\/)?\.git)$/$1/;
339     $repos =~ s/(.*)\/([^\/]+)\/?$/$2/;
340     return $repos;
343 # extract the information from a commit or tag object and return a hash containing the various fields
344 sub get_object_info($)
346     my $obj = shift;
347     my %info = ();
348     my @log = ();
349     my $do_log = 0;
351     $info{"encoding"} = "utf-8";
353     open TYPE, "-|" or exec "git", "cat-file", "-t", $obj or die "cannot run git-cat-file";
354     my $type = <TYPE>;
355     chomp $type;
356     close TYPE or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
358     open OBJ, "-|" or exec "git", "cat-file", $type, $obj or die "cannot run git-cat-file";
359     while (<OBJ>)
360     {
361         chomp;
362         if ($do_log)
363         {
364             last if /^-----BEGIN PGP SIGNATURE-----/;
365             push @log, $_;
366         }
367         elsif (/^(author|committer|tagger) ((.*) (<.*>)) (\d+) ([+-]\d+)$/)
368         {
369             $info{$1} = $2;
370             $info{$1 . "_name"} = $3;
371             $info{$1 . "_email"} = $4;
372             $info{$1 . "_date"} = $5;
373             $info{$1 . "_tz"} = $6;
374         }
375         elsif (/^tag (.+)/)
376         {
377             $info{"tag"} = $1;
378         }
379         elsif (/^encoding (.+)/)
380         {
381             $info{"encoding"} = $1;
382         }
383         elsif (/^$/) { $do_log = 1; }
384     }
385     close OBJ or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
387     $info{"type"} = $type;
388     $info{"log"} = \@log;
389     return %info;
392 # send a ref change notice to a mailing list
393 sub send_ref_notice($$@)
395     my ($ref, $action, @notice) = @_;
396     my ($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/);
398     $reftype =~ s/^head$/branch/;
400     @notice = (format_table(
401         "Module: $repos_name",
402         ($reftype eq "tag" ? "Tag:" : "Branch:") . $refname,
403         @notice,
404         ($action ne "removed" and $gitweb_url)
405             ? "URL: $gitweb_url/?a=shortlog;h=$ref" : undef),
406         "",
407         "The $refname $reftype has been $action.");
409     mail_notification($commitlist_address, "$refname $reftype $action",
410         "text/plain; charset=us-ascii", @notice);
413 # send a commit notice to a mailing list
414 sub send_commit_notice($$)
416     my ($ref,$obj) = @_;
417     my %info = get_object_info($obj);
418     my @notice = ();
419     my ($url,$subject,$obj_string);
421     if ($gitweb_url)
422     {
423         if ($abbreviate_url)
424         {
425             open REVPARSE, "-|" or exec "git", "rev-parse", "--short", $obj or die "cannot exec git-rev-parse";
426             $obj_string = <REVPARSE>;
427             chomp $obj_string if defined $obj_string;
428             close REVPARSE or die $! ? "Cannot execute rev-parse: $!" : "rev-parse exited with status: $?";
429         }
430         $obj_string = $obj if not defined $obj_string;
431         $url = "$gitweb_url/?a=$info{type};h=$obj_string";
432     }
434     if ($info{"type"} eq "tag")
435     {
436         push @notice, format_table(
437           "Module: $repos_name",
438           "Branch: $ref",
439           "Tag: $obj",
440           "Tagger:" . $info{"tagger"},
441           "Date:" . format_date($info{"tagger_date"},$info{"tagger_tz"}),
442           $url ? "URL: $url" : undef),
443           "",
444           join "\n", @{$info{"log"}};
446         $subject = "Tag " . $info{"tag"} . ": ";
447         $subject .= $info{"tagger_name"} . ": " unless $omit_author;
448     }
449     else
450     {
451         push @notice, format_table(
452           "Module: $repos_name",
453           "Branch: $ref",
454           "Commit: $obj",
455           "Author:" . $info{"author"},
456           $show_committer && $info{"committer"} ne $info{"author"} ? "Committer:" . $info{"committer"} : undef,
457           "Date:" . format_date($info{"author_date"},$info{"author_tz"}),
458           $url ? "URL: $url" : undef),
459           "",
460           @{$info{"log"}},
461           "",
462           "---",
463           "";
465         open STAT, "-|" or exec "git", "diff-tree", "--stat", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
466         push @notice, join("", <STAT>);
467         close STAT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
469         open DIFF, "-|" or exec "git", "diff-tree", "-p", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
470         my $diff = join("", <DIFF>);
471         close DIFF or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
473         if (($max_diff_size == -1) || (length($diff) < $max_diff_size))
474         {
475             push @notice, $diff;
476         }
477         else
478         {
479             push @notice, "Diff: $gitweb_url/?a=commitdiff;h=$obj_string" if $gitweb_url;
480         }
481         $subject = $info{"author_name"} . ": " unless $omit_author;
482     }
484     $subject .= truncate_str(${$info{"log"}}[0],50);
485     $_ = decode($info{"encoding"}, $_) for @notice;
486     mail_notification($commitlist_address, $subject, "text/plain; charset=UTF-8", @notice);
489 # send a commit notice to the CIA server
490 sub send_cia_notice($$)
492     my ($ref,$commit) = @_;
493     my %info = get_object_info($commit);
494     my @cia_text = ();
496     return if $info{"type"} ne "commit";
498     push @cia_text,
499         "<message>",
500         "  <generator>",
501         "    <name>git-notify script for CIA</name>",
502         "  </generator>",
503         "  <source>",
504         "    <project>" . xml_escape($cia_project_name) . "</project>",
505         "    <module>" . xml_escape($repos_name) . "</module>",
506         "    <branch>" . xml_escape($ref). "</branch>",
507         "  </source>",
508         "  <body>",
509         "    <commit>",
510         "      <revision>" . substr($commit,0,10) . "</revision>",
511         "      <author>" . xml_escape($info{"author"}) . "</author>",
512         "      <log>" . xml_escape(join "\n", @{$info{"log"}}) . "</log>",
513         "      <files>";
515     open COMMIT, "-|" or exec "git", "diff-tree", "--name-status", "-r", "-M", $commit or die "cannot run git-diff-tree";
516     while (<COMMIT>)
517     {
518         chomp;
519         if (/^([AMD])\t(.*)$/)
520         {
521             my ($action, $file) = ($1, $2);
522             my %actions = ( "A" => "add", "M" => "modify", "D" => "remove" );
523             next unless defined $actions{$action};
524             push @cia_text, "        <file action=\"$actions{$action}\">" . xml_escape($file) . "</file>";
525         }
526         elsif (/^R\d+\t(.*)\t(.*)$/)
527         {
528             my ($old, $new) = ($1, $2);
529             push @cia_text, "        <file action=\"rename\" to=\"" . xml_escape($new) . "\">" . xml_escape($old) . "</file>";
530         }
531     }
532     close COMMIT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
534     push @cia_text,
535         "      </files>",
536         $gitweb_url ? "      <url>" . xml_escape("$gitweb_url/?a=commit;h=$commit") . "</url>" : "",
537         "    </commit>",
538         "  </body>",
539         "  <timestamp>" . $info{"author_date"} . "</timestamp>",
540         "</message>";
542     mail_notification($cia_address, "DeliverXML", "text/xml", @cia_text);
545 # send a global commit notice when there are too many commits for individual mails
546 sub send_global_notice($$$)
548     my ($ref, $old_sha1, $new_sha1) = @_;
549     my $notice = git_rev_list("--pretty", "^$old_sha1", "$new_sha1", @exclude_list);
551     foreach my $rev (@$notice)
552     {
553         $rev =~ s/^commit /URL:    $gitweb_url\/?a=commit;h=/ if $gitweb_url;
554     }
556     mail_notification($commitlist_address, "New commits on branch $ref", "text/plain; charset=UTF-8", @$notice);
559 # send all the notices
560 sub send_all_notices($$$)
562     my ($old_sha1, $new_sha1, $ref) = @_;
563     my ($reftype, $refname, $action, @notice);
565     return if ($ref =~ /^refs\/remotes\//
566         or (@include_list && !grep {$_ eq $ref} @include_list));
567     die "The name \"$ref\" doesn't sound like a local branch or tag"
568         if not (($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/));
570     if ($new_sha1 eq '0' x 40)
571     {
572         $action = "removed";
573         @notice = ( "Old SHA1: $old_sha1" );
574     }
575     elsif ($old_sha1 eq '0' x 40)
576     {
577         $action = "created";
578         @notice = ( "SHA1: $new_sha1" );
579     }
580     elsif ($reftype eq "tag")
581     {
582         $action = "updated";
583         @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
584     }
585     elsif (not grep( $_ eq $old_sha1, @{ git_rev_list( $new_sha1, "--full-history" ) } ))
586     {
587         $action = "rewritten";
588         @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
589     }
591     send_ref_notice( $ref, $action, @notice ) if ($commitlist_address and $action);
593     unless ($reftype eq "tag" or $new_sha1 eq '0' x 40)
594     {
595         my $commits = get_new_commits ( $old_sha1, $new_sha1 );
597         if (@$commits > $max_individual_notices)
598         {
599             send_global_notice( $refname, $old_sha1, $new_sha1 ) if $commitlist_address;
600         }
601         elsif (@$commits > 0)
602         {
603             foreach my $commit (@$commits)
604             {
605                 send_commit_notice( $refname, $commit ) if $commitlist_address;
606                 send_cia_notice( $refname, $commit ) if $cia_project_name;
607             }
608         }
609         elsif ($commitlist_address)
610         {
611             @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
612             send_ref_notice( $ref, "modified", @notice );
613         }
614     }
617 parse_options();
619 umask( $mode_mask );
621 # append repository path to URL
622 $gitweb_url .= "/$repos_name.git" if $gitweb_url;
624 if (@ARGV)
626     send_all_notices( $ARGV[0], $ARGV[1], $ARGV[2] );
628 else  # read them from stdin
630     while (<>)
631     {
632         chomp;
633         if (/^([0-9a-f]{40}) ([0-9a-f]{40}) (.*)$/) { send_all_notices( $1, $2, $3 ); }
634     }
637 exit 0;