Code

git-notify: Make the state file group writable
[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 url    Set the URL to the gitweb browser
25 #   -i branch If at least one -i is given, report only for specified branches
26 #   -x branch Exclude changes to the specified branch from reports
27 #   -X        Exclude merge commits
28 #
30 use strict;
31 use Fcntl ':flock';
32 use Encode qw(encode decode);
33 use Cwd 'realpath';
35 sub git_config($);
36 sub get_repos_name();
38 # some parameters you may want to change
40 # set this to something that takes "-s"
41 my $mailer = "/usr/bin/mail";
43 # CIA notification address
44 my $cia_address = "cia\@cia.navi.cx";
46 # debug mode
47 my $debug = 0;
49 # number of generated (non-CIA) notifications
50 my $sent_notices = 0;
52 # configuration parameters
54 # base URL of the gitweb repository browser (can be set with the -u option)
55 my $gitweb_url = git_config( "notify.baseurl" );
57 # default repository name (can be changed with the -r option)
58 my $repos_name = git_config( "notify.repository" ) || get_repos_name();
60 # max size of diffs in bytes (can be changed with the -s option)
61 my $max_diff_size = git_config( "notify.maxdiff" ) || 10000;
63 # address for mail notices (can be set with -m option)
64 my $commitlist_address = git_config( "notify.mail" );
66 # project name for CIA notices (can be set with -c option)
67 my $cia_project_name = git_config( "notify.cia" );
69 # max number of individual notices before falling back to a single global notice (can be set with -n option)
70 my $max_individual_notices = git_config( "notify.maxnotices" ) || 100;
72 # branches to include
73 my @include_list = split /\s+/, git_config( "notify.include" ) || "";
75 # branches to exclude
76 my @exclude_list = split /\s+/, git_config( "notify.exclude" ) || "";
78 # the state file we use (can be changed with the -t option)
79 my $state_file = git_config( "notify.statefile" ) || "/var/tmp/git-notify.state";
81 # umask for creating the state file (can be set with -U option)
82 my $mode_mask = git_config( "notify.umask" ) || 002;
84 # Extra options to git rev-list
85 my @revlist_options;
87 sub usage()
88 {
89     print "Usage: $0 [options] [--] old-sha1 new-sha1 refname\n";
90     print "   -c name   Send CIA notifications under specified project name\n";
91     print "   -m addr   Send mail notifications to specified address\n";
92     print "   -n max    Set max number of individual mails to send\n";
93     print "   -r name   Set the git repository name\n";
94     print "   -s bytes  Set the maximum diff size in bytes (-1 for no limit)\n";
95     print "   -t file   Set the file to use for reading and saving state\n";
96     print "   -u url    Set the URL to the gitweb browser\n";
97     print "   -U mask   Set the umask for creatung the state file\n";
98     print "   -i branch If at least one -i is given, report only for specified branches\n";
99     print "   -x branch Exclude changes to the specified branch from reports\n";
100     print "   -X        Exclude merge commits\n";
101     exit 1;
104 sub xml_escape($)
106     my $str = shift;
107     $str =~ s/&/&/g;
108     $str =~ s/</&lt;/g;
109     $str =~ s/>/&gt;/g;
110     my @chars = unpack "U*", $str;
111     $str = join "", map { ($_ > 127) ? sprintf "&#%u;", $_ : chr($_); } @chars;
112     return $str;
115 # execute git-rev-list(1) with the given parameters and return the output
116 sub git_rev_list(@)
118     my @args = @_;
119     my $revlist = [];
120     my $pid = open REVLIST, "-|";
122     die "Cannot open pipe: $!" if not defined $pid;
123     if (!$pid)
124     {
125         exec "git", "rev-list", @revlist_options, @args or die "Cannot execute rev-list: $!";
126     }
127     while (<REVLIST>)
128     {
129         chomp;
130         die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
131         push @$revlist, $_;
132     }
133     close REVLIST or die $! ? "Cannot execute rev-list: $!" : "rev-list exited with status: $?";
134     return $revlist;
137 # append the given commit hashes to the state file
138 sub save_commits($)
140     my $commits = shift;
142     open STATE, ">>", $state_file or die "Cannot open $state_file: $!";
143     flock STATE, LOCK_EX or die "Cannot lock $state_file";
144     print STATE "$_\n" for @$commits;
145     flock STATE, LOCK_UN or die "Cannot unlock $state_file";
146     close STATE or die "Cannot close $state_file: $!";
149 # for the given range, return the new hashes and append them to the state file
150 sub get_new_commits($$)
152     my ($old_sha1, $new_sha1) = @_;
153     my ($seen, @args);
154     my $newrevs = [];
156     @args = ( "^$old_sha1" ) unless $old_sha1 eq '0' x 40;
157     push @args, $new_sha1, @exclude_list;
159     my $revlist = git_rev_list(@args);
161     if (not -e $state_file)  # initialize the state file with all hashes
162     {
163         save_commits(git_rev_list("--all", "--full-history"));
164         return $revlist;
165     }
167     open STATE, $state_file or die "Cannot open $state_file: $!";
168     flock STATE, LOCK_SH or die "Cannot lock $state_file";
169     while (<STATE>)
170     {
171         chomp;
172         die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
173         $seen->{$_} = 1;
174     }
175     flock STATE, LOCK_UN or die "Cannot unlock $state_file";
176     close STATE or die "Cannot close $state_file: $!";
178     # FIXME: if another git-notify process reads the $state_file at *this*
179     # point, that process might generate duplicates of our notifications.
181     save_commits($revlist);
183     foreach my $commit (@$revlist)
184     {
185         push @$newrevs, $commit unless $seen->{$commit};
186     }
187     return $newrevs;
190 # truncate the given string if it exceeds the specified number of characters
191 sub truncate_str($$)
193     my ($str, $max) = @_;
195     if (length($str) > $max)
196     {
197         $str = substr($str, 0, $max);
198         $str =~ s/\s+\S+$//;
199         $str .= " ...";
200     }
201     return $str;
204 # right-justify the left column of "left: right" elements, omit undefined elements
205 sub format_table(@)
207     my @lines = @_;
208     my @table;
209     my $max = 0;
211     foreach my $line (@lines)
212     {
213        next if not defined $line;
214        my $pos = index($line, ":");
216        $max = $pos if $pos > $max;
217     }
219     foreach my $line (@lines)
220     {
221        next if not defined $line;
222        my ($left, $right) = split(/: */, $line, 2);
224        push @table, (defined $left and defined $right)
225            ? sprintf("%*s: %s", $max + 1, $left, $right)
226            : $line;
227     }
228     return @table;
231 # format an integer date + timezone as string
232 # algorithm taken from git's date.c
233 sub format_date($$)
235     my ($time,$tz) = @_;
237     if ($tz < 0)
238     {
239         my $minutes = (-$tz / 100) * 60 + (-$tz % 100);
240         $time -= $minutes * 60;
241     }
242     else
243     {
244         my $minutes = ($tz / 100) * 60 + ($tz % 100);
245         $time += $minutes * 60;
246     }
247     return gmtime($time) . sprintf " %+05d", $tz;
250 # fetch a parameter from the git config file
251 sub git_config($)
253     my ($param) = @_;
255     open CONFIG, "-|" or exec "git", "config", $param;
256     my $ret = <CONFIG>;
257     chomp $ret if $ret;
258     close CONFIG or $ret = undef;
259     return $ret;
262 # parse command line options
263 sub parse_options()
265     while (@ARGV && $ARGV[0] =~ /^-/)
266     {
267         my $arg = shift @ARGV;
269         if ($arg eq '--') { last; }
270         elsif ($arg eq '-c') { $cia_project_name = shift @ARGV; }
271         elsif ($arg eq '-m') { $commitlist_address = shift @ARGV; }
272         elsif ($arg eq '-n') { $max_individual_notices = shift @ARGV; }
273         elsif ($arg eq '-r') { $repos_name = shift @ARGV; }
274         elsif ($arg eq '-s') { $max_diff_size = shift @ARGV; }
275         elsif ($arg eq '-t') { $state_file = shift @ARGV; }
276         elsif ($arg eq '-u') { $gitweb_url = shift @ARGV; }
277         elsif ($arg eq '-U') { $mode_mask = shift @ARGV; }
278         elsif ($arg eq '-i') { push @include_list, shift @ARGV; }
279         elsif ($arg eq '-x') { push @exclude_list, shift @ARGV; }
280         elsif ($arg eq '-X') { push @revlist_options, "--no-merges"; }
281         elsif ($arg eq '-d') { $debug++; }
282         else { usage(); }
283     }
284     if (@ARGV && $#ARGV != 2) { usage(); }
285     @exclude_list = map { "^$_"; } @exclude_list;
288 # send an email notification
289 sub mail_notification($$$@)
291     my ($name, $subject, $content_type, @text) = @_;
292     $subject = encode("MIME-Q",$subject);
293     if ($debug)
294     {
295         binmode STDOUT, ":utf8";
296         print "---------------------\n";
297         print "To: $name\n";
298         print "Subject: $subject\n";
299         print "Content-Type: $content_type\n";
300         print "\n", join("\n", @text), "\n";
301     }
302     else
303     {
304         my $pid = open MAIL, "|-";
305         return unless defined $pid;
306         if (!$pid)
307         {
308             exec $mailer, "-s", $subject, "-a", "Content-Type: $content_type", $name or die "Cannot exec $mailer";
309         }
310         binmode MAIL, ":utf8";
311         print MAIL join("\n", @text), "\n";
312         close MAIL or die $! ? "Cannot execute $mailer: $!" : "$mailer exited with status: $?";
313     }
316 # get the default repository name
317 sub get_repos_name()
319     my $dir = `git rev-parse --git-dir`;
320     chomp $dir;
321     my $repos = realpath($dir);
322     $repos =~ s/(.*?)((\.git\/)?\.git)$/$1/;
323     $repos =~ s/(.*)\/([^\/]+)\/?$/$2/;
324     return $repos;
327 # extract the information from a commit object and return a hash containing the various fields
328 sub get_object_info($)
330     my $obj = shift;
331     my %info = ();
332     my @log = ();
333     my $do_log = 0;
335     $info{"encoding"} = "utf-8";
337     open OBJ, "-|" or exec "git", "cat-file", "commit", $obj or die "cannot run git-cat-file";
338     while (<OBJ>)
339     {
340         chomp;
341         if ($do_log) { push @log, $_; }
342         elsif (/^$/) { $do_log = 1; }
343         elsif (/^encoding (.+)/) { $info{"encoding"} = $1; }
344         elsif (/^(author|committer) ((.*) (<.*>)) (\d+) ([+-]\d+)$/)
345         {
346             $info{$1} = $2;
347             $info{$1 . "_name"} = $3;
348             $info{$1 . "_email"} = $4;
349             $info{$1 . "_date"} = $5;
350             $info{$1 . "_tz"} = $6;
351         }
352     }
353     close OBJ or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
355     $info{"log"} = \@log;
356     return %info;
359 # send a ref change notice to a mailing list
360 sub send_ref_notice($$@)
362     my ($ref, $action, @notice) = @_;
363     my ($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/);
365     $reftype =~ s/^head$/branch/;
367     @notice = (format_table(
368         "Module: $repos_name",
369         ($reftype eq "tag" ? "Tag:" : "Branch:") . $refname,
370         @notice,
371         ($action ne "removed" and $gitweb_url)
372             ? "URL: $gitweb_url/?a=shortlog;h=$ref" : undef),
373         "",
374         "The $refname $reftype has been $action.");
376     mail_notification($commitlist_address, "$refname $reftype $action",
377         "text/plain; charset=us-ascii", @notice);
378     $sent_notices++;
381 # send a commit notice to a mailing list
382 sub send_commit_notice($$)
384     my ($ref,$obj) = @_;
385     my %info = get_object_info($obj);
386     my @notice = ();
387     my $url;
389     open DIFF, "-|" or exec "git", "diff-tree", "-p", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
390     my $diff = join("", <DIFF>);
391     close DIFF or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
393     return if length($diff) == 0;
395     if ($gitweb_url)
396     {
397         open REVPARSE, "-|" or exec "git", "rev-parse", "--short", $obj or die "cannot exec git-rev-parse";
398         my $short_obj = <REVPARSE>;
399         close REVPARSE or die $! ? "Cannot execute rev-parse: $!" : "rev-parse exited with status: $?";
401         $short_obj = $obj if not defined $short_obj;
402         chomp $short_obj;
403         $url = "$gitweb_url/?a=commit;h=$short_obj";
404     }
406     push @notice, format_table(
407         "Module: $repos_name",
408         "Branch: $ref",
409         "Commit: $obj",
410         "Author:" . $info{"author"},
411         $info{"committer"} ne $info{"author"} ? "Committer:" . $info{"committer"} : undef,
412         "Date:" . format_date($info{"author_date"},$info{"author_tz"}),
413         $url ? "URL: $url" : undef),
414         "",
415         @{$info{"log"}},
416         "",
417         "---",
418         "";
420     open STAT, "-|" or exec "git", "diff-tree", "--stat", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
421     push @notice, join("", <STAT>);
422     close STAT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
424     if (($max_diff_size == -1) || (length($diff) < $max_diff_size))
425     {
426         push @notice, $diff;
427     }
428     else
429     {
430         push @notice, "Diff:   $gitweb_url/?a=commitdiff;h=$obj" if $gitweb_url;
431     }
433     $_ = decode($info{"encoding"}, $_) for @notice;
435     mail_notification($commitlist_address,
436         $info{"author_name"} . ": " . truncate_str(${$info{"log"}}[0], 50),
437         "text/plain; charset=UTF-8", @notice);
438     $sent_notices++;
441 # send a commit notice to the CIA server
442 sub send_cia_notice($$)
444     my ($ref,$commit) = @_;
445     my %info = get_object_info($commit);
446     my @cia_text = ();
448     push @cia_text,
449         "<message>",
450         "  <generator>",
451         "    <name>git-notify script for CIA</name>",
452         "  </generator>",
453         "  <source>",
454         "    <project>" . xml_escape($cia_project_name) . "</project>",
455         "    <module>" . xml_escape($repos_name) . "</module>",
456         "    <branch>" . xml_escape($ref). "</branch>",
457         "  </source>",
458         "  <body>",
459         "    <commit>",
460         "      <revision>" . substr($commit,0,10) . "</revision>",
461         "      <author>" . xml_escape($info{"author"}) . "</author>",
462         "      <log>" . xml_escape(join "\n", @{$info{"log"}}) . "</log>",
463         "      <files>";
465     open COMMIT, "-|" or exec "git", "diff-tree", "--name-status", "-r", "-M", $commit or die "cannot run git-diff-tree";
466     while (<COMMIT>)
467     {
468         chomp;
469         if (/^([AMD])\t(.*)$/)
470         {
471             my ($action, $file) = ($1, $2);
472             my %actions = ( "A" => "add", "M" => "modify", "D" => "remove" );
473             next unless defined $actions{$action};
474             push @cia_text, "        <file action=\"$actions{$action}\">" . xml_escape($file) . "</file>";
475         }
476         elsif (/^R\d+\t(.*)\t(.*)$/)
477         {
478             my ($old, $new) = ($1, $2);
479             push @cia_text, "        <file action=\"rename\" to=\"" . xml_escape($new) . "\">" . xml_escape($old) . "</file>";
480         }
481     }
482     close COMMIT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
484     push @cia_text,
485         "      </files>",
486         $gitweb_url ? "      <url>" . xml_escape("$gitweb_url/?a=commit;h=$commit") . "</url>" : "",
487         "    </commit>",
488         "  </body>",
489         "  <timestamp>" . $info{"author_date"} . "</timestamp>",
490         "</message>";
492     mail_notification($cia_address, "DeliverXML", "text/xml", @cia_text);
495 # send a global commit notice when there are too many commits for individual mails
496 sub send_global_notice($$$)
498     my ($ref, $old_sha1, $new_sha1) = @_;
499     my $notice = git_rev_list("--pretty", "^$old_sha1", "$new_sha1", @exclude_list);
501     foreach my $rev (@$notice)
502     {
503         $rev =~ s/^commit /URL:    $gitweb_url\/?a=commit;h=/ if $gitweb_url;
504     }
506     mail_notification($commitlist_address, "New commits on branch $ref", "text/plain; charset=UTF-8", @$notice);
507     $sent_notices++;
510 # send all the notices
511 sub send_all_notices($$$)
513     my ($old_sha1, $new_sha1, $ref) = @_;
514     my ($reftype, $refname, $action, @notice);
516     return if ($ref =~ /^refs\/remotes\//
517         or (@include_list && !grep {$_ eq $ref} @include_list));
518     die "The name \"$ref\" doesn't sound like a local branch or tag"
519         if not (($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/));
521     if ($new_sha1 eq '0' x 40)
522     {
523         $action = "removed";
524         @notice = ( "Old SHA1: $old_sha1" );
525     }
526     elsif ($old_sha1 eq '0' x 40)
527     {
528         $action = "created";
529         @notice = ( "SHA1: $new_sha1" );
530     }
531     elsif ($reftype eq "tag")
532     {
533         $action = "updated";
534         @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
535     }
536     elsif (not grep( $_ eq $old_sha1, @{ git_rev_list( $new_sha1, "--full-history" ) } ))
537     {
538         $action = "rewritten";
539         @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
540     }
542     send_ref_notice( $ref, $action, @notice ) if ($commitlist_address and $action);
544     unless ($reftype eq "tag" or $new_sha1 eq '0' x 40)
545     {
546         my $commits = get_new_commits ( $old_sha1, $new_sha1 );
548         if (@$commits > $max_individual_notices)
549         {
550             send_global_notice( $refname, $old_sha1, $new_sha1 ) if $commitlist_address;
551         }
552         else
553         {
554             foreach my $commit (@$commits)
555             {
556                 send_commit_notice( $refname, $commit ) if $commitlist_address;
557                 send_cia_notice( $refname, $commit ) if $cia_project_name;
558             }
559         }
560         if ($sent_notices == 0 and $commitlist_address)
561         {
562             @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
563             send_ref_notice( $ref, "modified", @notice );
564         }
565     }
568 parse_options();
570 umask( $mode_mask );
572 # append repository path to URL
573 $gitweb_url .= "/$repos_name.git" if $gitweb_url;
575 if (@ARGV)
577     send_all_notices( $ARGV[0], $ARGV[1], $ARGV[2] );
579 else  # read them from stdin
581     while (<>)
582     {
583         chomp;
584         if (/^([0-9a-f]{40}) ([0-9a-f]{40}) (.*)$/) { send_all_notices( $1, $2, $3 ); }
585     }
588 exit 0;