Code

git-notify: Optionally [tag] the subject
[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        Prefix the mail subject with a [repository name] tag
26 #   -t file   Prevent duplicate notifications by saving state to this file
27 #   -U mask   Set the umask for creating the state file
28 #   -u url    Set the URL to the gitweb browser
29 #   -i branch If at least one -i is given, report only for specified branches
30 #   -x branch Exclude changes to the specified branch from reports
31 #   -X        Exclude merge commits
32 #   -z        Try to abbreviate the SHA1 name within gitweb URLs (unsafe)
33 #
35 use strict;
36 use Fcntl ':flock';
37 use Encode qw(encode decode);
38 use Cwd 'realpath';
40 sub git_config($);
41 sub get_repos_name();
43 # some parameters you may want to change
45 # set this to something that takes "-s"
46 my $mailer = "/usr/bin/mail";
48 # CIA notification address
49 my $cia_address = "cia\@cia.navi.cx";
51 # debug mode
52 my $debug = 0;
54 # configuration parameters
56 # omit the author from the mail subject (can be set with the -A option)
57 my $omit_author = git_config( "notify.omitauthor" );
59 # prefix the mail subject with a [repository name] tag (can be set with the -T option)
60 my $emit_repo = git_config( "notify.emitrepository" );
62 # show the committer if different from the author (can be set with the -C option)
63 my $show_committer = git_config( "notify.showcommitter" );
65 # base URL of the gitweb repository browser (can be set with the -u option)
66 my $gitweb_url = git_config( "notify.baseurl" );
68 # abbreviate the SHA1 name within gitweb URLs (can be set with the -z option)
69 my $abbreviate_url = git_config( "notify.shorturls" );
71 # default repository name (can be changed with the -r option)
72 my $repos_name = git_config( "notify.repository" ) || get_repos_name();
74 # max size of diffs in bytes (can be changed with the -s option)
75 my $max_diff_size = git_config( "notify.maxdiff" ) || 10000;
77 # address for mail notices (can be set with -m option)
78 my $commitlist_address = git_config( "notify.mail" );
80 # project name for CIA notices (can be set with -c option)
81 my $cia_project_name = git_config( "notify.cia" );
83 # max number of individual notices before falling back to a single global notice (can be set with -n option)
84 my $max_individual_notices = git_config( "notify.maxnotices" ) || 100;
86 # branches to include
87 my @include_list = split /\s+/, git_config( "notify.include" ) || "";
89 # branches to exclude
90 my @exclude_list = split /\s+/, git_config( "notify.exclude" ) || "";
92 # the state file we use (can be set with the -t option)
93 my $state_file = git_config( "notify.statefile" );
95 # umask for creating the state file (can be set with -U option)
96 my $mode_mask = git_config( "notify.umask" ) || 002;
98 # Extra options to git rev-list
99 my @revlist_options;
101 sub usage()
103     print "Usage: $0 [options] [--] old-sha1 new-sha1 refname\n";
104     print "   -A        Omit the author name from the mail subject\n";
105     print "   -C        Show committer in the body if different from the author\n";
106     print "   -c name   Send CIA notifications under specified project name\n";
107     print "   -m addr   Send mail notifications to specified address\n";
108     print "   -n max    Set max number of individual mails to send\n";
109     print "   -r name   Set the git repository name\n";
110     print "   -s bytes  Set the maximum diff size in bytes (-1 for no limit)\n";
111     print "   -T        Prefix the mail subject with a [repository name] tag\n";
112     print "   -t file   Prevent duplicate notifications by saving state to this file\n";
113     print "   -U mask   Set the umask for creating the state file\n";
114     print "   -u url    Set the URL to the gitweb browser\n";
115     print "   -i branch If at least one -i is given, report only for specified branches\n";
116     print "   -x branch Exclude changes to the specified branch from reports\n";
117     print "   -X        Exclude merge commits\n";
118     print "   -z        Try to abbreviate the SHA1 name within gitweb URLs (unsafe)\n";
119     exit 1;
122 sub xml_escape($)
124     my $str = shift;
125     $str =~ s/&/&/g;
126     $str =~ s/</&lt;/g;
127     $str =~ s/>/&gt;/g;
128     my @chars = unpack "U*", $str;
129     $str = join "", map { ($_ > 127) ? sprintf "&#%u;", $_ : chr($_); } @chars;
130     return $str;
133 # execute git-rev-list(1) with the given parameters and return the output
134 sub git_rev_list(@)
136     my @args = @_;
137     my $revlist = [];
138     my $pid = open REVLIST, "-|";
140     die "Cannot open pipe: $!" if not defined $pid;
141     if (!$pid)
142     {
143         exec "git", "rev-list", @revlist_options, @args or die "Cannot execute rev-list: $!";
144     }
145     while (<REVLIST>)
146     {
147         chomp;
148         die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
149         push @$revlist, $_;
150     }
151     close REVLIST or die $! ? "Cannot execute rev-list: $!" : "rev-list exited with status: $?";
152     return $revlist;
155 # append the given commit hashes to the state file
156 sub save_commits($)
158     my $commits = shift;
160     open STATE, ">>", $state_file or die "Cannot open $state_file: $!";
161     flock STATE, LOCK_EX or die "Cannot lock $state_file";
162     print STATE "$_\n" for @$commits;
163     flock STATE, LOCK_UN or die "Cannot unlock $state_file";
164     close STATE or die "Cannot close $state_file: $!";
167 # for the given range, return the new hashes (and append them to the state file)
168 sub get_new_commits($$)
170     my ($old_sha1, $new_sha1) = @_;
171     my ($seen, @args);
172     my $newrevs = [];
174     @args = ( "^$old_sha1" ) unless $old_sha1 eq '0' x 40;
175     push @args, $new_sha1, @exclude_list;
177     my $revlist = git_rev_list(@args);
179     if (not defined $state_file or not -e $state_file)
180     {
181         save_commits(git_rev_list("--all", "--full-history")) if defined $state_file;
182         return $revlist;
183     }
185     open STATE, $state_file or die "Cannot open $state_file: $!";
186     flock STATE, LOCK_SH or die "Cannot lock $state_file";
187     while (<STATE>)
188     {
189         chomp;
190         die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
191         $seen->{$_} = 1;
192     }
193     flock STATE, LOCK_UN or die "Cannot unlock $state_file";
194     close STATE or die "Cannot close $state_file: $!";
196     # FIXME: if another git-notify process reads the $state_file at *this*
197     # point, that process might generate duplicates of our notifications.
199     save_commits($revlist);
201     foreach my $commit (@$revlist)
202     {
203         push @$newrevs, $commit unless $seen->{$commit};
204     }
205     return $newrevs;
208 # truncate the given string if it exceeds the specified number of characters
209 sub truncate_str($$)
211     my ($str, $max) = @_;
213     if (length($str) > $max)
214     {
215         $str = substr($str, 0, $max);
216         $str =~ s/\s+\S+$//;
217         $str .= " ...";
218     }
219     return $str;
222 # right-justify the left column of "left: right" elements, omit undefined elements
223 sub format_table(@)
225     my @lines = @_;
226     my @table;
227     my $max = 0;
229     foreach my $line (@lines)
230     {
231        next if not defined $line;
232        my $pos = index($line, ":");
234        $max = $pos if $pos > $max;
235     }
237     foreach my $line (@lines)
238     {
239        next if not defined $line;
240        my ($left, $right) = split(/: */, $line, 2);
242        push @table, (defined $left and defined $right)
243            ? sprintf("%*s: %s", $max + 1, $left, $right)
244            : $line;
245     }
246     return @table;
249 # format an integer date + timezone as string
250 # algorithm taken from git's date.c
251 sub format_date($$)
253     my ($time,$tz) = @_;
255     if ($tz < 0)
256     {
257         my $minutes = (-$tz / 100) * 60 + (-$tz % 100);
258         $time -= $minutes * 60;
259     }
260     else
261     {
262         my $minutes = ($tz / 100) * 60 + ($tz % 100);
263         $time += $minutes * 60;
264     }
265     return gmtime($time) . sprintf " %+05d", $tz;
268 # fetch a parameter from the git config file
269 sub git_config($)
271     my ($param) = @_;
273     open CONFIG, "-|" or exec "git", "config", $param;
274     my $ret = <CONFIG>;
275     chomp $ret if $ret;
276     close CONFIG or $ret = undef;
277     return $ret;
280 # parse command line options
281 sub parse_options()
283     while (@ARGV && $ARGV[0] =~ /^-/)
284     {
285         my $arg = shift @ARGV;
287         if ($arg eq '--') { last; }
288         elsif ($arg eq '-A') { $omit_author = 1; }
289         elsif ($arg eq '-C') { $show_committer = 1; }
290         elsif ($arg eq '-c') { $cia_project_name = shift @ARGV; }
291         elsif ($arg eq '-m') { $commitlist_address = shift @ARGV; }
292         elsif ($arg eq '-n') { $max_individual_notices = shift @ARGV; }
293         elsif ($arg eq '-r') { $repos_name = shift @ARGV; }
294         elsif ($arg eq '-s') { $max_diff_size = shift @ARGV; }
295         elsif ($arg eq '-T') { $emit_repo = 1; }
296         elsif ($arg eq '-t') { $state_file = shift @ARGV; }
297         elsif ($arg eq '-U') { $mode_mask = shift @ARGV; }
298         elsif ($arg eq '-u') { $gitweb_url = shift @ARGV; }
299         elsif ($arg eq '-i') { push @include_list, shift @ARGV; }
300         elsif ($arg eq '-x') { push @exclude_list, shift @ARGV; }
301         elsif ($arg eq '-X') { push @revlist_options, "--no-merges"; }
302         elsif ($arg eq '-z') { $abbreviate_url = 1; }
303         elsif ($arg eq '-d') { $debug++; }
304         else { usage(); }
305     }
306     if (@ARGV && $#ARGV != 2) { usage(); }
307     @exclude_list = map { "^$_"; } @exclude_list;
310 # send an email notification
311 sub mail_notification($$$@)
313     my ($name, $subject, $content_type, @text) = @_;
315     $subject = "[$repos_name] $subject" if $emit_repo;
316     $subject = encode("MIME-Q",$subject);
318     if ($debug)
319     {
320         binmode STDOUT, ":utf8";
321         print "---------------------\n";
322         print "To: $name\n";
323         print "Subject: $subject\n";
324         print "Content-Type: $content_type\n";
325         print "\n", join("\n", @text), "\n";
326     }
327     else
328     {
329         my $pid = open MAIL, "|-";
330         return unless defined $pid;
331         if (!$pid)
332         {
333             exec $mailer, "-s", $subject, "-a", "Content-Type: $content_type", $name or die "Cannot exec $mailer";
334         }
335         binmode MAIL, ":utf8";
336         print MAIL join("\n", @text), "\n";
337         close MAIL or warn $! ? "Cannot execute $mailer: $!" : "$mailer exited with status: $?";
338     }
341 # get the default repository name
342 sub get_repos_name()
344     my $dir = `git rev-parse --git-dir`;
345     chomp $dir;
346     my $repos = realpath($dir);
347     $repos =~ s/(.*?)((\.git\/)?\.git)$/$1/;
348     $repos =~ s/(.*)\/([^\/]+)\/?$/$2/;
349     return $repos;
352 # extract the information from a commit or tag object and return a hash containing the various fields
353 sub get_object_info($)
355     my $obj = shift;
356     my %info = ();
357     my @log = ();
358     my $do_log = 0;
360     $info{"encoding"} = "utf-8";
362     open TYPE, "-|" or exec "git", "cat-file", "-t", $obj or die "cannot run git-cat-file";
363     my $type = <TYPE>;
364     chomp $type;
365     close TYPE or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
367     open OBJ, "-|" or exec "git", "cat-file", $type, $obj or die "cannot run git-cat-file";
368     while (<OBJ>)
369     {
370         chomp;
371         if ($do_log)
372         {
373             last if /^-----BEGIN PGP SIGNATURE-----/;
374             push @log, $_;
375         }
376         elsif (/^(author|committer|tagger) ((.*) (<.*>)) (\d+) ([+-]\d+)$/)
377         {
378             $info{$1} = $2;
379             $info{$1 . "_name"} = $3;
380             $info{$1 . "_email"} = $4;
381             $info{$1 . "_date"} = $5;
382             $info{$1 . "_tz"} = $6;
383         }
384         elsif (/^tag (.+)/)
385         {
386             $info{"tag"} = $1;
387         }
388         elsif (/^encoding (.+)/)
389         {
390             $info{"encoding"} = $1;
391         }
392         elsif (/^$/) { $do_log = 1; }
393     }
394     close OBJ or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
396     $info{"type"} = $type;
397     $info{"log"} = \@log;
398     return %info;
401 # send a ref change notice to a mailing list
402 sub send_ref_notice($$@)
404     my ($ref, $action, @notice) = @_;
405     my ($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/);
407     $reftype =~ s/^head$/branch/;
409     @notice = (format_table(
410         "Module: $repos_name",
411         ($reftype eq "tag" ? "Tag:" : "Branch:") . $refname,
412         @notice,
413         ($action ne "removed" and $gitweb_url)
414             ? "URL: $gitweb_url/?a=shortlog;h=$ref" : undef),
415         "",
416         "The $refname $reftype has been $action.");
418     mail_notification($commitlist_address, "$refname $reftype $action",
419         "text/plain; charset=us-ascii", @notice);
422 # send a commit notice to a mailing list
423 sub send_commit_notice($$)
425     my ($ref,$obj) = @_;
426     my %info = get_object_info($obj);
427     my @notice = ();
428     my ($url,$subject,$obj_string);
430     if ($gitweb_url)
431     {
432         if ($abbreviate_url)
433         {
434             open REVPARSE, "-|" or exec "git", "rev-parse", "--short", $obj or die "cannot exec git-rev-parse";
435             $obj_string = <REVPARSE>;
436             chomp $obj_string if defined $obj_string;
437             close REVPARSE or die $! ? "Cannot execute rev-parse: $!" : "rev-parse exited with status: $?";
438         }
439         $obj_string = $obj if not defined $obj_string;
440         $url = "$gitweb_url/?a=$info{type};h=$obj_string";
441     }
443     if ($info{"type"} eq "tag")
444     {
445         push @notice, format_table(
446           "Module: $repos_name",
447           "Branch: $ref",
448           "Tag: $obj",
449           "Tagger:" . $info{"tagger"},
450           "Date:" . format_date($info{"tagger_date"},$info{"tagger_tz"}),
451           $url ? "URL: $url" : undef),
452           "",
453           join "\n", @{$info{"log"}};
455         $subject = "Tag " . $info{"tag"} . ": ";
456         $subject .= $info{"tagger_name"} . ": " unless $omit_author;
457     }
458     else
459     {
460         push @notice, format_table(
461           "Module: $repos_name",
462           "Branch: $ref",
463           "Commit: $obj",
464           "Author:" . $info{"author"},
465           $show_committer && $info{"committer"} ne $info{"author"} ? "Committer:" . $info{"committer"} : undef,
466           "Date:" . format_date($info{"author_date"},$info{"author_tz"}),
467           $url ? "URL: $url" : undef),
468           "",
469           @{$info{"log"}},
470           "",
471           "---",
472           "";
474         open STAT, "-|" or exec "git", "diff-tree", "--stat", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
475         push @notice, join("", <STAT>);
476         close STAT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
478         open DIFF, "-|" or exec "git", "diff-tree", "-p", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
479         my $diff = join("", <DIFF>);
480         close DIFF or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
482         if (($max_diff_size == -1) || (length($diff) < $max_diff_size))
483         {
484             push @notice, $diff;
485         }
486         else
487         {
488             push @notice, "Diff: $gitweb_url/?a=commitdiff;h=$obj_string" if $gitweb_url;
489         }
490         $subject = $info{"author_name"} . ": " unless $omit_author;
491     }
493     $subject .= truncate_str(${$info{"log"}}[0],50);
494     $_ = decode($info{"encoding"}, $_) for @notice;
495     mail_notification($commitlist_address, $subject, "text/plain; charset=UTF-8", @notice);
498 # send a commit notice to the CIA server
499 sub send_cia_notice($$)
501     my ($ref,$commit) = @_;
502     my %info = get_object_info($commit);
503     my @cia_text = ();
505     return if $info{"type"} ne "commit";
507     push @cia_text,
508         "<message>",
509         "  <generator>",
510         "    <name>git-notify script for CIA</name>",
511         "  </generator>",
512         "  <source>",
513         "    <project>" . xml_escape($cia_project_name) . "</project>",
514         "    <module>" . xml_escape($repos_name) . "</module>",
515         "    <branch>" . xml_escape($ref). "</branch>",
516         "  </source>",
517         "  <body>",
518         "    <commit>",
519         "      <revision>" . substr($commit,0,10) . "</revision>",
520         "      <author>" . xml_escape($info{"author"}) . "</author>",
521         "      <log>" . xml_escape(join "\n", @{$info{"log"}}) . "</log>",
522         "      <files>";
524     open COMMIT, "-|" or exec "git", "diff-tree", "--name-status", "-r", "-M", $commit or die "cannot run git-diff-tree";
525     while (<COMMIT>)
526     {
527         chomp;
528         if (/^([AMD])\t(.*)$/)
529         {
530             my ($action, $file) = ($1, $2);
531             my %actions = ( "A" => "add", "M" => "modify", "D" => "remove" );
532             next unless defined $actions{$action};
533             push @cia_text, "        <file action=\"$actions{$action}\">" . xml_escape($file) . "</file>";
534         }
535         elsif (/^R\d+\t(.*)\t(.*)$/)
536         {
537             my ($old, $new) = ($1, $2);
538             push @cia_text, "        <file action=\"rename\" to=\"" . xml_escape($new) . "\">" . xml_escape($old) . "</file>";
539         }
540     }
541     close COMMIT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
543     push @cia_text,
544         "      </files>",
545         $gitweb_url ? "      <url>" . xml_escape("$gitweb_url/?a=commit;h=$commit") . "</url>" : "",
546         "    </commit>",
547         "  </body>",
548         "  <timestamp>" . $info{"author_date"} . "</timestamp>",
549         "</message>";
551     mail_notification($cia_address, "DeliverXML", "text/xml", @cia_text);
554 # send a global commit notice when there are too many commits for individual mails
555 sub send_global_notice($$$)
557     my ($ref, $old_sha1, $new_sha1) = @_;
558     my $notice = git_rev_list("--pretty", "^$old_sha1", "$new_sha1", @exclude_list);
560     foreach my $rev (@$notice)
561     {
562         $rev =~ s/^commit /URL:    $gitweb_url\/?a=commit;h=/ if $gitweb_url;
563     }
565     mail_notification($commitlist_address, "New commits on branch $ref", "text/plain; charset=UTF-8", @$notice);
568 # send all the notices
569 sub send_all_notices($$$)
571     my ($old_sha1, $new_sha1, $ref) = @_;
572     my ($reftype, $refname, $action, @notice);
574     return if ($ref =~ /^refs\/remotes\//
575         or (@include_list && !grep {$_ eq $ref} @include_list));
576     die "The name \"$ref\" doesn't sound like a local branch or tag"
577         if not (($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/));
579     if ($new_sha1 eq '0' x 40)
580     {
581         $action = "removed";
582         @notice = ( "Old SHA1: $old_sha1" );
583     }
584     elsif ($old_sha1 eq '0' x 40)
585     {
586         $action = "created";
587         @notice = ( "SHA1: $new_sha1" );
588     }
589     elsif ($reftype eq "tag")
590     {
591         $action = "updated";
592         @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
593     }
594     elsif (not grep( $_ eq $old_sha1, @{ git_rev_list( $new_sha1, "--full-history" ) } ))
595     {
596         $action = "rewritten";
597         @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
598     }
600     send_ref_notice( $ref, $action, @notice ) if ($commitlist_address and $action);
602     unless ($reftype eq "tag" or $new_sha1 eq '0' x 40)
603     {
604         my $commits = get_new_commits ( $old_sha1, $new_sha1 );
606         if (@$commits > $max_individual_notices)
607         {
608             send_global_notice( $refname, $old_sha1, $new_sha1 ) if $commitlist_address;
609         }
610         elsif (@$commits > 0)
611         {
612             foreach my $commit (@$commits)
613             {
614                 send_commit_notice( $refname, $commit ) if $commitlist_address;
615                 send_cia_notice( $refname, $commit ) if $cia_project_name;
616             }
617         }
618         elsif ($commitlist_address)
619         {
620             @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
621             send_ref_notice( $ref, "modified", @notice );
622         }
623     }
626 parse_options();
628 umask( $mode_mask );
630 # append repository path to URL
631 $gitweb_url .= "/$repos_name.git" if $gitweb_url;
633 if (@ARGV)
635     send_all_notices( $ARGV[0], $ARGV[1], $ARGV[2] );
637 else  # read them from stdin
639     while (<>)
640     {
641         chomp;
642         if (/^([0-9a-f]{40}) ([0-9a-f]{40}) (.*)$/) { send_all_notices( $1, $2, $3 ); }
643     }
646 exit 0;