summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/git.pm
blob: 222692eda6ad4dacb3c901e8ba53f4310c75c89d (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki::Plugin::git;
  3. use warnings;
  4. use strict;
  5. use IkiWiki;
  6. use Encode;
  7. use open qw{:utf8 :std};
  8. my $sha1_pattern = qr/[0-9a-fA-F]{40}/; # pattern to validate Git sha1sums
  9. my $dummy_commit_msg = 'dummy commit'; # message to skip in recent changes
  10. my $no_chdir=0;
  11. sub import {
  12. hook(type => "checkconfig", id => "git", call => \&checkconfig);
  13. hook(type => "getsetup", id => "git", call => \&getsetup);
  14. hook(type => "genwrapper", id => "git", call => \&genwrapper);
  15. hook(type => "rcs", id => "rcs_update", call => \&rcs_update);
  16. hook(type => "rcs", id => "rcs_prepedit", call => \&rcs_prepedit);
  17. hook(type => "rcs", id => "rcs_commit", call => \&rcs_commit);
  18. hook(type => "rcs", id => "rcs_commit_staged", call => \&rcs_commit_staged);
  19. hook(type => "rcs", id => "rcs_add", call => \&rcs_add);
  20. hook(type => "rcs", id => "rcs_remove", call => \&rcs_remove);
  21. hook(type => "rcs", id => "rcs_rename", call => \&rcs_rename);
  22. hook(type => "rcs", id => "rcs_recentchanges", call => \&rcs_recentchanges);
  23. hook(type => "rcs", id => "rcs_diff", call => \&rcs_diff);
  24. hook(type => "rcs", id => "rcs_getctime", call => \&rcs_getctime);
  25. hook(type => "rcs", id => "rcs_getmtime", call => \&rcs_getmtime);
  26. hook(type => "rcs", id => "rcs_receive", call => \&rcs_receive);
  27. }
  28. sub checkconfig () {
  29. if (! defined $config{gitorigin_branch}) {
  30. $config{gitorigin_branch}="origin";
  31. }
  32. if (! defined $config{gitmaster_branch}) {
  33. $config{gitmaster_branch}="master";
  34. }
  35. if (defined $config{git_wrapper} &&
  36. length $config{git_wrapper}) {
  37. push @{$config{wrappers}}, {
  38. wrapper => $config{git_wrapper},
  39. wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
  40. };
  41. }
  42. if (defined $config{git_test_receive_wrapper} &&
  43. length $config{git_test_receive_wrapper}) {
  44. push @{$config{wrappers}}, {
  45. test_receive => 1,
  46. wrapper => $config{git_test_receive_wrapper},
  47. wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
  48. };
  49. }
  50. # Avoid notes, parser does not handle and they only slow things down.
  51. $ENV{GIT_NOTES_REF}="";
  52. # Run receive test only if being called by the wrapper, and not
  53. # when generating same.
  54. if ($config{test_receive} && ! exists $config{wrapper}) {
  55. require IkiWiki::Receive;
  56. IkiWiki::Receive::test();
  57. }
  58. }
  59. sub getsetup () {
  60. return
  61. plugin => {
  62. safe => 0, # rcs plugin
  63. rebuild => undef,
  64. section => "rcs",
  65. },
  66. git_wrapper => {
  67. type => "string",
  68. example => "/git/wiki.git/hooks/post-update",
  69. description => "git hook to generate",
  70. safe => 0, # file
  71. rebuild => 0,
  72. },
  73. git_wrappermode => {
  74. type => "string",
  75. example => '06755',
  76. description => "mode for git_wrapper (can safely be made suid)",
  77. safe => 0,
  78. rebuild => 0,
  79. },
  80. git_test_receive_wrapper => {
  81. type => "string",
  82. example => "/git/wiki.git/hooks/pre-receive",
  83. description => "git pre-receive hook to generate",
  84. safe => 0, # file
  85. rebuild => 0,
  86. },
  87. untrusted_committers => {
  88. type => "string",
  89. example => [],
  90. description => "unix users whose commits should be checked by the pre-receive hook",
  91. safe => 0,
  92. rebuild => 0,
  93. },
  94. historyurl => {
  95. type => "string",
  96. example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]]",
  97. description => "gitweb url to show file history ([[file]] substituted)",
  98. safe => 1,
  99. rebuild => 1,
  100. },
  101. diffurl => {
  102. type => "string",
  103. example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=blobdiff;f=[[file]];h=[[sha1_to]];hp=[[sha1_from]];hb=[[sha1_commit]];hpb=[[sha1_parent]]",
  104. description => "gitweb url to show a diff ([[file]], [[sha1_to]], [[sha1_from]], [[sha1_commit]], and [[sha1_parent]] substituted)",
  105. safe => 1,
  106. rebuild => 1,
  107. },
  108. gitorigin_branch => {
  109. type => "string",
  110. example => "origin",
  111. description => "where to pull and push changes (set to empty string to disable)",
  112. safe => 0, # paranoia
  113. rebuild => 0,
  114. },
  115. gitmaster_branch => {
  116. type => "string",
  117. example => "master",
  118. description => "branch that the wiki is stored in",
  119. safe => 0, # paranoia
  120. rebuild => 0,
  121. },
  122. }
  123. sub genwrapper {
  124. if ($config{test_receive}) {
  125. require IkiWiki::Receive;
  126. return IkiWiki::Receive::genwrapper();
  127. }
  128. else {
  129. return "";
  130. }
  131. }
  132. sub safe_git (&@) {
  133. # Start a child process safely without resorting /bin/sh.
  134. # Return command output or success state (in scalar context).
  135. my ($error_handler, @cmdline) = @_;
  136. my $pid = open my $OUT, "-|";
  137. error("Cannot fork: $!") if !defined $pid;
  138. if (!$pid) {
  139. # In child.
  140. # Git commands want to be in wc.
  141. if (! $no_chdir) {
  142. chdir $config{srcdir}
  143. or error("Cannot chdir to $config{srcdir}: $!");
  144. }
  145. exec @cmdline or error("Cannot exec '@cmdline': $!");
  146. }
  147. # In parent.
  148. # git output is probably utf-8 encoded, but may contain
  149. # other encodings or invalidly encoded stuff. So do not rely
  150. # on the normal utf-8 IO layer, decode it by hand.
  151. binmode($OUT);
  152. my @lines;
  153. while (<$OUT>) {
  154. $_=decode_utf8($_, 0);
  155. chomp;
  156. push @lines, $_;
  157. }
  158. close $OUT;
  159. $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
  160. return wantarray ? @lines : ($? == 0);
  161. }
  162. # Convenient wrappers.
  163. sub run_or_die ($@) { safe_git(\&error, @_) }
  164. sub run_or_cry ($@) { safe_git(sub { warn @_ }, @_) }
  165. sub run_or_non ($@) { safe_git(undef, @_) }
  166. sub merge_past ($$$) {
  167. # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
  168. # Git merge commands work with the committed changes, except in the
  169. # implicit case of '-m' of git checkout(1). So we should invent a
  170. # kludge here. In principle, we need to create a throw-away branch
  171. # in preparing for the merge itself. Since branches are cheap (and
  172. # branching is fast), this shouldn't cost high.
  173. #
  174. # The main problem is the presence of _uncommitted_ local changes. One
  175. # possible approach to get rid of this situation could be that we first
  176. # make a temporary commit in the master branch and later restore the
  177. # initial state (this is possible since Git has the ability to undo a
  178. # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
  179. # as follows:
  180. #
  181. # - create a diff of HEAD:current-sha1
  182. # - dummy commit
  183. # - create a dummy branch and switch to it
  184. # - rewind to past (reset --hard to the current-sha1)
  185. # - apply the diff and commit
  186. # - switch to master and do the merge with the dummy branch
  187. # - make a soft reset (undo the last commit of master)
  188. #
  189. # The above method has some drawbacks: (1) it needs a redundant commit
  190. # just to get rid of local changes, (2) somewhat slow because of the
  191. # required system forks. Until someone points a more straight method
  192. # (which I would be grateful) I have implemented an alternative method.
  193. # In this approach, we hide all the modified files from Git by renaming
  194. # them (using the 'rename' builtin) and later restore those files in
  195. # the throw-away branch (that is, we put the files themselves instead
  196. # of applying a patch).
  197. my ($sha1, $file, $message) = @_;
  198. my @undo; # undo stack for cleanup in case of an error
  199. my $conflict; # file content with conflict markers
  200. eval {
  201. # Hide local changes from Git by renaming the modified file.
  202. # Relative paths must be converted to absolute for renaming.
  203. my ($target, $hidden) = (
  204. "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
  205. );
  206. rename($target, $hidden)
  207. or error("rename '$target' to '$hidden' failed: $!");
  208. # Ensure to restore the renamed file on error.
  209. push @undo, sub {
  210. return if ! -e "$hidden"; # already renamed
  211. rename($hidden, $target)
  212. or warn "rename '$hidden' to '$target' failed: $!";
  213. };
  214. my $branch = "throw_away_${sha1}"; # supposed to be unique
  215. # Create a throw-away branch and rewind backward.
  216. push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
  217. run_or_die('git', 'branch', $branch, $sha1);
  218. # Switch to throw-away branch for the merge operation.
  219. push @undo, sub {
  220. if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
  221. run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
  222. }
  223. };
  224. run_or_die('git', 'checkout', $branch);
  225. # Put the modified file in _this_ branch.
  226. rename($hidden, $target)
  227. or error("rename '$hidden' to '$target' failed: $!");
  228. # _Silently_ commit all modifications in the current branch.
  229. run_or_non('git', 'commit', '-m', $message, '-a');
  230. # ... and re-switch to master.
  231. run_or_die('git', 'checkout', $config{gitmaster_branch});
  232. # Attempt to merge without complaining.
  233. if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
  234. $conflict = readfile($target);
  235. run_or_die('git', 'reset', '--hard');
  236. }
  237. };
  238. my $failure = $@;
  239. # Process undo stack (in reverse order). By policy cleanup
  240. # actions should normally print a warning on failure.
  241. while (my $handle = pop @undo) {
  242. $handle->();
  243. }
  244. error("Git merge failed!\n$failure\n") if $failure;
  245. return $conflict;
  246. }
  247. {
  248. my $prefix;
  249. sub decode_git_file ($) {
  250. my $file=shift;
  251. # git does not output utf-8 filenames, but instead
  252. # double-quotes them with the utf-8 characters
  253. # escaped as \nnn\nnn.
  254. if ($file =~ m/^"(.*)"$/) {
  255. ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
  256. }
  257. # strip prefix if in a subdir
  258. if (! defined $prefix) {
  259. ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
  260. if (! defined $prefix) {
  261. $prefix="";
  262. }
  263. }
  264. $file =~ s/^\Q$prefix\E//;
  265. return decode("utf8", $file);
  266. }
  267. }
  268. sub parse_diff_tree ($) {
  269. # Parse the raw diff tree chunk and return the info hash.
  270. # See git-diff-tree(1) for the syntax.
  271. my $dt_ref = shift;
  272. # End of stream?
  273. return if !defined @{ $dt_ref } ||
  274. !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
  275. my %ci;
  276. # Header line.
  277. while (my $line = shift @{ $dt_ref }) {
  278. return if $line !~ m/^(.+) ($sha1_pattern)/;
  279. my $sha1 = $2;
  280. $ci{'sha1'} = $sha1;
  281. last;
  282. }
  283. # Identification lines for the commit.
  284. while (my $line = shift @{ $dt_ref }) {
  285. # Regexps are semi-stolen from gitweb.cgi.
  286. if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
  287. $ci{'tree'} = $1;
  288. }
  289. elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
  290. # XXX: collecting in reverse order
  291. push @{ $ci{'parents'} }, $1;
  292. }
  293. elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
  294. my ($who, $name, $epoch, $tz) =
  295. ($1, $2, $3, $4 );
  296. $ci{ $who } = $name;
  297. $ci{ "${who}_epoch" } = $epoch;
  298. $ci{ "${who}_tz" } = $tz;
  299. if ($name =~ m/^[^<]+\s+<([^@>]+)/) {
  300. $ci{"${who}_username"} = $1;
  301. }
  302. elsif ($name =~ m/^([^<]+)\s+<>$/) {
  303. $ci{"${who}_username"} = $1;
  304. }
  305. else {
  306. $ci{"${who}_username"} = $name;
  307. }
  308. }
  309. elsif ($line =~ m/^$/) {
  310. # Trailing empty line signals next section.
  311. last;
  312. }
  313. }
  314. debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
  315. if (defined $ci{'parents'}) {
  316. $ci{'parent'} = @{ $ci{'parents'} }[0];
  317. }
  318. else {
  319. $ci{'parent'} = 0 x 40;
  320. }
  321. # Commit message (optional).
  322. while ($dt_ref->[0] =~ /^ /) {
  323. my $line = shift @{ $dt_ref };
  324. $line =~ s/^ //;
  325. push @{ $ci{'comment'} }, $line;
  326. }
  327. shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
  328. # Modified files.
  329. while (my $line = shift @{ $dt_ref }) {
  330. if ($line =~ m{^
  331. (:+) # number of parents
  332. ([^\t]+)\t # modes, sha1, status
  333. (.*) # file names
  334. $}xo) {
  335. my $num_parents = length $1;
  336. my @tmp = split(" ", $2);
  337. my ($file, $file_to) = split("\t", $3);
  338. my @mode_from = splice(@tmp, 0, $num_parents);
  339. my $mode_to = shift(@tmp);
  340. my @sha1_from = splice(@tmp, 0, $num_parents);
  341. my $sha1_to = shift(@tmp);
  342. my $status = shift(@tmp);
  343. if (length $file) {
  344. push @{ $ci{'details'} }, {
  345. 'file' => decode_git_file($file),
  346. 'sha1_from' => $sha1_from[0],
  347. 'sha1_to' => $sha1_to,
  348. 'mode_from' => $mode_from[0],
  349. 'mode_to' => $mode_to,
  350. 'status' => $status,
  351. };
  352. }
  353. next;
  354. };
  355. last;
  356. }
  357. return \%ci;
  358. }
  359. sub git_commit_info ($;$) {
  360. # Return an array of commit info hashes of num commits
  361. # starting from the given sha1sum.
  362. my ($sha1, $num) = @_;
  363. my @opts;
  364. push @opts, "--max-count=$num" if defined $num;
  365. my @raw_lines = run_or_die('git', 'log', @opts,
  366. '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
  367. '-r', $sha1, '--', '.');
  368. my @ci;
  369. while (my $parsed = parse_diff_tree(\@raw_lines)) {
  370. push @ci, $parsed;
  371. }
  372. warn "Cannot parse commit info for '$sha1' commit" if !@ci;
  373. return wantarray ? @ci : $ci[0];
  374. }
  375. sub git_sha1 (;$) {
  376. # Return head sha1sum (of given file).
  377. my $file = shift || q{--};
  378. # Ignore error since a non-existing file might be given.
  379. my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
  380. '--', $file);
  381. if ($sha1) {
  382. ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
  383. }
  384. else {
  385. debug("Empty sha1sum for '$file'.");
  386. }
  387. return defined $sha1 ? $sha1 : q{};
  388. }
  389. sub rcs_update () {
  390. # Update working directory.
  391. if (length $config{gitorigin_branch}) {
  392. run_or_cry('git', 'pull', $config{gitorigin_branch});
  393. }
  394. }
  395. sub rcs_prepedit ($) {
  396. # Return the commit sha1sum of the file when editing begins.
  397. # This will be later used in rcs_commit if a merge is required.
  398. my ($file) = @_;
  399. return git_sha1($file);
  400. }
  401. sub rcs_commit ($$$;$$) {
  402. # Try to commit the page; returns undef on _success_ and
  403. # a version of the page with the rcs's conflict markers on
  404. # failure.
  405. my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
  406. # Check to see if the page has been changed by someone else since
  407. # rcs_prepedit was called.
  408. my $cur = git_sha1($file);
  409. my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
  410. if (defined $cur && defined $prev && $cur ne $prev) {
  411. my $conflict = merge_past($prev, $file, $dummy_commit_msg);
  412. return $conflict if defined $conflict;
  413. }
  414. rcs_add($file);
  415. return rcs_commit_staged($message, $user, $ipaddr);
  416. }
  417. sub rcs_commit_staged ($$$) {
  418. # Commits all staged changes. Changes can be staged using rcs_add,
  419. # rcs_remove, and rcs_rename.
  420. my ($message, $user, $ipaddr)=@_;
  421. # Set the commit author and email to the web committer.
  422. my %env=%ENV;
  423. if (defined $user || defined $ipaddr) {
  424. my $u=encode_utf8(defined $user ? $user : $ipaddr);
  425. $ENV{GIT_AUTHOR_NAME}=$u;
  426. $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
  427. }
  428. $message = IkiWiki::possibly_foolish_untaint($message);
  429. my @opts;
  430. if ($message !~ /\S/) {
  431. # Force git to allow empty commit messages.
  432. # (If this version of git supports it.)
  433. my ($version)=`git --version` =~ /git version (.*)/;
  434. if ($version ge "1.5.4") {
  435. push @opts, '--cleanup=verbatim';
  436. }
  437. else {
  438. $message.=".";
  439. }
  440. }
  441. push @opts, '-q';
  442. # git commit returns non-zero if file has not been really changed.
  443. # so we should ignore its exit status (hence run_or_non).
  444. if (run_or_non('git', 'commit', @opts, '-m', $message)) {
  445. if (length $config{gitorigin_branch}) {
  446. run_or_cry('git', 'push', $config{gitorigin_branch});
  447. }
  448. }
  449. %ENV=%env;
  450. return undef; # success
  451. }
  452. sub rcs_add ($) {
  453. # Add file to archive.
  454. my ($file) = @_;
  455. run_or_cry('git', 'add', $file);
  456. }
  457. sub rcs_remove ($) {
  458. # Remove file from archive.
  459. my ($file) = @_;
  460. run_or_cry('git', 'rm', '-f', $file);
  461. }
  462. sub rcs_rename ($$) {
  463. my ($src, $dest) = @_;
  464. run_or_cry('git', 'mv', '-f', $src, $dest);
  465. }
  466. sub rcs_recentchanges ($) {
  467. # List of recent changes.
  468. my ($num) = @_;
  469. eval q{use Date::Parse};
  470. error($@) if $@;
  471. my @rets;
  472. foreach my $ci (git_commit_info('HEAD', $num || 1)) {
  473. # Skip redundant commits.
  474. next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
  475. my ($sha1, $when) = (
  476. $ci->{'sha1'},
  477. $ci->{'author_epoch'}
  478. );
  479. my @pages;
  480. foreach my $detail (@{ $ci->{'details'} }) {
  481. my $file = $detail->{'file'};
  482. my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
  483. $diffurl =~ s/\[\[file\]\]/$file/go;
  484. $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
  485. $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
  486. $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
  487. $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
  488. push @pages, {
  489. page => pagename($file),
  490. diffurl => $diffurl,
  491. };
  492. }
  493. my @messages;
  494. my $pastblank=0;
  495. foreach my $line (@{$ci->{'comment'}}) {
  496. $pastblank=1 if $line eq '';
  497. next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
  498. push @messages, { line => $line };
  499. }
  500. my $user=$ci->{'author_username'};
  501. my $web_commit = ($ci->{'author'} =~ /\@web>/);
  502. # compatability code for old web commit messages
  503. if (! $web_commit &&
  504. defined $messages[0] &&
  505. $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
  506. $user = defined $2 ? "$2" : "$3";
  507. $messages[0]->{line} = $4;
  508. $web_commit=1;
  509. }
  510. push @rets, {
  511. rev => $sha1,
  512. user => $user,
  513. committype => $web_commit ? "web" : "git",
  514. when => $when,
  515. message => [@messages],
  516. pages => [@pages],
  517. } if @pages;
  518. last if @rets >= $num;
  519. }
  520. return @rets;
  521. }
  522. sub rcs_diff ($) {
  523. my $rev=shift;
  524. my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
  525. my @lines;
  526. foreach my $line (run_or_non("git", "show", $sha1)) {
  527. if (@lines || $line=~/^diff --git/) {
  528. push @lines, $line."\n";
  529. }
  530. }
  531. if (wantarray) {
  532. return @lines;
  533. }
  534. else {
  535. return join("", @lines);
  536. }
  537. }
  538. {
  539. my %time_cache;
  540. sub findtimes ($$) {
  541. my $file=shift;
  542. my $id=shift; # 0 = mtime ; 1 = ctime
  543. # Remove srcdir prefix
  544. $file =~ s/^\Q$config{srcdir}\E\/?//;
  545. if (! keys %time_cache) {
  546. my $date;
  547. foreach my $line (run_or_die('git', 'log',
  548. '--pretty=format:%ct',
  549. '--name-only', '--relative')) {
  550. if (! defined $date && $line =~ /^(\d+)$/) {
  551. $date=$line;
  552. }
  553. elsif (! length $line) {
  554. $date=undef;
  555. }
  556. else {
  557. my $f=decode_git_file($line);
  558. if (! $time_cache{$f}) {
  559. $time_cache{$f}[0]=$date; # mtime
  560. }
  561. $time_cache{$f}[1]=$date; # ctime
  562. }
  563. }
  564. }
  565. return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
  566. }
  567. }
  568. sub rcs_getctime ($) {
  569. my $file=shift;
  570. return findtimes($file, 1);
  571. }
  572. sub rcs_getmtime ($) {
  573. my $file=shift;
  574. return findtimes($file, 0);
  575. }
  576. sub rcs_receive () {
  577. # The wiki may not be the only thing in the git repo.
  578. # Determine if it is in a subdirectory by examining the srcdir,
  579. # and its parents, looking for the .git directory.
  580. my $subdir="";
  581. my $dir=$config{srcdir};
  582. while (! -d "$dir/.git") {
  583. $subdir=IkiWiki::basename($dir)."/".$subdir;
  584. $dir=IkiWiki::dirname($dir);
  585. if (! length $dir) {
  586. error("cannot determine root of git repo");
  587. }
  588. }
  589. my @rets;
  590. while (<>) {
  591. chomp;
  592. my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
  593. # only allow changes to gitmaster_branch
  594. if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
  595. error sprintf(gettext("you are not allowed to change %s"), $refname);
  596. }
  597. # Avoid chdir when running git here, because the changes
  598. # are in the master git repo, not the srcdir repo.
  599. # The pre-recieve hook already puts us in the right place.
  600. $no_chdir=1;
  601. my @changes=git_commit_info($oldrev."..".$newrev);
  602. $no_chdir=0;
  603. foreach my $ci (@changes) {
  604. foreach my $detail (@{ $ci->{'details'} }) {
  605. my $file = $detail->{'file'};
  606. # check that all changed files are in the
  607. # subdir
  608. if (length $subdir &&
  609. ! ($file =~ s/^\Q$subdir\E//)) {
  610. error sprintf(gettext("you are not allowed to change %s"), $file);
  611. }
  612. my ($action, $mode, $path);
  613. if ($detail->{'status'} =~ /^[M]+\d*$/) {
  614. $action="change";
  615. $mode=$detail->{'mode_to'};
  616. }
  617. elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
  618. $action="add";
  619. $mode=$detail->{'mode_to'};
  620. }
  621. elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
  622. $action="remove";
  623. $mode=$detail->{'mode_from'};
  624. }
  625. else {
  626. error "unknown status ".$detail->{'status'};
  627. }
  628. # test that the file mode is ok
  629. if ($mode !~ /^100[64][64][64]$/) {
  630. error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
  631. }
  632. if ($action eq "change") {
  633. if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
  634. error gettext("you are not allowed to change file modes");
  635. }
  636. }
  637. # extract attachment to temp file
  638. if (($action eq 'add' || $action eq 'change') &&
  639. ! pagetype($file)) {
  640. eval q{use File::Temp};
  641. die $@ if $@;
  642. my $fh;
  643. ($fh, $path)=File::Temp::tempfile("XXXXXXXXXX", UNLINK => 1);
  644. if (system("git show ".$detail->{sha1_to}." > '$path'") != 0) {
  645. error("failed writing temp file");
  646. }
  647. }
  648. push @rets, {
  649. file => $file,
  650. action => $action,
  651. path => $path,
  652. };
  653. }
  654. }
  655. }
  656. return reverse @rets;
  657. }
  658. 1