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