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 post-update 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 if ($file =~ m/^"(.*)"$/) {
312 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
314 $file =~ s/^\Q$prefix\E//;
316 push @{ $ci{'details'} }, {
317 'file' => decode_utf8($file),
318 'sha1_from' => $sha1_from[0],
319 'sha1_to' => $sha1_to,
330 sub git_commit_info ($;$) { #{{{
331 # Return an array of commit info hashes of num commits (default: 1)
332 # starting from the given sha1sum.
334 my ($sha1, $num) = @_;
338 my @raw_lines = run_or_die('git', 'log', "--max-count=$num",
339 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
340 '-r', $sha1, '--', '.');
341 my ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
344 while (my $parsed = parse_diff_tree(($prefix or ""), \@raw_lines)) {
348 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
350 return wantarray ? @ci : $ci[0];
353 sub git_sha1 (;$) { #{{{
354 # Return head sha1sum (of given file).
356 my $file = shift || q{--};
358 # Ignore error since a non-existing file might be given.
359 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
362 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
363 } else { debug("Empty sha1sum for '$file'.") }
364 return defined $sha1 ? $sha1 : q{};
367 sub rcs_update () { #{{{
368 # Update working directory.
370 if (length $config{gitorigin_branch}) {
371 run_or_cry('git', 'pull', $config{gitorigin_branch});
375 sub rcs_prepedit ($) { #{{{
376 # Return the commit sha1sum of the file when editing begins.
377 # This will be later used in rcs_commit if a merge is required.
381 return git_sha1($file);
384 sub rcs_commit ($$$;$$) { #{{{
385 # Try to commit the page; returns undef on _success_ and
386 # a version of the page with the rcs's conflict markers on
389 my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
391 # Check to see if the page has been changed by someone else since
392 # rcs_prepedit was called.
393 my $cur = git_sha1($file);
394 my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
396 if (defined $cur && defined $prev && $cur ne $prev) {
397 my $conflict = merge_past($prev, $file, $dummy_commit_msg);
398 return $conflict if defined $conflict;
402 return rcs_commit_staged($message, $user, $ipaddr);
405 sub rcs_commit_staged ($$$) {
406 # Commits all staged changes. Changes can be staged using rcs_add,
407 # rcs_remove, and rcs_rename.
408 my ($message, $user, $ipaddr)=@_;
410 # Set the commit author and email to the web committer.
412 if (defined $user || defined $ipaddr) {
413 my $u=defined $user ? $user : $ipaddr;
414 $ENV{GIT_AUTHOR_NAME}=$u;
415 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
418 $message = IkiWiki::possibly_foolish_untaint($message);
420 if ($message !~ /\S/) {
421 # Force git to allow empty commit messages.
422 # (If this version of git supports it.)
423 my ($version)=`git --version` =~ /git version (.*)/;
424 if ($version ge "1.5.4") {
425 push @opts, '--cleanup=verbatim';
432 # git commit returns non-zero if file has not been really changed.
433 # so we should ignore its exit status (hence run_or_non).
434 if (run_or_non('git', 'commit', @opts, '-m', $message)) {
435 if (length $config{gitorigin_branch}) {
436 run_or_cry('git', 'push', $config{gitorigin_branch});
441 return undef; # success
444 sub rcs_add ($) { # {{{
445 # Add file to archive.
449 run_or_cry('git', 'add', $file);
452 sub rcs_remove ($) { # {{{
453 # Remove file from archive.
457 run_or_cry('git', 'rm', '-f', $file);
460 sub rcs_rename ($$) { # {{{
461 my ($src, $dest) = @_;
463 run_or_cry('git', 'mv', '-f', $src, $dest);
466 sub rcs_recentchanges ($) { #{{{
467 # List of recent changes.
471 eval q{use Date::Parse};
475 foreach my $ci (git_commit_info('HEAD', $num)) {
476 # Skip redundant commits.
477 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
479 my ($sha1, $when) = (
481 $ci->{'author_epoch'}
485 foreach my $detail (@{ $ci->{'details'} }) {
486 my $file = $detail->{'file'};
488 my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
489 $diffurl =~ s/\[\[file\]\]/$file/go;
490 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
491 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
492 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
495 page => pagename($file),
502 foreach my $line (@{$ci->{'comment'}}) {
503 $pastblank=1 if $line eq '';
504 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
505 push @messages, { line => $line };
508 my $user=$ci->{'author_username'};
509 my $web_commit = ($ci->{'author'} =~ /\@web>/);
511 # compatability code for old web commit messages
513 defined $messages[0] &&
514 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
515 $user = defined $2 ? "$2" : "$3";
516 $messages[0]->{line} = $4;
523 committype => $web_commit ? "web" : "git",
525 message => [@messages],
529 last if @rets >= $num;
535 sub rcs_diff ($) { #{{{
537 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
539 foreach my $line (run_or_non("git", "show", $sha1)) {
540 if (@lines || $line=~/^diff --git/) {
541 push @lines, $line."\n";
548 return join("", @lines);
552 sub rcs_getctime ($) { #{{{
554 # Remove srcdir prefix
555 $file =~ s/^\Q$config{srcdir}\E\/?//;
557 my $sha1 = git_sha1($file);
558 my $ci = git_commit_info($sha1);
559 my $ctime = $ci->{'author_epoch'};
560 debug("ctime for '$file': ". localtime($ctime));