0957ef0efd9dff6197e04f097b3471798e90066e
[ikiwiki.git] / IkiWiki / Plugin / darcs.pm
1 # Support for the darcs rcs, <URL:http://darcs.net/>.
2 # Copyright (C) 2006  Thomas Schwinge <tschwinge@gnu.org>
3 #               2007  Benjamin A'Lee <bma@bmalee.eu>
4 #                     Tuomo Valkonen <tuomov@iki.fi>
5 #               2008  Simon Michael <simon@joyful.com>
6 #                     Petr Ročkai <me@mornfall.net>
7 #                     Sven M. Hallberg <pesco@khjk.org>
8 #
9 # This program is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by the
11 # Free Software Foundation; either version 2 of the License, or (at your
12 # option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 # General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License along
20 # with this program; if not, write to the Free Software Foundation, Inc.,
21 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22
23 # History (see http://ikiwiki.info/todo/darcs/):
24 #
25 #  * Thomas Schwinge wrote the original file, implementing only rcs_commit.
26 #  * Benjamin A'Lee contributed an alternative implementation.
27 #  * Tuomo Valkonen contributed rcs_getctime and stub rcs_recentchanges.
28 #  * Simon Michael contributed multiple changes.
29 #  * Petr Ročkai fixed rcs_recentchanges and added caching to rcs_getctime.
30 #  * Sven M. Hallberg merged the above and added missing features.
31
32
33 # We're guaranteed to be the only instance of ikiwiki running at a given
34 # time.  It is essential that only ikiwiki is working on a particular
35 # repository.  That means one instance of ikiwiki and it also means that
36 # you must not 'darcs push' into this repository, as this might create
37 # race conditions, as I understand it.
38
39
40 package IkiWiki::Plugin::darcs;
41
42 use warnings;
43 use strict;
44 use IkiWiki;
45
46
47 sub import {
48     hook(type => "checkconfig", id => "darcs", call => \&checkconfig);
49     hook(type => "getsetup", id => "darcs", call => \&getsetup);
50     hook(type => "rcs", id => "rcs_update", call => \&rcs_update);
51     hook(type => "rcs", id => "rcs_prepedit", call => \&rcs_prepedit);
52     hook(type => "rcs", id => "rcs_commit", call => \&rcs_commit);
53     hook(type => "rcs", id => "rcs_commit_staged", call => \&rcs_commit_staged);
54     hook(type => "rcs", id => "rcs_add", call => \&rcs_add);
55     hook(type => "rcs", id => "rcs_remove", call => \&rcs_remove);
56     hook(type => "rcs", id => "rcs_rename", call => \&rcs_rename);
57     hook(type => "rcs", id => "rcs_recentchanges", call => \&rcs_recentchanges);
58     hook(type => "rcs", id => "rcs_diff", call => \&rcs_diff);
59     hook(type => "rcs", id => "rcs_getctime", call => \&rcs_getctime);
60 }
61
62
63 # Which darcs executable to use.
64 my $darcs = ($ENV{DARCS} or 'darcs');
65
66
67 # Internal functions
68
69 our %cache;
70
71 sub loadcache () {
72     my $repodir=$config{srcdir};
73     if (!defined %cache) {
74         my $f = "$repodir/.ikiwiki.ctimes";
75         if (-s "$f") {
76             my $VAR1;
77             my $x = `cat "$f"`;
78             $x =~ /^(.*)$/sm; # untaint
79             eval "$1";
80             %cache = %$VAR1;
81         }
82     }
83 }
84
85 END {
86     my $repodir=$config{srcdir};
87     if (defined %cache) {
88         debug("dumping ctime cache to $repodir/.ikiwiki.ctimes");
89         open CACHE, ">$repodir/.ikiwiki.ctimes";
90         print CACHE Dumper(\%cache);
91         close CACHE;
92     }
93 }
94
95 sub silentsystem (@) {
96     open(SAVED_STDOUT, ">&STDOUT");
97     open(STDOUT, ">/dev/null");
98     my $ret = system @_;
99     open(STDOUT, ">&SAVED_STDOUT");
100     return $ret;
101 }
102
103 sub darcs_info ($$$) {
104     my $field = shift;
105     my $repodir = shift;
106     my $file = shift; # Relative to the repodir.
107
108     my $child = open(DARCS_CHANGES, "-|");
109     if (! $child) {
110     exec($darcs, 'changes', '--repodir', $repodir, '--xml-output', $file) or
111         error("failed to run 'darcs changes'");
112     }
113
114     # Brute force for now.  :-/
115     while (<DARCS_CHANGES>) {
116     last if /^<\/created_as>$/;
117     }
118     ($_) = <DARCS_CHANGES> =~ /$field=\'([^\']+)/;
119     $field eq 'hash' and s/\.gz//; # Strip away the '.gz' from 'hash'es.
120
121     close(DARCS_CHANGES) or error("'darcs changes' exited " . $?);
122
123     return $_;
124 }
125
126 sub darcs_rev($) {
127     my $file = shift; # Relative to the repodir.
128     my $repodir = $config{srcdir};
129
130     my $child = open(DARCS_MANIFEST, "-|");
131     if (! $child) {
132         exec($darcs, 'query', 'manifest', '--repodir', $repodir) or
133             error("failed to run 'darcs query manifest'");
134     }
135     my $found=0;
136     while (<DARCS_MANIFEST>) {
137         $found = 1, last if /^$file$/;
138     }
139     return "" if (! $found);
140     close(DARCS_MANIFEST) or error("'darcs query manifest' exited " . $?);
141
142     my $hash = darcs_info('hash', $repodir, $file);
143     return defined $hash ? $hash : "";
144 }
145
146
147 # Exported functions.
148
149 sub checkconfig() {
150     if (defined $config{darcs_wrapper} && length $config{darcs_wrapper}) {
151         push @{$config{wrappers}}, {
152             wrapper => $config{darcs_wrapper},
153             wrappermode => (defined $config{darcs_wrappermode} ? $config{darcs_wrappermode} : "06755"),
154         };
155     }
156 }
157
158 sub getsetup() {
159     return
160         plugin => {
161             safe => 0, # rcs plugin
162             rebuild => undef,
163         },
164         darcs_wrapper => {
165             type => "string",
166             example => "/darcs/repo/_darcs/ikiwiki-wrapper",
167             description => "wrapper to generate (set as master repo apply hook)",
168             safe => 0, # file
169             rebuild => 0,
170         },
171         darcs_wrappermode => {
172             type => "string",
173             example => '06755',
174             description => "mode for darcs_wrapper (can safely be made suid)",
175             safe => 0,
176             rebuild => 0,
177         },
178         historyurl => {
179             type => "string",
180             example => "http://darcs.example.com/darcsweb.cgi?r=wiki;a=filehistory;f=[[file]]",
181             description => "darcsweb url to show file history ([[file]] substituted)",
182             safe => 1,
183             rebuild => 1,
184         },
185         diffurl => {
186             type => "string",
187             example => "http://darcs.example.com/darcsweb.cgi?r=wiki;a=filediff;h=[[hash]];f=[[file]]",
188             description => "darcsweb url to show a diff ([[hash]] and [[file]] substituted)",
189             safe => 1,
190             rebuild => 1,
191         },
192 }
193
194 sub rcs_update () {
195     silentsystem($darcs, "pull", "--repodir", $config{srcdir}, "-qa")
196 }
197
198 sub rcs_prepedit ($) {
199     # Prepares to edit a file under revision control.  Returns a token that
200     # must be passed to rcs_commit() when the file is to be commited.  For us,
201     # this token the hash value of the latest patch that modifies the file,
202     # i.e. something like its current revision.  If the file is not yet added
203     # to the repository, we return TODO: the empty string.
204
205     my $file = shift; # Relative to the repodir.
206     my $rev = darcs_rev($file);
207     return $rev;
208 }
209
210 sub rcs_commit ($$$;$$) {
211     # Commit the page.  Returns 'undef' on success and a version of the page
212     # with conflict markers on failure.
213
214     my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
215
216     # Compute if the "revision" of $file changed.
217     my $changed = darcs_rev($file) ne $rcstoken;
218
219     # Yes, the following is a bit convoluted.
220     if ($changed) {
221     # TODO.  Invent a better, non-conflicting name.
222     rename("$config{srcdir}/$file", "$config{srcdir}/$file.save") or
223         error("failed to rename $file to $file.save: $!");
224
225     # Roll the repository back to $rcstoken.
226
227     # TODO.  Can we be sure that no changes are lost?  I think that
228     # we can, if we make sure that the 'darcs push' below will always
229     # succeed.
230
231     # We need to revert everything as 'darcs obliterate' might choke
232     # otherwise.
233         # TODO: 'yes | ...' needed?  Doesn't seem so.
234     silentsystem($darcs, "revert", "--repodir", $config{srcdir}, "--all") and
235         error("'darcs revert' failed");
236     # Remove all patches starting at $rcstoken.
237     my $child = open(DARCS_OBLITERATE, "|-");
238     if (! $child) {
239         open(STDOUT, ">/dev/null");
240         exec($darcs, "obliterate", "--repodir", $config{srcdir},
241            "--match", "hash " . $rcstoken) and
242            error("'darcs obliterate' failed");
243     }
244     while (print DARCS_OBLITERATE "y") {
245         ;
246     }
247     close(DARCS_OBLITERATE);
248     # Restore the $rcstoken one.
249     silentsystem($darcs, "pull", "--quiet", "--repodir", $config{srcdir},
250            "--match", "hash " . $rcstoken, "--all") and
251            error("'darcs pull' failed");
252
253     # We're back at $rcstoken.  Re-install the modified file.
254     rename("$config{srcdir}/$file.save", "$config{srcdir}/$file") or
255         error("failed to rename $file.save to $file: $!");
256     }
257
258     # Record the changes.
259     my $author;
260     if (defined $user) {
261         $author = "$user\@web";
262     } elsif (defined $ipaddr) {
263         $author = "$ipaddr\@web";
264     } else {
265         $author = "anon\@web";
266     }
267     if (!defined $message || !length($message)) {
268         $message = "empty message";
269     }
270     silentsystem($darcs, 'record', '--repodir', $config{srcdir}, '--all',
271        '-m', $message, '--author', $author, $file) and
272            error("'darcs record' failed");
273
274     # Update the repository by pulling from the default repository, which is
275     # master repository.
276     silentsystem($darcs, "pull", "--quiet", "--repodir", $config{srcdir},
277        "--all") and error("'darcs pull' failed");
278
279     # If this updating yields any conflicts, we'll record them now to resolve
280     # them.  If nothing is recorded, there are no conflicts.
281     $rcstoken = darcs_rev($file);
282     # TODO: Use only the first line here, i.e. only the patch name?
283     writefile("$file.log", $config{srcdir}, 'resolve conflicts: ' . $message);
284     silentsystem($darcs, 'record', '--repodir', $config{srcdir}, '--all',
285        '-m', 'resolve conflicts: ' . $message, '--author', $author, $file) and
286            error("'darcs record' failed");
287     my $conflicts = darcs_rev($file) ne $rcstoken;
288     unlink("$config{srcdir}/$file.log") or
289     error("failed to remove '$file.log'");
290
291     # Push the changes to the main repository.
292     silentsystem($darcs, 'push', '--quiet', '--repodir', $config{srcdir}, '--all')
293     and error("'darcs push' failed");
294     # TODO: darcs send?
295
296     if ($conflicts) {
297         my $document = readfile("$config{srcdir}/$file");
298         # Try to leave everything in a consistent state.
299         # TODO: 'yes | ...' needed?  Doesn't seem so.
300         silentsystem($darcs, "revert", "--repodir", $config{srcdir}, "--all") and
301             warn("'darcs revert' failed");
302         return $document;
303     } else {
304         return undef;
305     }
306 }
307
308 sub rcs_commit_staged($$$) {
309     my ($message, $user, $ipaddr) = @_;
310
311     my $author;
312     if (defined $user) {
313         $author = "$user\@web";
314     } elsif (defined $ipaddr) {
315         $author = "$ipaddr\@web";
316     } else {
317         $author = "anon\@web";
318     }
319     if (!defined $message || !length($message)) {
320         $message = "empty message";
321     }
322
323     silentsystem($darcs, "record", "--repodir", $config{srcdir}, "-a", "-A", $author,
324         "-m", $message) and error("'darcs record' failed");
325
326     # Push the changes to the main repository.
327     silentsystem($darcs, 'push', '--quiet', '--repodir', $config{srcdir}, '--all')
328     and error("'darcs push' failed");
329     # TODO: darcs send?
330
331     return undef;
332 }
333
334 sub rcs_add ($) {
335     my $file = shift; # Relative to the repodir.
336
337     # Intermediate directories will be added automagically.
338     system($darcs, 'add', '--quiet', '--repodir', $config{srcdir},
339        '--boring', $file) and error("'darcs add' failed");
340 }
341
342 sub rcs_remove ($) {
343     my $file = shift; # Relative to the repodir.
344
345     system('rm', $config{srcdir}.'/'.$file)
346        and error("'rm' failed");
347 }
348
349 sub rcs_rename ($$) {
350     my $a = shift; # Relative to the repodir.
351     my $b = shift; # Relative to the repodir.
352
353     system($darcs, 'mv', '--repodir', $config{srcdir}, $a, $b)
354        and error("'darcs mv' failed");
355 }
356
357 sub rcs_recentchanges ($) {
358     my $num=shift;
359     my @ret;
360
361     eval q{use Date::Parse};
362     eval q{use XML::Simple};
363
364     my $repodir=$config{srcdir};
365
366     debug("darcs recent changes: $num");
367
368     my $child = open(LOG, "-|");
369     if (! $child) {
370         $ENV{"DARCS_DONT_ESCAPE_ANYTHING"}=1;
371         exec("darcs", "changes", "--xml", 
372             "--summary",
373              "--repodir", "$repodir",
374              "--last", "$num")
375         || error("'darcs changes' failed to run");
376     }
377     my $data;
378     $data .= $_ while(<LOG>);
379     close LOG;
380
381     my $log = XMLin($data, ForceArray => 1);
382
383     debug("parsing recent changes...");
384     foreach my $patch (@{$log->{patch}}) {
385         my $date=$patch->{local_date};
386         my $hash=$patch->{hash};
387         my $when=str2time($date);
388         my (@pages, @files, @pg);
389         push @pages, $_ for (@{$patch->{summary}->[0]->{modify_file}});
390         push @pages, $_ for (@{$patch->{summary}->[0]->{add_file}});
391         push @pages, $_ for (@{$patch->{summary}->[0]->{remove_file}});
392         for (@pages) {
393             my $f = $_;
394             $f = $_->{content} if (ref $_);
395             $f =~ s,^\s+,,; $f =~ s,\s+$,,; # cut whitespace
396
397             push @files, $f;
398         }
399         for (@{$patch->{summary}->[0]->{move}}) {
400             my $p = $_;
401             push @files, $p->{from};
402         }
403
404         for (@files) {
405             my $f = $_;
406             my $d = defined $config{'diffurl'} ? $config{'diffurl'} : "";
407             $d =~ s/\[\[file\]\]/$f/go;
408             $d =~ s/\[\[hash\]\]/$hash/go;
409
410             debug("file: $f");
411             debug("diffurl: $d");
412             push @pg, {
413                 page => pagename($f),
414                 diffurl => $d,
415             };
416         }
417         next unless (scalar @pg > 0);
418         debug("recent change: " . $patch->{name}[0] . " ("
419             . scalar @pg . " changes)");
420
421         my @message;
422         push @message, { line => $_ } for (@{$patch->{name}});
423
424         my $committype;
425         if ($patch->{author} =~ /\@web$/) {
426             $committype = "web";
427         } else {
428             $committype = "darcs";
429         }
430
431         push @ret, {
432             rev => $patch->{hash},
433             user => $patch->{author},
434             committype => $committype,
435             when => $when, 
436             message => [@message],
437             pages => [@pg],
438         };
439     }
440
441     return @ret;
442 }
443
444 sub rcs_diff ($) {
445     my $rev=shift;
446     my @lines;
447     foreach my $line (silentsystem("darcs", "diff", "--match", "hash ".$rev)) {
448         if (@lines || $line=~/^diff/) {
449             push @lines, $line."\n";
450         }
451     }
452     if (wantarray) {
453         return @lines;
454     }
455     else {
456         return join("", @lines);
457     }
458 }
459
460 sub rcs_getctime ($) {
461     my $file=shift;
462
463     eval q{use Date::Parse};
464     eval q{use XML::Simple};
465     local $/=undef;
466
467     # Sigh... doing things the hard way again
468     my $repodir=$config{srcdir};
469
470     &loadcache;
471
472     my $filer=substr($file, length($repodir));
473     $filer =~ s:^[/]+::;
474
475     if (defined $cache{$filer}) {
476         #debug("taking cached ctime ".localtime($cache{$filer})." for $filer");
477         return $cache{$filer};
478     }
479
480     my $child = open(LOG, "-|");
481     if (! $child) {
482         exec("darcs", "changes", "--xml", "--reverse",
483              "--repodir", "$repodir", "$filer")
484         || error("'darcs changes $filer' failed to run");
485     }
486
487     my $data;
488     $data .= $_ while(<LOG>);
489     close LOG;
490
491     my $log = XMLin($data, ForceArray => 1);
492
493     my $datestr=$log->{patch}[0]->{local_date};
494
495     if (! defined $datestr) {
496         warn "failed to get ctime for $filer";
497         $cache{$filer} = 0;
498         return 0;
499     }
500
501     my $date=str2time($datestr);
502
503     #debug("found ctime ".localtime($date)." for $filer");
504
505     $cache{$filer} = $date;
506     return $date;
507 }
508
509 1