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