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{diffurl}) {
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} && length $config{git_wrapper}) {
39 push @{$config{wrappers}}, {
40 wrapper => $config{git_wrapper},
41 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
46 sub getsetup () { #{{{
50 example => "/git/wiki.git/hooks/post-update",
51 description => "git post-update executable to generate",
58 description => "mode for git_wrapper (can safely be made suid)",
64 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]]",
65 description => "gitweb url to show file history ([[file]] substituted)",
71 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=blobdiff;h=[[sha1_to]];hp=[[sha1_from]];hb=[[sha1_parent]];f=[[file]]",
72 description => "gitweb url to show a diff ([[sha1_to]], [[sha1_from]], [[sha1_parent]], and [[file]] substituted)",
79 description => "where to pull and push changes (set to empty string to disable)",
86 description => "branch that the wiki is stored in",
92 sub safe_git (&@) { #{{{
93 # Start a child process safely without resorting /bin/sh.
94 # Return command output or success state (in scalar context).
96 my ($error_handler, @cmdline) = @_;
98 my $pid = open my $OUT, "-|";
100 error("Cannot fork: $!") if !defined $pid;
104 # Git commands want to be in wc.
105 chdir $config{srcdir}
106 or error("Cannot chdir to $config{srcdir}: $!");
107 exec @cmdline or error("Cannot exec '@cmdline': $!");
119 $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
121 return wantarray ? @lines : ($? == 0);
123 # Convenient wrappers.
124 sub run_or_die ($@) { safe_git(\&error, @_) }
125 sub run_or_cry ($@) { safe_git(sub { warn @_ }, @_) }
126 sub run_or_non ($@) { safe_git(undef, @_) }
129 sub merge_past ($$$) { #{{{
130 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
131 # Git merge commands work with the committed changes, except in the
132 # implicit case of '-m' of git checkout(1). So we should invent a
133 # kludge here. In principle, we need to create a throw-away branch
134 # in preparing for the merge itself. Since branches are cheap (and
135 # branching is fast), this shouldn't cost high.
137 # The main problem is the presence of _uncommitted_ local changes. One
138 # possible approach to get rid of this situation could be that we first
139 # make a temporary commit in the master branch and later restore the
140 # initial state (this is possible since Git has the ability to undo a
141 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
144 # - create a diff of HEAD:current-sha1
146 # - create a dummy branch and switch to it
147 # - rewind to past (reset --hard to the current-sha1)
148 # - apply the diff and commit
149 # - switch to master and do the merge with the dummy branch
150 # - make a soft reset (undo the last commit of master)
152 # The above method has some drawbacks: (1) it needs a redundant commit
153 # just to get rid of local changes, (2) somewhat slow because of the
154 # required system forks. Until someone points a more straight method
155 # (which I would be grateful) I have implemented an alternative method.
156 # In this approach, we hide all the modified files from Git by renaming
157 # them (using the 'rename' builtin) and later restore those files in
158 # the throw-away branch (that is, we put the files themselves instead
159 # of applying a patch).
161 my ($sha1, $file, $message) = @_;
163 my @undo; # undo stack for cleanup in case of an error
164 my $conflict; # file content with conflict markers
167 # Hide local changes from Git by renaming the modified file.
168 # Relative paths must be converted to absolute for renaming.
169 my ($target, $hidden) = (
170 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
172 rename($target, $hidden)
173 or error("rename '$target' to '$hidden' failed: $!");
174 # Ensure to restore the renamed file on error.
176 return if ! -e "$hidden"; # already renamed
177 rename($hidden, $target)
178 or warn "rename '$hidden' to '$target' failed: $!";
181 my $branch = "throw_away_${sha1}"; # supposed to be unique
183 # Create a throw-away branch and rewind backward.
184 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
185 run_or_die('git', 'branch', $branch, $sha1);
187 # Switch to throw-away branch for the merge operation.
189 if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
190 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
193 run_or_die('git', 'checkout', $branch);
195 # Put the modified file in _this_ branch.
196 rename($hidden, $target)
197 or error("rename '$hidden' to '$target' failed: $!");
199 # _Silently_ commit all modifications in the current branch.
200 run_or_non('git', 'commit', '-m', $message, '-a');
201 # ... and re-switch to master.
202 run_or_die('git', 'checkout', $config{gitmaster_branch});
204 # Attempt to merge without complaining.
205 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
206 $conflict = readfile($target);
207 run_or_die('git', 'reset', '--hard');
212 # Process undo stack (in reverse order). By policy cleanup
213 # actions should normally print a warning on failure.
214 while (my $handle = pop @undo) {
218 error("Git merge failed!\n$failure\n") if $failure;
223 sub parse_diff_tree ($@) { #{{{
224 # Parse the raw diff tree chunk and return the info hash.
225 # See git-diff-tree(1) for the syntax.
227 my ($prefix, $dt_ref) = @_;
230 return if !defined @{ $dt_ref } ||
231 !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
235 while (my $line = shift @{ $dt_ref }) {
236 return if $line !~ m/^(.+) ($sha1_pattern)/;
243 # Identification lines for the commit.
244 while (my $line = shift @{ $dt_ref }) {
245 # Regexps are semi-stolen from gitweb.cgi.
246 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
249 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
250 # XXX: collecting in reverse order
251 push @{ $ci{'parents'} }, $1;
253 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
254 my ($who, $name, $epoch, $tz) =
258 $ci{ "${who}_epoch" } = $epoch;
259 $ci{ "${who}_tz" } = $tz;
261 if ($name =~ m/^[^<]+\s+<([^@>]+)/) {
262 $ci{"${who}_username"} = $1;
264 elsif ($name =~ m/^([^<]+)\s+<>$/) {
265 $ci{"${who}_username"} = $1;
268 $ci{"${who}_username"} = $name;
271 elsif ($line =~ m/^$/) {
272 # Trailing empty line signals next section.
277 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
279 if (defined $ci{'parents'}) {
280 $ci{'parent'} = @{ $ci{'parents'} }[0];
283 $ci{'parent'} = 0 x 40;
286 # Commit message (optional).
287 while ($dt_ref->[0] =~ /^ /) {
288 my $line = shift @{ $dt_ref };
290 push @{ $ci{'comment'} }, $line;
292 shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
295 while (my $line = shift @{ $dt_ref }) {
297 (:+) # number of parents
298 ([^\t]+)\t # modes, sha1, status
301 my $num_parents = length $1;
302 my @tmp = split(" ", $2);
303 my ($file, $file_to) = split("\t", $3);
304 my @mode_from = splice(@tmp, 0, $num_parents);
305 my $mode_to = shift(@tmp);
306 my @sha1_from = splice(@tmp, 0, $num_parents);
307 my $sha1_to = shift(@tmp);
308 my $status = shift(@tmp);
310 if ($file =~ m/^"(.*)"$/) {
311 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
313 $file =~ s/^\Q$prefix\E//;
315 push @{ $ci{'details'} }, {
316 'file' => decode_utf8($file),
317 'sha1_from' => $sha1_from[0],
318 'sha1_to' => $sha1_to,
329 sub git_commit_info ($;$) { #{{{
330 # Return an array of commit info hashes of num commits (default: 1)
331 # starting from the given sha1sum.
333 my ($sha1, $num) = @_;
337 my @raw_lines = run_or_die('git', 'log', "--max-count=$num",
338 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
339 '-r', $sha1, '--', '.');
340 my ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
343 while (my $parsed = parse_diff_tree(($prefix or ""), \@raw_lines)) {
347 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
349 return wantarray ? @ci : $ci[0];
352 sub git_sha1 (;$) { #{{{
353 # Return head sha1sum (of given file).
355 my $file = shift || q{--};
357 # Ignore error since a non-existing file might be given.
358 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
361 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
362 } else { debug("Empty sha1sum for '$file'.") }
363 return defined $sha1 ? $sha1 : q{};
366 sub rcs_update () { #{{{
367 # Update working directory.
369 if (length $config{gitorigin_branch}) {
370 run_or_cry('git', 'pull', $config{gitorigin_branch});
374 sub rcs_prepedit ($) { #{{{
375 # Return the commit sha1sum of the file when editing begins.
376 # This will be later used in rcs_commit if a merge is required.
380 return git_sha1($file);
383 sub rcs_commit ($$$;$$) { #{{{
384 # Try to commit the page; returns undef on _success_ and
385 # a version of the page with the rcs's conflict markers on
388 my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
390 # Check to see if the page has been changed by someone else since
391 # rcs_prepedit was called.
392 my $cur = git_sha1($file);
393 my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
395 if (defined $cur && defined $prev && $cur ne $prev) {
396 my $conflict = merge_past($prev, $file, $dummy_commit_msg);
397 return $conflict if defined $conflict;
401 return rcs_commit_staged($message, $user, $ipaddr);
404 sub rcs_commit_staged ($$$) {
405 # Commits all staged changes. Changes can be staged using rcs_add,
406 # rcs_remove, and rcs_rename.
407 my ($message, $user, $ipaddr)=@_;
409 # Set the commit author and email to the web committer.
411 if (defined $user || defined $ipaddr) {
412 my $u=defined $user ? $user : $ipaddr;
413 $ENV{GIT_AUTHOR_NAME}=$u;
414 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
417 # git commit returns non-zero if file has not been really changed.
418 # so we should ignore its exit status (hence run_or_non).
419 $message = IkiWiki::possibly_foolish_untaint($message);
420 if (run_or_non('git', 'commit', '--cleanup=verbatim',
421 '-q', '-m', $message)) {
422 if (length $config{gitorigin_branch}) {
423 run_or_cry('git', 'push', $config{gitorigin_branch});
428 return undef; # success
431 sub rcs_add ($) { # {{{
432 # Add file to archive.
436 run_or_cry('git', 'add', $file);
439 sub rcs_remove ($) { # {{{
440 # Remove file from archive.
444 run_or_cry('git', 'rm', '-f', $file);
447 sub rcs_rename ($$) { # {{{
448 my ($src, $dest) = @_;
450 run_or_cry('git', 'mv', '-f', $src, $dest);
453 sub rcs_recentchanges ($) { #{{{
454 # List of recent changes.
458 eval q{use Date::Parse};
462 foreach my $ci (git_commit_info('HEAD', $num)) {
463 # Skip redundant commits.
464 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
466 my ($sha1, $when) = (
468 $ci->{'author_epoch'}
472 foreach my $detail (@{ $ci->{'details'} }) {
473 my $file = $detail->{'file'};
475 my $diffurl = $config{'diffurl'};
476 $diffurl =~ s/\[\[file\]\]/$file/go;
477 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
478 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
479 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
482 page => pagename($file),
489 foreach my $line (@{$ci->{'comment'}}) {
490 $pastblank=1 if $line eq '';
491 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
492 push @messages, { line => $line };
495 my $user=$ci->{'author_username'};
496 my $web_commit = ($ci->{'author'} =~ /\@web>/);
498 # compatability code for old web commit messages
500 defined $messages[0] &&
501 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
502 $user = defined $2 ? "$2" : "$3";
503 $messages[0]->{line} = $4;
510 committype => $web_commit ? "web" : "git",
512 message => [@messages],
516 last if @rets >= $num;
522 sub rcs_diff ($) { #{{{
524 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
526 foreach my $line (run_or_non("git", "show", $sha1)) {
527 if (@lines || $line=~/^diff --git/) {
528 push @lines, $line."\n";
535 return join("", @lines);
539 sub rcs_getctime ($) { #{{{
541 # Remove srcdir prefix
542 $file =~ s/^\Q$config{srcdir}\E\/?//;
544 my $sha1 = git_sha1($file);
545 my $ci = git_commit_info($sha1);
546 my $ctime = $ci->{'author_epoch'};
547 debug("ctime for '$file': ". localtime($ctime));