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