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