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 # -c name Send CIA notifications under specified project name
19 # -m addr Send mail notifications to specified address
20 # -n max Set max number of individual mails to send
21 # -r name Set the git repository name
22 # -s bytes Set the maximum diff size in bytes (-1 for no limit)
23 # -t file Set the file to use for reading and saving state
24 # -U mask Set the umask for creating the state file
25 # -u url Set the URL to the gitweb browser
26 # -i branch If at least one -i is given, report only for specified branches
27 # -x branch Exclude changes to the specified branch from reports
28 # -X Exclude merge commits
29 #
31 use strict;
32 use Fcntl ':flock';
33 use Encode qw(encode decode);
34 use Cwd 'realpath';
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 # configuration parameters
52 # base URL of the gitweb repository browser (can be set with the -u option)
53 my $gitweb_url = git_config( "notify.baseurl" );
55 # default repository name (can be changed with the -r option)
56 my $repos_name = git_config( "notify.repository" ) || get_repos_name();
58 # max size of diffs in bytes (can be changed with the -s option)
59 my $max_diff_size = git_config( "notify.maxdiff" ) || 10000;
61 # address for mail notices (can be set with -m option)
62 my $commitlist_address = git_config( "notify.mail" );
64 # project name for CIA notices (can be set with -c option)
65 my $cia_project_name = git_config( "notify.cia" );
67 # max number of individual notices before falling back to a single global notice (can be set with -n option)
68 my $max_individual_notices = git_config( "notify.maxnotices" ) || 100;
70 # branches to include
71 my @include_list = split /\s+/, git_config( "notify.include" ) || "";
73 # branches to exclude
74 my @exclude_list = split /\s+/, git_config( "notify.exclude" ) || "";
76 # the state file we use (can be changed with the -t option)
77 my $state_file = git_config( "notify.statefile" ) || "/var/tmp/git-notify.state";
79 # umask for creating the state file (can be set with -U option)
80 my $mode_mask = git_config( "notify.umask" ) || 002;
82 # Extra options to git rev-list
83 my @revlist_options;
85 sub usage()
86 {
87 print "Usage: $0 [options] [--] old-sha1 new-sha1 refname\n";
88 print " -c name Send CIA notifications under specified project name\n";
89 print " -m addr Send mail notifications to specified address\n";
90 print " -n max Set max number of individual mails to send\n";
91 print " -r name Set the git repository name\n";
92 print " -s bytes Set the maximum diff size in bytes (-1 for no limit)\n";
93 print " -t file Set the file to use for reading and saving state\n";
94 print " -U mask Set the umask for creating the state file\n";
95 print " -u url Set the URL to the gitweb browser\n";
96 print " -i branch If at least one -i is given, report only for specified branches\n";
97 print " -x branch Exclude changes to the specified branch from reports\n";
98 print " -X Exclude merge commits\n";
99 exit 1;
100 }
102 sub xml_escape($)
103 {
104 my $str = shift;
105 $str =~ s/&/&/g;
106 $str =~ s/</</g;
107 $str =~ s/>/>/g;
108 my @chars = unpack "U*", $str;
109 $str = join "", map { ($_ > 127) ? sprintf "&#%u;", $_ : chr($_); } @chars;
110 return $str;
111 }
113 # execute git-rev-list(1) with the given parameters and return the output
114 sub git_rev_list(@)
115 {
116 my @args = @_;
117 my $revlist = [];
118 my $pid = open REVLIST, "-|";
120 die "Cannot open pipe: $!" if not defined $pid;
121 if (!$pid)
122 {
123 exec "git", "rev-list", @revlist_options, @args or die "Cannot execute rev-list: $!";
124 }
125 while (<REVLIST>)
126 {
127 chomp;
128 die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
129 push @$revlist, $_;
130 }
131 close REVLIST or die $! ? "Cannot execute rev-list: $!" : "rev-list exited with status: $?";
132 return $revlist;
133 }
135 # append the given commit hashes to the state file
136 sub save_commits($)
137 {
138 my $commits = shift;
140 open STATE, ">>", $state_file or die "Cannot open $state_file: $!";
141 flock STATE, LOCK_EX or die "Cannot lock $state_file";
142 print STATE "$_\n" for @$commits;
143 flock STATE, LOCK_UN or die "Cannot unlock $state_file";
144 close STATE or die "Cannot close $state_file: $!";
145 }
147 # for the given range, return the new hashes and append them to the state file
148 sub get_new_commits($$)
149 {
150 my ($old_sha1, $new_sha1) = @_;
151 my ($seen, @args);
152 my $newrevs = [];
154 @args = ( "^$old_sha1" ) unless $old_sha1 eq '0' x 40;
155 push @args, $new_sha1, @exclude_list;
157 my $revlist = git_rev_list(@args);
159 if (not -e $state_file) # initialize the state file with all hashes
160 {
161 save_commits(git_rev_list("--all", "--full-history"));
162 return $revlist;
163 }
165 open STATE, $state_file or die "Cannot open $state_file: $!";
166 flock STATE, LOCK_SH or die "Cannot lock $state_file";
167 while (<STATE>)
168 {
169 chomp;
170 die "Invalid commit: $_" if not /^[0-9a-f]{40}$/;
171 $seen->{$_} = 1;
172 }
173 flock STATE, LOCK_UN or die "Cannot unlock $state_file";
174 close STATE or die "Cannot close $state_file: $!";
176 # FIXME: if another git-notify process reads the $state_file at *this*
177 # point, that process might generate duplicates of our notifications.
179 save_commits($revlist);
181 foreach my $commit (@$revlist)
182 {
183 push @$newrevs, $commit unless $seen->{$commit};
184 }
185 return $newrevs;
186 }
188 # truncate the given string if it exceeds the specified number of characters
189 sub truncate_str($$)
190 {
191 my ($str, $max) = @_;
193 if (length($str) > $max)
194 {
195 $str = substr($str, 0, $max);
196 $str =~ s/\s+\S+$//;
197 $str .= " ...";
198 }
199 return $str;
200 }
202 # right-justify the left column of "left: right" elements, omit undefined elements
203 sub format_table(@)
204 {
205 my @lines = @_;
206 my @table;
207 my $max = 0;
209 foreach my $line (@lines)
210 {
211 next if not defined $line;
212 my $pos = index($line, ":");
214 $max = $pos if $pos > $max;
215 }
217 foreach my $line (@lines)
218 {
219 next if not defined $line;
220 my ($left, $right) = split(/: */, $line, 2);
222 push @table, (defined $left and defined $right)
223 ? sprintf("%*s: %s", $max + 1, $left, $right)
224 : $line;
225 }
226 return @table;
227 }
229 # format an integer date + timezone as string
230 # algorithm taken from git's date.c
231 sub format_date($$)
232 {
233 my ($time,$tz) = @_;
235 if ($tz < 0)
236 {
237 my $minutes = (-$tz / 100) * 60 + (-$tz % 100);
238 $time -= $minutes * 60;
239 }
240 else
241 {
242 my $minutes = ($tz / 100) * 60 + ($tz % 100);
243 $time += $minutes * 60;
244 }
245 return gmtime($time) . sprintf " %+05d", $tz;
246 }
248 # fetch a parameter from the git config file
249 sub git_config($)
250 {
251 my ($param) = @_;
253 open CONFIG, "-|" or exec "git", "config", $param;
254 my $ret = <CONFIG>;
255 chomp $ret if $ret;
256 close CONFIG or $ret = undef;
257 return $ret;
258 }
260 # parse command line options
261 sub parse_options()
262 {
263 while (@ARGV && $ARGV[0] =~ /^-/)
264 {
265 my $arg = shift @ARGV;
267 if ($arg eq '--') { last; }
268 elsif ($arg eq '-c') { $cia_project_name = shift @ARGV; }
269 elsif ($arg eq '-m') { $commitlist_address = shift @ARGV; }
270 elsif ($arg eq '-n') { $max_individual_notices = shift @ARGV; }
271 elsif ($arg eq '-r') { $repos_name = shift @ARGV; }
272 elsif ($arg eq '-s') { $max_diff_size = shift @ARGV; }
273 elsif ($arg eq '-t') { $state_file = shift @ARGV; }
274 elsif ($arg eq '-U') { $mode_mask = shift @ARGV; }
275 elsif ($arg eq '-u') { $gitweb_url = shift @ARGV; }
276 elsif ($arg eq '-i') { push @include_list, shift @ARGV; }
277 elsif ($arg eq '-x') { push @exclude_list, shift @ARGV; }
278 elsif ($arg eq '-X') { push @revlist_options, "--no-merges"; }
279 elsif ($arg eq '-d') { $debug++; }
280 else { usage(); }
281 }
282 if (@ARGV && $#ARGV != 2) { usage(); }
283 @exclude_list = map { "^$_"; } @exclude_list;
284 }
286 # send an email notification
287 sub mail_notification($$$@)
288 {
289 my ($name, $subject, $content_type, @text) = @_;
290 $subject = encode("MIME-Q",$subject);
291 if ($debug)
292 {
293 binmode STDOUT, ":utf8";
294 print "---------------------\n";
295 print "To: $name\n";
296 print "Subject: $subject\n";
297 print "Content-Type: $content_type\n";
298 print "\n", join("\n", @text), "\n";
299 }
300 else
301 {
302 my $pid = open MAIL, "|-";
303 return unless defined $pid;
304 if (!$pid)
305 {
306 exec $mailer, "-s", $subject, "-a", "Content-Type: $content_type", $name or die "Cannot exec $mailer";
307 }
308 binmode MAIL, ":utf8";
309 print MAIL join("\n", @text), "\n";
310 close MAIL or warn $! ? "Cannot execute $mailer: $!" : "$mailer exited with status: $?";
311 }
312 }
314 # get the default repository name
315 sub get_repos_name()
316 {
317 my $dir = `git rev-parse --git-dir`;
318 chomp $dir;
319 my $repos = realpath($dir);
320 $repos =~ s/(.*?)((\.git\/)?\.git)$/$1/;
321 $repos =~ s/(.*)\/([^\/]+)\/?$/$2/;
322 return $repos;
323 }
325 # extract the information from a commit or tag object and return a hash containing the various fields
326 sub get_object_info($)
327 {
328 my $obj = shift;
329 my %info = ();
330 my @log = ();
331 my $do_log = 0;
333 $info{"encoding"} = "utf-8";
335 open TYPE, "-|" or exec "git", "cat-file", "-t", $obj or die "cannot run git-cat-file";
336 my $type = <TYPE>;
337 chomp $type;
338 close TYPE or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
340 open OBJ, "-|" or exec "git", "cat-file", $type, $obj or die "cannot run git-cat-file";
341 while (<OBJ>)
342 {
343 chomp;
344 if ($do_log)
345 {
346 last if /^-----BEGIN PGP SIGNATURE-----/;
347 push @log, $_;
348 }
349 elsif (/^(author|committer|tagger) ((.*) (<.*>)) (\d+) ([+-]\d+)$/)
350 {
351 $info{$1} = $2;
352 $info{$1 . "_name"} = $3;
353 $info{$1 . "_email"} = $4;
354 $info{$1 . "_date"} = $5;
355 $info{$1 . "_tz"} = $6;
356 }
357 elsif (/^tag (.+)/)
358 {
359 $info{"tag"} = $1;
360 }
361 elsif (/^encoding (.+)/)
362 {
363 $info{"encoding"} = $1;
364 }
365 elsif (/^$/) { $do_log = 1; }
366 }
367 close OBJ or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
369 $info{"type"} = $type;
370 $info{"log"} = \@log;
371 return %info;
372 }
374 # send a ref change notice to a mailing list
375 sub send_ref_notice($$@)
376 {
377 my ($ref, $action, @notice) = @_;
378 my ($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/);
380 $reftype =~ s/^head$/branch/;
382 @notice = (format_table(
383 "Module: $repos_name",
384 ($reftype eq "tag" ? "Tag:" : "Branch:") . $refname,
385 @notice,
386 ($action ne "removed" and $gitweb_url)
387 ? "URL: $gitweb_url/?a=shortlog;h=$ref" : undef),
388 "",
389 "The $refname $reftype has been $action.");
391 mail_notification($commitlist_address, "$refname $reftype $action",
392 "text/plain; charset=us-ascii", @notice);
393 }
395 # send a commit notice to a mailing list
396 sub send_commit_notice($$)
397 {
398 my ($ref,$obj) = @_;
399 my %info = get_object_info($obj);
400 my @notice = ();
401 my ($url,$subject);
403 if ($gitweb_url)
404 {
405 open REVPARSE, "-|" or exec "git", "rev-parse", "--short", $obj or die "cannot exec git-rev-parse";
406 my $short_obj = <REVPARSE>;
407 close REVPARSE or die $! ? "Cannot execute rev-parse: $!" : "rev-parse exited with status: $?";
409 $short_obj = $obj if not defined $short_obj;
410 chomp $short_obj;
411 $url = "$gitweb_url/?a=$info{type};h=$short_obj";
412 }
414 if ($info{"type"} eq "tag")
415 {
416 push @notice, format_table(
417 "Module: $repos_name",
418 "Branch: $ref",
419 "Tag: $obj",
420 "Tagger:" . $info{"tagger"},
421 "Date:" . format_date($info{"tagger_date"},$info{"tagger_tz"}),
422 $url ? "URL: $url" : undef),
423 "",
424 join "\n", @{$info{"log"}};
426 $subject = "Tag " . $info{"tag"} . ": " . $info{"tagger_name"};
427 }
428 else
429 {
430 push @notice, format_table(
431 "Module: $repos_name",
432 "Branch: $ref",
433 "Commit: $obj",
434 "Author:" . $info{"author"},
435 $info{"committer"} ne $info{"author"} ? "Committer:" . $info{"committer"} : undef,
436 "Date:" . format_date($info{"author_date"},$info{"author_tz"}),
437 $url ? "URL: $url" : undef),
438 "",
439 @{$info{"log"}},
440 "",
441 "---",
442 "";
444 open STAT, "-|" or exec "git", "diff-tree", "--stat", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
445 push @notice, join("", <STAT>);
446 close STAT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
448 open DIFF, "-|" or exec "git", "diff-tree", "-p", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
449 my $diff = join("", <DIFF>);
450 close DIFF or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
452 if (($max_diff_size == -1) || (length($diff) < $max_diff_size))
453 {
454 push @notice, $diff;
455 }
456 else
457 {
458 push @notice, "Diff: $gitweb_url/?a=commitdiff;h=$obj" if $gitweb_url;
459 }
460 $subject = $info{"author_name"};
461 }
463 $subject .= ": " . truncate_str(${$info{"log"}}[0],50);
464 $_ = decode($info{"encoding"}, $_) for @notice;
465 mail_notification($commitlist_address, $subject, "text/plain; charset=UTF-8", @notice);
466 }
468 # send a commit notice to the CIA server
469 sub send_cia_notice($$)
470 {
471 my ($ref,$commit) = @_;
472 my %info = get_object_info($commit);
473 my @cia_text = ();
475 return if $info{"type"} ne "commit";
477 push @cia_text,
478 "<message>",
479 " <generator>",
480 " <name>git-notify script for CIA</name>",
481 " </generator>",
482 " <source>",
483 " <project>" . xml_escape($cia_project_name) . "</project>",
484 " <module>" . xml_escape($repos_name) . "</module>",
485 " <branch>" . xml_escape($ref). "</branch>",
486 " </source>",
487 " <body>",
488 " <commit>",
489 " <revision>" . substr($commit,0,10) . "</revision>",
490 " <author>" . xml_escape($info{"author"}) . "</author>",
491 " <log>" . xml_escape(join "\n", @{$info{"log"}}) . "</log>",
492 " <files>";
494 open COMMIT, "-|" or exec "git", "diff-tree", "--name-status", "-r", "-M", $commit or die "cannot run git-diff-tree";
495 while (<COMMIT>)
496 {
497 chomp;
498 if (/^([AMD])\t(.*)$/)
499 {
500 my ($action, $file) = ($1, $2);
501 my %actions = ( "A" => "add", "M" => "modify", "D" => "remove" );
502 next unless defined $actions{$action};
503 push @cia_text, " <file action=\"$actions{$action}\">" . xml_escape($file) . "</file>";
504 }
505 elsif (/^R\d+\t(.*)\t(.*)$/)
506 {
507 my ($old, $new) = ($1, $2);
508 push @cia_text, " <file action=\"rename\" to=\"" . xml_escape($new) . "\">" . xml_escape($old) . "</file>";
509 }
510 }
511 close COMMIT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
513 push @cia_text,
514 " </files>",
515 $gitweb_url ? " <url>" . xml_escape("$gitweb_url/?a=commit;h=$commit") . "</url>" : "",
516 " </commit>",
517 " </body>",
518 " <timestamp>" . $info{"author_date"} . "</timestamp>",
519 "</message>";
521 mail_notification($cia_address, "DeliverXML", "text/xml", @cia_text);
522 }
524 # send a global commit notice when there are too many commits for individual mails
525 sub send_global_notice($$$)
526 {
527 my ($ref, $old_sha1, $new_sha1) = @_;
528 my $notice = git_rev_list("--pretty", "^$old_sha1", "$new_sha1", @exclude_list);
530 foreach my $rev (@$notice)
531 {
532 $rev =~ s/^commit /URL: $gitweb_url\/?a=commit;h=/ if $gitweb_url;
533 }
535 mail_notification($commitlist_address, "New commits on branch $ref", "text/plain; charset=UTF-8", @$notice);
536 }
538 # send all the notices
539 sub send_all_notices($$$)
540 {
541 my ($old_sha1, $new_sha1, $ref) = @_;
542 my ($reftype, $refname, $action, @notice);
544 return if ($ref =~ /^refs\/remotes\//
545 or (@include_list && !grep {$_ eq $ref} @include_list));
546 die "The name \"$ref\" doesn't sound like a local branch or tag"
547 if not (($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/));
549 if ($new_sha1 eq '0' x 40)
550 {
551 $action = "removed";
552 @notice = ( "Old SHA1: $old_sha1" );
553 }
554 elsif ($old_sha1 eq '0' x 40)
555 {
556 $action = "created";
557 @notice = ( "SHA1: $new_sha1" );
558 }
559 elsif ($reftype eq "tag")
560 {
561 $action = "updated";
562 @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
563 }
564 elsif (not grep( $_ eq $old_sha1, @{ git_rev_list( $new_sha1, "--full-history" ) } ))
565 {
566 $action = "rewritten";
567 @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
568 }
570 send_ref_notice( $ref, $action, @notice ) if ($commitlist_address and $action);
572 unless ($reftype eq "tag" or $new_sha1 eq '0' x 40)
573 {
574 my $commits = get_new_commits ( $old_sha1, $new_sha1 );
576 if (@$commits > $max_individual_notices)
577 {
578 send_global_notice( $refname, $old_sha1, $new_sha1 ) if $commitlist_address;
579 }
580 elsif (@$commits > 0)
581 {
582 foreach my $commit (@$commits)
583 {
584 send_commit_notice( $refname, $commit ) if $commitlist_address;
585 send_cia_notice( $refname, $commit ) if $cia_project_name;
586 }
587 }
588 elsif ($commitlist_address)
589 {
590 @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
591 send_ref_notice( $ref, "modified", @notice );
592 }
593 }
594 }
596 parse_options();
598 umask( $mode_mask );
600 # append repository path to URL
601 $gitweb_url .= "/$repos_name.git" if $gitweb_url;
603 if (@ARGV)
604 {
605 send_all_notices( $ARGV[0], $ARGV[1], $ARGV[2] );
606 }
607 else # read them from stdin
608 {
609 while (<>)
610 {
611 chomp;
612 if (/^([0-9a-f]{40}) ([0-9a-f]{40}) (.*)$/) { send_all_notices( $1, $2, $3 ); }
613 }
614 }
616 exit 0;