]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/git.pm
333b4ac87ca434c67fbd5960c24a5ba506b7991b
[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 (! @git_dir_stack) {
217                         chdir $config{srcdir}
218                             or error("cannot chdir to $config{srcdir}: $!");
219                 }
220                 else {
221                         chdir $git_dir_stack[0]
222                             or error("cannot chdir to $git_dir_stack[0]: $!");
223                 }
224                 exec @{$params{cmdline}} or error("Cannot exec '@{$params{cmdline}}': $!");
225         }
226         # In parent.
228         # git output is probably utf-8 encoded, but may contain
229         # other encodings or invalidly encoded stuff. So do not rely
230         # on the normal utf-8 IO layer, decode it by hand.
231         binmode($OUT);
233         my @lines;
234         while (<$OUT>) {
235                 $_=decode_utf8($_, 0);
237                 chomp;
239                 if (! defined $params{data_handler}) {
240                         push @lines, $_;
241                 }
242                 else {
243                         last unless $params{data_handler}->($_);
244                 }
245         }
247         close $OUT;
249         $params{error_handler}->("'@{$params{cmdline}}' failed: $!") if $? && $params{error_handler};
251         return wantarray ? @lines : ($? == 0);
253 # Convenient wrappers.
254 sub run_or_die ($@) { safe_git(error_handler => \&error, cmdline => \@_) }
255 sub run_or_cry ($@) { safe_git(error_handler => sub { warn @_ }, cmdline => \@_) }
256 sub run_or_non ($@) { safe_git(cmdline => \@_) }
258 sub ensure_committer {
259         if (! length $ENV{GIT_AUTHOR_NAME} || ! length $ENV{GIT_COMMITTER_NAME}) {
260                 my $name = join('', run_or_non("git", "config", "user.name"));
261                 if (! length $name) {
262                         run_or_die("git", "config", "user.name", "IkiWiki");
263                 }
264         }
266         if (! length $ENV{GIT_AUTHOR_EMAIL} || ! length $ENV{GIT_COMMITTER_EMAIL}) {
267                 my $email = join('', run_or_non("git", "config", "user.email"));
268                 if (! length $email) {
269                         run_or_die("git", "config", "user.email", "ikiwiki.info");
270                 }
271         }
274 sub merge_past ($$$) {
275         # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
276         # Git merge commands work with the committed changes, except in the
277         # implicit case of '-m' of git checkout(1).  So we should invent a
278         # kludge here.  In principle, we need to create a throw-away branch
279         # in preparing for the merge itself.  Since branches are cheap (and
280         # branching is fast), this shouldn't cost high.
281         #
282         # The main problem is the presence of _uncommitted_ local changes.  One
283         # possible approach to get rid of this situation could be that we first
284         # make a temporary commit in the master branch and later restore the
285         # initial state (this is possible since Git has the ability to undo a
286         # commit, i.e. 'git reset --soft HEAD^').  The method can be summarized
287         # as follows:
288         #
289         #       - create a diff of HEAD:current-sha1
290         #       - dummy commit
291         #       - create a dummy branch and switch to it
292         #       - rewind to past (reset --hard to the current-sha1)
293         #       - apply the diff and commit
294         #       - switch to master and do the merge with the dummy branch
295         #       - make a soft reset (undo the last commit of master)
296         #
297         # The above method has some drawbacks: (1) it needs a redundant commit
298         # just to get rid of local changes, (2) somewhat slow because of the
299         # required system forks.  Until someone points a more straight method
300         # (which I would be grateful) I have implemented an alternative method.
301         # In this approach, we hide all the modified files from Git by renaming
302         # them (using the 'rename' builtin) and later restore those files in
303         # the throw-away branch (that is, we put the files themselves instead
304         # of applying a patch).
306         my ($sha1, $file, $message) = @_;
308         my @undo;      # undo stack for cleanup in case of an error
309         my $conflict;  # file content with conflict markers
311         ensure_committer();
313         eval {
314                 # Hide local changes from Git by renaming the modified file.
315                 # Relative paths must be converted to absolute for renaming.
316                 my ($target, $hidden) = (
317                     "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
318                 );
319                 rename($target, $hidden)
320                     or error("rename '$target' to '$hidden' failed: $!");
321                 # Ensure to restore the renamed file on error.
322                 push @undo, sub {
323                         return if ! -e "$hidden"; # already renamed
324                         rename($hidden, $target)
325                             or warn "rename '$hidden' to '$target' failed: $!";
326                 };
328                 my $branch = "throw_away_${sha1}"; # supposed to be unique
330                 # Create a throw-away branch and rewind backward.
331                 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
332                 run_or_die('git', 'branch', $branch, $sha1);
334                 # Switch to throw-away branch for the merge operation.
335                 push @undo, sub {
336                         if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
337                                 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
338                         }
339                 };
340                 run_or_die('git', 'checkout', $branch);
342                 # Put the modified file in _this_ branch.
343                 rename($hidden, $target)
344                     or error("rename '$hidden' to '$target' failed: $!");
346                 # _Silently_ commit all modifications in the current branch.
347                 run_or_non('git', 'commit', '-m', $message, '-a');
348                 # ... and re-switch to master.
349                 run_or_die('git', 'checkout', $config{gitmaster_branch});
351                 # Attempt to merge without complaining.
352                 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
353                         $conflict = readfile($target);
354                         run_or_die('git', 'reset', '--hard');
355                 }
356         };
357         my $failure = $@;
359         # Process undo stack (in reverse order).  By policy cleanup
360         # actions should normally print a warning on failure.
361         while (my $handle = pop @undo) {
362                 $handle->();
363         }
365         error("Git merge failed!\n$failure\n") if $failure;
367         return $conflict;
370 sub decode_git_file ($) {
371         my $file=shift;
373         # git does not output utf-8 filenames, but instead
374         # double-quotes them with the utf-8 characters
375         # escaped as \nnn\nnn.
376         if ($file =~ m/^"(.*)"$/) {
377                 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
378         }
380         # strip prefix if in a subdir
381         if (! defined $prefix) {
382                 ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
383                 if (! defined $prefix) {
384                         $prefix="";
385                 }
386         }
387         $file =~ s/^\Q$prefix\E//;
389         return decode("utf8", $file);
392 sub parse_diff_tree ($) {
393         # Parse the raw diff tree chunk and return the info hash.
394         # See git-diff-tree(1) for the syntax.
395         my $dt_ref = shift;
397         # End of stream?
398         return if ! @{ $dt_ref } ||
399                   !defined $dt_ref->[0] || !length $dt_ref->[0];
401         my %ci;
402         # Header line.
403         while (my $line = shift @{ $dt_ref }) {
404                 return if $line !~ m/^(.+) ($sha1_pattern)/;
406                 my $sha1 = $2;
407                 $ci{'sha1'} = $sha1;
408                 last;
409         }
411         # Identification lines for the commit.
412         while (my $line = shift @{ $dt_ref }) {
413                 # Regexps are semi-stolen from gitweb.cgi.
414                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
415                         $ci{'tree'} = $1;
416                 }
417                 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
418                         # XXX: collecting in reverse order
419                         push @{ $ci{'parents'} }, $1;
420                 }
421                 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
422                         my ($who, $name, $epoch, $tz) =
423                            ($1,   $2,    $3,     $4 );
425                         $ci{  $who          } = $name;
426                         $ci{ "${who}_epoch" } = $epoch;
427                         $ci{ "${who}_tz"    } = $tz;
429                         if ($name =~ m/^([^<]+)\s+<([^@>]+)/) {
430                                 $ci{"${who}_name"} = $1;
431                                 $ci{"${who}_username"} = $2;
432                         }
433                         elsif ($name =~ m/^([^<]+)\s+<>$/) {
434                                 $ci{"${who}_username"} = $1;
435                         }
436                         else {
437                                 $ci{"${who}_username"} = $name;
438                         }
439                 }
440                 elsif ($line =~ m/^$/) {
441                         # Trailing empty line signals next section.
442                         last;
443                 }
444         }
446         debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
447         
448         if (defined $ci{'parents'}) {
449                 $ci{'parent'} = @{ $ci{'parents'} }[0];
450         }
451         else {
452                 $ci{'parent'} = 0 x 40;
453         }
455         # Commit message (optional).
456         while ($dt_ref->[0] =~ /^    /) {
457                 my $line = shift @{ $dt_ref };
458                 $line =~ s/^    //;
459                 push @{ $ci{'comment'} }, $line;
460         }
461         shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
463         $ci{details} = [parse_changed_files($dt_ref)];
465         return \%ci;
468 sub parse_changed_files {
469         my $dt_ref = shift;
471         my @files;
473         # Modified files.
474         while (my $line = shift @{ $dt_ref }) {
475                 if ($line =~ m{^
476                         (:+)       # number of parents
477                         ([^\t]+)\t # modes, sha1, status
478                         (.*)       # file names
479                 $}xo) {
480                         my $num_parents = length $1;
481                         my @tmp = split(" ", $2);
482                         my ($file, $file_to) = split("\t", $3);
483                         my @mode_from = splice(@tmp, 0, $num_parents);
484                         my $mode_to = shift(@tmp);
485                         my @sha1_from = splice(@tmp, 0, $num_parents);
486                         my $sha1_to = shift(@tmp);
487                         my $status = shift(@tmp);
489                         if (length $file) {
490                                 push @files, {
491                                         'file'      => decode_git_file($file),
492                                         'sha1_from' => $sha1_from[0],
493                                         'sha1_to'   => $sha1_to,
494                                         'mode_from' => $mode_from[0],
495                                         'mode_to'   => $mode_to,
496                                         'status'    => $status,
497                                 };
498                         }
499                         next;
500                 };
501                 last;
502         }
504         return @files;
507 sub git_commit_info ($;$) {
508         # Return an array of commit info hashes of num commits
509         # starting from the given sha1sum.
510         my ($sha1, $num) = @_;
512         my @opts;
513         push @opts, "--max-count=$num" if defined $num;
515         my @raw_lines = run_or_die('git', 'log', @opts,
516                 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
517                 '-r', $sha1, '--no-renames', '--', '.');
519         my @ci;
520         while (my $parsed = parse_diff_tree(\@raw_lines)) {
521                 push @ci, $parsed;
522         }
524         warn "Cannot parse commit info for '$sha1' commit" if !@ci;
526         return wantarray ? @ci : $ci[0];
529 sub rcs_find_changes ($) {
530         my $oldrev=shift;
532         # Note that git log will sometimes show files being added that
533         # don't exist. Particularly, git merge -s ours can result in a
534         # merge commit where some files were not really added.
535         # This is why the code below verifies that the files really
536         # exist.
537         my @raw_lines = run_or_die('git', 'log',
538                 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
539                 '--no-renames', , '--reverse',
540                 '-r', "$oldrev..HEAD", '--', '.');
542         # Due to --reverse, we see changes in chronological order.
543         my %changed;
544         my %deleted;
545         my $nullsha = 0 x 40;
546         my $newrev=$oldrev;
547         while (my $ci = parse_diff_tree(\@raw_lines)) {
548                 $newrev=$ci->{sha1};
549                 foreach my $i (@{$ci->{details}}) {
550                         my $file=$i->{file};
551                         if ($i->{sha1_to} eq $nullsha) {
552                                 if (! -e "$config{srcdir}/$file") {
553                                         delete $changed{$file};
554                                         $deleted{$file}=1;
555                                 }
556                         }
557                         else {
558                                 if (-e "$config{srcdir}/$file") {
559                                         delete $deleted{$file};
560                                         $changed{$file}=1;
561                                 }
562                         }
563                 }
564         }
566         return (\%changed, \%deleted, $newrev);
569 sub git_sha1_file ($) {
570         my $file=shift;
571         git_sha1("--", $file);
574 sub git_sha1 (@) {
575         # Ignore error since a non-existing file might be given.
576         my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
577                 '--', @_);
578         if (defined $sha1) {
579                 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
580         }
581         return defined $sha1 ? $sha1 : '';
584 sub rcs_get_current_rev () {
585         git_sha1();
588 sub rcs_update () {
589         # Update working directory.
591         ensure_committer();
593         if (length $config{gitorigin_branch}) {
594                 run_or_cry('git', 'pull', '--prune', $config{gitorigin_branch});
595         }
598 sub rcs_prepedit ($) {
599         # Return the commit sha1sum of the file when editing begins.
600         # This will be later used in rcs_commit if a merge is required.
601         my ($file) = @_;
603         return git_sha1_file($file);
606 sub rcs_commit (@) {
607         # Try to commit the page; returns undef on _success_ and
608         # a version of the page with the rcs's conflict markers on
609         # failure.
610         my %params=@_;
612         # Check to see if the page has been changed by someone else since
613         # rcs_prepedit was called.
614         my $cur    = git_sha1_file($params{file});
615         my $prev;
616         if (defined $params{token}) {
617                 ($prev) = $params{token} =~ /^($sha1_pattern)$/; # untaint
618         }
620         if (defined $cur && defined $prev && $cur ne $prev) {
621                 my $conflict = merge_past($prev, $params{file}, $dummy_commit_msg);
622                 return $conflict if defined $conflict;
623         }
625         return rcs_commit_helper(@_);
628 sub rcs_commit_staged (@) {
629         # Commits all staged changes. Changes can be staged using rcs_add,
630         # rcs_remove, and rcs_rename.
631         return rcs_commit_helper(@_);
634 sub rcs_commit_helper (@) {
635         my %params=@_;
636         
637         my %env=%ENV;
639         if (defined $params{session}) {
640                 # Set the commit author and email based on web session info.
641                 my $u;
642                 if (defined $params{session}->param("name")) {
643                         $u=$params{session}->param("name");
644                 }
645                 elsif (defined $params{session}->remote_addr()) {
646                         $u=$params{session}->remote_addr();
647                 }
648                 if (length $u) {
649                         $u=encode_utf8(IkiWiki::cloak($u));
650                         $ENV{GIT_AUTHOR_NAME}=$u;
651                 }
652                 else {
653                         $u = 'anonymous';
654                 }
655                 if (defined $params{session}->param("nickname")) {
656                         $u=encode_utf8($params{session}->param("nickname"));
657                         $u=~s/\s+/_/g;
658                         $u=~s/[^-_0-9[:alnum:]]+//g;
659                 }
660                 if (length $u) {
661                         $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
662                 }
663                 else {
664                         $ENV{GIT_AUTHOR_EMAIL}='anonymous@web';
665                 }
666         }
668         ensure_committer();
670         $params{message} = IkiWiki::possibly_foolish_untaint($params{message});
671         my @opts;
672         if ($params{message} !~ /\S/) {
673                 # Force git to allow empty commit messages.
674                 # (If this version of git supports it.)
675                 my ($version)=`git --version` =~ /git version (.*)/;
676                 if ($version ge "1.7.8") {
677                         push @opts, "--allow-empty-message", "--no-edit";
678                 }
679                 if ($version ge "1.7.2") {
680                         push @opts, "--allow-empty-message";
681                 }
682                 elsif ($version ge "1.5.4") {
683                         push @opts, '--cleanup=verbatim';
684                 }
685                 else {
686                         $params{message}.=".";
687                 }
688         }
689         if (exists $params{file}) {
690                 push @opts, '--', $params{file};
691         }
692         # git commit returns non-zero if nothing really changed.
693         # So we should ignore its exit status (hence run_or_non).
694         if (run_or_non('git', 'commit', '-m', $params{message}, '-q', @opts)) {
695                 if (length $config{gitorigin_branch}) {
696                         run_or_cry('git', 'push', $config{gitorigin_branch}, $config{gitmaster_branch});
697                 }
698         }
699         
700         %ENV=%env;
701         return undef; # success
704 sub rcs_add ($) {
705         # Add file to archive.
707         my ($file) = @_;
709         ensure_committer();
711         run_or_cry('git', 'add', '--', $file);
714 sub rcs_remove ($) {
715         # Remove file from archive.
717         my ($file) = @_;
719         ensure_committer();
721         run_or_cry('git', 'rm', '-f', '--', $file);
724 sub rcs_rename ($$) {
725         my ($src, $dest) = @_;
727         ensure_committer();
729         run_or_cry('git', 'mv', '-f', '--', $src, $dest);
732 sub rcs_recentchanges ($) {
733         # List of recent changes.
735         my ($num) = @_;
737         eval q{use Date::Parse};
738         error($@) if $@;
740         my @rets;
741         foreach my $ci (git_commit_info('HEAD', $num || 1)) {
742                 # Skip redundant commits.
743                 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
745                 my ($sha1, $when) = (
746                         $ci->{'sha1'},
747                         $ci->{'author_epoch'}
748                 );
750                 my @pages;
751                 foreach my $detail (@{ $ci->{'details'} }) {
752                         my $file = $detail->{'file'};
753                         my $efile = join('/',
754                                 map { uri_escape_utf8($_) } split('/', $file)
755                         );
757                         my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
758                         $diffurl =~ s/\[\[file\]\]/$efile/go;
759                         $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
760                         $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
761                         $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
762                         $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
764                         push @pages, {
765                                 page => pagename($file),
766                                 diffurl => $diffurl,
767                         };
768                 }
770                 my @messages;
771                 my $pastblank=0;
772                 foreach my $line (@{$ci->{'comment'}}) {
773                         $pastblank=1 if $line eq '';
774                         next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
775                         push @messages, { line => $line };
776                 }
778                 my $user=$ci->{'author_username'};
779                 my $web_commit = ($ci->{'author'} =~ /\@web>/);
780                 my $nickname;
782                 # Set nickname only if a non-url author_username is available,
783                 # and author_name is an url.
784                 if ($user !~ /:\/\// && defined $ci->{'author_name'} &&
785                     $ci->{'author_name'} =~ /:\/\//) {
786                         $nickname=$user;
787                         $user=$ci->{'author_name'};
788                 }
790                 # compatability code for old web commit messages
791                 if (! $web_commit &&
792                       defined $messages[0] &&
793                       $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
794                         $user = defined $2 ? "$2" : "$3";
795                         $messages[0]->{line} = $4;
796                         $web_commit=1;
797                 }
799                 push @rets, {
800                         rev        => $sha1,
801                         user       => $user,
802                         nickname   => $nickname,
803                         committype => $web_commit ? "web" : "git",
804                         when       => $when,
805                         message    => [@messages],
806                         pages      => [@pages],
807                 } if @pages;
809                 last if @rets >= $num;
810         }
812         return @rets;
815 sub rcs_diff ($;$) {
816         my $rev=shift;
817         my $maxlines=shift;
818         my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
819         my @lines;
820         my $addlines=sub {
821                 my $line=shift;
822                 return if defined $maxlines && @lines == $maxlines;
823                 push @lines, $line."\n"
824                         if (@lines || $line=~/^diff --git/);
825                 return 1;
826         };
827         safe_git(
828                 error_handler => undef,
829                 data_handler => $addlines,
830                 cmdline => ["git", "show", $sha1],
831         );
832         if (wantarray) {
833                 return @lines;
834         }
835         else {
836                 return join("", @lines);
837         }
841 my %time_cache;
843 sub findtimes ($$) {
844         my $file=shift;
845         my $id=shift; # 0 = mtime ; 1 = ctime
847         if (! keys %time_cache) {
848                 my $date;
849                 foreach my $line (run_or_die('git', 'log',
850                                 '--pretty=format:%at',
851                                 '--name-only', '--relative')) {
852                         if (! defined $date && $line =~ /^(\d+)$/) {
853                                 $date=$line;
854                         }
855                         elsif (! length $line) {
856                                 $date=undef;
857                         }
858                         else {
859                                 my $f=decode_git_file($line);
861                                 if (! $time_cache{$f}) {
862                                         $time_cache{$f}[0]=$date; # mtime
863                                 }
864                                 $time_cache{$f}[1]=$date; # ctime
865                         }
866                 }
867         }
869         return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
874 sub rcs_getctime ($) {
875         my $file=shift;
877         return findtimes($file, 1);
880 sub rcs_getmtime ($) {
881         my $file=shift;
883         return findtimes($file, 0);
887 my $ret;
888 sub git_find_root {
889         # The wiki may not be the only thing in the git repo.
890         # Determine if it is in a subdirectory by examining the srcdir,
891         # and its parents, looking for the .git directory.
893         return @$ret if defined $ret;
894         
895         my $subdir="";
896         my $dir=$config{srcdir};
897         while (! -d "$dir/.git") {
898                 $subdir=IkiWiki::basename($dir)."/".$subdir;
899                 $dir=IkiWiki::dirname($dir);
900                 if (! length $dir) {
901                         error("cannot determine root of git repo");
902                 }
903         }
905         $ret=[$subdir, $dir];
906         return @$ret;
911 sub git_parse_changes {
912         my $reverted = shift;
913         my @changes = @_;
915         my ($subdir, $rootdir) = git_find_root();
916         my @rets;
917         foreach my $ci (@changes) {
918                 foreach my $detail (@{ $ci->{'details'} }) {
919                         my $file = $detail->{'file'};
921                         # check that all changed files are in the subdir
922                         if (length $subdir &&
923                             ! ($file =~ s/^\Q$subdir\E//)) {
924                                 error sprintf(gettext("you are not allowed to change %s"), $file);
925                         }
927                         my ($action, $mode, $path);
928                         if ($detail->{'status'} =~ /^[M]+\d*$/) {
929                                 $action="change";
930                                 $mode=$detail->{'mode_to'};
931                         }
932                         elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
933                                 $action= $reverted ? "remove" : "add";
934                                 $mode=$detail->{'mode_to'};
935                         }
936                         elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
937                                 $action= $reverted ? "add" : "remove";
938                                 $mode=$detail->{'mode_from'};
939                         }
940                         else {
941                                 error "unknown status ".$detail->{'status'};
942                         }
944                         # test that the file mode is ok
945                         if ($mode !~ /^100[64][64][64]$/) {
946                                 error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
947                         }
948                         if ($action eq "change") {
949                                 if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
950                                         error gettext("you are not allowed to change file modes");
951                                 }
952                         }
954                         # extract attachment to temp file
955                         if (($action eq 'add' || $action eq 'change') &&
956                             ! pagetype($file)) {
957                                 eval q{use File::Temp};
958                                 die $@ if $@;
959                                 my $fh;
960                                 ($fh, $path)=File::Temp::tempfile(undef, UNLINK => 1);
961                                 my $cmd = "cd $git_dir_stack[0] && ".
962                                           "git show $detail->{sha1_to} > '$path'";
963                                 if (system($cmd) != 0) {
964                                         error("failed writing temp file '$path'.");
965                                 }
966                         }
968                         push @rets, {
969                                 file => $file,
970                                 action => $action,
971                                 path => $path,
972                         };
973                 }
974         }
976         return @rets;
979 sub rcs_receive () {
980         my @rets;
981         while (<>) {
982                 chomp;
983                 my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
985                 # only allow changes to gitmaster_branch
986                 if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
987                         error sprintf(gettext("you are not allowed to change %s"), $refname);
988                 }
990                 # Avoid chdir when running git here, because the changes
991                 # are in the master git repo, not the srcdir repo.
992                 # (Also, if a subdir is involved, we don't want to chdir to
993                 # it and only see changes in it.)
994                 # The pre-receive hook already puts us in the right place.
995                 in_git_dir(".", sub {
996                         push @rets, git_parse_changes(0, git_commit_info($oldrev."..".$newrev));
997                 });
998         }
1000         return reverse @rets;
1003 sub rcs_preprevert ($) {
1004         my $rev=shift;
1005         my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
1007         my @undo;      # undo stack for cleanup in case of an error
1009         ensure_committer();
1011         # Examine changes from root of git repo, not from any subdir,
1012         # in order to see all changes.
1013         my ($subdir, $rootdir) = git_find_root();
1014         return in_git_dir($rootdir, sub {
1015                 my @commits=git_commit_info($sha1, 1);
1016         
1017                 if (! @commits) {
1018                         error "unknown commit"; # just in case
1019                 }
1021                 # git revert will fail on merge commits. Add a nice message.
1022                 if (exists $commits[0]->{parents} &&
1023                     @{$commits[0]->{parents}} > 1) {
1024                         error gettext("you are not allowed to revert a merge");
1025                 }
1027                 # Due to the presence of rename-detection, we cannot actually
1028                 # see what will happen in a revert without trying it.
1029                 # But we can guess, which is enough to rule out most changes
1030                 # that we won't allow reverting.
1031                 git_parse_changes(1, @commits);
1033                 my $failure;
1034                 my @ret;
1035                 eval {
1036                         IkiWiki::disable_commit_hook();
1037                         push @undo, sub {
1038                                 IkiWiki::enable_commit_hook();
1039                         };
1040                         my $branch = "ikiwiki_revert_${sha1}"; # supposed to be unique
1042                         push @undo, sub {
1043                                 run_or_cry('git', 'branch', '-D', $branch) if $failure;
1044                         };
1045                         if (run_or_non('git', 'rev-parse', '--quiet', '--verify', $branch)) {
1046                                 run_or_non('git', 'branch', '-D', $branch);
1047                         }
1048                         run_or_die('git', 'branch', $branch, $config{gitmaster_branch});
1050                         my $working = create_temp_working_dir($rootdir, $branch);
1052                         push @undo, sub {
1053                                 remove_tree($working);
1054                         };
1056                         in_git_dir($working, sub {
1057                                 run_or_die('git', 'checkout', '--quiet', '--force', $branch);
1058                                 run_or_die('git', 'revert', '--no-commit', $sha1);
1059                                 run_or_die('git', 'commit', '-m', "revert $sha1", '-a');
1060                         });
1062                         my @raw_lines;
1063                         @raw_lines = run_or_die('git', 'diff', '--pretty=raw',
1064                                 '--raw', '--abbrev=40', '--always', '--no-renames',
1065                                 "..${branch}");
1067                         my $ci = {
1068                                 details => [parse_changed_files(\@raw_lines)],
1069                         };
1071                         @ret = git_parse_changes(0, $ci);
1072                 };
1073                 $failure = $@;
1075                 # Process undo stack (in reverse order).  By policy cleanup
1076                 # actions should normally print a warning on failure.
1077                 while (my $handle = pop @undo) {
1078                         $handle->();
1079                 }
1081                 if ($failure) {
1082                         my $message = sprintf(gettext("Failed to revert commit %s"), $sha1);
1083                         error("$message\n$failure\n");
1084                 }
1086                 return @ret;
1087         });
1090 sub rcs_revert ($) {
1091         # Try to revert the given rev; returns undef on _success_.
1092         my $rev = shift;
1093         my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
1095         ensure_committer();
1097         if (run_or_non('git', 'merge', '--ff-only', "ikiwiki_revert_$sha1")) {
1098                 return undef;
1099         }
1100         else {
1101                 run_or_non('git', 'branch', '-D', "ikiwiki_revert_$sha1");
1102                 return sprintf(gettext("Failed to revert commit %s"), $sha1);
1103         }