]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/git.pm
b683e4ec3b7fbba4b1f41c5bb7ac96c074ec2fd2
[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         if (exists $IkiWiki::hooks{rcs}) {
15                 error(gettext("cannot use multiple rcs plugins"));
16         }
17         hook(type => "checkconfig", id => "git", call => \&checkconfig);
18         hook(type => "getsetup", id => "git", call => \&getsetup);
19         hook(type => "rcs", id => "rcs_update", call => \&rcs_update);
20         hook(type => "rcs", id => "rcs_prepedit", call => \&rcs_prepedit);
21         hook(type => "rcs", id => "rcs_commit", call => \&rcs_commit);
22         hook(type => "rcs", id => "rcs_commit_staged", call => \&rcs_commit_staged);
23         hook(type => "rcs", id => "rcs_add", call => \&rcs_add);
24         hook(type => "rcs", id => "rcs_remove", call => \&rcs_remove);
25         hook(type => "rcs", id => "rcs_rename", call => \&rcs_rename);
26         hook(type => "rcs", id => "rcs_recentchanges", call => \&rcs_recentchanges);
27         hook(type => "rcs", id => "rcs_diff", call => \&rcs_diff);
28         hook(type => "rcs", id => "rcs_getctime", call => \&rcs_getctime);
29 } #}}}
30
31 sub checkconfig () { #{{{
32         if (! defined $config{gitorigin_branch}) {
33                 $config{gitorigin_branch}="origin";
34         }
35         if (! defined $config{gitmaster_branch}) {
36                 $config{gitmaster_branch}="master";
37         }
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"),
42                 };
43         }
44 } #}}}
45
46 sub getsetup () { #{{{
47         return
48                 git_wrapper => {
49                         type => "string",
50                         example => "/git/wiki.git/hooks/post-update",
51                         description => "git post-update executable to generate",
52                         safe => 0, # file
53                         rebuild => 0,
54                 },
55                 git_wrappermode => {
56                         type => "string",
57                         example => '06755',
58                         description => "mode for git_wrapper (can safely be made suid)",
59                         safe => 0,
60                         rebuild => 0,
61                 },
62                 historyurl => {
63                         type => "string",
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)",
66                         safe => 1,
67                         rebuild => 1,
68                 },
69                 diffurl => {
70                         type => "string",
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)",
73                         safe => 1,
74                         rebuild => 1,
75                 },
76                 gitorigin_branch => {
77                         type => "string",
78                         example => "origin",
79                         description => "where to pull and push changes (set to empty string to disable)",
80                         safe => 0, # paranoia
81                         rebuild => 0,
82                 },
83                 gitmaster_branch => {
84                         type => "string",
85                         example => "master",
86                         description => "branch that the wiki is stored in",
87                         safe => 0, # paranoia
88                         rebuild => 0,
89                 },
90 } #}}}
91
92 sub safe_git (&@) { #{{{
93         # Start a child process safely without resorting /bin/sh.
94         # Return command output or success state (in scalar context).
95
96         my ($error_handler, @cmdline) = @_;
97
98         my $pid = open my $OUT, "-|";
99
100         error("Cannot fork: $!") if !defined $pid;
101
102         if (!$pid) {
103                 # In child.
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': $!");
108         }
109         # In parent.
110
111         my @lines;
112         while (<$OUT>) {
113                 chomp;
114                 push @lines, $_;
115         }
116
117         close $OUT;
118
119         $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
120
121         return wantarray ? @lines : ($? == 0);
122 }
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,            @_) }
127 #}}}
128
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.
136         #
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
142         # as follows:
143         #
144         #       - create a diff of HEAD:current-sha1
145         #       - dummy commit
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)
151         #
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).
160
161         my ($sha1, $file, $message) = @_;
162
163         my @undo;      # undo stack for cleanup in case of an error
164         my $conflict;  # file content with conflict markers
165
166         eval {
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}"
171                 );
172                 rename($target, $hidden)
173                     or error("rename '$target' to '$hidden' failed: $!");
174                 # Ensure to restore the renamed file on error.
175                 push @undo, sub {
176                         return if ! -e "$hidden"; # already renamed
177                         rename($hidden, $target)
178                             or warn "rename '$hidden' to '$target' failed: $!";
179                 };
180
181                 my $branch = "throw_away_${sha1}"; # supposed to be unique
182
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);
186
187                 # Switch to throw-away branch for the merge operation.
188                 push @undo, sub {
189                         if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
190                                 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
191                         }
192                 };
193                 run_or_die('git', 'checkout', $branch);
194
195                 # Put the modified file in _this_ branch.
196                 rename($hidden, $target)
197                     or error("rename '$hidden' to '$target' failed: $!");
198
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});
203
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');
208                 }
209         };
210         my $failure = $@;
211
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) {
215                 $handle->();
216         }
217
218         error("Git merge failed!\n$failure\n") if $failure;
219
220         return $conflict;
221 } #}}}
222
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.
226
227         my ($prefix, $dt_ref) = @_;
228
229         # End of stream?
230         return if !defined @{ $dt_ref } ||
231                   !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
232
233         my %ci;
234         # Header line.
235         while (my $line = shift @{ $dt_ref }) {
236                 return if $line !~ m/^(.+) ($sha1_pattern)/;
237
238                 my $sha1 = $2;
239                 $ci{'sha1'} = $sha1;
240                 last;
241         }
242
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})$/) {
247                         $ci{'tree'} = $1;
248                 }
249                 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
250                         # XXX: collecting in reverse order
251                         push @{ $ci{'parents'} }, $1;
252                 }
253                 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
254                         my ($who, $name, $epoch, $tz) =
255                            ($1,   $2,    $3,     $4 );
256
257                         $ci{  $who          } = $name;
258                         $ci{ "${who}_epoch" } = $epoch;
259                         $ci{ "${who}_tz"    } = $tz;
260
261                         if ($name =~ m/^[^<]+\s+<([^@>]+)/) {
262                                 $ci{"${who}_username"} = $1;
263                         }
264                         elsif ($name =~ m/^([^<]+)\s+<>$/) {
265                                 $ci{"${who}_username"} = $1;
266                         }
267                         else {
268                                 $ci{"${who}_username"} = $name;
269                         }
270                 }
271                 elsif ($line =~ m/^$/) {
272                         # Trailing empty line signals next section.
273                         last;
274                 }
275         }
276
277         debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
278         
279         if (defined $ci{'parents'}) {
280                 $ci{'parent'} = @{ $ci{'parents'} }[0];
281         }
282         else {
283                 $ci{'parent'} = 0 x 40;
284         }
285
286         # Commit message (optional).
287         while ($dt_ref->[0] =~ /^    /) {
288                 my $line = shift @{ $dt_ref };
289                 $line =~ s/^    //;
290                 push @{ $ci{'comment'} }, $line;
291         }
292         shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
293
294         # Modified files.
295         while (my $line = shift @{ $dt_ref }) {
296                 if ($line =~ m{^
297                         (:+)       # number of parents
298                         ([^\t]+)\t # modes, sha1, status
299                         (.*)       # file names
300                 $}xo) {
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);
309
310                         if ($file =~ m/^"(.*)"$/) {
311                                 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
312                         }
313                         $file =~ s/^\Q$prefix\E//;
314                         if (length $file) {
315                                 push @{ $ci{'details'} }, {
316                                         'file'      => decode_utf8($file),
317                                         'sha1_from' => $sha1_from[0],
318                                         'sha1_to'   => $sha1_to,
319                                 };
320                         }
321                         next;
322                 };
323                 last;
324         }
325
326         return \%ci;
327 } #}}}
328
329 sub git_commit_info ($;$) { #{{{
330         # Return an array of commit info hashes of num commits (default: 1)
331         # starting from the given sha1sum.
332
333         my ($sha1, $num) = @_;
334
335         $num ||= 1;
336
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');
341
342         my @ci;
343         while (my $parsed = parse_diff_tree(($prefix or ""), \@raw_lines)) {
344                 push @ci, $parsed;
345         }
346
347         warn "Cannot parse commit info for '$sha1' commit" if !@ci;
348
349         return wantarray ? @ci : $ci[0];
350 } #}}}
351
352 sub git_sha1 (;$) { #{{{
353         # Return head sha1sum (of given file).
354
355         my $file = shift || q{--};
356
357         # Ignore error since a non-existing file might be given.
358         my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
359                 '--', $file);
360         if ($sha1) {
361                 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
362         } else { debug("Empty sha1sum for '$file'.") }
363         return defined $sha1 ? $sha1 : q{};
364 } #}}}
365
366 sub rcs_update () { #{{{
367         # Update working directory.
368
369         if (length $config{gitorigin_branch}) {
370                 run_or_cry('git', 'pull', $config{gitorigin_branch});
371         }
372 } #}}}
373
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.
377
378         my ($file) = @_;
379
380         return git_sha1($file);
381 } #}}}
382
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
386         # failure.
387
388         my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
389
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
394
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;
398         }
399
400         rcs_add($file); 
401         return rcs_commit_staged($message, $user, $ipaddr);
402 } #}}}
403
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)=@_;
408
409         # Set the commit author and email to the web committer.
410         my %env=%ENV;
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";
415         }
416
417         $message = IkiWiki::possibly_foolish_untaint($message);
418         my @opts;
419         if ($message !~ /\S/) {
420                 # Force git to allow empty commit messages.
421                 # (If this version of git supports it.)
422                 my ($version)=`git --version` =~ /git version (.*)/;
423                 if ($version ge "1.5.4") {
424                         push @opts, '--cleanup=verbatim';
425                 }
426                 else {
427                         $message.=".";
428                 }
429         }
430         push @opts, '-q';
431         # git commit returns non-zero if file has not been really changed.
432         # so we should ignore its exit status (hence run_or_non).
433         if (run_or_non('git', 'commit', @opts, '-m', $message)) {
434                 if (length $config{gitorigin_branch}) {
435                         run_or_cry('git', 'push', $config{gitorigin_branch});
436                 }
437         }
438         
439         %ENV=%env;
440         return undef; # success
441 }
442
443 sub rcs_add ($) { # {{{
444         # Add file to archive.
445
446         my ($file) = @_;
447
448         run_or_cry('git', 'add', $file);
449 } #}}}
450
451 sub rcs_remove ($) { # {{{
452         # Remove file from archive.
453
454         my ($file) = @_;
455
456         run_or_cry('git', 'rm', '-f', $file);
457 } #}}}
458
459 sub rcs_rename ($$) { # {{{
460         my ($src, $dest) = @_;
461
462         run_or_cry('git', 'mv', '-f', $src, $dest);
463 } #}}}
464
465 sub rcs_recentchanges ($) { #{{{
466         # List of recent changes.
467
468         my ($num) = @_;
469
470         eval q{use Date::Parse};
471         error($@) if $@;
472
473         my @rets;
474         foreach my $ci (git_commit_info('HEAD', $num)) {
475                 # Skip redundant commits.
476                 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
477
478                 my ($sha1, $when) = (
479                         $ci->{'sha1'},
480                         $ci->{'author_epoch'}
481                 );
482
483                 my @pages;
484                 foreach my $detail (@{ $ci->{'details'} }) {
485                         my $file = $detail->{'file'};
486
487                         my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
488                         $diffurl =~ s/\[\[file\]\]/$file/go;
489                         $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
490                         $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
491                         $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
492
493                         push @pages, {
494                                 page => pagename($file),
495                                 diffurl => $diffurl,
496                         };
497                 }
498
499                 my @messages;
500                 my $pastblank=0;
501                 foreach my $line (@{$ci->{'comment'}}) {
502                         $pastblank=1 if $line eq '';
503                         next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
504                         push @messages, { line => $line };
505                 }
506
507                 my $user=$ci->{'author_username'};
508                 my $web_commit = ($ci->{'author'} =~ /\@web>/);
509                 
510                 # compatability code for old web commit messages
511                 if (! $web_commit &&
512                       defined $messages[0] &&
513                       $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
514                         $user = defined $2 ? "$2" : "$3";
515                         $messages[0]->{line} = $4;
516                         $web_commit=1;
517                 }
518
519                 push @rets, {
520                         rev        => $sha1,
521                         user       => $user,
522                         committype => $web_commit ? "web" : "git",
523                         when       => $when,
524                         message    => [@messages],
525                         pages      => [@pages],
526                 } if @pages;
527
528                 last if @rets >= $num;
529         }
530
531         return @rets;
532 } #}}}
533
534 sub rcs_diff ($) { #{{{
535         my $rev=shift;
536         my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
537         my @lines;
538         foreach my $line (run_or_non("git", "show", $sha1)) {
539                 if (@lines || $line=~/^diff --git/) {
540                         push @lines, $line."\n";
541                 }
542         }
543         if (wantarray) {
544                 return @lines;
545         }
546         else {
547                 return join("", @lines);
548         }
549 } #}}}
550
551 sub rcs_getctime ($) { #{{{
552         my $file=shift;
553         # Remove srcdir prefix
554         $file =~ s/^\Q$config{srcdir}\E\/?//;
555
556         my $sha1  = git_sha1($file);
557         my $ci    = git_commit_info($sha1);
558         my $ctime = $ci->{'author_epoch'};
559         debug("ctime for '$file': ". localtime($ctime));
560
561         return $ctime;
562 } #}}}
563
564 1