Code

6d5a564c254398ed249b7e832abbce4deb139c41
[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 # execute git-rev-list(1) with the given parameters and return the output
106 sub git_rev_list(@)
108     my @args = @_;
109     my $revlist = [];
110     my $pid = open REVLIST, "-|";
112     die "Cannot open pipe: $!" if not defined $pid;
113     if (!$pid)
114     {
115         exec "git", "rev-list", @revlist_options, @args or die "Cannot execute rev-list: $!";
116     }
117     while (<REVLIST>)
118     {
119         chomp;
120         die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
121         push @$revlist, $_;
122     }
123     close REVLIST or die $! ? "Cannot execute rev-list: $!" : "rev-list exited with status: $?";
124     return $revlist;
127 # right-justify the left column of "left: right" elements, omit undefined elements
128 sub format_table(@)
130     my @lines = @_;
131     my @table;
132     my $max = 0;
134     foreach my $line (@lines)
135     {
136        next if not defined $line;
137        my $pos = index($line, ":");
139        $max = $pos if $pos > $max;
140     }
142     foreach my $line (@lines)
143     {
144        next if not defined $line;
145        my ($left, $right) = split(/: */, $line, 2);
147        push @table, (defined $left and defined $right)
148            ? sprintf("%*s: %s", $max + 1, $left, $right)
149            : $line;
150     }
151     return @table;
154 # format an integer date + timezone as string
155 # algorithm taken from git's date.c
156 sub format_date($$)
158     my ($time,$tz) = @_;
160     if ($tz < 0)
161     {
162         my $minutes = (-$tz / 100) * 60 + (-$tz % 100);
163         $time -= $minutes * 60;
164     }
165     else
166     {
167         my $minutes = ($tz / 100) * 60 + ($tz % 100);
168         $time += $minutes * 60;
169     }
170     return gmtime($time) . sprintf " %+05d", $tz;
173 # fetch a parameter from the git config file
174 sub git_config($)
176     my ($param) = @_;
178     open CONFIG, "-|" or exec "git", "config", $param;
179     my $ret = <CONFIG>;
180     chomp $ret if $ret;
181     close CONFIG or $ret = undef;
182     return $ret;
185 # parse command line options
186 sub parse_options()
188     while (@ARGV && $ARGV[0] =~ /^-/)
189     {
190         my $arg = shift @ARGV;
192         if ($arg eq '--') { last; }
193         elsif ($arg eq '-c') { $cia_project_name = shift @ARGV; }
194         elsif ($arg eq '-m') { $commitlist_address = shift @ARGV; }
195         elsif ($arg eq '-n') { $max_individual_notices = shift @ARGV; }
196         elsif ($arg eq '-r') { $repos_name = shift @ARGV; }
197         elsif ($arg eq '-s') { $max_diff_size = shift @ARGV; }
198         elsif ($arg eq '-u') { $gitweb_url = shift @ARGV; }
199         elsif ($arg eq '-i') { push @include_list, shift @ARGV; }
200         elsif ($arg eq '-x') { push @exclude_list, shift @ARGV; }
201         elsif ($arg eq '-X') { push @revlist_options, "--no-merges"; }
202         elsif ($arg eq '-d') { $debug++; }
203         else { usage(); }
204     }
205     if (@ARGV && $#ARGV != 2) { usage(); }
206     @exclude_list = map { "^$_"; } @exclude_list;
209 # send an email notification
210 sub mail_notification($$$@)
212     my ($name, $subject, $content_type, @text) = @_;
213     $subject = encode("MIME-Q",$subject);
214     if ($debug)
215     {
216         print "---------------------\n";
217         print "To: $name\n";
218         print "Subject: $subject\n";
219         print "Content-Type: $content_type\n";
220         print "\n", join("\n", @text), "\n";
221     }
222     else
223     {
224         my $pid = open MAIL, "|-";
225         return unless defined $pid;
226         if (!$pid)
227         {
228             exec $mailer, "-s", $subject, "-a", "Content-Type: $content_type", $name or die "Cannot exec $mailer";
229         }
230         print MAIL join("\n", @text), "\n";
231         close MAIL;
232     }
235 # get the default repository name
236 sub get_repos_name()
238     my $dir = `git rev-parse --git-dir`;
239     chomp $dir;
240     my $repos = realpath($dir);
241     $repos =~ s/(.*?)((\.git\/)?\.git)$/$1/;
242     $repos =~ s/(.*)\/([^\/]+)\/?$/$2/;
243     return $repos;
246 # extract the information from a commit object and return a hash containing the various fields
247 sub get_object_info($)
249     my $obj = shift;
250     my %info = ();
251     my @log = ();
252     my $do_log = 0;
254     open OBJ, "-|" or exec "git", "cat-file", "commit", $obj or die "cannot run git-cat-file";
255     while (<OBJ>)
256     {
257         chomp;
258         if ($do_log) { push @log, $_; }
259         elsif (/^$/) { $do_log = 1; }
260         elsif (/^(author|committer) ((.*) (<.*>)) (\d+) ([+-]\d+)$/)
261         {
262             $info{$1} = $2;
263             $info{$1 . "_name"} = $3;
264             $info{$1 . "_email"} = $4;
265             $info{$1 . "_date"} = $5;
266             $info{$1 . "_tz"} = $6;
267         }
268     }
269     close OBJ;
271     $info{"log"} = \@log;
272     return %info;
275 # send a commit notice to a mailing list
276 sub send_commit_notice($$)
278     my ($ref,$obj) = @_;
279     my %info = get_object_info($obj);
280     my @notice = ();
282     open DIFF, "-|" or exec "git", "diff-tree", "-p", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
283     my $diff = join("", <DIFF>);
284     close DIFF;
286     return if length($diff) == 0;
288     push @notice, format_table(
289         "Module: $repos_name",
290         "Branch: $ref",
291         "Commit: $obj",
292         $gitweb_url ? "URL: $gitweb_url/?a=commit;h=$obj" : undef),
293         "Author:" . $info{"author"},
294         $info{"committer"} ne $info{"author"} ? "Committer:" . $info{"committer"} : undef,
295         "Date:" . format_date($info{"author_date"},$info{"author_tz"}),
296         "",
297         @{$info{"log"}},
298         "",
299         "---",
300         "";
302     open STAT, "-|" or exec "git", "diff-tree", "--stat", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
303     push @notice, join("", <STAT>);
304     close STAT;
306     if (($max_diff_size == -1) || (length($diff) < $max_diff_size))
307     {
308         push @notice, $diff;
309     }
310     else
311     {
312         push @notice, "Diff:   $gitweb_url/?a=commitdiff;h=$obj" if $gitweb_url;
313     }
315     mail_notification($commitlist_address,
316         $info{"author_name"} . ": " . ${$info{"log"}}[0],
317         "text/plain; charset=UTF-8", @notice);
320 # send a commit notice to the CIA server
321 sub send_cia_notice($$)
323     my ($ref,$commit) = @_;
324     my %info = get_object_info($commit);
325     my @cia_text = ();
327     push @cia_text,
328         "<message>",
329         "  <generator>",
330         "    <name>git-notify script for CIA</name>",
331         "  </generator>",
332         "  <source>",
333         "    <project>" . xml_escape($cia_project_name) . "</project>",
334         "    <module>" . xml_escape($repos_name) . "</module>",
335         "    <branch>" . xml_escape($ref). "</branch>",
336         "  </source>",
337         "  <body>",
338         "    <commit>",
339         "      <revision>" . substr($commit,0,10) . "</revision>",
340         "      <author>" . xml_escape($info{"author"}) . "</author>",
341         "      <log>" . xml_escape(join "\n", @{$info{"log"}}) . "</log>",
342         "      <files>";
344     open COMMIT, "-|" or exec "git", "diff-tree", "--name-status", "-r", "-M", $commit or die "cannot run git-diff-tree";
345     while (<COMMIT>)
346     {
347         chomp;
348         if (/^([AMD])\t(.*)$/)
349         {
350             my ($action, $file) = ($1, $2);
351             my %actions = ( "A" => "add", "M" => "modify", "D" => "remove" );
352             next unless defined $actions{$action};
353             push @cia_text, "        <file action=\"$actions{$action}\">" . xml_escape($file) . "</file>";
354         }
355         elsif (/^R\d+\t(.*)\t(.*)$/)
356         {
357             my ($old, $new) = ($1, $2);
358             push @cia_text, "        <file action=\"rename\" to=\"" . xml_escape($new) . "\">" . xml_escape($old) . "</file>";
359         }
360     }
361     close COMMIT;
363     push @cia_text,
364         "      </files>",
365         $gitweb_url ? "      <url>" . xml_escape("$gitweb_url/?a=commit;h=$commit") . "</url>" : "",
366         "    </commit>",
367         "  </body>",
368         "  <timestamp>" . $info{"author_date"} . "</timestamp>",
369         "</message>";
371     mail_notification($cia_address, "DeliverXML", "text/xml", @cia_text);
374 # send a global commit notice when there are too many commits for individual mails
375 sub send_global_notice($$$)
377     my ($ref, $old_sha1, $new_sha1) = @_;
378     my $notice = git_rev_list("--pretty", "^$old_sha1", "$new_sha1", @exclude_list);
380     foreach my $rev (@$notice)
381     {
382         $rev =~ s/^commit /URL:    $gitweb_url\/?a=commit;h=/ if $gitweb_url;
383     }
385     mail_notification($commitlist_address, "New commits on branch $ref", "text/plain; charset=UTF-8", @$notice);
388 # send all the notices
389 sub send_all_notices($$$)
391     my ($old_sha1, $new_sha1, $ref) = @_;
393     $ref =~ s/^refs\/heads\///;
395     return if (@include_list && !grep {$_ eq $ref} @include_list);
397     if ($old_sha1 eq '0' x 40)  # new ref
398     {
399         send_commit_notice( $ref, $new_sha1 ) if $commitlist_address;
400         return;
401     }
403     my @commits = ();
405     open LIST, "-|" or exec "git", "rev-list", @revlist_options, "^$old_sha1", "$new_sha1", @exclude_list or die "cannot exec git-rev-list";
406     while (<LIST>)
407     {
408         chomp;
409         die "invalid commit $_" unless /^[0-9a-f]{40}$/;
410         unshift @commits, $_;
411     }
412     close LIST;
414     if (@commits > $max_individual_notices)
415     {
416         send_global_notice( $ref, $old_sha1, $new_sha1 ) if $commitlist_address;
417         return;
418     }
420     foreach my $commit (@commits)
421     {
422         send_commit_notice( $ref, $commit ) if $commitlist_address;
423         send_cia_notice( $ref, $commit ) if $cia_project_name;
424     }
427 parse_options();
429 # append repository path to URL
430 $gitweb_url .= "/$repos_name.git" if $gitweb_url;
432 if (@ARGV)
434     send_all_notices( $ARGV[0], $ARGV[1], $ARGV[2] );
436 else  # read them from stdin
438     while (<>)
439     {
440         chomp;
441         if (/^([0-9a-f]{40}) ([0-9a-f]{40}) (.*)$/) { send_all_notices( $1, $2, $3 ); }
442     }
445 exit 0;