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);
32 hook(type => "rcs", id => "rcs_find_changes", call => \&rcs_find_changes);
33 hook(type => "rcs", id => "rcs_get_current_rev", call => \&rcs_get_current_rev);
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();
159 sub in_git_dir ($$) {
168 # Start a child process safely without resorting to /bin/sh.
169 # Returns command output (in list content) or success state
170 # (in scalar context), or runs the specified data handler.
172 my ($error_handler, $data_handler, @cmdline) = @_;
174 my $pid = open my $OUT, "-|";
176 error("Cannot fork: $!") if !defined $pid;
180 # Git commands want to be in wc.
181 if (! defined $git_dir) {
182 chdir $config{srcdir}
183 or error("cannot chdir to $config{srcdir}: $!");
187 or error("cannot chdir to $git_dir: $!");
189 exec @cmdline or error("Cannot exec '@cmdline': $!");
193 # git output is probably utf-8 encoded, but may contain
194 # other encodings or invalidly encoded stuff. So do not rely
195 # on the normal utf-8 IO layer, decode it by hand.
200 $_=decode_utf8($_, 0);
204 if (! defined $data_handler) {
208 last unless $data_handler->($_);
214 $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
216 return wantarray ? @lines : ($? == 0);
218 # Convenient wrappers.
219 sub run_or_die ($@) { safe_git(\&error, undef, @_) }
220 sub run_or_cry ($@) { safe_git(sub { warn @_ }, undef, @_) }
221 sub run_or_non ($@) { safe_git(undef, undef, @_) }
224 sub merge_past ($$$) {
225 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
226 # Git merge commands work with the committed changes, except in the
227 # implicit case of '-m' of git checkout(1). So we should invent a
228 # kludge here. In principle, we need to create a throw-away branch
229 # in preparing for the merge itself. Since branches are cheap (and
230 # branching is fast), this shouldn't cost high.
232 # The main problem is the presence of _uncommitted_ local changes. One
233 # possible approach to get rid of this situation could be that we first
234 # make a temporary commit in the master branch and later restore the
235 # initial state (this is possible since Git has the ability to undo a
236 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
239 # - create a diff of HEAD:current-sha1
241 # - create a dummy branch and switch to it
242 # - rewind to past (reset --hard to the current-sha1)
243 # - apply the diff and commit
244 # - switch to master and do the merge with the dummy branch
245 # - make a soft reset (undo the last commit of master)
247 # The above method has some drawbacks: (1) it needs a redundant commit
248 # just to get rid of local changes, (2) somewhat slow because of the
249 # required system forks. Until someone points a more straight method
250 # (which I would be grateful) I have implemented an alternative method.
251 # In this approach, we hide all the modified files from Git by renaming
252 # them (using the 'rename' builtin) and later restore those files in
253 # the throw-away branch (that is, we put the files themselves instead
254 # of applying a patch).
256 my ($sha1, $file, $message) = @_;
258 my @undo; # undo stack for cleanup in case of an error
259 my $conflict; # file content with conflict markers
262 # Hide local changes from Git by renaming the modified file.
263 # Relative paths must be converted to absolute for renaming.
264 my ($target, $hidden) = (
265 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
267 rename($target, $hidden)
268 or error("rename '$target' to '$hidden' failed: $!");
269 # Ensure to restore the renamed file on error.
271 return if ! -e "$hidden"; # already renamed
272 rename($hidden, $target)
273 or warn "rename '$hidden' to '$target' failed: $!";
276 my $branch = "throw_away_${sha1}"; # supposed to be unique
278 # Create a throw-away branch and rewind backward.
279 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
280 run_or_die('git', 'branch', $branch, $sha1);
282 # Switch to throw-away branch for the merge operation.
284 if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
285 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
288 run_or_die('git', 'checkout', $branch);
290 # Put the modified file in _this_ branch.
291 rename($hidden, $target)
292 or error("rename '$hidden' to '$target' failed: $!");
294 # _Silently_ commit all modifications in the current branch.
295 run_or_non('git', 'commit', '-m', $message, '-a');
296 # ... and re-switch to master.
297 run_or_die('git', 'checkout', $config{gitmaster_branch});
299 # Attempt to merge without complaining.
300 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
301 $conflict = readfile($target);
302 run_or_die('git', 'reset', '--hard');
307 # Process undo stack (in reverse order). By policy cleanup
308 # actions should normally print a warning on failure.
309 while (my $handle = pop @undo) {
313 error("Git merge failed!\n$failure\n") if $failure;
318 sub decode_git_file ($) {
321 # git does not output utf-8 filenames, but instead
322 # double-quotes them with the utf-8 characters
323 # escaped as \nnn\nnn.
324 if ($file =~ m/^"(.*)"$/) {
325 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
328 # strip prefix if in a subdir
329 if (! defined $prefix) {
330 ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
331 if (! defined $prefix) {
335 $file =~ s/^\Q$prefix\E//;
337 return decode("utf8", $file);
340 sub parse_diff_tree ($) {
341 # Parse the raw diff tree chunk and return the info hash.
342 # See git-diff-tree(1) for the syntax.
346 return if ! @{ $dt_ref } ||
347 !defined $dt_ref->[0] || !length $dt_ref->[0];
351 while (my $line = shift @{ $dt_ref }) {
352 return if $line !~ m/^(.+) ($sha1_pattern)/;
359 # Identification lines for the commit.
360 while (my $line = shift @{ $dt_ref }) {
361 # Regexps are semi-stolen from gitweb.cgi.
362 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
365 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
366 # XXX: collecting in reverse order
367 push @{ $ci{'parents'} }, $1;
369 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
370 my ($who, $name, $epoch, $tz) =
374 $ci{ "${who}_epoch" } = $epoch;
375 $ci{ "${who}_tz" } = $tz;
377 if ($name =~ m/^([^<]+)\s+<([^@>]+)/) {
378 $ci{"${who}_name"} = $1;
379 $ci{"${who}_username"} = $2;
381 elsif ($name =~ m/^([^<]+)\s+<>$/) {
382 $ci{"${who}_username"} = $1;
385 $ci{"${who}_username"} = $name;
388 elsif ($line =~ m/^$/) {
389 # Trailing empty line signals next section.
394 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
396 if (defined $ci{'parents'}) {
397 $ci{'parent'} = @{ $ci{'parents'} }[0];
400 $ci{'parent'} = 0 x 40;
403 # Commit message (optional).
404 while ($dt_ref->[0] =~ /^ /) {
405 my $line = shift @{ $dt_ref };
407 push @{ $ci{'comment'} }, $line;
409 shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
412 while (my $line = shift @{ $dt_ref }) {
414 (:+) # number of parents
415 ([^\t]+)\t # modes, sha1, status
418 my $num_parents = length $1;
419 my @tmp = split(" ", $2);
420 my ($file, $file_to) = split("\t", $3);
421 my @mode_from = splice(@tmp, 0, $num_parents);
422 my $mode_to = shift(@tmp);
423 my @sha1_from = splice(@tmp, 0, $num_parents);
424 my $sha1_to = shift(@tmp);
425 my $status = shift(@tmp);
428 push @{ $ci{'details'} }, {
429 'file' => decode_git_file($file),
430 'sha1_from' => $sha1_from[0],
431 'sha1_to' => $sha1_to,
432 'mode_from' => $mode_from[0],
433 'mode_to' => $mode_to,
445 sub git_commit_info ($;$) {
446 # Return an array of commit info hashes of num commits
447 # starting from the given sha1sum.
448 my ($sha1, $num) = @_;
451 push @opts, "--max-count=$num" if defined $num;
453 my @raw_lines = run_or_die('git', 'log', @opts,
454 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
455 '-r', $sha1, '--', '.');
458 while (my $parsed = parse_diff_tree(\@raw_lines)) {
462 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
464 return wantarray ? @ci : $ci[0];
467 sub rcs_find_changes ($) {
470 my @raw_lines = run_or_die('git', 'log',
471 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
472 '--no-renames', , '--reverse',
473 '-r', "$oldrev..HEAD", '--', '.');
475 # Due to --reverse, we see changes in chronological order.
478 my $nullsha = 0 x 40;
480 while (my $ci = parse_diff_tree(\@raw_lines)) {
482 foreach my $i (@{$ci->{details}}) {
484 if ($i->{sha1_to} eq $nullsha) {
485 delete $changed{$file};
489 delete $deleted{$file};
495 return (\%changed, \%deleted, $newrev);
498 sub git_sha1_file ($) {
500 git_sha1("--", $file);
504 # Ignore error since a non-existing file might be given.
505 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
508 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
510 return defined $sha1 ? $sha1 : '';
513 sub rcs_get_current_rev () {
518 # Update working directory.
520 if (length $config{gitorigin_branch}) {
521 run_or_cry('git', 'pull', '--prune', $config{gitorigin_branch});
525 sub rcs_prepedit ($) {
526 # Return the commit sha1sum of the file when editing begins.
527 # This will be later used in rcs_commit if a merge is required.
530 return git_sha1_file($file);
534 # Try to commit the page; returns undef on _success_ and
535 # a version of the page with the rcs's conflict markers on
539 # Check to see if the page has been changed by someone else since
540 # rcs_prepedit was called.
541 my $cur = git_sha1_file($params{file});
542 my ($prev) = $params{token} =~ /^($sha1_pattern)$/; # untaint
544 if (defined $cur && defined $prev && $cur ne $prev) {
545 my $conflict = merge_past($prev, $params{file}, $dummy_commit_msg);
546 return $conflict if defined $conflict;
549 return rcs_commit_helper(@_);
552 sub rcs_commit_staged (@) {
553 # Commits all staged changes. Changes can be staged using rcs_add,
554 # rcs_remove, and rcs_rename.
555 return rcs_commit_helper(@_);
558 sub rcs_commit_helper (@) {
563 if (defined $params{session}) {
564 # Set the commit author and email based on web session info.
566 if (defined $params{session}->param("name")) {
567 $u=$params{session}->param("name");
569 elsif (defined $params{session}->remote_addr()) {
570 $u=$params{session}->remote_addr();
574 $ENV{GIT_AUTHOR_NAME}=$u;
576 if (defined $params{session}->param("nickname")) {
577 $u=encode_utf8($params{session}->param("nickname"));
579 $u=~s/[^-_0-9[:alnum:]]+//g;
582 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
586 $params{message} = IkiWiki::possibly_foolish_untaint($params{message});
588 if ($params{message} !~ /\S/) {
589 # Force git to allow empty commit messages.
590 # (If this version of git supports it.)
591 my ($version)=`git --version` =~ /git version (.*)/;
592 if ($version ge "1.7.8") {
593 push @opts, "--allow-empty-message", "--no-edit";
595 if ($version ge "1.7.2") {
596 push @opts, "--allow-empty-message";
598 elsif ($version ge "1.5.4") {
599 push @opts, '--cleanup=verbatim';
602 $params{message}.=".";
605 if (exists $params{file}) {
606 push @opts, '--', $params{file};
608 # git commit returns non-zero if nothing really changed.
609 # So we should ignore its exit status (hence run_or_non).
610 if (run_or_non('git', 'commit', '-m', $params{message}, '-q', @opts)) {
611 if (length $config{gitorigin_branch}) {
612 run_or_cry('git', 'push', $config{gitorigin_branch}, $config{gitmaster_branch});
617 return undef; # success
621 # Add file to archive.
625 run_or_cry('git', 'add', $file);
629 # Remove file from archive.
633 run_or_cry('git', 'rm', '-f', $file);
636 sub rcs_rename ($$) {
637 my ($src, $dest) = @_;
639 run_or_cry('git', 'mv', '-f', $src, $dest);
642 sub rcs_recentchanges ($) {
643 # List of recent changes.
647 eval q{use Date::Parse};
651 foreach my $ci (git_commit_info('HEAD', $num || 1)) {
652 # Skip redundant commits.
653 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
655 my ($sha1, $when) = (
657 $ci->{'author_epoch'}
661 foreach my $detail (@{ $ci->{'details'} }) {
662 my $file = $detail->{'file'};
663 my $efile = join('/',
664 map { uri_escape_utf8($_) } split('/', $file)
667 my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
668 $diffurl =~ s/\[\[file\]\]/$efile/go;
669 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
670 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
671 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
672 $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
675 page => pagename($file),
682 foreach my $line (@{$ci->{'comment'}}) {
683 $pastblank=1 if $line eq '';
684 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
685 push @messages, { line => $line };
688 my $user=$ci->{'author_username'};
689 my $web_commit = ($ci->{'author'} =~ /\@web>/);
692 # Set nickname only if a non-url author_username is available,
693 # and author_name is an url.
694 if ($user !~ /:\/\// && defined $ci->{'author_name'} &&
695 $ci->{'author_name'} =~ /:\/\//) {
697 $user=$ci->{'author_name'};
700 # compatability code for old web commit messages
702 defined $messages[0] &&
703 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
704 $user = defined $2 ? "$2" : "$3";
705 $messages[0]->{line} = $4;
712 nickname => $nickname,
713 committype => $web_commit ? "web" : "git",
715 message => [@messages],
719 last if @rets >= $num;
728 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
732 return if defined $maxlines && @lines == $maxlines;
733 push @lines, $line."\n"
734 if (@lines || $line=~/^diff --git/);
737 safe_git(undef, $addlines, "git", "show", $sha1);
742 return join("", @lines);
751 my $id=shift; # 0 = mtime ; 1 = ctime
753 if (! keys %time_cache) {
755 foreach my $line (run_or_die('git', 'log',
756 '--pretty=format:%at',
757 '--name-only', '--relative')) {
758 if (! defined $date && $line =~ /^(\d+)$/) {
761 elsif (! length $line) {
765 my $f=decode_git_file($line);
767 if (! $time_cache{$f}) {
768 $time_cache{$f}[0]=$date; # mtime
770 $time_cache{$f}[1]=$date; # ctime
775 return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
780 sub rcs_getctime ($) {
783 return findtimes($file, 1);
786 sub rcs_getmtime ($) {
789 return findtimes($file, 0);
795 # The wiki may not be the only thing in the git repo.
796 # Determine if it is in a subdirectory by examining the srcdir,
797 # and its parents, looking for the .git directory.
799 return @$ret if defined $ret;
802 my $dir=$config{srcdir};
803 while (! -d "$dir/.git") {
804 $subdir=IkiWiki::basename($dir)."/".$subdir;
805 $dir=IkiWiki::dirname($dir);
807 error("cannot determine root of git repo");
811 $ret=[$subdir, $dir];
817 sub git_parse_changes {
818 my $reverted = shift;
821 my ($subdir, $rootdir) = git_find_root();
823 foreach my $ci (@changes) {
824 foreach my $detail (@{ $ci->{'details'} }) {
825 my $file = $detail->{'file'};
827 # check that all changed files are in the subdir
828 if (length $subdir &&
829 ! ($file =~ s/^\Q$subdir\E//)) {
830 error sprintf(gettext("you are not allowed to change %s"), $file);
833 my ($action, $mode, $path);
834 if ($detail->{'status'} =~ /^[M]+\d*$/) {
836 $mode=$detail->{'mode_to'};
838 elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
839 $action= $reverted ? "remove" : "add";
840 $mode=$detail->{'mode_to'};
842 elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
843 $action= $reverted ? "add" : "remove";
844 $mode=$detail->{'mode_from'};
847 error "unknown status ".$detail->{'status'};
850 # test that the file mode is ok
851 if ($mode !~ /^100[64][64][64]$/) {
852 error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
854 if ($action eq "change") {
855 if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
856 error gettext("you are not allowed to change file modes");
860 # extract attachment to temp file
861 if (($action eq 'add' || $action eq 'change') &&
863 eval q{use File::Temp};
866 ($fh, $path)=File::Temp::tempfile(undef, UNLINK => 1);
867 my $cmd = "cd $git_dir && ".
868 "git show $detail->{sha1_to} > '$path'";
869 if (system($cmd) != 0) {
870 error("failed writing temp file '$path'.");
889 my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
891 # only allow changes to gitmaster_branch
892 if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
893 error sprintf(gettext("you are not allowed to change %s"), $refname);
896 # Avoid chdir when running git here, because the changes
897 # are in the master git repo, not the srcdir repo.
898 # (Also, if a subdir is involved, we don't want to chdir to
899 # it and only see changes in it.)
900 # The pre-receive hook already puts us in the right place.
901 in_git_dir(".", sub {
902 push @rets, git_parse_changes(0, git_commit_info($oldrev."..".$newrev));
906 return reverse @rets;
909 sub rcs_preprevert ($) {
911 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
913 # Examine changes from root of git repo, not from any subdir,
914 # in order to see all changes.
915 my ($subdir, $rootdir) = git_find_root();
916 in_git_dir($rootdir, sub {
917 my @commits=git_commit_info($sha1, 1);
920 error "unknown commit"; # just in case
923 # git revert will fail on merge commits. Add a nice message.
924 if (exists $commits[0]->{parents} &&
925 @{$commits[0]->{parents}} > 1) {
926 error gettext("you are not allowed to revert a merge");
929 git_parse_changes(1, @commits);
934 # Try to revert the given rev; returns undef on _success_.
936 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
938 if (run_or_non('git', 'revert', '--no-commit', $sha1)) {
942 run_or_die('git', 'reset', '--hard');
943 return sprintf(gettext("Failed to revert commit %s"), $sha1);