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