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