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