]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Rcs/git.pm
* Avoid a race in the git rcs_commit function, by not assuming HEAD will
[ikiwiki.git] / IkiWiki / Rcs / git.pm
1 #!/usr/bin/perl
2
3 use warnings;
4 use strict;
5 use IkiWiki;
6 use Encode;
7 use open qw{:utf8 :std};
8
9 package IkiWiki;
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/^commit ([0-9a-fA-F]{40})$/) {
169                         $ci{'commit'} = $1;
170                 }
171                 elsif ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
172                         $ci{'tree'} = $1;
173                 }
174                 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
175                         # XXX: collecting in reverse order
176                         push @{ $ci{'parents'} }, $1;
177                 }
178                 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
179                         my ($who, $name, $epoch, $tz) =
180                            ($1,   $2,    $3,     $4 );
181
182                         $ci{  $who          } = $name;
183                         $ci{ "${who}_epoch" } = $epoch;
184                         $ci{ "${who}_tz"    } = $tz;
185
186                         if ($name =~ m/^([^<]+) <([^@>]+)/) {
187                                 my ($fullname, $username) = ($1, $2);
188                                 $ci{"${who}_fullname"}    = $fullname;
189                                 $ci{"${who}_username"}    = $username;
190                         }
191                         else {
192                                 $ci{"${who}_fullname"} =
193                                         $ci{"${who}_username"} = $name;
194                         }
195                 }
196                 elsif ($line =~ m/^$/) {
197                         # Trailing empty line signals next section.
198                         last;
199                 }
200         }
201
202         debug("No 'tree' or 'parents' seen in diff-tree output")
203             if !defined $ci{'tree'} || !defined $ci{'parents'};
204
205         $ci{'parent'} = @{ $ci{'parents'} }[0] if defined $ci{'parents'};
206
207         # Commit message.
208         while (my $line = shift @{ $dt_ref }) {
209                 if ($line =~ m/^$/) {
210                         # Trailing empty line signals next section.
211                         last;
212                 };
213                 $line =~ s/^    //;
214                 push @{ $ci{'comment'} }, $line;
215         }
216
217         # Modified files.
218         while (my $line = shift @{ $dt_ref }) {
219                 if ($line =~ m{^:
220                         ([0-7]{6})[ ]      # from mode
221                         ([0-7]{6})[ ]      # to mode
222                         ($sha1_pattern)[ ] # from sha1
223                         ($sha1_pattern)[ ] # to sha1
224                         (.)                # status
225                         ([0-9]{0,3})\t     # similarity
226                         (.*)               # file
227                 $}xo) {
228                         my ($sha1_from, $sha1_to, $file) =
229                            ($3,         $4,       $7   );
230
231                         if ($file =~ m/^"(.*)"$/) {
232                                 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
233                         }
234                         $file =~ s/^\Q$prefix\E//;
235                         if (length $file) {
236                                 push @{ $ci{'details'} }, {
237                                         'file'      => decode_utf8($file),
238                                         'sha1_from' => $sha1_from,
239                                         'sha1_to'   => $sha1_to,
240                                 };
241                         }
242                         next;
243                 };
244                 last;
245         }
246
247         debug("No detail in diff-tree output") if !defined $ci{'details'};
248
249         return \%ci;
250 } #}}}
251
252 sub git_commit_info ($;$) { #{{{
253         # Return an array of commit info hashes of num commits (default: 1)
254         # starting from the given sha1sum.
255
256         my ($sha1, $num) = @_;
257
258         $num ||= 1;
259
260         my @raw_lines = run_or_die('git-log', "--max-count=$num", 
261                 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-m',
262                 '-r', $sha1, '--', '.');
263         my ($prefix) = run_or_die('git-rev-parse', '--show-prefix');
264
265         my @ci;
266         while (my $parsed = _parse_diff_tree(($prefix or ""), \@raw_lines)) {
267                 push @ci, $parsed;
268         }
269
270         warn "Cannot parse commit info for '$sha1' commit" if !@ci;
271
272         return wantarray ? @ci : $ci[0];
273 } #}}}
274
275 sub git_sha1 (;$) { #{{{
276         # Return head sha1sum (of given file).
277
278         my $file = shift || q{--};
279
280         # Ignore error since a non-existing file might be given.
281         my ($sha1) = run_or_non('git-rev-list', '--max-count=1', 'HEAD', $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         if (defined $user) {
313                 $message = "web commit by $user" .
314                     (length $message ? ": $message" : "");
315         }
316         elsif (defined $ipaddr) {
317                 $message = "web commit from $ipaddr" .
318                     (length $message ? ": $message" : "");
319         }
320
321         # XXX: Wiki directory is in the unlocked state when starting this
322         # action.  But it takes time for a Git process to finish its job
323         # (especially if a merge required), so we must re-lock to prevent
324         # race conditions.  Only when the time of the real commit action
325         # (i.e. git-push(1)) comes, we'll unlock the directory.
326         lockwiki();
327
328         # Check to see if the page has been changed by someone else since
329         # rcs_prepedit was called.
330         my $cur    = git_sha1($file);
331         my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
332
333         if (defined $cur && defined $prev && $cur ne $prev) {
334                 my $conflict = _merge_past($prev, $file, $dummy_commit_msg);
335                 return $conflict if defined $conflict;
336         }
337
338         # git-commit(1) returns non-zero if file has not been really changed.
339         # so we should ignore its exit status (hence run_or_non).
340         $message = possibly_foolish_untaint($message);
341         if (run_or_non('git-commit', '-q', '-m', $message, '-i', $file)) {
342                 unlockwiki();
343                 if (length $config{gitorigin_branch}) {
344                         run_or_cry('git-push', $config{gitorigin_branch});
345                 }
346         }
347
348         return undef; # success
349 } #}}}
350
351 sub rcs_add ($) { # {{{
352         # Add file to archive.
353
354         my ($file) = @_;
355
356         run_or_cry('git-add', $file);
357 } #}}}
358
359 sub rcs_recentchanges ($) { #{{{
360         # List of recent changes.
361
362         my ($num) = @_;
363
364         eval q{use Date::Parse};
365         error($@) if $@;
366
367         my @rets;
368         foreach my $ci (git_commit_info('HEAD', $num)) {
369                 my $title = @{ $ci->{'comment'} }[0];
370
371                 # Skip redundant commits.
372                 next if ($title eq $dummy_commit_msg);
373
374                 my ($sha1, $when) = (
375                         $ci->{'sha1'},
376                         time - $ci->{'author_epoch'}
377                 );
378
379                 my (@pages, @messages);
380                 foreach my $detail (@{ $ci->{'details'} }) {
381                         my $file = $detail->{'file'};
382
383                         my $diffurl = $config{'diffurl'};
384                         $diffurl =~ s/\[\[file\]\]/$file/go;
385                         $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
386                         $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
387                         $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
388
389                         push @pages, {
390                                 page => pagename($file),
391                                 diffurl => $diffurl,
392                         };
393                 }
394                 push @messages, { line => $title };
395
396                 my ($user, $type) = (q{}, "web");
397
398                 if (defined $messages[0] &&
399                     $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
400                         $user = defined $2 ? "$2" : "$3";
401                         $messages[0]->{line} = $4;
402                 }
403                 else {
404                         $type ="git";
405                         $user = $ci->{'author_username'};
406                 }
407
408                 push @rets, {
409                         rev        => $sha1,
410                         user       => $user,
411                         committype => $type,
412                         when       => $when,
413                         message    => [@messages],
414                         pages      => [@pages],
415                 };
416
417                 last if @rets >= $num;
418         }
419
420         return @rets;
421 } #}}}
422
423 sub rcs_notify () { #{{{
424         # Send notification mail to subscribed users.
425         #
426         # In usual Git usage, hooks/update script is presumed to send
427         # notification mails (see git-receive-pack(1)).  But we prefer
428         # hooks/post-update to support IkiWiki commits coming from a
429         # cloned repository (through command line) because post-update
430         # is called _after_ each ref in repository is updated (update
431         # hook is called _before_ the repository is updated).  Since
432         # post-update hook does not accept command line arguments, we
433         # don't have an $ENV variable in this function.
434         #
435         # Here, we rely on a simple fact: we can extract all parts of the
436         # notification content by parsing the "HEAD" commit (which also
437         # triggers a refresh of IkiWiki pages).
438
439         my $ci = git_commit_info('HEAD');
440         return if !defined $ci;
441
442         my @changed_pages = map { $_->{'file'} } @{ $ci->{'details'} };
443
444         my ($user, $message);
445         if (@{ $ci->{'comment'} }[0] =~ m/$config{web_commit_regexp}/) {
446                 $user    = defined $2 ? "$2" : "$3";
447                 $message = $4;
448         }
449         else {
450                 $user    = $ci->{'author_username'};
451                 $message = join "\n", @{ $ci->{'comment'} };
452         }
453
454         my $sha1 = $ci->{'commit'};
455
456         require IkiWiki::UserInfo;
457         send_commit_mails(
458                 sub {
459                         $message;
460                 },
461                 sub {
462                         join "\n", run_or_die('git-diff', "${sha1}^", $sha1);
463                 }, $user, @changed_pages
464         );
465 } #}}}
466
467 sub rcs_getctime ($) { #{{{
468         my $file=shift;
469         # Remove srcdir prefix
470         $file =~ s/^\Q$config{srcdir}\E\/?//;
471
472         my $sha1  = git_sha1($file);
473         my $ci    = git_commit_info($sha1);
474         my $ctime = $ci->{'author_epoch'};
475         debug("ctime for '$file': ". localtime($ctime));
476
477         return $ctime;
478 } #}}}
479
480 1