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