Code

289a5f645a0f9f69b427edab8f6a063138d2c47f
[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 #   -z        Try to abbreviate the SHA1 name within gitweb URLs (unsafe)
31 #
33 use strict;
34 use Fcntl ':flock';
35 use Encode qw(encode decode);
36 use Cwd 'realpath';
38 sub git_config($);
39 sub get_repos_name();
41 # some parameters you may want to change
43 # set this to something that takes "-s"
44 my $mailer = "/usr/bin/mail";
46 # CIA notification address
47 my $cia_address = "cia\@cia.navi.cx";
49 # debug mode
50 my $debug = 0;
52 # configuration parameters
54 # show the committer if different from the author (can be set with the -C option)
55 my $show_committer = git_config( "notify.showcommitter" );
57 # base URL of the gitweb repository browser (can be set with the -u option)
58 my $gitweb_url = git_config( "notify.baseurl" );
60 # abbreviate the SHA1 name within gitweb URLs (can be set with the -z option)
61 my $abbreviate_url = git_config( "notify.shorturls" );
63 # default repository name (can be changed with the -r option)
64 my $repos_name = git_config( "notify.repository" ) || get_repos_name();
66 # max size of diffs in bytes (can be changed with the -s option)
67 my $max_diff_size = git_config( "notify.maxdiff" ) || 10000;
69 # address for mail notices (can be set with -m option)
70 my $commitlist_address = git_config( "notify.mail" );
72 # project name for CIA notices (can be set with -c option)
73 my $cia_project_name = git_config( "notify.cia" );
75 # max number of individual notices before falling back to a single global notice (can be set with -n option)
76 my $max_individual_notices = git_config( "notify.maxnotices" ) || 100;
78 # branches to include
79 my @include_list = split /\s+/, git_config( "notify.include" ) || "";
81 # branches to exclude
82 my @exclude_list = split /\s+/, git_config( "notify.exclude" ) || "";
84 # the state file we use (can be set with the -t option)
85 my $state_file = git_config( "notify.statefile" );
87 # umask for creating the state file (can be set with -U option)
88 my $mode_mask = git_config( "notify.umask" ) || 002;
90 # Extra options to git rev-list
91 my @revlist_options;
93 sub usage()
94 {
95     print "Usage: $0 [options] [--] old-sha1 new-sha1 refname\n";
96     print "   -C        Show committer in the body if different from the author\n";
97     print "   -c name   Send CIA notifications under specified project name\n";
98     print "   -m addr   Send mail notifications to specified address\n";
99     print "   -n max    Set max number of individual mails to send\n";
100     print "   -r name   Set the git repository name\n";
101     print "   -s bytes  Set the maximum diff size in bytes (-1 for no limit)\n";
102     print "   -t file   Prevent duplicate notifications by saving state to this file\n";
103     print "   -U mask   Set the umask for creating the state file\n";
104     print "   -u url    Set the URL to the gitweb browser\n";
105     print "   -i branch If at least one -i is given, report only for specified branches\n";
106     print "   -x branch Exclude changes to the specified branch from reports\n";
107     print "   -X        Exclude merge commits\n";
108     print "   -z        Try to abbreviate the SHA1 name within gitweb URLs (unsafe)\n";
109     exit 1;
112 sub xml_escape($)
114     my $str = shift;
115     $str =~ s/&/&/g;
116     $str =~ s/</&lt;/g;
117     $str =~ s/>/&gt;/g;
118     my @chars = unpack "U*", $str;
119     $str = join "", map { ($_ > 127) ? sprintf "&#%u;", $_ : chr($_); } @chars;
120     return $str;
123 # execute git-rev-list(1) with the given parameters and return the output
124 sub git_rev_list(@)
126     my @args = @_;
127     my $revlist = [];
128     my $pid = open REVLIST, "-|";
130     die "Cannot open pipe: $!" if not defined $pid;
131     if (!$pid)
132     {
133         exec "git", "rev-list", @revlist_options, @args or die "Cannot execute rev-list: $!";
134     }
135     while (<REVLIST>)
136     {
137         chomp;
138         die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
139         push @$revlist, $_;
140     }
141     close REVLIST or die $! ? "Cannot execute rev-list: $!" : "rev-list exited with status: $?";
142     return $revlist;
145 # append the given commit hashes to the state file
146 sub save_commits($)
148     my $commits = shift;
150     open STATE, ">>", $state_file or die "Cannot open $state_file: $!";
151     flock STATE, LOCK_EX or die "Cannot lock $state_file";
152     print STATE "$_\n" for @$commits;
153     flock STATE, LOCK_UN or die "Cannot unlock $state_file";
154     close STATE or die "Cannot close $state_file: $!";
157 # for the given range, return the new hashes (and append them to the state file)
158 sub get_new_commits($$)
160     my ($old_sha1, $new_sha1) = @_;
161     my ($seen, @args);
162     my $newrevs = [];
164     @args = ( "^$old_sha1" ) unless $old_sha1 eq '0' x 40;
165     push @args, $new_sha1, @exclude_list;
167     my $revlist = git_rev_list(@args);
169     if (not defined $state_file or not -e $state_file)
170     {
171         save_commits(git_rev_list("--all", "--full-history")) if defined $state_file;
172         return $revlist;
173     }
175     open STATE, $state_file or die "Cannot open $state_file: $!";
176     flock STATE, LOCK_SH or die "Cannot lock $state_file";
177     while (<STATE>)
178     {
179         chomp;
180         die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
181         $seen->{$_} = 1;
182     }
183     flock STATE, LOCK_UN or die "Cannot unlock $state_file";
184     close STATE or die "Cannot close $state_file: $!";
186     # FIXME: if another git-notify process reads the $state_file at *this*
187     # point, that process might generate duplicates of our notifications.
189     save_commits($revlist);
191     foreach my $commit (@$revlist)
192     {
193         push @$newrevs, $commit unless $seen->{$commit};
194     }
195     return $newrevs;
198 # truncate the given string if it exceeds the specified number of characters
199 sub truncate_str($$)
201     my ($str, $max) = @_;
203     if (length($str) > $max)
204     {
205         $str = substr($str, 0, $max);
206         $str =~ s/\s+\S+$//;
207         $str .= " ...";
208     }
209     return $str;
212 # right-justify the left column of "left: right" elements, omit undefined elements
213 sub format_table(@)
215     my @lines = @_;
216     my @table;
217     my $max = 0;
219     foreach my $line (@lines)
220     {
221        next if not defined $line;
222        my $pos = index($line, ":");
224        $max = $pos if $pos > $max;
225     }
227     foreach my $line (@lines)
228     {
229        next if not defined $line;
230        my ($left, $right) = split(/: */, $line, 2);
232        push @table, (defined $left and defined $right)
233            ? sprintf("%*s: %s", $max + 1, $left, $right)
234            : $line;
235     }
236     return @table;
239 # format an integer date + timezone as string
240 # algorithm taken from git's date.c
241 sub format_date($$)
243     my ($time,$tz) = @_;
245     if ($tz < 0)
246     {
247         my $minutes = (-$tz / 100) * 60 + (-$tz % 100);
248         $time -= $minutes * 60;
249     }
250     else
251     {
252         my $minutes = ($tz / 100) * 60 + ($tz % 100);
253         $time += $minutes * 60;
254     }
255     return gmtime($time) . sprintf " %+05d", $tz;
258 # fetch a parameter from the git config file
259 sub git_config($)
261     my ($param) = @_;
263     open CONFIG, "-|" or exec "git", "config", $param;
264     my $ret = <CONFIG>;
265     chomp $ret if $ret;
266     close CONFIG or $ret = undef;
267     return $ret;
270 # parse command line options
271 sub parse_options()
273     while (@ARGV && $ARGV[0] =~ /^-/)
274     {
275         my $arg = shift @ARGV;
277         if ($arg eq '--') { last; }
278         elsif ($arg eq '-C') { $show_committer = 1; }
279         elsif ($arg eq '-c') { $cia_project_name = shift @ARGV; }
280         elsif ($arg eq '-m') { $commitlist_address = shift @ARGV; }
281         elsif ($arg eq '-n') { $max_individual_notices = shift @ARGV; }
282         elsif ($arg eq '-r') { $repos_name = shift @ARGV; }
283         elsif ($arg eq '-s') { $max_diff_size = shift @ARGV; }
284         elsif ($arg eq '-t') { $state_file = shift @ARGV; }
285         elsif ($arg eq '-U') { $mode_mask = shift @ARGV; }
286         elsif ($arg eq '-u') { $gitweb_url = shift @ARGV; }
287         elsif ($arg eq '-i') { push @include_list, shift @ARGV; }
288         elsif ($arg eq '-x') { push @exclude_list, shift @ARGV; }
289         elsif ($arg eq '-X') { push @revlist_options, "--no-merges"; }
290         elsif ($arg eq '-z') { $abbreviate_url = 1; }
291         elsif ($arg eq '-d') { $debug++; }
292         else { usage(); }
293     }
294     if (@ARGV && $#ARGV != 2) { usage(); }
295     @exclude_list = map { "^$_"; } @exclude_list;
298 # send an email notification
299 sub mail_notification($$$@)
301     my ($name, $subject, $content_type, @text) = @_;
302     $subject = encode("MIME-Q",$subject);
303     if ($debug)
304     {
305         binmode STDOUT, ":utf8";
306         print "---------------------\n";
307         print "To: $name\n";
308         print "Subject: $subject\n";
309         print "Content-Type: $content_type\n";
310         print "\n", join("\n", @text), "\n";
311     }
312     else
313     {
314         my $pid = open MAIL, "|-";
315         return unless defined $pid;
316         if (!$pid)
317         {
318             exec $mailer, "-s", $subject, "-a", "Content-Type: $content_type", $name or die "Cannot exec $mailer";
319         }
320         binmode MAIL, ":utf8";
321         print MAIL join("\n", @text), "\n";
322         close MAIL or warn $! ? "Cannot execute $mailer: $!" : "$mailer exited with status: $?";
323     }
326 # get the default repository name
327 sub get_repos_name()
329     my $dir = `git rev-parse --git-dir`;
330     chomp $dir;
331     my $repos = realpath($dir);
332     $repos =~ s/(.*?)((\.git\/)?\.git)$/$1/;
333     $repos =~ s/(.*)\/([^\/]+)\/?$/$2/;
334     return $repos;
337 # extract the information from a commit or tag object and return a hash containing the various fields
338 sub get_object_info($)
340     my $obj = shift;
341     my %info = ();
342     my @log = ();
343     my $do_log = 0;
345     $info{"encoding"} = "utf-8";
347     open TYPE, "-|" or exec "git", "cat-file", "-t", $obj or die "cannot run git-cat-file";
348     my $type = <TYPE>;
349     chomp $type;
350     close TYPE or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
352     open OBJ, "-|" or exec "git", "cat-file", $type, $obj or die "cannot run git-cat-file";
353     while (<OBJ>)
354     {
355         chomp;
356         if ($do_log)
357         {
358             last if /^-----BEGIN PGP SIGNATURE-----/;
359             push @log, $_;
360         }
361         elsif (/^(author|committer|tagger) ((.*) (<.*>)) (\d+) ([+-]\d+)$/)
362         {
363             $info{$1} = $2;
364             $info{$1 . "_name"} = $3;
365             $info{$1 . "_email"} = $4;
366             $info{$1 . "_date"} = $5;
367             $info{$1 . "_tz"} = $6;
368         }
369         elsif (/^tag (.+)/)
370         {
371             $info{"tag"} = $1;
372         }
373         elsif (/^encoding (.+)/)
374         {
375             $info{"encoding"} = $1;
376         }
377         elsif (/^$/) { $do_log = 1; }
378     }
379     close OBJ or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
381     $info{"type"} = $type;
382     $info{"log"} = \@log;
383     return %info;
386 # send a ref change notice to a mailing list
387 sub send_ref_notice($$@)
389     my ($ref, $action, @notice) = @_;
390     my ($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/);
392     $reftype =~ s/^head$/branch/;
394     @notice = (format_table(
395         "Module: $repos_name",
396         ($reftype eq "tag" ? "Tag:" : "Branch:") . $refname,
397         @notice,
398         ($action ne "removed" and $gitweb_url)
399             ? "URL: $gitweb_url/?a=shortlog;h=$ref" : undef),
400         "",
401         "The $refname $reftype has been $action.");
403     mail_notification($commitlist_address, "$refname $reftype $action",
404         "text/plain; charset=us-ascii", @notice);
407 # send a commit notice to a mailing list
408 sub send_commit_notice($$)
410     my ($ref,$obj) = @_;
411     my %info = get_object_info($obj);
412     my @notice = ();
413     my ($url,$subject,$obj_string);
415     if ($gitweb_url)
416     {
417         if ($abbreviate_url)
418         {
419             open REVPARSE, "-|" or exec "git", "rev-parse", "--short", $obj or die "cannot exec git-rev-parse";
420             $obj_string = <REVPARSE>;
421             chomp $obj_string if defined $obj_string;
422             close REVPARSE or die $! ? "Cannot execute rev-parse: $!" : "rev-parse exited with status: $?";
423         }
424         $obj_string = $obj if not defined $obj_string;
425         $url = "$gitweb_url/?a=$info{type};h=$obj_string";
426     }
428     if ($info{"type"} eq "tag")
429     {
430         push @notice, format_table(
431           "Module: $repos_name",
432           "Branch: $ref",
433           "Tag: $obj",
434           "Tagger:" . $info{"tagger"},
435           "Date:" . format_date($info{"tagger_date"},$info{"tagger_tz"}),
436           $url ? "URL: $url" : undef),
437           "",
438           join "\n", @{$info{"log"}};
440         $subject = "Tag " . $info{"tag"} . ": " . $info{"tagger_name"};
441     }
442     else
443     {
444         push @notice, format_table(
445           "Module: $repos_name",
446           "Branch: $ref",
447           "Commit: $obj",
448           "Author:" . $info{"author"},
449           $show_committer && $info{"committer"} ne $info{"author"} ? "Committer:" . $info{"committer"} : undef,
450           "Date:" . format_date($info{"author_date"},$info{"author_tz"}),
451           $url ? "URL: $url" : undef),
452           "",
453           @{$info{"log"}},
454           "",
455           "---",
456           "";
458         open STAT, "-|" or exec "git", "diff-tree", "--stat", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
459         push @notice, join("", <STAT>);
460         close STAT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
462         open DIFF, "-|" or exec "git", "diff-tree", "-p", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
463         my $diff = join("", <DIFF>);
464         close DIFF or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
466         if (($max_diff_size == -1) || (length($diff) < $max_diff_size))
467         {
468             push @notice, $diff;
469         }
470         else
471         {
472             push @notice, "Diff: $gitweb_url/?a=commitdiff;h=$obj_string" if $gitweb_url;
473         }
474         $subject = $info{"author_name"};
475     }
477     $subject .= ": " . truncate_str(${$info{"log"}}[0],50);
478     $_ = decode($info{"encoding"}, $_) for @notice;
479     mail_notification($commitlist_address, $subject, "text/plain; charset=UTF-8", @notice);
482 # send a commit notice to the CIA server
483 sub send_cia_notice($$)
485     my ($ref,$commit) = @_;
486     my %info = get_object_info($commit);
487     my @cia_text = ();
489     return if $info{"type"} ne "commit";
491     push @cia_text,
492         "<message>",
493         "  <generator>",
494         "    <name>git-notify script for CIA</name>",
495         "  </generator>",
496         "  <source>",
497         "    <project>" . xml_escape($cia_project_name) . "</project>",
498         "    <module>" . xml_escape($repos_name) . "</module>",
499         "    <branch>" . xml_escape($ref). "</branch>",
500         "  </source>",
501         "  <body>",
502         "    <commit>",
503         "      <revision>" . substr($commit,0,10) . "</revision>",
504         "      <author>" . xml_escape($info{"author"}) . "</author>",
505         "      <log>" . xml_escape(join "\n", @{$info{"log"}}) . "</log>",
506         "      <files>";
508     open COMMIT, "-|" or exec "git", "diff-tree", "--name-status", "-r", "-M", $commit or die "cannot run git-diff-tree";
509     while (<COMMIT>)
510     {
511         chomp;
512         if (/^([AMD])\t(.*)$/)
513         {
514             my ($action, $file) = ($1, $2);
515             my %actions = ( "A" => "add", "M" => "modify", "D" => "remove" );
516             next unless defined $actions{$action};
517             push @cia_text, "        <file action=\"$actions{$action}\">" . xml_escape($file) . "</file>";
518         }
519         elsif (/^R\d+\t(.*)\t(.*)$/)
520         {
521             my ($old, $new) = ($1, $2);
522             push @cia_text, "        <file action=\"rename\" to=\"" . xml_escape($new) . "\">" . xml_escape($old) . "</file>";
523         }
524     }
525     close COMMIT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
527     push @cia_text,
528         "      </files>",
529         $gitweb_url ? "      <url>" . xml_escape("$gitweb_url/?a=commit;h=$commit") . "</url>" : "",
530         "    </commit>",
531         "  </body>",
532         "  <timestamp>" . $info{"author_date"} . "</timestamp>",
533         "</message>";
535     mail_notification($cia_address, "DeliverXML", "text/xml", @cia_text);
538 # send a global commit notice when there are too many commits for individual mails
539 sub send_global_notice($$$)
541     my ($ref, $old_sha1, $new_sha1) = @_;
542     my $notice = git_rev_list("--pretty", "^$old_sha1", "$new_sha1", @exclude_list);
544     foreach my $rev (@$notice)
545     {
546         $rev =~ s/^commit /URL:    $gitweb_url\/?a=commit;h=/ if $gitweb_url;
547     }
549     mail_notification($commitlist_address, "New commits on branch $ref", "text/plain; charset=UTF-8", @$notice);
552 # send all the notices
553 sub send_all_notices($$$)
555     my ($old_sha1, $new_sha1, $ref) = @_;
556     my ($reftype, $refname, $action, @notice);
558     return if ($ref =~ /^refs\/remotes\//
559         or (@include_list && !grep {$_ eq $ref} @include_list));
560     die "The name \"$ref\" doesn't sound like a local branch or tag"
561         if not (($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/));
563     if ($new_sha1 eq '0' x 40)
564     {
565         $action = "removed";
566         @notice = ( "Old SHA1: $old_sha1" );
567     }
568     elsif ($old_sha1 eq '0' x 40)
569     {
570         $action = "created";
571         @notice = ( "SHA1: $new_sha1" );
572     }
573     elsif ($reftype eq "tag")
574     {
575         $action = "updated";
576         @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
577     }
578     elsif (not grep( $_ eq $old_sha1, @{ git_rev_list( $new_sha1, "--full-history" ) } ))
579     {
580         $action = "rewritten";
581         @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
582     }
584     send_ref_notice( $ref, $action, @notice ) if ($commitlist_address and $action);
586     unless ($reftype eq "tag" or $new_sha1 eq '0' x 40)
587     {
588         my $commits = get_new_commits ( $old_sha1, $new_sha1 );
590         if (@$commits > $max_individual_notices)
591         {
592             send_global_notice( $refname, $old_sha1, $new_sha1 ) if $commitlist_address;
593         }
594         elsif (@$commits > 0)
595         {
596             foreach my $commit (@$commits)
597             {
598                 send_commit_notice( $refname, $commit ) if $commitlist_address;
599                 send_cia_notice( $refname, $commit ) if $cia_project_name;
600             }
601         }
602         elsif ($commitlist_address)
603         {
604             @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
605             send_ref_notice( $ref, "modified", @notice );
606         }
607     }
610 parse_options();
612 umask( $mode_mask );
614 # append repository path to URL
615 $gitweb_url .= "/$repos_name.git" if $gitweb_url;
617 if (@ARGV)
619     send_all_notices( $ARGV[0], $ARGV[1], $ARGV[2] );
621 else  # read them from stdin
623     while (<>)
624     {
625         chomp;
626         if (/^([0-9a-f]{40}) ([0-9a-f]{40}) (.*)$/) { send_all_notices( $1, $2, $3 ); }
627     }
630 exit 0;