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