2 package IkiWiki::Plugin::git;
8 use open qw{:utf8 :std};
10 my $sha1_pattern = qr/[0-9a-fA-F]{40}/; # pattern to validate Git sha1sums
11 my $dummy_commit_msg = 'dummy commit'; # message to skip in recent changes
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_showpatch", call => \&rcs_showpatch);
36 if (! defined $config{gitorigin_branch}) {
37 $config{gitorigin_branch}="origin";
39 if (! defined $config{gitmaster_branch}) {
40 $config{gitmaster_branch}="master";
42 if (defined $config{git_wrapper} &&
43 length $config{git_wrapper}) {
44 push @{$config{wrappers}}, {
45 wrapper => $config{git_wrapper},
46 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
47 wrapper_background_command => $config{git_wrapper_background_command},
51 if (defined $config{git_test_receive_wrapper} &&
52 length $config{git_test_receive_wrapper} &&
53 defined $config{untrusted_committers} &&
54 @{$config{untrusted_committers}}) {
55 push @{$config{wrappers}}, {
57 wrapper => $config{git_test_receive_wrapper},
58 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
62 # Avoid notes, parser does not handle and they only slow things down.
63 $ENV{GIT_NOTES_REF}="";
65 # Run receive test only if being called by the wrapper, and not
66 # when generating same.
67 if ($config{test_receive} && ! exists $config{wrapper}) {
68 require IkiWiki::Receive;
69 IkiWiki::Receive::test();
76 safe => 0, # rcs plugin
82 example => "/git/wiki.git/hooks/post-update",
83 description => "git hook to generate",
87 git_wrapper_background_command => {
89 example => "git push github",
90 description => "shell command for git_wrapper to run, in the background",
97 description => "mode for git_wrapper (can safely be made suid)",
101 git_test_receive_wrapper => {
103 example => "/git/wiki.git/hooks/pre-receive",
104 description => "git pre-receive hook to generate",
108 untrusted_committers => {
111 description => "unix users whose commits should be checked by the pre-receive hook",
117 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]];hb=HEAD",
118 description => "gitweb url to show file history ([[file]] substituted)",
124 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]]",
125 description => "gitweb url to show a diff ([[file]], [[sha1_to]], [[sha1_from]], [[sha1_commit]], and [[sha1_parent]] substituted)",
129 gitorigin_branch => {
132 description => "where to pull and push changes (set to empty string to disable)",
133 safe => 0, # paranoia
136 gitmaster_branch => {
139 description => "branch that the wiki is stored in",
140 safe => 0, # paranoia
146 if ($config{test_receive}) {
147 require IkiWiki::Receive;
148 return IkiWiki::Receive::genwrapper();
156 # Start a child process safely without resorting /bin/sh.
157 # Return command output or success state (in scalar context).
159 my ($error_handler, @cmdline) = @_;
161 my $pid = open my $OUT, "-|";
163 error("Cannot fork: $!") if !defined $pid;
167 # Git commands want to be in wc.
169 chdir $config{srcdir}
170 or error("Cannot chdir to $config{srcdir}: $!");
172 exec @cmdline or error("Cannot exec '@cmdline': $!");
176 # git output is probably utf-8 encoded, but may contain
177 # other encodings or invalidly encoded stuff. So do not rely
178 # on the normal utf-8 IO layer, decode it by hand.
183 $_=decode_utf8($_, 0);
192 $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
194 return wantarray ? @lines : ($? == 0);
196 # Convenient wrappers.
197 sub run_or_die ($@) { safe_git(\&error, @_) }
198 sub run_or_cry ($@) { safe_git(sub { warn @_ }, @_) }
199 sub run_or_non ($@) { safe_git(undef, @_) }
202 sub merge_past ($$$) {
203 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
204 # Git merge commands work with the committed changes, except in the
205 # implicit case of '-m' of git checkout(1). So we should invent a
206 # kludge here. In principle, we need to create a throw-away branch
207 # in preparing for the merge itself. Since branches are cheap (and
208 # branching is fast), this shouldn't cost high.
210 # The main problem is the presence of _uncommitted_ local changes. One
211 # possible approach to get rid of this situation could be that we first
212 # make a temporary commit in the master branch and later restore the
213 # initial state (this is possible since Git has the ability to undo a
214 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
217 # - create a diff of HEAD:current-sha1
219 # - create a dummy branch and switch to it
220 # - rewind to past (reset --hard to the current-sha1)
221 # - apply the diff and commit
222 # - switch to master and do the merge with the dummy branch
223 # - make a soft reset (undo the last commit of master)
225 # The above method has some drawbacks: (1) it needs a redundant commit
226 # just to get rid of local changes, (2) somewhat slow because of the
227 # required system forks. Until someone points a more straight method
228 # (which I would be grateful) I have implemented an alternative method.
229 # In this approach, we hide all the modified files from Git by renaming
230 # them (using the 'rename' builtin) and later restore those files in
231 # the throw-away branch (that is, we put the files themselves instead
232 # of applying a patch).
234 my ($sha1, $file, $message) = @_;
236 my @undo; # undo stack for cleanup in case of an error
237 my $conflict; # file content with conflict markers
240 # Hide local changes from Git by renaming the modified file.
241 # Relative paths must be converted to absolute for renaming.
242 my ($target, $hidden) = (
243 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
245 rename($target, $hidden)
246 or error("rename '$target' to '$hidden' failed: $!");
247 # Ensure to restore the renamed file on error.
249 return if ! -e "$hidden"; # already renamed
250 rename($hidden, $target)
251 or warn "rename '$hidden' to '$target' failed: $!";
254 my $branch = "throw_away_${sha1}"; # supposed to be unique
256 # Create a throw-away branch and rewind backward.
257 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
258 run_or_die('git', 'branch', $branch, $sha1);
260 # Switch to throw-away branch for the merge operation.
262 if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
263 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
266 run_or_die('git', 'checkout', $branch);
268 # Put the modified file in _this_ branch.
269 rename($hidden, $target)
270 or error("rename '$hidden' to '$target' failed: $!");
272 # _Silently_ commit all modifications in the current branch.
273 run_or_non('git', 'commit', '-m', $message, '-a');
274 # ... and re-switch to master.
275 run_or_die('git', 'checkout', $config{gitmaster_branch});
277 # Attempt to merge without complaining.
278 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
279 $conflict = readfile($target);
280 run_or_die('git', 'reset', '--hard');
285 # Process undo stack (in reverse order). By policy cleanup
286 # actions should normally print a warning on failure.
287 while (my $handle = pop @undo) {
291 error("Git merge failed!\n$failure\n") if $failure;
298 sub decode_git_file ($) {
301 # git does not output utf-8 filenames, but instead
302 # double-quotes them with the utf-8 characters
303 # escaped as \nnn\nnn.
304 if ($file =~ m/^"(.*)"$/) {
305 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
308 # strip prefix if in a subdir
309 if (! defined $prefix) {
310 ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
311 if (! defined $prefix) {
315 $file =~ s/^\Q$prefix\E//;
317 return decode("utf8", $file);
321 sub parse_diff_tree ($) {
322 # Parse the raw diff tree chunk and return the info hash.
323 # See git-diff-tree(1) for the syntax.
327 return if !defined @{ $dt_ref } ||
328 !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
332 while (my $line = shift @{ $dt_ref }) {
333 return if $line !~ m/^(.+) ($sha1_pattern)/;
340 # Identification lines for the commit.
341 while (my $line = shift @{ $dt_ref }) {
342 # Regexps are semi-stolen from gitweb.cgi.
343 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
346 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
347 # XXX: collecting in reverse order
348 push @{ $ci{'parents'} }, $1;
350 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
351 my ($who, $name, $epoch, $tz) =
355 $ci{ "${who}_epoch" } = $epoch;
356 $ci{ "${who}_tz" } = $tz;
358 if ($name =~ m/^([^<]+)\s+<([^@>]+)/) {
359 $ci{"${who}_name"} = $1;
360 $ci{"${who}_username"} = $2;
362 elsif ($name =~ m/^([^<]+)\s+<>$/) {
363 $ci{"${who}_username"} = $1;
366 $ci{"${who}_username"} = $name;
369 elsif ($line =~ m/^$/) {
370 # Trailing empty line signals next section.
375 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
377 if (defined $ci{'parents'}) {
378 $ci{'parent'} = @{ $ci{'parents'} }[0];
381 $ci{'parent'} = 0 x 40;
384 # Commit message (optional).
385 while ($dt_ref->[0] =~ /^ /) {
386 my $line = shift @{ $dt_ref };
388 push @{ $ci{'comment'} }, $line;
390 shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
393 while (my $line = shift @{ $dt_ref }) {
395 (:+) # number of parents
396 ([^\t]+)\t # modes, sha1, status
399 my $num_parents = length $1;
400 my @tmp = split(" ", $2);
401 my ($file, $file_to) = split("\t", $3);
402 my @mode_from = splice(@tmp, 0, $num_parents);
403 my $mode_to = shift(@tmp);
404 my @sha1_from = splice(@tmp, 0, $num_parents);
405 my $sha1_to = shift(@tmp);
406 my $status = shift(@tmp);
409 push @{ $ci{'details'} }, {
410 'file' => decode_git_file($file),
411 'sha1_from' => $sha1_from[0],
412 'sha1_to' => $sha1_to,
413 'mode_from' => $mode_from[0],
414 'mode_to' => $mode_to,
426 sub git_commit_info ($;$) {
427 # Return an array of commit info hashes of num commits
428 # starting from the given sha1sum.
429 my ($sha1, $num) = @_;
432 push @opts, "--max-count=$num" if defined $num;
434 my @raw_lines = run_or_die('git', 'log', @opts,
435 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
436 '-r', $sha1, '--', '.');
439 while (my $parsed = parse_diff_tree(\@raw_lines)) {
443 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
445 return wantarray ? @ci : $ci[0];
449 # Return head sha1sum (of given file).
450 my $file = shift || q{--};
452 # Ignore error since a non-existing file might be given.
453 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
456 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
459 debug("Empty sha1sum for '$file'.");
461 return defined $sha1 ? $sha1 : q{};
465 # Update working directory.
467 if (length $config{gitorigin_branch}) {
468 run_or_cry('git', 'pull', '--prune', $config{gitorigin_branch});
472 sub rcs_prepedit ($) {
473 # Return the commit sha1sum of the file when editing begins.
474 # This will be later used in rcs_commit if a merge is required.
477 return git_sha1($file);
481 # Try to commit the page; returns undef on _success_ and
482 # a version of the page with the rcs's conflict markers on
486 # Check to see if the page has been changed by someone else since
487 # rcs_prepedit was called.
488 my $cur = git_sha1($params{file});
489 my ($prev) = $params{token} =~ /^($sha1_pattern)$/; # untaint
491 if (defined $cur && defined $prev && $cur ne $prev) {
492 my $conflict = merge_past($prev, $params{file}, $dummy_commit_msg);
493 return $conflict if defined $conflict;
496 rcs_add($params{file});
497 return rcs_commit_staged(
498 message => $params{message},
499 session => $params{session},
503 sub rcs_commit_staged (@) {
504 # Commits all staged changes. Changes can be staged using rcs_add,
505 # rcs_remove, and rcs_rename.
510 if (defined $params{session}) {
511 # Set the commit author and email based on web session info.
513 if (defined $params{session}->param("name")) {
514 $u=$params{session}->param("name");
516 elsif (defined $params{session}->remote_addr()) {
517 $u=$params{session}->remote_addr();
521 $ENV{GIT_AUTHOR_NAME}=$u;
523 if (defined $params{session}->param("nickname")) {
524 $u=encode_utf8($params{session}->param("nickname"));
526 $u=~s/[^-_0-9[:alnum:]]+//g;
529 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
533 $params{message} = IkiWiki::possibly_foolish_untaint($params{message});
535 if ($params{message} !~ /\S/) {
536 # Force git to allow empty commit messages.
537 # (If this version of git supports it.)
538 my ($version)=`git --version` =~ /git version (.*)/;
539 if ($version ge "1.5.4") {
540 push @opts, '--cleanup=verbatim';
543 $params{message}.=".";
547 # git commit returns non-zero if file has not been really changed.
548 # so we should ignore its exit status (hence run_or_non).
549 if (run_or_non('git', 'commit', @opts, '-m', $params{message})) {
550 if (length $config{gitorigin_branch}) {
551 run_or_cry('git', 'push', $config{gitorigin_branch});
556 return undef; # success
560 # Add file to archive.
564 run_or_cry('git', 'add', $file);
568 # Remove file from archive.
572 run_or_cry('git', 'rm', '-f', $file);
575 sub rcs_rename ($$) {
576 my ($src, $dest) = @_;
578 run_or_cry('git', 'mv', '-f', $src, $dest);
581 sub rcs_recentchanges ($) {
582 # List of recent changes.
586 eval q{use Date::Parse};
590 foreach my $ci (git_commit_info('HEAD', $num || 1)) {
591 # Skip redundant commits.
592 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
594 my ($sha1, $when) = (
596 $ci->{'author_epoch'}
600 foreach my $detail (@{ $ci->{'details'} }) {
601 my $file = $detail->{'file'};
603 my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
604 $diffurl =~ s/\[\[file\]\]/$file/go;
605 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
606 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
607 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
608 $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
611 page => pagename($file),
618 foreach my $line (@{$ci->{'comment'}}) {
619 $pastblank=1 if $line eq '';
620 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
621 push @messages, { line => $line };
624 my $user=$ci->{'author_username'};
625 my $web_commit = ($ci->{'author'} =~ /\@web>/);
628 # Set nickname only if a non-url author_username is available,
629 # and author_name is an url.
630 if ($user !~ /:\/\// && defined $ci->{'author_name'} &&
631 $ci->{'author_name'} =~ /:\/\//) {
633 $user=$ci->{'author_name'};
636 # compatability code for old web commit messages
638 defined $messages[0] &&
639 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
640 $user = defined $2 ? "$2" : "$3";
641 $messages[0]->{line} = $4;
648 nickname => $nickname,
649 committype => $web_commit ? "web" : "git",
651 message => [@messages],
655 last if @rets >= $num;
663 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
665 foreach my $line (run_or_non("git", "show", $sha1)) {
666 if (@lines || $line=~/^diff --git/) {
667 push @lines, $line."\n";
674 return join("", @lines);
683 my $id=shift; # 0 = mtime ; 1 = ctime
685 if (! keys %time_cache) {
687 foreach my $line (run_or_die('git', 'log',
688 '--pretty=format:%ct',
689 '--name-only', '--relative')) {
690 if (! defined $date && $line =~ /^(\d+)$/) {
693 elsif (! length $line) {
697 my $f=decode_git_file($line);
699 if (! $time_cache{$f}) {
700 $time_cache{$f}[0]=$date; # mtime
702 $time_cache{$f}[1]=$date; # ctime
707 return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
712 sub rcs_getctime ($) {
715 return findtimes($file, 1);
718 sub rcs_getmtime ($) {
721 return findtimes($file, 0);
728 # The wiki may not be the only thing in the git repo.
729 # Determine if it is in a subdirectory by examining the srcdir,
730 # and its parents, looking for the .git directory.
732 return $git_root if defined $git_root;
735 my $dir=$config{srcdir};
736 while (! -d "$dir/.git") {
737 $subdir=IkiWiki::basename($dir)."/".$subdir;
738 $dir=IkiWiki::dirname($dir);
740 error("cannot determine root of git repo");
749 sub git_parse_changes {
752 my $subdir = git_find_root();
754 foreach my $ci (@changes) {
755 foreach my $detail (@{ $ci->{'details'} }) {
756 my $file = $detail->{'file'};
758 # check that all changed files are in the subdir
759 if (length $subdir &&
760 ! ($file =~ s/^\Q$subdir\E//)) {
761 error sprintf(gettext("you are not allowed to change %s"), $file);
764 my ($action, $mode, $path);
765 if ($detail->{'status'} =~ /^[M]+\d*$/) {
767 $mode=$detail->{'mode_to'};
769 elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
771 $mode=$detail->{'mode_to'};
773 elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
775 $mode=$detail->{'mode_from'};
778 error "unknown status ".$detail->{'status'};
781 # test that the file mode is ok
782 if ($mode !~ /^100[64][64][64]$/) {
783 error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
785 if ($action eq "change") {
786 if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
787 error gettext("you are not allowed to change file modes");
791 # extract attachment to temp file
792 if (($action eq 'add' || $action eq 'change') &&
794 eval q{use File::Temp};
797 ($fh, $path)=File::Temp::tempfile("XXXXXXXXXX", UNLINK => 1);
798 # Ensure we run this in the right place,
799 # see comments in rcs_receive.
800 my $cmd = ($no_chdir ? '' : "cd $config{srcdir} && ")
801 . "git show $detail->{sha1_to} > '$path'";
802 if (system($cmd) != 0) {
803 error("failed writing temp file '$path'.");
822 my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
824 # only allow changes to gitmaster_branch
825 if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
826 error sprintf(gettext("you are not allowed to change %s"), $refname);
829 # Avoid chdir when running git here, because the changes
830 # are in the master git repo, not the srcdir repo.
831 # The pre-receive hook already puts us in the right place.
833 push @rets, git_parse_changes(git_commit_info($oldrev."..".$newrev));
837 return reverse @rets;
840 sub rcs_preprevert (@) {
842 my $rev = $params{rev};
844 # Note test_changes expects 'cgi' and 'session' parameters.
845 require IkiWiki::Receive;
846 IkiWiki::Receive::test_changes(%params, changes =>
847 [git_parse_changes(git_commit_info($rev, 1))]);
851 # Try to revert the given patch; returns undef on _success_.
853 my $rev = $params{rev};
855 if (run_or_non('git', 'revert', '--no-commit', $rev)) {
856 debug "Committing revert for patch '$rev'.";
857 rcs_commit_staged(message =>
858 sprintf(gettext("This reverts commit %s"), $rev), @_);
861 # No idea what is actually getting reverted, so all we can
862 # do is say we failed.
863 run_or_die('git', 'reset', '--hard');
864 return sprintf(gettext("Failed to revert commit %s"), $rev);
868 sub rcs_showpatch (@) {
869 # Show the patch with the given revision id.
871 my $rev = $params{rev};
873 return join "\n", run_or_die('git', 'show', $rev);