git-notify 19 KB

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