Version control backends promoted to first-class plugins
[ikiwiki] / IkiWiki / Plugin / git.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4
5 use warnings;
6 use strict;
7 use IkiWiki;
8 use Encode;
9 use open qw{:utf8 :std};
10
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
13
14 hook(type => "checkconfig", id => "git", call => sub { #{{{
15         if (! defined $config{diffurl}) {
16                 $config{diffurl}="";
17         }
18         if (! defined $config{gitorigin_branch}) {
19                 $config{gitorigin_branch}="origin";
20         }
21         if (! defined $config{gitmaster_branch}) {
22                 $config{gitmaster_branch}="master";
23         }
24         if (length $config{git_wrapper}) {
25                 push @{$config{wrappers}}, {
26                         wrapper => $config{git_wrapper},
27                         wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
28                 };
29         }
30 }); #}}}
31
32 hook(type => "getsetup", id => "git", call => sub { #{{{
33         return
34                 git_wrapper => {
35                         type => "string",
36                         example => "/git/wiki.git/hooks/post-update",
37                         description => "git post-update executable to generate",
38                         safe => 0, # file
39                         rebuild => 0,
40                 },
41                 git_wrappermode => {
42                         type => "string",
43                         example => '06755',
44                         description => "mode for git_wrapper (can safely be made suid)",
45                         safe => 0,
46                         rebuild => 0,
47                 },
48                 historyurl => {
49                         type => "string",
50                         example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]]",
51                         description => "gitweb url to show file history ([[file]] substituted)",
52                         safe => 1,
53                         rebuild => 1,
54                 },
55                 diffurl => {
56                         type => "string",
57                         example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=blobdiff;h=[[sha1_to]];hp=[[sha1_from]];hb=[[sha1_parent]];f=[[file]]",
58                         description => "gitweb url to show a diff ([[sha1_to]], [[sha1_from]], [[sha1_parent]], and [[file]] substituted)",
59                         safe => 1,
60                         rebuild => 1,
61                 },
62                 gitorigin_branch => {
63                         type => "string",
64                         example => "origin",
65                         description => "where to pull and push changes (set to empty string to disable)",
66                         safe => 0, # paranoia
67                         rebuild => 0,
68                 },
69                 gitmaster_branch => {
70                         type => "string",
71                         example => "master",
72                         description => "branch that the wiki is stored in",
73                         safe => 0, # paranoia
74                         rebuild => 0,
75                 },
76 }); #}}}
77
78 sub _safe_git (&@) { #{{{
79         # Start a child process safely without resorting /bin/sh.
80         # Return command output or success state (in scalar context).
81
82         my ($error_handler, @cmdline) = @_;
83
84         my $pid = open my $OUT, "-|";
85
86         error("Cannot fork: $!") if !defined $pid;
87
88         if (!$pid) {
89                 # In child.
90                 # Git commands want to be in wc.
91                 chdir $config{srcdir}
92                     or error("Cannot chdir to $config{srcdir}: $!");
93                 exec @cmdline or error("Cannot exec '@cmdline': $!");
94         }
95         # In parent.
96
97         my @lines;
98         while (<$OUT>) {
99                 chomp;
100                 push @lines, $_;
101         }
102
103         close $OUT;
104
105         $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
106
107         return wantarray ? @lines : ($? == 0);
108 }
109 # Convenient wrappers.
110 sub run_or_die ($@) { _safe_git(\&error, @_) }
111 sub run_or_cry ($@) { _safe_git(sub { warn @_ },  @_) }
112 sub run_or_non ($@) { _safe_git(undef,            @_) }
113 #}}}
114
115 sub _merge_past ($$$) { #{{{
116         # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
117         # Git merge commands work with the committed changes, except in the
118         # implicit case of '-m' of git checkout(1).  So we should invent a
119         # kludge here.  In principle, we need to create a throw-away branch
120         # in preparing for the merge itself.  Since branches are cheap (and
121         # branching is fast), this shouldn't cost high.
122         #
123         # The main problem is the presence of _uncommitted_ local changes.  One
124         # possible approach to get rid of this situation could be that we first
125         # make a temporary commit in the master branch and later restore the
126         # initial state (this is possible since Git has the ability to undo a
127         # commit, i.e. 'git reset --soft HEAD^').  The method can be summarized
128         # as follows:
129         #
130         #       - create a diff of HEAD:current-sha1
131         #       - dummy commit
132         #       - create a dummy branch and switch to it
133         #       - rewind to past (reset --hard to the current-sha1)
134         #       - apply the diff and commit
135         #       - switch to master and do the merge with the dummy branch
136         #       - make a soft reset (undo the last commit of master)
137         #
138         # The above method has some drawbacks: (1) it needs a redundant commit
139         # just to get rid of local changes, (2) somewhat slow because of the
140         # required system forks.  Until someone points a more straight method
141         # (which I would be grateful) I have implemented an alternative method.
142         # In this approach, we hide all the modified files from Git by renaming
143         # them (using the 'rename' builtin) and later restore those files in
144         # the throw-away branch (that is, we put the files themselves instead
145         # of applying a patch).
146
147         my ($sha1, $file, $message) = @_;
148
149         my @undo;      # undo stack for cleanup in case of an error
150         my $conflict;  # file content with conflict markers
151
152         eval {
153                 # Hide local changes from Git by renaming the modified file.
154                 # Relative paths must be converted to absolute for renaming.
155                 my ($target, $hidden) = (
156                     "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
157                 );
158                 rename($target, $hidden)
159                     or error("rename '$target' to '$hidden' failed: $!");
160                 # Ensure to restore the renamed file on error.
161                 push @undo, sub {
162                         return if ! -e "$hidden"; # already renamed
163                         rename($hidden, $target)
164                             or warn "rename '$hidden' to '$target' failed: $!";
165                 };
166
167                 my $branch = "throw_away_${sha1}"; # supposed to be unique
168
169                 # Create a throw-away branch and rewind backward.
170                 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
171                 run_or_die('git', 'branch', $branch, $sha1);
172
173                 # Switch to throw-away branch for the merge operation.
174                 push @undo, sub {
175                         if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
176                                 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
177                         }
178                 };
179                 run_or_die('git', 'checkout', $branch);
180
181                 # Put the modified file in _this_ branch.
182                 rename($hidden, $target)
183                     or error("rename '$hidden' to '$target' failed: $!");
184
185                 # _Silently_ commit all modifications in the current branch.
186                 run_or_non('git', 'commit', '-m', $message, '-a');
187                 # ... and re-switch to master.
188                 run_or_die('git', 'checkout', $config{gitmaster_branch});
189
190                 # Attempt to merge without complaining.
191                 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
192                         $conflict = readfile($target);
193                         run_or_die('git', 'reset', '--hard');
194                 }
195         };
196         my $failure = $@;
197
198         # Process undo stack (in reverse order).  By policy cleanup
199         # actions should normally print a warning on failure.
200         while (my $handle = pop @undo) {
201                 $handle->();
202         }
203
204         error("Git merge failed!\n$failure\n") if $failure;
205
206         return $conflict;
207 } #}}}
208
209 sub _parse_diff_tree ($@) { #{{{
210         # Parse the raw diff tree chunk and return the info hash.
211         # See git-diff-tree(1) for the syntax.
212
213         my ($prefix, $dt_ref) = @_;
214
215         # End of stream?
216         return if !defined @{ $dt_ref } ||
217                   !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
218
219         my %ci;
220         # Header line.
221         while (my $line = shift @{ $dt_ref }) {
222                 return if $line !~ m/^(.+) ($sha1_pattern)/;
223
224                 my $sha1 = $2;
225                 $ci{'sha1'} = $sha1;
226                 last;
227         }
228
229         # Identification lines for the commit.
230         while (my $line = shift @{ $dt_ref }) {
231                 # Regexps are semi-stolen from gitweb.cgi.
232                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
233                         $ci{'tree'} = $1;
234                 }
235                 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
236                         # XXX: collecting in reverse order
237                         push @{ $ci{'parents'} }, $1;
238                 }
239                 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
240                         my ($who, $name, $epoch, $tz) =
241                            ($1,   $2,    $3,     $4 );
242
243                         $ci{  $who          } = $name;
244                         $ci{ "${who}_epoch" } = $epoch;
245                         $ci{ "${who}_tz"    } = $tz;
246
247                         if ($name =~ m/^[^<]+\s+<([^@>]+)/) {
248                                 $ci{"${who}_username"} = $1;
249                         }
250                         elsif ($name =~ m/^([^<]+)\s+<>$/) {
251                                 $ci{"${who}_username"} = $1;
252                         }
253                         else {
254                                 $ci{"${who}_username"} = $name;
255                         }
256                 }
257                 elsif ($line =~ m/^$/) {
258                         # Trailing empty line signals next section.
259                         last;
260                 }
261         }
262
263         debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
264         
265         if (defined $ci{'parents'}) {
266                 $ci{'parent'} = @{ $ci{'parents'} }[0];
267         }
268         else {
269                 $ci{'parent'} = 0 x 40;
270         }
271
272         # Commit message (optional).
273         while ($dt_ref->[0] =~ /^    /) {
274                 my $line = shift @{ $dt_ref };
275                 $line =~ s/^    //;
276                 push @{ $ci{'comment'} }, $line;
277         }
278         shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
279
280         # Modified files.
281         while (my $line = shift @{ $dt_ref }) {
282                 if ($line =~ m{^
283                         (:+)       # number of parents
284                         ([^\t]+)\t # modes, sha1, status
285                         (.*)       # file names
286                 $}xo) {
287                         my $num_parents = length $1;
288                         my @tmp = split(" ", $2);
289                         my ($file, $file_to) = split("\t", $3);
290                         my @mode_from = splice(@tmp, 0, $num_parents);
291                         my $mode_to = shift(@tmp);
292                         my @sha1_from = splice(@tmp, 0, $num_parents);
293                         my $sha1_to = shift(@tmp);
294                         my $status = shift(@tmp);
295
296                         if ($file =~ m/^"(.*)"$/) {
297                                 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
298                         }
299                         $file =~ s/^\Q$prefix\E//;
300                         if (length $file) {
301                                 push @{ $ci{'details'} }, {
302                                         'file'      => decode_utf8($file),
303                                         'sha1_from' => $sha1_from[0],
304                                         'sha1_to'   => $sha1_to,
305                                 };
306                         }
307                         next;
308                 };
309                 last;
310         }
311
312         return \%ci;
313 } #}}}
314
315 sub git_commit_info ($;$) { #{{{
316         # Return an array of commit info hashes of num commits (default: 1)
317         # starting from the given sha1sum.
318
319         my ($sha1, $num) = @_;
320
321         $num ||= 1;
322
323         my @raw_lines = run_or_die('git', 'log', "--max-count=$num", 
324                 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
325                 '-r', $sha1, '--', '.');
326         my ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
327
328         my @ci;
329         while (my $parsed = _parse_diff_tree(($prefix or ""), \@raw_lines)) {
330                 push @ci, $parsed;
331         }
332
333         warn "Cannot parse commit info for '$sha1' commit" if !@ci;
334
335         return wantarray ? @ci : $ci[0];
336 } #}}}
337
338 sub git_sha1 (;$) { #{{{
339         # Return head sha1sum (of given file).
340
341         my $file = shift || q{--};
342
343         # Ignore error since a non-existing file might be given.
344         my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
345                 '--', $file);
346         if ($sha1) {
347                 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
348         } else { debug("Empty sha1sum for '$file'.") }
349         return defined $sha1 ? $sha1 : q{};
350 } #}}}
351
352 sub rcs_update () { #{{{
353         # Update working directory.
354
355         if (length $config{gitorigin_branch}) {
356                 run_or_cry('git', 'pull', $config{gitorigin_branch});
357         }
358 } #}}}
359
360 sub rcs_prepedit ($) { #{{{
361         # Return the commit sha1sum of the file when editing begins.
362         # This will be later used in rcs_commit if a merge is required.
363
364         my ($file) = @_;
365
366         return git_sha1($file);
367 } #}}}
368
369 sub rcs_commit ($$$;$$) { #{{{
370         # Try to commit the page; returns undef on _success_ and
371         # a version of the page with the rcs's conflict markers on
372         # failure.
373
374         my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
375
376         # Check to see if the page has been changed by someone else since
377         # rcs_prepedit was called.
378         my $cur    = git_sha1($file);
379         my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
380
381         if (defined $cur && defined $prev && $cur ne $prev) {
382                 my $conflict = _merge_past($prev, $file, $dummy_commit_msg);
383                 return $conflict if defined $conflict;
384         }
385
386         rcs_add($file); 
387         return rcs_commit_staged($message, $user, $ipaddr);
388 } #}}}
389
390 sub rcs_commit_staged ($$$) {
391         # Commits all staged changes. Changes can be staged using rcs_add,
392         # rcs_remove, and rcs_rename.
393         my ($message, $user, $ipaddr)=@_;
394
395         # Set the commit author and email to the web committer.
396         my %env=%ENV;
397         if (defined $user || defined $ipaddr) {
398                 my $u=defined $user ? $user : $ipaddr;
399                 $ENV{GIT_AUTHOR_NAME}=$u;
400                 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
401         }
402
403         # git commit returns non-zero if file has not been really changed.
404         # so we should ignore its exit status (hence run_or_non).
405         $message = possibly_foolish_untaint($message);
406         if (run_or_non('git', 'commit', '--cleanup=verbatim',
407                        '-q', '-m', $message)) {
408                 if (length $config{gitorigin_branch}) {
409                         run_or_cry('git', 'push', $config{gitorigin_branch});
410                 }
411         }
412         
413         %ENV=%env;
414         return undef; # success
415 }
416
417 sub rcs_add ($) { # {{{
418         # Add file to archive.
419
420         my ($file) = @_;
421
422         run_or_cry('git', 'add', $file);
423 } #}}}
424
425 sub rcs_remove ($) { # {{{
426         # Remove file from archive.
427
428         my ($file) = @_;
429
430         run_or_cry('git', 'rm', '-f', $file);
431 } #}}}
432
433 sub rcs_rename ($$) { # {{{
434         my ($src, $dest) = @_;
435
436         run_or_cry('git', 'mv', '-f', $src, $dest);
437 } #}}}
438
439 sub rcs_recentchanges ($) { #{{{
440         # List of recent changes.
441
442         my ($num) = @_;
443
444         eval q{use Date::Parse};
445         error($@) if $@;
446
447         my @rets;
448         foreach my $ci (git_commit_info('HEAD', $num)) {
449                 # Skip redundant commits.
450                 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
451
452                 my ($sha1, $when) = (
453                         $ci->{'sha1'},
454                         $ci->{'author_epoch'}
455                 );
456
457                 my @pages;
458                 foreach my $detail (@{ $ci->{'details'} }) {
459                         my $file = $detail->{'file'};
460
461                         my $diffurl = $config{'diffurl'};
462                         $diffurl =~ s/\[\[file\]\]/$file/go;
463                         $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
464                         $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
465                         $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
466
467                         push @pages, {
468                                 page => pagename($file),
469                                 diffurl => $diffurl,
470                         };
471                 }
472
473                 my @messages;
474                 my $pastblank=0;
475                 foreach my $line (@{$ci->{'comment'}}) {
476                         $pastblank=1 if $line eq '';
477                         next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
478                         push @messages, { line => $line };
479                 }
480
481                 my $user=$ci->{'author_username'};
482                 my $web_commit = ($ci->{'author'} =~ /\@web>/);
483                 
484                 # compatability code for old web commit messages
485                 if (! $web_commit &&
486                       defined $messages[0] &&
487                       $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
488                         $user = defined $2 ? "$2" : "$3";
489                         $messages[0]->{line} = $4;
490                         $web_commit=1;
491                 }
492
493                 push @rets, {
494                         rev        => $sha1,
495                         user       => $user,
496                         committype => $web_commit ? "web" : "git",
497                         when       => $when,
498                         message    => [@messages],
499                         pages      => [@pages],
500                 } if @pages;
501
502                 last if @rets >= $num;
503         }
504
505         return @rets;
506 } #}}}
507
508 sub rcs_diff ($) { #{{{
509         my $rev=shift;
510         my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
511         my @lines;
512         foreach my $line (run_or_non("git", "show", $sha1)) {
513                 if (@lines || $line=~/^diff --git/) {
514                         push @lines, $line."\n";
515                 }
516         }
517         if (wantarray) {
518                 return @lines;
519         }
520         else {
521                 return join("", @lines);
522         }
523 } #}}}
524
525 sub rcs_getctime ($) { #{{{
526         my $file=shift;
527         # Remove srcdir prefix
528         $file =~ s/^\Q$config{srcdir}\E\/?//;
529
530         my $sha1  = git_sha1($file);
531         my $ci    = git_commit_info($sha1);
532         my $ctime = $ci->{'author_epoch'};
533         debug("ctime for '$file': ". localtime($ctime));
534
535         return $ctime;
536 } #}}}
537
538 1