git-notify 17 KB

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