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