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