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
14 hook(type => "checkconfig", id => "git", call => \&checkconfig);
15 hook(type => "getsetup", id => "git", call => \&getsetup);
16 hook(type => "genwrapper", id => "git", call => \&genwrapper);
17 hook(type => "rcs", id => "rcs_update", call => \&rcs_update);
18 hook(type => "rcs", id => "rcs_prepedit", call => \&rcs_prepedit);
19 hook(type => "rcs", id => "rcs_commit", call => \&rcs_commit);
20 hook(type => "rcs", id => "rcs_commit_staged", call => \&rcs_commit_staged);
21 hook(type => "rcs", id => "rcs_add", call => \&rcs_add);
22 hook(type => "rcs", id => "rcs_remove", call => \&rcs_remove);
23 hook(type => "rcs", id => "rcs_rename", call => \&rcs_rename);
24 hook(type => "rcs", id => "rcs_recentchanges", call => \&rcs_recentchanges);
25 hook(type => "rcs", id => "rcs_diff", call => \&rcs_diff);
26 hook(type => "rcs", id => "rcs_getctime", call => \&rcs_getctime);
27 hook(type => "rcs", id => "rcs_getmtime", call => \&rcs_getmtime);
28 hook(type => "rcs", id => "rcs_receive", call => \&rcs_receive);
29 hook(type => "rcs", id => "rcs_preprevert", call => \&rcs_preprevert);
30 hook(type => "rcs", id => "rcs_revert", call => \&rcs_revert);
34 if (! defined $config{gitorigin_branch}) {
35 $config{gitorigin_branch}="origin";
37 if (! defined $config{gitmaster_branch}) {
38 $config{gitmaster_branch}="master";
40 if (defined $config{git_wrapper} &&
41 length $config{git_wrapper}) {
42 push @{$config{wrappers}}, {
43 wrapper => $config{git_wrapper},
44 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
45 wrapper_background_command => $config{git_wrapper_background_command},
49 if (defined $config{git_test_receive_wrapper} &&
50 length $config{git_test_receive_wrapper} &&
51 defined $config{untrusted_committers} &&
52 @{$config{untrusted_committers}}) {
53 push @{$config{wrappers}}, {
55 wrapper => $config{git_test_receive_wrapper},
56 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
60 # Avoid notes, parser does not handle and they only slow things down.
61 $ENV{GIT_NOTES_REF}="";
63 # Run receive test only if being called by the wrapper, and not
64 # when generating same.
65 if ($config{test_receive} && ! exists $config{wrapper}) {
66 require IkiWiki::Receive;
67 IkiWiki::Receive::test();
74 safe => 0, # rcs plugin
80 example => "/git/wiki.git/hooks/post-update",
81 description => "git hook to generate",
85 git_wrapper_background_command => {
87 example => "git push github",
88 description => "shell command for git_wrapper to run, in the background",
95 description => "mode for git_wrapper (can safely be made suid)",
99 git_test_receive_wrapper => {
101 example => "/git/wiki.git/hooks/pre-receive",
102 description => "git pre-receive hook to generate",
106 untrusted_committers => {
109 description => "unix users whose commits should be checked by the pre-receive hook",
115 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]];hb=HEAD",
116 description => "gitweb url to show file history ([[file]] substituted)",
122 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]]",
123 description => "gitweb url to show a diff ([[file]], [[sha1_to]], [[sha1_from]], [[sha1_commit]], and [[sha1_parent]] substituted)",
127 gitorigin_branch => {
130 description => "where to pull and push changes (set to empty string to disable)",
131 safe => 0, # paranoia
134 gitmaster_branch => {
137 description => "branch that the wiki is stored in",
138 safe => 0, # paranoia
144 if ($config{test_receive}) {
145 require IkiWiki::Receive;
146 return IkiWiki::Receive::genwrapper();
156 sub in_git_dir ($$) {
165 # Start a child process safely without resorting to /bin/sh.
166 # Returns command output (in list content) or success state
167 # (in scalar context), or runs the specified data handler.
169 my ($error_handler, $data_handler, @cmdline) = @_;
171 my $pid = open my $OUT, "-|";
173 error("Cannot fork: $!") if !defined $pid;
177 # Git commands want to be in wc.
178 if (! defined $git_dir) {
179 chdir $config{srcdir}
180 or error("cannot chdir to $config{srcdir}: $!");
184 or error("cannot chdir to $git_dir: $!");
186 exec @cmdline or error("Cannot exec '@cmdline': $!");
190 # git output is probably utf-8 encoded, but may contain
191 # other encodings or invalidly encoded stuff. So do not rely
192 # on the normal utf-8 IO layer, decode it by hand.
197 $_=decode_utf8($_, 0);
201 if (! defined $data_handler) {
205 last unless $data_handler->($_);
211 $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
213 return wantarray ? @lines : ($? == 0);
215 # Convenient wrappers.
216 sub run_or_die ($@) { safe_git(\&error, undef, @_) }
217 sub run_or_cry ($@) { safe_git(sub { warn @_ }, undef, @_) }
218 sub run_or_non ($@) { safe_git(undef, undef, @_) }
221 sub merge_past ($$$) {
222 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
223 # Git merge commands work with the committed changes, except in the
224 # implicit case of '-m' of git checkout(1). So we should invent a
225 # kludge here. In principle, we need to create a throw-away branch
226 # in preparing for the merge itself. Since branches are cheap (and
227 # branching is fast), this shouldn't cost high.
229 # The main problem is the presence of _uncommitted_ local changes. One
230 # possible approach to get rid of this situation could be that we first
231 # make a temporary commit in the master branch and later restore the
232 # initial state (this is possible since Git has the ability to undo a
233 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
236 # - create a diff of HEAD:current-sha1
238 # - create a dummy branch and switch to it
239 # - rewind to past (reset --hard to the current-sha1)
240 # - apply the diff and commit
241 # - switch to master and do the merge with the dummy branch
242 # - make a soft reset (undo the last commit of master)
244 # The above method has some drawbacks: (1) it needs a redundant commit
245 # just to get rid of local changes, (2) somewhat slow because of the
246 # required system forks. Until someone points a more straight method
247 # (which I would be grateful) I have implemented an alternative method.
248 # In this approach, we hide all the modified files from Git by renaming
249 # them (using the 'rename' builtin) and later restore those files in
250 # the throw-away branch (that is, we put the files themselves instead
251 # of applying a patch).
253 my ($sha1, $file, $message) = @_;
255 my @undo; # undo stack for cleanup in case of an error
256 my $conflict; # file content with conflict markers
259 # Hide local changes from Git by renaming the modified file.
260 # Relative paths must be converted to absolute for renaming.
261 my ($target, $hidden) = (
262 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
264 rename($target, $hidden)
265 or error("rename '$target' to '$hidden' failed: $!");
266 # Ensure to restore the renamed file on error.
268 return if ! -e "$hidden"; # already renamed
269 rename($hidden, $target)
270 or warn "rename '$hidden' to '$target' failed: $!";
273 my $branch = "throw_away_${sha1}"; # supposed to be unique
275 # Create a throw-away branch and rewind backward.
276 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
277 run_or_die('git', 'branch', $branch, $sha1);
279 # Switch to throw-away branch for the merge operation.
281 if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
282 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
285 run_or_die('git', 'checkout', $branch);
287 # Put the modified file in _this_ branch.
288 rename($hidden, $target)
289 or error("rename '$hidden' to '$target' failed: $!");
291 # _Silently_ commit all modifications in the current branch.
292 run_or_non('git', 'commit', '-m', $message, '-a');
293 # ... and re-switch to master.
294 run_or_die('git', 'checkout', $config{gitmaster_branch});
296 # Attempt to merge without complaining.
297 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
298 $conflict = readfile($target);
299 run_or_die('git', 'reset', '--hard');
304 # Process undo stack (in reverse order). By policy cleanup
305 # actions should normally print a warning on failure.
306 while (my $handle = pop @undo) {
310 error("Git merge failed!\n$failure\n") if $failure;
315 sub decode_git_file ($) {
318 # git does not output utf-8 filenames, but instead
319 # double-quotes them with the utf-8 characters
320 # escaped as \nnn\nnn.
321 if ($file =~ m/^"(.*)"$/) {
322 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
325 # strip prefix if in a subdir
326 if (! defined $prefix) {
327 ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
328 if (! defined $prefix) {
332 $file =~ s/^\Q$prefix\E//;
334 return decode("utf8", $file);
337 sub parse_diff_tree ($) {
338 # Parse the raw diff tree chunk and return the info hash.
339 # See git-diff-tree(1) for the syntax.
343 return if !defined @{ $dt_ref } ||
344 !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
348 while (my $line = shift @{ $dt_ref }) {
349 return if $line !~ m/^(.+) ($sha1_pattern)/;
356 # Identification lines for the commit.
357 while (my $line = shift @{ $dt_ref }) {
358 # Regexps are semi-stolen from gitweb.cgi.
359 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
362 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
363 # XXX: collecting in reverse order
364 push @{ $ci{'parents'} }, $1;
366 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
367 my ($who, $name, $epoch, $tz) =
371 $ci{ "${who}_epoch" } = $epoch;
372 $ci{ "${who}_tz" } = $tz;
374 if ($name =~ m/^([^<]+)\s+<([^@>]+)/) {
375 $ci{"${who}_name"} = $1;
376 $ci{"${who}_username"} = $2;
378 elsif ($name =~ m/^([^<]+)\s+<>$/) {
379 $ci{"${who}_username"} = $1;
382 $ci{"${who}_username"} = $name;
385 elsif ($line =~ m/^$/) {
386 # Trailing empty line signals next section.
391 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
393 if (defined $ci{'parents'}) {
394 $ci{'parent'} = @{ $ci{'parents'} }[0];
397 $ci{'parent'} = 0 x 40;
400 # Commit message (optional).
401 while ($dt_ref->[0] =~ /^ /) {
402 my $line = shift @{ $dt_ref };
404 push @{ $ci{'comment'} }, $line;
406 shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
409 while (my $line = shift @{ $dt_ref }) {
411 (:+) # number of parents
412 ([^\t]+)\t # modes, sha1, status
415 my $num_parents = length $1;
416 my @tmp = split(" ", $2);
417 my ($file, $file_to) = split("\t", $3);
418 my @mode_from = splice(@tmp, 0, $num_parents);
419 my $mode_to = shift(@tmp);
420 my @sha1_from = splice(@tmp, 0, $num_parents);
421 my $sha1_to = shift(@tmp);
422 my $status = shift(@tmp);
425 push @{ $ci{'details'} }, {
426 'file' => decode_git_file($file),
427 'sha1_from' => $sha1_from[0],
428 'sha1_to' => $sha1_to,
429 'mode_from' => $mode_from[0],
430 'mode_to' => $mode_to,
442 sub git_commit_info ($;$) {
443 # Return an array of commit info hashes of num commits
444 # starting from the given sha1sum.
445 my ($sha1, $num) = @_;
448 push @opts, "--max-count=$num" if defined $num;
450 my @raw_lines = run_or_die('git', 'log', @opts,
451 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
452 '-r', $sha1, '--', '.');
455 while (my $parsed = parse_diff_tree(\@raw_lines)) {
459 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
461 return wantarray ? @ci : $ci[0];
465 # Return head sha1sum (of given file).
466 my $file = shift || q{--};
468 # Ignore error since a non-existing file might be given.
469 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
472 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
475 debug("Empty sha1sum for '$file'.");
477 return defined $sha1 ? $sha1 : q{};
481 # Update working directory.
483 if (length $config{gitorigin_branch}) {
484 run_or_cry('git', 'pull', '--prune', $config{gitorigin_branch});
488 sub rcs_prepedit ($) {
489 # Return the commit sha1sum of the file when editing begins.
490 # This will be later used in rcs_commit if a merge is required.
493 return git_sha1($file);
497 # Try to commit the page; returns undef on _success_ and
498 # a version of the page with the rcs's conflict markers on
502 # Check to see if the page has been changed by someone else since
503 # rcs_prepedit was called.
504 my $cur = git_sha1($params{file});
505 my ($prev) = $params{token} =~ /^($sha1_pattern)$/; # untaint
507 if (defined $cur && defined $prev && $cur ne $prev) {
508 my $conflict = merge_past($prev, $params{file}, $dummy_commit_msg);
509 return $conflict if defined $conflict;
512 return rcs_commit_helper(@_);
515 sub rcs_commit_staged (@) {
516 # Commits all staged changes. Changes can be staged using rcs_add,
517 # rcs_remove, and rcs_rename.
518 return rcs_commit_helper(@_);
521 sub rcs_commit_helper (@) {
526 if (defined $params{session}) {
527 # Set the commit author and email based on web session info.
529 if (defined $params{session}->param("name")) {
530 $u=$params{session}->param("name");
532 elsif (defined $params{session}->remote_addr()) {
533 $u=$params{session}->remote_addr();
537 $ENV{GIT_AUTHOR_NAME}=$u;
539 if (defined $params{session}->param("nickname")) {
540 $u=encode_utf8($params{session}->param("nickname"));
542 $u=~s/[^-_0-9[:alnum:]]+//g;
545 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
549 $params{message} = IkiWiki::possibly_foolish_untaint($params{message});
551 if ($params{message} !~ /\S/) {
552 # Force git to allow empty commit messages.
553 # (If this version of git supports it.)
554 my ($version)=`git --version` =~ /git version (.*)/;
555 if ($version ge "1.5.4") {
556 push @opts, '--cleanup=verbatim';
559 $params{message}.=".";
562 if (exists $params{file}) {
563 push @opts, '--', $params{file};
565 # git commit returns non-zero if nothing really changed.
566 # So we should ignore its exit status (hence run_or_non).
567 if (run_or_non('git', 'commit', '-m', $params{message}, '-q', @opts)) {
568 if (length $config{gitorigin_branch}) {
569 run_or_cry('git', 'push', $config{gitorigin_branch});
574 return undef; # success
578 # Add file to archive.
582 run_or_cry('git', 'add', $file);
586 # Remove file from archive.
590 run_or_cry('git', 'rm', '-f', $file);
593 sub rcs_rename ($$) {
594 my ($src, $dest) = @_;
596 run_or_cry('git', 'mv', '-f', $src, $dest);
599 sub rcs_recentchanges ($) {
600 # List of recent changes.
604 eval q{use Date::Parse};
608 foreach my $ci (git_commit_info('HEAD', $num || 1)) {
609 # Skip redundant commits.
610 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
612 my ($sha1, $when) = (
614 $ci->{'author_epoch'}
618 foreach my $detail (@{ $ci->{'details'} }) {
619 my $file = $detail->{'file'};
621 my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
622 $diffurl =~ s/\[\[file\]\]/$file/go;
623 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
624 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
625 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
626 $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
629 page => pagename($file),
636 foreach my $line (@{$ci->{'comment'}}) {
637 $pastblank=1 if $line eq '';
638 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
639 push @messages, { line => $line };
642 my $user=$ci->{'author_username'};
643 my $web_commit = ($ci->{'author'} =~ /\@web>/);
646 # Set nickname only if a non-url author_username is available,
647 # and author_name is an url.
648 if ($user !~ /:\/\// && defined $ci->{'author_name'} &&
649 $ci->{'author_name'} =~ /:\/\//) {
651 $user=$ci->{'author_name'};
654 # compatability code for old web commit messages
656 defined $messages[0] &&
657 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
658 $user = defined $2 ? "$2" : "$3";
659 $messages[0]->{line} = $4;
666 nickname => $nickname,
667 committype => $web_commit ? "web" : "git",
669 message => [@messages],
673 last if @rets >= $num;
682 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
686 return if defined $maxlines && @lines == $maxlines;
687 push @lines, $line."\n"
688 if (@lines || $line=~/^diff --git/);
691 safe_git(undef, $addlines, "git", "show", $sha1);
696 return join("", @lines);
705 my $id=shift; # 0 = mtime ; 1 = ctime
707 if (! keys %time_cache) {
709 foreach my $line (run_or_die('git', 'log',
710 '--pretty=format:%at',
711 '--name-only', '--relative')) {
712 if (! defined $date && $line =~ /^(\d+)$/) {
715 elsif (! length $line) {
719 my $f=decode_git_file($line);
721 if (! $time_cache{$f}) {
722 $time_cache{$f}[0]=$date; # mtime
724 $time_cache{$f}[1]=$date; # ctime
729 return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
734 sub rcs_getctime ($) {
737 return findtimes($file, 1);
740 sub rcs_getmtime ($) {
743 return findtimes($file, 0);
749 # The wiki may not be the only thing in the git repo.
750 # Determine if it is in a subdirectory by examining the srcdir,
751 # and its parents, looking for the .git directory.
753 return @$ret if defined $ret;
756 my $dir=$config{srcdir};
757 while (! -d "$dir/.git") {
758 $subdir=IkiWiki::basename($dir)."/".$subdir;
759 $dir=IkiWiki::dirname($dir);
761 error("cannot determine root of git repo");
765 $ret=[$subdir, $dir];
771 sub git_parse_changes {
772 my $reverted = shift;
775 my ($subdir, $rootdir) = git_find_root();
777 foreach my $ci (@changes) {
778 foreach my $detail (@{ $ci->{'details'} }) {
779 my $file = $detail->{'file'};
781 # check that all changed files are in the subdir
782 if (length $subdir &&
783 ! ($file =~ s/^\Q$subdir\E//)) {
784 error sprintf(gettext("you are not allowed to change %s"), $file);
787 my ($action, $mode, $path);
788 if ($detail->{'status'} =~ /^[M]+\d*$/) {
790 $mode=$detail->{'mode_to'};
792 elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
793 $action= $reverted ? "remove" : "add";
794 $mode=$detail->{'mode_to'};
796 elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
797 $action= $reverted ? "add" : "remove";
798 $mode=$detail->{'mode_from'};
801 error "unknown status ".$detail->{'status'};
804 # test that the file mode is ok
805 if ($mode !~ /^100[64][64][64]$/) {
806 error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
808 if ($action eq "change") {
809 if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
810 error gettext("you are not allowed to change file modes");
814 # extract attachment to temp file
815 if (($action eq 'add' || $action eq 'change') &&
817 eval q{use File::Temp};
820 ($fh, $path)=File::Temp::tempfile(undef, UNLINK => 1);
821 my $cmd = "cd $git_dir && ".
822 "git show $detail->{sha1_to} > '$path'";
823 if (system($cmd) != 0) {
824 error("failed writing temp file '$path'.");
843 my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
845 # only allow changes to gitmaster_branch
846 if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
847 error sprintf(gettext("you are not allowed to change %s"), $refname);
850 # Avoid chdir when running git here, because the changes
851 # are in the master git repo, not the srcdir repo.
852 # (Also, if a subdir is involved, we don't want to chdir to
853 # it and only see changes in it.)
854 # The pre-receive hook already puts us in the right place.
855 in_git_dir(".", sub {
856 push @rets, git_parse_changes(0, git_commit_info($oldrev."..".$newrev));
860 return reverse @rets;
863 sub rcs_preprevert ($) {
865 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
867 # Examine changes from root of git repo, not from any subdir,
868 # in order to see all changes.
869 my ($subdir, $rootdir) = git_find_root();
870 in_git_dir($rootdir, sub {
871 my @commits=git_commit_info($sha1, 1);
874 error "unknown commit"; # just in case
877 # git revert will fail on merge commits. Add a nice message.
878 if (exists $commits[0]->{parents} &&
879 @{$commits[0]->{parents}} > 1) {
880 error gettext("you are not allowed to revert a merge");
883 git_parse_changes(1, @commits);
888 # Try to revert the given rev; returns undef on _success_.
890 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
892 if (run_or_non('git', 'revert', '--no-commit', $sha1)) {
896 run_or_die('git', 'reset', '--hard');
897 return sprintf(gettext("Failed to revert commit %s"), $sha1);