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