]> sipb.mit.edu Git - ikiwiki.git/blob - doc/todo/darcs.mdwn
response
[ikiwiki.git] / doc / todo / darcs.mdwn
1 Here's Thomas Schwinge unfinished darcs support for ikiwiki.
2
3 (Finishing this has been suggested as a [[soc]] project.)
4
5 > I haven't been working on this for months and also won't in the near
6 > future.  Feel free to use what I have done so
7 > far and bring it into an usable state!  Also, feel free to contact me
8 >  if there are questions.
9
10 -- [Thomas Schwinge](mailto:tschwinge@gnu.org)
11
12 [[toggle text="show"]]
13 [[toggleable text="""
14         # Support for the darcs rcs, <URL:http://darcs.net/>.
15         # Copyright (C) 2006  Thomas Schwinge <tschwinge@gnu.org>
16         #
17         # This program is free software; you can redistribute it and/or modify it
18         # under the terms of the GNU General Public License as published by the
19         # Free Software Foundation; either version 2 of the License, or (at your
20         # option) any later version.
21         #
22         # This program is distributed in the hope that it will be useful, but
23         # WITHOUT ANY WARRANTY; without even the implied warranty of
24         # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25         # General Public License for more details.
26         #
27         # You should have received a copy of the GNU General Public License along
28         # with this program; if not, write to the Free Software Foundation, Inc.,
29         # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
30         
31         
32         # We're guaranteed to be the only instance of ikiwiki running at a given
33         # time.  It is essential that only ikiwiki is working on a particular
34         # repository.  That means one instance of ikiwiki and it also means that
35         # you must not `darcs push' into this repository, as this might create
36         # race conditions, as I understand it.
37         
38         
39         use warnings;
40         use strict;
41         use IkiWiki;
42         
43         package IkiWiki;
44         
45         
46         # Which darcs executable to use.
47         my $darcs = ($ENV{DARCS} or 'darcs');
48         
49         
50         # Internal functions.
51         
52         sub darcs_info ($$$) {
53             my $field = shift;
54             my $repodir = shift;
55             my $file = shift; # Relative to the repodir.
56         
57             my $child = open(DARCS_CHANGES, "-|");
58             if (! $child) {
59                 exec($darcs, 'changes', '--repo=' . $repodir, '--xml-output', $file) or
60                     error('failed to run `darcs changes\'');
61             }
62         
63             # Brute force for now.  :-/
64             while (<DARCS_CHANGES>) {
65                 last if /^<\/created_as>$/;
66             }
67             ($_) = <DARCS_CHANGES> =~ /$field=\'([^\']+)/;
68             $field eq 'hash' and s/\.gz//; # Strip away the `.gz' from `hash'es.
69         
70             close(DARCS_CHANGES) or error('`darcs changes\' exited ' . $?);
71         
72             return $_;
73         }
74         
75         
76         # Exported functions.
77         
78         sub rcs_update () {
79             # Not needed.
80         }
81         
82         sub rcs_prepedit ($) {
83             # Prepares to edit a file under revision control.  Returns a token that
84             # must be passed to rcs_commit() when the file is to be commited.  For us,
85             # this token the hash value of the latest patch that modifies the file,
86             # i.e. something like its current revision.  If the file is not yet added
87             # to the repository, we return TODO: the empty string.
88         
89             my $file = shift; # Relative to the repodir.
90         
91             my $hash = darcs_info('hash', $config{srcdir}, $file);
92             return defined $hash ? $hash : "";
93         }
94         
95         sub rcs_commit ($$$) {
96             # Commit the page.  Returns `undef' on success and a version of the page
97             # with conflict markers on failure.
98         
99             my $file = shift; # Relative to the repodir.
100             my $message = shift;
101             my $rcstoken = shift;
102         
103             # Compute if the ``revision'' of $file changed.
104             my $changed = darcs_info('hash', $config{srcdir}, $file) ne $rcstoken;
105         
106             # Yes, the following is a bit convoluted.
107             if ($changed) {
108                 # TODO.  Invent a better, non-conflicting name.
109                 rename("$config{srcdir}/$file", "$config{srcdir}/$file.save") or
110                     error("failed to rename $file to $file.save: $!");
111         
112                 # Roll the repository back to $rcstoken.
113         
114                 # TODO.  Can we be sure that no changes are lost?  I think that
115                 # we can, if we make sure that the `darcs push' below will always
116                 # succeed.
117         
118                 # We need to revert everything as `darcs obliterate' might choke
119                 # otherwise.
120                 # TODO: `yes | ...' needed?  Doesn't seem so.
121                 system($darcs, "revert", "--repodir=" . $config{srcdir}, "--all") and
122                     error("`darcs revert' failed");
123                 # Remove all patches starting at $rcstoken.
124                 # TODO.  Something like `yes | darcs obliterate ...' seems to be needed.
125                 system($darcs, "obliterate", "--quiet", "--repodir" . $config{srcdir},
126                        "--match", "hash " . $rcstoken) and
127                            error("`darcs obliterate' failed");
128                 # Restore the $rcstoken one.
129                 system($darcs, "pull", "--quiet", "--repodir=" . $config{srcdir},
130                        "--match", "hash " . $rcstoken, "--all") and
131                            error("`darcs pull' failed");
132         
133                 # We're back at $rcstoken.  Re-install the modified file.
134                 rename("$config{srcdir}/$file.save", "$config{srcdir}/$file") or
135                     error("failed to rename $file.save to $file: $!");
136             }
137         
138             # Record the changes.
139             # TODO: What if $message is empty?
140             writefile("$file.log", $config{srcdir}, $message);
141             system($darcs, 'record', '--repodir=' . $config{srcdir}, '--all',
142                    '--logfile=' . "$config{srcdir}/$file.log",
143                    '--author=' . 'web commit <web-hurd@gnu.org>', $file) and
144                        error('`darcs record\' failed');
145         
146             # Update the repository by pulling from the default repository, which is
147             # master repository.
148             system($darcs, "pull", "--quiet", "--repodir=" . $config{srcdir},
149                    "--all") and error("`darcs pull' failed\n");
150         
151             # If this updating yields any conflicts, we'll record them now to resolve
152             # them.  If nothing is recorded, there are no conflicts.
153             $rcstoken = darcs_info('hash', $config{srcdir}, $file);
154             # TODO: Use only the first line here, i.e. only the patch name?
155             writefile("$file.log", $config{srcdir}, 'resolve conflicts: ' . $message);
156             system($darcs, 'record', '--repodir=' . $config{srcdir}, '--all',
157                    '--logfile=' . "$config{srcdir}/$file.log",
158                    '--author=' . 'web commit <web-hurd@gnu.org>', $file) and
159                        error('`darcs record\' failed');
160             my $conflicts = darcs_info('hash', $config{srcdir}, $file) ne $rcstoken;
161             unlink("$config{srcdir}/$file.log") or
162                 error("failed to remove `$file.log'");
163         
164             # Push the changes to the main repository.
165             system($darcs, 'push', '--quiet', '--repodir=' . $config{srcdir}, '--all')
166                 and error('`darcs push\' failed');
167             # TODO: darcs send?
168         
169             if ($conflicts) {
170                 my $document = readfile("$config{srcdir}/$file");
171                 # Try to leave everything in a consistent state.
172                 # TODO: `yes | ...' needed?  Doesn't seem so.
173                 system($darcs, "revert", "--repodir=" . $config{srcdir}, "--all") and
174                     warn("`darcs revert' failed.\n");
175                 return $document;
176             } else {
177                 return undef;
178             }
179         }
180         
181         sub rcs_add ($) {
182             my $file = shift; # Relative to the repodir.
183         
184             # Intermediate directories will be added automagically.
185             system($darcs, 'add', '--quiet', '--repodir=' . $config{srcdir},
186                    '--boring', $file) and error('`darcs add\' failed');
187         }
188         
189         sub rcs_recentchanges ($) {
190             warn('rcs_recentchanges() is not implemented');
191             return 'rcs_recentchanges() is not implemented';
192         }
193         
194         sub rcs_notify () {
195             warn('rcs_notify() is not implemented');
196         }
197         
198         sub rcs_getctime () {
199             warn('rcs_getctime() is not implemented');
200         }
201         
202         1
203 """]]
204
205 This is my ([bma](bma@bmalee.eu)) darcs.pm - it's messy (my Perl isn't up to much) but seems to work. It uses just one repo, like the mercurial plugin (unlike the above version, which AIUI uses two).
206
207 `rcs_commit()` uses backticks instead of `system()`, to prevent darcs' output being sent to the browser and mucking with the HTTP headers (`darcs record` has no --quiet option). And `rcs_recentchanges()` uses regexes rather than parsing darcs' XML output.
208
209 [[toggle text="show" id="bma"]]
210 [[toggleable id="bma" text="""
211
212         #!/usr/bin/perl
213         
214         use warnings;
215         use strict;
216         use IkiWiki;
217         use Date::Parse;
218         use open qw{:utf8 :std};
219         
220         package IkiWiki;
221         
222         sub rcs_update () { #{{{
223                 # Do nothing - there's nowhere to update *from*.
224         } #}}}
225         
226         sub rcs_prepedit ($) { #{{{
227         } #}}}
228         
229         sub rcs_commit ($$$;$$) { #{{{
230                 my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
231         
232                 # $user should probably be a name and an email address, by darcs
233                 # convention.
234                 if (defined $user) {
235                         $user = possibly_foolish_untaint($user);
236                 }
237                 elsif (defined $ipaddr) {
238                         $user = "Anonymous from $ipaddr";
239                 }
240                 else {
241                         $user = "Anonymous";
242                 }
243         
244                 $message = possibly_foolish_untaint($message);
245                 
246                 # BUG: this outputs one line of text, and there's not a -q or --quiet
247                 # option. Redirecting output to /dev/null works, but I still get the
248                 # HTTP status and location headers displayed in the browser - is that
249                 # darcs' fault or ikiwiki's?
250                 # Doing it in backticks *works*, but I'm sure it could be done better.
251                 my @cmdline = ("darcs", "record", "--repodir", "$config{srcdir}",
252                                "-a", "-m", "$message", "--author", "$user", $file);
253                 `darcs record --repodir "$config{srcdir}" -a -m "$message" --author "$user" $file`; # Return value? Output? Who needs 'em?
254                 #if (system(@cmdline) != 0) {
255                 #       warn "'@cmdline' failed: $!";
256                 #}
257         
258                 return undef; # success
259                 
260         sub rcs_add ($) { # {{{
261                 my ($file) = @_;
262         
263                 my @cmdline = ("darcs", "add", "--repodir", "$config{srcdir}", "-a", "-q", "$file");
264                 if (system(@cmdline) != 0) {
265                         warn "'@cmdline' failed: $!";
266                 }
267         } #}}}
268         
269         sub rcs_recentchanges ($) { #{{{
270                 # TODO: This is horrible code. It doesn't work perfectly, and uses regexes
271                 # rather than parsing Darcs' XML output.
272                 my $num=shift;
273                 my @ret;
274                 
275                 return unless -d "$config{srcdir}/_darcs";
276         
277                 my $changelog = `darcs changes --xml --summary --repodir "$config{srcdir}"`;
278                 $changelog = join("", split(/\s*\n\s*/, $changelog));
279                 my @changes = split(/<\/patch>.*?<patch/m, $changelog);
280         
281         
282                 foreach my $change (@changes) {
283                         $change =~ m/hash='(.*?)'/;
284                         my $rev = $1;
285                         $change =~ m/author='(.*?)'/;
286                         my $user = $1."\n";
287                         my $committype = "web";
288                         if($user =~ m/&lt;/) {
289                                 # Author fields generated by darcs include an email address: look for the "<".
290                                 $committype = "darcs";
291                                 use HTML::Entities;
292                                 $user = decode_entities $user;
293                         }
294                         $change =~ m/local_date='(.*?)'/;
295                         my $when = $1;
296                         $when=time - str2time($when, 'UTC');
297                         $change =~ m/<name>(.*?)<\/name>/g;
298                         my @message = {line => $1};
299                         foreach my $match ($change =~ m/<comment>(.*?)<\/comment>/gm) {
300                                 push @message, {line => $1};
301                         }
302
303                         my @pages;
304                         foreach my $match ($change =~ m/<.*?_(file|directory)>(.*?)(<(added|removed)_lines.*\/>)*<\/.*?_(file|directory)>/g) {
305                                 # My perl-fu is weak. I'm probably going about this all wrong, anyway.
306                                 push @pages, {page => pagename($match)} if ( -f $config{srcdir}."/".$match || -d $config{srcdir}."/".$match) and not $match =~ m/^$/;
307                         }
308                         push @ret, { rev => $rev,
309                                         user => $user,
310                                         committype => $committype,
311                                         when => $when,
312                                         message => [@message],
313                                         pages => [@pages],
314                                 }
315                 }
316                 return @ret;
317         } #}}}
318         
319         sub rcs_notify () { #{{{
320                 # TODO
321         } #}}}
322         
323         sub rcs_getctime ($) { #{{{
324                 error gettext("getctime not implemented");
325         } #}}}
326         
327         1
328
329
330
331 """]]
332
333 ---
334
335 Well, here's my version too. It only does getctime -- using a real XML parser, instead of regexp ugliness -- and maybe recentchanges, but that may be bitrotted, or maybe I never finished it, as I only need the getctime. As for actual commits, I have previously voiced my opinion, that this should be done by the plugin generating a patch bundle, and forwarding it to darcs in some way (`darcs apply` or even email to another host, possibly moderated), instead of the hacky direct modification of a working copy. It could also be faster to getctime in a batch. Just reading in all the changes the first time they're needed, might not be a big improvement in many cases, but if we got a batch request from ikiwiki, we could keep reaing the changes until all the files in this batch request have been met.  --[[tuomov]]
336
337 [[toggle text="show" id="tuomov"]]
338 [[toggleable id="tuomov" text="""
339 <pre>
340 #!/usr/bin/perl
341 # Stubs for no revision control.
342
343 use warnings;
344 use strict;
345 use IkiWiki;
346
347 package IkiWiki;
348
349 sub rcs_update () {
350 }
351
352 sub rcs_prepedit ($) {
353         return ""
354 }
355
356 sub rcs_commit ($$$) {
357         return undef # success
358 }
359
360 sub rcs_add ($) {
361 }
362
363 sub rcs_recentchanges ($) {
364         my $num=shift;
365         my @ret;
366         
367         eval q{use Date::Parse};
368         eval q{use XML::Simple};
369         
370         my $repodir=$config{srcdir};
371         
372         if (-d "$config{srcdir}/_darcs") {
373                 my $child = open(LOG, "-|");
374                 if (! $child) {
375                         exec("darcs", "changes", "--xml", 
376                              "--repodir", "$repodir",
377                              "--last", "$num")
378                         || error("darcs changes failed to run");
379                 }
380                 my $data=<LOG>;
381                 close LOG;
382                 
383                 my $log = XMLin($data, ForceArray => 1);
384                 
385                 foreach my $patch ($log->{patch}) {
386                         my $date=$patch->{local_date};
387                         my $hash=$patch->{hash};
388                         my $when=concise(ago(time - str2time($date)));
389                         my @pages;
390                         
391                         my $child = open(SUMMARY, "-|");
392                         if (! $child) {
393                                 exec("darcs", "annotate", "-s", "--xml", 
394                                      "--match", "hash: $hash",
395                                      "--repodir", "$repodir")
396                                 || error("darcs annotate failed to run");
397                         }
398                         my $data=<SUMMARY>;
399                         close SUMMARY;
400                 
401                         my $summary = XMLin("<lame>$data</lame>", ForceArray => 1);
402
403                         # TODO: find @pages
404                         
405                         push @ret, {
406                                 #rev => $rev,
407                                 user => $patch->{author},
408                                 #committype => $committype,
409                                 when => $when, 
410                                 #message => [@message],
411                                 pages => [@pages],
412                         }; # if @pages;
413                         return @ret if @ret >= $num;
414                 }
415         }
416         
417         return @ret;
418 }
419
420 sub rcs_notify () {
421 }
422
423 sub rcs_getctime ($) {
424         my $file=shift;
425         
426         eval q{use Date::Parse};
427         eval q{use XML::Simple};
428         local $/=undef;
429         
430         # Sigh... doing things the hard way again
431         my $repodir=$config{srcdir};
432         
433         my $filer=substr($file, length($repodir));
434         $filer =~ s:^[/]+::;
435         
436         my $child = open(LOG, "-|");
437         if (! $child) {
438                 exec("darcs", "changes", "--xml", "--reverse",
439                      "--repodir", "$repodir", "$filer")
440                 || error("darcs changes $filer failed to run");
441         }
442         
443         my $data=<LOG>;
444         close LOG;
445         
446         my $log = XMLin($data, ForceArray => 1);
447         
448         my $datestr=$log->{patch}[0]->{local_date};
449         
450         if (! defined $datestr) {
451                 warn "failed to get ctime for $filer";
452                 return 0;
453         }
454         
455         my $date=str2time($datestr);
456         
457         debug("found ctime ".localtime($date)." for $file");
458         
459         return $date;
460 }
461
462 1
463 </pre>
464 """]]
465
466 ---
467
468 I merged the two versions above and made some fixes; it is recording my web edits in darcs and showing a recent changes page.
469 It is in a [darcs repository](http://joyful.com/darcsweb/darcsweb.cgi?r=ikiwiki-darcs), please send patches. --[[Simon_Michael]]
470
471 > I'd like to see at least the following fixed before I commit this: --[[Joey]]
472 > * Running `darcs record $filename` in backticks is not good (security)
473 >   The thing to do is to open stdout to /dev/null before execing darcs.
474 > * Get `rcs_recentchanges_xml` working, parsing xml with regexps does
475 >   not seem like a maintenance win.
476 > * `rcs_notify` should be removed, it's no longer used.
477 > * Some form of conflict handling. Using darcs to attempt to merge
478 >   the changes is I gusss optional (although every other rcs backend,
479 >   including svn manages to do this), but it needs to at *least* detect
480 >   conflicts and return a page with conflict markers for the user to fix
481 >   the conflict.
482
483 [[tag patch]]