updated from pesco's darcs repo, current to Oct 11 version
[ikiwiki] / 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 # Internal functions
64
65 sub silentsystem (@) {
66         open(SAVED_STDOUT, ">&STDOUT");
67         open(STDOUT, ">/dev/null");
68         my $ret = system @_;
69         open(STDOUT, ">&SAVED_STDOUT");
70         return $ret;
71 }
72
73 sub darcs_info ($$$) {
74         my $field = shift;
75         my $repodir = shift;
76         my $file = shift; # Relative to the repodir.
77
78         my $child = open(DARCS_CHANGES, "-|");
79         if (! $child) {
80                 exec('darcs', 'changes', '--repodir', $repodir, '--xml-output', $file) or
81                         error("failed to run 'darcs changes'");
82         }
83
84         # Brute force for now.  :-/
85         while (<DARCS_CHANGES>) {
86                 last if /^<\/created_as>$/;
87         }
88         ($_) = <DARCS_CHANGES> =~ /$field=\'([^\']+)/;
89         $field eq 'hash' and s/\.gz//; # Strip away the '.gz' from 'hash'es.
90
91         close(DARCS_CHANGES) or error("'darcs changes' exited " . $?);
92
93         return $_;
94 }
95
96 sub darcs_rev($) {
97         my $file = shift; # Relative to the repodir.
98         my $repodir = $config{srcdir};
99
100         my $child = open(DARCS_MANIFEST, "-|");
101         if (! $child) {
102                 exec('darcs', 'query', 'manifest', '--repodir', $repodir) or
103                         error("failed to run 'darcs query manifest'");
104         }
105         my $found=0;
106         while (<DARCS_MANIFEST>) {
107                 $found = 1, last if /^$file$/;
108         }
109         return "" if (! $found);
110         close(DARCS_MANIFEST) or error("'darcs query manifest' exited " . $?);
111
112         my $hash = darcs_info('hash', $repodir, $file);
113         return defined $hash ? $hash : "";
114 }
115
116
117 # Exported functions.
118
119 sub checkconfig() {
120         if (defined $config{darcs_wrapper} && length $config{darcs_wrapper}) {
121                 push @{$config{wrappers}}, {
122                         wrapper => $config{darcs_wrapper},
123                         wrappermode => (defined $config{darcs_wrappermode} ? $config{darcs_wrappermode} : "06755"),
124                 };
125         }
126 }
127
128 sub getsetup() {
129         return
130         plugin => {
131                 safe => 0, # rcs plugin
132                 rebuild => undef,
133         },
134         darcs_wrapper => {
135                 type => "string",
136                 example => "/darcs/repo/_darcs/ikiwiki-wrapper",
137                 description => "wrapper to generate (set as master repo apply hook)",
138                 safe => 0, # file
139                 rebuild => 0,
140         },
141         darcs_wrappermode => {
142                 type => "string",
143                 example => '06755',
144                 description => "mode for darcs_wrapper (can safely be made suid)",
145                 safe => 0,
146                 rebuild => 0,
147         },
148         historyurl => {
149                 type => "string",
150                 example => "http://darcs.example.com/darcsweb.cgi?r=wiki;a=filehistory;f=[[file]]",
151                 description => "darcsweb url to show file history ([[file]] substituted)",
152                 safe => 1,
153                 rebuild => 1,
154         },
155         diffurl => {
156                 type => "string",
157                 example => "http://darcs.example.com/darcsweb.cgi?r=wiki;a=filediff;h=[[hash]];f=[[file]]",
158                 description => "darcsweb url to show a diff ([[hash]] and [[file]] substituted)",
159                 safe => 1,
160                 rebuild => 1,
161         },
162 }
163
164 sub rcs_update () {
165         silentsystem('darcs', "pull", "--repodir", $config{srcdir}, "-qa")
166 }
167
168 sub rcs_prepedit ($) {
169         # Prepares to edit a file under revision control.  Returns a token that
170         # must be passed to rcs_commit() when the file is to be commited.  For us,
171         # this token the hash value of the latest patch that modifies the file,
172         # i.e. something like its current revision.  If the file is not yet added
173         # to the repository, we return TODO: the empty string.
174
175         my $file = shift; # Relative to the repodir.
176         my $rev = darcs_rev($file);
177         return $rev;
178 }
179
180 sub rcs_commit ($$$;$$) {
181         # Commit the page.  Returns 'undef' on success and a version of the page
182         # with conflict markers on failure.
183
184         my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
185
186         # Compute if the "revision" of $file changed.
187         my $changed = darcs_rev($file) ne $rcstoken;
188
189         # Yes, the following is a bit convoluted.
190         if ($changed) {
191         # TODO.  Invent a better, non-conflicting name.
192         rename("$config{srcdir}/$file", "$config{srcdir}/$file.save") or
193                 error("failed to rename $file to $file.save: $!");
194
195         # Roll the repository back to $rcstoken.
196
197         # TODO.  Can we be sure that no changes are lost?  I think that
198         # we can, if we make sure that the 'darcs push' below will always
199         # succeed.
200
201         # We need to revert everything as 'darcs obliterate' might choke
202         # otherwise.
203         # TODO: 'yes | ...' needed?  Doesn't seem so.
204         silentsystem('darcs', "revert", "--repodir", $config{srcdir}, "--all") and
205                 error("'darcs revert' failed");
206         # Remove all patches starting at $rcstoken.
207         my $child = open(DARCS_OBLITERATE, "|-");
208         if (! $child) {
209                 open(STDOUT, ">/dev/null");
210                 exec('darcs', "obliterate", "--repodir", $config{srcdir},
211                    "--match", "hash " . $rcstoken) and
212                    error("'darcs obliterate' failed");
213         }
214         while (print DARCS_OBLITERATE "y") {
215                 ;
216         }
217         close(DARCS_OBLITERATE);
218         # Restore the $rcstoken one.
219         silentsystem('darcs', "pull", "--quiet", "--repodir", $config{srcdir},
220                 "--match", "hash " . $rcstoken, "--all") and
221                 error("'darcs pull' failed");
222
223         # We're back at $rcstoken.  Re-install the modified file.
224         rename("$config{srcdir}/$file.save", "$config{srcdir}/$file") or
225                 error("failed to rename $file.save to $file: $!");
226         }
227
228         # Record the changes.
229         my $author;
230         if (defined $user) {
231                 $author = "$user\@web";
232         } elsif (defined $ipaddr) {
233                 $author = "$ipaddr\@web";
234         } else {
235                 $author = "anon\@web";
236         }
237         if (!defined $message || !length($message)) {
238                 $message = "empty message";
239         }
240         silentsystem('darcs', 'record', '--repodir', $config{srcdir}, '--all',
241            '-m', $message, '--author', $author, $file) and
242                 error("'darcs record' failed");
243
244         # Update the repository by pulling from the default repository, which is
245         # master repository.
246         silentsystem('darcs', "pull", "--quiet", "--repodir", $config{srcdir},
247                 "--all") and error("'darcs pull' failed");
248
249         # If this updating yields any conflicts, we'll record them now to resolve
250         # them.  If nothing is recorded, there are no conflicts.
251         $rcstoken = darcs_rev($file);
252         # TODO: Use only the first line here, i.e. only the patch name?
253         writefile("$file.log", $config{srcdir}, 'resolve conflicts: ' . $message);
254         silentsystem('darcs', 'record', '--repodir', $config{srcdir}, '--all',
255                 '-m', 'resolve conflicts: ' . $message, '--author', $author, $file) and
256                 error("'darcs record' failed");
257         my $conflicts = darcs_rev($file) ne $rcstoken;
258         unlink("$config{srcdir}/$file.log") or
259         error("failed to remove '$file.log'");
260
261         # Push the changes to the main repository.
262         silentsystem('darcs', 'push', '--quiet', '--repodir', $config{srcdir}, '--all')
263         and error("'darcs push' failed");
264         # TODO: darcs send?
265
266         if ($conflicts) {
267                 my $document = readfile("$config{srcdir}/$file");
268                 # Try to leave everything in a consistent state.
269                 # TODO: 'yes | ...' needed?  Doesn't seem so.
270                 silentsystem('darcs', "revert", "--repodir", $config{srcdir}, "--all") and
271                         warn("'darcs revert' failed");
272                 return $document;
273         } else {
274                 return undef;
275         }
276 }
277
278 sub rcs_commit_staged($$$) {
279         my ($message, $user, $ipaddr) = @_;
280
281         my $author;
282         if (defined $user) {
283                 $author = "$user\@web";
284         } elsif (defined $ipaddr) {
285                 $author = "$ipaddr\@web";
286         } else {
287                 $author = "anon\@web";
288         }
289         if (!defined $message || !length($message)) {
290                 $message = "empty message";
291         }
292
293         silentsystem('darcs', "record", "--repodir", $config{srcdir}, "-a", "-A", $author,
294                 "-m", $message) and error("'darcs record' failed");
295
296         # Push the changes to the main repository.
297         silentsystem('darcs', 'push', '--quiet', '--repodir', $config{srcdir}, '--all')
298                 and error("'darcs push' failed");
299         # TODO: darcs send?
300
301         return undef;
302 }
303
304 sub rcs_add ($) {
305         my $file = shift; # Relative to the repodir.
306
307         # Intermediate directories will be added automagically.
308         system('darcs', 'add', '--quiet', '--repodir', $config{srcdir},
309            '--boring', $file) and error("'darcs add' failed");
310 }
311
312 sub rcs_remove ($) {
313         my $file = shift; # Relative to the repodir.
314
315         unlink($config{srcdir}.'/'.$file);
316 }
317
318 sub rcs_rename ($$) {
319         my $a = shift; # Relative to the repodir.
320         my $b = shift; # Relative to the repodir.
321
322         system('darcs', 'mv', '--repodir', $config{srcdir}, $a, $b)
323            and error("'darcs mv' failed");
324 }
325
326 sub rcs_recentchanges ($) {
327         my $num=shift;
328         my @ret;
329
330         eval q{use Date::Parse};
331         eval q{use XML::Simple};
332
333         my $repodir=$config{srcdir};
334
335         debug("darcs recent changes: $num");
336
337         my $child = open(LOG, "-|");
338         if (! $child) {
339                 $ENV{"DARCS_DONT_ESCAPE_ANYTHING"}=1;
340                 exec("darcs", "changes", "--xml", 
341                         "--summary",
342                          "--repodir", "$repodir",
343                          "--last", "$num")
344                 || error("'darcs changes' failed to run");
345         }
346         my $data;
347         $data .= $_ while(<LOG>);
348         close LOG;
349
350         my $log = XMLin($data, ForceArray => 1);
351
352         debug("parsing recent changes...");
353         foreach my $patch (@{$log->{patch}}) {
354                 my $date=$patch->{local_date};
355                 my $hash=$patch->{hash};
356                 my $when=str2time($date);
357                 my (@pages, @files, @pg);
358                 push @pages, $_ for (@{$patch->{summary}->[0]->{modify_file}});
359                 push @pages, $_ for (@{$patch->{summary}->[0]->{add_file}});
360                 push @pages, $_ for (@{$patch->{summary}->[0]->{remove_file}});
361                 for (@pages) {
362                         my $f = $_;
363                         $f = $_->{content} if (ref $_);
364                         $f =~ s,^\s+,,; $f =~ s,\s+$,,; # cut whitespace
365
366                         push @files, $f;
367                 }
368                 for (@{$patch->{summary}->[0]->{move}}) {
369                         my $p = $_;
370                         push @files, $p->{from};
371                 }
372
373                 for (@files) {
374                         my $f = $_;
375                         my $d = defined $config{'diffurl'} ? $config{'diffurl'} : "";
376                         $d =~ s/\[\[file\]\]/$f/go;
377                         $d =~ s/\[\[hash\]\]/$hash/go;
378
379                         debug("file: $f");
380                         debug("diffurl: $d");
381                         push @pg, {
382                                 page => pagename($f),
383                                 diffurl => $d,
384                         };
385                 }
386                 next unless (scalar @pg > 0);
387                 debug("recent change: " . $patch->{name}[0] . " ("
388                         . scalar @pg . " changes)");
389
390                 my @message;
391                 push @message, { line => $_ } for (@{$patch->{name}});
392
393                 my $committype;
394                 if ($patch->{author} =~ /\@web$/) {
395                         $committype = "web";
396                 } else {
397                         $committype = "darcs";
398                 }
399
400                 push @ret, {
401                         rev => $patch->{hash},
402                         user => $patch->{author},
403                         committype => $committype,
404                         when => $when, 
405                         message => [@message],
406                         pages => [@pg],
407                 };
408         }
409
410         return @ret;
411 }
412
413 sub rcs_diff ($) {
414         my $rev=shift;
415         my @lines;
416         foreach my $line (silentsystem("darcs", "diff", "--match", "hash ".$rev)) {
417                 if (@lines || $line=~/^diff/) {
418                         push @lines, $line."\n";
419                 }
420         }
421         if (wantarray) {
422                 return @lines;
423         }
424         else {
425                 return join("", @lines);
426         }
427 }
428
429 sub rcs_getctime ($) {
430         my $file=shift;
431
432         eval q{use Date::Parse};
433         eval q{use XML::Simple};
434         local $/=undef;
435
436         # Sigh... doing things the hard way again
437         my $repodir=$config{srcdir};
438
439         my $filer=substr($file, length($repodir));
440         $filer =~ s:^[/]+::;
441
442         my $child = open(LOG, "-|");
443         if (! $child) {
444                 exec("darcs", "changes", "--xml", "--reverse",
445                         "--repodir", "$repodir", "$filer")
446                 || error("'darcs changes $filer' failed to run");
447         }
448
449         my $data;
450         $data .= $_ while(<LOG>);
451         close LOG;
452
453         my $log = XMLin($data, ForceArray => 1);
454
455         my $datestr=$log->{patch}[0]->{local_date};
456
457         if (! defined $datestr) {
458                 warn "failed to get ctime for $filer";
459                 return 0;
460         }
461
462         my $date=str2time($datestr);
463
464         #debug("found ctime ".localtime($date)." for $filer");
465
466         return $date;
467 }
468
469 1
470
471 # vim: ts=4 sw=4 noet