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