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