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