Code

0c2f7395fd2c1484aff70b739c0c3d884ea8d2c7
[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 #
7 # This program is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU General Public License as
9 # published by the Free Software Foundation; either version 2 of
10 # the License, or (at your option) any later version.
11 #
12 #
13 # This script is meant to be called from .git/hooks/post-receive.
14 #
15 # Usage: git-notify [options] [--] old-sha1 new-sha1 refname
16 #
17 #   -c name   Send CIA notifications under specified project name
18 #   -m addr   Send mail notifications to specified address
19 #   -n max    Set max number of individual mails to send
20 #   -r name   Set the git repository name
21 #   -s bytes  Set the maximum diff size in bytes (-1 for no limit)
22 #   -u url    Set the URL to the gitweb browser
23 #   -i branch If at least one -i is given, report only for specified branches
24 #   -x branch Exclude changes to the specified branch from reports
25 #   -X        Exclude merge commits
26 #
28 use strict;
29 use open ':utf8';
30 use Encode 'encode';
31 use Cwd 'realpath';
33 binmode STDIN, ':utf8';
34 binmode STDOUT, ':utf8';
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 # configuration parameters
52 # base URL of the gitweb repository browser (can be set with the -u option)
53 my $gitweb_url = git_config( "notify.baseurl" );
55 # default repository name (can be changed with the -r option)
56 my $repos_name = git_config( "notify.repository" ) || get_repos_name();
58 # max size of diffs in bytes (can be changed with the -s option)
59 my $max_diff_size = git_config( "notify.maxdiff" ) || 10000;
61 # address for mail notices (can be set with -m option)
62 my $commitlist_address = git_config( "notify.mail" );
64 # project name for CIA notices (can be set with -c option)
65 my $cia_project_name = git_config( "notify.cia" );
67 # max number of individual notices before falling back to a single global notice (can be set with -n option)
68 my $max_individual_notices = git_config( "notify.maxnotices" ) || 100;
70 # branches to include
71 my @include_list = split /\s+/, git_config( "notify.include" ) || "";
73 # branches to exclude
74 my @exclude_list = split /\s+/, git_config( "notify.exclude" ) || "";
76 # Extra options to git rev-list
77 my @revlist_options;
79 sub usage()
80 {
81     print "Usage: $0 [options] [--] old-sha1 new-sha1 refname\n";
82     print "   -c name   Send CIA notifications under specified project name\n";
83     print "   -m addr   Send mail notifications to specified address\n";
84     print "   -n max    Set max number of individual mails to send\n";
85     print "   -r name   Set the git repository name\n";
86     print "   -s bytes  Set the maximum diff size in bytes (-1 for no limit)\n";
87     print "   -u url    Set the URL to the gitweb browser\n";
88     print "   -i branch If at least one -i is given, report only for specified branches\n";
89     print "   -x branch Exclude changes to the specified branch from reports\n";
90     print "   -X        Exclude merge commits\n";
91     exit 1;
92 }
94 sub xml_escape($)
95 {
96     my $str = shift;
97     $str =~ s/&/&/g;
98     $str =~ s/</&lt;/g;
99     $str =~ s/>/&gt;/g;
100     my @chars = unpack "U*", $str;
101     $str = join "", map { ($_ > 127) ? sprintf "&#%u;", $_ : chr($_); } @chars;
102     return $str;
105 # right-justify the left column of "left: right" elements, omit undefined elements
106 sub format_table(@)
108     my @lines = @_;
109     my @table;
110     my $max = 0;
112     foreach my $line (@lines)
113     {
114        next if not defined $line;
115        my $pos = index($line, ":");
117        $max = $pos if $pos > $max;
118     }
120     foreach my $line (@lines)
121     {
122        next if not defined $line;
123        my ($left, $right) = split(/: */, $line, 2);
125        push @table, (defined $left and defined $right)
126            ? sprintf("%*s: %s", $max + 1, $left, $right)
127            : $line;
128     }
129     return @table;
132 # format an integer date + timezone as string
133 # algorithm taken from git's date.c
134 sub format_date($$)
136     my ($time,$tz) = @_;
138     if ($tz < 0)
139     {
140         my $minutes = (-$tz / 100) * 60 + (-$tz % 100);
141         $time -= $minutes * 60;
142     }
143     else
144     {
145         my $minutes = ($tz / 100) * 60 + ($tz % 100);
146         $time += $minutes * 60;
147     }
148     return gmtime($time) . sprintf " %+05d", $tz;
151 # fetch a parameter from the git config file
152 sub git_config($)
154     my ($param) = @_;
156     open CONFIG, "-|" or exec "git", "config", $param;
157     my $ret = <CONFIG>;
158     chomp $ret if $ret;
159     close CONFIG or $ret = undef;
160     return $ret;
163 # parse command line options
164 sub parse_options()
166     while (@ARGV && $ARGV[0] =~ /^-/)
167     {
168         my $arg = shift @ARGV;
170         if ($arg eq '--') { last; }
171         elsif ($arg eq '-c') { $cia_project_name = shift @ARGV; }
172         elsif ($arg eq '-m') { $commitlist_address = shift @ARGV; }
173         elsif ($arg eq '-n') { $max_individual_notices = shift @ARGV; }
174         elsif ($arg eq '-r') { $repos_name = shift @ARGV; }
175         elsif ($arg eq '-s') { $max_diff_size = shift @ARGV; }
176         elsif ($arg eq '-u') { $gitweb_url = shift @ARGV; }
177         elsif ($arg eq '-i') { push @include_list, shift @ARGV; }
178         elsif ($arg eq '-x') { push @exclude_list, shift @ARGV; }
179         elsif ($arg eq '-X') { push @revlist_options, "--no-merges"; }
180         elsif ($arg eq '-d') { $debug++; }
181         else { usage(); }
182     }
183     if (@ARGV && $#ARGV != 2) { usage(); }
184     @exclude_list = map { "^$_"; } @exclude_list;
187 # send an email notification
188 sub mail_notification($$$@)
190     my ($name, $subject, $content_type, @text) = @_;
191     $subject = encode("MIME-Q",$subject);
192     if ($debug)
193     {
194         print "---------------------\n";
195         print "To: $name\n";
196         print "Subject: $subject\n";
197         print "Content-Type: $content_type\n";
198         print "\n", join("\n", @text), "\n";
199     }
200     else
201     {
202         my $pid = open MAIL, "|-";
203         return unless defined $pid;
204         if (!$pid)
205         {
206             exec $mailer, "-s", $subject, "-a", "Content-Type: $content_type", $name or die "Cannot exec $mailer";
207         }
208         print MAIL join("\n", @text), "\n";
209         close MAIL;
210     }
213 # get the default repository name
214 sub get_repos_name()
216     my $dir = `git rev-parse --git-dir`;
217     chomp $dir;
218     my $repos = realpath($dir);
219     $repos =~ s/(.*?)((\.git\/)?\.git)$/$1/;
220     $repos =~ s/(.*)\/([^\/]+)\/?$/$2/;
221     return $repos;
224 # extract the information from a commit object and return a hash containing the various fields
225 sub get_object_info($)
227     my $obj = shift;
228     my %info = ();
229     my @log = ();
230     my $do_log = 0;
232     open OBJ, "-|" or exec "git", "cat-file", "commit", $obj or die "cannot run git-cat-file";
233     while (<OBJ>)
234     {
235         chomp;
236         if ($do_log) { push @log, $_; }
237         elsif (/^$/) { $do_log = 1; }
238         elsif (/^(author|committer) ((.*) (<.*>)) (\d+) ([+-]\d+)$/)
239         {
240             $info{$1} = $2;
241             $info{$1 . "_name"} = $3;
242             $info{$1 . "_email"} = $4;
243             $info{$1 . "_date"} = $5;
244             $info{$1 . "_tz"} = $6;
245         }
246     }
247     close OBJ;
249     $info{"log"} = \@log;
250     return %info;
253 # send a commit notice to a mailing list
254 sub send_commit_notice($$)
256     my ($ref,$obj) = @_;
257     my %info = get_object_info($obj);
258     my @notice = ();
260     open DIFF, "-|" or exec "git", "diff-tree", "-p", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
261     my $diff = join("", <DIFF>);
262     close DIFF;
264     return if length($diff) == 0;
266     push @notice, format_table(
267         "Module: $repos_name",
268         "Branch: $ref",
269         "Commit: $obj",
270         $gitweb_url ? "URL: $gitweb_url/?a=commit;h=$obj" : undef),
271         "Author:" . $info{"author"},
272         "Date:" . format_date($info{"author_date"},$info{"author_tz"}),
273         "",
274         @{$info{"log"}},
275         "",
276         "---",
277         "";
279     open STAT, "-|" or exec "git", "diff-tree", "--stat", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
280     push @notice, join("", <STAT>);
281     close STAT;
283     if (($max_diff_size == -1) || (length($diff) < $max_diff_size))
284     {
285         push @notice, $diff;
286     }
287     else
288     {
289         push @notice, "Diff:   $gitweb_url/?a=commitdiff;h=$obj" if $gitweb_url;
290     }
292     mail_notification($commitlist_address,
293         $info{"author_name"} . ": " . ${$info{"log"}}[0],
294         "text/plain; charset=UTF-8", @notice);
297 # send a commit notice to the CIA server
298 sub send_cia_notice($$)
300     my ($ref,$commit) = @_;
301     my %info = get_object_info($commit);
302     my @cia_text = ();
304     push @cia_text,
305         "<message>",
306         "  <generator>",
307         "    <name>git-notify script for CIA</name>",
308         "  </generator>",
309         "  <source>",
310         "    <project>" . xml_escape($cia_project_name) . "</project>",
311         "    <module>" . xml_escape($repos_name) . "</module>",
312         "    <branch>" . xml_escape($ref). "</branch>",
313         "  </source>",
314         "  <body>",
315         "    <commit>",
316         "      <revision>" . substr($commit,0,10) . "</revision>",
317         "      <author>" . xml_escape($info{"author"}) . "</author>",
318         "      <log>" . xml_escape(join "\n", @{$info{"log"}}) . "</log>",
319         "      <files>";
321     open COMMIT, "-|" or exec "git", "diff-tree", "--name-status", "-r", "-M", $commit or die "cannot run git-diff-tree";
322     while (<COMMIT>)
323     {
324         chomp;
325         if (/^([AMD])\t(.*)$/)
326         {
327             my ($action, $file) = ($1, $2);
328             my %actions = ( "A" => "add", "M" => "modify", "D" => "remove" );
329             next unless defined $actions{$action};
330             push @cia_text, "        <file action=\"$actions{$action}\">" . xml_escape($file) . "</file>";
331         }
332         elsif (/^R\d+\t(.*)\t(.*)$/)
333         {
334             my ($old, $new) = ($1, $2);
335             push @cia_text, "        <file action=\"rename\" to=\"" . xml_escape($new) . "\">" . xml_escape($old) . "</file>";
336         }
337     }
338     close COMMIT;
340     push @cia_text,
341         "      </files>",
342         $gitweb_url ? "      <url>" . xml_escape("$gitweb_url/?a=commit;h=$commit") . "</url>" : "",
343         "    </commit>",
344         "  </body>",
345         "  <timestamp>" . $info{"author_date"} . "</timestamp>",
346         "</message>";
348     mail_notification($cia_address, "DeliverXML", "text/xml", @cia_text);
351 # send a global commit notice when there are too many commits for individual mails
352 sub send_global_notice($$$)
354     my ($ref, $old_sha1, $new_sha1) = @_;
355     my @notice = ();
357     push @revlist_options, "--pretty";
358     open LIST, "-|" or exec "git", "rev-list", @revlist_options, "^$old_sha1", "$new_sha1", @exclude_list or die "cannot exec git-rev-list";
359     while (<LIST>)
360     {
361         chomp;
362         s/^commit /URL:    $gitweb_url\/?a=commit;h=/ if $gitweb_url;
363         push @notice, $_;
364     }
365     close LIST;
367     mail_notification($commitlist_address, "New commits on branch $ref", "text/plain; charset=UTF-8", @notice);
370 # send all the notices
371 sub send_all_notices($$$)
373     my ($old_sha1, $new_sha1, $ref) = @_;
375     $ref =~ s/^refs\/heads\///;
377     return if (@include_list && !grep {$_ eq $ref} @include_list);
379     if ($old_sha1 eq '0' x 40)  # new ref
380     {
381         send_commit_notice( $ref, $new_sha1 ) if $commitlist_address;
382         return;
383     }
385     my @commits = ();
387     open LIST, "-|" or exec "git", "rev-list", @revlist_options, "^$old_sha1", "$new_sha1", @exclude_list or die "cannot exec git-rev-list";
388     while (<LIST>)
389     {
390         chomp;
391         die "invalid commit $_" unless /^[0-9a-f]{40}$/;
392         unshift @commits, $_;
393     }
394     close LIST;
396     if (@commits > $max_individual_notices)
397     {
398         send_global_notice( $ref, $old_sha1, $new_sha1 ) if $commitlist_address;
399         return;
400     }
402     foreach my $commit (@commits)
403     {
404         send_commit_notice( $ref, $commit ) if $commitlist_address;
405         send_cia_notice( $ref, $commit ) if $cia_project_name;
406     }
409 parse_options();
411 # append repository path to URL
412 $gitweb_url .= "/$repos_name.git" if $gitweb_url;
414 if (@ARGV)
416     send_all_notices( $ARGV[0], $ARGV[1], $ARGV[2] );
418 else  # read them from stdin
420     while (<>)
421     {
422         chomp;
423         if (/^([0-9a-f]{40}) ([0-9a-f]{40}) (.*)$/) { send_all_notices( $1, $2, $3 ); }
424     }
427 exit 0;