changelog
[ikiwiki.git] / IkiWiki / Plugin / git.pm
1 #!/usr/bin/perl
2 package IkiWiki::Plugin::git;
3
4 use warnings;
5 use strict;
6 use IkiWiki;
7 use Encode;
8 use open qw{:utf8 :std};
9
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
12
13 sub import { #{{{
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);
26 } #}}}
27
28 sub checkconfig () { #{{{
29         if (! defined $config{gitorigin_branch}) {
30                 $config{gitorigin_branch}="origin";
31         }
32         if (! defined $config{gitmaster_branch}) {
33                 $config{gitmaster_branch}="master";
34         }
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"),
39                 };
40         }
41 } #}}}
42
43 sub getsetup () { #{{{
44         return
45                 git_wrapper => {
46                         type => "string",
47                         example => "/git/wiki.git/hooks/post-update",
48                         description => "git post-update executable to generate",
49                         safe => 0, # file
50                         rebuild => 0,
51                 },
52                 git_wrappermode => {
53                         type => "string",
54                         example => '06755',
55                         description => "mode for git_wrapper (can safely be made suid)",
56                         safe => 0,
57                         rebuild => 0,
58                 },
59                 historyurl => {
60                         type => "string",
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)",
63                         safe => 1,
64                         rebuild => 1,
65                 },
66                 diffurl => {
67                         type => "string",
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)",
70                         safe => 1,
71                         rebuild => 1,
72                 },
73                 gitorigin_branch => {
74                         type => "string",
75                         example => "origin",
76                         description => "where to pull and push changes (set to empty string to disable)",
77                         safe => 0, # paranoia
78                         rebuild => 0,
79                 },
80                 gitmaster_branch => {
81                         type => "string",
82                         example => "master",
83                         description => "branch that the wiki is stored in",
84                         safe => 0, # paranoia
85                         rebuild => 0,
86                 },
87 } #}}}
88
89 sub safe_git (&@) { #{{{
90         # Start a child process safely without resorting /bin/sh.
91         # Return command output or success state (in scalar context).
92
93         my ($error_handler, @cmdline) = @_;
94
95         my $pid = open my $OUT, "-|";
96
97         error("Cannot fork: $!") if !defined $pid;
98
99         if (!$pid) {
100                 # In child.
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': $!");
105         }
106         # In parent.
107
108         my @lines;
109         while (<$OUT>) {
110                 chomp;
111                 push @lines, $_;
112         }
113
114         close $OUT;
115
116         $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
117
118         return wantarray ? @lines : ($? == 0);
119 }
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,            @_) }
124 #}}}
125
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.
133         #
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
139         # as follows:
140         #
141         #       - create a diff of HEAD:current-sha1
142         #       - dummy commit
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)
148         #
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).
157
158         my ($sha1, $file, $message) = @_;
159
160         my @undo;      # undo stack for cleanup in case of an error
161         my $conflict;  # file content with conflict markers
162
163         eval {
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}"
168                 );
169                 rename($target, $hidden)
170                     or error("rename '$target' to '$hidden' failed: $!");
171                 # Ensure to restore the renamed file on error.
172                 push @undo, sub {
173                         return if ! -e "$hidden"; # already renamed
174                         rename($hidden, $target)
175                             or warn "rename '$hidden' to '$target' failed: $!";
176                 };
177
178                 my $branch = "throw_away_${sha1}"; # supposed to be unique
179
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);
183
184                 # Switch to throw-away branch for the merge operation.
185                 push @undo, sub {
186                         if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
187                                 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
188                         }
189                 };
190                 run_or_die('git', 'checkout', $branch);
191
192                 # Put the modified file in _this_ branch.
193                 rename($hidden, $target)
194                     or error("rename '$hidden' to '$target' failed: $!");
195
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});
200
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');
205                 }
206         };
207         my $failure = $@;
208
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) {
212                 $handle->();
213         }
214
215         error("Git merge failed!\n$failure\n") if $failure;
216
217         return $conflict;
218 } #}}}
219
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.
223
224         my ($prefix, $dt_ref) = @_;
225
226         # End of stream?
227         return if !defined @{ $dt_ref } ||
228                   !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
229
230         my %ci;
231         # Header line.
232         while (my $line = shift @{ $dt_ref }) {
233                 return if $line !~ m/^(.+) ($sha1_pattern)/;
234
235                 my $sha1 = $2;
236                 $ci{'sha1'} = $sha1;
237                 last;
238         }
239
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})$/) {
244                         $ci{'tree'} = $1;
245                 }
246                 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
247                         # XXX: collecting in reverse order
248                         push @{ $ci{'parents'} }, $1;
249                 }
250                 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
251                         my ($who, $name, $epoch, $tz) =
252                            ($1,   $2,    $3,     $4 );
253
254                         $ci{  $who          } = $name;
255                         $ci{ "${who}_epoch" } = $epoch;
256                         $ci{ "${who}_tz"    } = $tz;
257
258                         if ($name =~ m/^[^<]+\s+<([^@>]+)/) {
259                                 $ci{"${who}_username"} = $1;
260                         }
261                         elsif ($name =~ m/^([^<]+)\s+<>$/) {
262                                 $ci{"${who}_username"} = $1;
263                         }
264                         else {
265                                 $ci{"${who}_username"} = $name;
266                         }
267                 }
268                 elsif ($line =~ m/^$/) {
269                         # Trailing empty line signals next section.
270                         last;
271                 }
272         }
273
274         debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
275         
276         if (defined $ci{'parents'}) {
277                 $ci{'parent'} = @{ $ci{'parents'} }[0];
278         }
279         else {
280                 $ci{'parent'} = 0 x 40;
281         }
282
283         # Commit message (optional).
284         while ($dt_ref->[0] =~ /^    /) {
285                 my $line = shift @{ $dt_ref };
286                 $line =~ s/^    //;
287                 push @{ $ci{'comment'} }, $line;
288         }
289         shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
290
291         # Modified files.
292         while (my $line = shift @{ $dt_ref }) {
293                 if ($line =~ m{^
294                         (:+)       # number of parents
295                         ([^\t]+)\t # modes, sha1, status
296                         (.*)       # file names
297                 $}xo) {
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);
306
307                         if ($file =~ m/^"(.*)"$/) {
308                                 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
309                         }
310                         $file =~ s/^\Q$prefix\E//;
311                         if (length $file) {
312                                 push @{ $ci{'details'} }, {
313                                         'file'      => decode_utf8($file),
314                                         'sha1_from' => $sha1_from[0],
315                                         'sha1_to'   => $sha1_to,
316                                 };
317                         }
318                         next;
319                 };
320                 last;
321         }
322
323         return \%ci;
324 } #}}}
325
326 sub git_commit_info ($;$) { #{{{
327         # Return an array of commit info hashes of num commits (default: 1)
328         # starting from the given sha1sum.
329
330         my ($sha1, $num) = @_;
331
332         $num ||= 1;
333
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');
338
339         my @ci;
340         while (my $parsed = parse_diff_tree(($prefix or ""), \@raw_lines)) {
341                 push @ci, $parsed;
342         }
343
344         warn "Cannot parse commit info for '$sha1' commit" if !@ci;
345
346         return wantarray ? @ci : $ci[0];
347 } #}}}
348
349 sub git_sha1 (;$) { #{{{
350         # Return head sha1sum (of given file).
351
352         my $file = shift || q{--};
353
354         # Ignore error since a non-existing file might be given.
355         my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
356                 '--', $file);
357         if ($sha1) {
358                 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
359         } else { debug("Empty sha1sum for '$file'.") }
360         return defined $sha1 ? $sha1 : q{};
361 } #}}}
362
363 sub rcs_update () { #{{{
364         # Update working directory.
365
366         if (length $config{gitorigin_branch}) {
367                 run_or_cry('git', 'pull', $config{gitorigin_branch});
368         }
369 } #}}}
370
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.
374
375         my ($file) = @_;
376
377         return git_sha1($file);
378 } #}}}
379
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
383         # failure.
384
385         my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
386
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
391
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;
395         }
396
397         rcs_add($file); 
398         return rcs_commit_staged($message, $user, $ipaddr);
399 } #}}}
400
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)=@_;
405
406         # Set the commit author and email to the web committer.
407         my %env=%ENV;
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";
412         }
413
414         # git commit returns non-zero if file has not been really changed.
415         # so we should ignore its exit status (hence run_or_non).
416         $message = IkiWiki::possibly_foolish_untaint($message);
417         if (run_or_non('git', 'commit', '--cleanup=verbatim',
418                        '-q', '-m', $message)) {
419                 if (length $config{gitorigin_branch}) {
420                         run_or_cry('git', 'push', $config{gitorigin_branch});
421                 }
422         }
423         
424         %ENV=%env;
425         return undef; # success
426 }
427
428 sub rcs_add ($) { # {{{
429         # Add file to archive.
430
431         my ($file) = @_;
432
433         run_or_cry('git', 'add', $file);
434 } #}}}
435
436 sub rcs_remove ($) { # {{{
437         # Remove file from archive.
438
439         my ($file) = @_;
440
441         run_or_cry('git', 'rm', '-f', $file);
442 } #}}}
443
444 sub rcs_rename ($$) { # {{{
445         my ($src, $dest) = @_;
446
447         run_or_cry('git', 'mv', '-f', $src, $dest);
448 } #}}}
449
450 sub rcs_recentchanges ($) { #{{{
451         # List of recent changes.
452
453         my ($num) = @_;
454
455         eval q{use Date::Parse};
456         error($@) if $@;
457
458         my @rets;
459         foreach my $ci (git_commit_info('HEAD', $num)) {
460                 # Skip redundant commits.
461                 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
462
463                 my ($sha1, $when) = (
464                         $ci->{'sha1'},
465                         $ci->{'author_epoch'}
466                 );
467
468                 my @pages;
469                 foreach my $detail (@{ $ci->{'details'} }) {
470                         my $file = $detail->{'file'};
471
472                         my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
473                         $diffurl =~ s/\[\[file\]\]/$file/go;
474                         $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
475                         $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
476                         $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
477
478                         push @pages, {
479                                 page => pagename($file),
480                                 diffurl => $diffurl,
481                         };
482                 }
483
484                 my @messages;
485                 my $pastblank=0;
486                 foreach my $line (@{$ci->{'comment'}}) {
487                         $pastblank=1 if $line eq '';
488                         next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
489                         push @messages, { line => $line };
490                 }
491
492                 my $user=$ci->{'author_username'};
493                 my $web_commit = ($ci->{'author'} =~ /\@web>/);
494                 
495                 # compatability code for old web commit messages
496                 if (! $web_commit &&
497                       defined $messages[0] &&
498                       $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
499                         $user = defined $2 ? "$2" : "$3";
500                         $messages[0]->{line} = $4;
501                         $web_commit=1;
502                 }
503
504                 push @rets, {
505                         rev        => $sha1,
506                         user       => $user,
507                         committype => $web_commit ? "web" : "git",
508                         when       => $when,
509                         message    => [@messages],
510                         pages      => [@pages],
511                 } if @pages;
512
513                 last if @rets >= $num;
514         }
515
516         return @rets;
517 } #}}}
518
519 sub rcs_diff ($) { #{{{
520         my $rev=shift;
521         my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
522         my @lines;
523         foreach my $line (run_or_non("git", "show", $sha1)) {
524                 if (@lines || $line=~/^diff --git/) {
525                         push @lines, $line."\n";
526                 }
527         }
528         if (wantarray) {
529                 return @lines;
530         }
531         else {
532                 return join("", @lines);
533         }
534 } #}}}
535
536 sub rcs_getctime ($) { #{{{
537         my $file=shift;
538         # Remove srcdir prefix
539         $file =~ s/^\Q$config{srcdir}\E\/?//;
540
541         my $sha1  = git_sha1($file);
542         my $ci    = git_commit_info($sha1);
543         my $ctime = $ci->{'author_epoch'};
544         debug("ctime for '$file': ". localtime($ctime));
545
546         return $ctime;
547 } #}}}
548
549 1