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/</</g;
102 $str =~ s/>/>/g;
103 my @chars = unpack "U*", $str;
104 $str = join "", map { ($_ > 127) ? sprintf "&#%u;", $_ : chr($_); } @chars;
105 return $str;
106 }
108 # execute git-rev-list(1) with the given parameters and return the output
109 sub git_rev_list(@)
110 {
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;
128 }
130 # truncate the given string if it exceeds the specified number of characters
131 sub truncate_str($$)
132 {
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;
142 }
144 # right-justify the left column of "left: right" elements, omit undefined elements
145 sub format_table(@)
146 {
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;
169 }
171 # format an integer date + timezone as string
172 # algorithm taken from git's date.c
173 sub format_date($$)
174 {
175 my ($time,$tz) = @_;
177 if ($tz < 0)
178 {
179 my $minutes = (-$tz / 100) * 60 + (-$tz % 100);
180 $time -= $minutes * 60;
181 }
182 else
183 {
184 my $minutes = ($tz / 100) * 60 + ($tz % 100);
185 $time += $minutes * 60;
186 }
187 return gmtime($time) . sprintf " %+05d", $tz;
188 }
190 # fetch a parameter from the git config file
191 sub git_config($)
192 {
193 my ($param) = @_;
195 open CONFIG, "-|" or exec "git", "config", $param;
196 my $ret = <CONFIG>;
197 chomp $ret if $ret;
198 close CONFIG or $ret = undef;
199 return $ret;
200 }
202 # parse command line options
203 sub parse_options()
204 {
205 while (@ARGV && $ARGV[0] =~ /^-/)
206 {
207 my $arg = shift @ARGV;
209 if ($arg eq '--') { last; }
210 elsif ($arg eq '-c') { $cia_project_name = shift @ARGV; }
211 elsif ($arg eq '-m') { $commitlist_address = shift @ARGV; }
212 elsif ($arg eq '-n') { $max_individual_notices = shift @ARGV; }
213 elsif ($arg eq '-r') { $repos_name = shift @ARGV; }
214 elsif ($arg eq '-s') { $max_diff_size = shift @ARGV; }
215 elsif ($arg eq '-u') { $gitweb_url = shift @ARGV; }
216 elsif ($arg eq '-i') { push @include_list, shift @ARGV; }
217 elsif ($arg eq '-x') { push @exclude_list, shift @ARGV; }
218 elsif ($arg eq '-X') { push @revlist_options, "--no-merges"; }
219 elsif ($arg eq '-d') { $debug++; }
220 else { usage(); }
221 }
222 if (@ARGV && $#ARGV != 2) { usage(); }
223 @exclude_list = map { "^$_"; } @exclude_list;
224 }
226 # send an email notification
227 sub mail_notification($$$@)
228 {
229 my ($name, $subject, $content_type, @text) = @_;
230 $subject = encode("MIME-Q",$subject);
231 if ($debug)
232 {
233 print "---------------------\n";
234 print "To: $name\n";
235 print "Subject: $subject\n";
236 print "Content-Type: $content_type\n";
237 print "\n", join("\n", @text), "\n";
238 }
239 else
240 {
241 my $pid = open MAIL, "|-";
242 return unless defined $pid;
243 if (!$pid)
244 {
245 exec $mailer, "-s", $subject, "-a", "Content-Type: $content_type", $name or die "Cannot exec $mailer";
246 }
247 print MAIL join("\n", @text), "\n";
248 close MAIL;
249 }
250 }
252 # get the default repository name
253 sub get_repos_name()
254 {
255 my $dir = `git rev-parse --git-dir`;
256 chomp $dir;
257 my $repos = realpath($dir);
258 $repos =~ s/(.*?)((\.git\/)?\.git)$/$1/;
259 $repos =~ s/(.*)\/([^\/]+)\/?$/$2/;
260 return $repos;
261 }
263 # extract the information from a commit object and return a hash containing the various fields
264 sub get_object_info($)
265 {
266 my $obj = shift;
267 my %info = ();
268 my @log = ();
269 my $do_log = 0;
271 open OBJ, "-|" or exec "git", "cat-file", "commit", $obj or die "cannot run git-cat-file";
272 while (<OBJ>)
273 {
274 chomp;
275 if ($do_log) { push @log, $_; }
276 elsif (/^$/) { $do_log = 1; }
277 elsif (/^(author|committer) ((.*) (<.*>)) (\d+) ([+-]\d+)$/)
278 {
279 $info{$1} = $2;
280 $info{$1 . "_name"} = $3;
281 $info{$1 . "_email"} = $4;
282 $info{$1 . "_date"} = $5;
283 $info{$1 . "_tz"} = $6;
284 }
285 }
286 close OBJ;
288 $info{"log"} = \@log;
289 return %info;
290 }
292 # send a ref change notice to a mailing list
293 sub send_ref_notice($$@)
294 {
295 my ($ref, $action, @notice) = @_;
296 my ($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/);
298 $reftype =~ s/^head$/branch/;
300 @notice = (format_table(
301 "Module: $repos_name",
302 ($reftype eq "tag" ? "Tag:" : "Branch:") . $refname,
303 @notice,
304 ($action ne "removed" and $gitweb_url)
305 ? "URL: $gitweb_url/?a=shortlog;h=$ref" : undef),
306 "",
307 "The $refname $reftype has been $action.");
309 mail_notification($commitlist_address, "$refname $reftype $action",
310 "text/plain; charset=us-ascii", @notice);
311 $sent_notices++;
312 }
314 # send a commit notice to a mailing list
315 sub send_commit_notice($$)
316 {
317 my ($ref,$obj) = @_;
318 my %info = get_object_info($obj);
319 my @notice = ();
321 open DIFF, "-|" or exec "git", "diff-tree", "-p", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
322 my $diff = join("", <DIFF>);
323 close DIFF;
325 return if length($diff) == 0;
327 push @notice, format_table(
328 "Module: $repos_name",
329 "Branch: $ref",
330 "Commit: $obj",
331 $gitweb_url ? "URL: $gitweb_url/?a=commit;h=$obj" : undef),
332 "Author:" . $info{"author"},
333 $info{"committer"} ne $info{"author"} ? "Committer:" . $info{"committer"} : undef,
334 "Date:" . format_date($info{"author_date"},$info{"author_tz"}),
335 "",
336 @{$info{"log"}},
337 "",
338 "---",
339 "";
341 open STAT, "-|" or exec "git", "diff-tree", "--stat", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
342 push @notice, join("", <STAT>);
343 close STAT;
345 if (($max_diff_size == -1) || (length($diff) < $max_diff_size))
346 {
347 push @notice, $diff;
348 }
349 else
350 {
351 push @notice, "Diff: $gitweb_url/?a=commitdiff;h=$obj" if $gitweb_url;
352 }
354 mail_notification($commitlist_address,
355 $info{"author_name"} . ": " . truncate_str(${$info{"log"}}[0], 50),
356 "text/plain; charset=UTF-8", @notice);
357 $sent_notices++;
358 }
360 # send a commit notice to the CIA server
361 sub send_cia_notice($$)
362 {
363 my ($ref,$commit) = @_;
364 my %info = get_object_info($commit);
365 my @cia_text = ();
367 push @cia_text,
368 "<message>",
369 " <generator>",
370 " <name>git-notify script for CIA</name>",
371 " </generator>",
372 " <source>",
373 " <project>" . xml_escape($cia_project_name) . "</project>",
374 " <module>" . xml_escape($repos_name) . "</module>",
375 " <branch>" . xml_escape($ref). "</branch>",
376 " </source>",
377 " <body>",
378 " <commit>",
379 " <revision>" . substr($commit,0,10) . "</revision>",
380 " <author>" . xml_escape($info{"author"}) . "</author>",
381 " <log>" . xml_escape(join "\n", @{$info{"log"}}) . "</log>",
382 " <files>";
384 open COMMIT, "-|" or exec "git", "diff-tree", "--name-status", "-r", "-M", $commit or die "cannot run git-diff-tree";
385 while (<COMMIT>)
386 {
387 chomp;
388 if (/^([AMD])\t(.*)$/)
389 {
390 my ($action, $file) = ($1, $2);
391 my %actions = ( "A" => "add", "M" => "modify", "D" => "remove" );
392 next unless defined $actions{$action};
393 push @cia_text, " <file action=\"$actions{$action}\">" . xml_escape($file) . "</file>";
394 }
395 elsif (/^R\d+\t(.*)\t(.*)$/)
396 {
397 my ($old, $new) = ($1, $2);
398 push @cia_text, " <file action=\"rename\" to=\"" . xml_escape($new) . "\">" . xml_escape($old) . "</file>";
399 }
400 }
401 close COMMIT;
403 push @cia_text,
404 " </files>",
405 $gitweb_url ? " <url>" . xml_escape("$gitweb_url/?a=commit;h=$commit") . "</url>" : "",
406 " </commit>",
407 " </body>",
408 " <timestamp>" . $info{"author_date"} . "</timestamp>",
409 "</message>";
411 mail_notification($cia_address, "DeliverXML", "text/xml", @cia_text);
412 }
414 # send a global commit notice when there are too many commits for individual mails
415 sub send_global_notice($$$)
416 {
417 my ($ref, $old_sha1, $new_sha1) = @_;
418 my $notice = git_rev_list("--pretty", "^$old_sha1", "$new_sha1", @exclude_list);
420 foreach my $rev (@$notice)
421 {
422 $rev =~ s/^commit /URL: $gitweb_url\/?a=commit;h=/ if $gitweb_url;
423 }
425 mail_notification($commitlist_address, "New commits on branch $ref", "text/plain; charset=UTF-8", @$notice);
426 $sent_notices++;
427 }
429 # send all the notices
430 sub send_all_notices($$$)
431 {
432 my ($old_sha1, $new_sha1, $ref) = @_;
433 my ($reftype, $refname, $action, @notice);
435 return if ($ref =~ /^refs\/remotes\//
436 or (@include_list && !grep {$_ eq $ref} @include_list));
437 die "The name \"$ref\" doesn't sound like a local branch or tag"
438 if not (($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/));
440 if ($new_sha1 eq '0' x 40)
441 {
442 $action = "removed";
443 @notice = ( "Old SHA1: $old_sha1" );
444 }
445 elsif ($old_sha1 eq '0' x 40)
446 {
447 $action = "created";
448 @notice = ( "SHA1: $new_sha1" );
449 }
450 elsif ($reftype eq "tag")
451 {
452 $action = "updated";
453 @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
454 }
455 elsif (not grep( $_ eq $old_sha1, @{ git_rev_list( $new_sha1, "--full-history" ) } ))
456 {
457 $action = "rewritten";
458 @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
459 }
461 send_ref_notice( $ref, $action, @notice ) if ($commitlist_address and $action);
463 unless ($reftype eq "tag" or $new_sha1 eq '0' x 40)
464 {
465 my $commits = get_new_commits ( $old_sha1, $new_sha1 );
467 if (@$commits > $max_individual_notices)
468 {
469 send_global_notice( $refname, $old_sha1, $new_sha1 ) if $commitlist_address;
470 }
471 else
472 {
473 foreach my $commit (@$commits)
474 {
475 send_commit_notice( $refname, $commit ) if $commitlist_address;
476 send_cia_notice( $refname, $commit ) if $cia_project_name;
477 }
478 }
479 if ($sent_notices == 0 and $commitlist_address)
480 {
481 @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
482 send_ref_notice( $ref, "modified", @notice );
483 }
484 }
485 }
487 parse_options();
489 # append repository path to URL
490 $gitweb_url .= "/$repos_name.git" if $gitweb_url;
492 if (@ARGV)
493 {
494 send_all_notices( $ARGV[0], $ARGV[1], $ARGV[2] );
495 }
496 else # read them from stdin
497 {
498 while (<>)
499 {
500 chomp;
501 if (/^([0-9a-f]{40}) ([0-9a-f]{40}) (.*)$/) { send_all_notices( $1, $2, $3 ); }
502 }
503 }
505 exit 0;