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
14 hook(type => "checkconfig", id => "git", call => \&checkconfig);
15 hook(type => "getsetup", id => "git", call => \&getsetup);
16 hook(type => "rcs", id => "rcs_update", call => \&rcs_update);
17 hook(type => "rcs", id => "rcs_prepedit", call => \&rcs_prepedit);
18 hook(type => "rcs", id => "rcs_commit", call => \&rcs_commit);
19 hook(type => "rcs", id => "rcs_commit_staged", call => \&rcs_commit_staged);
20 hook(type => "rcs", id => "rcs_add", call => \&rcs_add);
21 hook(type => "rcs", id => "rcs_remove", call => \&rcs_remove);
22 hook(type => "rcs", id => "rcs_rename", call => \&rcs_rename);
23 hook(type => "rcs", id => "rcs_recentchanges", call => \&rcs_recentchanges);
24 hook(type => "rcs", id => "rcs_diff", call => \&rcs_diff);
25 hook(type => "rcs", id => "rcs_getctime", call => \&rcs_getctime);
28 sub checkconfig () { #{{{
29 if (! defined $config{gitorigin_branch}) {
30 $config{gitorigin_branch}="origin";
32 if (! defined $config{gitmaster_branch}) {
33 $config{gitmaster_branch}="master";
35 if (defined $config{git_wrapper} && length $config{git_wrapper}) {
36 push @{$config{wrappers}}, {
37 wrapper => $config{git_wrapper},
38 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
43 sub getsetup () { #{{{
47 example => "/git/wiki.git/hooks/post-update",
48 description => "git post-update hook to generate",
55 description => "mode for git_wrapper (can safely be made suid)",
61 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]]",
62 description => "gitweb url to show file history ([[file]] substituted)",
68 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=blobdiff;h=[[sha1_to]];hp=[[sha1_from]];hb=[[sha1_parent]];f=[[file]]",
69 description => "gitweb url to show a diff ([[sha1_to]], [[sha1_from]], [[sha1_parent]], and [[file]] substituted)",
76 description => "where to pull and push changes (set to empty string to disable)",
83 description => "branch that the wiki is stored in",
89 sub safe_git (&@) { #{{{
90 # Start a child process safely without resorting /bin/sh.
91 # Return command output or success state (in scalar context).
93 my ($error_handler, @cmdline) = @_;
95 my $pid = open my $OUT, "-|";
97 error("Cannot fork: $!") if !defined $pid;
101 # Git commands want to be in wc.
102 chdir $config{srcdir}
103 or error("Cannot chdir to $config{srcdir}: $!");
104 exec @cmdline or error("Cannot exec '@cmdline': $!");
116 $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
118 return wantarray ? @lines : ($? == 0);
120 # Convenient wrappers.
121 sub run_or_die ($@) { safe_git(\&error, @_) }
122 sub run_or_cry ($@) { safe_git(sub { warn @_ }, @_) }
123 sub run_or_non ($@) { safe_git(undef, @_) }
126 sub merge_past ($$$) { #{{{
127 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
128 # Git merge commands work with the committed changes, except in the
129 # implicit case of '-m' of git checkout(1). So we should invent a
130 # kludge here. In principle, we need to create a throw-away branch
131 # in preparing for the merge itself. Since branches are cheap (and
132 # branching is fast), this shouldn't cost high.
134 # The main problem is the presence of _uncommitted_ local changes. One
135 # possible approach to get rid of this situation could be that we first
136 # make a temporary commit in the master branch and later restore the
137 # initial state (this is possible since Git has the ability to undo a
138 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
141 # - create a diff of HEAD:current-sha1
143 # - create a dummy branch and switch to it
144 # - rewind to past (reset --hard to the current-sha1)
145 # - apply the diff and commit
146 # - switch to master and do the merge with the dummy branch
147 # - make a soft reset (undo the last commit of master)
149 # The above method has some drawbacks: (1) it needs a redundant commit
150 # just to get rid of local changes, (2) somewhat slow because of the
151 # required system forks. Until someone points a more straight method
152 # (which I would be grateful) I have implemented an alternative method.
153 # In this approach, we hide all the modified files from Git by renaming
154 # them (using the 'rename' builtin) and later restore those files in
155 # the throw-away branch (that is, we put the files themselves instead
156 # of applying a patch).
158 my ($sha1, $file, $message) = @_;
160 my @undo; # undo stack for cleanup in case of an error
161 my $conflict; # file content with conflict markers
164 # Hide local changes from Git by renaming the modified file.
165 # Relative paths must be converted to absolute for renaming.
166 my ($target, $hidden) = (
167 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
169 rename($target, $hidden)
170 or error("rename '$target' to '$hidden' failed: $!");
171 # Ensure to restore the renamed file on error.
173 return if ! -e "$hidden"; # already renamed
174 rename($hidden, $target)
175 or warn "rename '$hidden' to '$target' failed: $!";
178 my $branch = "throw_away_${sha1}"; # supposed to be unique
180 # Create a throw-away branch and rewind backward.
181 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
182 run_or_die('git', 'branch', $branch, $sha1);
184 # Switch to throw-away branch for the merge operation.
186 if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
187 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
190 run_or_die('git', 'checkout', $branch);
192 # Put the modified file in _this_ branch.
193 rename($hidden, $target)
194 or error("rename '$hidden' to '$target' failed: $!");
196 # _Silently_ commit all modifications in the current branch.
197 run_or_non('git', 'commit', '-m', $message, '-a');
198 # ... and re-switch to master.
199 run_or_die('git', 'checkout', $config{gitmaster_branch});
201 # Attempt to merge without complaining.
202 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
203 $conflict = readfile($target);
204 run_or_die('git', 'reset', '--hard');
209 # Process undo stack (in reverse order). By policy cleanup
210 # actions should normally print a warning on failure.
211 while (my $handle = pop @undo) {
215 error("Git merge failed!\n$failure\n") if $failure;
220 sub parse_diff_tree ($@) { #{{{
221 # Parse the raw diff tree chunk and return the info hash.
222 # See git-diff-tree(1) for the syntax.
224 my ($prefix, $dt_ref) = @_;
227 return if !defined @{ $dt_ref } ||
228 !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
232 while (my $line = shift @{ $dt_ref }) {
233 return if $line !~ m/^(.+) ($sha1_pattern)/;
240 # Identification lines for the commit.
241 while (my $line = shift @{ $dt_ref }) {
242 # Regexps are semi-stolen from gitweb.cgi.
243 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
246 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
247 # XXX: collecting in reverse order
248 push @{ $ci{'parents'} }, $1;
250 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
251 my ($who, $name, $epoch, $tz) =
255 $ci{ "${who}_epoch" } = $epoch;
256 $ci{ "${who}_tz" } = $tz;
258 if ($name =~ m/^[^<]+\s+<([^@>]+)/) {
259 $ci{"${who}_username"} = $1;
261 elsif ($name =~ m/^([^<]+)\s+<>$/) {
262 $ci{"${who}_username"} = $1;
265 $ci{"${who}_username"} = $name;
268 elsif ($line =~ m/^$/) {
269 # Trailing empty line signals next section.
274 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
276 if (defined $ci{'parents'}) {
277 $ci{'parent'} = @{ $ci{'parents'} }[0];
280 $ci{'parent'} = 0 x 40;
283 # Commit message (optional).
284 while ($dt_ref->[0] =~ /^ /) {
285 my $line = shift @{ $dt_ref };
287 push @{ $ci{'comment'} }, $line;
289 shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
292 while (my $line = shift @{ $dt_ref }) {
294 (:+) # number of parents
295 ([^\t]+)\t # modes, sha1, status
298 my $num_parents = length $1;
299 my @tmp = split(" ", $2);
300 my ($file, $file_to) = split("\t", $3);
301 my @mode_from = splice(@tmp, 0, $num_parents);
302 my $mode_to = shift(@tmp);
303 my @sha1_from = splice(@tmp, 0, $num_parents);
304 my $sha1_to = shift(@tmp);
305 my $status = shift(@tmp);
307 if ($file =~ m/^"(.*)"$/) {
308 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
310 $file =~ s/^\Q$prefix\E//;
312 push @{ $ci{'details'} }, {
313 'file' => decode_utf8($file),
314 'sha1_from' => $sha1_from[0],
315 'sha1_to' => $sha1_to,
326 sub git_commit_info ($;$) { #{{{
327 # Return an array of commit info hashes of num commits (default: 1)
328 # starting from the given sha1sum.
330 my ($sha1, $num) = @_;
334 my @raw_lines = run_or_die('git', 'log', "--max-count=$num",
335 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
336 '-r', $sha1, '--', '.');
337 my ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
340 while (my $parsed = parse_diff_tree(($prefix or ""), \@raw_lines)) {
344 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
346 return wantarray ? @ci : $ci[0];
349 sub git_sha1 (;$) { #{{{
350 # Return head sha1sum (of given file).
352 my $file = shift || q{--};
354 # Ignore error since a non-existing file might be given.
355 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
358 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
359 } else { debug("Empty sha1sum for '$file'.") }
360 return defined $sha1 ? $sha1 : q{};
363 sub rcs_update () { #{{{
364 # Update working directory.
366 if (length $config{gitorigin_branch}) {
367 run_or_cry('git', 'pull', $config{gitorigin_branch});
371 sub rcs_prepedit ($) { #{{{
372 # Return the commit sha1sum of the file when editing begins.
373 # This will be later used in rcs_commit if a merge is required.
377 return git_sha1($file);
380 sub rcs_commit ($$$;$$) { #{{{
381 # Try to commit the page; returns undef on _success_ and
382 # a version of the page with the rcs's conflict markers on
385 my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
387 # Check to see if the page has been changed by someone else since
388 # rcs_prepedit was called.
389 my $cur = git_sha1($file);
390 my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
392 if (defined $cur && defined $prev && $cur ne $prev) {
393 my $conflict = merge_past($prev, $file, $dummy_commit_msg);
394 return $conflict if defined $conflict;
398 return rcs_commit_staged($message, $user, $ipaddr);
401 sub rcs_commit_staged ($$$) {
402 # Commits all staged changes. Changes can be staged using rcs_add,
403 # rcs_remove, and rcs_rename.
404 my ($message, $user, $ipaddr)=@_;
406 # Set the commit author and email to the web committer.
408 if (defined $user || defined $ipaddr) {
409 my $u=defined $user ? $user : $ipaddr;
410 $ENV{GIT_AUTHOR_NAME}=$u;
411 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
414 $message = IkiWiki::possibly_foolish_untaint($message);
416 if ($message !~ /\S/) {
417 # Force git to allow empty commit messages.
418 # (If this version of git supports it.)
419 my ($version)=`git --version` =~ /git version (.*)/;
420 if ($version ge "1.5.4") {
421 push @opts, '--cleanup=verbatim';
428 # git commit returns non-zero if file has not been really changed.
429 # so we should ignore its exit status (hence run_or_non).
430 if (run_or_non('git', 'commit', @opts, '-m', $message)) {
431 if (length $config{gitorigin_branch}) {
432 run_or_cry('git', 'push', $config{gitorigin_branch});
437 return undef; # success
440 sub rcs_add ($) { # {{{
441 # Add file to archive.
445 run_or_cry('git', 'add', $file);
448 sub rcs_remove ($) { # {{{
449 # Remove file from archive.
453 run_or_cry('git', 'rm', '-f', $file);
456 sub rcs_rename ($$) { # {{{
457 my ($src, $dest) = @_;
459 run_or_cry('git', 'mv', '-f', $src, $dest);
462 sub rcs_recentchanges ($) { #{{{
463 # List of recent changes.
467 eval q{use Date::Parse};
471 foreach my $ci (git_commit_info('HEAD', $num)) {
472 # Skip redundant commits.
473 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
475 my ($sha1, $when) = (
477 $ci->{'author_epoch'}
481 foreach my $detail (@{ $ci->{'details'} }) {
482 my $file = $detail->{'file'};
484 my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
485 $diffurl =~ s/\[\[file\]\]/$file/go;
486 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
487 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
488 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
491 page => pagename($file),
498 foreach my $line (@{$ci->{'comment'}}) {
499 $pastblank=1 if $line eq '';
500 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
501 push @messages, { line => $line };
504 my $user=$ci->{'author_username'};
505 my $web_commit = ($ci->{'author'} =~ /\@web>/);
507 # compatability code for old web commit messages
509 defined $messages[0] &&
510 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
511 $user = defined $2 ? "$2" : "$3";
512 $messages[0]->{line} = $4;
519 committype => $web_commit ? "web" : "git",
521 message => [@messages],
525 last if @rets >= $num;
531 sub rcs_diff ($) { #{{{
533 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
535 foreach my $line (run_or_non("git", "show", $sha1)) {
536 if (@lines || $line=~/^diff --git/) {
537 push @lines, $line."\n";
544 return join("", @lines);
548 sub rcs_getctime ($) { #{{{
550 # Remove srcdir prefix
551 $file =~ s/^\Q$config{srcdir}\E\/?//;
553 my $sha1 = git_sha1($file);
554 my $ci = git_commit_info($sha1);
555 my $ctime = $ci->{'author_epoch'};
556 debug("ctime for '$file': ". localtime($ctime));