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);
33 hook(type => "rcs", id => "rcs_revert", call => \&rcs_revert);
37 if (! defined $config{gitorigin_branch}) {
38 $config{gitorigin_branch}="origin";
40 if (! defined $config{gitmaster_branch}) {
41 $config{gitmaster_branch}="master";
43 if (defined $config{git_wrapper} &&
44 length $config{git_wrapper}) {
45 push @{$config{wrappers}}, {
46 wrapper => $config{git_wrapper},
47 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
48 wrapper_background_command => $config{git_wrapper_background_command},
52 if (defined $config{git_test_receive_wrapper} &&
53 length $config{git_test_receive_wrapper} &&
54 defined $config{untrusted_committers} &&
55 @{$config{untrusted_committers}}) {
56 push @{$config{wrappers}}, {
58 wrapper => $config{git_test_receive_wrapper},
59 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
63 # Avoid notes, parser does not handle and they only slow things down.
64 $ENV{GIT_NOTES_REF}="";
66 # Run receive test only if being called by the wrapper, and not
67 # when generating same.
68 if ($config{test_receive} && ! exists $config{wrapper}) {
69 require IkiWiki::Receive;
70 IkiWiki::Receive::test();
77 safe => 0, # rcs plugin
83 example => "/git/wiki.git/hooks/post-update",
84 description => "git hook to generate",
88 git_wrapper_background_command => {
90 example => "git push github",
91 description => "shell command for git_wrapper to run, in the background",
98 description => "mode for git_wrapper (can safely be made suid)",
102 git_test_receive_wrapper => {
104 example => "/git/wiki.git/hooks/pre-receive",
105 description => "git pre-receive hook to generate",
109 untrusted_committers => {
112 description => "unix users whose commits should be checked by the pre-receive hook",
118 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]];hb=HEAD",
119 description => "gitweb url to show file history ([[file]] substituted)",
125 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=blobdiff;f=[[file]];h=[[sha1_to]];hp=[[sha1_from]];hb=[[sha1_commit]];hpb=[[sha1_parent]]",
126 description => "gitweb url to show a diff ([[file]], [[sha1_to]], [[sha1_from]], [[sha1_commit]], and [[sha1_parent]] substituted)",
130 gitorigin_branch => {
133 description => "where to pull and push changes (set to empty string to disable)",
134 safe => 0, # paranoia
137 gitmaster_branch => {
140 description => "branch that the wiki is stored in",
141 safe => 0, # paranoia
147 if ($config{test_receive}) {
148 require IkiWiki::Receive;
149 return IkiWiki::Receive::genwrapper();
157 # Start a child process safely without resorting /bin/sh.
158 # Return command output or success state (in scalar context).
160 my ($error_handler, @cmdline) = @_;
162 my $pid = open my $OUT, "-|";
164 error("Cannot fork: $!") if !defined $pid;
168 # Git commands want to be in wc.
170 chdir $config{srcdir}
171 or error("Cannot chdir to $config{srcdir}: $!");
173 exec @cmdline or error("Cannot exec '@cmdline': $!");
177 # git output is probably utf-8 encoded, but may contain
178 # other encodings or invalidly encoded stuff. So do not rely
179 # on the normal utf-8 IO layer, decode it by hand.
184 $_=decode_utf8($_, 0);
193 $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
195 return wantarray ? @lines : ($? == 0);
197 # Convenient wrappers.
198 sub run_or_die ($@) { safe_git(\&error, @_) }
199 sub run_or_cry ($@) { safe_git(sub { warn @_ }, @_) }
200 sub run_or_non ($@) { safe_git(undef, @_) }
203 sub merge_past ($$$) {
204 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
205 # Git merge commands work with the committed changes, except in the
206 # implicit case of '-m' of git checkout(1). So we should invent a
207 # kludge here. In principle, we need to create a throw-away branch
208 # in preparing for the merge itself. Since branches are cheap (and
209 # branching is fast), this shouldn't cost high.
211 # The main problem is the presence of _uncommitted_ local changes. One
212 # possible approach to get rid of this situation could be that we first
213 # make a temporary commit in the master branch and later restore the
214 # initial state (this is possible since Git has the ability to undo a
215 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
218 # - create a diff of HEAD:current-sha1
220 # - create a dummy branch and switch to it
221 # - rewind to past (reset --hard to the current-sha1)
222 # - apply the diff and commit
223 # - switch to master and do the merge with the dummy branch
224 # - make a soft reset (undo the last commit of master)
226 # The above method has some drawbacks: (1) it needs a redundant commit
227 # just to get rid of local changes, (2) somewhat slow because of the
228 # required system forks. Until someone points a more straight method
229 # (which I would be grateful) I have implemented an alternative method.
230 # In this approach, we hide all the modified files from Git by renaming
231 # them (using the 'rename' builtin) and later restore those files in
232 # the throw-away branch (that is, we put the files themselves instead
233 # of applying a patch).
235 my ($sha1, $file, $message) = @_;
237 my @undo; # undo stack for cleanup in case of an error
238 my $conflict; # file content with conflict markers
241 # Hide local changes from Git by renaming the modified file.
242 # Relative paths must be converted to absolute for renaming.
243 my ($target, $hidden) = (
244 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
246 rename($target, $hidden)
247 or error("rename '$target' to '$hidden' failed: $!");
248 # Ensure to restore the renamed file on error.
250 return if ! -e "$hidden"; # already renamed
251 rename($hidden, $target)
252 or warn "rename '$hidden' to '$target' failed: $!";
255 my $branch = "throw_away_${sha1}"; # supposed to be unique
257 # Create a throw-away branch and rewind backward.
258 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
259 run_or_die('git', 'branch', $branch, $sha1);
261 # Switch to throw-away branch for the merge operation.
263 if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
264 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
267 run_or_die('git', 'checkout', $branch);
269 # Put the modified file in _this_ branch.
270 rename($hidden, $target)
271 or error("rename '$hidden' to '$target' failed: $!");
273 # _Silently_ commit all modifications in the current branch.
274 run_or_non('git', 'commit', '-m', $message, '-a');
275 # ... and re-switch to master.
276 run_or_die('git', 'checkout', $config{gitmaster_branch});
278 # Attempt to merge without complaining.
279 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
280 $conflict = readfile($target);
281 run_or_die('git', 'reset', '--hard');
286 # Process undo stack (in reverse order). By policy cleanup
287 # actions should normally print a warning on failure.
288 while (my $handle = pop @undo) {
292 error("Git merge failed!\n$failure\n") if $failure;
299 sub decode_git_file ($) {
302 # git does not output utf-8 filenames, but instead
303 # double-quotes them with the utf-8 characters
304 # escaped as \nnn\nnn.
305 if ($file =~ m/^"(.*)"$/) {
306 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
309 # strip prefix if in a subdir
310 if (! defined $prefix) {
311 ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
312 if (! defined $prefix) {
316 $file =~ s/^\Q$prefix\E//;
318 return decode("utf8", $file);
322 sub parse_diff_tree ($) {
323 # Parse the raw diff tree chunk and return the info hash.
324 # See git-diff-tree(1) for the syntax.
328 return if !defined @{ $dt_ref } ||
329 !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
333 while (my $line = shift @{ $dt_ref }) {
334 return if $line !~ m/^(.+) ($sha1_pattern)/;
341 # Identification lines for the commit.
342 while (my $line = shift @{ $dt_ref }) {
343 # Regexps are semi-stolen from gitweb.cgi.
344 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
347 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
348 # XXX: collecting in reverse order
349 push @{ $ci{'parents'} }, $1;
351 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
352 my ($who, $name, $epoch, $tz) =
356 $ci{ "${who}_epoch" } = $epoch;
357 $ci{ "${who}_tz" } = $tz;
359 if ($name =~ m/^([^<]+)\s+<([^@>]+)/) {
360 $ci{"${who}_name"} = $1;
361 $ci{"${who}_username"} = $2;
363 elsif ($name =~ m/^([^<]+)\s+<>$/) {
364 $ci{"${who}_username"} = $1;
367 $ci{"${who}_username"} = $name;
370 elsif ($line =~ m/^$/) {
371 # Trailing empty line signals next section.
376 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
378 if (defined $ci{'parents'}) {
379 $ci{'parent'} = @{ $ci{'parents'} }[0];
382 $ci{'parent'} = 0 x 40;
385 # Commit message (optional).
386 while ($dt_ref->[0] =~ /^ /) {
387 my $line = shift @{ $dt_ref };
389 push @{ $ci{'comment'} }, $line;
391 shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
394 while (my $line = shift @{ $dt_ref }) {
396 (:+) # number of parents
397 ([^\t]+)\t # modes, sha1, status
400 my $num_parents = length $1;
401 my @tmp = split(" ", $2);
402 my ($file, $file_to) = split("\t", $3);
403 my @mode_from = splice(@tmp, 0, $num_parents);
404 my $mode_to = shift(@tmp);
405 my @sha1_from = splice(@tmp, 0, $num_parents);
406 my $sha1_to = shift(@tmp);
407 my $status = shift(@tmp);
410 push @{ $ci{'details'} }, {
411 'file' => decode_git_file($file),
412 'sha1_from' => $sha1_from[0],
413 'sha1_to' => $sha1_to,
414 'mode_from' => $mode_from[0],
415 'mode_to' => $mode_to,
427 sub git_commit_info ($;$) {
428 # Return an array of commit info hashes of num commits
429 # starting from the given sha1sum.
430 my ($sha1, $num) = @_;
433 push @opts, "--max-count=$num" if defined $num;
435 my @raw_lines = run_or_die('git', 'log', @opts,
436 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
437 '-r', $sha1, '--', '.');
440 while (my $parsed = parse_diff_tree(\@raw_lines)) {
444 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
446 return wantarray ? @ci : $ci[0];
450 # Return head sha1sum (of given file).
451 my $file = shift || q{--};
453 # Ignore error since a non-existing file might be given.
454 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
457 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
460 debug("Empty sha1sum for '$file'.");
462 return defined $sha1 ? $sha1 : q{};
466 # Update working directory.
468 if (length $config{gitorigin_branch}) {
469 run_or_cry('git', 'pull', '--prune', $config{gitorigin_branch});
473 sub rcs_prepedit ($) {
474 # Return the commit sha1sum of the file when editing begins.
475 # This will be later used in rcs_commit if a merge is required.
478 return git_sha1($file);
482 # Try to commit the page; returns undef on _success_ and
483 # a version of the page with the rcs's conflict markers on
487 # Check to see if the page has been changed by someone else since
488 # rcs_prepedit was called.
489 my $cur = git_sha1($params{file});
490 my ($prev) = $params{token} =~ /^($sha1_pattern)$/; # untaint
492 if (defined $cur && defined $prev && $cur ne $prev) {
493 my $conflict = merge_past($prev, $params{file}, $dummy_commit_msg);
494 return $conflict if defined $conflict;
497 rcs_add($params{file});
498 return rcs_commit_staged(
499 message => $params{message},
500 session => $params{session},
504 sub rcs_commit_staged (@) {
505 # Commits all staged changes. Changes can be staged using rcs_add,
506 # rcs_remove, and rcs_rename.
511 if (defined $params{session}) {
512 # Set the commit author and email based on web session info.
514 if (defined $params{session}->param("name")) {
515 $u=$params{session}->param("name");
517 elsif (defined $params{session}->remote_addr()) {
518 $u=$params{session}->remote_addr();
522 $ENV{GIT_AUTHOR_NAME}=$u;
524 if (defined $params{session}->param("nickname")) {
525 $u=encode_utf8($params{session}->param("nickname"));
527 $u=~s/[^-_0-9[:alnum:]]+//g;
530 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
534 $params{message} = IkiWiki::possibly_foolish_untaint($params{message});
536 if ($params{message} !~ /\S/) {
537 # Force git to allow empty commit messages.
538 # (If this version of git supports it.)
539 my ($version)=`git --version` =~ /git version (.*)/;
540 if ($version ge "1.5.4") {
541 push @opts, '--cleanup=verbatim';
544 $params{message}.=".";
548 # git commit returns non-zero if file has not been really changed.
549 # so we should ignore its exit status (hence run_or_non).
550 if (run_or_non('git', 'commit', @opts, '-m', $params{message})) {
551 if (length $config{gitorigin_branch}) {
552 run_or_cry('git', 'push', $config{gitorigin_branch});
557 return undef; # success
561 # Add file to archive.
565 run_or_cry('git', 'add', $file);
569 # Remove file from archive.
573 run_or_cry('git', 'rm', '-f', $file);
576 sub rcs_rename ($$) {
577 my ($src, $dest) = @_;
579 run_or_cry('git', 'mv', '-f', $src, $dest);
582 sub rcs_recentchanges ($) {
583 # List of recent changes.
587 eval q{use Date::Parse};
591 foreach my $ci (git_commit_info('HEAD', $num || 1)) {
592 # Skip redundant commits.
593 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
595 my ($sha1, $when) = (
597 $ci->{'author_epoch'}
601 foreach my $detail (@{ $ci->{'details'} }) {
602 my $file = $detail->{'file'};
604 my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
605 $diffurl =~ s/\[\[file\]\]/$file/go;
606 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
607 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
608 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
609 $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
612 page => pagename($file),
619 foreach my $line (@{$ci->{'comment'}}) {
620 $pastblank=1 if $line eq '';
621 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
622 push @messages, { line => $line };
625 my $user=$ci->{'author_username'};
626 my $web_commit = ($ci->{'author'} =~ /\@web>/);
629 # Set nickname only if a non-url author_username is available,
630 # and author_name is an url.
631 if ($user !~ /:\/\// && defined $ci->{'author_name'} &&
632 $ci->{'author_name'} =~ /:\/\//) {
634 $user=$ci->{'author_name'};
637 # compatability code for old web commit messages
639 defined $messages[0] &&
640 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
641 $user = defined $2 ? "$2" : "$3";
642 $messages[0]->{line} = $4;
649 nickname => $nickname,
650 committype => $web_commit ? "web" : "git",
652 message => [@messages],
656 last if @rets >= $num;
664 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
666 foreach my $line (run_or_non("git", "show", $sha1)) {
667 if (@lines || $line=~/^diff --git/) {
668 push @lines, $line."\n";
675 return join("", @lines);
684 my $id=shift; # 0 = mtime ; 1 = ctime
686 if (! keys %time_cache) {
688 foreach my $line (run_or_die('git', 'log',
689 '--pretty=format:%ct',
690 '--name-only', '--relative')) {
691 if (! defined $date && $line =~ /^(\d+)$/) {
694 elsif (! length $line) {
698 my $f=decode_git_file($line);
700 if (! $time_cache{$f}) {
701 $time_cache{$f}[0]=$date; # mtime
703 $time_cache{$f}[1]=$date; # ctime
708 return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
713 sub rcs_getctime ($) {
716 return findtimes($file, 1);
719 sub rcs_getmtime ($) {
722 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");
748 sub git_parse_changes {
751 my $subdir = git_find_root();
753 foreach my $ci (@changes) {
754 foreach my $detail (@{ $ci->{'details'} }) {
755 my $file = $detail->{'file'};
757 # check that all changed files are in the
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') &&
795 eval q{use File::Temp};
798 ($fh, $path)=File::Temp::tempfile("XXXXXXXXXX", UNLINK => 1);
799 # Ensure we run this in the right place, 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 (@) {
841 # Determine what the effects are of reverting the patch with the
842 # ID given by 'rev'. Returns the same structure as rcs_receive.
843 # Note test_changes expects 'cgi' and 'session' parameters.
845 my $rev = $params{rev};
847 require IkiWiki::Receive;
848 IkiWiki::Receive::test_changes(%params, changes => [git_parse_changes(git_commit_info($rev, 1))]);
852 # Try to revert the given patch; returns undef on _success_.
853 # Same parameters as rcs_commit_staged + 'rev', the patch ID to be
856 my $rev = $params{rev};
858 if(run_or_non('git', 'revert', '--no-commit', $rev)) {
859 debug "Committing revert for patch '$rev'.";
860 rcs_commit_staged(message => "This reverts commit $rev", @_);
862 # No idea what is actually getting reverted, so all we can do is say we failed.
863 run_or_die('git', 'reset', '--hard');
864 return "Failed to revert patch $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);