]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/git.pm
git: do not mix in_git_dir with eval{}
[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 File::Path qw{remove_tree};
9 use URI::Escape q{uri_escape_utf8};
10 use open qw{:utf8 :std};
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
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 }
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         }
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         }
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 }
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                 },
147 sub genwrapper {
148         if ($config{test_receive}) {
149                 require IkiWiki::Receive;
150                 return IkiWiki::Receive::genwrapper();
151         }
152         else {
153                 return "";
154         }
157 my @git_dir_stack;
158 my $prefix;
160 sub in_git_dir ($$) {
161         unshift @git_dir_stack, shift;
162         my @ret=shift->();
163         shift @git_dir_stack;
164         $prefix=undef;
165         return @ret;
168 # Loosely based on git-new-workdir from git contrib.
169 sub create_temp_working_dir ($$) {
170         my $rootdir = shift;
171         my $branch = shift;
172         my $working = "$rootdir/.git/ikiwiki-temp-working";
173         remove_tree($working);
175         foreach my $dir ("", ".git") {
176                 if (!mkdir("$working/$dir")) {
177                         error("Unable to create $working/$dir: $!");
178                 }
179         }
181         # Hooks are deliberately not included: we will commit to the temporary
182         # branch that is used in the temporary working tree, and we don't want
183         # to run the post-commit hook there.
184         #
185         # logs/refs is not included because we don't use the reflog.
186         # remotes, rr-cache, svn are similarly excluded.
187         foreach my $link ("config", "refs", "objects", "info", "packed-refs") {
188                 if (!symlink("../../$link", "$working/.git/$link")) {
189                         error("Unable to create symlink $working/.git/$link: $!");
190                 }
191         }
193         open (my $out, '>', "$working/.git/HEAD") or
194                 error("failed to write $working.git/HEAD: $!");
195         print $out "ref: refs/heads/$branch\n" or
196                 error("failed to write $working.git/HEAD: $!");
197         close $out or
198                 error("failed to write $working.git/HEAD: $!");
199         return $working;
202 sub safe_git {
203         # Start a child process safely without resorting to /bin/sh.
204         # Returns command output (in list content) or success state
205         # (in scalar context), or runs the specified data handler.
207         my %params = @_;
209         my $pid = open my $OUT, "-|";
211         error("Cannot fork: $!") if !defined $pid;
213         if (!$pid) {
214                 # In child.
215                 # Git commands want to be in wc.
216                 if (exists $params{chdir}) {
217                         chdir $params{chdir}
218                             or error("cannot chdir to $params{chdir}: $!");
219                 }
220                 elsif (! @git_dir_stack) {
221                         chdir $config{srcdir}
222                             or error("cannot chdir to $config{srcdir}: $!");
223                 }
224                 else {
225                         chdir $git_dir_stack[0]
226                             or error("cannot chdir to $git_dir_stack[0]: $!");
227                 }
229                 if ($params{stdout}) {
230                         open(STDOUT, '>&', $params{stdout}) or error("Cannot reopen stdout: $!");
231                 }
233                 exec @{$params{cmdline}} or error("Cannot exec '@{$params{cmdline}}': $!");
234         }
235         # In parent.
237         # git output is probably utf-8 encoded, but may contain
238         # other encodings or invalidly encoded stuff. So do not rely
239         # on the normal utf-8 IO layer, decode it by hand.
240         binmode($OUT);
242         my @lines;
243         while (<$OUT>) {
244                 $_=decode_utf8($_, 0);
246                 chomp;
248                 if (! defined $params{data_handler}) {
249                         push @lines, $_;
250                 }
251                 else {
252                         last unless $params{data_handler}->($_);
253                 }
254         }
256         close $OUT;
258         $params{error_handler}->("'@{$params{cmdline}}' failed: $!") if $? && $params{error_handler};
260         return wantarray ? @lines : ($? == 0);
262 # Convenient wrappers.
263 sub run_or_die ($@) { safe_git(error_handler => \&error, cmdline => \@_) }
264 sub run_or_cry ($@) { safe_git(error_handler => sub { warn @_ }, cmdline => \@_) }
265 sub run_or_non ($@) { safe_git(cmdline => \@_) }
266 sub run_or_die_in ($$@) {
267         my $dir = shift;
268         safe_git(chdir => $dir, error_handler => \&error, cmdline => \@_);
270 sub run_or_cry_in ($$@) {
271         my $dir = shift;
272         safe_git(chdir => $dir, error_handler => sub { warn @_ }, cmdline => \@_);
274 sub run_or_non_in ($$@) {
275         my $dir = shift;
276         safe_git(chdir => $dir, cmdline => \@_);
279 sub ensure_committer {
280         if (! length $ENV{GIT_AUTHOR_NAME} || ! length $ENV{GIT_COMMITTER_NAME}) {
281                 my $name = join('', run_or_non("git", "config", "user.name"));
282                 if (! length $name) {
283                         run_or_die("git", "config", "user.name", "IkiWiki");
284                 }
285         }
287         if (! length $ENV{GIT_AUTHOR_EMAIL} || ! length $ENV{GIT_COMMITTER_EMAIL}) {
288                 my $email = join('', run_or_non("git", "config", "user.email"));
289                 if (! length $email) {
290                         run_or_die("git", "config", "user.email", "ikiwiki.info");
291                 }
292         }
295 sub merge_past ($$$) {
296         # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
297         # Git merge commands work with the committed changes, except in the
298         # implicit case of '-m' of git checkout(1).  So we should invent a
299         # kludge here.  In principle, we need to create a throw-away branch
300         # in preparing for the merge itself.  Since branches are cheap (and
301         # branching is fast), this shouldn't cost high.
302         #
303         # The main problem is the presence of _uncommitted_ local changes.  One
304         # possible approach to get rid of this situation could be that we first
305         # make a temporary commit in the master branch and later restore the
306         # initial state (this is possible since Git has the ability to undo a
307         # commit, i.e. 'git reset --soft HEAD^').  The method can be summarized
308         # as follows:
309         #
310         #       - create a diff of HEAD:current-sha1
311         #       - dummy commit
312         #       - create a dummy branch and switch to it
313         #       - rewind to past (reset --hard to the current-sha1)
314         #       - apply the diff and commit
315         #       - switch to master and do the merge with the dummy branch
316         #       - make a soft reset (undo the last commit of master)
317         #
318         # The above method has some drawbacks: (1) it needs a redundant commit
319         # just to get rid of local changes, (2) somewhat slow because of the
320         # required system forks.  Until someone points a more straight method
321         # (which I would be grateful) I have implemented an alternative method.
322         # In this approach, we hide all the modified files from Git by renaming
323         # them (using the 'rename' builtin) and later restore those files in
324         # the throw-away branch (that is, we put the files themselves instead
325         # of applying a patch).
327         my ($sha1, $file, $message) = @_;
329         my @undo;      # undo stack for cleanup in case of an error
330         my $conflict;  # file content with conflict markers
332         ensure_committer();
334         eval {
335                 # Hide local changes from Git by renaming the modified file.
336                 # Relative paths must be converted to absolute for renaming.
337                 my ($target, $hidden) = (
338                     "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
339                 );
340                 rename($target, $hidden)
341                     or error("rename '$target' to '$hidden' failed: $!");
342                 # Ensure to restore the renamed file on error.
343                 push @undo, sub {
344                         return if ! -e "$hidden"; # already renamed
345                         rename($hidden, $target)
346                             or warn "rename '$hidden' to '$target' failed: $!";
347                 };
349                 my $branch = "throw_away_${sha1}"; # supposed to be unique
351                 # Create a throw-away branch and rewind backward.
352                 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
353                 run_or_die('git', 'branch', $branch, $sha1);
355                 # Switch to throw-away branch for the merge operation.
356                 push @undo, sub {
357                         if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
358                                 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
359                         }
360                 };
361                 run_or_die('git', 'checkout', $branch);
363                 # Put the modified file in _this_ branch.
364                 rename($hidden, $target)
365                     or error("rename '$hidden' to '$target' failed: $!");
367                 # _Silently_ commit all modifications in the current branch.
368                 run_or_non('git', 'commit', '-m', $message, '-a');
369                 # ... and re-switch to master.
370                 run_or_die('git', 'checkout', $config{gitmaster_branch});
372                 # Attempt to merge without complaining.
373                 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
374                         $conflict = readfile($target);
375                         run_or_die('git', 'reset', '--hard');
376                 }
377         };
378         my $failure = $@;
380         # Process undo stack (in reverse order).  By policy cleanup
381         # actions should normally print a warning on failure.
382         while (my $handle = pop @undo) {
383                 $handle->();
384         }
386         error("Git merge failed!\n$failure\n") if $failure;
388         return $conflict;
391 sub decode_git_file ($) {
392         my $file=shift;
394         # git does not output utf-8 filenames, but instead
395         # double-quotes them with the utf-8 characters
396         # escaped as \nnn\nnn.
397         if ($file =~ m/^"(.*)"$/) {
398                 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
399         }
401         # strip prefix if in a subdir
402         if (! defined $prefix) {
403                 ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
404                 if (! defined $prefix) {
405                         $prefix="";
406                 }
407         }
408         $file =~ s/^\Q$prefix\E//;
410         return decode("utf8", $file);
413 sub parse_diff_tree ($) {
414         # Parse the raw diff tree chunk and return the info hash.
415         # See git-diff-tree(1) for the syntax.
416         my $dt_ref = shift;
418         # End of stream?
419         return if ! @{ $dt_ref } ||
420                   !defined $dt_ref->[0] || !length $dt_ref->[0];
422         my %ci;
423         # Header line.
424         while (my $line = shift @{ $dt_ref }) {
425                 return if $line !~ m/^(.+) ($sha1_pattern)/;
427                 my $sha1 = $2;
428                 $ci{'sha1'} = $sha1;
429                 last;
430         }
432         # Identification lines for the commit.
433         while (my $line = shift @{ $dt_ref }) {
434                 # Regexps are semi-stolen from gitweb.cgi.
435                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
436                         $ci{'tree'} = $1;
437                 }
438                 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
439                         # XXX: collecting in reverse order
440                         push @{ $ci{'parents'} }, $1;
441                 }
442                 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
443                         my ($who, $name, $epoch, $tz) =
444                            ($1,   $2,    $3,     $4 );
446                         $ci{  $who          } = $name;
447                         $ci{ "${who}_epoch" } = $epoch;
448                         $ci{ "${who}_tz"    } = $tz;
450                         if ($name =~ m/^([^<]+)\s+<([^@>]+)/) {
451                                 $ci{"${who}_name"} = $1;
452                                 $ci{"${who}_username"} = $2;
453                         }
454                         elsif ($name =~ m/^([^<]+)\s+<>$/) {
455                                 $ci{"${who}_username"} = $1;
456                         }
457                         else {
458                                 $ci{"${who}_username"} = $name;
459                         }
460                 }
461                 elsif ($line =~ m/^$/) {
462                         # Trailing empty line signals next section.
463                         last;
464                 }
465         }
467         debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
468         
469         if (defined $ci{'parents'}) {
470                 $ci{'parent'} = @{ $ci{'parents'} }[0];
471         }
472         else {
473                 $ci{'parent'} = 0 x 40;
474         }
476         # Commit message (optional).
477         while ($dt_ref->[0] =~ /^    /) {
478                 my $line = shift @{ $dt_ref };
479                 $line =~ s/^    //;
480                 push @{ $ci{'comment'} }, $line;
481         }
482         shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
484         $ci{details} = [parse_changed_files($dt_ref)];
486         return \%ci;
489 sub parse_changed_files {
490         my $dt_ref = shift;
492         my @files;
494         # Modified files.
495         while (my $line = shift @{ $dt_ref }) {
496                 if ($line =~ m{^
497                         (:+)       # number of parents
498                         ([^\t]+)\t # modes, sha1, status
499                         (.*)       # file names
500                 $}xo) {
501                         my $num_parents = length $1;
502                         my @tmp = split(" ", $2);
503                         my ($file, $file_to) = split("\t", $3);
504                         my @mode_from = splice(@tmp, 0, $num_parents);
505                         my $mode_to = shift(@tmp);
506                         my @sha1_from = splice(@tmp, 0, $num_parents);
507                         my $sha1_to = shift(@tmp);
508                         my $status = shift(@tmp);
510                         if (length $file) {
511                                 push @files, {
512                                         'file'      => decode_git_file($file),
513                                         'sha1_from' => $sha1_from[0],
514                                         'sha1_to'   => $sha1_to,
515                                         'mode_from' => $mode_from[0],
516                                         'mode_to'   => $mode_to,
517                                         'status'    => $status,
518                                 };
519                         }
520                         next;
521                 };
522                 last;
523         }
525         return @files;
528 sub git_commit_info ($;$) {
529         # Return an array of commit info hashes of num commits
530         # starting from the given sha1sum.
531         my ($sha1, $num) = @_;
533         my @opts;
534         push @opts, "--max-count=$num" if defined $num;
536         my @raw_lines = run_or_die('git', 'log', @opts,
537                 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
538                 '-r', $sha1, '--no-renames', '--', '.');
540         my @ci;
541         while (my $parsed = parse_diff_tree(\@raw_lines)) {
542                 push @ci, $parsed;
543         }
545         warn "Cannot parse commit info for '$sha1' commit" if !@ci;
547         return wantarray ? @ci : $ci[0];
550 sub rcs_find_changes ($) {
551         my $oldrev=shift;
553         # Note that git log will sometimes show files being added that
554         # don't exist. Particularly, git merge -s ours can result in a
555         # merge commit where some files were not really added.
556         # This is why the code below verifies that the files really
557         # exist.
558         my @raw_lines = run_or_die('git', 'log',
559                 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
560                 '--no-renames', , '--reverse',
561                 '-r', "$oldrev..HEAD", '--', '.');
563         # Due to --reverse, we see changes in chronological order.
564         my %changed;
565         my %deleted;
566         my $nullsha = 0 x 40;
567         my $newrev=$oldrev;
568         while (my $ci = parse_diff_tree(\@raw_lines)) {
569                 $newrev=$ci->{sha1};
570                 foreach my $i (@{$ci->{details}}) {
571                         my $file=$i->{file};
572                         if ($i->{sha1_to} eq $nullsha) {
573                                 if (! -e "$config{srcdir}/$file") {
574                                         delete $changed{$file};
575                                         $deleted{$file}=1;
576                                 }
577                         }
578                         else {
579                                 if (-e "$config{srcdir}/$file") {
580                                         delete $deleted{$file};
581                                         $changed{$file}=1;
582                                 }
583                         }
584                 }
585         }
587         return (\%changed, \%deleted, $newrev);
590 sub git_sha1_file ($) {
591         my $file=shift;
592         git_sha1("--", $file);
595 sub git_sha1 (@) {
596         # Ignore error since a non-existing file might be given.
597         my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
598                 '--', @_);
599         if (defined $sha1) {
600                 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
601         }
602         return defined $sha1 ? $sha1 : '';
605 sub rcs_get_current_rev () {
606         git_sha1();
609 sub rcs_update () {
610         # Update working directory.
612         ensure_committer();
614         if (length $config{gitorigin_branch}) {
615                 run_or_cry('git', 'pull', '--prune', $config{gitorigin_branch});
616         }
619 sub rcs_prepedit ($) {
620         # Return the commit sha1sum of the file when editing begins.
621         # This will be later used in rcs_commit if a merge is required.
622         my ($file) = @_;
624         return git_sha1_file($file);
627 sub rcs_commit (@) {
628         # Try to commit the page; returns undef on _success_ and
629         # a version of the page with the rcs's conflict markers on
630         # failure.
631         my %params=@_;
633         # Check to see if the page has been changed by someone else since
634         # rcs_prepedit was called.
635         my $cur    = git_sha1_file($params{file});
636         my $prev;
637         if (defined $params{token}) {
638                 ($prev) = $params{token} =~ /^($sha1_pattern)$/; # untaint
639         }
641         if (defined $cur && defined $prev && $cur ne $prev) {
642                 my $conflict = merge_past($prev, $params{file}, $dummy_commit_msg);
643                 return $conflict if defined $conflict;
644         }
646         return rcs_commit_helper(@_);
649 sub rcs_commit_staged (@) {
650         # Commits all staged changes. Changes can be staged using rcs_add,
651         # rcs_remove, and rcs_rename.
652         return rcs_commit_helper(@_);
655 sub rcs_commit_helper (@) {
656         my %params=@_;
657         
658         my %env=%ENV;
660         if (defined $params{session}) {
661                 # Set the commit author and email based on web session info.
662                 my $u;
663                 if (defined $params{session}->param("name")) {
664                         $u=$params{session}->param("name");
665                 }
666                 elsif (defined $params{session}->remote_addr()) {
667                         $u=$params{session}->remote_addr();
668                 }
669                 if (length $u) {
670                         $u=encode_utf8(IkiWiki::cloak($u));
671                         $ENV{GIT_AUTHOR_NAME}=$u;
672                 }
673                 else {
674                         $u = 'anonymous';
675                 }
676                 if (defined $params{session}->param("nickname")) {
677                         $u=encode_utf8($params{session}->param("nickname"));
678                         $u=~s/\s+/_/g;
679                         $u=~s/[^-_0-9[:alnum:]]+//g;
680                 }
681                 if (length $u) {
682                         $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
683                 }
684                 else {
685                         $ENV{GIT_AUTHOR_EMAIL}='anonymous@web';
686                 }
687         }
689         ensure_committer();
691         $params{message} = IkiWiki::possibly_foolish_untaint($params{message});
692         my @opts;
693         if ($params{message} !~ /\S/) {
694                 # Force git to allow empty commit messages.
695                 # (If this version of git supports it.)
696                 my ($version)=`git --version` =~ /git version (.*)/;
697                 if ($version ge "1.7.8") {
698                         push @opts, "--allow-empty-message", "--no-edit";
699                 }
700                 if ($version ge "1.7.2") {
701                         push @opts, "--allow-empty-message";
702                 }
703                 elsif ($version ge "1.5.4") {
704                         push @opts, '--cleanup=verbatim';
705                 }
706                 else {
707                         $params{message}.=".";
708                 }
709         }
710         if (exists $params{file}) {
711                 push @opts, '--', $params{file};
712         }
713         # git commit returns non-zero if nothing really changed.
714         # So we should ignore its exit status (hence run_or_non).
715         if (run_or_non('git', 'commit', '-m', $params{message}, '-q', @opts)) {
716                 if (length $config{gitorigin_branch}) {
717                         run_or_cry('git', 'push', $config{gitorigin_branch}, $config{gitmaster_branch});
718                 }
719         }
720         
721         %ENV=%env;
722         return undef; # success
725 sub rcs_add ($) {
726         # Add file to archive.
728         my ($file) = @_;
730         ensure_committer();
732         run_or_cry('git', 'add', '--', $file);
735 sub rcs_remove ($) {
736         # Remove file from archive.
738         my ($file) = @_;
740         ensure_committer();
742         run_or_cry('git', 'rm', '-f', '--', $file);
745 sub rcs_rename ($$) {
746         my ($src, $dest) = @_;
748         ensure_committer();
750         run_or_cry('git', 'mv', '-f', '--', $src, $dest);
753 sub rcs_recentchanges ($) {
754         # List of recent changes.
756         my ($num) = @_;
758         eval q{use Date::Parse};
759         error($@) if $@;
761         my @rets;
762         foreach my $ci (git_commit_info('HEAD', $num || 1)) {
763                 # Skip redundant commits.
764                 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
766                 my ($sha1, $when) = (
767                         $ci->{'sha1'},
768                         $ci->{'author_epoch'}
769                 );
771                 my @pages;
772                 foreach my $detail (@{ $ci->{'details'} }) {
773                         my $file = $detail->{'file'};
774                         my $efile = join('/',
775                                 map { uri_escape_utf8($_) } split('/', $file)
776                         );
778                         my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
779                         $diffurl =~ s/\[\[file\]\]/$efile/go;
780                         $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
781                         $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
782                         $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
783                         $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
785                         push @pages, {
786                                 page => pagename($file),
787                                 diffurl => $diffurl,
788                         };
789                 }
791                 my @messages;
792                 my $pastblank=0;
793                 foreach my $line (@{$ci->{'comment'}}) {
794                         $pastblank=1 if $line eq '';
795                         next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
796                         push @messages, { line => $line };
797                 }
799                 my $user=$ci->{'author_username'};
800                 my $web_commit = ($ci->{'author'} =~ /\@web>/);
801                 my $nickname;
803                 # Set nickname only if a non-url author_username is available,
804                 # and author_name is an url.
805                 if ($user !~ /:\/\// && defined $ci->{'author_name'} &&
806                     $ci->{'author_name'} =~ /:\/\//) {
807                         $nickname=$user;
808                         $user=$ci->{'author_name'};
809                 }
811                 # compatability code for old web commit messages
812                 if (! $web_commit &&
813                       defined $messages[0] &&
814                       $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
815                         $user = defined $2 ? "$2" : "$3";
816                         $messages[0]->{line} = $4;
817                         $web_commit=1;
818                 }
820                 push @rets, {
821                         rev        => $sha1,
822                         user       => $user,
823                         nickname   => $nickname,
824                         committype => $web_commit ? "web" : "git",
825                         when       => $when,
826                         message    => [@messages],
827                         pages      => [@pages],
828                 } if @pages;
830                 last if @rets >= $num;
831         }
833         return @rets;
836 sub rcs_diff ($;$) {
837         my $rev=shift;
838         my $maxlines=shift;
839         my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
840         my @lines;
841         my $addlines=sub {
842                 my $line=shift;
843                 return if defined $maxlines && @lines == $maxlines;
844                 push @lines, $line."\n"
845                         if (@lines || $line=~/^diff --git/);
846                 return 1;
847         };
848         safe_git(
849                 error_handler => undef,
850                 data_handler => $addlines,
851                 cmdline => ["git", "show", $sha1],
852         );
853         if (wantarray) {
854                 return @lines;
855         }
856         else {
857                 return join("", @lines);
858         }
862 my %time_cache;
864 sub findtimes ($$) {
865         my $file=shift;
866         my $id=shift; # 0 = mtime ; 1 = ctime
868         if (! keys %time_cache) {
869                 my $date;
870                 foreach my $line (run_or_die('git', 'log',
871                                 '--pretty=format:%at',
872                                 '--name-only', '--relative')) {
873                         if (! defined $date && $line =~ /^(\d+)$/) {
874                                 $date=$line;
875                         }
876                         elsif (! length $line) {
877                                 $date=undef;
878                         }
879                         else {
880                                 my $f=decode_git_file($line);
882                                 if (! $time_cache{$f}) {
883                                         $time_cache{$f}[0]=$date; # mtime
884                                 }
885                                 $time_cache{$f}[1]=$date; # ctime
886                         }
887                 }
888         }
890         return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
895 sub rcs_getctime ($) {
896         my $file=shift;
898         return findtimes($file, 1);
901 sub rcs_getmtime ($) {
902         my $file=shift;
904         return findtimes($file, 0);
908 my $ret;
909 sub git_find_root {
910         # The wiki may not be the only thing in the git repo.
911         # Determine if it is in a subdirectory by examining the srcdir,
912         # and its parents, looking for the .git directory.
914         return @$ret if defined $ret;
915         
916         my $subdir="";
917         my $dir=$config{srcdir};
918         while (! -d "$dir/.git") {
919                 $subdir=IkiWiki::basename($dir)."/".$subdir;
920                 $dir=IkiWiki::dirname($dir);
921                 if (! length $dir) {
922                         error("cannot determine root of git repo");
923                 }
924         }
926         $ret=[$subdir, $dir];
927         return @$ret;
932 sub git_parse_changes {
933         my $reverted = shift;
934         my @changes = @_;
936         my ($subdir, $rootdir) = git_find_root();
937         my @rets;
938         foreach my $ci (@changes) {
939                 foreach my $detail (@{ $ci->{'details'} }) {
940                         my $file = $detail->{'file'};
942                         # check that all changed files are in the subdir
943                         if (length $subdir &&
944                             ! ($file =~ s/^\Q$subdir\E//)) {
945                                 error sprintf(gettext("you are not allowed to change %s"), $file);
946                         }
948                         my ($action, $mode, $path);
949                         if ($detail->{'status'} =~ /^[M]+\d*$/) {
950                                 $action="change";
951                                 $mode=$detail->{'mode_to'};
952                         }
953                         elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
954                                 $action= $reverted ? "remove" : "add";
955                                 $mode=$detail->{'mode_to'};
956                         }
957                         elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
958                                 $action= $reverted ? "add" : "remove";
959                                 $mode=$detail->{'mode_from'};
960                         }
961                         else {
962                                 error "unknown status ".$detail->{'status'};
963                         }
965                         # test that the file mode is ok
966                         if ($mode !~ /^100[64][64][64]$/) {
967                                 error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
968                         }
969                         if ($action eq "change") {
970                                 if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
971                                         error gettext("you are not allowed to change file modes");
972                                 }
973                         }
975                         # extract attachment to temp file
976                         if (($action eq 'add' || $action eq 'change') &&
977                             ! pagetype($file)) {
978                                 eval q{use File::Temp};
979                                 die $@ if $@;
980                                 my $fh;
981                                 ($fh, $path)=File::Temp::tempfile(undef, UNLINK => 1);
982                                 safe_git(
983                                         error_handler => sub { error("failed writing temp file '$path': ".shift."."); },
984                                         stdout => $fh,
985                                         cmdline => ['git', 'show', $detail->{sha1_to}],
986                                 );
987                         }
989                         push @rets, {
990                                 file => $file,
991                                 action => $action,
992                                 path => $path,
993                         };
994                 }
995         }
997         return @rets;
1000 sub rcs_receive () {
1001         my @rets;
1002         while (<>) {
1003                 chomp;
1004                 my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
1006                 # only allow changes to gitmaster_branch
1007                 if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
1008                         error sprintf(gettext("you are not allowed to change %s"), $refname);
1009                 }
1011                 # Avoid chdir when running git here, because the changes
1012                 # are in the master git repo, not the srcdir repo.
1013                 # (Also, if a subdir is involved, we don't want to chdir to
1014                 # it and only see changes in it.)
1015                 # The pre-receive hook already puts us in the right place.
1016                 in_git_dir(".", sub {
1017                         push @rets, git_parse_changes(0, git_commit_info($oldrev."..".$newrev));
1018                 });
1019         }
1021         return reverse @rets;
1024 sub rcs_preprevert ($) {
1025         my $rev=shift;
1026         my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
1028         my @undo;      # undo stack for cleanup in case of an error
1030         ensure_committer();
1032         # Examine changes from root of git repo, not from any subdir,
1033         # in order to see all changes.
1034         my ($subdir, $rootdir) = git_find_root();
1035         return in_git_dir($rootdir, sub {
1036                 my @commits=git_commit_info($sha1, 1);
1037         
1038                 if (! @commits) {
1039                         error "unknown commit"; # just in case
1040                 }
1042                 # git revert will fail on merge commits. Add a nice message.
1043                 if (exists $commits[0]->{parents} &&
1044                     @{$commits[0]->{parents}} > 1) {
1045                         error gettext("you are not allowed to revert a merge");
1046                 }
1048                 # Due to the presence of rename-detection, we cannot actually
1049                 # see what will happen in a revert without trying it.
1050                 # But we can guess, which is enough to rule out most changes
1051                 # that we won't allow reverting.
1052                 git_parse_changes(1, @commits);
1054                 my $failure;
1055                 my @ret;
1056                 eval {
1057                         my $branch = "ikiwiki_revert_${sha1}"; # supposed to be unique
1059                         push @undo, sub {
1060                                 run_or_cry_in($rootdir, 'git', 'branch', '-D', $branch) if $failure;
1061                         };
1062                         if (run_or_non_in($rootdir, 'git', 'rev-parse', '--quiet', '--verify', $branch)) {
1063                                 run_or_non_in($rootdir, 'git', 'branch', '-D', $branch);
1064                         }
1065                         run_or_die_in($rootdir, 'git', 'branch', $branch, $config{gitmaster_branch});
1067                         my $working = create_temp_working_dir($rootdir, $branch);
1069                         push @undo, sub {
1070                                 remove_tree($working);
1071                         };
1073                         run_or_die_in($working, 'git', 'checkout', '--quiet', '--force', $branch);
1074                         run_or_die_in($working, 'git', 'revert', '--no-commit', $sha1);
1075                         run_or_die_in($working, 'git', 'commit', '-m', "revert $sha1", '-a');
1077                         my @raw_lines;
1078                         @raw_lines = run_or_die_in($rootdir, 'git', 'diff', '--pretty=raw',
1079                                 '--raw', '--abbrev=40', '--always', '--no-renames',
1080                                 "..${branch}");
1082                         my $ci = {
1083                                 details => [parse_changed_files(\@raw_lines)],
1084                         };
1086                         @ret = git_parse_changes(0, $ci);
1087                 };
1088                 $failure = $@;
1090                 # Process undo stack (in reverse order).  By policy cleanup
1091                 # actions should normally print a warning on failure.
1092                 while (my $handle = pop @undo) {
1093                         $handle->();
1094                 }
1096                 if ($failure) {
1097                         my $message = sprintf(gettext("Failed to revert commit %s"), $sha1);
1098                         error("$message\n$failure\n");
1099                 }
1101                 return @ret;
1102         });
1105 sub rcs_revert ($) {
1106         # Try to revert the given rev; returns undef on _success_.
1107         my $rev = shift;
1108         my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
1110         ensure_committer();
1112         if (run_or_non('git', 'cherry-pick', '--no-commit', "ikiwiki_revert_$sha1")) {
1113                 return undef;
1114         }
1115         else {
1116                 run_or_non('git', 'branch', '-D', "ikiwiki_revert_$sha1");
1117                 return sprintf(gettext("Failed to revert commit %s"), $sha1);
1118         }