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