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