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 # -A Omit the author name from the mail subject
19 # -C Show committer in the body if different from the author
20 # -c name Send CIA notifications under specified project name
21 # -m addr Send mail notifications to specified address
22 # -n max Set max number of individual mails to send
23 # -r name Set the git repository name
24 # -s bytes Set the maximum diff size in bytes (-1 for no limit)
25 # -T Prefix the mail subject with a [repository name] tag
26 # -t file Prevent duplicate notifications by saving state to this file
27 # -U mask Set the umask for creating the state file
28 # -u url Set the URL to the gitweb browser
29 # -i branch If at least one -i is given, report only for specified branches
30 # -x branch Exclude changes to the specified branch from reports
31 # -X Exclude merge commits
32 # -z Try to abbreviate the SHA1 name within gitweb URLs (unsafe)
33 #
35 use strict;
36 use Fcntl ':flock';
37 use Encode qw(encode decode);
38 use Cwd 'realpath';
40 sub git_config($);
41 sub get_repos_name();
43 # some parameters you may want to change
45 # set this to something that takes "-s"
46 my $mailer = "/usr/bin/mail";
48 # CIA notification address
49 my $cia_address = "cia\@cia.navi.cx";
51 # debug mode
52 my $debug = 0;
54 # configuration parameters
56 # omit the author from the mail subject (can be set with the -A option)
57 my $omit_author = git_config( "notify.omitauthor" );
59 # prefix the mail subject with a [repository name] tag (can be set with the -T option)
60 my $emit_repo = git_config( "notify.emitrepository" );
62 # show the committer if different from the author (can be set with the -C option)
63 my $show_committer = git_config( "notify.showcommitter" );
65 # base URL of the gitweb repository browser (can be set with the -u option)
66 my $gitweb_url = git_config( "notify.baseurl" );
68 # abbreviate the SHA1 name within gitweb URLs (can be set with the -z option)
69 my $abbreviate_url = git_config( "notify.shorturls" );
71 # default repository name (can be changed with the -r option)
72 my $repos_name = git_config( "notify.repository" ) || get_repos_name();
74 # max size of diffs in bytes (can be changed with the -s option)
75 my $max_diff_size = git_config( "notify.maxdiff" ) || 10000;
77 # address for mail notices (can be set with -m option)
78 my $commitlist_address = git_config( "notify.mail" );
80 # project name for CIA notices (can be set with -c option)
81 my $cia_project_name = git_config( "notify.cia" );
83 # max number of individual notices before falling back to a single global notice (can be set with -n option)
84 my $max_individual_notices = git_config( "notify.maxnotices" ) || 100;
86 # branches to include
87 my @include_list = split /\s+/, git_config( "notify.include" ) || "";
89 # branches to exclude
90 my @exclude_list = split /\s+/, git_config( "notify.exclude" ) || "";
92 # the state file we use (can be set with the -t option)
93 my $state_file = git_config( "notify.statefile" );
95 # umask for creating the state file (can be set with -U option)
96 my $mode_mask = git_config( "notify.umask" ) || 002;
98 # Extra options to git rev-list
99 my @revlist_options;
101 sub usage()
102 {
103 print "Usage: $0 [options] [--] old-sha1 new-sha1 refname\n";
104 print " -A Omit the author name from the mail subject\n";
105 print " -C Show committer in the body if different from the author\n";
106 print " -c name Send CIA notifications under specified project name\n";
107 print " -m addr Send mail notifications to specified address\n";
108 print " -n max Set max number of individual mails to send\n";
109 print " -r name Set the git repository name\n";
110 print " -s bytes Set the maximum diff size in bytes (-1 for no limit)\n";
111 print " -T Prefix the mail subject with a [repository name] tag\n";
112 print " -t file Prevent duplicate notifications by saving state to this file\n";
113 print " -U mask Set the umask for creating the state file\n";
114 print " -u url Set the URL to the gitweb browser\n";
115 print " -i branch If at least one -i is given, report only for specified branches\n";
116 print " -x branch Exclude changes to the specified branch from reports\n";
117 print " -X Exclude merge commits\n";
118 print " -z Try to abbreviate the SHA1 name within gitweb URLs (unsafe)\n";
119 exit 1;
120 }
122 sub xml_escape($)
123 {
124 my $str = shift;
125 $str =~ s/&/&/g;
126 $str =~ s/</</g;
127 $str =~ s/>/>/g;
128 my @chars = unpack "U*", $str;
129 $str = join "", map { ($_ > 127) ? sprintf "&#%u;", $_ : chr($_); } @chars;
130 return $str;
131 }
133 # execute git-rev-list(1) with the given parameters and return the output
134 sub git_rev_list(@)
135 {
136 my @args = @_;
137 my $revlist = [];
138 my $pid = open REVLIST, "-|";
140 die "Cannot open pipe: $!" if not defined $pid;
141 if (!$pid)
142 {
143 exec "git", "rev-list", @revlist_options, @args or die "Cannot execute rev-list: $!";
144 }
145 while (<REVLIST>)
146 {
147 chomp;
148 unless (grep {$_ eq "--pretty"} @args)
149 {
150 die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
151 }
152 push @$revlist, $_;
153 }
154 close REVLIST or die $! ? "Cannot execute rev-list: $!" : "rev-list exited with status: $?";
155 return $revlist;
156 }
158 # append the given commit hashes to the state file
159 sub save_commits($)
160 {
161 my $commits = shift;
163 open STATE, ">>", $state_file or die "Cannot open $state_file: $!";
164 flock STATE, LOCK_EX or die "Cannot lock $state_file";
165 print STATE "$_\n" for @$commits;
166 flock STATE, LOCK_UN or die "Cannot unlock $state_file";
167 close STATE or die "Cannot close $state_file: $!";
168 }
170 # for the given range, return the new hashes (and append them to the state file)
171 sub get_new_commits($$)
172 {
173 my ($old_sha1, $new_sha1) = @_;
174 my ($seen, @args);
175 my $newrevs = [];
177 @args = ( "^$old_sha1" ) unless $old_sha1 eq '0' x 40;
178 push @args, $new_sha1, @exclude_list;
180 my $revlist = git_rev_list(@args);
182 if (not defined $state_file or not -e $state_file)
183 {
184 save_commits(git_rev_list("--all", "--full-history")) if defined $state_file;
185 return $revlist;
186 }
188 open STATE, $state_file or die "Cannot open $state_file: $!";
189 flock STATE, LOCK_SH or die "Cannot lock $state_file";
190 while (<STATE>)
191 {
192 chomp;
193 die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
194 $seen->{$_} = 1;
195 }
196 flock STATE, LOCK_UN or die "Cannot unlock $state_file";
197 close STATE or die "Cannot close $state_file: $!";
199 # FIXME: if another git-notify process reads the $state_file at *this*
200 # point, that process might generate duplicates of our notifications.
202 save_commits($revlist);
204 foreach my $commit (@$revlist)
205 {
206 push @$newrevs, $commit unless $seen->{$commit};
207 }
208 return $newrevs;
209 }
211 # truncate the given string if it exceeds the specified number of characters
212 sub truncate_str($$)
213 {
214 my ($str, $max) = @_;
216 if (length($str) > $max)
217 {
218 $str = substr($str, 0, $max);
219 $str =~ s/\s+\S+$//;
220 $str .= " ...";
221 }
222 return $str;
223 }
225 # right-justify the left column of "left: right" elements, omit undefined elements
226 sub format_table(@)
227 {
228 my @lines = @_;
229 my @table;
230 my $max = 0;
232 foreach my $line (@lines)
233 {
234 next if not defined $line;
235 my $pos = index($line, ":");
237 $max = $pos if $pos > $max;
238 }
240 foreach my $line (@lines)
241 {
242 next if not defined $line;
243 my ($left, $right) = split(/: */, $line, 2);
245 push @table, (defined $left and defined $right)
246 ? sprintf("%*s: %s", $max + 1, $left, $right)
247 : $line;
248 }
249 return @table;
250 }
252 # format an integer date + timezone as string
253 # algorithm taken from git's date.c
254 sub format_date($$)
255 {
256 my ($time,$tz) = @_;
258 if ($tz < 0)
259 {
260 my $minutes = (-$tz / 100) * 60 + (-$tz % 100);
261 $time -= $minutes * 60;
262 }
263 else
264 {
265 my $minutes = ($tz / 100) * 60 + ($tz % 100);
266 $time += $minutes * 60;
267 }
268 return gmtime($time) . sprintf " %+05d", $tz;
269 }
271 # fetch a parameter from the git config file
272 sub git_config($)
273 {
274 my ($param) = @_;
276 open CONFIG, "-|" or exec "git", "config", $param;
277 my $ret = <CONFIG>;
278 chomp $ret if $ret;
279 close CONFIG or $ret = undef;
280 return $ret;
281 }
283 # parse command line options
284 sub parse_options()
285 {
286 while (@ARGV && $ARGV[0] =~ /^-/)
287 {
288 my $arg = shift @ARGV;
290 if ($arg eq '--') { last; }
291 elsif ($arg eq '-A') { $omit_author = 1; }
292 elsif ($arg eq '-C') { $show_committer = 1; }
293 elsif ($arg eq '-c') { $cia_project_name = shift @ARGV; }
294 elsif ($arg eq '-m') { $commitlist_address = shift @ARGV; }
295 elsif ($arg eq '-n') { $max_individual_notices = shift @ARGV; }
296 elsif ($arg eq '-r') { $repos_name = shift @ARGV; }
297 elsif ($arg eq '-s') { $max_diff_size = shift @ARGV; }
298 elsif ($arg eq '-T') { $emit_repo = 1; }
299 elsif ($arg eq '-t') { $state_file = shift @ARGV; }
300 elsif ($arg eq '-U') { $mode_mask = shift @ARGV; }
301 elsif ($arg eq '-u') { $gitweb_url = shift @ARGV; }
302 elsif ($arg eq '-i') { push @include_list, shift @ARGV; }
303 elsif ($arg eq '-x') { push @exclude_list, shift @ARGV; }
304 elsif ($arg eq '-X') { push @revlist_options, "--no-merges"; }
305 elsif ($arg eq '-z') { $abbreviate_url = 1; }
306 elsif ($arg eq '-d') { $debug++; }
307 else { usage(); }
308 }
309 if (@ARGV && $#ARGV != 2) { usage(); }
310 @exclude_list = map { "^$_"; } @exclude_list;
311 }
313 # send an email notification
314 sub mail_notification($$$@)
315 {
316 my ($name, $subject, $content_type, @text) = @_;
318 $subject = "[$repos_name] $subject" if $emit_repo;
319 $subject = encode("MIME-Q",$subject);
321 if ($debug)
322 {
323 binmode STDOUT, ":utf8";
324 print "---------------------\n";
325 print "To: $name\n";
326 print "Subject: $subject\n";
327 print "Content-Type: $content_type\n";
328 print "\n", join("\n", @text), "\n";
329 }
330 else
331 {
332 my $pid = open MAIL, "|-";
333 return unless defined $pid;
334 if (!$pid)
335 {
336 exec $mailer, "-s", $subject, "-a", "Content-Type: $content_type", $name or die "Cannot exec $mailer";
337 }
338 binmode MAIL, ":utf8";
339 print MAIL join("\n", @text), "\n";
340 close MAIL or warn $! ? "Cannot execute $mailer: $!" : "$mailer exited with status: $?";
341 }
342 }
344 # get the default repository name
345 sub get_repos_name()
346 {
347 my $dir = `git rev-parse --git-dir`;
348 chomp $dir;
349 my $repos = realpath($dir);
350 $repos =~ s/(.*?)((\.git\/)?\.git)$/$1/;
351 $repos =~ s/(.*)\/([^\/]+)\/?$/$2/;
352 return $repos;
353 }
355 # extract the information from a commit or tag object and return a hash containing the various fields
356 sub get_object_info($)
357 {
358 my $obj = shift;
359 my %info = ();
360 my @log = ();
361 my $do_log = 0;
363 $info{"encoding"} = "utf-8";
365 open TYPE, "-|" or exec "git", "cat-file", "-t", $obj or die "cannot run git-cat-file";
366 my $type = <TYPE>;
367 chomp $type;
368 close TYPE or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
370 open OBJ, "-|" or exec "git", "cat-file", $type, $obj or die "cannot run git-cat-file";
371 while (<OBJ>)
372 {
373 chomp;
374 if ($do_log)
375 {
376 last if /^-----BEGIN PGP SIGNATURE-----/;
377 push @log, $_;
378 }
379 elsif (/^(author|committer|tagger) ((.*) (<.*>)) (\d+) ([+-]\d+)$/)
380 {
381 $info{$1} = $2;
382 $info{$1 . "_name"} = $3;
383 $info{$1 . "_email"} = $4;
384 $info{$1 . "_date"} = $5;
385 $info{$1 . "_tz"} = $6;
386 }
387 elsif (/^tag (.+)/)
388 {
389 $info{"tag"} = $1;
390 }
391 elsif (/^encoding (.+)/)
392 {
393 $info{"encoding"} = $1;
394 }
395 elsif (/^$/) { $do_log = 1; }
396 }
397 close OBJ or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
399 $info{"type"} = $type;
400 $info{"log"} = \@log;
401 return %info;
402 }
404 # send a ref change notice to a mailing list
405 sub send_ref_notice($$@)
406 {
407 my ($ref, $action, @notice) = @_;
408 my ($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/);
410 $reftype =~ s/^head$/branch/;
412 @notice = (format_table(
413 "Module: $repos_name",
414 ($reftype eq "tag" ? "Tag:" : "Branch:") . $refname,
415 @notice,
416 ($action ne "removed" and $gitweb_url)
417 ? "URL: $gitweb_url/?a=shortlog;h=$ref" : undef),
418 "",
419 "The $refname $reftype has been $action.");
421 mail_notification($commitlist_address, "$refname $reftype $action",
422 "text/plain; charset=us-ascii", @notice);
423 }
425 # send a commit notice to a mailing list
426 sub send_commit_notice($$)
427 {
428 my ($ref,$obj) = @_;
429 my %info = get_object_info($obj);
430 my @notice = ();
431 my ($url,$subject,$obj_string);
433 if ($gitweb_url)
434 {
435 if ($abbreviate_url)
436 {
437 open REVPARSE, "-|" or exec "git", "rev-parse", "--short", $obj or die "cannot exec git-rev-parse";
438 $obj_string = <REVPARSE>;
439 chomp $obj_string if defined $obj_string;
440 close REVPARSE or die $! ? "Cannot execute rev-parse: $!" : "rev-parse exited with status: $?";
441 }
442 $obj_string = $obj if not defined $obj_string;
443 $url = "$gitweb_url/?a=$info{type};h=$obj_string";
444 }
446 if ($info{"type"} eq "tag")
447 {
448 push @notice, format_table(
449 "Module: $repos_name",
450 "Branch: $ref",
451 "Tag: $obj",
452 "Tagger:" . $info{"tagger"},
453 "Date:" . format_date($info{"tagger_date"},$info{"tagger_tz"}),
454 $url ? "URL: $url" : undef),
455 "",
456 join "\n", @{$info{"log"}};
458 $subject = "Tag " . $info{"tag"} . ": ";
459 $subject .= $info{"tagger_name"} . ": " unless $omit_author;
460 }
461 else
462 {
463 push @notice, format_table(
464 "Module: $repos_name",
465 "Branch: $ref",
466 "Commit: $obj",
467 "Author:" . $info{"author"},
468 $show_committer && $info{"committer"} ne $info{"author"} ? "Committer:" . $info{"committer"} : undef,
469 "Date:" . format_date($info{"author_date"},$info{"author_tz"}),
470 $url ? "URL: $url" : undef),
471 "",
472 @{$info{"log"}},
473 "",
474 "---",
475 "";
477 open STAT, "-|" or exec "git", "diff-tree", "--stat", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
478 push @notice, join("", <STAT>);
479 close STAT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
481 open DIFF, "-|" or exec "git", "diff-tree", "-p", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
482 my $diff = join("", <DIFF>);
483 close DIFF or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
485 if (($max_diff_size == -1) || (length($diff) < $max_diff_size))
486 {
487 push @notice, $diff;
488 }
489 else
490 {
491 push @notice, "Diff: $gitweb_url/?a=commitdiff;h=$obj_string" if $gitweb_url;
492 }
493 $subject = $info{"author_name"} . ": " unless $omit_author;
494 }
496 $subject .= truncate_str(${$info{"log"}}[0],50);
497 $_ = decode($info{"encoding"}, $_) for @notice;
498 mail_notification($commitlist_address, $subject, "text/plain; charset=UTF-8", @notice);
499 }
501 # send a commit notice to the CIA server
502 sub send_cia_notice($$)
503 {
504 my ($ref,$commit) = @_;
505 my %info = get_object_info($commit);
506 my @cia_text = ();
508 return if $info{"type"} ne "commit";
510 push @cia_text,
511 "<message>",
512 " <generator>",
513 " <name>git-notify script for CIA</name>",
514 " </generator>",
515 " <source>",
516 " <project>" . xml_escape($cia_project_name) . "</project>",
517 " <module>" . xml_escape($repos_name) . "</module>",
518 " <branch>" . xml_escape($ref). "</branch>",
519 " </source>",
520 " <body>",
521 " <commit>",
522 " <revision>" . substr($commit,0,10) . "</revision>",
523 " <author>" . xml_escape($info{"author"}) . "</author>",
524 " <log>" . xml_escape(join "\n", @{$info{"log"}}) . "</log>",
525 " <files>";
527 open COMMIT, "-|" or exec "git", "diff-tree", "--name-status", "-r", "-M", $commit or die "cannot run git-diff-tree";
528 while (<COMMIT>)
529 {
530 chomp;
531 if (/^([AMD])\t(.*)$/)
532 {
533 my ($action, $file) = ($1, $2);
534 my %actions = ( "A" => "add", "M" => "modify", "D" => "remove" );
535 next unless defined $actions{$action};
536 push @cia_text, " <file action=\"$actions{$action}\">" . xml_escape($file) . "</file>";
537 }
538 elsif (/^R\d+\t(.*)\t(.*)$/)
539 {
540 my ($old, $new) = ($1, $2);
541 push @cia_text, " <file action=\"rename\" to=\"" . xml_escape($new) . "\">" . xml_escape($old) . "</file>";
542 }
543 }
544 close COMMIT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
546 push @cia_text,
547 " </files>",
548 $gitweb_url ? " <url>" . xml_escape("$gitweb_url/?a=commit;h=$commit") . "</url>" : "",
549 " </commit>",
550 " </body>",
551 " <timestamp>" . $info{"author_date"} . "</timestamp>",
552 "</message>";
554 mail_notification($cia_address, "DeliverXML", "text/xml", @cia_text);
555 }
557 # send a global commit notice when there are too many commits for individual mails
558 sub send_global_notice($$$)
559 {
560 my ($ref, $old_sha1, $new_sha1) = @_;
561 my $notice = git_rev_list("--pretty", "^$old_sha1", "$new_sha1", @exclude_list);
563 foreach my $rev (@$notice)
564 {
565 $rev =~ s/^commit /URL: $gitweb_url\/?a=commit;h=/ if $gitweb_url;
566 }
568 mail_notification($commitlist_address, "New commits on branch $ref", "text/plain; charset=UTF-8", @$notice);
569 }
571 # send all the notices
572 sub send_all_notices($$$)
573 {
574 my ($old_sha1, $new_sha1, $ref) = @_;
575 my ($reftype, $refname, $action, @notice);
577 return if ($ref =~ /^refs\/remotes\//
578 or (@include_list && !grep {$_ eq $ref} @include_list));
579 die "The name \"$ref\" doesn't sound like a local branch or tag"
580 if not (($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/));
582 if ($new_sha1 eq '0' x 40)
583 {
584 $action = "removed";
585 @notice = ( "Old SHA1: $old_sha1" );
586 }
587 elsif ($old_sha1 eq '0' x 40)
588 {
589 $action = "created";
590 @notice = ( "SHA1: $new_sha1" );
591 }
592 elsif ($reftype eq "tag")
593 {
594 $action = "updated";
595 @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
596 }
597 elsif (not grep( $_ eq $old_sha1, @{ git_rev_list( $new_sha1, "--full-history" ) } ))
598 {
599 $action = "rewritten";
600 @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
601 }
603 send_ref_notice( $ref, $action, @notice ) if ($commitlist_address and $action);
605 unless ($reftype eq "tag" or $new_sha1 eq '0' x 40)
606 {
607 my $commits = get_new_commits ( $old_sha1, $new_sha1 );
609 if (@$commits > $max_individual_notices)
610 {
611 send_global_notice( $refname, $old_sha1, $new_sha1 ) if $commitlist_address;
612 }
613 elsif (@$commits > 0)
614 {
615 foreach my $commit (@$commits)
616 {
617 send_commit_notice( $refname, $commit ) if $commitlist_address;
618 send_cia_notice( $refname, $commit ) if $cia_project_name;
619 }
620 }
621 elsif ($commitlist_address)
622 {
623 @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
624 send_ref_notice( $ref, "modified", @notice );
625 }
626 }
627 }
629 parse_options();
631 umask( $mode_mask );
633 # append repository path to URL
634 $gitweb_url .= "/$repos_name.git" if $gitweb_url;
636 if (@ARGV)
637 {
638 send_all_notices( $ARGV[0], $ARGV[1], $ARGV[2] );
639 }
640 else # read them from stdin
641 {
642 while (<>)
643 {
644 chomp;
645 if (/^([0-9a-f]{40}) ([0-9a-f]{40}) (.*)$/) { send_all_notices( $1, $2, $3 ); }
646 }
647 }
649 exit 0;