Code

git-nofity: Try to shorten Gitweb URLs
[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 # 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 # Extra options to git rev-list
80 my @revlist_options;
82 sub usage()
83 {
84     print "Usage: $0 [options] [--] old-sha1 new-sha1 refname\n";
85     print "   -c name   Send CIA notifications under specified project name\n";
86     print "   -m addr   Send mail notifications to specified address\n";
87     print "   -n max    Set max number of individual mails to send\n";
88     print "   -r name   Set the git repository name\n";
89     print "   -s bytes  Set the maximum diff size in bytes (-1 for no limit)\n";
90     print "   -u url    Set the URL to the gitweb browser\n";
91     print "   -i branch If at least one -i is given, report only for specified branches\n";
92     print "   -x branch Exclude changes to the specified branch from reports\n";
93     print "   -X        Exclude merge commits\n";
94     exit 1;
95 }
97 sub xml_escape($)
98 {
99     my $str = shift;
100     $str =~ s/&/&/g;
101     $str =~ s/</&lt;/g;
102     $str =~ s/>/&gt;/g;
103     my @chars = unpack "U*", $str;
104     $str = join "", map { ($_ > 127) ? sprintf "&#%u;", $_ : chr($_); } @chars;
105     return $str;
108 # execute git-rev-list(1) with the given parameters and return the output
109 sub git_rev_list(@)
111     my @args = @_;
112     my $revlist = [];
113     my $pid = open REVLIST, "-|";
115     die "Cannot open pipe: $!" if not defined $pid;
116     if (!$pid)
117     {
118         exec "git", "rev-list", @revlist_options, @args or die "Cannot execute rev-list: $!";
119     }
120     while (<REVLIST>)
121     {
122         chomp;
123         die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
124         push @$revlist, $_;
125     }
126     close REVLIST or die $! ? "Cannot execute rev-list: $!" : "rev-list exited with status: $?";
127     return $revlist;
130 # truncate the given string if it exceeds the specified number of characters
131 sub truncate_str($$)
133     my ($str, $max) = @_;
135     if (length($str) > $max)
136     {
137         $str = substr($str, 0, $max);
138         $str =~ s/\s+\S+$//;
139         $str .= " ...";
140     }
141     return $str;
144 # right-justify the left column of "left: right" elements, omit undefined elements
145 sub format_table(@)
147     my @lines = @_;
148     my @table;
149     my $max = 0;
151     foreach my $line (@lines)
152     {
153        next if not defined $line;
154        my $pos = index($line, ":");
156        $max = $pos if $pos > $max;
157     }
159     foreach my $line (@lines)
160     {
161        next if not defined $line;
162        my ($left, $right) = split(/: */, $line, 2);
164        push @table, (defined $left and defined $right)
165            ? sprintf("%*s: %s", $max + 1, $left, $right)
166            : $line;
167     }
168     return @table;
171 # return the gitweb URL of the given commit or undef
172 sub gitweb_url($$)
176 # format an integer date + timezone as string
177 # algorithm taken from git's date.c
178 sub format_date($$)
180     my ($time,$tz) = @_;
182     if ($tz < 0)
183     {
184         my $minutes = (-$tz / 100) * 60 + (-$tz % 100);
185         $time -= $minutes * 60;
186     }
187     else
188     {
189         my $minutes = ($tz / 100) * 60 + ($tz % 100);
190         $time += $minutes * 60;
191     }
192     return gmtime($time) . sprintf " %+05d", $tz;
195 # fetch a parameter from the git config file
196 sub git_config($)
198     my ($param) = @_;
200     open CONFIG, "-|" or exec "git", "config", $param;
201     my $ret = <CONFIG>;
202     chomp $ret if $ret;
203     close CONFIG or $ret = undef;
204     return $ret;
207 # parse command line options
208 sub parse_options()
210     while (@ARGV && $ARGV[0] =~ /^-/)
211     {
212         my $arg = shift @ARGV;
214         if ($arg eq '--') { last; }
215         elsif ($arg eq '-c') { $cia_project_name = shift @ARGV; }
216         elsif ($arg eq '-m') { $commitlist_address = shift @ARGV; }
217         elsif ($arg eq '-n') { $max_individual_notices = shift @ARGV; }
218         elsif ($arg eq '-r') { $repos_name = shift @ARGV; }
219         elsif ($arg eq '-s') { $max_diff_size = shift @ARGV; }
220         elsif ($arg eq '-u') { $gitweb_url = shift @ARGV; }
221         elsif ($arg eq '-i') { push @include_list, shift @ARGV; }
222         elsif ($arg eq '-x') { push @exclude_list, shift @ARGV; }
223         elsif ($arg eq '-X') { push @revlist_options, "--no-merges"; }
224         elsif ($arg eq '-d') { $debug++; }
225         else { usage(); }
226     }
227     if (@ARGV && $#ARGV != 2) { usage(); }
228     @exclude_list = map { "^$_"; } @exclude_list;
231 # send an email notification
232 sub mail_notification($$$@)
234     my ($name, $subject, $content_type, @text) = @_;
235     $subject = encode("MIME-Q",$subject);
236     if ($debug)
237     {
238         print "---------------------\n";
239         print "To: $name\n";
240         print "Subject: $subject\n";
241         print "Content-Type: $content_type\n";
242         print "\n", join("\n", @text), "\n";
243     }
244     else
245     {
246         my $pid = open MAIL, "|-";
247         return unless defined $pid;
248         if (!$pid)
249         {
250             exec $mailer, "-s", $subject, "-a", "Content-Type: $content_type", $name or die "Cannot exec $mailer";
251         }
252         print MAIL join("\n", @text), "\n";
253         close MAIL;
254     }
257 # get the default repository name
258 sub get_repos_name()
260     my $dir = `git rev-parse --git-dir`;
261     chomp $dir;
262     my $repos = realpath($dir);
263     $repos =~ s/(.*?)((\.git\/)?\.git)$/$1/;
264     $repos =~ s/(.*)\/([^\/]+)\/?$/$2/;
265     return $repos;
268 # extract the information from a commit object and return a hash containing the various fields
269 sub get_object_info($)
271     my $obj = shift;
272     my %info = ();
273     my @log = ();
274     my $do_log = 0;
276     open OBJ, "-|" or exec "git", "cat-file", "commit", $obj or die "cannot run git-cat-file";
277     while (<OBJ>)
278     {
279         chomp;
280         if ($do_log) { push @log, $_; }
281         elsif (/^$/) { $do_log = 1; }
282         elsif (/^(author|committer) ((.*) (<.*>)) (\d+) ([+-]\d+)$/)
283         {
284             $info{$1} = $2;
285             $info{$1 . "_name"} = $3;
286             $info{$1 . "_email"} = $4;
287             $info{$1 . "_date"} = $5;
288             $info{$1 . "_tz"} = $6;
289         }
290     }
291     close OBJ;
293     $info{"log"} = \@log;
294     return %info;
297 # send a ref change notice to a mailing list
298 sub send_ref_notice($$@)
300     my ($ref, $action, @notice) = @_;
301     my ($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/);
303     $reftype =~ s/^head$/branch/;
305     @notice = (format_table(
306         "Module: $repos_name",
307         ($reftype eq "tag" ? "Tag:" : "Branch:") . $refname,
308         @notice,
309         ($action ne "removed" and $gitweb_url)
310             ? "URL: $gitweb_url/?a=shortlog;h=$ref" : undef),
311         "",
312         "The $refname $reftype has been $action.");
314     mail_notification($commitlist_address, "$refname $reftype $action",
315         "text/plain; charset=us-ascii", @notice);
316     $sent_notices++;
319 # send a commit notice to a mailing list
320 sub send_commit_notice($$)
322     my ($ref,$obj) = @_;
323     my %info = get_object_info($obj);
324     my @notice = ();
325     my $url;
327     open DIFF, "-|" or exec "git", "diff-tree", "-p", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
328     my $diff = join("", <DIFF>);
329     close DIFF;
331     return if length($diff) == 0;
333     if ($gitweb_url)
334     {
335         open REVPARSE, "-|" or exec "git", "rev-parse", "--short", $obj or die "cannot exec git-rev-parse";
336         my $short_obj = <REVPARSE>;
337         close REVPARSE or die $! ? "Cannot execute rev-parse: $!" : "rev-parse exited with status: $?";
339         $short_obj = $obj if not defined $short_obj;
340         chomp $short_obj;
341         $url = "$gitweb_url/?a=commit;h=$short_obj";
342     }
344     push @notice, format_table(
345         "Module: $repos_name",
346         "Branch: $ref",
347         "Commit: $obj",
348         "Author:" . $info{"author"},
349         $info{"committer"} ne $info{"author"} ? "Committer:" . $info{"committer"} : undef,
350         "Date:" . format_date($info{"author_date"},$info{"author_tz"}),
351         $url ? "URL: $url" : undef),
352         "",
353         @{$info{"log"}},
354         "",
355         "---",
356         "";
358     open STAT, "-|" or exec "git", "diff-tree", "--stat", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
359     push @notice, join("", <STAT>);
360     close STAT;
362     if (($max_diff_size == -1) || (length($diff) < $max_diff_size))
363     {
364         push @notice, $diff;
365     }
366     else
367     {
368         push @notice, "Diff:   $gitweb_url/?a=commitdiff;h=$obj" if $gitweb_url;
369     }
371     mail_notification($commitlist_address,
372         $info{"author_name"} . ": " . truncate_str(${$info{"log"}}[0], 50),
373         "text/plain; charset=UTF-8", @notice);
374     $sent_notices++;
377 # send a commit notice to the CIA server
378 sub send_cia_notice($$)
380     my ($ref,$commit) = @_;
381     my %info = get_object_info($commit);
382     my @cia_text = ();
384     push @cia_text,
385         "<message>",
386         "  <generator>",
387         "    <name>git-notify script for CIA</name>",
388         "  </generator>",
389         "  <source>",
390         "    <project>" . xml_escape($cia_project_name) . "</project>",
391         "    <module>" . xml_escape($repos_name) . "</module>",
392         "    <branch>" . xml_escape($ref). "</branch>",
393         "  </source>",
394         "  <body>",
395         "    <commit>",
396         "      <revision>" . substr($commit,0,10) . "</revision>",
397         "      <author>" . xml_escape($info{"author"}) . "</author>",
398         "      <log>" . xml_escape(join "\n", @{$info{"log"}}) . "</log>",
399         "      <files>";
401     open COMMIT, "-|" or exec "git", "diff-tree", "--name-status", "-r", "-M", $commit or die "cannot run git-diff-tree";
402     while (<COMMIT>)
403     {
404         chomp;
405         if (/^([AMD])\t(.*)$/)
406         {
407             my ($action, $file) = ($1, $2);
408             my %actions = ( "A" => "add", "M" => "modify", "D" => "remove" );
409             next unless defined $actions{$action};
410             push @cia_text, "        <file action=\"$actions{$action}\">" . xml_escape($file) . "</file>";
411         }
412         elsif (/^R\d+\t(.*)\t(.*)$/)
413         {
414             my ($old, $new) = ($1, $2);
415             push @cia_text, "        <file action=\"rename\" to=\"" . xml_escape($new) . "\">" . xml_escape($old) . "</file>";
416         }
417     }
418     close COMMIT;
420     push @cia_text,
421         "      </files>",
422         $gitweb_url ? "      <url>" . xml_escape("$gitweb_url/?a=commit;h=$commit") . "</url>" : "",
423         "    </commit>",
424         "  </body>",
425         "  <timestamp>" . $info{"author_date"} . "</timestamp>",
426         "</message>";
428     mail_notification($cia_address, "DeliverXML", "text/xml", @cia_text);
431 # send a global commit notice when there are too many commits for individual mails
432 sub send_global_notice($$$)
434     my ($ref, $old_sha1, $new_sha1) = @_;
435     my $notice = git_rev_list("--pretty", "^$old_sha1", "$new_sha1", @exclude_list);
437     foreach my $rev (@$notice)
438     {
439         $rev =~ s/^commit /URL:    $gitweb_url\/?a=commit;h=/ if $gitweb_url;
440     }
442     mail_notification($commitlist_address, "New commits on branch $ref", "text/plain; charset=UTF-8", @$notice);
443     $sent_notices++;
446 # send all the notices
447 sub send_all_notices($$$)
449     my ($old_sha1, $new_sha1, $ref) = @_;
450     my ($reftype, $refname, $action, @notice);
452     return if ($ref =~ /^refs\/remotes\//
453         or (@include_list && !grep {$_ eq $ref} @include_list));
454     die "The name \"$ref\" doesn't sound like a local branch or tag"
455         if not (($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/));
457     if ($new_sha1 eq '0' x 40)
458     {
459         $action = "removed";
460         @notice = ( "Old SHA1: $old_sha1" );
461     }
462     elsif ($old_sha1 eq '0' x 40)
463     {
464         $action = "created";
465         @notice = ( "SHA1: $new_sha1" );
466     }
467     elsif ($reftype eq "tag")
468     {
469         $action = "updated";
470         @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
471     }
472     elsif (not grep( $_ eq $old_sha1, @{ git_rev_list( $new_sha1, "--full-history" ) } ))
473     {
474         $action = "rewritten";
475         @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
476     }
478     send_ref_notice( $ref, $action, @notice ) if ($commitlist_address and $action);
480     unless ($reftype eq "tag" or $new_sha1 eq '0' x 40)
481     {
482         my $commits = get_new_commits ( $old_sha1, $new_sha1 );
484         if (@$commits > $max_individual_notices)
485         {
486             send_global_notice( $refname, $old_sha1, $new_sha1 ) if $commitlist_address;
487         }
488         else
489         {
490             foreach my $commit (@$commits)
491             {
492                 send_commit_notice( $refname, $commit ) if $commitlist_address;
493                 send_cia_notice( $refname, $commit ) if $cia_project_name;
494             }
495         }
496         if ($sent_notices == 0 and $commitlist_address)
497         {
498             @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
499             send_ref_notice( $ref, "modified", @notice );
500         }
501     }
504 parse_options();
506 # append repository path to URL
507 $gitweb_url .= "/$repos_name.git" if $gitweb_url;
509 if (@ARGV)
511     send_all_notices( $ARGV[0], $ARGV[1], $ARGV[2] );
513 else  # read them from stdin
515     while (<>)
516     {
517         chomp;
518         if (/^([0-9a-f]{40}) ([0-9a-f]{40}) (.*)$/) { send_all_notices( $1, $2, $3 ); }
519     }
522 exit 0;