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