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