2 package IkiWiki::Plugin::git;
8 use URI::Escape q{uri_escape_utf8};
9 use open qw{:utf8 :std};
11 my $sha1_pattern = qr/[0-9a-fA-F]{40}/; # pattern to validate Git sha1sums
12 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);
35 if (! defined $config{gitorigin_branch}) {
36 $config{gitorigin_branch}="origin";
38 if (! defined $config{gitmaster_branch}) {
39 $config{gitmaster_branch}="master";
41 if (defined $config{git_wrapper} &&
42 length $config{git_wrapper}) {
43 push @{$config{wrappers}}, {
44 wrapper => $config{git_wrapper},
45 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
46 wrapper_background_command => $config{git_wrapper_background_command},
50 if (defined $config{git_test_receive_wrapper} &&
51 length $config{git_test_receive_wrapper} &&
52 defined $config{untrusted_committers} &&
53 @{$config{untrusted_committers}}) {
54 push @{$config{wrappers}}, {
56 wrapper => $config{git_test_receive_wrapper},
57 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
61 # Avoid notes, parser does not handle and they only slow things down.
62 $ENV{GIT_NOTES_REF}="";
64 # Run receive test only if being called by the wrapper, and not
65 # when generating same.
66 if ($config{test_receive} && ! exists $config{wrapper}) {
67 require IkiWiki::Receive;
68 IkiWiki::Receive::test();
75 safe => 0, # rcs plugin
81 example => "/git/wiki.git/hooks/post-update",
82 description => "git hook to generate",
86 git_wrapper_background_command => {
88 example => "git push github",
89 description => "shell command for git_wrapper to run, in the background",
96 description => "mode for git_wrapper (can safely be made suid)",
100 git_test_receive_wrapper => {
102 example => "/git/wiki.git/hooks/pre-receive",
103 description => "git pre-receive hook to generate",
107 untrusted_committers => {
110 description => "unix users whose commits should be checked by the pre-receive hook",
116 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]];hb=HEAD",
117 description => "gitweb url to show file history ([[file]] substituted)",
123 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]]",
124 description => "gitweb url to show a diff ([[file]], [[sha1_to]], [[sha1_from]], [[sha1_commit]], and [[sha1_parent]] substituted)",
128 gitorigin_branch => {
131 description => "where to pull and push changes (set to empty string to disable)",
132 safe => 0, # paranoia
135 gitmaster_branch => {
138 description => "branch that the wiki is stored in",
139 safe => 0, # paranoia
145 if ($config{test_receive}) {
146 require IkiWiki::Receive;
147 return IkiWiki::Receive::genwrapper();
157 sub in_git_dir ($$) {
166 # Start a child process safely without resorting to /bin/sh.
167 # Returns command output (in list content) or success state
168 # (in scalar context), or runs the specified data handler.
170 my ($error_handler, $data_handler, @cmdline) = @_;
172 my $pid = open my $OUT, "-|";
174 error("Cannot fork: $!") if !defined $pid;
178 # Git commands want to be in wc.
179 if (! defined $git_dir) {
180 chdir $config{srcdir}
181 or error("cannot chdir to $config{srcdir}: $!");
185 or error("cannot chdir to $git_dir: $!");
187 exec @cmdline or error("Cannot exec '@cmdline': $!");
191 # git output is probably utf-8 encoded, but may contain
192 # other encodings or invalidly encoded stuff. So do not rely
193 # on the normal utf-8 IO layer, decode it by hand.
198 $_=decode_utf8($_, 0);
202 if (! defined $data_handler) {
206 last unless $data_handler->($_);
212 $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
214 return wantarray ? @lines : ($? == 0);
216 # Convenient wrappers.
217 sub run_or_die ($@) { safe_git(\&error, undef, @_) }
218 sub run_or_cry ($@) { safe_git(sub { warn @_ }, undef, @_) }
219 sub run_or_non ($@) { safe_git(undef, undef, @_) }
222 sub merge_past ($$$) {
223 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
224 # Git merge commands work with the committed changes, except in the
225 # implicit case of '-m' of git checkout(1). So we should invent a
226 # kludge here. In principle, we need to create a throw-away branch
227 # in preparing for the merge itself. Since branches are cheap (and
228 # branching is fast), this shouldn't cost high.
230 # The main problem is the presence of _uncommitted_ local changes. One
231 # possible approach to get rid of this situation could be that we first
232 # make a temporary commit in the master branch and later restore the
233 # initial state (this is possible since Git has the ability to undo a
234 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
237 # - create a diff of HEAD:current-sha1
239 # - create a dummy branch and switch to it
240 # - rewind to past (reset --hard to the current-sha1)
241 # - apply the diff and commit
242 # - switch to master and do the merge with the dummy branch
243 # - make a soft reset (undo the last commit of master)
245 # The above method has some drawbacks: (1) it needs a redundant commit
246 # just to get rid of local changes, (2) somewhat slow because of the
247 # required system forks. Until someone points a more straight method
248 # (which I would be grateful) I have implemented an alternative method.
249 # In this approach, we hide all the modified files from Git by renaming
250 # them (using the 'rename' builtin) and later restore those files in
251 # the throw-away branch (that is, we put the files themselves instead
252 # of applying a patch).
254 my ($sha1, $file, $message) = @_;
256 my @undo; # undo stack for cleanup in case of an error
257 my $conflict; # file content with conflict markers
260 # Hide local changes from Git by renaming the modified file.
261 # Relative paths must be converted to absolute for renaming.
262 my ($target, $hidden) = (
263 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
265 rename($target, $hidden)
266 or error("rename '$target' to '$hidden' failed: $!");
267 # Ensure to restore the renamed file on error.
269 return if ! -e "$hidden"; # already renamed
270 rename($hidden, $target)
271 or warn "rename '$hidden' to '$target' failed: $!";
274 my $branch = "throw_away_${sha1}"; # supposed to be unique
276 # Create a throw-away branch and rewind backward.
277 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
278 run_or_die('git', 'branch', $branch, $sha1);
280 # Switch to throw-away branch for the merge operation.
282 if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
283 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
286 run_or_die('git', 'checkout', $branch);
288 # Put the modified file in _this_ branch.
289 rename($hidden, $target)
290 or error("rename '$hidden' to '$target' failed: $!");
292 # _Silently_ commit all modifications in the current branch.
293 run_or_non('git', 'commit', '-m', $message, '-a');
294 # ... and re-switch to master.
295 run_or_die('git', 'checkout', $config{gitmaster_branch});
297 # Attempt to merge without complaining.
298 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
299 $conflict = readfile($target);
300 run_or_die('git', 'reset', '--hard');
305 # Process undo stack (in reverse order). By policy cleanup
306 # actions should normally print a warning on failure.
307 while (my $handle = pop @undo) {
311 error("Git merge failed!\n$failure\n") if $failure;
316 sub decode_git_file ($) {
319 # git does not output utf-8 filenames, but instead
320 # double-quotes them with the utf-8 characters
321 # escaped as \nnn\nnn.
322 if ($file =~ m/^"(.*)"$/) {
323 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
326 # strip prefix if in a subdir
327 if (! defined $prefix) {
328 ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
329 if (! defined $prefix) {
333 $file =~ s/^\Q$prefix\E//;
335 return decode("utf8", $file);
338 sub parse_diff_tree ($) {
339 # Parse the raw diff tree chunk and return the info hash.
340 # See git-diff-tree(1) for the syntax.
344 return if !defined @{ $dt_ref } ||
345 !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
349 while (my $line = shift @{ $dt_ref }) {
350 return if $line !~ m/^(.+) ($sha1_pattern)/;
357 # Identification lines for the commit.
358 while (my $line = shift @{ $dt_ref }) {
359 # Regexps are semi-stolen from gitweb.cgi.
360 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
363 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
364 # XXX: collecting in reverse order
365 push @{ $ci{'parents'} }, $1;
367 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
368 my ($who, $name, $epoch, $tz) =
372 $ci{ "${who}_epoch" } = $epoch;
373 $ci{ "${who}_tz" } = $tz;
375 if ($name =~ m/^([^<]+)\s+<([^@>]+)/) {
376 $ci{"${who}_name"} = $1;
377 $ci{"${who}_username"} = $2;
379 elsif ($name =~ m/^([^<]+)\s+<>$/) {
380 $ci{"${who}_username"} = $1;
383 $ci{"${who}_username"} = $name;
386 elsif ($line =~ m/^$/) {
387 # Trailing empty line signals next section.
392 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
394 if (defined $ci{'parents'}) {
395 $ci{'parent'} = @{ $ci{'parents'} }[0];
398 $ci{'parent'} = 0 x 40;
401 # Commit message (optional).
402 while ($dt_ref->[0] =~ /^ /) {
403 my $line = shift @{ $dt_ref };
405 push @{ $ci{'comment'} }, $line;
407 shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
410 while (my $line = shift @{ $dt_ref }) {
412 (:+) # number of parents
413 ([^\t]+)\t # modes, sha1, status
416 my $num_parents = length $1;
417 my @tmp = split(" ", $2);
418 my ($file, $file_to) = split("\t", $3);
419 my @mode_from = splice(@tmp, 0, $num_parents);
420 my $mode_to = shift(@tmp);
421 my @sha1_from = splice(@tmp, 0, $num_parents);
422 my $sha1_to = shift(@tmp);
423 my $status = shift(@tmp);
426 push @{ $ci{'details'} }, {
427 'file' => decode_git_file($file),
428 'sha1_from' => $sha1_from[0],
429 'sha1_to' => $sha1_to,
430 'mode_from' => $mode_from[0],
431 'mode_to' => $mode_to,
443 sub git_commit_info ($;$) {
444 # Return an array of commit info hashes of num commits
445 # starting from the given sha1sum.
446 my ($sha1, $num) = @_;
449 push @opts, "--max-count=$num" if defined $num;
451 my @raw_lines = run_or_die('git', 'log', @opts,
452 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
453 '-r', $sha1, '--', '.');
456 while (my $parsed = parse_diff_tree(\@raw_lines)) {
460 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
462 return wantarray ? @ci : $ci[0];
466 # Return head sha1sum (of given file).
467 my $file = shift || q{--};
469 # Ignore error since a non-existing file might be given.
470 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
473 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
476 debug("Empty sha1sum for '$file'.");
478 return defined $sha1 ? $sha1 : q{};
482 # Update working directory.
484 if (length $config{gitorigin_branch}) {
485 run_or_cry('git', 'pull', '--prune', $config{gitorigin_branch});
489 sub rcs_prepedit ($) {
490 # Return the commit sha1sum of the file when editing begins.
491 # This will be later used in rcs_commit if a merge is required.
494 return git_sha1($file);
498 # Try to commit the page; returns undef on _success_ and
499 # a version of the page with the rcs's conflict markers on
503 # Check to see if the page has been changed by someone else since
504 # rcs_prepedit was called.
505 my $cur = git_sha1($params{file});
506 my ($prev) = $params{token} =~ /^($sha1_pattern)$/; # untaint
508 if (defined $cur && defined $prev && $cur ne $prev) {
509 my $conflict = merge_past($prev, $params{file}, $dummy_commit_msg);
510 return $conflict if defined $conflict;
513 return rcs_commit_helper(@_);
516 sub rcs_commit_staged (@) {
517 # Commits all staged changes. Changes can be staged using rcs_add,
518 # rcs_remove, and rcs_rename.
519 return rcs_commit_helper(@_);
522 sub rcs_commit_helper (@) {
527 if (defined $params{session}) {
528 # Set the commit author and email based on web session info.
530 if (defined $params{session}->param("name")) {
531 $u=$params{session}->param("name");
533 elsif (defined $params{session}->remote_addr()) {
534 $u=$params{session}->remote_addr();
538 $ENV{GIT_AUTHOR_NAME}=$u;
540 if (defined $params{session}->param("nickname")) {
541 $u=encode_utf8($params{session}->param("nickname"));
543 $u=~s/[^-_0-9[:alnum:]]+//g;
546 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
550 $params{message} = IkiWiki::possibly_foolish_untaint($params{message});
552 if ($params{message} !~ /\S/) {
553 # Force git to allow empty commit messages.
554 # (If this version of git supports it.)
555 my ($version)=`git --version` =~ /git version (.*)/;
556 if ($version ge "1.5.4") {
557 push @opts, '--cleanup=verbatim';
560 $params{message}.=".";
563 if (exists $params{file}) {
564 push @opts, '--', $params{file};
566 # git commit returns non-zero if nothing really changed.
567 # So we should ignore its exit status (hence run_or_non).
568 if (run_or_non('git', 'commit', '-m', $params{message}, '-q', @opts)) {
569 if (length $config{gitorigin_branch}) {
570 run_or_cry('git', 'push', $config{gitorigin_branch});
575 return undef; # success
579 # Add file to archive.
583 run_or_cry('git', 'add', $file);
587 # Remove file from archive.
591 run_or_cry('git', 'rm', '-f', $file);
594 sub rcs_rename ($$) {
595 my ($src, $dest) = @_;
597 run_or_cry('git', 'mv', '-f', $src, $dest);
600 sub rcs_recentchanges ($) {
601 # List of recent changes.
605 eval q{use Date::Parse};
609 foreach my $ci (git_commit_info('HEAD', $num || 1)) {
610 # Skip redundant commits.
611 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
613 my ($sha1, $when) = (
615 $ci->{'author_epoch'}
619 foreach my $detail (@{ $ci->{'details'} }) {
620 my $file = $detail->{'file'};
621 my $efile = uri_escape_utf8($file);
623 my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
624 $diffurl =~ s/\[\[file\]\]/$efile/go;
625 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
626 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
627 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
628 $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
631 page => pagename($file),
638 foreach my $line (@{$ci->{'comment'}}) {
639 $pastblank=1 if $line eq '';
640 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
641 push @messages, { line => $line };
644 my $user=$ci->{'author_username'};
645 my $web_commit = ($ci->{'author'} =~ /\@web>/);
648 # Set nickname only if a non-url author_username is available,
649 # and author_name is an url.
650 if ($user !~ /:\/\// && defined $ci->{'author_name'} &&
651 $ci->{'author_name'} =~ /:\/\//) {
653 $user=$ci->{'author_name'};
656 # compatability code for old web commit messages
658 defined $messages[0] &&
659 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
660 $user = defined $2 ? "$2" : "$3";
661 $messages[0]->{line} = $4;
668 nickname => $nickname,
669 committype => $web_commit ? "web" : "git",
671 message => [@messages],
675 last if @rets >= $num;
684 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
688 return if defined $maxlines && @lines == $maxlines;
689 push @lines, $line."\n"
690 if (@lines || $line=~/^diff --git/);
693 safe_git(undef, $addlines, "git", "show", $sha1);
698 return join("", @lines);
707 my $id=shift; # 0 = mtime ; 1 = ctime
709 if (! keys %time_cache) {
711 foreach my $line (run_or_die('git', 'log',
712 '--pretty=format:%at',
713 '--name-only', '--relative')) {
714 if (! defined $date && $line =~ /^(\d+)$/) {
717 elsif (! length $line) {
721 my $f=decode_git_file($line);
723 if (! $time_cache{$f}) {
724 $time_cache{$f}[0]=$date; # mtime
726 $time_cache{$f}[1]=$date; # ctime
731 return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
736 sub rcs_getctime ($) {
739 return findtimes($file, 1);
742 sub rcs_getmtime ($) {
745 return findtimes($file, 0);
751 # The wiki may not be the only thing in the git repo.
752 # Determine if it is in a subdirectory by examining the srcdir,
753 # and its parents, looking for the .git directory.
755 return @$ret if defined $ret;
758 my $dir=$config{srcdir};
759 while (! -d "$dir/.git") {
760 $subdir=IkiWiki::basename($dir)."/".$subdir;
761 $dir=IkiWiki::dirname($dir);
763 error("cannot determine root of git repo");
767 $ret=[$subdir, $dir];
773 sub git_parse_changes {
774 my $reverted = shift;
777 my ($subdir, $rootdir) = git_find_root();
779 foreach my $ci (@changes) {
780 foreach my $detail (@{ $ci->{'details'} }) {
781 my $file = $detail->{'file'};
783 # check that all changed files are in the subdir
784 if (length $subdir &&
785 ! ($file =~ s/^\Q$subdir\E//)) {
786 error sprintf(gettext("you are not allowed to change %s"), $file);
789 my ($action, $mode, $path);
790 if ($detail->{'status'} =~ /^[M]+\d*$/) {
792 $mode=$detail->{'mode_to'};
794 elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
795 $action= $reverted ? "remove" : "add";
796 $mode=$detail->{'mode_to'};
798 elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
799 $action= $reverted ? "add" : "remove";
800 $mode=$detail->{'mode_from'};
803 error "unknown status ".$detail->{'status'};
806 # test that the file mode is ok
807 if ($mode !~ /^100[64][64][64]$/) {
808 error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
810 if ($action eq "change") {
811 if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
812 error gettext("you are not allowed to change file modes");
816 # extract attachment to temp file
817 if (($action eq 'add' || $action eq 'change') &&
819 eval q{use File::Temp};
822 ($fh, $path)=File::Temp::tempfile(undef, UNLINK => 1);
823 my $cmd = "cd $git_dir && ".
824 "git show $detail->{sha1_to} > '$path'";
825 if (system($cmd) != 0) {
826 error("failed writing temp file '$path'.");
845 my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
847 # only allow changes to gitmaster_branch
848 if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
849 error sprintf(gettext("you are not allowed to change %s"), $refname);
852 # Avoid chdir when running git here, because the changes
853 # are in the master git repo, not the srcdir repo.
854 # (Also, if a subdir is involved, we don't want to chdir to
855 # it and only see changes in it.)
856 # The pre-receive hook already puts us in the right place.
857 in_git_dir(".", sub {
858 push @rets, git_parse_changes(0, git_commit_info($oldrev."..".$newrev));
862 return reverse @rets;
865 sub rcs_preprevert ($) {
867 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
869 # Examine changes from root of git repo, not from any subdir,
870 # in order to see all changes.
871 my ($subdir, $rootdir) = git_find_root();
872 in_git_dir($rootdir, sub {
873 my @commits=git_commit_info($sha1, 1);
876 error "unknown commit"; # just in case
879 # git revert will fail on merge commits. Add a nice message.
880 if (exists $commits[0]->{parents} &&
881 @{$commits[0]->{parents}} > 1) {
882 error gettext("you are not allowed to revert a merge");
885 git_parse_changes(1, @commits);
890 # Try to revert the given rev; returns undef on _success_.
892 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
894 if (run_or_non('git', 'revert', '--no-commit', $sha1)) {
898 run_or_die('git', 'reset', '--hard');
899 return sprintf(gettext("Failed to revert commit %s"), $sha1);