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