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