Code

d53461c8af7f8c08ee83f3d9859253520d4784f9
[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 name   Send CIA notifications under specified project name
19 #   -m addr   Send mail notifications to specified address
20 #   -n max    Set max number of individual mails to send
21 #   -r name   Set the git repository name
22 #   -s bytes  Set the maximum diff size in bytes (-1 for no limit)
23 #   -t file   Set the file to use for reading and saving state
24 #   -U mask   Set the umask for creating the state file
25 #   -u url    Set the URL to the gitweb browser
26 #   -i branch If at least one -i is given, report only for specified branches
27 #   -x branch Exclude changes to the specified branch from reports
28 #   -X        Exclude merge commits
29 #
31 use strict;
32 use Fcntl ':flock';
33 use Encode qw(encode decode);
34 use Cwd 'realpath';
36 sub git_config($);
37 sub get_repos_name();
39 # some parameters you may want to change
41 # set this to something that takes "-s"
42 my $mailer = "/usr/bin/mail";
44 # CIA notification address
45 my $cia_address = "cia\@cia.navi.cx";
47 # debug mode
48 my $debug = 0;
50 # number of generated (non-CIA) notifications
51 my $sent_notices = 0;
53 # configuration parameters
55 # base URL of the gitweb repository browser (can be set with the -u option)
56 my $gitweb_url = git_config( "notify.baseurl" );
58 # default repository name (can be changed with the -r option)
59 my $repos_name = git_config( "notify.repository" ) || get_repos_name();
61 # max size of diffs in bytes (can be changed with the -s option)
62 my $max_diff_size = git_config( "notify.maxdiff" ) || 10000;
64 # address for mail notices (can be set with -m option)
65 my $commitlist_address = git_config( "notify.mail" );
67 # project name for CIA notices (can be set with -c option)
68 my $cia_project_name = git_config( "notify.cia" );
70 # max number of individual notices before falling back to a single global notice (can be set with -n option)
71 my $max_individual_notices = git_config( "notify.maxnotices" ) || 100;
73 # branches to include
74 my @include_list = split /\s+/, git_config( "notify.include" ) || "";
76 # branches to exclude
77 my @exclude_list = split /\s+/, git_config( "notify.exclude" ) || "";
79 # the state file we use (can be changed with the -t option)
80 my $state_file = git_config( "notify.statefile" ) || "/var/tmp/git-notify.state";
82 # umask for creating the state file (can be set with -U option)
83 my $mode_mask = git_config( "notify.umask" ) || 002;
85 # Extra options to git rev-list
86 my @revlist_options;
88 sub usage()
89 {
90     print "Usage: $0 [options] [--] old-sha1 new-sha1 refname\n";
91     print "   -c name   Send CIA notifications under specified project name\n";
92     print "   -m addr   Send mail notifications to specified address\n";
93     print "   -n max    Set max number of individual mails to send\n";
94     print "   -r name   Set the git repository name\n";
95     print "   -s bytes  Set the maximum diff size in bytes (-1 for no limit)\n";
96     print "   -t file   Set the file to use for reading and saving state\n";
97     print "   -U mask   Set the umask for creating the state file\n";
98     print "   -u url    Set the URL to the gitweb browser\n";
99     print "   -i branch If at least one -i is given, report only for specified branches\n";
100     print "   -x branch Exclude changes to the specified branch from reports\n";
101     print "   -X        Exclude merge commits\n";
102     exit 1;
105 sub xml_escape($)
107     my $str = shift;
108     $str =~ s/&/&/g;
109     $str =~ s/</&lt;/g;
110     $str =~ s/>/&gt;/g;
111     my @chars = unpack "U*", $str;
112     $str = join "", map { ($_ > 127) ? sprintf "&#%u;", $_ : chr($_); } @chars;
113     return $str;
116 # execute git-rev-list(1) with the given parameters and return the output
117 sub git_rev_list(@)
119     my @args = @_;
120     my $revlist = [];
121     my $pid = open REVLIST, "-|";
123     die "Cannot open pipe: $!" if not defined $pid;
124     if (!$pid)
125     {
126         exec "git", "rev-list", @revlist_options, @args or die "Cannot execute rev-list: $!";
127     }
128     while (<REVLIST>)
129     {
130         chomp;
131         die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
132         push @$revlist, $_;
133     }
134     close REVLIST or die $! ? "Cannot execute rev-list: $!" : "rev-list exited with status: $?";
135     return $revlist;
138 # append the given commit hashes to the state file
139 sub save_commits($)
141     my $commits = shift;
143     open STATE, ">>", $state_file or die "Cannot open $state_file: $!";
144     flock STATE, LOCK_EX or die "Cannot lock $state_file";
145     print STATE "$_\n" for @$commits;
146     flock STATE, LOCK_UN or die "Cannot unlock $state_file";
147     close STATE or die "Cannot close $state_file: $!";
150 # for the given range, return the new hashes and append them to the state file
151 sub get_new_commits($$)
153     my ($old_sha1, $new_sha1) = @_;
154     my ($seen, @args);
155     my $newrevs = [];
157     @args = ( "^$old_sha1" ) unless $old_sha1 eq '0' x 40;
158     push @args, $new_sha1, @exclude_list;
160     my $revlist = git_rev_list(@args);
162     if (not -e $state_file)  # initialize the state file with all hashes
163     {
164         save_commits(git_rev_list("--all", "--full-history"));
165         return $revlist;
166     }
168     open STATE, $state_file or die "Cannot open $state_file: $!";
169     flock STATE, LOCK_SH or die "Cannot lock $state_file";
170     while (<STATE>)
171     {
172         chomp;
173         die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
174         $seen->{$_} = 1;
175     }
176     flock STATE, LOCK_UN or die "Cannot unlock $state_file";
177     close STATE or die "Cannot close $state_file: $!";
179     # FIXME: if another git-notify process reads the $state_file at *this*
180     # point, that process might generate duplicates of our notifications.
182     save_commits($revlist);
184     foreach my $commit (@$revlist)
185     {
186         push @$newrevs, $commit unless $seen->{$commit};
187     }
188     return $newrevs;
191 # truncate the given string if it exceeds the specified number of characters
192 sub truncate_str($$)
194     my ($str, $max) = @_;
196     if (length($str) > $max)
197     {
198         $str = substr($str, 0, $max);
199         $str =~ s/\s+\S+$//;
200         $str .= " ...";
201     }
202     return $str;
205 # right-justify the left column of "left: right" elements, omit undefined elements
206 sub format_table(@)
208     my @lines = @_;
209     my @table;
210     my $max = 0;
212     foreach my $line (@lines)
213     {
214        next if not defined $line;
215        my $pos = index($line, ":");
217        $max = $pos if $pos > $max;
218     }
220     foreach my $line (@lines)
221     {
222        next if not defined $line;
223        my ($left, $right) = split(/: */, $line, 2);
225        push @table, (defined $left and defined $right)
226            ? sprintf("%*s: %s", $max + 1, $left, $right)
227            : $line;
228     }
229     return @table;
232 # format an integer date + timezone as string
233 # algorithm taken from git's date.c
234 sub format_date($$)
236     my ($time,$tz) = @_;
238     if ($tz < 0)
239     {
240         my $minutes = (-$tz / 100) * 60 + (-$tz % 100);
241         $time -= $minutes * 60;
242     }
243     else
244     {
245         my $minutes = ($tz / 100) * 60 + ($tz % 100);
246         $time += $minutes * 60;
247     }
248     return gmtime($time) . sprintf " %+05d", $tz;
251 # fetch a parameter from the git config file
252 sub git_config($)
254     my ($param) = @_;
256     open CONFIG, "-|" or exec "git", "config", $param;
257     my $ret = <CONFIG>;
258     chomp $ret if $ret;
259     close CONFIG or $ret = undef;
260     return $ret;
263 # parse command line options
264 sub parse_options()
266     while (@ARGV && $ARGV[0] =~ /^-/)
267     {
268         my $arg = shift @ARGV;
270         if ($arg eq '--') { last; }
271         elsif ($arg eq '-c') { $cia_project_name = shift @ARGV; }
272         elsif ($arg eq '-m') { $commitlist_address = shift @ARGV; }
273         elsif ($arg eq '-n') { $max_individual_notices = shift @ARGV; }
274         elsif ($arg eq '-r') { $repos_name = shift @ARGV; }
275         elsif ($arg eq '-s') { $max_diff_size = shift @ARGV; }
276         elsif ($arg eq '-t') { $state_file = shift @ARGV; }
277         elsif ($arg eq '-U') { $mode_mask = shift @ARGV; }
278         elsif ($arg eq '-u') { $gitweb_url = shift @ARGV; }
279         elsif ($arg eq '-i') { push @include_list, shift @ARGV; }
280         elsif ($arg eq '-x') { push @exclude_list, shift @ARGV; }
281         elsif ($arg eq '-X') { push @revlist_options, "--no-merges"; }
282         elsif ($arg eq '-d') { $debug++; }
283         else { usage(); }
284     }
285     if (@ARGV && $#ARGV != 2) { usage(); }
286     @exclude_list = map { "^$_"; } @exclude_list;
289 # send an email notification
290 sub mail_notification($$$@)
292     my ($name, $subject, $content_type, @text) = @_;
293     $subject = encode("MIME-Q",$subject);
294     if ($debug)
295     {
296         binmode STDOUT, ":utf8";
297         print "---------------------\n";
298         print "To: $name\n";
299         print "Subject: $subject\n";
300         print "Content-Type: $content_type\n";
301         print "\n", join("\n", @text), "\n";
302     }
303     else
304     {
305         my $pid = open MAIL, "|-";
306         return unless defined $pid;
307         if (!$pid)
308         {
309             exec $mailer, "-s", $subject, "-a", "Content-Type: $content_type", $name or die "Cannot exec $mailer";
310         }
311         binmode MAIL, ":utf8";
312         print MAIL join("\n", @text), "\n";
313         close MAIL or die $! ? "Cannot execute $mailer: $!" : "$mailer exited with status: $?";
314     }
317 # get the default repository name
318 sub get_repos_name()
320     my $dir = `git rev-parse --git-dir`;
321     chomp $dir;
322     my $repos = realpath($dir);
323     $repos =~ s/(.*?)((\.git\/)?\.git)$/$1/;
324     $repos =~ s/(.*)\/([^\/]+)\/?$/$2/;
325     return $repos;
328 # extract the information from a commit or tag object and return a hash containing the various fields
329 sub get_object_info($)
331     my $obj = shift;
332     my %info = ();
333     my @log = ();
334     my $do_log = 0;
336     $info{"encoding"} = "utf-8";
338     open TYPE, "-|" or exec "git", "cat-file", "-t", $obj or die "cannot run git-cat-file";
339     my $type = <TYPE>;
340     chomp $type;
341     close TYPE or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
343     open OBJ, "-|" or exec "git", "cat-file", $type, $obj or die "cannot run git-cat-file";
344     while (<OBJ>)
345     {
346         chomp;
347         if ($do_log)
348         {
349             last if /^-----BEGIN PGP SIGNATURE-----/;
350             push @log, $_;
351         }
352         elsif (/^(author|committer|tagger) ((.*) (<.*>)) (\d+) ([+-]\d+)$/)
353         {
354             $info{$1} = $2;
355             $info{$1 . "_name"} = $3;
356             $info{$1 . "_email"} = $4;
357             $info{$1 . "_date"} = $5;
358             $info{$1 . "_tz"} = $6;
359         }
360         elsif (/^tag (.+)/)
361         {
362             $info{"tag"} = $1;
363         }
364         elsif (/^encoding (.+)/)
365         {
366             $info{"encoding"} = $1;
367         }
368         elsif (/^$/) { $do_log = 1; }
369     }
370     close OBJ or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
372     $info{"type"} = $type;
373     $info{"log"} = \@log;
374     return %info;
377 # send a ref change notice to a mailing list
378 sub send_ref_notice($$@)
380     my ($ref, $action, @notice) = @_;
381     my ($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/);
383     $reftype =~ s/^head$/branch/;
385     @notice = (format_table(
386         "Module: $repos_name",
387         ($reftype eq "tag" ? "Tag:" : "Branch:") . $refname,
388         @notice,
389         ($action ne "removed" and $gitweb_url)
390             ? "URL: $gitweb_url/?a=shortlog;h=$ref" : undef),
391         "",
392         "The $refname $reftype has been $action.");
394     mail_notification($commitlist_address, "$refname $reftype $action",
395         "text/plain; charset=us-ascii", @notice);
396     $sent_notices++;
399 # send a commit notice to a mailing list
400 sub send_commit_notice($$)
402     my ($ref,$obj) = @_;
403     my %info = get_object_info($obj);
404     my @notice = ();
405     my ($url,$subject);
407     if ($gitweb_url)
408     {
409         open REVPARSE, "-|" or exec "git", "rev-parse", "--short", $obj or die "cannot exec git-rev-parse";
410         my $short_obj = <REVPARSE>;
411         close REVPARSE or die $! ? "Cannot execute rev-parse: $!" : "rev-parse exited with status: $?";
413         $short_obj = $obj if not defined $short_obj;
414         chomp $short_obj;
415         $url = "$gitweb_url/?a=$info{type};h=$short_obj";
416     }
418     if ($info{"type"} eq "tag")
419     {
420         push @notice, format_table(
421           "Module: $repos_name",
422           "Branch: $ref",
423           "Tag: $obj",
424           "Tagger:" . $info{"tagger"},
425           "Date:" . format_date($info{"tagger_date"},$info{"tagger_tz"}),
426           $url ? "URL: $url" : undef),
427           "",
428           join "\n", @{$info{"log"}};
430         $subject = "Tag " . $info{"tag"} . ": " . $info{"tagger_name"};
431     }
432     else
433     {
434         push @notice, format_table(
435           "Module: $repos_name",
436           "Branch: $ref",
437           "Commit: $obj",
438           "Author:" . $info{"author"},
439           $info{"committer"} ne $info{"author"} ? "Committer:" . $info{"committer"} : undef,
440           "Date:" . format_date($info{"author_date"},$info{"author_tz"}),
441           $url ? "URL: $url" : undef),
442           "",
443           @{$info{"log"}},
444           "",
445           "---",
446           "";
448         open STAT, "-|" or exec "git", "diff-tree", "--stat", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
449         push @notice, join("", <STAT>);
450         close STAT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
452         open DIFF, "-|" or exec "git", "diff-tree", "-p", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
453         my $diff = join("", <DIFF>);
454         close DIFF or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
456         if (($max_diff_size == -1) || (length($diff) < $max_diff_size))
457         {
458             push @notice, $diff;
459         }
460         else
461         {
462             push @notice, "Diff:   $gitweb_url/?a=commitdiff;h=$obj" if $gitweb_url;
463         }
464         $subject = $info{"author_name"};
465     }
467     $subject .= ": " . truncate_str(${$info{"log"}}[0],50);
468     $_ = decode($info{"encoding"}, $_) for @notice;
469     mail_notification($commitlist_address, $subject, "text/plain; charset=UTF-8", @notice);
470     $sent_notices++;
473 # send a commit notice to the CIA server
474 sub send_cia_notice($$)
476     my ($ref,$commit) = @_;
477     my %info = get_object_info($commit);
478     my @cia_text = ();
480     return if $info{"type"} ne "commit";
482     push @cia_text,
483         "<message>",
484         "  <generator>",
485         "    <name>git-notify script for CIA</name>",
486         "  </generator>",
487         "  <source>",
488         "    <project>" . xml_escape($cia_project_name) . "</project>",
489         "    <module>" . xml_escape($repos_name) . "</module>",
490         "    <branch>" . xml_escape($ref). "</branch>",
491         "  </source>",
492         "  <body>",
493         "    <commit>",
494         "      <revision>" . substr($commit,0,10) . "</revision>",
495         "      <author>" . xml_escape($info{"author"}) . "</author>",
496         "      <log>" . xml_escape(join "\n", @{$info{"log"}}) . "</log>",
497         "      <files>";
499     open COMMIT, "-|" or exec "git", "diff-tree", "--name-status", "-r", "-M", $commit or die "cannot run git-diff-tree";
500     while (<COMMIT>)
501     {
502         chomp;
503         if (/^([AMD])\t(.*)$/)
504         {
505             my ($action, $file) = ($1, $2);
506             my %actions = ( "A" => "add", "M" => "modify", "D" => "remove" );
507             next unless defined $actions{$action};
508             push @cia_text, "        <file action=\"$actions{$action}\">" . xml_escape($file) . "</file>";
509         }
510         elsif (/^R\d+\t(.*)\t(.*)$/)
511         {
512             my ($old, $new) = ($1, $2);
513             push @cia_text, "        <file action=\"rename\" to=\"" . xml_escape($new) . "\">" . xml_escape($old) . "</file>";
514         }
515     }
516     close COMMIT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
518     push @cia_text,
519         "      </files>",
520         $gitweb_url ? "      <url>" . xml_escape("$gitweb_url/?a=commit;h=$commit") . "</url>" : "",
521         "    </commit>",
522         "  </body>",
523         "  <timestamp>" . $info{"author_date"} . "</timestamp>",
524         "</message>";
526     mail_notification($cia_address, "DeliverXML", "text/xml", @cia_text);
529 # send a global commit notice when there are too many commits for individual mails
530 sub send_global_notice($$$)
532     my ($ref, $old_sha1, $new_sha1) = @_;
533     my $notice = git_rev_list("--pretty", "^$old_sha1", "$new_sha1", @exclude_list);
535     foreach my $rev (@$notice)
536     {
537         $rev =~ s/^commit /URL:    $gitweb_url\/?a=commit;h=/ if $gitweb_url;
538     }
540     mail_notification($commitlist_address, "New commits on branch $ref", "text/plain; charset=UTF-8", @$notice);
541     $sent_notices++;
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         else
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         if ($sent_notices == 0 and $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;