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