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