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