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"),
47 if (defined $config{git_test_receive_wrapper} &&
48 length $config{git_test_receive_wrapper}) {
49 push @{$config{wrappers}}, {
51 wrapper => $config{git_test_receive_wrapper},
52 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
56 # Avoid notes, parser does not handle and they only slow things down.
57 $ENV{GIT_NOTES_REF}="";
59 # Run receive test only if being called by the wrapper, and not
60 # when generating same.
61 if ($config{test_receive} && ! exists $config{wrapper}) {
62 require IkiWiki::Receive;
63 IkiWiki::Receive::test();
70 safe => 0, # rcs plugin
76 example => "/git/wiki.git/hooks/post-update",
77 description => "git hook to generate",
84 description => "mode for git_wrapper (can safely be made suid)",
88 git_test_receive_wrapper => {
90 example => "/git/wiki.git/hooks/pre-receive",
91 description => "git pre-receive hook to generate",
95 untrusted_committers => {
98 description => "unix users whose commits should be checked by the pre-receive hook",
104 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]]",
105 description => "gitweb url to show file history ([[file]] substituted)",
111 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]]",
112 description => "gitweb url to show a diff ([[file]], [[sha1_to]], [[sha1_from]], [[sha1_commit]], and [[sha1_parent]] substituted)",
116 gitorigin_branch => {
119 description => "where to pull and push changes (set to empty string to disable)",
120 safe => 0, # paranoia
123 gitmaster_branch => {
126 description => "branch that the wiki is stored in",
127 safe => 0, # paranoia
133 if ($config{test_receive}) {
134 require IkiWiki::Receive;
135 return IkiWiki::Receive::genwrapper();
143 # Start a child process safely without resorting /bin/sh.
144 # Return command output or success state (in scalar context).
146 my ($error_handler, @cmdline) = @_;
148 my $pid = open my $OUT, "-|";
150 error("Cannot fork: $!") if !defined $pid;
154 # Git commands want to be in wc.
156 chdir $config{srcdir}
157 or error("Cannot chdir to $config{srcdir}: $!");
159 exec @cmdline or error("Cannot exec '@cmdline': $!");
163 # git output is probably utf-8 encoded, but may contain
164 # other encodings or invalidly encoded stuff. So do not rely
165 # on the normal utf-8 IO layer, decode it by hand.
170 $_=decode_utf8($_, 0);
179 $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
181 return wantarray ? @lines : ($? == 0);
183 # Convenient wrappers.
184 sub run_or_die ($@) { safe_git(\&error, @_) }
185 sub run_or_cry ($@) { safe_git(sub { warn @_ }, @_) }
186 sub run_or_non ($@) { safe_git(undef, @_) }
189 sub merge_past ($$$) {
190 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
191 # Git merge commands work with the committed changes, except in the
192 # implicit case of '-m' of git checkout(1). So we should invent a
193 # kludge here. In principle, we need to create a throw-away branch
194 # in preparing for the merge itself. Since branches are cheap (and
195 # branching is fast), this shouldn't cost high.
197 # The main problem is the presence of _uncommitted_ local changes. One
198 # possible approach to get rid of this situation could be that we first
199 # make a temporary commit in the master branch and later restore the
200 # initial state (this is possible since Git has the ability to undo a
201 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
204 # - create a diff of HEAD:current-sha1
206 # - create a dummy branch and switch to it
207 # - rewind to past (reset --hard to the current-sha1)
208 # - apply the diff and commit
209 # - switch to master and do the merge with the dummy branch
210 # - make a soft reset (undo the last commit of master)
212 # The above method has some drawbacks: (1) it needs a redundant commit
213 # just to get rid of local changes, (2) somewhat slow because of the
214 # required system forks. Until someone points a more straight method
215 # (which I would be grateful) I have implemented an alternative method.
216 # In this approach, we hide all the modified files from Git by renaming
217 # them (using the 'rename' builtin) and later restore those files in
218 # the throw-away branch (that is, we put the files themselves instead
219 # of applying a patch).
221 my ($sha1, $file, $message) = @_;
223 my @undo; # undo stack for cleanup in case of an error
224 my $conflict; # file content with conflict markers
227 # Hide local changes from Git by renaming the modified file.
228 # Relative paths must be converted to absolute for renaming.
229 my ($target, $hidden) = (
230 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
232 rename($target, $hidden)
233 or error("rename '$target' to '$hidden' failed: $!");
234 # Ensure to restore the renamed file on error.
236 return if ! -e "$hidden"; # already renamed
237 rename($hidden, $target)
238 or warn "rename '$hidden' to '$target' failed: $!";
241 my $branch = "throw_away_${sha1}"; # supposed to be unique
243 # Create a throw-away branch and rewind backward.
244 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
245 run_or_die('git', 'branch', $branch, $sha1);
247 # Switch to throw-away branch for the merge operation.
249 if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
250 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
253 run_or_die('git', 'checkout', $branch);
255 # Put the modified file in _this_ branch.
256 rename($hidden, $target)
257 or error("rename '$hidden' to '$target' failed: $!");
259 # _Silently_ commit all modifications in the current branch.
260 run_or_non('git', 'commit', '-m', $message, '-a');
261 # ... and re-switch to master.
262 run_or_die('git', 'checkout', $config{gitmaster_branch});
264 # Attempt to merge without complaining.
265 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
266 $conflict = readfile($target);
267 run_or_die('git', 'reset', '--hard');
272 # Process undo stack (in reverse order). By policy cleanup
273 # actions should normally print a warning on failure.
274 while (my $handle = pop @undo) {
278 error("Git merge failed!\n$failure\n") if $failure;
285 sub decode_git_file ($) {
288 # git does not output utf-8 filenames, but instead
289 # double-quotes them with the utf-8 characters
290 # escaped as \nnn\nnn.
291 if ($file =~ m/^"(.*)"$/) {
292 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
295 # strip prefix if in a subdir
296 if (! defined $prefix) {
297 ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
298 if (! defined $prefix) {
302 $file =~ s/^\Q$prefix\E//;
304 return decode("utf8", $file);
308 sub parse_diff_tree ($) {
309 # Parse the raw diff tree chunk and return the info hash.
310 # See git-diff-tree(1) for the syntax.
314 return if !defined @{ $dt_ref } ||
315 !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
319 while (my $line = shift @{ $dt_ref }) {
320 return if $line !~ m/^(.+) ($sha1_pattern)/;
327 # Identification lines for the commit.
328 while (my $line = shift @{ $dt_ref }) {
329 # Regexps are semi-stolen from gitweb.cgi.
330 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
333 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
334 # XXX: collecting in reverse order
335 push @{ $ci{'parents'} }, $1;
337 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
338 my ($who, $name, $epoch, $tz) =
342 $ci{ "${who}_epoch" } = $epoch;
343 $ci{ "${who}_tz" } = $tz;
345 if ($name =~ m/^[^<]+\s+<([^@>]+)/) {
346 $ci{"${who}_username"} = $1;
348 elsif ($name =~ m/^([^<]+)\s+<>$/) {
349 $ci{"${who}_username"} = $1;
352 $ci{"${who}_username"} = $name;
355 elsif ($line =~ m/^$/) {
356 # Trailing empty line signals next section.
361 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
363 if (defined $ci{'parents'}) {
364 $ci{'parent'} = @{ $ci{'parents'} }[0];
367 $ci{'parent'} = 0 x 40;
370 # Commit message (optional).
371 while ($dt_ref->[0] =~ /^ /) {
372 my $line = shift @{ $dt_ref };
374 push @{ $ci{'comment'} }, $line;
376 shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
379 while (my $line = shift @{ $dt_ref }) {
381 (:+) # number of parents
382 ([^\t]+)\t # modes, sha1, status
385 my $num_parents = length $1;
386 my @tmp = split(" ", $2);
387 my ($file, $file_to) = split("\t", $3);
388 my @mode_from = splice(@tmp, 0, $num_parents);
389 my $mode_to = shift(@tmp);
390 my @sha1_from = splice(@tmp, 0, $num_parents);
391 my $sha1_to = shift(@tmp);
392 my $status = shift(@tmp);
395 push @{ $ci{'details'} }, {
396 'file' => decode_git_file($file),
397 'sha1_from' => $sha1_from[0],
398 'sha1_to' => $sha1_to,
399 'mode_from' => $mode_from[0],
400 'mode_to' => $mode_to,
412 sub git_commit_info ($;$) {
413 # Return an array of commit info hashes of num commits
414 # starting from the given sha1sum.
415 my ($sha1, $num) = @_;
418 push @opts, "--max-count=$num" if defined $num;
420 my @raw_lines = run_or_die('git', 'log', @opts,
421 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
422 '-r', $sha1, '--', '.');
425 while (my $parsed = parse_diff_tree(\@raw_lines)) {
429 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
431 return wantarray ? @ci : $ci[0];
435 # Return head sha1sum (of given file).
436 my $file = shift || q{--};
438 # Ignore error since a non-existing file might be given.
439 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
442 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
445 debug("Empty sha1sum for '$file'.");
447 return defined $sha1 ? $sha1 : q{};
451 # Update working directory.
453 if (length $config{gitorigin_branch}) {
454 run_or_cry('git', 'pull', $config{gitorigin_branch});
458 sub rcs_prepedit ($) {
459 # Return the commit sha1sum of the file when editing begins.
460 # This will be later used in rcs_commit if a merge is required.
463 return git_sha1($file);
466 sub rcs_commit ($$$;$$) {
467 # Try to commit the page; returns undef on _success_ and
468 # a version of the page with the rcs's conflict markers on
471 my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
473 # Check to see if the page has been changed by someone else since
474 # rcs_prepedit was called.
475 my $cur = git_sha1($file);
476 my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
478 if (defined $cur && defined $prev && $cur ne $prev) {
479 my $conflict = merge_past($prev, $file, $dummy_commit_msg);
480 return $conflict if defined $conflict;
484 return rcs_commit_staged($message, $user, $ipaddr);
487 sub rcs_commit_staged ($$$) {
488 # Commits all staged changes. Changes can be staged using rcs_add,
489 # rcs_remove, and rcs_rename.
490 my ($message, $user, $ipaddr)=@_;
492 # Set the commit author and email to the web committer.
494 if (defined $user || defined $ipaddr) {
495 my $u=encode_utf8(defined $user ? $user : $ipaddr);
496 $ENV{GIT_AUTHOR_NAME}=$u;
497 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
500 $message = IkiWiki::possibly_foolish_untaint($message);
502 if ($message !~ /\S/) {
503 # Force git to allow empty commit messages.
504 # (If this version of git supports it.)
505 my ($version)=`git --version` =~ /git version (.*)/;
506 if ($version ge "1.5.4") {
507 push @opts, '--cleanup=verbatim';
514 # git commit returns non-zero if file has not been really changed.
515 # so we should ignore its exit status (hence run_or_non).
516 if (run_or_non('git', 'commit', @opts, '-m', $message)) {
517 if (length $config{gitorigin_branch}) {
518 run_or_cry('git', 'push', $config{gitorigin_branch});
523 return undef; # success
527 # Add file to archive.
531 run_or_cry('git', 'add', $file);
535 # Remove file from archive.
539 run_or_cry('git', 'rm', '-f', $file);
542 sub rcs_rename ($$) {
543 my ($src, $dest) = @_;
545 run_or_cry('git', 'mv', '-f', $src, $dest);
548 sub rcs_recentchanges ($) {
549 # List of recent changes.
553 eval q{use Date::Parse};
557 foreach my $ci (git_commit_info('HEAD', $num || 1)) {
558 # Skip redundant commits.
559 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
561 my ($sha1, $when) = (
563 $ci->{'author_epoch'}
567 foreach my $detail (@{ $ci->{'details'} }) {
568 my $file = $detail->{'file'};
570 my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
571 $diffurl =~ s/\[\[file\]\]/$file/go;
572 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
573 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
574 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
575 $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
578 page => pagename($file),
585 foreach my $line (@{$ci->{'comment'}}) {
586 $pastblank=1 if $line eq '';
587 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
588 push @messages, { line => $line };
591 my $user=$ci->{'author_username'};
592 my $web_commit = ($ci->{'author'} =~ /\@web>/);
594 # compatability code for old web commit messages
596 defined $messages[0] &&
597 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
598 $user = defined $2 ? "$2" : "$3";
599 $messages[0]->{line} = $4;
606 committype => $web_commit ? "web" : "git",
608 message => [@messages],
612 last if @rets >= $num;
620 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
622 foreach my $line (run_or_non("git", "show", $sha1)) {
623 if (@lines || $line=~/^diff --git/) {
624 push @lines, $line."\n";
631 return join("", @lines);
640 my $id=shift; # 0 = mtime ; 1 = ctime
642 # Remove srcdir prefix
643 $file =~ s/^\Q$config{srcdir}\E\/?//;
645 if (! keys %time_cache) {
647 foreach my $line (run_or_die('git', 'log',
648 '--pretty=format:%ct',
649 '--name-only', '--relative')) {
650 if (! defined $date && $line =~ /^(\d+)$/) {
653 elsif (! length $line) {
657 my $f=decode_git_file($line);
659 if (! $time_cache{$f}) {
660 $time_cache{$f}[0]=$date; # mtime
662 $time_cache{$f}[1]=$date; # ctime
667 return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
672 sub rcs_getctime ($) {
675 return findtimes($file, 1);
678 sub rcs_getmtime ($) {
681 return findtimes($file, 0);
685 # The wiki may not be the only thing in the git repo.
686 # Determine if it is in a subdirectory by examining the srcdir,
687 # and its parents, looking for the .git directory.
689 my $dir=$config{srcdir};
690 while (! -d "$dir/.git") {
691 $subdir=IkiWiki::basename($dir)."/".$subdir;
692 $dir=IkiWiki::dirname($dir);
694 error("cannot determine root of git repo");
701 my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
703 # only allow changes to gitmaster_branch
704 if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
705 error sprintf(gettext("you are not allowed to change %s"), $refname);
708 # Avoid chdir when running git here, because the changes
709 # are in the master git repo, not the srcdir repo.
710 # The pre-recieve hook already puts us in the right place.
712 my @changes=git_commit_info($oldrev."..".$newrev);
715 foreach my $ci (@changes) {
716 foreach my $detail (@{ $ci->{'details'} }) {
717 my $file = $detail->{'file'};
719 # check that all changed files are in the
721 if (length $subdir &&
722 ! ($file =~ s/^\Q$subdir\E//)) {
723 error sprintf(gettext("you are not allowed to change %s"), $file);
726 my ($action, $mode, $path);
727 if ($detail->{'status'} =~ /^[M]+\d*$/) {
729 $mode=$detail->{'mode_to'};
731 elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
733 $mode=$detail->{'mode_to'};
735 elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
737 $mode=$detail->{'mode_from'};
740 error "unknown status ".$detail->{'status'};
743 # test that the file mode is ok
744 if ($mode !~ /^100[64][64][64]$/) {
745 error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
747 if ($action eq "change") {
748 if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
749 error gettext("you are not allowed to change file modes");
753 # extract attachment to temp file
754 if (($action eq 'add' || $action eq 'change') &&
756 eval q{use File::Temp};
759 ($fh, $path)=File::Temp::tempfile("XXXXXXXXXX", UNLINK => 1);
760 if (system("git show ".$detail->{sha1_to}." > '$path'") != 0) {
761 error("failed writing temp file");
774 return reverse @rets;