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