Code

git-notify: Optionally call mail(1) without "-a"
[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 #   -H        The mail(1) utility doesn't accept headers via "-a"
22 #   -m addr   Send mail notifications to specified address
23 #   -n max    Set max number of individual mails to send
24 #   -r name   Set the git repository name
25 #   -s bytes  Set the maximum diff size in bytes (-1 for no limit)
26 #   -T        Prefix the mail subject with a [repository name] tag
27 #   -t file   Prevent duplicate notifications by saving state to this file
28 #   -U mask   Set the umask for creating the state file
29 #   -u url    Set the URL to the gitweb browser
30 #   -i branch If at least one -i is given, report only for specified branches
31 #   -x branch Exclude changes to the specified branch from reports
32 #   -X        Exclude merge commits
33 #   -z        Try to abbreviate the SHA1 name within gitweb URLs (unsafe)
34 #
36 use strict;
37 use Fcntl ':flock';
38 use Encode qw(encode decode);
39 use Cwd 'realpath';
41 sub git_config($);
42 sub get_repos_name();
44 # some parameters you may want to change
46 # set this to something that takes "-s"
47 my $mailer = "/usr/bin/mail";
49 # CIA notification address
50 my $cia_address = "cia\@cia.navi.cx";
52 # debug mode
53 my $debug = 0;
55 # configuration parameters
57 # the $mailer doesn't accept headers via "-a" (can be set with the -H option)
58 my $legacy_mail = git_config( "notify.legacymail" );
60 # omit the author from the mail subject (can be set with the -A option)
61 my $omit_author = git_config( "notify.omitauthor" );
63 # prefix the mail subject with a [repository name] tag (can be set with the -T option)
64 my $emit_repo = git_config( "notify.emitrepository" );
66 # show the committer if different from the author (can be set with the -C option)
67 my $show_committer = git_config( "notify.showcommitter" );
69 # base URL of the gitweb repository browser (can be set with the -u option)
70 my $gitweb_url = git_config( "notify.baseurl" );
72 # abbreviate the SHA1 name within gitweb URLs (can be set with the -z option)
73 my $abbreviate_url = git_config( "notify.shorturls" );
75 # default repository name (can be changed with the -r option)
76 my $repos_name = git_config( "notify.repository" ) || get_repos_name();
78 # max size of diffs in bytes (can be changed with the -s option)
79 my $max_diff_size = git_config( "notify.maxdiff" ) || 10000;
81 # address for mail notices (can be set with -m option)
82 my $commitlist_address = git_config( "notify.mail" );
84 # project name for CIA notices (can be set with -c option)
85 my $cia_project_name = git_config( "notify.cia" );
87 # max number of individual notices before falling back to a single global notice (can be set with -n option)
88 my $max_individual_notices = git_config( "notify.maxnotices" ) || 100;
90 # branches to include
91 my @include_list = split /\s+/, git_config( "notify.include" ) || "";
93 # branches to exclude
94 my @exclude_list = split /\s+/, git_config( "notify.exclude" ) || "";
96 # the state file we use (can be set with the -t option)
97 my $state_file = git_config( "notify.statefile" );
99 # umask for creating the state file (can be set with -U option)
100 my $mode_mask = git_config( "notify.umask" ) || 002;
102 # Extra options to git rev-list
103 my @revlist_options;
105 sub usage()
107     print "Usage: $0 [options] [--] old-sha1 new-sha1 refname\n";
108     print "   -A        Omit the author name from the mail subject\n";
109     print "   -C        Show committer in the body if different from the author\n";
110     print "   -c name   Send CIA notifications under specified project name\n";
111     print "   -H        The mail(1) utility doesn't accept headers via `-a'\n";
112     print "   -m addr   Send mail notifications to specified address\n";
113     print "   -n max    Set max number of individual mails to send\n";
114     print "   -r name   Set the git repository name\n";
115     print "   -s bytes  Set the maximum diff size in bytes (-1 for no limit)\n";
116     print "   -T        Prefix the mail subject with a [repository name] tag\n";
117     print "   -t file   Prevent duplicate notifications by saving state to this file\n";
118     print "   -U mask   Set the umask for creating the state file\n";
119     print "   -u url    Set the URL to the gitweb browser\n";
120     print "   -i branch If at least one -i is given, report only for specified branches\n";
121     print "   -x branch Exclude changes to the specified branch from reports\n";
122     print "   -X        Exclude merge commits\n";
123     print "   -z        Try to abbreviate the SHA1 name within gitweb URLs (unsafe)\n";
124     exit 1;
127 sub xml_escape($)
129     my $str = shift;
130     $str =~ s/&/&/g;
131     $str =~ s/</&lt;/g;
132     $str =~ s/>/&gt;/g;
133     my @chars = unpack "U*", $str;
134     $str = join "", map { ($_ > 127) ? sprintf "&#%u;", $_ : chr($_); } @chars;
135     return $str;
138 # execute git-rev-list(1) with the given parameters and return the output
139 sub git_rev_list(@)
141     my @args = @_;
142     my $revlist = [];
143     my $pid = open REVLIST, "-|";
145     die "Cannot open pipe: $!" if not defined $pid;
146     if (!$pid)
147     {
148         exec "git", "rev-list", @revlist_options, @args or die "Cannot execute rev-list: $!";
149     }
150     while (<REVLIST>)
151     {
152         chomp;
153         unless (grep {$_ eq "--pretty"} @args)
154         {
155             die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
156         }
157         push @$revlist, $_;
158     }
159     close REVLIST or die $! ? "Cannot execute rev-list: $!" : "rev-list exited with status: $?";
160     return $revlist;
163 # append the given commit hashes to the state file
164 sub save_commits($)
166     my $commits = shift;
168     open STATE, ">>", $state_file or die "Cannot open $state_file: $!";
169     flock STATE, LOCK_EX or die "Cannot lock $state_file";
170     print STATE "$_\n" for @$commits;
171     flock STATE, LOCK_UN or die "Cannot unlock $state_file";
172     close STATE or die "Cannot close $state_file: $!";
175 # for the given range, return the new hashes (and append them to the state file)
176 sub get_new_commits($$)
178     my ($old_sha1, $new_sha1) = @_;
179     my ($seen, @args);
180     my $newrevs = [];
182     @args = ( "^$old_sha1" ) unless $old_sha1 eq '0' x 40;
183     push @args, $new_sha1, @exclude_list;
185     my $revlist = git_rev_list(@args);
187     if (not defined $state_file or not -e $state_file)
188     {
189         save_commits(git_rev_list("--all", "--full-history")) if defined $state_file;
190         return $revlist;
191     }
193     open STATE, $state_file or die "Cannot open $state_file: $!";
194     flock STATE, LOCK_SH or die "Cannot lock $state_file";
195     while (<STATE>)
196     {
197         chomp;
198         die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
199         $seen->{$_} = 1;
200     }
201     flock STATE, LOCK_UN or die "Cannot unlock $state_file";
202     close STATE or die "Cannot close $state_file: $!";
204     # FIXME: if another git-notify process reads the $state_file at *this*
205     # point, that process might generate duplicates of our notifications.
207     save_commits($revlist);
209     foreach my $commit (@$revlist)
210     {
211         push @$newrevs, $commit unless $seen->{$commit};
212     }
213     return $newrevs;
216 # truncate the given string if it exceeds the specified number of characters
217 sub truncate_str($$)
219     my ($str, $max) = @_;
221     if (length($str) > $max)
222     {
223         $str = substr($str, 0, $max);
224         $str =~ s/\s+\S+$//;
225         $str .= " ...";
226     }
227     return $str;
230 # right-justify the left column of "left: right" elements, omit undefined elements
231 sub format_table(@)
233     my @lines = @_;
234     my @table;
235     my $max = 0;
237     foreach my $line (@lines)
238     {
239        next if not defined $line;
240        my $pos = index($line, ":");
242        $max = $pos if $pos > $max;
243     }
245     foreach my $line (@lines)
246     {
247        next if not defined $line;
248        my ($left, $right) = split(/: */, $line, 2);
250        push @table, (defined $left and defined $right)
251            ? sprintf("%*s: %s", $max + 1, $left, $right)
252            : $line;
253     }
254     return @table;
257 # format an integer date + timezone as string
258 # algorithm taken from git's date.c
259 sub format_date($$)
261     my ($time,$tz) = @_;
263     if ($tz < 0)
264     {
265         my $minutes = (-$tz / 100) * 60 + (-$tz % 100);
266         $time -= $minutes * 60;
267     }
268     else
269     {
270         my $minutes = ($tz / 100) * 60 + ($tz % 100);
271         $time += $minutes * 60;
272     }
273     return gmtime($time) . sprintf " %+05d", $tz;
276 # fetch a parameter from the git config file
277 sub git_config($)
279     my ($param) = @_;
281     open CONFIG, "-|" or exec "git", "config", $param;
282     my $ret = <CONFIG>;
283     chomp $ret if $ret;
284     close CONFIG or $ret = undef;
285     return $ret;
288 # parse command line options
289 sub parse_options()
291     while (@ARGV && $ARGV[0] =~ /^-/)
292     {
293         my $arg = shift @ARGV;
295         if ($arg eq '--') { last; }
296         elsif ($arg eq '-A') { $omit_author = 1; }
297         elsif ($arg eq '-C') { $show_committer = 1; }
298         elsif ($arg eq '-c') { $cia_project_name = shift @ARGV; }
299         elsif ($arg eq '-H') { $legacy_mail = 1; }
300         elsif ($arg eq '-m') { $commitlist_address = shift @ARGV; }
301         elsif ($arg eq '-n') { $max_individual_notices = shift @ARGV; }
302         elsif ($arg eq '-r') { $repos_name = shift @ARGV; }
303         elsif ($arg eq '-s') { $max_diff_size = shift @ARGV; }
304         elsif ($arg eq '-T') { $emit_repo = 1; }
305         elsif ($arg eq '-t') { $state_file = shift @ARGV; }
306         elsif ($arg eq '-U') { $mode_mask = shift @ARGV; }
307         elsif ($arg eq '-u') { $gitweb_url = shift @ARGV; }
308         elsif ($arg eq '-i') { push @include_list, shift @ARGV; }
309         elsif ($arg eq '-x') { push @exclude_list, shift @ARGV; }
310         elsif ($arg eq '-X') { push @revlist_options, "--no-merges"; }
311         elsif ($arg eq '-z') { $abbreviate_url = 1; }
312         elsif ($arg eq '-d') { $debug++; }
313         else { usage(); }
314     }
315     if (@ARGV && $#ARGV != 2) { usage(); }
316     @exclude_list = map { "^$_"; } @exclude_list;
319 # send an email notification
320 sub mail_notification($$$@)
322     my ($name, $subject, $content_type, @text) = @_;
324     $subject = "[$repos_name] $subject" if $emit_repo;
325     $subject = encode("MIME-Q",$subject);
327     if ($debug)
328     {
329         binmode STDOUT, ":utf8";
330         print "---------------------\n";
331         print "To: $name\n";
332         print "Subject: $subject\n";
333         print "Content-Type: $content_type\n";
334         print "\n", join("\n", @text), "\n";
335     }
336     else
337     {
338         my $pid = open MAIL, "|-";
339         return unless defined $pid;
340         if (!$pid)
341         {
342             my @mailer_options = ( "-s", $subject );
344             unless ($legacy_mail)
345             {
346                 push @mailer_options, "-a", "Content-Type: $content_type";
347             }
348             exec $mailer, @mailer_options, $name or die "Cannot exec $mailer";
349         }
350         binmode MAIL, ":utf8";
351         print MAIL join("\n", @text), "\n";
352         close MAIL or warn $! ? "Cannot execute $mailer: $!" : "$mailer exited with status: $?";
353     }
356 # get the default repository name
357 sub get_repos_name()
359     my $dir = `git rev-parse --git-dir`;
360     chomp $dir;
361     my $repos = realpath($dir);
362     $repos =~ s/(.*?)((\.git\/)?\.git)$/$1/;
363     $repos =~ s/(.*)\/([^\/]+)\/?$/$2/;
364     return $repos;
367 # return the type of the given object
368 sub get_object_type($)
370     my $obj = shift;
372     open TYPE, "-|" or exec "git", "cat-file", "-t", $obj or die "cannot run git-cat-file";
373     my $type = <TYPE>;
374     chomp $type;
375     close TYPE or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
376     return $type;
379 # extract the information from a commit or tag object and return a hash containing the various fields
380 sub get_object_info($)
382     my $obj = shift;
383     my %info = ();
384     my @log = ();
385     my $do_log = 0;
387     $info{"encoding"} = "utf-8";
389     my $type = get_object_type($obj);
391     open OBJ, "-|" or exec "git", "cat-file", $type, $obj or die "cannot run git-cat-file";
392     while (<OBJ>)
393     {
394         chomp;
395         if ($do_log)
396         {
397             last if /^-----BEGIN PGP SIGNATURE-----/;
398             push @log, $_;
399         }
400         elsif (/^(author|committer|tagger) ((.*) (<.*>)) (\d+) ([+-]\d+)$/)
401         {
402             $info{$1} = $2;
403             $info{$1 . "_name"} = $3;
404             $info{$1 . "_email"} = $4;
405             $info{$1 . "_date"} = $5;
406             $info{$1 . "_tz"} = $6;
407         }
408         elsif (/^tag (.+)/)
409         {
410             $info{"tag"} = $1;
411         }
412         elsif (/^encoding (.+)/)
413         {
414             $info{"encoding"} = $1;
415         }
416         elsif (/^$/) { $do_log = 1; }
417     }
418     close OBJ or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
420     $info{"type"} = $type;
421     $info{"log"} = \@log;
422     return %info;
425 # send a ref change notice to a mailing list
426 sub send_ref_notice($$@)
428     my ($ref, $action, @notice) = @_;
429     my ($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/);
431     $reftype =~ s/^head$/branch/;
433     @notice = (format_table(
434         "Module: $repos_name",
435         ($reftype eq "tag" ? "Tag:" : "Branch:") . $refname,
436         @notice,
437         ($action ne "removed" and $gitweb_url)
438             ? "URL: $gitweb_url/?a=shortlog;h=$ref" : undef),
439         "",
440         "The $refname $reftype has been $action.");
442     mail_notification($commitlist_address, "$refname $reftype $action",
443         "text/plain; charset=us-ascii", @notice);
446 # send a commit notice to a mailing list
447 sub send_commit_notice($$)
449     my ($ref,$obj) = @_;
450     my %info = get_object_info($obj);
451     my @notice = ();
452     my ($url,$subject,$obj_string);
454     if ($gitweb_url)
455     {
456         if ($abbreviate_url)
457         {
458             open REVPARSE, "-|" or exec "git", "rev-parse", "--short", $obj or die "cannot exec git-rev-parse";
459             $obj_string = <REVPARSE>;
460             chomp $obj_string if defined $obj_string;
461             close REVPARSE or die $! ? "Cannot execute rev-parse: $!" : "rev-parse exited with status: $?";
462         }
463         $obj_string = $obj if not defined $obj_string;
464         $url = "$gitweb_url/?a=$info{type};h=$obj_string";
465     }
467     if ($info{"type"} eq "tag")
468     {
469         push @notice, format_table(
470           "Module: $repos_name",
471           "Tag: $ref",
472           "SHA1: $obj",
473           "Tagger:" . $info{"tagger"},
474           "Date:" . format_date($info{"tagger_date"},$info{"tagger_tz"}),
475           $url ? "URL: $url" : undef),
476           "",
477           join "\n", @{$info{"log"}};
479         $subject = "Tag " . $info{"tag"} . ": ";
480         $subject .= $info{"tagger_name"} . ": " unless $omit_author;
481     }
482     else
483     {
484         push @notice, format_table(
485           "Module: $repos_name",
486           "Branch: $ref",
487           "Commit: $obj",
488           "Author:" . $info{"author"},
489           $show_committer && $info{"committer"} ne $info{"author"} ? "Committer:" . $info{"committer"} : undef,
490           "Date:" . format_date($info{"author_date"},$info{"author_tz"}),
491           $url ? "URL: $url" : undef),
492           "",
493           @{$info{"log"}},
494           "",
495           "---",
496           "";
498         open STAT, "-|" or exec "git", "diff-tree", "--stat", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
499         push @notice, join("", <STAT>);
500         close STAT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
502         open DIFF, "-|" or exec "git", "diff-tree", "-p", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
503         my $diff = join("", <DIFF>);
504         close DIFF or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
506         if (($max_diff_size == -1) || (length($diff) < $max_diff_size))
507         {
508             push @notice, $diff;
509         }
510         else
511         {
512             push @notice, "Diff: $gitweb_url/?a=commitdiff;h=$obj_string" if $gitweb_url;
513         }
514         $subject = $info{"author_name"} . ": " unless $omit_author;
515     }
517     $subject .= truncate_str(${$info{"log"}}[0],50);
518     $_ = decode($info{"encoding"}, $_) for @notice;
519     mail_notification($commitlist_address, $subject, "text/plain; charset=UTF-8", @notice);
522 # send a commit notice to the CIA server
523 sub send_cia_notice($$)
525     my ($ref,$commit) = @_;
526     my %info = get_object_info($commit);
527     my @cia_text = ();
529     return if $info{"type"} ne "commit";
531     push @cia_text,
532         "<message>",
533         "  <generator>",
534         "    <name>git-notify script for CIA</name>",
535         "  </generator>",
536         "  <source>",
537         "    <project>" . xml_escape($cia_project_name) . "</project>",
538         "    <module>" . xml_escape($repos_name) . "</module>",
539         "    <branch>" . xml_escape($ref). "</branch>",
540         "  </source>",
541         "  <body>",
542         "    <commit>",
543         "      <revision>" . substr($commit,0,10) . "</revision>",
544         "      <author>" . xml_escape($info{"author"}) . "</author>",
545         "      <log>" . xml_escape(join "\n", @{$info{"log"}}) . "</log>",
546         "      <files>";
548     open COMMIT, "-|" or exec "git", "diff-tree", "--name-status", "-r", "-M", $commit or die "cannot run git-diff-tree";
549     while (<COMMIT>)
550     {
551         chomp;
552         if (/^([AMD])\t(.*)$/)
553         {
554             my ($action, $file) = ($1, $2);
555             my %actions = ( "A" => "add", "M" => "modify", "D" => "remove" );
556             next unless defined $actions{$action};
557             push @cia_text, "        <file action=\"$actions{$action}\">" . xml_escape($file) . "</file>";
558         }
559         elsif (/^R\d+\t(.*)\t(.*)$/)
560         {
561             my ($old, $new) = ($1, $2);
562             push @cia_text, "        <file action=\"rename\" to=\"" . xml_escape($new) . "\">" . xml_escape($old) . "</file>";
563         }
564     }
565     close COMMIT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
567     push @cia_text,
568         "      </files>",
569         $gitweb_url ? "      <url>" . xml_escape("$gitweb_url/?a=commit;h=$commit") . "</url>" : "",
570         "    </commit>",
571         "  </body>",
572         "  <timestamp>" . $info{"author_date"} . "</timestamp>",
573         "</message>";
575     mail_notification($cia_address, "DeliverXML", "text/xml", @cia_text);
578 # send a global commit notice when there are too many commits for individual mails
579 sub send_global_notice($$$)
581     my ($ref, $old_sha1, $new_sha1) = @_;
582     my $notice = git_rev_list("--pretty", "^$old_sha1", "$new_sha1", @exclude_list);
584     foreach my $rev (@$notice)
585     {
586         $rev =~ s/^commit /URL:    $gitweb_url\/?a=commit;h=/ if $gitweb_url;
587     }
589     mail_notification($commitlist_address, "New commits on branch $ref", "text/plain; charset=UTF-8", @$notice);
592 # send all the notices
593 sub send_all_notices($$$)
595     my ($old_sha1, $new_sha1, $ref) = @_;
596     my ($reftype, $refname, $tagtype, $action, @notice);
598     return if ($ref =~ /^refs\/remotes\//
599         or (@include_list && !grep {$_ eq $ref} @include_list));
600     die "The name \"$ref\" doesn't sound like a local branch or tag"
601         if not (($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/));
603     if ($reftype eq "tag")
604     {
605         $tagtype = get_object_type($ref) eq "tag" ? "annotated" : "lightweight";
606     }
608     if ($new_sha1 eq '0' x 40)
609     {
610         $action = "removed";
611         @notice = ( "Old SHA1: $old_sha1" );
612     }
613     elsif ($old_sha1 eq '0' x 40)
614     {
615         if ($reftype eq "tag" and $tagtype eq "annotated")
616         {
617             send_commit_notice( $refname, $new_sha1 ) if $commitlist_address;
618             return;
619         }
620         $action = "created";
621         @notice = ( "SHA1: $new_sha1" );
622     }
623     elsif ($reftype eq "tag")
624     {
625         $action = "updated";
626         @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
627     }
628     elsif (not grep( $_ eq $old_sha1, @{ git_rev_list( $new_sha1, "--full-history" ) } ))
629     {
630         $action = "rewritten";
631         @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
632     }
634     send_ref_notice( $ref, $action, @notice ) if ($commitlist_address and $action);
636     unless ($reftype eq "tag" or $new_sha1 eq '0' x 40)
637     {
638         my $commits = get_new_commits ( $old_sha1, $new_sha1 );
640         if (@$commits > $max_individual_notices)
641         {
642             send_global_notice( $refname, $old_sha1, $new_sha1 ) if $commitlist_address;
643         }
644         elsif (@$commits > 0)
645         {
646             foreach my $commit (@$commits)
647             {
648                 send_commit_notice( $refname, $commit ) if $commitlist_address;
649                 send_cia_notice( $refname, $commit ) if $cia_project_name;
650             }
651         }
652         elsif ($commitlist_address)
653         {
654             @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
655             send_ref_notice( $ref, "modified", @notice );
656         }
657     }
660 parse_options();
662 umask( $mode_mask );
664 # append repository path to URL
665 $gitweb_url .= "/$repos_name.git" if $gitweb_url;
667 if (@ARGV)
669     send_all_notices( $ARGV[0], $ARGV[1], $ARGV[2] );
671 else  # read them from stdin
673     while (<>)
674     {
675         chomp;
676         if (/^([0-9a-f]{40}) ([0-9a-f]{40}) (.*)$/) { send_all_notices( $1, $2, $3 ); }
677     }
680 exit 0;