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