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