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_receive", call => \&rcs_receive);
32 if (! defined $config{gitorigin_branch}) {
33 $config{gitorigin_branch}="origin";
35 if (! defined $config{gitmaster_branch}) {
36 $config{gitmaster_branch}="master";
38 if (defined $config{git_wrapper} &&
39 length $config{git_wrapper}) {
40 push @{$config{wrappers}}, {
41 wrapper => $config{git_wrapper},
42 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
46 if (defined $config{git_test_receive_wrapper} &&
47 length $config{git_test_receive_wrapper}) {
48 push @{$config{wrappers}}, {
50 wrapper => $config{git_test_receive_wrapper},
51 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
55 # Run receive test only if being called by the wrapper, and not
56 # when generating same.
57 if ($config{test_receive} && ! exists $config{wrapper}) {
58 require IkiWiki::Receive;
59 IkiWiki::Receive::test();
66 safe => 0, # rcs plugin
71 example => "/git/wiki.git/hooks/post-update",
72 description => "git hook to generate",
79 description => "mode for git_wrapper (can safely be made suid)",
83 git_test_receive_wrapper => {
85 example => "/git/wiki.git/hooks/pre-receive",
86 description => "git pre-receive hook to generate",
90 untrusted_committers => {
93 description => "unix users whose commits should be checked by the pre-receive hook",
99 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]]",
100 description => "gitweb url to show file history ([[file]] substituted)",
106 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]]",
107 description => "gitweb url to show a diff ([[file]], [[sha1_to]], [[sha1_from]], [[sha1_commit]], and [[sha1_parent]] substituted)",
111 gitorigin_branch => {
114 description => "where to pull and push changes (set to empty string to disable)",
115 safe => 0, # paranoia
118 gitmaster_branch => {
121 description => "branch that the wiki is stored in",
122 safe => 0, # paranoia
128 if ($config{test_receive}) {
129 require IkiWiki::Receive;
130 return IkiWiki::Receive::genwrapper();
138 # Start a child process safely without resorting /bin/sh.
139 # Return command output or success state (in scalar context).
141 my ($error_handler, @cmdline) = @_;
143 my $pid = open my $OUT, "-|";
145 error("Cannot fork: $!") if !defined $pid;
149 # Git commands want to be in wc.
151 chdir $config{srcdir}
152 or error("Cannot chdir to $config{srcdir}: $!");
154 exec @cmdline or error("Cannot exec '@cmdline': $!");
158 # git output is probably utf-8 encoded, but may contain
159 # other encodings or invalidly encoded stuff. So do not rely
160 # on the normal utf-8 IO layer, decode it by hand.
165 $_=decode_utf8($_, 0);
174 $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
176 return wantarray ? @lines : ($? == 0);
178 # Convenient wrappers.
179 sub run_or_die ($@) { safe_git(\&error, @_) }
180 sub run_or_cry ($@) { safe_git(sub { warn @_ }, @_) }
181 sub run_or_non ($@) { safe_git(undef, @_) }
184 sub merge_past ($$$) {
185 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
186 # Git merge commands work with the committed changes, except in the
187 # implicit case of '-m' of git checkout(1). So we should invent a
188 # kludge here. In principle, we need to create a throw-away branch
189 # in preparing for the merge itself. Since branches are cheap (and
190 # branching is fast), this shouldn't cost high.
192 # The main problem is the presence of _uncommitted_ local changes. One
193 # possible approach to get rid of this situation could be that we first
194 # make a temporary commit in the master branch and later restore the
195 # initial state (this is possible since Git has the ability to undo a
196 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
199 # - create a diff of HEAD:current-sha1
201 # - create a dummy branch and switch to it
202 # - rewind to past (reset --hard to the current-sha1)
203 # - apply the diff and commit
204 # - switch to master and do the merge with the dummy branch
205 # - make a soft reset (undo the last commit of master)
207 # The above method has some drawbacks: (1) it needs a redundant commit
208 # just to get rid of local changes, (2) somewhat slow because of the
209 # required system forks. Until someone points a more straight method
210 # (which I would be grateful) I have implemented an alternative method.
211 # In this approach, we hide all the modified files from Git by renaming
212 # them (using the 'rename' builtin) and later restore those files in
213 # the throw-away branch (that is, we put the files themselves instead
214 # of applying a patch).
216 my ($sha1, $file, $message) = @_;
218 my @undo; # undo stack for cleanup in case of an error
219 my $conflict; # file content with conflict markers
222 # Hide local changes from Git by renaming the modified file.
223 # Relative paths must be converted to absolute for renaming.
224 my ($target, $hidden) = (
225 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
227 rename($target, $hidden)
228 or error("rename '$target' to '$hidden' failed: $!");
229 # Ensure to restore the renamed file on error.
231 return if ! -e "$hidden"; # already renamed
232 rename($hidden, $target)
233 or warn "rename '$hidden' to '$target' failed: $!";
236 my $branch = "throw_away_${sha1}"; # supposed to be unique
238 # Create a throw-away branch and rewind backward.
239 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
240 run_or_die('git', 'branch', $branch, $sha1);
242 # Switch to throw-away branch for the merge operation.
244 if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
245 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
248 run_or_die('git', 'checkout', $branch);
250 # Put the modified file in _this_ branch.
251 rename($hidden, $target)
252 or error("rename '$hidden' to '$target' failed: $!");
254 # _Silently_ commit all modifications in the current branch.
255 run_or_non('git', 'commit', '-m', $message, '-a');
256 # ... and re-switch to master.
257 run_or_die('git', 'checkout', $config{gitmaster_branch});
259 # Attempt to merge without complaining.
260 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
261 $conflict = readfile($target);
262 run_or_die('git', 'reset', '--hard');
267 # Process undo stack (in reverse order). By policy cleanup
268 # actions should normally print a warning on failure.
269 while (my $handle = pop @undo) {
273 error("Git merge failed!\n$failure\n") if $failure;
278 sub parse_diff_tree ($@) {
279 # Parse the raw diff tree chunk and return the info hash.
280 # See git-diff-tree(1) for the syntax.
282 my ($prefix, $dt_ref) = @_;
285 return if !defined @{ $dt_ref } ||
286 !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
290 while (my $line = shift @{ $dt_ref }) {
291 return if $line !~ m/^(.+) ($sha1_pattern)/;
298 # Identification lines for the commit.
299 while (my $line = shift @{ $dt_ref }) {
300 # Regexps are semi-stolen from gitweb.cgi.
301 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
304 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
305 # XXX: collecting in reverse order
306 push @{ $ci{'parents'} }, $1;
308 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
309 my ($who, $name, $epoch, $tz) =
313 $ci{ "${who}_epoch" } = $epoch;
314 $ci{ "${who}_tz" } = $tz;
316 if ($name =~ m/^[^<]+\s+<([^@>]+)/) {
317 $ci{"${who}_username"} = $1;
319 elsif ($name =~ m/^([^<]+)\s+<>$/) {
320 $ci{"${who}_username"} = $1;
323 $ci{"${who}_username"} = $name;
326 elsif ($line =~ m/^$/) {
327 # Trailing empty line signals next section.
332 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
334 if (defined $ci{'parents'}) {
335 $ci{'parent'} = @{ $ci{'parents'} }[0];
338 $ci{'parent'} = 0 x 40;
341 # Commit message (optional).
342 while ($dt_ref->[0] =~ /^ /) {
343 my $line = shift @{ $dt_ref };
345 push @{ $ci{'comment'} }, $line;
347 shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
350 while (my $line = shift @{ $dt_ref }) {
352 (:+) # number of parents
353 ([^\t]+)\t # modes, sha1, status
356 my $num_parents = length $1;
357 my @tmp = split(" ", $2);
358 my ($file, $file_to) = split("\t", $3);
359 my @mode_from = splice(@tmp, 0, $num_parents);
360 my $mode_to = shift(@tmp);
361 my @sha1_from = splice(@tmp, 0, $num_parents);
362 my $sha1_to = shift(@tmp);
363 my $status = shift(@tmp);
365 # git does not output utf-8 filenames, but instead
366 # double-quotes them with the utf-8 characters
367 # escaped as \nnn\nnn.
368 if ($file =~ m/^"(.*)"$/) {
369 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
371 $file =~ s/^\Q$prefix\E//;
373 push @{ $ci{'details'} }, {
374 'file' => decode("utf8", $file),
375 'sha1_from' => $sha1_from[0],
376 'sha1_to' => $sha1_to,
377 'mode_from' => $mode_from[0],
378 'mode_to' => $mode_to,
390 sub git_commit_info ($;$) {
391 # Return an array of commit info hashes of num commits
392 # starting from the given sha1sum.
393 my ($sha1, $num) = @_;
396 push @opts, "--max-count=$num" if defined $num;
398 my @raw_lines = run_or_die('git', 'log', @opts,
399 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
400 '-r', $sha1, '--', '.');
401 my ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
404 while (my $parsed = parse_diff_tree(($prefix or ""), \@raw_lines)) {
408 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
410 return wantarray ? @ci : $ci[0];
414 # Return head sha1sum (of given file).
415 my $file = shift || q{--};
417 # Ignore error since a non-existing file might be given.
418 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
421 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
424 debug("Empty sha1sum for '$file'.");
426 return defined $sha1 ? $sha1 : q{};
430 # Update working directory.
432 if (length $config{gitorigin_branch}) {
433 run_or_cry('git', 'pull', $config{gitorigin_branch});
437 sub rcs_prepedit ($) {
438 # Return the commit sha1sum of the file when editing begins.
439 # This will be later used in rcs_commit if a merge is required.
442 return git_sha1($file);
445 sub rcs_commit ($$$;$$) {
446 # Try to commit the page; returns undef on _success_ and
447 # a version of the page with the rcs's conflict markers on
450 my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
452 # Check to see if the page has been changed by someone else since
453 # rcs_prepedit was called.
454 my $cur = git_sha1($file);
455 my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
457 if (defined $cur && defined $prev && $cur ne $prev) {
458 my $conflict = merge_past($prev, $file, $dummy_commit_msg);
459 return $conflict if defined $conflict;
463 return rcs_commit_staged($message, $user, $ipaddr);
466 sub rcs_commit_staged ($$$) {
467 # Commits all staged changes. Changes can be staged using rcs_add,
468 # rcs_remove, and rcs_rename.
469 my ($message, $user, $ipaddr)=@_;
471 # Set the commit author and email to the web committer.
473 if (defined $user || defined $ipaddr) {
474 my $u=encode_utf8(defined $user ? $user : $ipaddr);
475 $ENV{GIT_AUTHOR_NAME}=$u;
476 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
479 $message = IkiWiki::possibly_foolish_untaint($message);
481 if ($message !~ /\S/) {
482 # Force git to allow empty commit messages.
483 # (If this version of git supports it.)
484 my ($version)=`git --version` =~ /git version (.*)/;
485 if ($version ge "1.5.4") {
486 push @opts, '--cleanup=verbatim';
493 # git commit returns non-zero if file has not been really changed.
494 # so we should ignore its exit status (hence run_or_non).
495 if (run_or_non('git', 'commit', @opts, '-m', $message)) {
496 if (length $config{gitorigin_branch}) {
497 run_or_cry('git', 'push', $config{gitorigin_branch});
502 return undef; # success
506 # Add file to archive.
510 run_or_cry('git', 'add', $file);
514 # Remove file from archive.
518 run_or_cry('git', 'rm', '-f', $file);
521 sub rcs_rename ($$) {
522 my ($src, $dest) = @_;
524 run_or_cry('git', 'mv', '-f', $src, $dest);
527 sub rcs_recentchanges ($) {
528 # List of recent changes.
532 eval q{use Date::Parse};
536 foreach my $ci (git_commit_info('HEAD', $num || 1)) {
537 # Skip redundant commits.
538 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
540 my ($sha1, $when) = (
542 $ci->{'author_epoch'}
546 foreach my $detail (@{ $ci->{'details'} }) {
547 my $file = $detail->{'file'};
549 my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
550 $diffurl =~ s/\[\[file\]\]/$file/go;
551 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
552 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
553 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
554 $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
557 page => pagename($file),
564 foreach my $line (@{$ci->{'comment'}}) {
565 $pastblank=1 if $line eq '';
566 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
567 push @messages, { line => $line };
570 my $user=$ci->{'author_username'};
571 my $web_commit = ($ci->{'author'} =~ /\@web>/);
573 # compatability code for old web commit messages
575 defined $messages[0] &&
576 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
577 $user = defined $2 ? "$2" : "$3";
578 $messages[0]->{line} = $4;
585 committype => $web_commit ? "web" : "git",
587 message => [@messages],
591 last if @rets >= $num;
599 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
601 foreach my $line (run_or_non("git", "show", $sha1)) {
602 if (@lines || $line=~/^diff --git/) {
603 push @lines, $line."\n";
610 return join("", @lines);
614 sub rcs_getctime ($) {
616 # Remove srcdir prefix
617 $file =~ s/^\Q$config{srcdir}\E\/?//;
619 my @raw_lines = run_or_die('git', 'log',
620 '--follow', '--no-merges',
621 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
624 while (my $parsed = parse_diff_tree("", \@raw_lines)) {
627 my $ctime = $ci[$#ci]->{'author_epoch'};
628 debug("ctime for '$file': ". localtime($ctime));
634 # The wiki may not be the only thing in the git repo.
635 # Determine if it is in a subdirectory by examining the srcdir,
636 # and its parents, looking for the .git directory.
638 my $dir=$config{srcdir};
639 while (! -d "$dir/.git") {
640 $subdir=IkiWiki::basename($dir)."/".$subdir;
641 $dir=IkiWiki::dirname($dir);
643 error("cannot determine root of git repo");
650 my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
652 # only allow changes to gitmaster_branch
653 if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
654 error sprintf(gettext("you are not allowed to change %s"), $refname);
657 # Avoid chdir when running git here, because the changes
658 # are in the master git repo, not the srcdir repo.
659 # The pre-recieve hook already puts us in the right place.
661 my @changes=git_commit_info($oldrev."..".$newrev);
664 foreach my $ci (@changes) {
665 foreach my $detail (@{ $ci->{'details'} }) {
666 my $file = $detail->{'file'};
668 # check that all changed files are in the
670 if (length $subdir &&
671 ! ($file =~ s/^\Q$subdir\E//)) {
672 error sprintf(gettext("you are not allowed to change %s"), $file);
675 my ($action, $mode, $path);
676 if ($detail->{'status'} =~ /^[M]+\d*$/) {
678 $mode=$detail->{'mode_to'};
680 elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
682 $mode=$detail->{'mode_to'};
684 elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
686 $mode=$detail->{'mode_from'};
689 error "unknown status ".$detail->{'status'};
692 # test that the file mode is ok
693 if ($mode !~ /^100[64][64][64]$/) {
694 error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
696 if ($action eq "change") {
697 if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
698 error gettext("you are not allowed to change file modes");
702 # extract attachment to temp file
703 if (($action eq 'add' || $action eq 'change') &&
705 eval q{use File::Temp};
708 ($fh, $path)=File::Temp::tempfile("XXXXXXXXXX", UNLINK => 1);
709 if (system("git show ".$detail->{sha1_to}." > '$path'") != 0) {
710 error("failed writing temp file");
723 return reverse @rets;