]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/git.pm
git: don't redundantly pass "--" to git_sha1
[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 # Loosely based on git-new-workdir from git contrib.
158 sub create_temp_working_dir ($$) {
159         my $rootdir = shift;
160         my $branch = shift;
161         my $working = "$rootdir/.git/ikiwiki-temp-working";
162         remove_tree($working);
164         foreach my $dir ("", ".git") {
165                 if (!mkdir("$working/$dir")) {
166                         error("Unable to create $working/$dir: $!");
167                 }
168         }
170         # Hooks are deliberately not included: we will commit to the temporary
171         # branch that is used in the temporary working tree, and we don't want
172         # to run the post-commit hook there.
173         #
174         # logs/refs is not included because we don't use the reflog.
175         # remotes, rr-cache, svn are similarly excluded.
176         foreach my $link ("config", "refs", "objects", "info", "packed-refs") {
177                 if (!symlink("../../$link", "$working/.git/$link")) {
178                         error("Unable to create symlink $working/.git/$link: $!");
179                 }
180         }
182         open (my $out, '>', "$working/.git/HEAD") or
183                 error("failed to write $working.git/HEAD: $!");
184         print $out "ref: refs/heads/$branch\n" or
185                 error("failed to write $working.git/HEAD: $!");
186         close $out or
187                 error("failed to write $working.git/HEAD: $!");
188         return $working;
191 sub safe_git {
192         # Start a child process safely without resorting to /bin/sh.
193         # Returns command output (in list content) or success state
194         # (in scalar context), or runs the specified data handler.
196         my %params = @_;
198         my $pid = open my $OUT, "-|";
200         error("Working directory not specified") unless defined $params{chdir};
201         error("Cannot fork: $!") if !defined $pid;
203         if (!$pid) {
204                 # In child.
205                 # Git commands want to be in wc.
206                 if ($params{chdir} ne '.') {
207                         chdir $params{chdir}
208                             or error("cannot chdir to $params{chdir}: $!");
209                 }
211                 if ($params{stdout}) {
212                         open(STDOUT, '>&', $params{stdout}) or error("Cannot reopen stdout: $!");
213                 }
215                 exec @{$params{cmdline}} or error("Cannot exec '@{$params{cmdline}}': $!");
216         }
217         # In parent.
219         # git output is probably utf-8 encoded, but may contain
220         # other encodings or invalidly encoded stuff. So do not rely
221         # on the normal utf-8 IO layer, decode it by hand.
222         binmode($OUT);
224         my @lines;
225         while (<$OUT>) {
226                 $_=decode_utf8($_, 0);
228                 chomp;
230                 if (! defined $params{data_handler}) {
231                         push @lines, $_;
232                 }
233                 else {
234                         last unless $params{data_handler}->($_);
235                 }
236         }
238         close $OUT;
240         $params{error_handler}->("'@{$params{cmdline}}' failed: $!") if $? && $params{error_handler};
242         return wantarray ? @lines : ($? == 0);
244 # Convenient wrappers.
245 sub run_or_die_in ($$@) {
246         my $dir = shift;
247         safe_git(chdir => $dir, error_handler => \&error, cmdline => \@_);
249 sub run_or_cry_in ($$@) {
250         my $dir = shift;
251         safe_git(chdir => $dir, error_handler => sub { warn @_ }, cmdline => \@_);
253 sub run_or_non_in ($$@) {
254         my $dir = shift;
255         safe_git(chdir => $dir, cmdline => \@_);
258 sub ensure_committer ($) {
259         my $dir = shift;
261         if (! length $ENV{GIT_AUTHOR_NAME} || ! length $ENV{GIT_COMMITTER_NAME}) {
262                 my $name = join('', run_or_non_in($dir, "git", "config", "user.name"));
263                 if (! length $name) {
264                         run_or_die_in($dir, "git", "config", "user.name", "IkiWiki");
265                 }
266         }
268         if (! length $ENV{GIT_AUTHOR_EMAIL} || ! length $ENV{GIT_COMMITTER_EMAIL}) {
269                 my $email = join('', run_or_non_in($dir, "git", "config", "user.email"));
270                 if (! length $email) {
271                         run_or_die_in($dir, "git", "config", "user.email", "ikiwiki.info");
272                 }
273         }
276 sub merge_past ($$$) {
277         # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
278         # Git merge commands work with the committed changes, except in the
279         # implicit case of '-m' of git checkout(1).  So we should invent a
280         # kludge here.  In principle, we need to create a throw-away branch
281         # in preparing for the merge itself.  Since branches are cheap (and
282         # branching is fast), this shouldn't cost high.
283         #
284         # The main problem is the presence of _uncommitted_ local changes.  One
285         # possible approach to get rid of this situation could be that we first
286         # make a temporary commit in the master branch and later restore the
287         # initial state (this is possible since Git has the ability to undo a
288         # commit, i.e. 'git reset --soft HEAD^').  The method can be summarized
289         # as follows:
290         #
291         #       - create a diff of HEAD:current-sha1
292         #       - dummy commit
293         #       - create a dummy branch and switch to it
294         #       - rewind to past (reset --hard to the current-sha1)
295         #       - apply the diff and commit
296         #       - switch to master and do the merge with the dummy branch
297         #       - make a soft reset (undo the last commit of master)
298         #
299         # The above method has some drawbacks: (1) it needs a redundant commit
300         # just to get rid of local changes, (2) somewhat slow because of the
301         # required system forks.  Until someone points a more straight method
302         # (which I would be grateful) I have implemented an alternative method.
303         # In this approach, we hide all the modified files from Git by renaming
304         # them (using the 'rename' builtin) and later restore those files in
305         # the throw-away branch (that is, we put the files themselves instead
306         # of applying a patch).
308         my ($sha1, $file, $message) = @_;
310         my @undo;      # undo stack for cleanup in case of an error
311         my $conflict;  # file content with conflict markers
313         ensure_committer($config{srcdir});
315         eval {
316                 # Hide local changes from Git by renaming the modified file.
317                 # Relative paths must be converted to absolute for renaming.
318                 my ($target, $hidden) = (
319                     "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
320                 );
321                 rename($target, $hidden)
322                     or error("rename '$target' to '$hidden' failed: $!");
323                 # Ensure to restore the renamed file on error.
324                 push @undo, sub {
325                         return if ! -e "$hidden"; # already renamed
326                         rename($hidden, $target)
327                             or warn "rename '$hidden' to '$target' failed: $!";
328                 };
330                 my $branch = "throw_away_${sha1}"; # supposed to be unique
332                 # Create a throw-away branch and rewind backward.
333                 push @undo, sub { run_or_cry_in($config{srcdir}, 'git', 'branch', '-D', $branch) };
334                 run_or_die_in($config{srcdir}, 'git', 'branch', $branch, $sha1);
336                 # Switch to throw-away branch for the merge operation.
337                 push @undo, sub {
338                         if (!run_or_cry_in($config{srcdir}, 'git', 'checkout', $config{gitmaster_branch})) {
339                                 run_or_cry_in($config{srcdir}, 'git', 'checkout','-f',$config{gitmaster_branch});
340                         }
341                 };
342                 run_or_die_in($config{srcdir}, 'git', 'checkout', $branch);
344                 # Put the modified file in _this_ branch.
345                 rename($hidden, $target)
346                     or error("rename '$hidden' to '$target' failed: $!");
348                 # _Silently_ commit all modifications in the current branch.
349                 run_or_non_in($config{srcdir}, 'git', 'commit', '-m', $message, '-a');
350                 # ... and re-switch to master.
351                 run_or_die_in($config{srcdir}, 'git', 'checkout', $config{gitmaster_branch});
353                 # Attempt to merge without complaining.
354                 if (!run_or_non_in($config{srcdir}, 'git', 'pull', '--no-commit', '.', $branch)) {
355                         $conflict = readfile($target);
356                         run_or_die_in($config{srcdir}, 'git', 'reset', '--hard');
357                 }
358         };
359         my $failure = $@;
361         # Process undo stack (in reverse order).  By policy cleanup
362         # actions should normally print a warning on failure.
363         while (my $handle = pop @undo) {
364                 $handle->();
365         }
367         error("Git merge failed!\n$failure\n") if $failure;
369         return $conflict;
373 my %prefix_cache;
375 sub decode_git_file ($$) {
376         my $dir=shift;
377         my $file=shift;
379         # git does not output utf-8 filenames, but instead
380         # double-quotes them with the utf-8 characters
381         # escaped as \nnn\nnn.
382         if ($file =~ m/^"(.*)"$/) {
383                 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
384         }
386         # strip prefix if in a subdir
387         if (! defined $prefix_cache{$dir}) {
388                 ($prefix_cache{$dir}) = run_or_die_in($dir, 'git', 'rev-parse', '--show-prefix');
389                 if (! defined $prefix_cache{$dir}) {
390                         $prefix_cache{$dir}="";
391                 }
392         }
393         $file =~ s/^\Q$prefix_cache{$dir}\E//;
395         return decode("utf8", $file);
399 sub parse_diff_tree ($$) {
400         # Parse the raw diff tree chunk and return the info hash.
401         # See git-diff-tree(1) for the syntax.
402         my $dir = shift;
403         my $dt_ref = shift;
405         # End of stream?
406         return if ! @{ $dt_ref } ||
407                   !defined $dt_ref->[0] || !length $dt_ref->[0];
409         my %ci;
410         # Header line.
411         while (my $line = shift @{ $dt_ref }) {
412                 return if $line !~ m/^(.+) ($sha1_pattern)/;
414                 my $sha1 = $2;
415                 $ci{'sha1'} = $sha1;
416                 last;
417         }
419         # Identification lines for the commit.
420         while (my $line = shift @{ $dt_ref }) {
421                 # Regexps are semi-stolen from gitweb.cgi.
422                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
423                         $ci{'tree'} = $1;
424                 }
425                 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
426                         # XXX: collecting in reverse order
427                         push @{ $ci{'parents'} }, $1;
428                 }
429                 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
430                         my ($who, $name, $epoch, $tz) =
431                            ($1,   $2,    $3,     $4 );
433                         $ci{  $who          } = $name;
434                         $ci{ "${who}_epoch" } = $epoch;
435                         $ci{ "${who}_tz"    } = $tz;
437                         if ($name =~ m/^([^<]+)\s+<([^@>]+)/) {
438                                 $ci{"${who}_name"} = $1;
439                                 $ci{"${who}_username"} = $2;
440                         }
441                         elsif ($name =~ m/^([^<]+)\s+<>$/) {
442                                 $ci{"${who}_username"} = $1;
443                         }
444                         else {
445                                 $ci{"${who}_username"} = $name;
446                         }
447                 }
448                 elsif ($line =~ m/^$/) {
449                         # Trailing empty line signals next section.
450                         last;
451                 }
452         }
454         debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
455         
456         if (defined $ci{'parents'}) {
457                 $ci{'parent'} = @{ $ci{'parents'} }[0];
458         }
459         else {
460                 $ci{'parent'} = 0 x 40;
461         }
463         # Commit message (optional).
464         while ($dt_ref->[0] =~ /^    /) {
465                 my $line = shift @{ $dt_ref };
466                 $line =~ s/^    //;
467                 push @{ $ci{'comment'} }, $line;
468         }
469         shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
471         $ci{details} = [parse_changed_files($dir, $dt_ref)];
473         return \%ci;
476 sub parse_changed_files ($$) {
477         my $dir = shift;
478         my $dt_ref = shift;
480         my @files;
482         # Modified files.
483         while (my $line = shift @{ $dt_ref }) {
484                 if ($line =~ m{^
485                         (:+)       # number of parents
486                         ([^\t]+)\t # modes, sha1, status
487                         (.*)       # file names
488                 $}xo) {
489                         my $num_parents = length $1;
490                         my @tmp = split(" ", $2);
491                         my ($file, $file_to) = split("\t", $3);
492                         my @mode_from = splice(@tmp, 0, $num_parents);
493                         my $mode_to = shift(@tmp);
494                         my @sha1_from = splice(@tmp, 0, $num_parents);
495                         my $sha1_to = shift(@tmp);
496                         my $status = shift(@tmp);
498                         if (length $file) {
499                                 push @files, {
500                                         'file'      => decode_git_file($dir, $file),
501                                         'sha1_from' => $sha1_from[0],
502                                         'sha1_to'   => $sha1_to,
503                                         'mode_from' => $mode_from[0],
504                                         'mode_to'   => $mode_to,
505                                         'status'    => $status,
506                                 };
507                         }
508                         next;
509                 };
510                 last;
511         }
513         return @files;
516 sub git_commit_info ($$;$) {
517         # Return an array of commit info hashes of num commits
518         # starting from the given sha1sum.
519         my ($dir, $sha1, $num) = @_;
521         my @opts;
522         push @opts, "--max-count=$num" if defined $num;
524         my @raw_lines = run_or_die_in($dir, 'git', 'log', @opts,
525                 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
526                 '-r', $sha1, '--no-renames', '--', '.');
528         my @ci;
529         while (my $parsed = parse_diff_tree($dir, \@raw_lines)) {
530                 push @ci, $parsed;
531         }
533         warn "Cannot parse commit info for '$sha1' commit" if !@ci;
535         return wantarray ? @ci : $ci[0];
538 sub rcs_find_changes ($) {
539         my $oldrev=shift;
541         # Note that git log will sometimes show files being added that
542         # don't exist. Particularly, git merge -s ours can result in a
543         # merge commit where some files were not really added.
544         # This is why the code below verifies that the files really
545         # exist.
546         my @raw_lines = run_or_die_in($config{srcdir}, 'git', 'log',
547                 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
548                 '--no-renames', , '--reverse',
549                 '-r', "$oldrev..HEAD", '--', '.');
551         # Due to --reverse, we see changes in chronological order.
552         my %changed;
553         my %deleted;
554         my $nullsha = 0 x 40;
555         my $newrev=$oldrev;
556         while (my $ci = parse_diff_tree($config{srcdir}, \@raw_lines)) {
557                 $newrev=$ci->{sha1};
558                 foreach my $i (@{$ci->{details}}) {
559                         my $file=$i->{file};
560                         if ($i->{sha1_to} eq $nullsha) {
561                                 if (! -e "$config{srcdir}/$file") {
562                                         delete $changed{$file};
563                                         $deleted{$file}=1;
564                                 }
565                         }
566                         else {
567                                 if (-e "$config{srcdir}/$file") {
568                                         delete $deleted{$file};
569                                         $changed{$file}=1;
570                                 }
571                         }
572                 }
573         }
575         return (\%changed, \%deleted, $newrev);
578 sub git_sha1_file ($$) {
579         my $dir=shift;
580         my $file=shift;
581         return git_sha1($dir, $file);
584 sub git_sha1 ($@) {
585         my $dir = shift;
586         # Ignore error since a non-existing file might be given.
587         my ($sha1) = run_or_non_in($dir, 'git', 'rev-list', '--max-count=1', 'HEAD',
588                 '--', @_);
589         if (defined $sha1) {
590                 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
591         }
592         return defined $sha1 ? $sha1 : '';
595 sub rcs_get_current_rev () {
596         return git_sha1($config{srcdir});
599 sub rcs_update () {
600         # Update working directory.
601         ensure_committer($config{srcdir});
603         if (length $config{gitorigin_branch}) {
604                 run_or_cry_in($config{srcdir}, 'git', 'pull', '--prune', $config{gitorigin_branch});
605         }
608 sub rcs_prepedit ($) {
609         # Return the commit sha1sum of the file when editing begins.
610         # This will be later used in rcs_commit if a merge is required.
611         my ($file) = @_;
613         return git_sha1_file($config{srcdir}, $file);
616 sub rcs_commit (@) {
617         # Try to commit the page; returns undef on _success_ and
618         # a version of the page with the rcs's conflict markers on
619         # failure.
620         my %params=@_;
622         # Check to see if the page has been changed by someone else since
623         # rcs_prepedit was called.
624         my $cur = git_sha1_file($config{srcdir}, $params{file});
625         my $prev;
626         if (defined $params{token}) {
627                 ($prev) = $params{token} =~ /^($sha1_pattern)$/; # untaint
628         }
630         if (defined $cur && defined $prev && $cur ne $prev) {
631                 my $conflict = merge_past($prev, $params{file}, $dummy_commit_msg);
632                 return $conflict if defined $conflict;
633         }
635         return rcs_commit_helper(@_);
638 sub rcs_commit_staged (@) {
639         # Commits all staged changes. Changes can be staged using rcs_add,
640         # rcs_remove, and rcs_rename.
641         return rcs_commit_helper(@_);
644 sub rcs_commit_helper (@) {
645         my %params=@_;
646         
647         my %env=%ENV;
649         if (defined $params{session}) {
650                 # Set the commit author and email based on web session info.
651                 my $u;
652                 if (defined $params{session}->param("name")) {
653                         $u=$params{session}->param("name");
654                 }
655                 elsif (defined $params{session}->remote_addr()) {
656                         $u=$params{session}->remote_addr();
657                 }
658                 if (length $u) {
659                         $u=encode_utf8($u);
660                         $ENV{GIT_AUTHOR_NAME}=$u;
661                 }
662                 else {
663                         $u = 'anonymous';
664                 }
665                 if (defined $params{session}->param("nickname")) {
666                         $u=encode_utf8($params{session}->param("nickname"));
667                         $u=~s/\s+/_/g;
668                         $u=~s/[^-_0-9[:alnum:]]+//g;
669                 }
670                 if (length $u) {
671                         $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
672                 }
673                 else {
674                         $ENV{GIT_AUTHOR_EMAIL}='anonymous@web';
675                 }
676         }
678         ensure_committer($config{srcdir});
680         $params{message} = IkiWiki::possibly_foolish_untaint($params{message});
681         my @opts;
682         if ($params{message} !~ /\S/) {
683                 # Force git to allow empty commit messages.
684                 # (If this version of git supports it.)
685                 my ($version)=`git --version` =~ /git version (.*)/;
686                 if ($version ge "1.7.8") {
687                         push @opts, "--allow-empty-message", "--no-edit";
688                 }
689                 if ($version ge "1.7.2") {
690                         push @opts, "--allow-empty-message";
691                 }
692                 elsif ($version ge "1.5.4") {
693                         push @opts, '--cleanup=verbatim';
694                 }
695                 else {
696                         $params{message}.=".";
697                 }
698         }
699         if (exists $params{file}) {
700                 push @opts, '--', $params{file};
701         }
702         # git commit returns non-zero if nothing really changed.
703         # So we should ignore its exit status (hence run_or_non_in).
704         if (run_or_non_in($config{srcdir}, 'git', 'commit', '-m', $params{message}, '-q', @opts)) {
705                 if (length $config{gitorigin_branch}) {
706                         run_or_cry_in($config{srcdir}, 'git', 'push', $config{gitorigin_branch}, $config{gitmaster_branch});
707                 }
708         }
709         
710         %ENV=%env;
711         return undef; # success
714 sub rcs_add ($) {
715         # Add file to archive.
717         my ($file) = @_;
719         ensure_committer($config{srcdir});
720         run_or_cry_in($config{srcdir}, 'git', 'add', '--', $file);
723 sub rcs_remove ($) {
724         # Remove file from archive.
726         my ($file) = @_;
728         ensure_committer($config{srcdir});
729         run_or_cry_in($config{srcdir}, 'git', 'rm', '-f', '--', $file);
732 sub rcs_rename ($$) {
733         my ($src, $dest) = @_;
735         ensure_committer($config{srcdir});
736         run_or_cry_in($config{srcdir}, 'git', 'mv', '-f', '--', $src, $dest);
739 sub rcs_recentchanges ($) {
740         # List of recent changes.
742         my ($num) = @_;
744         eval q{use Date::Parse};
745         error($@) if $@;
747         my @rets;
748         foreach my $ci (git_commit_info($config{srcdir}, 'HEAD', $num || 1)) {
749                 # Skip redundant commits.
750                 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
752                 my ($sha1, $when) = (
753                         $ci->{'sha1'},
754                         $ci->{'author_epoch'}
755                 );
757                 my @pages;
758                 foreach my $detail (@{ $ci->{'details'} }) {
759                         my $file = $detail->{'file'};
760                         my $efile = join('/',
761                                 map { uri_escape_utf8($_) } split('/', $file)
762                         );
764                         my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
765                         $diffurl =~ s/\[\[file\]\]/$efile/go;
766                         $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
767                         $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
768                         $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
769                         $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
771                         push @pages, {
772                                 page => pagename($file),
773                                 diffurl => $diffurl,
774                         };
775                 }
777                 my @messages;
778                 my $pastblank=0;
779                 foreach my $line (@{$ci->{'comment'}}) {
780                         $pastblank=1 if $line eq '';
781                         next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
782                         push @messages, { line => $line };
783                 }
785                 my $user=$ci->{'author_username'};
786                 my $web_commit = ($ci->{'author'} =~ /\@web>/);
787                 my $nickname;
789                 # Set nickname only if a non-url author_username is available,
790                 # and author_name is an url.
791                 if ($user !~ /:\/\// && defined $ci->{'author_name'} &&
792                     $ci->{'author_name'} =~ /:\/\//) {
793                         $nickname=$user;
794                         $user=$ci->{'author_name'};
795                 }
797                 # compatability code for old web commit messages
798                 if (! $web_commit &&
799                       defined $messages[0] &&
800                       $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
801                         $user = defined $2 ? "$2" : "$3";
802                         $messages[0]->{line} = $4;
803                         $web_commit=1;
804                 }
806                 push @rets, {
807                         rev        => $sha1,
808                         user       => $user,
809                         nickname   => $nickname,
810                         committype => $web_commit ? "web" : "git",
811                         when       => $when,
812                         message    => [@messages],
813                         pages      => [@pages],
814                 } if @pages;
816                 last if @rets >= $num;
817         }
819         return @rets;
822 sub rcs_diff ($;$) {
823         my $rev=shift;
824         my $maxlines=shift;
825         my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
826         my @lines;
827         my $addlines=sub {
828                 my $line=shift;
829                 return if defined $maxlines && @lines == $maxlines;
830                 push @lines, $line."\n"
831                         if (@lines || $line=~/^diff --git/);
832                 return 1;
833         };
834         safe_git(
835                 chdir => $config{srcdir},
836                 error_handler => undef,
837                 data_handler => $addlines,
838                 cmdline => ["git", "show", $sha1],
839         );
840         if (wantarray) {
841                 return @lines;
842         }
843         else {
844                 return join("", @lines);
845         }
849 my %time_cache;
851 sub findtimes ($$) {
852         my $file=shift;
853         my $id=shift; # 0 = mtime ; 1 = ctime
855         if (! keys %time_cache) {
856                 my $date;
857                 foreach my $line (run_or_die_in($config{srcdir}, 'git', 'log',
858                                 '--pretty=format:%at',
859                                 '--name-only', '--relative')) {
860                         if (! defined $date && $line =~ /^(\d+)$/) {
861                                 $date=$line;
862                         }
863                         elsif (! length $line) {
864                                 $date=undef;
865                         }
866                         else {
867                                 my $f=decode_git_file($config{srcdir}, $line);
869                                 if (! $time_cache{$f}) {
870                                         $time_cache{$f}[0]=$date; # mtime
871                                 }
872                                 $time_cache{$f}[1]=$date; # ctime
873                         }
874                 }
875         }
877         return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
882 sub rcs_getctime ($) {
883         my $file=shift;
885         return findtimes($file, 1);
888 sub rcs_getmtime ($) {
889         my $file=shift;
891         return findtimes($file, 0);
895 my $ret;
896 sub git_find_root {
897         # The wiki may not be the only thing in the git repo.
898         # Determine if it is in a subdirectory by examining the srcdir,
899         # and its parents, looking for the .git directory.
901         return @$ret if defined $ret;
902         
903         my $subdir="";
904         my $dir=$config{srcdir};
905         while (! -d "$dir/.git") {
906                 $subdir=IkiWiki::basename($dir)."/".$subdir;
907                 $dir=IkiWiki::dirname($dir);
908                 if (! length $dir) {
909                         error("cannot determine root of git repo");
910                 }
911         }
913         $ret=[$subdir, $dir];
914         return @$ret;
919 sub git_parse_changes ($$@) {
920         my $dir = shift;
921         my $reverted = shift;
922         my @changes = @_;
924         my ($subdir, $rootdir) = git_find_root();
925         my @rets;
926         foreach my $ci (@changes) {
927                 foreach my $detail (@{ $ci->{'details'} }) {
928                         my $file = $detail->{'file'};
930                         # check that all changed files are in the subdir
931                         if (length $subdir &&
932                             ! ($file =~ s/^\Q$subdir\E//)) {
933                                 error sprintf(gettext("you are not allowed to change %s"), $file);
934                         }
936                         my ($action, $mode, $path);
937                         if ($detail->{'status'} =~ /^[M]+\d*$/) {
938                                 $action="change";
939                                 $mode=$detail->{'mode_to'};
940                         }
941                         elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
942                                 $action= $reverted ? "remove" : "add";
943                                 $mode=$detail->{'mode_to'};
944                         }
945                         elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
946                                 $action= $reverted ? "add" : "remove";
947                                 $mode=$detail->{'mode_from'};
948                         }
949                         else {
950                                 error "unknown status ".$detail->{'status'};
951                         }
953                         # test that the file mode is ok
954                         if ($mode !~ /^100[64][64][64]$/) {
955                                 error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
956                         }
957                         if ($action eq "change") {
958                                 if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
959                                         error gettext("you are not allowed to change file modes");
960                                 }
961                         }
963                         # extract attachment to temp file
964                         if (($action eq 'add' || $action eq 'change') &&
965                             ! pagetype($file)) {
966                                 eval q{use File::Temp};
967                                 die $@ if $@;
968                                 my $fh;
969                                 ($fh, $path)=File::Temp::tempfile(undef, UNLINK => 1);
970                                 safe_git(
971                                         chdir => $dir,
972                                         error_handler => sub { error("failed writing temp file '$path': ".shift."."); },
973                                         stdout => $fh,
974                                         cmdline => ['git', 'show', $detail->{sha1_to}],
975                                 );
976                         }
978                         push @rets, {
979                                 file => $file,
980                                 action => $action,
981                                 path => $path,
982                         };
983                 }
984         }
986         return @rets;
989 sub rcs_receive () {
990         my @rets;
991         while (<>) {
992                 chomp;
993                 my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
995                 # only allow changes to gitmaster_branch
996                 if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
997                         error sprintf(gettext("you are not allowed to change %s"), $refname);
998                 }
1000                 # Avoid chdir when running git here, because the changes
1001                 # are in the master git repo, not the srcdir repo.
1002                 # (Also, if a subdir is involved, we don't want to chdir to
1003                 # it and only see changes in it.)
1004                 # The pre-receive hook already puts us in the right place.
1005                 push @rets, git_parse_changes('.', 0, git_commit_info('.', $oldrev."..".$newrev));
1006         }
1008         return reverse @rets;
1011 sub rcs_preprevert ($) {
1012         my $rev=shift;
1013         my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
1015         my @undo;      # undo stack for cleanup in case of an error
1017         # Examine changes from root of git repo, not from any subdir,
1018         # in order to see all changes.
1019         my ($subdir, $rootdir) = git_find_root();
1020         ensure_committer($rootdir);
1022         # preserve indentation of previous in_git_dir code for now
1023         do {
1024                 my @commits=git_commit_info($rootdir, $sha1, 1);
1026                 if (! @commits) {
1027                         error "unknown commit"; # just in case
1028                 }
1030                 # git revert will fail on merge commits. Add a nice message.
1031                 if (exists $commits[0]->{parents} &&
1032                     @{$commits[0]->{parents}} > 1) {
1033                         error gettext("you are not allowed to revert a merge");
1034                 }
1036                 # Due to the presence of rename-detection, we cannot actually
1037                 # see what will happen in a revert without trying it.
1038                 # But we can guess, which is enough to rule out most changes
1039                 # that we won't allow reverting.
1040                 git_parse_changes($rootdir, 1, @commits);
1042                 my $failure;
1043                 my @ret;
1044                 eval {
1045                         my $branch = "ikiwiki_revert_${sha1}"; # supposed to be unique
1047                         push @undo, sub {
1048                                 run_or_cry_in($rootdir, 'git', 'branch', '-D', $branch) if $failure;
1049                         };
1050                         if (run_or_non_in($rootdir, 'git', 'rev-parse', '--quiet', '--verify', $branch)) {
1051                                 run_or_non_in($rootdir, 'git', 'branch', '-D', $branch);
1052                         }
1053                         run_or_die_in($rootdir, 'git', 'branch', $branch, $config{gitmaster_branch});
1055                         my $working = create_temp_working_dir($rootdir, $branch);
1057                         push @undo, sub {
1058                                 remove_tree($working);
1059                         };
1061                         run_or_die_in($working, 'git', 'checkout', '--quiet', '--force', $branch);
1062                         run_or_die_in($working, 'git', 'revert', '--no-commit', $sha1);
1063                         run_or_die_in($working, 'git', 'commit', '-m', "revert $sha1", '-a');
1065                         my @raw_lines;
1066                         @raw_lines = run_or_die_in($rootdir, 'git', 'diff', '--pretty=raw',
1067                                 '--raw', '--abbrev=40', '--always', '--no-renames',
1068                                 "..${branch}");
1070                         my $ci = {
1071                                 details => [parse_changed_files($rootdir, \@raw_lines)],
1072                         };
1074                         @ret = git_parse_changes($rootdir, 0, $ci);
1075                 };
1076                 $failure = $@;
1078                 # Process undo stack (in reverse order).  By policy cleanup
1079                 # actions should normally print a warning on failure.
1080                 while (my $handle = pop @undo) {
1081                         $handle->();
1082                 }
1084                 if ($failure) {
1085                         my $message = sprintf(gettext("Failed to revert commit %s"), $sha1);
1086                         error("$message\n$failure\n");
1087                 }
1088                 return @ret;
1089         };
1092 sub rcs_revert ($) {
1093         # Try to revert the given rev; returns undef on _success_.
1094         my $rev = shift;
1095         my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
1097         ensure_committer($config{srcdir});
1099         if (run_or_non_in($config{srcdir}, 'git', 'cherry-pick', '--no-commit', "ikiwiki_revert_$sha1")) {
1100                 return undef;
1101         }
1102         else {
1103                 run_or_non_in($config{srcdir}, 'git', 'branch', '-D', "ikiwiki_revert_$sha1");
1104                 return sprintf(gettext("Failed to revert commit %s"), $sha1);
1105         }