Code

faa1785053bf735a90cf713da3b1992b5ca393ab
[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        Enable compatibility with SourceForge's gitweb URLs
26 #   -s bytes  Set the maximum diff size in bytes (-1 for no limit)
27 #   -T        Prefix the mail subject with a [repository name] tag
28 #   -t file   Prevent duplicate notifications by saving state to this file
29 #   -U mask   Set the umask for creating the state file
30 #   -u url    Set the URL to the gitweb browser
31 #   -i branch If at least one -i is given, report only for specified branches
32 #   -x branch Exclude changes to the specified branch from reports
33 #   -X        Exclude merge commits
34 #   -z        Try to abbreviate the SHA1 name within gitweb URLs (unsafe)
35 #
37 use strict;
38 use Fcntl ':flock';
39 use Encode qw(encode decode);
40 use Cwd 'realpath';
42 sub git_config($);
43 sub get_repos_name();
45 # some parameters you may want to change
47 # set this to something that takes "-s"
48 my $mailer = "/usr/bin/mail";
50 # CIA notification address
51 my $cia_address = "cia\@cia.navi.cx";
53 # debug mode
54 my $debug = 0;
56 # configuration parameters
58 # the $mailer doesn't accept headers via "-a" (can be set with the -H option)
59 my $legacy_mail = git_config( "notify.legacymail" );
61 # omit the author from the mail subject (can be set with the -A option)
62 my $omit_author = git_config( "notify.omitauthor" );
64 # prefix the mail subject with a [repository name] tag (can be set with the -T option)
65 my $emit_repo = git_config( "notify.emitrepository" );
67 # show the committer if different from the author (can be set with the -C option)
68 my $show_committer = git_config( "notify.showcommitter" );
70 # base URL of the gitweb repository browser (can be set with the -u option)
71 my $gitweb_url = git_config( "notify.baseurl" );
73 # abbreviate the SHA1 name within gitweb URLs (can be set with the -z option)
74 my $abbreviate_url = git_config( "notify.shorturls" );
76 # enable compatibility with SourceForge's gitweb (can be set with the -S option)
77 my $sourceforge = git_config( "notify.sourceforge" );
79 # default repository name (can be changed with the -r option)
80 my $repos_name = git_config( "notify.repository" ) || get_repos_name();
82 # max size of diffs in bytes (can be changed with the -s option)
83 my $max_diff_size = git_config( "notify.maxdiff" ) || 10000;
85 # address for mail notices (can be set with -m option)
86 my $commitlist_address = git_config( "notify.mail" );
88 # project name for CIA notices (can be set with -c option)
89 my $cia_project_name = git_config( "notify.cia" );
91 # max number of individual notices before falling back to a single global notice (can be set with -n option)
92 my $max_individual_notices = git_config( "notify.maxnotices" ) || 100;
94 # branches to include
95 my @include_list = split /\s+/, git_config( "notify.include" ) || "";
97 # branches to exclude
98 my @exclude_list = split /\s+/, git_config( "notify.exclude" ) || "";
100 # the state file we use (can be set with the -t option)
101 my $state_file = git_config( "notify.statefile" );
103 # umask for creating the state file (can be set with -U option)
104 my $mode_mask = git_config( "notify.umask" ) || 002;
106 # Extra options to git rev-list
107 my @revlist_options;
109 sub usage()
111     print "Usage: $0 [options] [--] old-sha1 new-sha1 refname\n";
112     print "   -A        Omit the author name from the mail subject\n";
113     print "   -C        Show committer in the body if different from the author\n";
114     print "   -c name   Send CIA notifications under specified project name\n";
115     print "   -H        The mail(1) utility doesn't accept headers via `-a'\n";
116     print "   -m addr   Send mail notifications to specified address\n";
117     print "   -n max    Set max number of individual mails to send\n";
118     print "   -r name   Set the git repository name\n";
119     print "   -S        Enable compatibility with SourceForge's gitweb URLs\n";
120     print "   -s bytes  Set the maximum diff size in bytes (-1 for no limit)\n";
121     print "   -T        Prefix the mail subject with a [repository name] tag\n";
122     print "   -t file   Prevent duplicate notifications by saving state to this file\n";
123     print "   -U mask   Set the umask for creating the state file\n";
124     print "   -u url    Set the URL to the gitweb browser\n";
125     print "   -i branch If at least one -i is given, report only for specified branches\n";
126     print "   -x branch Exclude changes to the specified branch from reports\n";
127     print "   -X        Exclude merge commits\n";
128     print "   -z        Try to abbreviate the SHA1 name within gitweb URLs (unsafe)\n";
129     exit 1;
132 sub xml_escape($)
134     my $str = shift;
135     $str =~ s/&/&/g;
136     $str =~ s/</&lt;/g;
137     $str =~ s/>/&gt;/g;
138     my @chars = unpack "U*", $str;
139     $str = join "", map { ($_ > 127) ? sprintf "&#%u;", $_ : chr($_); } @chars;
140     return $str;
143 # execute git-rev-list(1) with the given parameters and return the output
144 sub git_rev_list(@)
146     my @args = @_;
147     my $revlist = [];
148     my $pid = open REVLIST, "-|";
150     die "Cannot open pipe: $!" if not defined $pid;
151     if (!$pid)
152     {
153         exec "git", "rev-list", @revlist_options, @args or die "Cannot execute rev-list: $!";
154     }
155     while (<REVLIST>)
156     {
157         chomp;
158         unless (grep {$_ eq "--pretty"} @args)
159         {
160             die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
161         }
162         push @$revlist, $_;
163     }
164     close REVLIST or die $! ? "Cannot execute rev-list: $!" : "rev-list exited with status: $?";
165     return $revlist;
168 # append the given commit hashes to the state file
169 sub save_commits($)
171     my $commits = shift;
173     open STATE, ">>", $state_file or die "Cannot open $state_file: $!";
174     flock STATE, LOCK_EX or die "Cannot lock $state_file";
175     print STATE "$_\n" for @$commits;
176     flock STATE, LOCK_UN or die "Cannot unlock $state_file";
177     close STATE or die "Cannot close $state_file: $!";
180 # for the given range, return the new hashes (and append them to the state file)
181 sub get_new_commits($$)
183     my ($old_sha1, $new_sha1) = @_;
184     my ($seen, @args);
185     my $newrevs = [];
187     @args = ( "^$old_sha1" ) unless $old_sha1 eq '0' x 40;
188     push @args, $new_sha1, @exclude_list;
190     my $revlist = git_rev_list(@args);
192     if (not defined $state_file or not -e $state_file)
193     {
194         save_commits(git_rev_list("--all", "--full-history")) if defined $state_file;
195         return $revlist;
196     }
198     open STATE, $state_file or die "Cannot open $state_file: $!";
199     flock STATE, LOCK_SH or die "Cannot lock $state_file";
200     while (<STATE>)
201     {
202         chomp;
203         die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
204         $seen->{$_} = 1;
205     }
206     flock STATE, LOCK_UN or die "Cannot unlock $state_file";
207     close STATE or die "Cannot close $state_file: $!";
209     # FIXME: if another git-notify process reads the $state_file at *this*
210     # point, that process might generate duplicates of our notifications.
212     save_commits($revlist);
214     foreach my $commit (@$revlist)
215     {
216         push @$newrevs, $commit unless $seen->{$commit};
217     }
218     return $newrevs;
221 # truncate the given string if it exceeds the specified number of characters
222 sub truncate_str($$)
224     my ($str, $max) = @_;
226     if (length($str) > $max)
227     {
228         $str = substr($str, 0, $max);
229         $str =~ s/\s+\S+$//;
230         $str .= " ...";
231     }
232     return $str;
235 # right-justify the left column of "left: right" elements, omit undefined elements
236 sub format_table(@)
238     my @lines = @_;
239     my @table;
240     my $max = 0;
242     foreach my $line (@lines)
243     {
244        next if not defined $line;
245        my $pos = index($line, ":");
247        $max = $pos if $pos > $max;
248     }
250     foreach my $line (@lines)
251     {
252        next if not defined $line;
253        my ($left, $right) = split(/: */, $line, 2);
255        push @table, (defined $left and defined $right)
256            ? sprintf("%*s: %s", $max + 1, $left, $right)
257            : $line;
258     }
259     return @table;
262 # format an integer date + timezone as string
263 # algorithm taken from git's date.c
264 sub format_date($$)
266     my ($time,$tz) = @_;
268     if ($tz < 0)
269     {
270         my $minutes = (-$tz / 100) * 60 + (-$tz % 100);
271         $time -= $minutes * 60;
272     }
273     else
274     {
275         my $minutes = ($tz / 100) * 60 + ($tz % 100);
276         $time += $minutes * 60;
277     }
278     return gmtime($time) . sprintf " %+05d", $tz;
281 # fetch a parameter from the git config file
282 sub git_config($)
284     my ($param) = @_;
286     open CONFIG, "-|" or exec "git", "config", $param;
287     my $ret = <CONFIG>;
288     chomp $ret if $ret;
289     close CONFIG or $ret = undef;
290     return $ret;
293 # parse command line options
294 sub parse_options()
296     while (@ARGV && $ARGV[0] =~ /^-/)
297     {
298         my $arg = shift @ARGV;
300         if ($arg eq '--') { last; }
301         elsif ($arg eq '-A') { $omit_author = 1; }
302         elsif ($arg eq '-C') { $show_committer = 1; }
303         elsif ($arg eq '-c') { $cia_project_name = shift @ARGV; }
304         elsif ($arg eq '-H') { $legacy_mail = 1; }
305         elsif ($arg eq '-m') { $commitlist_address = shift @ARGV; }
306         elsif ($arg eq '-n') { $max_individual_notices = shift @ARGV; }
307         elsif ($arg eq '-r') { $repos_name = shift @ARGV; }
308         elsif ($arg eq '-S') { $sourceforge = 1; }
309         elsif ($arg eq '-s') { $max_diff_size = shift @ARGV; }
310         elsif ($arg eq '-T') { $emit_repo = 1; }
311         elsif ($arg eq '-t') { $state_file = shift @ARGV; }
312         elsif ($arg eq '-U') { $mode_mask = shift @ARGV; }
313         elsif ($arg eq '-u') { $gitweb_url = shift @ARGV; }
314         elsif ($arg eq '-i') { push @include_list, shift @ARGV; }
315         elsif ($arg eq '-x') { push @exclude_list, shift @ARGV; }
316         elsif ($arg eq '-X') { push @revlist_options, "--no-merges"; }
317         elsif ($arg eq '-z') { $abbreviate_url = 1; }
318         elsif ($arg eq '-d') { $debug++; }
319         else { usage(); }
320     }
321     if (@ARGV && $#ARGV != 2) { usage(); }
322     @exclude_list = map { "^$_"; } @exclude_list;
325 # send an email notification
326 sub mail_notification($$$@)
328     my ($name, $subject, $content_type, @text) = @_;
330     $subject = "[$repos_name] $subject" if $emit_repo;
331     $subject = encode("MIME-Q",$subject);
333     if ($debug)
334     {
335         binmode STDOUT, ":utf8";
336         print "---------------------\n";
337         print "To: $name\n";
338         print "Subject: $subject\n";
339         print "Content-Type: $content_type\n";
340         print "\n", join("\n", @text), "\n";
341     }
342     else
343     {
344         my $pid = open MAIL, "|-";
345         return unless defined $pid;
346         if (!$pid)
347         {
348             my @mailer_options = ( "-s", $subject );
350             unless ($legacy_mail)
351             {
352                 push @mailer_options, "-a", "Content-Type: $content_type";
353             }
354             exec $mailer, @mailer_options, $name or die "Cannot exec $mailer";
355         }
356         binmode MAIL, ":utf8";
357         print MAIL join("\n", @text), "\n";
358         close MAIL or warn $! ? "Cannot execute $mailer: $!" : "$mailer exited with status: $?";
359     }
362 # get the default repository name
363 sub get_repos_name()
365     my $dir = `git rev-parse --git-dir`;
366     chomp $dir;
367     my $repos = realpath($dir);
368     $repos =~ s/(.*?)((\.git\/)?\.git)$/$1/;
369     $repos =~ s/(.*)\/([^\/]+)\/?$/$2/;
370     return $repos;
373 # return the type of the given object
374 sub get_object_type($)
376     my $obj = shift;
378     open TYPE, "-|" or exec "git", "cat-file", "-t", $obj or die "cannot run git-cat-file";
379     my $type = <TYPE>;
380     chomp $type;
381     close TYPE or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
382     return $type;
385 # extract the information from a commit or tag object and return a hash containing the various fields
386 sub get_object_info($)
388     my $obj = shift;
389     my %info = ();
390     my @log = ();
391     my $do_log = 0;
393     $info{"encoding"} = "utf-8";
395     my $type = get_object_type($obj);
397     open OBJ, "-|" or exec "git", "cat-file", $type, $obj or die "cannot run git-cat-file";
398     while (<OBJ>)
399     {
400         chomp;
401         if ($do_log)
402         {
403             last if /^-----BEGIN PGP SIGNATURE-----/;
404             push @log, $_;
405         }
406         elsif (/^(author|committer|tagger) ((.*) (<.*>)) (\d+) ([+-]\d+)$/)
407         {
408             $info{$1} = $2;
409             $info{$1 . "_name"} = $3;
410             $info{$1 . "_email"} = $4;
411             $info{$1 . "_date"} = $5;
412             $info{$1 . "_tz"} = $6;
413         }
414         elsif (/^tag (.+)/)
415         {
416             $info{"tag"} = $1;
417         }
418         elsif (/^encoding (.+)/)
419         {
420             $info{"encoding"} = $1;
421         }
422         elsif (/^$/) { $do_log = 1; }
423     }
424     close OBJ or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
426     $info{"type"} = $type;
427     $info{"log"} = \@log;
428     return %info;
431 # send a ref change notice to a mailing list
432 sub send_ref_notice($$@)
434     my ($ref, $action, @notice) = @_;
435     my ($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/);
437     $reftype =~ s/^head$/branch/;
439     @notice = (format_table(
440         "Module: $repos_name",
441         ($reftype eq "tag" ? "Tag:" : "Branch:") . $refname,
442         @notice,
443         ($action ne "removed" and $gitweb_url)
444             ? "URL: ${gitweb_url}a=shortlog;h=$ref" : undef),
445         "",
446         "The $refname $reftype has been $action.");
448     mail_notification($commitlist_address, "$refname $reftype $action",
449         "text/plain; charset=us-ascii", @notice);
452 # send a commit notice to a mailing list
453 sub send_commit_notice($$)
455     my ($ref,$obj) = @_;
456     my %info = get_object_info($obj);
457     my @notice = ();
458     my ($url,$subject,$obj_string);
460     if ($gitweb_url)
461     {
462         if ($abbreviate_url)
463         {
464             open REVPARSE, "-|" or exec "git", "rev-parse", "--short", $obj or die "cannot exec git-rev-parse";
465             $obj_string = <REVPARSE>;
466             chomp $obj_string if defined $obj_string;
467             close REVPARSE or die $! ? "Cannot execute rev-parse: $!" : "rev-parse exited with status: $?";
468         }
469         $obj_string = $obj if not defined $obj_string;
470         $url = "${gitweb_url}a=$info{type};h=$obj_string";
471     }
473     if ($info{"type"} eq "tag")
474     {
475         push @notice, format_table(
476           "Module: $repos_name",
477           "Tag: $ref",
478           "SHA1: $obj",
479           "Tagger:" . $info{"tagger"},
480           "Date:" . format_date($info{"tagger_date"},$info{"tagger_tz"}),
481           $url ? "URL: $url" : undef),
482           "",
483           join "\n", @{$info{"log"}};
485         $subject = "Tag " . $info{"tag"} . ": ";
486         $subject .= $info{"tagger_name"} . ": " unless $omit_author;
487     }
488     else
489     {
490         push @notice, format_table(
491           "Module: $repos_name",
492           "Branch: $ref",
493           "Commit: $obj",
494           "Author:" . $info{"author"},
495           $show_committer && $info{"committer"} ne $info{"author"} ? "Committer:" . $info{"committer"} : undef,
496           "Date:" . format_date($info{"author_date"},$info{"author_tz"}),
497           $url ? "URL: $url" : undef),
498           "",
499           @{$info{"log"}},
500           "",
501           "---",
502           "";
504         open STAT, "-|" or exec "git", "diff-tree", "--stat", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
505         push @notice, join("", <STAT>);
506         close STAT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
508         open DIFF, "-|" or exec "git", "diff-tree", "-p", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
509         my $diff = join("", <DIFF>);
510         close DIFF or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
512         if (($max_diff_size == -1) || (length($diff) < $max_diff_size))
513         {
514             push @notice, $diff;
515         }
516         else
517         {
518             push @notice, "Diff: ${gitweb_url}a=commitdiff;h=$obj_string" if $gitweb_url;
519         }
520         $subject = $info{"author_name"} . ": " unless $omit_author;
521     }
523     $subject .= truncate_str(${$info{"log"}}[0],50);
524     $_ = decode($info{"encoding"}, $_) for @notice;
525     mail_notification($commitlist_address, $subject, "text/plain; charset=UTF-8", @notice);
528 # send a commit notice to the CIA server
529 sub send_cia_notice($$)
531     my ($ref,$commit) = @_;
532     my %info = get_object_info($commit);
533     my @cia_text = ();
535     return if $info{"type"} ne "commit";
537     push @cia_text,
538         "<message>",
539         "  <generator>",
540         "    <name>git-notify script for CIA</name>",
541         "  </generator>",
542         "  <source>",
543         "    <project>" . xml_escape($cia_project_name) . "</project>",
544         "    <module>" . xml_escape($repos_name) . "</module>",
545         "    <branch>" . xml_escape($ref). "</branch>",
546         "  </source>",
547         "  <body>",
548         "    <commit>",
549         "      <revision>" . substr($commit,0,10) . "</revision>",
550         "      <author>" . xml_escape($info{"author"}) . "</author>",
551         "      <log>" . xml_escape(join "\n", @{$info{"log"}}) . "</log>",
552         "      <files>";
554     open COMMIT, "-|" or exec "git", "diff-tree", "--name-status", "-r", "-M", $commit or die "cannot run git-diff-tree";
555     while (<COMMIT>)
556     {
557         chomp;
558         if (/^([AMD])\t(.*)$/)
559         {
560             my ($action, $file) = ($1, $2);
561             my %actions = ( "A" => "add", "M" => "modify", "D" => "remove" );
562             next unless defined $actions{$action};
563             push @cia_text, "        <file action=\"$actions{$action}\">" . xml_escape($file) . "</file>";
564         }
565         elsif (/^R\d+\t(.*)\t(.*)$/)
566         {
567             my ($old, $new) = ($1, $2);
568             push @cia_text, "        <file action=\"rename\" to=\"" . xml_escape($new) . "\">" . xml_escape($old) . "</file>";
569         }
570     }
571     close COMMIT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
573     push @cia_text,
574         "      </files>",
575         $gitweb_url ? "      <url>" . xml_escape("${gitweb_url}a=commit;h=$commit") . "</url>" : "",
576         "    </commit>",
577         "  </body>",
578         "  <timestamp>" . $info{"author_date"} . "</timestamp>",
579         "</message>";
581     mail_notification($cia_address, "DeliverXML", "text/xml", @cia_text);
584 # send a global commit notice when there are too many commits for individual mails
585 sub send_global_notice($$$)
587     my ($ref, $old_sha1, $new_sha1) = @_;
588     my $notice = git_rev_list("--pretty", "^$old_sha1", "$new_sha1", @exclude_list);
590     foreach my $rev (@$notice)
591     {
592         $rev =~ s/^commit /URL:    ${gitweb_url}a=commit;h=/ if $gitweb_url;
593     }
595     mail_notification($commitlist_address, "New commits on branch $ref", "text/plain; charset=UTF-8", @$notice);
598 # send all the notices
599 sub send_all_notices($$$)
601     my ($old_sha1, $new_sha1, $ref) = @_;
602     my ($reftype, $refname, $tagtype, $action, @notice);
604     return if ($ref =~ /^refs\/remotes\//
605         or (@include_list && !grep {$_ eq $ref} @include_list));
606     die "The name \"$ref\" doesn't sound like a local branch or tag"
607         if not (($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/));
609     if ($reftype eq "tag")
610     {
611         $tagtype = get_object_type($ref) eq "tag" ? "annotated" : "lightweight";
612     }
614     if ($new_sha1 eq '0' x 40)
615     {
616         $action = "removed";
617         @notice = ( "Old SHA1: $old_sha1" );
618     }
619     elsif ($old_sha1 eq '0' x 40)
620     {
621         if ($reftype eq "tag" and $tagtype eq "annotated")
622         {
623             send_commit_notice( $refname, $new_sha1 ) if $commitlist_address;
624             return;
625         }
626         $action = "created";
627         @notice = ( "SHA1: $new_sha1" );
628     }
629     elsif ($reftype eq "tag")
630     {
631         $action = "updated";
632         @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
633     }
634     elsif (not grep( $_ eq $old_sha1, @{ git_rev_list( $new_sha1, "--full-history" ) } ))
635     {
636         $action = "rewritten";
637         @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
638     }
640     send_ref_notice( $ref, $action, @notice ) if ($commitlist_address and $action);
642     unless ($reftype eq "tag" or $new_sha1 eq '0' x 40)
643     {
644         my $commits = get_new_commits ( $old_sha1, $new_sha1 );
646         if (@$commits > $max_individual_notices)
647         {
648             send_global_notice( $refname, $old_sha1, $new_sha1 ) if $commitlist_address;
649         }
650         elsif (@$commits > 0)
651         {
652             foreach my $commit (@$commits)
653             {
654                 send_commit_notice( $refname, $commit ) if $commitlist_address;
655                 send_cia_notice( $refname, $commit ) if $cia_project_name;
656             }
657         }
658         elsif ($commitlist_address)
659         {
660             @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
661             send_ref_notice( $ref, "modified", @notice );
662         }
663     }
666 parse_options();
668 umask( $mode_mask );
670 # append repository path to URL
671 if ($gitweb_url) {
672     $gitweb_url .= $sourceforge ? "/$repos_name;" : "/$repos_name.git/?";
675 if (@ARGV)
677     send_all_notices( $ARGV[0], $ARGV[1], $ARGV[2] );
679 else  # read them from stdin
681     while (<>)
682     {
683         chomp;
684         if (/^([0-9a-f]{40}) ([0-9a-f]{40}) (.*)$/) { send_all_notices( $1, $2, $3 ); }
685     }
688 exit 0;