git-notify 18 KB

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