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