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
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);
33 if (! defined $config{gitorigin_branch}) {
34 $config{gitorigin_branch}="origin";
36 if (! defined $config{gitmaster_branch}) {
37 $config{gitmaster_branch}="master";
39 if (defined $config{git_wrapper} &&
40 length $config{git_wrapper}) {
41 push @{$config{wrappers}}, {
42 wrapper => $config{git_wrapper},
43 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
44 wrapper_background_command => $config{git_wrapper_background_command},
48 if (defined $config{git_test_receive_wrapper} &&
49 length $config{git_test_receive_wrapper} &&
50 defined $config{untrusted_committers} &&
51 @{$config{untrusted_committers}}) {
52 push @{$config{wrappers}}, {
54 wrapper => $config{git_test_receive_wrapper},
55 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
59 # Avoid notes, parser does not handle and they only slow things down.
60 $ENV{GIT_NOTES_REF}="";
62 # Run receive test only if being called by the wrapper, and not
63 # when generating same.
64 if ($config{test_receive} && ! exists $config{wrapper}) {
65 require IkiWiki::Receive;
66 IkiWiki::Receive::test();
73 safe => 0, # rcs plugin
79 example => "/git/wiki.git/hooks/post-update",
80 description => "git hook to generate",
84 git_wrapper_background_command => {
86 example => "git push github",
87 description => "shell command for git_wrapper to run, in the background",
94 description => "mode for git_wrapper (can safely be made suid)",
98 git_test_receive_wrapper => {
100 example => "/git/wiki.git/hooks/pre-receive",
101 description => "git pre-receive hook to generate",
105 untrusted_committers => {
108 description => "unix users whose commits should be checked by the pre-receive hook",
114 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]];hb=HEAD",
115 description => "gitweb url to show file history ([[file]] substituted)",
121 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]]",
122 description => "gitweb url to show a diff ([[file]], [[sha1_to]], [[sha1_from]], [[sha1_commit]], and [[sha1_parent]] substituted)",
126 gitorigin_branch => {
129 description => "where to pull and push changes (set to empty string to disable)",
130 safe => 0, # paranoia
133 gitmaster_branch => {
136 description => "branch that the wiki is stored in",
137 safe => 0, # paranoia
143 if ($config{test_receive}) {
144 require IkiWiki::Receive;
145 return IkiWiki::Receive::genwrapper();
153 # Start a child process safely without resorting /bin/sh.
154 # Return command output or success state (in scalar context).
156 my ($error_handler, @cmdline) = @_;
158 my $pid = open my $OUT, "-|";
160 error("Cannot fork: $!") if !defined $pid;
164 # Git commands want to be in wc.
166 chdir $config{srcdir}
167 or error("Cannot chdir to $config{srcdir}: $!");
169 exec @cmdline or error("Cannot exec '@cmdline': $!");
173 # git output is probably utf-8 encoded, but may contain
174 # other encodings or invalidly encoded stuff. So do not rely
175 # on the normal utf-8 IO layer, decode it by hand.
180 $_=decode_utf8($_, 0);
189 $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
191 return wantarray ? @lines : ($? == 0);
193 # Convenient wrappers.
194 sub run_or_die ($@) { safe_git(\&error, @_) }
195 sub run_or_cry ($@) { safe_git(sub { warn @_ }, @_) }
196 sub run_or_non ($@) { safe_git(undef, @_) }
199 sub merge_past ($$$) {
200 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
201 # Git merge commands work with the committed changes, except in the
202 # implicit case of '-m' of git checkout(1). So we should invent a
203 # kludge here. In principle, we need to create a throw-away branch
204 # in preparing for the merge itself. Since branches are cheap (and
205 # branching is fast), this shouldn't cost high.
207 # The main problem is the presence of _uncommitted_ local changes. One
208 # possible approach to get rid of this situation could be that we first
209 # make a temporary commit in the master branch and later restore the
210 # initial state (this is possible since Git has the ability to undo a
211 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
214 # - create a diff of HEAD:current-sha1
216 # - create a dummy branch and switch to it
217 # - rewind to past (reset --hard to the current-sha1)
218 # - apply the diff and commit
219 # - switch to master and do the merge with the dummy branch
220 # - make a soft reset (undo the last commit of master)
222 # The above method has some drawbacks: (1) it needs a redundant commit
223 # just to get rid of local changes, (2) somewhat slow because of the
224 # required system forks. Until someone points a more straight method
225 # (which I would be grateful) I have implemented an alternative method.
226 # In this approach, we hide all the modified files from Git by renaming
227 # them (using the 'rename' builtin) and later restore those files in
228 # the throw-away branch (that is, we put the files themselves instead
229 # of applying a patch).
231 my ($sha1, $file, $message) = @_;
233 my @undo; # undo stack for cleanup in case of an error
234 my $conflict; # file content with conflict markers
237 # Hide local changes from Git by renaming the modified file.
238 # Relative paths must be converted to absolute for renaming.
239 my ($target, $hidden) = (
240 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
242 rename($target, $hidden)
243 or error("rename '$target' to '$hidden' failed: $!");
244 # Ensure to restore the renamed file on error.
246 return if ! -e "$hidden"; # already renamed
247 rename($hidden, $target)
248 or warn "rename '$hidden' to '$target' failed: $!";
251 my $branch = "throw_away_${sha1}"; # supposed to be unique
253 # Create a throw-away branch and rewind backward.
254 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
255 run_or_die('git', 'branch', $branch, $sha1);
257 # Switch to throw-away branch for the merge operation.
259 if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
260 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
263 run_or_die('git', 'checkout', $branch);
265 # Put the modified file in _this_ branch.
266 rename($hidden, $target)
267 or error("rename '$hidden' to '$target' failed: $!");
269 # _Silently_ commit all modifications in the current branch.
270 run_or_non('git', 'commit', '-m', $message, '-a');
271 # ... and re-switch to master.
272 run_or_die('git', 'checkout', $config{gitmaster_branch});
274 # Attempt to merge without complaining.
275 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
276 $conflict = readfile($target);
277 run_or_die('git', 'reset', '--hard');
282 # Process undo stack (in reverse order). By policy cleanup
283 # actions should normally print a warning on failure.
284 while (my $handle = pop @undo) {
288 error("Git merge failed!\n$failure\n") if $failure;
295 sub decode_git_file ($) {
298 # git does not output utf-8 filenames, but instead
299 # double-quotes them with the utf-8 characters
300 # escaped as \nnn\nnn.
301 if ($file =~ m/^"(.*)"$/) {
302 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
305 # strip prefix if in a subdir
306 if (! defined $prefix) {
307 ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
308 if (! defined $prefix) {
312 $file =~ s/^\Q$prefix\E//;
314 return decode("utf8", $file);
318 sub parse_diff_tree ($) {
319 # Parse the raw diff tree chunk and return the info hash.
320 # See git-diff-tree(1) for the syntax.
324 return if !defined @{ $dt_ref } ||
325 !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
329 while (my $line = shift @{ $dt_ref }) {
330 return if $line !~ m/^(.+) ($sha1_pattern)/;
337 # Identification lines for the commit.
338 while (my $line = shift @{ $dt_ref }) {
339 # Regexps are semi-stolen from gitweb.cgi.
340 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
343 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
344 # XXX: collecting in reverse order
345 push @{ $ci{'parents'} }, $1;
347 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
348 my ($who, $name, $epoch, $tz) =
352 $ci{ "${who}_epoch" } = $epoch;
353 $ci{ "${who}_tz" } = $tz;
355 if ($name =~ m/^([^<]+)\s+<([^@>]+)/) {
356 $ci{"${who}_name"} = $1;
357 $ci{"${who}_username"} = $2;
359 elsif ($name =~ m/^([^<]+)\s+<>$/) {
360 $ci{"${who}_username"} = $1;
363 $ci{"${who}_username"} = $name;
366 elsif ($line =~ m/^$/) {
367 # Trailing empty line signals next section.
372 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
374 if (defined $ci{'parents'}) {
375 $ci{'parent'} = @{ $ci{'parents'} }[0];
378 $ci{'parent'} = 0 x 40;
381 # Commit message (optional).
382 while ($dt_ref->[0] =~ /^ /) {
383 my $line = shift @{ $dt_ref };
385 push @{ $ci{'comment'} }, $line;
387 shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
390 while (my $line = shift @{ $dt_ref }) {
392 (:+) # number of parents
393 ([^\t]+)\t # modes, sha1, status
396 my $num_parents = length $1;
397 my @tmp = split(" ", $2);
398 my ($file, $file_to) = split("\t", $3);
399 my @mode_from = splice(@tmp, 0, $num_parents);
400 my $mode_to = shift(@tmp);
401 my @sha1_from = splice(@tmp, 0, $num_parents);
402 my $sha1_to = shift(@tmp);
403 my $status = shift(@tmp);
406 push @{ $ci{'details'} }, {
407 'file' => decode_git_file($file),
408 'sha1_from' => $sha1_from[0],
409 'sha1_to' => $sha1_to,
410 'mode_from' => $mode_from[0],
411 'mode_to' => $mode_to,
423 sub git_commit_info ($;$) {
424 # Return an array of commit info hashes of num commits
425 # starting from the given sha1sum.
426 my ($sha1, $num) = @_;
429 push @opts, "--max-count=$num" if defined $num;
431 my @raw_lines = run_or_die('git', 'log', @opts,
432 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
433 '-r', $sha1, '--', '.');
436 while (my $parsed = parse_diff_tree(\@raw_lines)) {
440 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
442 return wantarray ? @ci : $ci[0];
446 # Return head sha1sum (of given file).
447 my $file = shift || q{--};
449 # Ignore error since a non-existing file might be given.
450 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
453 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
456 debug("Empty sha1sum for '$file'.");
458 return defined $sha1 ? $sha1 : q{};
462 # Update working directory.
464 if (length $config{gitorigin_branch}) {
465 run_or_cry('git', 'pull', $config{gitorigin_branch});
469 sub rcs_prepedit ($) {
470 # Return the commit sha1sum of the file when editing begins.
471 # This will be later used in rcs_commit if a merge is required.
474 return git_sha1($file);
478 # Try to commit the page; returns undef on _success_ and
479 # a version of the page with the rcs's conflict markers on
483 # Check to see if the page has been changed by someone else since
484 # rcs_prepedit was called.
485 my $cur = git_sha1($params{file});
486 my ($prev) = $params{token} =~ /^($sha1_pattern)$/; # untaint
488 if (defined $cur && defined $prev && $cur ne $prev) {
489 my $conflict = merge_past($prev, $params{file}, $dummy_commit_msg);
490 return $conflict if defined $conflict;
493 rcs_add($params{file});
494 return rcs_commit_staged(
495 message => $params{message},
496 session => $params{session},
500 sub rcs_commit_staged (@) {
501 # Commits all staged changes. Changes can be staged using rcs_add,
502 # rcs_remove, and rcs_rename.
507 if (defined $params{session}) {
508 # Set the commit author and email based on web session info.
510 if (defined $params{session}->param("name")) {
511 $u=$params{session}->param("name");
513 elsif (defined $params{session}->remote_addr()) {
514 $u=$params{session}->remote_addr();
518 $ENV{GIT_AUTHOR_NAME}=$u;
520 if (defined $params{session}->param("nickname")) {
521 $u=encode_utf8($params{session}->param("nickname"));
523 $u=~s/[^-_0-9[:alnum:]]+//g;
526 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
530 $params{message} = IkiWiki::possibly_foolish_untaint($params{message});
532 if ($params{message} !~ /\S/) {
533 # Force git to allow empty commit messages.
534 # (If this version of git supports it.)
535 my ($version)=`git --version` =~ /git version (.*)/;
536 if ($version ge "1.5.4") {
537 push @opts, '--cleanup=verbatim';
540 $params{message}.=".";
544 # git commit returns non-zero if file has not been really changed.
545 # so we should ignore its exit status (hence run_or_non).
546 if (run_or_non('git', 'commit', @opts, '-m', $params{message})) {
547 if (length $config{gitorigin_branch}) {
548 run_or_cry('git', 'push', $config{gitorigin_branch});
553 return undef; # success
557 # Add file to archive.
561 run_or_cry('git', 'add', $file);
565 # Remove file from archive.
569 run_or_cry('git', 'rm', '-f', $file);
572 sub rcs_rename ($$) {
573 my ($src, $dest) = @_;
575 run_or_cry('git', 'mv', '-f', $src, $dest);
578 sub rcs_recentchanges ($) {
579 # List of recent changes.
583 eval q{use Date::Parse};
587 foreach my $ci (git_commit_info('HEAD', $num || 1)) {
588 # Skip redundant commits.
589 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
591 my ($sha1, $when) = (
593 $ci->{'author_epoch'}
597 foreach my $detail (@{ $ci->{'details'} }) {
598 my $file = $detail->{'file'};
600 my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
601 $diffurl =~ s/\[\[file\]\]/$file/go;
602 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
603 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
604 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
605 $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
608 page => pagename($file),
615 foreach my $line (@{$ci->{'comment'}}) {
616 $pastblank=1 if $line eq '';
617 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
618 push @messages, { line => $line };
621 my $user=$ci->{'author_username'};
622 my $web_commit = ($ci->{'author'} =~ /\@web>/);
625 # Set nickname only if a non-url author_username is available,
626 # and author_name is an url.
627 if ($user !~ /:\/\// && defined $ci->{'author_name'} &&
628 $ci->{'author_name'} =~ /:\/\//) {
630 $user=$ci->{'author_name'};
633 # compatability code for old web commit messages
635 defined $messages[0] &&
636 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
637 $user = defined $2 ? "$2" : "$3";
638 $messages[0]->{line} = $4;
645 nickname => $nickname,
646 committype => $web_commit ? "web" : "git",
648 message => [@messages],
652 last if @rets >= $num;
660 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
662 foreach my $line (run_or_non("git", "show", $sha1)) {
663 if (@lines || $line=~/^diff --git/) {
664 push @lines, $line."\n";
671 return join("", @lines);
680 my $id=shift; # 0 = mtime ; 1 = ctime
682 if (! keys %time_cache) {
684 foreach my $line (run_or_die('git', 'log',
685 '--pretty=format:%ct',
686 '--name-only', '--relative')) {
687 if (! defined $date && $line =~ /^(\d+)$/) {
690 elsif (! length $line) {
694 my $f=decode_git_file($line);
696 if (! $time_cache{$f}) {
697 $time_cache{$f}[0]=$date; # mtime
699 $time_cache{$f}[1]=$date; # ctime
704 return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
709 sub rcs_getctime ($) {
712 return findtimes($file, 1);
715 sub rcs_getmtime ($) {
718 return findtimes($file, 0);
722 # The wiki may not be the only thing in the git repo.
723 # Determine if it is in a subdirectory by examining the srcdir,
724 # and its parents, looking for the .git directory.
726 my $dir=$config{srcdir};
727 while (! -d "$dir/.git") {
728 $subdir=IkiWiki::basename($dir)."/".$subdir;
729 $dir=IkiWiki::dirname($dir);
731 error("cannot determine root of git repo");
738 my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
740 # only allow changes to gitmaster_branch
741 if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
742 error sprintf(gettext("you are not allowed to change %s"), $refname);
745 # Avoid chdir when running git here, because the changes
746 # are in the master git repo, not the srcdir repo.
747 # The pre-recieve hook already puts us in the right place.
749 my @changes=git_commit_info($oldrev."..".$newrev);
752 foreach my $ci (@changes) {
753 foreach my $detail (@{ $ci->{'details'} }) {
754 my $file = $detail->{'file'};
756 # check that all changed files are in the
758 if (length $subdir &&
759 ! ($file =~ s/^\Q$subdir\E//)) {
760 error sprintf(gettext("you are not allowed to change %s"), $file);
763 my ($action, $mode, $path);
764 if ($detail->{'status'} =~ /^[M]+\d*$/) {
766 $mode=$detail->{'mode_to'};
768 elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
770 $mode=$detail->{'mode_to'};
772 elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
774 $mode=$detail->{'mode_from'};
777 error "unknown status ".$detail->{'status'};
780 # test that the file mode is ok
781 if ($mode !~ /^100[64][64][64]$/) {
782 error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
784 if ($action eq "change") {
785 if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
786 error gettext("you are not allowed to change file modes");
790 # extract attachment to temp file
791 if (($action eq 'add' || $action eq 'change') &&
793 eval q{use File::Temp};
796 ($fh, $path)=File::Temp::tempfile("XXXXXXXXXX", UNLINK => 1);
797 if (system("git show ".$detail->{sha1_to}." > '$path'") != 0) {
798 error("failed writing temp file");
811 return reverse @rets;