summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/git.pm
blob: 86d80186f3f8671140dc01a00706e2d265545779 (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. sub parse_diff_tree ($@) {
  248. # Parse the raw diff tree chunk and return the info hash.
  249. # See git-diff-tree(1) for the syntax.
  250. my ($prefix, $dt_ref) = @_;
  251. # End of stream?
  252. return if !defined @{ $dt_ref } ||
  253. !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
  254. my %ci;
  255. # Header line.
  256. while (my $line = shift @{ $dt_ref }) {
  257. return if $line !~ m/^(.+) ($sha1_pattern)/;
  258. my $sha1 = $2;
  259. $ci{'sha1'} = $sha1;
  260. last;
  261. }
  262. # Identification lines for the commit.
  263. while (my $line = shift @{ $dt_ref }) {
  264. # Regexps are semi-stolen from gitweb.cgi.
  265. if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
  266. $ci{'tree'} = $1;
  267. }
  268. elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
  269. # XXX: collecting in reverse order
  270. push @{ $ci{'parents'} }, $1;
  271. }
  272. elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
  273. my ($who, $name, $epoch, $tz) =
  274. ($1, $2, $3, $4 );
  275. $ci{ $who } = $name;
  276. $ci{ "${who}_epoch" } = $epoch;
  277. $ci{ "${who}_tz" } = $tz;
  278. if ($name =~ m/^[^<]+\s+<([^@>]+)/) {
  279. $ci{"${who}_username"} = $1;
  280. }
  281. elsif ($name =~ m/^([^<]+)\s+<>$/) {
  282. $ci{"${who}_username"} = $1;
  283. }
  284. else {
  285. $ci{"${who}_username"} = $name;
  286. }
  287. }
  288. elsif ($line =~ m/^$/) {
  289. # Trailing empty line signals next section.
  290. last;
  291. }
  292. }
  293. debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
  294. if (defined $ci{'parents'}) {
  295. $ci{'parent'} = @{ $ci{'parents'} }[0];
  296. }
  297. else {
  298. $ci{'parent'} = 0 x 40;
  299. }
  300. # Commit message (optional).
  301. while ($dt_ref->[0] =~ /^ /) {
  302. my $line = shift @{ $dt_ref };
  303. $line =~ s/^ //;
  304. push @{ $ci{'comment'} }, $line;
  305. }
  306. shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
  307. # Modified files.
  308. while (my $line = shift @{ $dt_ref }) {
  309. if ($line =~ m{^
  310. (:+) # number of parents
  311. ([^\t]+)\t # modes, sha1, status
  312. (.*) # file names
  313. $}xo) {
  314. my $num_parents = length $1;
  315. my @tmp = split(" ", $2);
  316. my ($file, $file_to) = split("\t", $3);
  317. my @mode_from = splice(@tmp, 0, $num_parents);
  318. my $mode_to = shift(@tmp);
  319. my @sha1_from = splice(@tmp, 0, $num_parents);
  320. my $sha1_to = shift(@tmp);
  321. my $status = shift(@tmp);
  322. # git does not output utf-8 filenames, but instead
  323. # double-quotes them with the utf-8 characters
  324. # escaped as \nnn\nnn.
  325. if ($file =~ m/^"(.*)"$/) {
  326. ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
  327. }
  328. $file =~ s/^\Q$prefix\E//;
  329. if (length $file) {
  330. push @{ $ci{'details'} }, {
  331. 'file' => decode("utf8", $file),
  332. 'sha1_from' => $sha1_from[0],
  333. 'sha1_to' => $sha1_to,
  334. 'mode_from' => $mode_from[0],
  335. 'mode_to' => $mode_to,
  336. 'status' => $status,
  337. };
  338. }
  339. next;
  340. };
  341. last;
  342. }
  343. return \%ci;
  344. }
  345. sub git_commit_info ($;$) {
  346. # Return an array of commit info hashes of num commits
  347. # starting from the given sha1sum.
  348. my ($sha1, $num) = @_;
  349. my @opts;
  350. push @opts, "--max-count=$num" if defined $num;
  351. my @raw_lines = run_or_die('git', 'log', @opts,
  352. '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
  353. '-r', $sha1, '--', '.');
  354. my ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
  355. my @ci;
  356. while (my $parsed = parse_diff_tree(($prefix or ""), \@raw_lines)) {
  357. push @ci, $parsed;
  358. }
  359. warn "Cannot parse commit info for '$sha1' commit" if !@ci;
  360. return wantarray ? @ci : $ci[0];
  361. }
  362. sub git_sha1 (;$) {
  363. # Return head sha1sum (of given file).
  364. my $file = shift || q{--};
  365. # Ignore error since a non-existing file might be given.
  366. my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
  367. '--', $file);
  368. if ($sha1) {
  369. ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
  370. }
  371. else {
  372. debug("Empty sha1sum for '$file'.");
  373. }
  374. return defined $sha1 ? $sha1 : q{};
  375. }
  376. sub rcs_update () {
  377. # Update working directory.
  378. if (length $config{gitorigin_branch}) {
  379. run_or_cry('git', 'pull', $config{gitorigin_branch});
  380. }
  381. }
  382. sub rcs_prepedit ($) {
  383. # Return the commit sha1sum of the file when editing begins.
  384. # This will be later used in rcs_commit if a merge is required.
  385. my ($file) = @_;
  386. return git_sha1($file);
  387. }
  388. sub rcs_commit ($$$;$$) {
  389. # Try to commit the page; returns undef on _success_ and
  390. # a version of the page with the rcs's conflict markers on
  391. # failure.
  392. my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
  393. # Check to see if the page has been changed by someone else since
  394. # rcs_prepedit was called.
  395. my $cur = git_sha1($file);
  396. my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
  397. if (defined $cur && defined $prev && $cur ne $prev) {
  398. my $conflict = merge_past($prev, $file, $dummy_commit_msg);
  399. return $conflict if defined $conflict;
  400. }
  401. rcs_add($file);
  402. return rcs_commit_staged($message, $user, $ipaddr);
  403. }
  404. sub rcs_commit_staged ($$$) {
  405. # Commits all staged changes. Changes can be staged using rcs_add,
  406. # rcs_remove, and rcs_rename.
  407. my ($message, $user, $ipaddr)=@_;
  408. # Set the commit author and email to the web committer.
  409. my %env=%ENV;
  410. if (defined $user || defined $ipaddr) {
  411. my $u=encode_utf8(defined $user ? $user : $ipaddr);
  412. $ENV{GIT_AUTHOR_NAME}=$u;
  413. $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
  414. }
  415. $message = IkiWiki::possibly_foolish_untaint($message);
  416. my @opts;
  417. if ($message !~ /\S/) {
  418. # Force git to allow empty commit messages.
  419. # (If this version of git supports it.)
  420. my ($version)=`git --version` =~ /git version (.*)/;
  421. if ($version ge "1.5.4") {
  422. push @opts, '--cleanup=verbatim';
  423. }
  424. else {
  425. $message.=".";
  426. }
  427. }
  428. push @opts, '-q';
  429. # git commit returns non-zero if file has not been really changed.
  430. # so we should ignore its exit status (hence run_or_non).
  431. if (run_or_non('git', 'commit', @opts, '-m', $message)) {
  432. if (length $config{gitorigin_branch}) {
  433. run_or_cry('git', 'push', $config{gitorigin_branch});
  434. }
  435. }
  436. %ENV=%env;
  437. return undef; # success
  438. }
  439. sub rcs_add ($) {
  440. # Add file to archive.
  441. my ($file) = @_;
  442. run_or_cry('git', 'add', $file);
  443. }
  444. sub rcs_remove ($) {
  445. # Remove file from archive.
  446. my ($file) = @_;
  447. run_or_cry('git', 'rm', '-f', $file);
  448. }
  449. sub rcs_rename ($$) {
  450. my ($src, $dest) = @_;
  451. run_or_cry('git', 'mv', '-f', $src, $dest);
  452. }
  453. sub rcs_recentchanges ($) {
  454. # List of recent changes.
  455. my ($num) = @_;
  456. eval q{use Date::Parse};
  457. error($@) if $@;
  458. my @rets;
  459. foreach my $ci (git_commit_info('HEAD', $num || 1)) {
  460. # Skip redundant commits.
  461. next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
  462. my ($sha1, $when) = (
  463. $ci->{'sha1'},
  464. $ci->{'author_epoch'}
  465. );
  466. my @pages;
  467. foreach my $detail (@{ $ci->{'details'} }) {
  468. my $file = $detail->{'file'};
  469. my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
  470. $diffurl =~ s/\[\[file\]\]/$file/go;
  471. $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
  472. $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
  473. $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
  474. $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
  475. push @pages, {
  476. page => pagename($file),
  477. diffurl => $diffurl,
  478. };
  479. }
  480. my @messages;
  481. my $pastblank=0;
  482. foreach my $line (@{$ci->{'comment'}}) {
  483. $pastblank=1 if $line eq '';
  484. next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
  485. push @messages, { line => $line };
  486. }
  487. my $user=$ci->{'author_username'};
  488. my $web_commit = ($ci->{'author'} =~ /\@web>/);
  489. # compatability code for old web commit messages
  490. if (! $web_commit &&
  491. defined $messages[0] &&
  492. $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
  493. $user = defined $2 ? "$2" : "$3";
  494. $messages[0]->{line} = $4;
  495. $web_commit=1;
  496. }
  497. push @rets, {
  498. rev => $sha1,
  499. user => $user,
  500. committype => $web_commit ? "web" : "git",
  501. when => $when,
  502. message => [@messages],
  503. pages => [@pages],
  504. } if @pages;
  505. last if @rets >= $num;
  506. }
  507. return @rets;
  508. }
  509. sub rcs_diff ($) {
  510. my $rev=shift;
  511. my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
  512. my @lines;
  513. foreach my $line (run_or_non("git", "show", $sha1)) {
  514. if (@lines || $line=~/^diff --git/) {
  515. push @lines, $line."\n";
  516. }
  517. }
  518. if (wantarray) {
  519. return @lines;
  520. }
  521. else {
  522. return join("", @lines);
  523. }
  524. }
  525. sub rcs_getctime ($) {
  526. my $file=shift;
  527. # Remove srcdir prefix
  528. $file =~ s/^\Q$config{srcdir}\E\/?//;
  529. my @raw_lines = run_or_die('git', 'log',
  530. '--follow', '--no-merges',
  531. '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
  532. '-r', '--', $file);
  533. my @ci;
  534. while (my $parsed = parse_diff_tree("", \@raw_lines)) {
  535. push @ci, $parsed;
  536. }
  537. my $ctime = $ci[$#ci]->{'author_epoch'};
  538. debug("ctime for '$file': ". localtime($ctime));
  539. return $ctime;
  540. }
  541. sub rcs_getmtime ($) {
  542. error "rcs_getmtime is not implemented for git\n"; # TODO
  543. }
  544. sub rcs_receive () {
  545. # The wiki may not be the only thing in the git repo.
  546. # Determine if it is in a subdirectory by examining the srcdir,
  547. # and its parents, looking for the .git directory.
  548. my $subdir="";
  549. my $dir=$config{srcdir};
  550. while (! -d "$dir/.git") {
  551. $subdir=IkiWiki::basename($dir)."/".$subdir;
  552. $dir=IkiWiki::dirname($dir);
  553. if (! length $dir) {
  554. error("cannot determine root of git repo");
  555. }
  556. }
  557. my @rets;
  558. while (<>) {
  559. chomp;
  560. my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
  561. # only allow changes to gitmaster_branch
  562. if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
  563. error sprintf(gettext("you are not allowed to change %s"), $refname);
  564. }
  565. # Avoid chdir when running git here, because the changes
  566. # are in the master git repo, not the srcdir repo.
  567. # The pre-recieve hook already puts us in the right place.
  568. $no_chdir=1;
  569. my @changes=git_commit_info($oldrev."..".$newrev);
  570. $no_chdir=0;
  571. foreach my $ci (@changes) {
  572. foreach my $detail (@{ $ci->{'details'} }) {
  573. my $file = $detail->{'file'};
  574. # check that all changed files are in the
  575. # subdir
  576. if (length $subdir &&
  577. ! ($file =~ s/^\Q$subdir\E//)) {
  578. error sprintf(gettext("you are not allowed to change %s"), $file);
  579. }
  580. my ($action, $mode, $path);
  581. if ($detail->{'status'} =~ /^[M]+\d*$/) {
  582. $action="change";
  583. $mode=$detail->{'mode_to'};
  584. }
  585. elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
  586. $action="add";
  587. $mode=$detail->{'mode_to'};
  588. }
  589. elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
  590. $action="remove";
  591. $mode=$detail->{'mode_from'};
  592. }
  593. else {
  594. error "unknown status ".$detail->{'status'};
  595. }
  596. # test that the file mode is ok
  597. if ($mode !~ /^100[64][64][64]$/) {
  598. error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
  599. }
  600. if ($action eq "change") {
  601. if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
  602. error gettext("you are not allowed to change file modes");
  603. }
  604. }
  605. # extract attachment to temp file
  606. if (($action eq 'add' || $action eq 'change') &&
  607. ! pagetype($file)) {
  608. eval q{use File::Temp};
  609. die $@ if $@;
  610. my $fh;
  611. ($fh, $path)=File::Temp::tempfile("XXXXXXXXXX", UNLINK => 1);
  612. if (system("git show ".$detail->{sha1_to}." > '$path'") != 0) {
  613. error("failed writing temp file");
  614. }
  615. }
  616. push @rets, {
  617. file => $file,
  618. action => $action,
  619. path => $path,
  620. };
  621. }
  622. }
  623. }
  624. return reverse @rets;
  625. }
  626. 1