dc843efd88d8ccacec5edc53e6eb6d77f5c1c294
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 # return the type of the given object
356 sub get_object_type($)
357 {
358 my $obj = shift;
360 open TYPE, "-|" or exec "git", "cat-file", "-t", $obj or die "cannot run git-cat-file";
361 my $type = <TYPE>;
362 chomp $type;
363 close TYPE or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
364 return $type;
365 }
367 # extract the information from a commit or tag object and return a hash containing the various fields
368 sub get_object_info($)
369 {
370 my $obj = shift;
371 my %info = ();
372 my @log = ();
373 my $do_log = 0;
375 $info{"encoding"} = "utf-8";
377 my $type = get_object_type($obj);
379 open OBJ, "-|" or exec "git", "cat-file", $type, $obj or die "cannot run git-cat-file";
380 while (<OBJ>)
381 {
382 chomp;
383 if ($do_log)
384 {
385 last if /^-----BEGIN PGP SIGNATURE-----/;
386 push @log, $_;
387 }
388 elsif (/^(author|committer|tagger) ((.*) (<.*>)) (\d+) ([+-]\d+)$/)
389 {
390 $info{$1} = $2;
391 $info{$1 . "_name"} = $3;
392 $info{$1 . "_email"} = $4;
393 $info{$1 . "_date"} = $5;
394 $info{$1 . "_tz"} = $6;
395 }
396 elsif (/^tag (.+)/)
397 {
398 $info{"tag"} = $1;
399 }
400 elsif (/^encoding (.+)/)
401 {
402 $info{"encoding"} = $1;
403 }
404 elsif (/^$/) { $do_log = 1; }
405 }
406 close OBJ or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
408 $info{"type"} = $type;
409 $info{"log"} = \@log;
410 return %info;
411 }
413 # send a ref change notice to a mailing list
414 sub send_ref_notice($$@)
415 {
416 my ($ref, $action, @notice) = @_;
417 my ($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/);
419 $reftype =~ s/^head$/branch/;
421 @notice = (format_table(
422 "Module: $repos_name",
423 ($reftype eq "tag" ? "Tag:" : "Branch:") . $refname,
424 @notice,
425 ($action ne "removed" and $gitweb_url)
426 ? "URL: $gitweb_url/?a=shortlog;h=$ref" : undef),
427 "",
428 "The $refname $reftype has been $action.");
430 mail_notification($commitlist_address, "$refname $reftype $action",
431 "text/plain; charset=us-ascii", @notice);
432 }
434 # send a commit notice to a mailing list
435 sub send_commit_notice($$)
436 {
437 my ($ref,$obj) = @_;
438 my %info = get_object_info($obj);
439 my @notice = ();
440 my ($url,$subject,$obj_string);
442 if ($gitweb_url)
443 {
444 if ($abbreviate_url)
445 {
446 open REVPARSE, "-|" or exec "git", "rev-parse", "--short", $obj or die "cannot exec git-rev-parse";
447 $obj_string = <REVPARSE>;
448 chomp $obj_string if defined $obj_string;
449 close REVPARSE or die $! ? "Cannot execute rev-parse: $!" : "rev-parse exited with status: $?";
450 }
451 $obj_string = $obj if not defined $obj_string;
452 $url = "$gitweb_url/?a=$info{type};h=$obj_string";
453 }
455 if ($info{"type"} eq "tag")
456 {
457 push @notice, format_table(
458 "Module: $repos_name",
459 "Branch: $ref",
460 "Tag: $obj",
461 "Tagger:" . $info{"tagger"},
462 "Date:" . format_date($info{"tagger_date"},$info{"tagger_tz"}),
463 $url ? "URL: $url" : undef),
464 "",
465 join "\n", @{$info{"log"}};
467 $subject = "Tag " . $info{"tag"} . ": ";
468 $subject .= $info{"tagger_name"} . ": " unless $omit_author;
469 }
470 else
471 {
472 push @notice, format_table(
473 "Module: $repos_name",
474 "Branch: $ref",
475 "Commit: $obj",
476 "Author:" . $info{"author"},
477 $show_committer && $info{"committer"} ne $info{"author"} ? "Committer:" . $info{"committer"} : undef,
478 "Date:" . format_date($info{"author_date"},$info{"author_tz"}),
479 $url ? "URL: $url" : undef),
480 "",
481 @{$info{"log"}},
482 "",
483 "---",
484 "";
486 open STAT, "-|" or exec "git", "diff-tree", "--stat", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
487 push @notice, join("", <STAT>);
488 close STAT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
490 open DIFF, "-|" or exec "git", "diff-tree", "-p", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
491 my $diff = join("", <DIFF>);
492 close DIFF or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
494 if (($max_diff_size == -1) || (length($diff) < $max_diff_size))
495 {
496 push @notice, $diff;
497 }
498 else
499 {
500 push @notice, "Diff: $gitweb_url/?a=commitdiff;h=$obj_string" if $gitweb_url;
501 }
502 $subject = $info{"author_name"} . ": " unless $omit_author;
503 }
505 $subject .= truncate_str(${$info{"log"}}[0],50);
506 $_ = decode($info{"encoding"}, $_) for @notice;
507 mail_notification($commitlist_address, $subject, "text/plain; charset=UTF-8", @notice);
508 }
510 # send a commit notice to the CIA server
511 sub send_cia_notice($$)
512 {
513 my ($ref,$commit) = @_;
514 my %info = get_object_info($commit);
515 my @cia_text = ();
517 return if $info{"type"} ne "commit";
519 push @cia_text,
520 "<message>",
521 " <generator>",
522 " <name>git-notify script for CIA</name>",
523 " </generator>",
524 " <source>",
525 " <project>" . xml_escape($cia_project_name) . "</project>",
526 " <module>" . xml_escape($repos_name) . "</module>",
527 " <branch>" . xml_escape($ref). "</branch>",
528 " </source>",
529 " <body>",
530 " <commit>",
531 " <revision>" . substr($commit,0,10) . "</revision>",
532 " <author>" . xml_escape($info{"author"}) . "</author>",
533 " <log>" . xml_escape(join "\n", @{$info{"log"}}) . "</log>",
534 " <files>";
536 open COMMIT, "-|" or exec "git", "diff-tree", "--name-status", "-r", "-M", $commit or die "cannot run git-diff-tree";
537 while (<COMMIT>)
538 {
539 chomp;
540 if (/^([AMD])\t(.*)$/)
541 {
542 my ($action, $file) = ($1, $2);
543 my %actions = ( "A" => "add", "M" => "modify", "D" => "remove" );
544 next unless defined $actions{$action};
545 push @cia_text, " <file action=\"$actions{$action}\">" . xml_escape($file) . "</file>";
546 }
547 elsif (/^R\d+\t(.*)\t(.*)$/)
548 {
549 my ($old, $new) = ($1, $2);
550 push @cia_text, " <file action=\"rename\" to=\"" . xml_escape($new) . "\">" . xml_escape($old) . "</file>";
551 }
552 }
553 close COMMIT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
555 push @cia_text,
556 " </files>",
557 $gitweb_url ? " <url>" . xml_escape("$gitweb_url/?a=commit;h=$commit") . "</url>" : "",
558 " </commit>",
559 " </body>",
560 " <timestamp>" . $info{"author_date"} . "</timestamp>",
561 "</message>";
563 mail_notification($cia_address, "DeliverXML", "text/xml", @cia_text);
564 }
566 # send a global commit notice when there are too many commits for individual mails
567 sub send_global_notice($$$)
568 {
569 my ($ref, $old_sha1, $new_sha1) = @_;
570 my $notice = git_rev_list("--pretty", "^$old_sha1", "$new_sha1", @exclude_list);
572 foreach my $rev (@$notice)
573 {
574 $rev =~ s/^commit /URL: $gitweb_url\/?a=commit;h=/ if $gitweb_url;
575 }
577 mail_notification($commitlist_address, "New commits on branch $ref", "text/plain; charset=UTF-8", @$notice);
578 }
580 # send all the notices
581 sub send_all_notices($$$)
582 {
583 my ($old_sha1, $new_sha1, $ref) = @_;
584 my ($reftype, $refname, $tagtype, $action, @notice);
586 return if ($ref =~ /^refs\/remotes\//
587 or (@include_list && !grep {$_ eq $ref} @include_list));
588 die "The name \"$ref\" doesn't sound like a local branch or tag"
589 if not (($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/));
591 if ($reftype eq "tag")
592 {
593 $tagtype = get_object_type($ref) eq "tag" ? "annotated" : "lightweight";
594 }
596 if ($new_sha1 eq '0' x 40)
597 {
598 $action = "removed";
599 @notice = ( "Old SHA1: $old_sha1" );
600 }
601 elsif ($old_sha1 eq '0' x 40)
602 {
603 if ($reftype eq "tag" and $tagtype eq "annotated")
604 {
605 send_commit_notice( $refname, $new_sha1 ) if $commitlist_address;
606 return;
607 }
608 $action = "created";
609 @notice = ( "SHA1: $new_sha1" );
610 }
611 elsif ($reftype eq "tag")
612 {
613 $action = "updated";
614 @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
615 }
616 elsif (not grep( $_ eq $old_sha1, @{ git_rev_list( $new_sha1, "--full-history" ) } ))
617 {
618 $action = "rewritten";
619 @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
620 }
622 send_ref_notice( $ref, $action, @notice ) if ($commitlist_address and $action);
624 unless ($reftype eq "tag" or $new_sha1 eq '0' x 40)
625 {
626 my $commits = get_new_commits ( $old_sha1, $new_sha1 );
628 if (@$commits > $max_individual_notices)
629 {
630 send_global_notice( $refname, $old_sha1, $new_sha1 ) if $commitlist_address;
631 }
632 elsif (@$commits > 0)
633 {
634 foreach my $commit (@$commits)
635 {
636 send_commit_notice( $refname, $commit ) if $commitlist_address;
637 send_cia_notice( $refname, $commit ) if $cia_project_name;
638 }
639 }
640 elsif ($commitlist_address)
641 {
642 @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
643 send_ref_notice( $ref, "modified", @notice );
644 }
645 }
646 }
648 parse_options();
650 umask( $mode_mask );
652 # append repository path to URL
653 $gitweb_url .= "/$repos_name.git" if $gitweb_url;
655 if (@ARGV)
656 {
657 send_all_notices( $ARGV[0], $ARGV[1], $ARGV[2] );
658 }
659 else # read them from stdin
660 {
661 while (<>)
662 {
663 chomp;
664 if (/^([0-9a-f]{40}) ([0-9a-f]{40}) (.*)$/) { send_all_notices( $1, $2, $3 ); }
665 }
666 }
668 exit 0;