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