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