]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/git.pm
Try revert operations (on a branch) before approving them
[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         if (! length $ENV{GIT_AUTHOR_NAME} || ! length $ENV{GIT_COMMITTER_NAME}) {
225                 my $name = join('', run_or_non("git", "config", "user.name"));
226                 if (! length $name) {
227                         run_or_die("git", "config", "user.name", "IkiWiki");
228                 }
229         }
231         if (! length $ENV{GIT_AUTHOR_EMAIL} || ! length $ENV{GIT_COMMITTER_EMAIL}) {
232                 my $email = join('', run_or_non("git", "config", "user.email"));
233                 if (! length $email) {
234                         run_or_die("git", "config", "user.email", "ikiwiki.info");
235                 }
236         }
239 sub merge_past ($$$) {
240         # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
241         # Git merge commands work with the committed changes, except in the
242         # implicit case of '-m' of git checkout(1).  So we should invent a
243         # kludge here.  In principle, we need to create a throw-away branch
244         # in preparing for the merge itself.  Since branches are cheap (and
245         # branching is fast), this shouldn't cost high.
246         #
247         # The main problem is the presence of _uncommitted_ local changes.  One
248         # possible approach to get rid of this situation could be that we first
249         # make a temporary commit in the master branch and later restore the
250         # initial state (this is possible since Git has the ability to undo a
251         # commit, i.e. 'git reset --soft HEAD^').  The method can be summarized
252         # as follows:
253         #
254         #       - create a diff of HEAD:current-sha1
255         #       - dummy commit
256         #       - create a dummy branch and switch to it
257         #       - rewind to past (reset --hard to the current-sha1)
258         #       - apply the diff and commit
259         #       - switch to master and do the merge with the dummy branch
260         #       - make a soft reset (undo the last commit of master)
261         #
262         # The above method has some drawbacks: (1) it needs a redundant commit
263         # just to get rid of local changes, (2) somewhat slow because of the
264         # required system forks.  Until someone points a more straight method
265         # (which I would be grateful) I have implemented an alternative method.
266         # In this approach, we hide all the modified files from Git by renaming
267         # them (using the 'rename' builtin) and later restore those files in
268         # the throw-away branch (that is, we put the files themselves instead
269         # of applying a patch).
271         my ($sha1, $file, $message) = @_;
273         my @undo;      # undo stack for cleanup in case of an error
274         my $conflict;  # file content with conflict markers
276         ensure_committer();
278         eval {
279                 # Hide local changes from Git by renaming the modified file.
280                 # Relative paths must be converted to absolute for renaming.
281                 my ($target, $hidden) = (
282                     "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
283                 );
284                 rename($target, $hidden)
285                     or error("rename '$target' to '$hidden' failed: $!");
286                 # Ensure to restore the renamed file on error.
287                 push @undo, sub {
288                         return if ! -e "$hidden"; # already renamed
289                         rename($hidden, $target)
290                             or warn "rename '$hidden' to '$target' failed: $!";
291                 };
293                 my $branch = "throw_away_${sha1}"; # supposed to be unique
295                 # Create a throw-away branch and rewind backward.
296                 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
297                 run_or_die('git', 'branch', $branch, $sha1);
299                 # Switch to throw-away branch for the merge operation.
300                 push @undo, sub {
301                         if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
302                                 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
303                         }
304                 };
305                 run_or_die('git', 'checkout', $branch);
307                 # Put the modified file in _this_ branch.
308                 rename($hidden, $target)
309                     or error("rename '$hidden' to '$target' failed: $!");
311                 # _Silently_ commit all modifications in the current branch.
312                 run_or_non('git', 'commit', '-m', $message, '-a');
313                 # ... and re-switch to master.
314                 run_or_die('git', 'checkout', $config{gitmaster_branch});
316                 # Attempt to merge without complaining.
317                 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
318                         $conflict = readfile($target);
319                         run_or_die('git', 'reset', '--hard');
320                 }
321         };
322         my $failure = $@;
324         # Process undo stack (in reverse order).  By policy cleanup
325         # actions should normally print a warning on failure.
326         while (my $handle = pop @undo) {
327                 $handle->();
328         }
330         error("Git merge failed!\n$failure\n") if $failure;
332         return $conflict;
335 sub decode_git_file ($) {
336         my $file=shift;
338         # git does not output utf-8 filenames, but instead
339         # double-quotes them with the utf-8 characters
340         # escaped as \nnn\nnn.
341         if ($file =~ m/^"(.*)"$/) {
342                 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
343         }
345         # strip prefix if in a subdir
346         if (! defined $prefix) {
347                 ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
348                 if (! defined $prefix) {
349                         $prefix="";
350                 }
351         }
352         $file =~ s/^\Q$prefix\E//;
354         return decode("utf8", $file);
357 sub parse_diff_tree ($) {
358         # Parse the raw diff tree chunk and return the info hash.
359         # See git-diff-tree(1) for the syntax.
360         my $dt_ref = shift;
362         # End of stream?
363         return if ! @{ $dt_ref } ||
364                   !defined $dt_ref->[0] || !length $dt_ref->[0];
366         my %ci;
367         # Header line.
368         while (my $line = shift @{ $dt_ref }) {
369                 return if $line !~ m/^(.+) ($sha1_pattern)/;
371                 my $sha1 = $2;
372                 $ci{'sha1'} = $sha1;
373                 last;
374         }
376         # Identification lines for the commit.
377         while (my $line = shift @{ $dt_ref }) {
378                 # Regexps are semi-stolen from gitweb.cgi.
379                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
380                         $ci{'tree'} = $1;
381                 }
382                 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
383                         # XXX: collecting in reverse order
384                         push @{ $ci{'parents'} }, $1;
385                 }
386                 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
387                         my ($who, $name, $epoch, $tz) =
388                            ($1,   $2,    $3,     $4 );
390                         $ci{  $who          } = $name;
391                         $ci{ "${who}_epoch" } = $epoch;
392                         $ci{ "${who}_tz"    } = $tz;
394                         if ($name =~ m/^([^<]+)\s+<([^@>]+)/) {
395                                 $ci{"${who}_name"} = $1;
396                                 $ci{"${who}_username"} = $2;
397                         }
398                         elsif ($name =~ m/^([^<]+)\s+<>$/) {
399                                 $ci{"${who}_username"} = $1;
400                         }
401                         else {
402                                 $ci{"${who}_username"} = $name;
403                         }
404                 }
405                 elsif ($line =~ m/^$/) {
406                         # Trailing empty line signals next section.
407                         last;
408                 }
409         }
411         debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
412         
413         if (defined $ci{'parents'}) {
414                 $ci{'parent'} = @{ $ci{'parents'} }[0];
415         }
416         else {
417                 $ci{'parent'} = 0 x 40;
418         }
420         # Commit message (optional).
421         while ($dt_ref->[0] =~ /^    /) {
422                 my $line = shift @{ $dt_ref };
423                 $line =~ s/^    //;
424                 push @{ $ci{'comment'} }, $line;
425         }
426         shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
428         $ci{details} = [parse_changed_files($dt_ref)];
430         return \%ci;
433 sub parse_changed_files {
434         my $dt_ref = shift;
436         my @files;
438         # Modified files.
439         while (my $line = shift @{ $dt_ref }) {
440                 if ($line =~ m{^
441                         (:+)       # number of parents
442                         ([^\t]+)\t # modes, sha1, status
443                         (.*)       # file names
444                 $}xo) {
445                         my $num_parents = length $1;
446                         my @tmp = split(" ", $2);
447                         my ($file, $file_to) = split("\t", $3);
448                         my @mode_from = splice(@tmp, 0, $num_parents);
449                         my $mode_to = shift(@tmp);
450                         my @sha1_from = splice(@tmp, 0, $num_parents);
451                         my $sha1_to = shift(@tmp);
452                         my $status = shift(@tmp);
454                         if (length $file) {
455                                 push @files, {
456                                         'file'      => decode_git_file($file),
457                                         'sha1_from' => $sha1_from[0],
458                                         'sha1_to'   => $sha1_to,
459                                         'mode_from' => $mode_from[0],
460                                         'mode_to'   => $mode_to,
461                                         'status'    => $status,
462                                 };
463                         }
464                         next;
465                 };
466                 last;
467         }
469         return @files;
472 sub git_commit_info ($;$) {
473         # Return an array of commit info hashes of num commits
474         # starting from the given sha1sum.
475         my ($sha1, $num) = @_;
477         my @opts;
478         push @opts, "--max-count=$num" if defined $num;
480         my @raw_lines = run_or_die('git', 'log', @opts,
481                 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
482                 '-r', $sha1, '--no-renames', '--', '.');
484         my @ci;
485         while (my $parsed = parse_diff_tree(\@raw_lines)) {
486                 push @ci, $parsed;
487         }
489         warn "Cannot parse commit info for '$sha1' commit" if !@ci;
491         return wantarray ? @ci : $ci[0];
494 sub rcs_find_changes ($) {
495         my $oldrev=shift;
497         # Note that git log will sometimes show files being added that
498         # don't exist. Particularly, git merge -s ours can result in a
499         # merge commit where some files were not really added.
500         # This is why the code below verifies that the files really
501         # exist.
502         my @raw_lines = run_or_die('git', 'log',
503                 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
504                 '--no-renames', , '--reverse',
505                 '-r', "$oldrev..HEAD", '--', '.');
507         # Due to --reverse, we see changes in chronological order.
508         my %changed;
509         my %deleted;
510         my $nullsha = 0 x 40;
511         my $newrev=$oldrev;
512         while (my $ci = parse_diff_tree(\@raw_lines)) {
513                 $newrev=$ci->{sha1};
514                 foreach my $i (@{$ci->{details}}) {
515                         my $file=$i->{file};
516                         if ($i->{sha1_to} eq $nullsha) {
517                                 if (! -e "$config{srcdir}/$file") {
518                                         delete $changed{$file};
519                                         $deleted{$file}=1;
520                                 }
521                         }
522                         else {
523                                 if (-e "$config{srcdir}/$file") {
524                                         delete $deleted{$file};
525                                         $changed{$file}=1;
526                                 }
527                         }
528                 }
529         }
531         return (\%changed, \%deleted, $newrev);
534 sub git_sha1_file ($) {
535         my $file=shift;
536         git_sha1("--", $file);
539 sub git_sha1 (@) {
540         # Ignore error since a non-existing file might be given.
541         my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
542                 '--', @_);
543         if (defined $sha1) {
544                 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
545         }
546         return defined $sha1 ? $sha1 : '';
549 sub rcs_get_current_rev () {
550         git_sha1();
553 sub rcs_update () {
554         # Update working directory.
556         ensure_committer();
558         if (length $config{gitorigin_branch}) {
559                 run_or_cry('git', 'pull', '--prune', $config{gitorigin_branch});
560         }
563 sub rcs_prepedit ($) {
564         # Return the commit sha1sum of the file when editing begins.
565         # This will be later used in rcs_commit if a merge is required.
566         my ($file) = @_;
568         return git_sha1_file($file);
571 sub rcs_commit (@) {
572         # Try to commit the page; returns undef on _success_ and
573         # a version of the page with the rcs's conflict markers on
574         # failure.
575         my %params=@_;
577         # Check to see if the page has been changed by someone else since
578         # rcs_prepedit was called.
579         my $cur    = git_sha1_file($params{file});
580         my $prev;
581         if (defined $params{token}) {
582                 ($prev) = $params{token} =~ /^($sha1_pattern)$/; # untaint
583         }
585         if (defined $cur && defined $prev && $cur ne $prev) {
586                 my $conflict = merge_past($prev, $params{file}, $dummy_commit_msg);
587                 return $conflict if defined $conflict;
588         }
590         return rcs_commit_helper(@_);
593 sub rcs_commit_staged (@) {
594         # Commits all staged changes. Changes can be staged using rcs_add,
595         # rcs_remove, and rcs_rename.
596         return rcs_commit_helper(@_);
599 sub rcs_commit_helper (@) {
600         my %params=@_;
601         
602         my %env=%ENV;
604         if (defined $params{session}) {
605                 # Set the commit author and email based on web session info.
606                 my $u;
607                 if (defined $params{session}->param("name")) {
608                         $u=$params{session}->param("name");
609                 }
610                 elsif (defined $params{session}->remote_addr()) {
611                         $u=$params{session}->remote_addr();
612                 }
613                 if (length $u) {
614                         $u=encode_utf8($u);
615                         $ENV{GIT_AUTHOR_NAME}=$u;
616                 }
617                 else {
618                         $u = 'anonymous';
619                 }
620                 if (defined $params{session}->param("nickname")) {
621                         $u=encode_utf8($params{session}->param("nickname"));
622                         $u=~s/\s+/_/g;
623                         $u=~s/[^-_0-9[:alnum:]]+//g;
624                 }
625                 if (length $u) {
626                         $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
627                 }
628                 else {
629                         $ENV{GIT_AUTHOR_EMAIL}='anonymous@web';
630                 }
631         }
633         ensure_committer();
635         $params{message} = IkiWiki::possibly_foolish_untaint($params{message});
636         my @opts;
637         if ($params{message} !~ /\S/) {
638                 # Force git to allow empty commit messages.
639                 # (If this version of git supports it.)
640                 my ($version)=`git --version` =~ /git version (.*)/;
641                 if ($version ge "1.7.8") {
642                         push @opts, "--allow-empty-message", "--no-edit";
643                 }
644                 if ($version ge "1.7.2") {
645                         push @opts, "--allow-empty-message";
646                 }
647                 elsif ($version ge "1.5.4") {
648                         push @opts, '--cleanup=verbatim';
649                 }
650                 else {
651                         $params{message}.=".";
652                 }
653         }
654         if (exists $params{file}) {
655                 push @opts, '--', $params{file};
656         }
657         # git commit returns non-zero if nothing really changed.
658         # So we should ignore its exit status (hence run_or_non).
659         if (run_or_non('git', 'commit', '-m', $params{message}, '-q', @opts)) {
660                 if (length $config{gitorigin_branch}) {
661                         run_or_cry('git', 'push', $config{gitorigin_branch}, $config{gitmaster_branch});
662                 }
663         }
664         
665         %ENV=%env;
666         return undef; # success
669 sub rcs_add ($) {
670         # Add file to archive.
672         my ($file) = @_;
674         ensure_committer();
676         run_or_cry('git', 'add', '--', $file);
679 sub rcs_remove ($) {
680         # Remove file from archive.
682         my ($file) = @_;
684         ensure_committer();
686         run_or_cry('git', 'rm', '-f', '--', $file);
689 sub rcs_rename ($$) {
690         my ($src, $dest) = @_;
692         ensure_committer();
694         run_or_cry('git', 'mv', '-f', '--', $src, $dest);
697 sub rcs_recentchanges ($) {
698         # List of recent changes.
700         my ($num) = @_;
702         eval q{use Date::Parse};
703         error($@) if $@;
705         my @rets;
706         foreach my $ci (git_commit_info('HEAD', $num || 1)) {
707                 # Skip redundant commits.
708                 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
710                 my ($sha1, $when) = (
711                         $ci->{'sha1'},
712                         $ci->{'author_epoch'}
713                 );
715                 my @pages;
716                 foreach my $detail (@{ $ci->{'details'} }) {
717                         my $file = $detail->{'file'};
718                         my $efile = join('/',
719                                 map { uri_escape_utf8($_) } split('/', $file)
720                         );
722                         my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
723                         $diffurl =~ s/\[\[file\]\]/$efile/go;
724                         $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
725                         $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
726                         $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
727                         $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
729                         push @pages, {
730                                 page => pagename($file),
731                                 diffurl => $diffurl,
732                         };
733                 }
735                 my @messages;
736                 my $pastblank=0;
737                 foreach my $line (@{$ci->{'comment'}}) {
738                         $pastblank=1 if $line eq '';
739                         next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
740                         push @messages, { line => $line };
741                 }
743                 my $user=$ci->{'author_username'};
744                 my $web_commit = ($ci->{'author'} =~ /\@web>/);
745                 my $nickname;
747                 # Set nickname only if a non-url author_username is available,
748                 # and author_name is an url.
749                 if ($user !~ /:\/\// && defined $ci->{'author_name'} &&
750                     $ci->{'author_name'} =~ /:\/\//) {
751                         $nickname=$user;
752                         $user=$ci->{'author_name'};
753                 }
755                 # compatability code for old web commit messages
756                 if (! $web_commit &&
757                       defined $messages[0] &&
758                       $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
759                         $user = defined $2 ? "$2" : "$3";
760                         $messages[0]->{line} = $4;
761                         $web_commit=1;
762                 }
764                 push @rets, {
765                         rev        => $sha1,
766                         user       => $user,
767                         nickname   => $nickname,
768                         committype => $web_commit ? "web" : "git",
769                         when       => $when,
770                         message    => [@messages],
771                         pages      => [@pages],
772                 } if @pages;
774                 last if @rets >= $num;
775         }
777         return @rets;
780 sub rcs_diff ($;$) {
781         my $rev=shift;
782         my $maxlines=shift;
783         my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
784         my @lines;
785         my $addlines=sub {
786                 my $line=shift;
787                 return if defined $maxlines && @lines == $maxlines;
788                 push @lines, $line."\n"
789                         if (@lines || $line=~/^diff --git/);
790                 return 1;
791         };
792         safe_git(undef, $addlines, "git", "show", $sha1);
793         if (wantarray) {
794                 return @lines;
795         }
796         else {
797                 return join("", @lines);
798         }
802 my %time_cache;
804 sub findtimes ($$) {
805         my $file=shift;
806         my $id=shift; # 0 = mtime ; 1 = ctime
808         if (! keys %time_cache) {
809                 my $date;
810                 foreach my $line (run_or_die('git', 'log',
811                                 '--pretty=format:%at',
812                                 '--name-only', '--relative')) {
813                         if (! defined $date && $line =~ /^(\d+)$/) {
814                                 $date=$line;
815                         }
816                         elsif (! length $line) {
817                                 $date=undef;
818                         }
819                         else {
820                                 my $f=decode_git_file($line);
822                                 if (! $time_cache{$f}) {
823                                         $time_cache{$f}[0]=$date; # mtime
824                                 }
825                                 $time_cache{$f}[1]=$date; # ctime
826                         }
827                 }
828         }
830         return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
835 sub rcs_getctime ($) {
836         my $file=shift;
838         return findtimes($file, 1);
841 sub rcs_getmtime ($) {
842         my $file=shift;
844         return findtimes($file, 0);
848 my $ret;
849 sub git_find_root {
850         # The wiki may not be the only thing in the git repo.
851         # Determine if it is in a subdirectory by examining the srcdir,
852         # and its parents, looking for the .git directory.
854         return @$ret if defined $ret;
855         
856         my $subdir="";
857         my $dir=$config{srcdir};
858         while (! -d "$dir/.git") {
859                 $subdir=IkiWiki::basename($dir)."/".$subdir;
860                 $dir=IkiWiki::dirname($dir);
861                 if (! length $dir) {
862                         error("cannot determine root of git repo");
863                 }
864         }
866         $ret=[$subdir, $dir];
867         return @$ret;
872 sub git_parse_changes {
873         my $reverted = shift;
874         my @changes = @_;
876         my ($subdir, $rootdir) = git_find_root();
877         my @rets;
878         foreach my $ci (@changes) {
879                 foreach my $detail (@{ $ci->{'details'} }) {
880                         my $file = $detail->{'file'};
882                         # check that all changed files are in the subdir
883                         if (length $subdir &&
884                             ! ($file =~ s/^\Q$subdir\E//)) {
885                                 error sprintf(gettext("you are not allowed to change %s"), $file);
886                         }
888                         my ($action, $mode, $path);
889                         if ($detail->{'status'} =~ /^[M]+\d*$/) {
890                                 $action="change";
891                                 $mode=$detail->{'mode_to'};
892                         }
893                         elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
894                                 $action= $reverted ? "remove" : "add";
895                                 $mode=$detail->{'mode_to'};
896                         }
897                         elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
898                                 $action= $reverted ? "add" : "remove";
899                                 $mode=$detail->{'mode_from'};
900                         }
901                         else {
902                                 error "unknown status ".$detail->{'status'};
903                         }
905                         # test that the file mode is ok
906                         if ($mode !~ /^100[64][64][64]$/) {
907                                 error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
908                         }
909                         if ($action eq "change") {
910                                 if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
911                                         error gettext("you are not allowed to change file modes");
912                                 }
913                         }
915                         # extract attachment to temp file
916                         if (($action eq 'add' || $action eq 'change') &&
917                             ! pagetype($file)) {
918                                 eval q{use File::Temp};
919                                 die $@ if $@;
920                                 my $fh;
921                                 ($fh, $path)=File::Temp::tempfile(undef, UNLINK => 1);
922                                 my $cmd = "cd $git_dir && ".
923                                           "git show $detail->{sha1_to} > '$path'";
924                                 if (system($cmd) != 0) {
925                                         error("failed writing temp file '$path'.");
926                                 }
927                         }
929                         push @rets, {
930                                 file => $file,
931                                 action => $action,
932                                 path => $path,
933                         };
934                 }
935         }
937         return @rets;
940 sub rcs_receive () {
941         my @rets;
942         while (<>) {
943                 chomp;
944                 my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
946                 # only allow changes to gitmaster_branch
947                 if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
948                         error sprintf(gettext("you are not allowed to change %s"), $refname);
949                 }
951                 # Avoid chdir when running git here, because the changes
952                 # are in the master git repo, not the srcdir repo.
953                 # (Also, if a subdir is involved, we don't want to chdir to
954                 # it and only see changes in it.)
955                 # The pre-receive hook already puts us in the right place.
956                 in_git_dir(".", sub {
957                         push @rets, git_parse_changes(0, git_commit_info($oldrev."..".$newrev));
958                 });
959         }
961         return reverse @rets;
964 sub rcs_preprevert ($) {
965         my $rev=shift;
966         my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
968         my @undo;      # undo stack for cleanup in case of an error
970         ensure_committer();
972         # Examine changes from root of git repo, not from any subdir,
973         # in order to see all changes.
974         my ($subdir, $rootdir) = git_find_root();
975         return in_git_dir($rootdir, sub {
976                 my @commits=git_commit_info($sha1, 1);
977         
978                 if (! @commits) {
979                         error "unknown commit"; # just in case
980                 }
982                 # git revert will fail on merge commits. Add a nice message.
983                 if (exists $commits[0]->{parents} &&
984                     @{$commits[0]->{parents}} > 1) {
985                         error gettext("you are not allowed to revert a merge");
986                 }
988                 # Due to the presence of rename-detection, we cannot actually
989                 # see what will happen in a revert without trying it.
990                 # But we can guess, which is enough to rule out most changes
991                 # that we won't allow reverting.
992                 git_parse_changes(1, @commits);
994                 my $failure;
995                 my @ret;
996                 # If it looks OK, do it for real, on a branch.
997                 eval {
998                         IkiWiki::disable_commit_hook();
999                         push @undo, sub {
1000                                 IkiWiki::enable_commit_hook();
1001                         };
1002                         my $branch = "ikiwiki_revert_${sha1}"; # supposed to be unique
1004                         push @undo, sub {
1005                                 run_or_cry('git', 'branch', '-D', $branch) if $failure;
1006                         };
1007                         if (run_or_non('git', 'rev-parse', '--quiet', '--verify', $branch)) {
1008                                 run_or_non('git', 'branch', '-D', $branch);
1009                         }
1010                         run_or_die('git', 'branch', $branch, $config{gitmaster_branch});
1012                         push @undo, sub {
1013                                 if (!run_or_cry('git', 'checkout', '--quiet', $config{gitmaster_branch})) {
1014                                         run_or_cry('git', 'checkout','-f', '--quiet', $config{gitmaster_branch});
1015                                 }
1016                         };
1017                         run_or_die('git', 'checkout', '--quiet', $branch);
1019                         run_or_die('git', 'revert', '--no-commit', $sha1);
1020                         run_or_non('git', 'commit', '-m', "revert $sha1", '-a');
1022                         # Re-switch to master.
1023                         run_or_die('git', 'checkout', '--quiet', $config{gitmaster_branch});
1025                         my @raw_lines;
1026                         @raw_lines = run_or_die('git', 'diff', '--pretty=raw',
1027                                 '--raw', '--abbrev=40', '--always', '--no-renames',
1028                                 "ikiwiki_revert_${sha1}..");
1030                         my $ci = {
1031                                 details => [parse_changed_files(\@raw_lines)],
1032                         };
1034                         @ret = git_parse_changes(0, $ci);
1035                 };
1036                 $failure = $@;
1038                 # Process undo stack (in reverse order).  By policy cleanup
1039                 # actions should normally print a warning on failure.
1040                 while (my $handle = pop @undo) {
1041                         $handle->();
1042                 }
1044                 if ($failure) {
1045                         my $message = sprintf(gettext("Failed to revert commit %s"), $sha1);
1046                         error("$message\n$failure\n");
1047                 }
1049                 return @ret;
1050         });
1053 sub rcs_revert ($) {
1054         # Try to revert the given rev; returns undef on _success_.
1055         my $rev = shift;
1056         my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
1058         ensure_committer();
1060         if (run_or_non('git', 'merge', '--ff-only', "ikiwiki_revert_$sha1")) {
1061                 return undef;
1062         }
1063         else {
1064                 run_or_non('git', 'branch', '-D', "ikiwiki_revert_$sha1");
1065                 return sprintf(gettext("Failed to revert commit %s"), $sha1);
1066         }