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 () { #{{{
46 safe => 0, # rcs plugin
51 example => "/git/wiki.git/hooks/post-update",
52 description => "git hook to generate",
59 description => "mode for git_wrapper (can safely be made suid)",
65 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]]",
66 description => "gitweb url to show file history ([[file]] substituted)",
72 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=blobdiff;h=[[sha1_to]];hp=[[sha1_from]];hb=[[sha1_parent]];f=[[file]]",
73 description => "gitweb url to show a diff ([[sha1_to]], [[sha1_from]], [[sha1_parent]], and [[file]] substituted)",
80 description => "where to pull and push changes (set to empty string to disable)",
87 description => "branch that the wiki is stored in",
93 sub safe_git (&@) { #{{{
94 # Start a child process safely without resorting /bin/sh.
95 # Return command output or success state (in scalar context).
97 my ($error_handler, @cmdline) = @_;
99 my $pid = open my $OUT, "-|";
101 error("Cannot fork: $!") if !defined $pid;
105 # Git commands want to be in wc.
106 chdir $config{srcdir}
107 or error("Cannot chdir to $config{srcdir}: $!");
108 exec @cmdline or error("Cannot exec '@cmdline': $!");
120 $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
122 return wantarray ? @lines : ($? == 0);
124 # Convenient wrappers.
125 sub run_or_die ($@) { safe_git(\&error, @_) }
126 sub run_or_cry ($@) { safe_git(sub { warn @_ }, @_) }
127 sub run_or_non ($@) { safe_git(undef, @_) }
130 sub merge_past ($$$) { #{{{
131 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
132 # Git merge commands work with the committed changes, except in the
133 # implicit case of '-m' of git checkout(1). So we should invent a
134 # kludge here. In principle, we need to create a throw-away branch
135 # in preparing for the merge itself. Since branches are cheap (and
136 # branching is fast), this shouldn't cost high.
138 # The main problem is the presence of _uncommitted_ local changes. One
139 # possible approach to get rid of this situation could be that we first
140 # make a temporary commit in the master branch and later restore the
141 # initial state (this is possible since Git has the ability to undo a
142 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
145 # - create a diff of HEAD:current-sha1
147 # - create a dummy branch and switch to it
148 # - rewind to past (reset --hard to the current-sha1)
149 # - apply the diff and commit
150 # - switch to master and do the merge with the dummy branch
151 # - make a soft reset (undo the last commit of master)
153 # The above method has some drawbacks: (1) it needs a redundant commit
154 # just to get rid of local changes, (2) somewhat slow because of the
155 # required system forks. Until someone points a more straight method
156 # (which I would be grateful) I have implemented an alternative method.
157 # In this approach, we hide all the modified files from Git by renaming
158 # them (using the 'rename' builtin) and later restore those files in
159 # the throw-away branch (that is, we put the files themselves instead
160 # of applying a patch).
162 my ($sha1, $file, $message) = @_;
164 my @undo; # undo stack for cleanup in case of an error
165 my $conflict; # file content with conflict markers
168 # Hide local changes from Git by renaming the modified file.
169 # Relative paths must be converted to absolute for renaming.
170 my ($target, $hidden) = (
171 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
173 rename($target, $hidden)
174 or error("rename '$target' to '$hidden' failed: $!");
175 # Ensure to restore the renamed file on error.
177 return if ! -e "$hidden"; # already renamed
178 rename($hidden, $target)
179 or warn "rename '$hidden' to '$target' failed: $!";
182 my $branch = "throw_away_${sha1}"; # supposed to be unique
184 # Create a throw-away branch and rewind backward.
185 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
186 run_or_die('git', 'branch', $branch, $sha1);
188 # Switch to throw-away branch for the merge operation.
190 if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
191 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
194 run_or_die('git', 'checkout', $branch);
196 # Put the modified file in _this_ branch.
197 rename($hidden, $target)
198 or error("rename '$hidden' to '$target' failed: $!");
200 # _Silently_ commit all modifications in the current branch.
201 run_or_non('git', 'commit', '-m', $message, '-a');
202 # ... and re-switch to master.
203 run_or_die('git', 'checkout', $config{gitmaster_branch});
205 # Attempt to merge without complaining.
206 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
207 $conflict = readfile($target);
208 run_or_die('git', 'reset', '--hard');
213 # Process undo stack (in reverse order). By policy cleanup
214 # actions should normally print a warning on failure.
215 while (my $handle = pop @undo) {
219 error("Git merge failed!\n$failure\n") if $failure;
224 sub parse_diff_tree ($@) { #{{{
225 # Parse the raw diff tree chunk and return the info hash.
226 # See git-diff-tree(1) for the syntax.
228 my ($prefix, $dt_ref) = @_;
231 return if !defined @{ $dt_ref } ||
232 !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
236 while (my $line = shift @{ $dt_ref }) {
237 return if $line !~ m/^(.+) ($sha1_pattern)/;
244 # Identification lines for the commit.
245 while (my $line = shift @{ $dt_ref }) {
246 # Regexps are semi-stolen from gitweb.cgi.
247 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
250 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
251 # XXX: collecting in reverse order
252 push @{ $ci{'parents'} }, $1;
254 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
255 my ($who, $name, $epoch, $tz) =
259 $ci{ "${who}_epoch" } = $epoch;
260 $ci{ "${who}_tz" } = $tz;
262 if ($name =~ m/^[^<]+\s+<([^@>]+)/) {
263 $ci{"${who}_username"} = $1;
265 elsif ($name =~ m/^([^<]+)\s+<>$/) {
266 $ci{"${who}_username"} = $1;
269 $ci{"${who}_username"} = $name;
272 elsif ($line =~ m/^$/) {
273 # Trailing empty line signals next section.
278 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
280 if (defined $ci{'parents'}) {
281 $ci{'parent'} = @{ $ci{'parents'} }[0];
284 $ci{'parent'} = 0 x 40;
287 # Commit message (optional).
288 while ($dt_ref->[0] =~ /^ /) {
289 my $line = shift @{ $dt_ref };
291 push @{ $ci{'comment'} }, $line;
293 shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
296 while (my $line = shift @{ $dt_ref }) {
298 (:+) # number of parents
299 ([^\t]+)\t # modes, sha1, status
302 my $num_parents = length $1;
303 my @tmp = split(" ", $2);
304 my ($file, $file_to) = split("\t", $3);
305 my @mode_from = splice(@tmp, 0, $num_parents);
306 my $mode_to = shift(@tmp);
307 my @sha1_from = splice(@tmp, 0, $num_parents);
308 my $sha1_to = shift(@tmp);
309 my $status = shift(@tmp);
311 # git does not output utf-8 filenames, but instead
312 # double-quotes them with the utf-8 characters
313 # escaped as \nnn\nnn.
314 if ($file =~ m/^"(.*)"$/) {
315 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
317 $file =~ s/^\Q$prefix\E//;
319 push @{ $ci{'details'} }, {
320 'file' => decode("utf8", $file),
321 'sha1_from' => $sha1_from[0],
322 'sha1_to' => $sha1_to,
333 sub git_commit_info ($;$) { #{{{
334 # Return an array of commit info hashes of num commits (default: 1)
335 # starting from the given sha1sum.
337 my ($sha1, $num) = @_;
341 my @raw_lines = run_or_die('git', 'log', "--max-count=$num",
342 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
343 '-r', $sha1, '--', '.');
344 my ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
347 while (my $parsed = parse_diff_tree(($prefix or ""), \@raw_lines)) {
351 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
353 return wantarray ? @ci : $ci[0];
356 sub git_sha1 (;$) { #{{{
357 # Return head sha1sum (of given file).
359 my $file = shift || q{--};
361 # Ignore error since a non-existing file might be given.
362 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
365 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
366 } else { debug("Empty sha1sum for '$file'.") }
367 return defined $sha1 ? $sha1 : q{};
370 sub rcs_update () { #{{{
371 # Update working directory.
373 if (length $config{gitorigin_branch}) {
374 run_or_cry('git', 'pull', $config{gitorigin_branch});
378 sub rcs_prepedit ($) { #{{{
379 # Return the commit sha1sum of the file when editing begins.
380 # This will be later used in rcs_commit if a merge is required.
384 return git_sha1($file);
387 sub rcs_commit ($$$;$$) { #{{{
388 # Try to commit the page; returns undef on _success_ and
389 # a version of the page with the rcs's conflict markers on
392 my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
394 # Check to see if the page has been changed by someone else since
395 # rcs_prepedit was called.
396 my $cur = git_sha1($file);
397 my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
399 if (defined $cur && defined $prev && $cur ne $prev) {
400 my $conflict = merge_past($prev, $file, $dummy_commit_msg);
401 return $conflict if defined $conflict;
405 return rcs_commit_staged($message, $user, $ipaddr);
408 sub rcs_commit_staged ($$$) {
409 # Commits all staged changes. Changes can be staged using rcs_add,
410 # rcs_remove, and rcs_rename.
411 my ($message, $user, $ipaddr)=@_;
413 # Set the commit author and email to the web committer.
415 if (defined $user || defined $ipaddr) {
416 my $u=defined $user ? $user : $ipaddr;
417 $ENV{GIT_AUTHOR_NAME}=$u;
418 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
421 $message = IkiWiki::possibly_foolish_untaint($message);
423 if ($message !~ /\S/) {
424 # Force git to allow empty commit messages.
425 # (If this version of git supports it.)
426 my ($version)=`git --version` =~ /git version (.*)/;
427 if ($version ge "1.5.4") {
428 push @opts, '--cleanup=verbatim';
435 # git commit returns non-zero if file has not been really changed.
436 # so we should ignore its exit status (hence run_or_non).
437 if (run_or_non('git', 'commit', @opts, '-m', $message)) {
438 if (length $config{gitorigin_branch}) {
439 run_or_cry('git', 'push', $config{gitorigin_branch});
444 return undef; # success
447 sub rcs_add ($) { # {{{
448 # Add file to archive.
452 run_or_cry('git', 'add', $file);
455 sub rcs_remove ($) { # {{{
456 # Remove file from archive.
460 run_or_cry('git', 'rm', '-f', $file);
463 sub rcs_rename ($$) { # {{{
464 my ($src, $dest) = @_;
466 run_or_cry('git', 'mv', '-f', $src, $dest);
469 sub rcs_recentchanges ($) { #{{{
470 # List of recent changes.
474 eval q{use Date::Parse};
478 foreach my $ci (git_commit_info('HEAD', $num)) {
479 # Skip redundant commits.
480 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
482 my ($sha1, $when) = (
484 $ci->{'author_epoch'}
488 foreach my $detail (@{ $ci->{'details'} }) {
489 my $file = $detail->{'file'};
491 my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
492 $diffurl =~ s/\[\[file\]\]/$file/go;
493 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
494 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
495 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
498 page => pagename($file),
505 foreach my $line (@{$ci->{'comment'}}) {
506 $pastblank=1 if $line eq '';
507 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
508 push @messages, { line => $line };
511 my $user=$ci->{'author_username'};
512 my $web_commit = ($ci->{'author'} =~ /\@web>/);
514 # compatability code for old web commit messages
516 defined $messages[0] &&
517 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
518 $user = defined $2 ? "$2" : "$3";
519 $messages[0]->{line} = $4;
526 committype => $web_commit ? "web" : "git",
528 message => [@messages],
532 last if @rets >= $num;
538 sub rcs_diff ($) { #{{{
540 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
542 foreach my $line (run_or_non("git", "show", $sha1)) {
543 if (@lines || $line=~/^diff --git/) {
544 push @lines, $line."\n";
551 return join("", @lines);
555 sub rcs_getctime ($) { #{{{
557 # Remove srcdir prefix
558 $file =~ s/^\Q$config{srcdir}\E\/?//;
560 my $sha1 = git_sha1($file);
561 my $ci = git_commit_info($sha1);
562 my $ctime = $ci->{'author_epoch'};
563 debug("ctime for '$file': ". localtime($ctime));