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