ebede1a4f69041864a1876adf3e2eaf463761e3a
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 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 OBJ, "-|" or exec "git", "cat-file", "commit", $obj or die "cannot run git-cat-file";
339 while (<OBJ>)
340 {
341 chomp;
342 if ($do_log) { push @log, $_; }
343 elsif (/^$/) { $do_log = 1; }
344 elsif (/^encoding (.+)/) { $info{"encoding"} = $1; }
345 elsif (/^(author|committer) ((.*) (<.*>)) (\d+) ([+-]\d+)$/)
346 {
347 $info{$1} = $2;
348 $info{$1 . "_name"} = $3;
349 $info{$1 . "_email"} = $4;
350 $info{$1 . "_date"} = $5;
351 $info{$1 . "_tz"} = $6;
352 }
353 }
354 close OBJ or die $! ? "Cannot execute cat-file: $!" : "cat-file exited with status: $?";
356 $info{"log"} = \@log;
357 return %info;
358 }
360 # send a ref change notice to a mailing list
361 sub send_ref_notice($$@)
362 {
363 my ($ref, $action, @notice) = @_;
364 my ($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/);
366 $reftype =~ s/^head$/branch/;
368 @notice = (format_table(
369 "Module: $repos_name",
370 ($reftype eq "tag" ? "Tag:" : "Branch:") . $refname,
371 @notice,
372 ($action ne "removed" and $gitweb_url)
373 ? "URL: $gitweb_url/?a=shortlog;h=$ref" : undef),
374 "",
375 "The $refname $reftype has been $action.");
377 mail_notification($commitlist_address, "$refname $reftype $action",
378 "text/plain; charset=us-ascii", @notice);
379 $sent_notices++;
380 }
382 # send a commit notice to a mailing list
383 sub send_commit_notice($$)
384 {
385 my ($ref,$obj) = @_;
386 my %info = get_object_info($obj);
387 my @notice = ();
388 my $url;
390 open DIFF, "-|" or exec "git", "diff-tree", "-p", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
391 my $diff = join("", <DIFF>);
392 close DIFF or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
394 return if length($diff) == 0;
396 if ($gitweb_url)
397 {
398 open REVPARSE, "-|" or exec "git", "rev-parse", "--short", $obj or die "cannot exec git-rev-parse";
399 my $short_obj = <REVPARSE>;
400 close REVPARSE or die $! ? "Cannot execute rev-parse: $!" : "rev-parse exited with status: $?";
402 $short_obj = $obj if not defined $short_obj;
403 chomp $short_obj;
404 $url = "$gitweb_url/?a=commit;h=$short_obj";
405 }
407 push @notice, format_table(
408 "Module: $repos_name",
409 "Branch: $ref",
410 "Commit: $obj",
411 "Author:" . $info{"author"},
412 $info{"committer"} ne $info{"author"} ? "Committer:" . $info{"committer"} : undef,
413 "Date:" . format_date($info{"author_date"},$info{"author_tz"}),
414 $url ? "URL: $url" : undef),
415 "",
416 @{$info{"log"}},
417 "",
418 "---",
419 "";
421 open STAT, "-|" or exec "git", "diff-tree", "--stat", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
422 push @notice, join("", <STAT>);
423 close STAT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
425 if (($max_diff_size == -1) || (length($diff) < $max_diff_size))
426 {
427 push @notice, $diff;
428 }
429 else
430 {
431 push @notice, "Diff: $gitweb_url/?a=commitdiff;h=$obj" if $gitweb_url;
432 }
434 $_ = decode($info{"encoding"}, $_) for @notice;
436 mail_notification($commitlist_address,
437 $info{"author_name"} . ": " . truncate_str(${$info{"log"}}[0], 50),
438 "text/plain; charset=UTF-8", @notice);
439 $sent_notices++;
440 }
442 # send a commit notice to the CIA server
443 sub send_cia_notice($$)
444 {
445 my ($ref,$commit) = @_;
446 my %info = get_object_info($commit);
447 my @cia_text = ();
449 push @cia_text,
450 "<message>",
451 " <generator>",
452 " <name>git-notify script for CIA</name>",
453 " </generator>",
454 " <source>",
455 " <project>" . xml_escape($cia_project_name) . "</project>",
456 " <module>" . xml_escape($repos_name) . "</module>",
457 " <branch>" . xml_escape($ref). "</branch>",
458 " </source>",
459 " <body>",
460 " <commit>",
461 " <revision>" . substr($commit,0,10) . "</revision>",
462 " <author>" . xml_escape($info{"author"}) . "</author>",
463 " <log>" . xml_escape(join "\n", @{$info{"log"}}) . "</log>",
464 " <files>";
466 open COMMIT, "-|" or exec "git", "diff-tree", "--name-status", "-r", "-M", $commit or die "cannot run git-diff-tree";
467 while (<COMMIT>)
468 {
469 chomp;
470 if (/^([AMD])\t(.*)$/)
471 {
472 my ($action, $file) = ($1, $2);
473 my %actions = ( "A" => "add", "M" => "modify", "D" => "remove" );
474 next unless defined $actions{$action};
475 push @cia_text, " <file action=\"$actions{$action}\">" . xml_escape($file) . "</file>";
476 }
477 elsif (/^R\d+\t(.*)\t(.*)$/)
478 {
479 my ($old, $new) = ($1, $2);
480 push @cia_text, " <file action=\"rename\" to=\"" . xml_escape($new) . "\">" . xml_escape($old) . "</file>";
481 }
482 }
483 close COMMIT or die $! ? "Cannot execute diff-tree: $!" : "diff-tree exited with status: $?";
485 push @cia_text,
486 " </files>",
487 $gitweb_url ? " <url>" . xml_escape("$gitweb_url/?a=commit;h=$commit") . "</url>" : "",
488 " </commit>",
489 " </body>",
490 " <timestamp>" . $info{"author_date"} . "</timestamp>",
491 "</message>";
493 mail_notification($cia_address, "DeliverXML", "text/xml", @cia_text);
494 }
496 # send a global commit notice when there are too many commits for individual mails
497 sub send_global_notice($$$)
498 {
499 my ($ref, $old_sha1, $new_sha1) = @_;
500 my $notice = git_rev_list("--pretty", "^$old_sha1", "$new_sha1", @exclude_list);
502 foreach my $rev (@$notice)
503 {
504 $rev =~ s/^commit /URL: $gitweb_url\/?a=commit;h=/ if $gitweb_url;
505 }
507 mail_notification($commitlist_address, "New commits on branch $ref", "text/plain; charset=UTF-8", @$notice);
508 $sent_notices++;
509 }
511 # send all the notices
512 sub send_all_notices($$$)
513 {
514 my ($old_sha1, $new_sha1, $ref) = @_;
515 my ($reftype, $refname, $action, @notice);
517 return if ($ref =~ /^refs\/remotes\//
518 or (@include_list && !grep {$_ eq $ref} @include_list));
519 die "The name \"$ref\" doesn't sound like a local branch or tag"
520 if not (($reftype, $refname) = ($ref =~ /^refs\/(head|tag)s\/(.+)/));
522 if ($new_sha1 eq '0' x 40)
523 {
524 $action = "removed";
525 @notice = ( "Old SHA1: $old_sha1" );
526 }
527 elsif ($old_sha1 eq '0' x 40)
528 {
529 $action = "created";
530 @notice = ( "SHA1: $new_sha1" );
531 }
532 elsif ($reftype eq "tag")
533 {
534 $action = "updated";
535 @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
536 }
537 elsif (not grep( $_ eq $old_sha1, @{ git_rev_list( $new_sha1, "--full-history" ) } ))
538 {
539 $action = "rewritten";
540 @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
541 }
543 send_ref_notice( $ref, $action, @notice ) if ($commitlist_address and $action);
545 unless ($reftype eq "tag" or $new_sha1 eq '0' x 40)
546 {
547 my $commits = get_new_commits ( $old_sha1, $new_sha1 );
549 if (@$commits > $max_individual_notices)
550 {
551 send_global_notice( $refname, $old_sha1, $new_sha1 ) if $commitlist_address;
552 }
553 else
554 {
555 foreach my $commit (@$commits)
556 {
557 send_commit_notice( $refname, $commit ) if $commitlist_address;
558 send_cia_notice( $refname, $commit ) if $cia_project_name;
559 }
560 }
561 if ($sent_notices == 0 and $commitlist_address)
562 {
563 @notice = ( "Old SHA1: $old_sha1", "New SHA1: $new_sha1" );
564 send_ref_notice( $ref, "modified", @notice );
565 }
566 }
567 }
569 parse_options();
571 umask( $mode_mask );
573 # append repository path to URL
574 $gitweb_url .= "/$repos_name.git" if $gitweb_url;
576 if (@ARGV)
577 {
578 send_all_notices( $ARGV[0], $ARGV[1], $ARGV[2] );
579 }
580 else # read them from stdin
581 {
582 while (<>)
583 {
584 chomp;
585 if (/^([0-9a-f]{40}) ([0-9a-f]{40}) (.*)$/) { send_all_notices( $1, $2, $3 ); }
586 }
587 }
589 exit 0;