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);
34 if (! defined $config{gitorigin_branch}) {
35 $config{gitorigin_branch}="origin";
37 if (! defined $config{gitmaster_branch}) {
38 $config{gitmaster_branch}="master";
40 if (defined $config{git_wrapper} &&
41 length $config{git_wrapper}) {
42 push @{$config{wrappers}}, {
43 wrapper => $config{git_wrapper},
44 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
48 if (defined $config{git_test_receive_wrapper} &&
49 length $config{git_test_receive_wrapper}) {
50 push @{$config{wrappers}}, {
52 wrapper => $config{git_test_receive_wrapper},
53 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
57 # Avoid notes, parser does not handle and they only slow things down.
58 $ENV{GIT_NOTES_REF}="";
60 # Run receive test only if being called by the wrapper, and not
61 # when generating same.
62 if ($config{test_receive} && ! exists $config{wrapper}) {
63 require IkiWiki::Receive;
64 IkiWiki::Receive::test();
71 safe => 0, # rcs plugin
77 example => "/git/wiki.git/hooks/post-update",
78 description => "git hook to generate",
85 description => "mode for git_wrapper (can safely be made suid)",
89 git_test_receive_wrapper => {
91 example => "/git/wiki.git/hooks/pre-receive",
92 description => "git pre-receive hook to generate",
96 untrusted_committers => {
99 description => "unix users whose commits should be checked by the pre-receive hook",
105 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]]",
106 description => "gitweb url to show file history ([[file]] substituted)",
112 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]]",
113 description => "gitweb url to show a diff ([[file]], [[sha1_to]], [[sha1_from]], [[sha1_commit]], and [[sha1_parent]] substituted)",
117 gitorigin_branch => {
120 description => "where to pull and push changes (set to empty string to disable)",
121 safe => 0, # paranoia
124 gitmaster_branch => {
127 description => "branch that the wiki is stored in",
128 safe => 0, # paranoia
134 if ($config{test_receive}) {
135 require IkiWiki::Receive;
136 return IkiWiki::Receive::genwrapper();
144 # Start a child process safely without resorting /bin/sh.
145 # Return command output or success state (in scalar context).
147 my ($error_handler, @cmdline) = @_;
149 my $pid = open my $OUT, "-|";
151 error("Cannot fork: $!") if !defined $pid;
155 # Git commands want to be in wc.
157 chdir $config{srcdir}
158 or error("Cannot chdir to $config{srcdir}: $!");
160 exec @cmdline or error("Cannot exec '@cmdline': $!");
164 # git output is probably utf-8 encoded, but may contain
165 # other encodings or invalidly encoded stuff. So do not rely
166 # on the normal utf-8 IO layer, decode it by hand.
171 $_=decode_utf8($_, 0);
180 $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
182 return wantarray ? @lines : ($? == 0);
184 # Convenient wrappers.
185 sub run_or_die ($@) { safe_git(\&error, @_) }
186 sub run_or_cry ($@) { safe_git(sub { warn @_ }, @_) }
187 sub run_or_non ($@) { safe_git(undef, @_) }
190 sub merge_past ($$$) {
191 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
192 # Git merge commands work with the committed changes, except in the
193 # implicit case of '-m' of git checkout(1). So we should invent a
194 # kludge here. In principle, we need to create a throw-away branch
195 # in preparing for the merge itself. Since branches are cheap (and
196 # branching is fast), this shouldn't cost high.
198 # The main problem is the presence of _uncommitted_ local changes. One
199 # possible approach to get rid of this situation could be that we first
200 # make a temporary commit in the master branch and later restore the
201 # initial state (this is possible since Git has the ability to undo a
202 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
205 # - create a diff of HEAD:current-sha1
207 # - create a dummy branch and switch to it
208 # - rewind to past (reset --hard to the current-sha1)
209 # - apply the diff and commit
210 # - switch to master and do the merge with the dummy branch
211 # - make a soft reset (undo the last commit of master)
213 # The above method has some drawbacks: (1) it needs a redundant commit
214 # just to get rid of local changes, (2) somewhat slow because of the
215 # required system forks. Until someone points a more straight method
216 # (which I would be grateful) I have implemented an alternative method.
217 # In this approach, we hide all the modified files from Git by renaming
218 # them (using the 'rename' builtin) and later restore those files in
219 # the throw-away branch (that is, we put the files themselves instead
220 # of applying a patch).
222 my ($sha1, $file, $message) = @_;
224 my @undo; # undo stack for cleanup in case of an error
225 my $conflict; # file content with conflict markers
228 # Hide local changes from Git by renaming the modified file.
229 # Relative paths must be converted to absolute for renaming.
230 my ($target, $hidden) = (
231 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
233 rename($target, $hidden)
234 or error("rename '$target' to '$hidden' failed: $!");
235 # Ensure to restore the renamed file on error.
237 return if ! -e "$hidden"; # already renamed
238 rename($hidden, $target)
239 or warn "rename '$hidden' to '$target' failed: $!";
242 my $branch = "throw_away_${sha1}"; # supposed to be unique
244 # Create a throw-away branch and rewind backward.
245 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
246 run_or_die('git', 'branch', $branch, $sha1);
248 # Switch to throw-away branch for the merge operation.
250 if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
251 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
254 run_or_die('git', 'checkout', $branch);
256 # Put the modified file in _this_ branch.
257 rename($hidden, $target)
258 or error("rename '$hidden' to '$target' failed: $!");
260 # _Silently_ commit all modifications in the current branch.
261 run_or_non('git', 'commit', '-m', $message, '-a');
262 # ... and re-switch to master.
263 run_or_die('git', 'checkout', $config{gitmaster_branch});
265 # Attempt to merge without complaining.
266 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
267 $conflict = readfile($target);
268 run_or_die('git', 'reset', '--hard');
273 # Process undo stack (in reverse order). By policy cleanup
274 # actions should normally print a warning on failure.
275 while (my $handle = pop @undo) {
279 error("Git merge failed!\n$failure\n") if $failure;
284 sub parse_diff_tree ($@) {
285 # Parse the raw diff tree chunk and return the info hash.
286 # See git-diff-tree(1) for the syntax.
288 my ($prefix, $dt_ref) = @_;
291 return if !defined @{ $dt_ref } ||
292 !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
296 while (my $line = shift @{ $dt_ref }) {
297 return if $line !~ m/^(.+) ($sha1_pattern)/;
304 # Identification lines for the commit.
305 while (my $line = shift @{ $dt_ref }) {
306 # Regexps are semi-stolen from gitweb.cgi.
307 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
310 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
311 # XXX: collecting in reverse order
312 push @{ $ci{'parents'} }, $1;
314 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
315 my ($who, $name, $epoch, $tz) =
319 $ci{ "${who}_epoch" } = $epoch;
320 $ci{ "${who}_tz" } = $tz;
322 if ($name =~ m/^[^<]+\s+<([^@>]+)/) {
323 $ci{"${who}_username"} = $1;
325 elsif ($name =~ m/^([^<]+)\s+<>$/) {
326 $ci{"${who}_username"} = $1;
329 $ci{"${who}_username"} = $name;
332 elsif ($line =~ m/^$/) {
333 # Trailing empty line signals next section.
338 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
340 if (defined $ci{'parents'}) {
341 $ci{'parent'} = @{ $ci{'parents'} }[0];
344 $ci{'parent'} = 0 x 40;
347 # Commit message (optional).
348 while ($dt_ref->[0] =~ /^ /) {
349 my $line = shift @{ $dt_ref };
351 push @{ $ci{'comment'} }, $line;
353 shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
356 while (my $line = shift @{ $dt_ref }) {
358 (:+) # number of parents
359 ([^\t]+)\t # modes, sha1, status
362 my $num_parents = length $1;
363 my @tmp = split(" ", $2);
364 my ($file, $file_to) = split("\t", $3);
365 my @mode_from = splice(@tmp, 0, $num_parents);
366 my $mode_to = shift(@tmp);
367 my @sha1_from = splice(@tmp, 0, $num_parents);
368 my $sha1_to = shift(@tmp);
369 my $status = shift(@tmp);
371 # git does not output utf-8 filenames, but instead
372 # double-quotes them with the utf-8 characters
373 # escaped as \nnn\nnn.
374 if ($file =~ m/^"(.*)"$/) {
375 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
377 $file =~ s/^\Q$prefix\E//;
379 push @{ $ci{'details'} }, {
380 'file' => decode("utf8", $file),
381 'sha1_from' => $sha1_from[0],
382 'sha1_to' => $sha1_to,
383 'mode_from' => $mode_from[0],
384 'mode_to' => $mode_to,
396 sub git_commit_info ($;$) {
397 # Return an array of commit info hashes of num commits
398 # starting from the given sha1sum.
399 my ($sha1, $num) = @_;
402 push @opts, "--max-count=$num" if defined $num;
404 my @raw_lines = run_or_die('git', 'log', @opts,
405 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
406 '-r', $sha1, '--', '.');
407 my ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
410 while (my $parsed = parse_diff_tree(($prefix or ""), \@raw_lines)) {
414 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
416 return wantarray ? @ci : $ci[0];
420 # Return head sha1sum (of given file).
421 my $file = shift || q{--};
423 # Ignore error since a non-existing file might be given.
424 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
427 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
430 debug("Empty sha1sum for '$file'.");
432 return defined $sha1 ? $sha1 : q{};
436 # Update working directory.
438 if (length $config{gitorigin_branch}) {
439 run_or_cry('git', 'pull', $config{gitorigin_branch});
443 sub rcs_prepedit ($) {
444 # Return the commit sha1sum of the file when editing begins.
445 # This will be later used in rcs_commit if a merge is required.
448 return git_sha1($file);
451 sub rcs_commit ($$$;$$) {
452 # Try to commit the page; returns undef on _success_ and
453 # a version of the page with the rcs's conflict markers on
456 my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
458 # Check to see if the page has been changed by someone else since
459 # rcs_prepedit was called.
460 my $cur = git_sha1($file);
461 my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
463 if (defined $cur && defined $prev && $cur ne $prev) {
464 my $conflict = merge_past($prev, $file, $dummy_commit_msg);
465 return $conflict if defined $conflict;
469 return rcs_commit_staged($message, $user, $ipaddr);
472 sub rcs_commit_staged ($$$) {
473 # Commits all staged changes. Changes can be staged using rcs_add,
474 # rcs_remove, and rcs_rename.
475 my ($message, $user, $ipaddr)=@_;
477 # Set the commit author and email to the web committer.
479 if (defined $user || defined $ipaddr) {
480 my $u=encode_utf8(defined $user ? $user : $ipaddr);
481 # MITLOGIN This algorithm could be improved
482 $ENV{GIT_AUTHOR_NAME}=IkiWiki::userinfo_get($u, "realname");
483 $ENV{GIT_AUTHOR_EMAIL}="$u\@mit.edu";
486 $message = IkiWiki::possibly_foolish_untaint($message);
488 if ($message !~ /\S/) {
489 # Force git to allow empty commit messages.
490 # (If this version of git supports it.)
491 my ($version)=`git --version` =~ /git version (.*)/;
492 if ($version ge "1.5.4") {
493 push @opts, '--cleanup=verbatim';
500 # git commit returns non-zero if file has not been really changed.
501 # so we should ignore its exit status (hence run_or_non).
502 if (run_or_non('git', 'commit', @opts, '-m', $message)) {
503 if (length $config{gitorigin_branch}) {
504 run_or_cry('git', 'push', $config{gitorigin_branch});
509 return undef; # success
513 # Add file to archive.
517 run_or_cry('git', 'add', $file);
521 # Remove file from archive.
525 run_or_cry('git', 'rm', '-f', $file);
528 sub rcs_rename ($$) {
529 my ($src, $dest) = @_;
531 run_or_cry('git', 'mv', '-f', $src, $dest);
534 sub rcs_recentchanges ($) {
535 # List of recent changes.
539 eval q{use Date::Parse};
543 foreach my $ci (git_commit_info('HEAD', $num || 1)) {
544 # Skip redundant commits.
545 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
547 my ($sha1, $when) = (
549 $ci->{'author_epoch'}
553 foreach my $detail (@{ $ci->{'details'} }) {
554 my $file = $detail->{'file'};
556 my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
557 $diffurl =~ s/\[\[file\]\]/$file/go;
558 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
559 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
560 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
561 $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
564 page => pagename($file),
571 foreach my $line (@{$ci->{'comment'}}) {
572 $pastblank=1 if $line eq '';
573 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
574 push @messages, { line => $line };
577 my $user=$ci->{'author_username'};
578 my $web_commit = ($ci->{'author'} =~ /\@web>/);
580 # compatability code for old web commit messages
582 defined $messages[0] &&
583 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
584 $user = defined $2 ? "$2" : "$3";
585 $messages[0]->{line} = $4;
592 committype => $web_commit ? "web" : "git",
594 message => [@messages],
598 last if @rets >= $num;
606 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
608 foreach my $line (run_or_non("git", "show", $sha1)) {
609 if (@lines || $line=~/^diff --git/) {
610 push @lines, $line."\n";
617 return join("", @lines);
626 my $id=shift; # 0 = mtime ; 1 = ctime
628 # Remove srcdir prefix
629 $file =~ s/^\Q$config{srcdir}\E\/?//;
631 if (! keys %time_cache) {
633 foreach my $line (run_or_die('git', 'log',
634 '--pretty=format:%ct',
635 '--name-only', '--relative')) {
636 if (! defined $date && $line =~ /^(\d+)$/) {
639 elsif (! length $line) {
643 if (! $time_cache{$line}) {
644 $time_cache{$line}[0]=$date; # mtime
646 $time_cache{$line}[1]=$date; # ctime
651 return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
656 sub rcs_getctime ($) {
659 return findtimes($file, 1);
662 sub rcs_getmtime ($) {
665 return findtimes($file, 0);
669 # The wiki may not be the only thing in the git repo.
670 # Determine if it is in a subdirectory by examining the srcdir,
671 # and its parents, looking for the .git directory.
673 my $dir=$config{srcdir};
674 while (! -d "$dir/.git") {
675 $subdir=IkiWiki::basename($dir)."/".$subdir;
676 $dir=IkiWiki::dirname($dir);
678 error("cannot determine root of git repo");
685 my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
687 # only allow changes to gitmaster_branch
688 if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
689 error sprintf(gettext("you are not allowed to change %s"), $refname);
692 # Avoid chdir when running git here, because the changes
693 # are in the master git repo, not the srcdir repo.
694 # The pre-recieve hook already puts us in the right place.
696 my @changes=git_commit_info($oldrev."..".$newrev);
699 foreach my $ci (@changes) {
700 foreach my $detail (@{ $ci->{'details'} }) {
701 my $file = $detail->{'file'};
703 # check that all changed files are in the
705 if (length $subdir &&
706 ! ($file =~ s/^\Q$subdir\E//)) {
707 error sprintf(gettext("you are not allowed to change %s"), $file);
710 my ($action, $mode, $path);
711 if ($detail->{'status'} =~ /^[M]+\d*$/) {
713 $mode=$detail->{'mode_to'};
715 elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
717 $mode=$detail->{'mode_to'};
719 elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
721 $mode=$detail->{'mode_from'};
724 error "unknown status ".$detail->{'status'};
727 # test that the file mode is ok
728 if ($mode !~ /^100[64][64][64]$/) {
729 error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
731 if ($action eq "change") {
732 if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
733 error gettext("you are not allowed to change file modes");
737 # extract attachment to temp file
738 if (($action eq 'add' || $action eq 'change') &&
740 eval q{use File::Temp};
743 ($fh, $path)=File::Temp::tempfile("XXXXXXXXXX", UNLINK => 1);
744 if (system("git show ".$detail->{sha1_to}." > '$path'") != 0) {
745 error("failed writing temp file");
758 return reverse @rets;