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
475 return defined $sha1 ? $sha1 : '';
479 # Update working directory.
481 if (length $config{gitorigin_branch}) {
482 run_or_cry('git', 'pull', '--prune', $config{gitorigin_branch});
486 sub rcs_prepedit ($) {
487 # Return the commit sha1sum of the file when editing begins.
488 # This will be later used in rcs_commit if a merge is required.
491 return git_sha1($file);
495 # Try to commit the page; returns undef on _success_ and
496 # a version of the page with the rcs's conflict markers on
500 # Check to see if the page has been changed by someone else since
501 # rcs_prepedit was called.
502 my $cur = git_sha1($params{file});
503 my ($prev) = $params{token} =~ /^($sha1_pattern)$/; # untaint
505 if (defined $cur && defined $prev && $cur ne $prev) {
506 my $conflict = merge_past($prev, $params{file}, $dummy_commit_msg);
507 return $conflict if defined $conflict;
510 return rcs_commit_helper(@_);
513 sub rcs_commit_staged (@) {
514 # Commits all staged changes. Changes can be staged using rcs_add,
515 # rcs_remove, and rcs_rename.
516 return rcs_commit_helper(@_);
519 sub rcs_commit_helper (@) {
524 if (defined $params{session}) {
525 # Set the commit author and email based on web session info.
527 if (defined $params{session}->param("name")) {
528 $u=$params{session}->param("name");
530 elsif (defined $params{session}->remote_addr()) {
531 $u=$params{session}->remote_addr();
535 $ENV{GIT_AUTHOR_NAME}=$u;
537 if (defined $params{session}->param("nickname")) {
538 $u=encode_utf8($params{session}->param("nickname"));
540 $u=~s/[^-_0-9[:alnum:]]+//g;
543 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
547 $params{message} = IkiWiki::possibly_foolish_untaint($params{message});
549 if ($params{message} !~ /\S/) {
550 # Force git to allow empty commit messages.
551 # (If this version of git supports it.)
552 my ($version)=`git --version` =~ /git version (.*)/;
553 if ($version ge "1.5.4") {
554 push @opts, '--cleanup=verbatim';
557 $params{message}.=".";
560 if (exists $params{file}) {
561 push @opts, '--', $params{file};
563 # git commit returns non-zero if nothing really changed.
564 # So we should ignore its exit status (hence run_or_non).
565 if (run_or_non('git', 'commit', '-m', $params{message}, '-q', @opts)) {
566 if (length $config{gitorigin_branch}) {
567 run_or_cry('git', 'push', $config{gitorigin_branch});
572 return undef; # success
576 # Add file to archive.
580 run_or_cry('git', 'add', $file);
584 # Remove file from archive.
588 run_or_cry('git', 'rm', '-f', $file);
591 sub rcs_rename ($$) {
592 my ($src, $dest) = @_;
594 run_or_cry('git', 'mv', '-f', $src, $dest);
597 sub rcs_recentchanges ($) {
598 # List of recent changes.
602 eval q{use Date::Parse};
606 foreach my $ci (git_commit_info('HEAD', $num || 1)) {
607 # Skip redundant commits.
608 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
610 my ($sha1, $when) = (
612 $ci->{'author_epoch'}
616 foreach my $detail (@{ $ci->{'details'} }) {
617 my $file = $detail->{'file'};
618 my $efile = uri_escape_utf8($file);
620 my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
621 $diffurl =~ s/\[\[file\]\]/$efile/go;
622 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
623 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
624 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
625 $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
628 page => pagename($file),
635 foreach my $line (@{$ci->{'comment'}}) {
636 $pastblank=1 if $line eq '';
637 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
638 push @messages, { line => $line };
641 my $user=$ci->{'author_username'};
642 my $web_commit = ($ci->{'author'} =~ /\@web>/);
645 # Set nickname only if a non-url author_username is available,
646 # and author_name is an url.
647 if ($user !~ /:\/\// && defined $ci->{'author_name'} &&
648 $ci->{'author_name'} =~ /:\/\//) {
650 $user=$ci->{'author_name'};
653 # compatability code for old web commit messages
655 defined $messages[0] &&
656 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
657 $user = defined $2 ? "$2" : "$3";
658 $messages[0]->{line} = $4;
665 nickname => $nickname,
666 committype => $web_commit ? "web" : "git",
668 message => [@messages],
672 last if @rets >= $num;
681 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
685 return if defined $maxlines && @lines == $maxlines;
686 push @lines, $line."\n"
687 if (@lines || $line=~/^diff --git/);
690 safe_git(undef, $addlines, "git", "show", $sha1);
695 return join("", @lines);
704 my $id=shift; # 0 = mtime ; 1 = ctime
706 if (! keys %time_cache) {
708 foreach my $line (run_or_die('git', 'log',
709 '--pretty=format:%at',
710 '--name-only', '--relative')) {
711 if (! defined $date && $line =~ /^(\d+)$/) {
714 elsif (! length $line) {
718 my $f=decode_git_file($line);
720 if (! $time_cache{$f}) {
721 $time_cache{$f}[0]=$date; # mtime
723 $time_cache{$f}[1]=$date; # ctime
728 return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
733 sub rcs_getctime ($) {
736 return findtimes($file, 1);
739 sub rcs_getmtime ($) {
742 return findtimes($file, 0);
748 # The wiki may not be the only thing in the git repo.
749 # Determine if it is in a subdirectory by examining the srcdir,
750 # and its parents, looking for the .git directory.
752 return @$ret if defined $ret;
755 my $dir=$config{srcdir};
756 while (! -d "$dir/.git") {
757 $subdir=IkiWiki::basename($dir)."/".$subdir;
758 $dir=IkiWiki::dirname($dir);
760 error("cannot determine root of git repo");
764 $ret=[$subdir, $dir];
770 sub git_parse_changes {
771 my $reverted = shift;
774 my ($subdir, $rootdir) = git_find_root();
776 foreach my $ci (@changes) {
777 foreach my $detail (@{ $ci->{'details'} }) {
778 my $file = $detail->{'file'};
780 # check that all changed files are in the subdir
781 if (length $subdir &&
782 ! ($file =~ s/^\Q$subdir\E//)) {
783 error sprintf(gettext("you are not allowed to change %s"), $file);
786 my ($action, $mode, $path);
787 if ($detail->{'status'} =~ /^[M]+\d*$/) {
789 $mode=$detail->{'mode_to'};
791 elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
792 $action= $reverted ? "remove" : "add";
793 $mode=$detail->{'mode_to'};
795 elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
796 $action= $reverted ? "add" : "remove";
797 $mode=$detail->{'mode_from'};
800 error "unknown status ".$detail->{'status'};
803 # test that the file mode is ok
804 if ($mode !~ /^100[64][64][64]$/) {
805 error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
807 if ($action eq "change") {
808 if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
809 error gettext("you are not allowed to change file modes");
813 # extract attachment to temp file
814 if (($action eq 'add' || $action eq 'change') &&
816 eval q{use File::Temp};
819 ($fh, $path)=File::Temp::tempfile(undef, UNLINK => 1);
820 my $cmd = "cd $git_dir && ".
821 "git show $detail->{sha1_to} > '$path'";
822 if (system($cmd) != 0) {
823 error("failed writing temp file '$path'.");
842 my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
844 # only allow changes to gitmaster_branch
845 if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
846 error sprintf(gettext("you are not allowed to change %s"), $refname);
849 # Avoid chdir when running git here, because the changes
850 # are in the master git repo, not the srcdir repo.
851 # (Also, if a subdir is involved, we don't want to chdir to
852 # it and only see changes in it.)
853 # The pre-receive hook already puts us in the right place.
854 in_git_dir(".", sub {
855 push @rets, git_parse_changes(0, git_commit_info($oldrev."..".$newrev));
859 return reverse @rets;
862 sub rcs_preprevert ($) {
864 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
866 # Examine changes from root of git repo, not from any subdir,
867 # in order to see all changes.
868 my ($subdir, $rootdir) = git_find_root();
869 in_git_dir($rootdir, sub {
870 my @commits=git_commit_info($sha1, 1);
873 error "unknown commit"; # just in case
876 # git revert will fail on merge commits. Add a nice message.
877 if (exists $commits[0]->{parents} &&
878 @{$commits[0]->{parents}} > 1) {
879 error gettext("you are not allowed to revert a merge");
882 git_parse_changes(1, @commits);
887 # Try to revert the given rev; returns undef on _success_.
889 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
891 if (run_or_non('git', 'revert', '--no-commit', $sha1)) {
895 run_or_die('git', 'reset', '--hard');
896 return sprintf(gettext("Failed to revert commit %s"), $sha1);