2 package IkiWiki::Plugin::git;
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
16 hook(type => "checkconfig", id => "git", call => \&checkconfig);
17 hook(type => "getsetup", id => "git", call => \&getsetup);
18 hook(type => "genwrapper", id => "git", call => \&genwrapper);
19 hook(type => "rcs", id => "rcs_update", call => \&rcs_update);
20 hook(type => "rcs", id => "rcs_prepedit", call => \&rcs_prepedit);
21 hook(type => "rcs", id => "rcs_commit", call => \&rcs_commit);
22 hook(type => "rcs", id => "rcs_commit_staged", call => \&rcs_commit_staged);
23 hook(type => "rcs", id => "rcs_add", call => \&rcs_add);
24 hook(type => "rcs", id => "rcs_remove", call => \&rcs_remove);
25 hook(type => "rcs", id => "rcs_rename", call => \&rcs_rename);
26 hook(type => "rcs", id => "rcs_recentchanges", call => \&rcs_recentchanges);
27 hook(type => "rcs", id => "rcs_diff", call => \&rcs_diff);
28 hook(type => "rcs", id => "rcs_getctime", call => \&rcs_getctime);
29 hook(type => "rcs", id => "rcs_getmtime", call => \&rcs_getmtime);
30 hook(type => "rcs", id => "rcs_receive", call => \&rcs_receive);
31 hook(type => "rcs", id => "rcs_preprevert", call => \&rcs_preprevert);
32 hook(type => "rcs", id => "rcs_revert", call => \&rcs_revert);
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 to /bin/sh.
157 # Returns command output (in list content) or success state
158 # (in scalar context), or runs the specified data handler.
160 my ($error_handler, $data_handler, @cmdline) = @_;
162 my $pid = open my $OUT, "-|";
164 error("Cannot fork: $!") if !defined $pid;
168 # Git commands want to be in wc.
169 if (! defined $git_dir) {
170 chdir $config{srcdir}
171 or error("cannot chdir to $config{srcdir}: $!");
175 or error("cannot chdir to $git_dir: $!");
177 exec @cmdline or error("Cannot exec '@cmdline': $!");
181 # git output is probably utf-8 encoded, but may contain
182 # other encodings or invalidly encoded stuff. So do not rely
183 # on the normal utf-8 IO layer, decode it by hand.
188 $_=decode_utf8($_, 0);
192 if (! defined $data_handler) {
196 last unless $data_handler->($_);
202 $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
204 return wantarray ? @lines : ($? == 0);
206 # Convenient wrappers.
207 sub run_or_die ($@) { safe_git(\&error, undef, @_) }
208 sub run_or_cry ($@) { safe_git(sub { warn @_ }, undef, @_) }
209 sub run_or_non ($@) { safe_git(undef, undef, @_) }
212 sub merge_past ($$$) {
213 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
214 # Git merge commands work with the committed changes, except in the
215 # implicit case of '-m' of git checkout(1). So we should invent a
216 # kludge here. In principle, we need to create a throw-away branch
217 # in preparing for the merge itself. Since branches are cheap (and
218 # branching is fast), this shouldn't cost high.
220 # The main problem is the presence of _uncommitted_ local changes. One
221 # possible approach to get rid of this situation could be that we first
222 # make a temporary commit in the master branch and later restore the
223 # initial state (this is possible since Git has the ability to undo a
224 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
227 # - create a diff of HEAD:current-sha1
229 # - create a dummy branch and switch to it
230 # - rewind to past (reset --hard to the current-sha1)
231 # - apply the diff and commit
232 # - switch to master and do the merge with the dummy branch
233 # - make a soft reset (undo the last commit of master)
235 # The above method has some drawbacks: (1) it needs a redundant commit
236 # just to get rid of local changes, (2) somewhat slow because of the
237 # required system forks. Until someone points a more straight method
238 # (which I would be grateful) I have implemented an alternative method.
239 # In this approach, we hide all the modified files from Git by renaming
240 # them (using the 'rename' builtin) and later restore those files in
241 # the throw-away branch (that is, we put the files themselves instead
242 # of applying a patch).
244 my ($sha1, $file, $message) = @_;
246 my @undo; # undo stack for cleanup in case of an error
247 my $conflict; # file content with conflict markers
250 # Hide local changes from Git by renaming the modified file.
251 # Relative paths must be converted to absolute for renaming.
252 my ($target, $hidden) = (
253 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
255 rename($target, $hidden)
256 or error("rename '$target' to '$hidden' failed: $!");
257 # Ensure to restore the renamed file on error.
259 return if ! -e "$hidden"; # already renamed
260 rename($hidden, $target)
261 or warn "rename '$hidden' to '$target' failed: $!";
264 my $branch = "throw_away_${sha1}"; # supposed to be unique
266 # Create a throw-away branch and rewind backward.
267 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
268 run_or_die('git', 'branch', $branch, $sha1);
270 # Switch to throw-away branch for the merge operation.
272 if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
273 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
276 run_or_die('git', 'checkout', $branch);
278 # Put the modified file in _this_ branch.
279 rename($hidden, $target)
280 or error("rename '$hidden' to '$target' failed: $!");
282 # _Silently_ commit all modifications in the current branch.
283 run_or_non('git', 'commit', '-m', $message, '-a');
284 # ... and re-switch to master.
285 run_or_die('git', 'checkout', $config{gitmaster_branch});
287 # Attempt to merge without complaining.
288 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
289 $conflict = readfile($target);
290 run_or_die('git', 'reset', '--hard');
295 # Process undo stack (in reverse order). By policy cleanup
296 # actions should normally print a warning on failure.
297 while (my $handle = pop @undo) {
301 error("Git merge failed!\n$failure\n") if $failure;
308 sub decode_git_file ($) {
311 # git does not output utf-8 filenames, but instead
312 # double-quotes them with the utf-8 characters
313 # escaped as \nnn\nnn.
314 if ($file =~ m/^"(.*)"$/) {
315 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
318 # strip prefix if in a subdir
319 if (! defined $prefix) {
320 ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
321 if (! defined $prefix) {
325 $file =~ s/^\Q$prefix\E//;
327 return decode("utf8", $file);
331 sub parse_diff_tree ($) {
332 # Parse the raw diff tree chunk and return the info hash.
333 # See git-diff-tree(1) for the syntax.
337 return if !defined @{ $dt_ref } ||
338 !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
342 while (my $line = shift @{ $dt_ref }) {
343 return if $line !~ m/^(.+) ($sha1_pattern)/;
350 # Identification lines for the commit.
351 while (my $line = shift @{ $dt_ref }) {
352 # Regexps are semi-stolen from gitweb.cgi.
353 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
356 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
357 # XXX: collecting in reverse order
358 push @{ $ci{'parents'} }, $1;
360 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
361 my ($who, $name, $epoch, $tz) =
365 $ci{ "${who}_epoch" } = $epoch;
366 $ci{ "${who}_tz" } = $tz;
368 if ($name =~ m/^([^<]+)\s+<([^@>]+)/) {
369 $ci{"${who}_name"} = $1;
370 $ci{"${who}_username"} = $2;
372 elsif ($name =~ m/^([^<]+)\s+<>$/) {
373 $ci{"${who}_username"} = $1;
376 $ci{"${who}_username"} = $name;
379 elsif ($line =~ m/^$/) {
380 # Trailing empty line signals next section.
385 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
387 if (defined $ci{'parents'}) {
388 $ci{'parent'} = @{ $ci{'parents'} }[0];
391 $ci{'parent'} = 0 x 40;
394 # Commit message (optional).
395 while ($dt_ref->[0] =~ /^ /) {
396 my $line = shift @{ $dt_ref };
398 push @{ $ci{'comment'} }, $line;
400 shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
403 while (my $line = shift @{ $dt_ref }) {
405 (:+) # number of parents
406 ([^\t]+)\t # modes, sha1, status
409 my $num_parents = length $1;
410 my @tmp = split(" ", $2);
411 my ($file, $file_to) = split("\t", $3);
412 my @mode_from = splice(@tmp, 0, $num_parents);
413 my $mode_to = shift(@tmp);
414 my @sha1_from = splice(@tmp, 0, $num_parents);
415 my $sha1_to = shift(@tmp);
416 my $status = shift(@tmp);
419 push @{ $ci{'details'} }, {
420 'file' => decode_git_file($file),
421 'sha1_from' => $sha1_from[0],
422 'sha1_to' => $sha1_to,
423 'mode_from' => $mode_from[0],
424 'mode_to' => $mode_to,
436 sub git_commit_info ($;$) {
437 # Return an array of commit info hashes of num commits
438 # starting from the given sha1sum.
439 my ($sha1, $num) = @_;
442 push @opts, "--max-count=$num" if defined $num;
444 my @raw_lines = run_or_die('git', 'log', @opts,
445 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
446 '-r', $sha1, '--', '.');
449 while (my $parsed = parse_diff_tree(\@raw_lines)) {
453 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
455 return wantarray ? @ci : $ci[0];
459 # Return head sha1sum (of given file).
460 my $file = shift || q{--};
462 # Ignore error since a non-existing file might be given.
463 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
466 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
469 debug("Empty sha1sum for '$file'.");
471 return defined $sha1 ? $sha1 : q{};
475 # Update working directory.
477 if (length $config{gitorigin_branch}) {
478 run_or_cry('git', 'pull', '--prune', $config{gitorigin_branch});
482 sub rcs_prepedit ($) {
483 # Return the commit sha1sum of the file when editing begins.
484 # This will be later used in rcs_commit if a merge is required.
487 return git_sha1($file);
491 # Try to commit the page; returns undef on _success_ and
492 # a version of the page with the rcs's conflict markers on
496 # Check to see if the page has been changed by someone else since
497 # rcs_prepedit was called.
498 my $cur = git_sha1($params{file});
499 my ($prev) = $params{token} =~ /^($sha1_pattern)$/; # untaint
501 if (defined $cur && defined $prev && $cur ne $prev) {
502 my $conflict = merge_past($prev, $params{file}, $dummy_commit_msg);
503 return $conflict if defined $conflict;
506 return rcs_commit_helper(@_);
509 sub rcs_commit_staged (@) {
510 # Commits all staged changes. Changes can be staged using rcs_add,
511 # rcs_remove, and rcs_rename.
512 return rcs_commit_helper(@_);
515 sub rcs_commit_helper (@) {
520 if (defined $params{session}) {
521 # Set the commit author and email based on web session info.
523 if (defined $params{session}->param("name")) {
524 $u=$params{session}->param("name");
526 elsif (defined $params{session}->remote_addr()) {
527 $u=$params{session}->remote_addr();
531 # MITLOGIN This algorithm could be improved
532 $ENV{GIT_AUTHOR_NAME}=IkiWiki::userinfo_get($u, "realname");
534 if (defined $params{session}->param("nickname")) {
535 $u=encode_utf8($params{session}->param("nickname"));
537 $u=~s/[^-_0-9[:alnum:]]+//g;
540 $ENV{GIT_AUTHOR_EMAIL}="$u\@mit.edu";
544 $params{message} = IkiWiki::possibly_foolish_untaint($params{message});
546 if ($params{message} !~ /\S/) {
547 # Force git to allow empty commit messages.
548 # (If this version of git supports it.)
549 my ($version)=`git --version` =~ /git version (.*)/;
550 if ($version ge "1.5.4") {
551 push @opts, '--cleanup=verbatim';
554 $params{message}.=".";
557 if (exists $params{file}) {
558 push @opts, '--', $params{file};
560 # git commit returns non-zero if nothing really changed.
561 # So we should ignore its exit status (hence run_or_non).
562 if (run_or_non('git', 'commit', '-m', $params{message}, '-q', @opts)) {
563 if (length $config{gitorigin_branch}) {
564 run_or_cry('git', 'push', $config{gitorigin_branch});
569 return undef; # success
573 # Add file to archive.
577 run_or_cry('git', 'add', $file);
581 # Remove file from archive.
585 run_or_cry('git', 'rm', '-f', $file);
588 sub rcs_rename ($$) {
589 my ($src, $dest) = @_;
591 run_or_cry('git', 'mv', '-f', $src, $dest);
594 sub rcs_recentchanges ($) {
595 # List of recent changes.
599 eval q{use Date::Parse};
603 foreach my $ci (git_commit_info('HEAD', $num || 1)) {
604 # Skip redundant commits.
605 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
607 my ($sha1, $when) = (
609 $ci->{'author_epoch'}
613 foreach my $detail (@{ $ci->{'details'} }) {
614 my $file = $detail->{'file'};
616 my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
617 $diffurl =~ s/\[\[file\]\]/$file/go;
618 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
619 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
620 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
621 $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
624 page => pagename($file),
631 foreach my $line (@{$ci->{'comment'}}) {
632 $pastblank=1 if $line eq '';
633 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
634 push @messages, { line => $line };
637 my $user=$ci->{'author_username'};
638 my $web_commit = ($ci->{'author'} =~ /\@web>/);
641 # Set nickname only if a non-url author_username is available,
642 # and author_name is an url.
643 if ($user !~ /:\/\// && defined $ci->{'author_name'} &&
644 $ci->{'author_name'} =~ /:\/\//) {
646 $user=$ci->{'author_name'};
649 # compatability code for old web commit messages
651 defined $messages[0] &&
652 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
653 $user = defined $2 ? "$2" : "$3";
654 $messages[0]->{line} = $4;
661 nickname => $nickname,
662 committype => $web_commit ? "web" : "git",
664 message => [@messages],
668 last if @rets >= $num;
677 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
681 return if defined $maxlines && @lines == $maxlines;
682 push @lines, $line."\n"
683 if (@lines || $line=~/^diff --git/);
686 safe_git(undef, $addlines, "git", "show", $sha1);
691 return join("", @lines);
700 my $id=shift; # 0 = mtime ; 1 = ctime
702 if (! keys %time_cache) {
704 foreach my $line (run_or_die('git', 'log',
705 '--pretty=format:%at',
706 '--name-only', '--relative')) {
707 if (! defined $date && $line =~ /^(\d+)$/) {
710 elsif (! length $line) {
714 my $f=decode_git_file($line);
716 if (! $time_cache{$f}) {
717 $time_cache{$f}[0]=$date; # mtime
719 $time_cache{$f}[1]=$date; # ctime
724 return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
729 sub rcs_getctime ($) {
732 return findtimes($file, 1);
735 sub rcs_getmtime ($) {
738 return findtimes($file, 0);
744 # The wiki may not be the only thing in the git repo.
745 # Determine if it is in a subdirectory by examining the srcdir,
746 # and its parents, looking for the .git directory.
748 return @$ret if defined $ret;
751 my $dir=$config{srcdir};
752 while (! -d "$dir/.git") {
753 $subdir=IkiWiki::basename($dir)."/".$subdir;
754 $dir=IkiWiki::dirname($dir);
756 error("cannot determine root of git repo");
760 $ret=[$subdir, $dir];
766 sub git_parse_changes {
767 my $reverted = shift;
770 my ($subdir, $rootdir) = git_find_root();
772 foreach my $ci (@changes) {
773 foreach my $detail (@{ $ci->{'details'} }) {
774 my $file = $detail->{'file'};
776 # check that all changed files are in the subdir
777 if (length $subdir &&
778 ! ($file =~ s/^\Q$subdir\E//)) {
779 error sprintf(gettext("you are not allowed to change %s"), $file);
782 my ($action, $mode, $path);
783 if ($detail->{'status'} =~ /^[M]+\d*$/) {
785 $mode=$detail->{'mode_to'};
787 elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
788 $action= $reverted ? "remove" : "add";
789 $mode=$detail->{'mode_to'};
791 elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
792 $action= $reverted ? "add" : "remove";
793 $mode=$detail->{'mode_from'};
796 error "unknown status ".$detail->{'status'};
799 # test that the file mode is ok
800 if ($mode !~ /^100[64][64][64]$/) {
801 error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
803 if ($action eq "change") {
804 if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
805 error gettext("you are not allowed to change file modes");
809 # extract attachment to temp file
810 if (($action eq 'add' || $action eq 'change') &&
812 eval q{use File::Temp};
815 ($fh, $path)=File::Temp::tempfile(undef, UNLINK => 1);
816 my $cmd = "cd $git_dir && ".
817 "git show $detail->{sha1_to} > '$path'";
818 if (system($cmd) != 0) {
819 error("failed writing temp file '$path'.");
838 my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
840 # only allow changes to gitmaster_branch
841 if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
842 error sprintf(gettext("you are not allowed to change %s"), $refname);
845 # Avoid chdir when running git here, because the changes
846 # are in the master git repo, not the srcdir repo.
847 # (Also, if a subdir is involved, we don't want to chdir to
848 # it and only see changes in it.)
849 # The pre-receive hook already puts us in the right place.
851 push @rets, git_parse_changes(0, git_commit_info($oldrev."..".$newrev));
855 return reverse @rets;
858 sub rcs_preprevert ($) {
860 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
862 # Examine changes from root of git repo, not from any subdir,
863 # in order to see all changes.
864 my ($subdir, $rootdir) = git_find_root();
867 my @commits=git_commit_info($sha1, 1);
869 error "unknown commit"; # just in case
872 # git revert will fail on merge commits. Add a nice message.
873 if (exists $commits[0]->{parents} &&
874 @{$commits[0]->{parents}} > 1) {
875 error gettext("you are not allowed to revert a merge");
878 my @ret=git_parse_changes(1, @commits);
885 # Try to revert the given rev; returns undef on _success_.
887 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
889 if (run_or_non('git', 'revert', '--no-commit', $sha1)) {
893 run_or_die('git', 'reset', '--hard');
894 return sprintf(gettext("Failed to revert commit %s"), $sha1);