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