]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Rcs/monotone.pm
d7e8f296a69f6d80c205ebbcaa4e40f3dc49e8a3
[ikiwiki.git] / IkiWiki / Rcs / monotone.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4
5 use warnings;
6 use strict;
7 use IkiWiki;
8 use Monotone;
9 use Date::Parse qw(str2time);
10 use Date::Format qw(time2str);
11
12 my $sha1_pattern = qr/[0-9a-fA-F]{40}/; # pattern to validate sha1sums
13
14 hook(type => "checkconfig", id => "monotone", call => sub { #{{{
15         if (!defined($config{mtnrootdir})) {
16                 $config{mtnrootdir} = $config{srcdir};
17         }
18         if (! -d "$config{mtnrootdir}/_MTN") {
19                 error("Ikiwiki srcdir does not seem to be a Monotone workspace (or set the mtnrootdir)!");
20         }
21         
22         my $child = open(MTN, "-|");
23         if (! $child) {
24                 open STDERR, ">/dev/null";
25                 exec("mtn", "version") || error("mtn version failed to run");
26         }
27
28         my $version=undef;
29         while (<MTN>) {
30                 if (/^monotone (\d+\.\d+) /) {
31                         $version=$1;
32                 }
33         }
34
35         close MTN || debug("mtn version exited $?");
36
37         if (!defined($version)) {
38                 error("Cannot determine monotone version");
39         }
40         if ($version < 0.38) {
41                 error("Monotone version too old, is $version but required 0.38");
42         }
43
44         if (length $config{mtn_wrapper}) {
45                 push @{$config{wrappers}}, {
46                         wrapper => $config{mtn_wrapper},
47                         wrappermode => (defined $config{mtn_wrappermode} ? $config{mtn_wrappermode} : "06755"),
48                 };
49         }
50 }); #}}}
51
52 hook(type => "getsetup", id => "monotone", call => sub { #{{{
53         return
54                 mtn_wrapper => {
55                         type => "string",
56                         example => "/srv/mtn/wiki/_MTN/ikiwiki-netsync-hook",
57                         description => "monotone netsync hook executable to generate",
58                         safe => 0, # file
59                         rebuild => 0,
60                 },
61                 mtn_wrappermode => {
62                         type => "string",
63                         example => '06755',
64                         description => "mode for mtn_wrapper (can safely be made suid)",
65                         safe => 0,
66                         rebuild => 0,
67                 },
68                 mtnkey => {
69                         type => "string",
70                         example => 'web@example.com',
71                         description => "your monotone key",
72                         safe => 1,
73                         rebuild => 0,
74                 },
75                 historyurl => {
76                         type => "string",
77                         example => "http://viewmtn.example.com/branch/head/filechanges/com.example.branch/[[file]]",
78                         description => "viewmtn url to show file history ([[file]] substituted)",
79                         safe => 1,
80                         rebuild => 1,
81                 },
82                 diffurl => {
83                         type => "string",
84                         example => "http://viewmtn.example.com/revision/diff/[[r1]]/with/[[r2]]/[[file]]",
85                         description => "viewmtn url to show a diff ([[r1]], [[r2]], and [[file]] substituted)",
86                         safe => 1,
87                         rebuild => 1,
88                 },
89                 mtnsync => {
90                         type => "boolean",
91                         example => 0,
92                         description => "sync on update and commit?",
93                         safe => 0, # paranoia
94                         rebuild => 0,
95                 },
96                 mtnrootdir => {
97                         type => "string",
98                         description => "path to your workspace (defaults to the srcdir; specify if the srcdir is a subdirectory of the workspace)",
99                         safe => 0, # path
100                         rebuild => 0,
101                 },
102 }); #}}}
103
104 sub get_rev () { #{{{
105         my $sha1 = `mtn --root=$config{mtnrootdir} automate get_base_revision_id`;
106
107         ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
108         if (! $sha1) {
109                 debug("Unable to get base revision for '$config{srcdir}'.")
110         }
111
112         return $sha1;
113 } #}}}
114
115 sub get_rev_auto ($) { #{{{
116         my $automator=shift;
117
118         my @results = $automator->call("get_base_revision_id");
119
120         my $sha1 = $results[0];
121         ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
122         if (! $sha1) {
123                 debug("Unable to get base revision for '$config{srcdir}'.")
124         }
125
126         return $sha1;
127 } #}}}
128
129 sub mtn_merge ($$$$) { #{{{
130         my $leftRev=shift;
131         my $rightRev=shift;
132         my $branch=shift;
133         my $author=shift;
134     
135         my $mergeRev;
136
137         my $child = open(MTNMERGE, "-|");
138         if (! $child) {
139                 open STDERR, ">&STDOUT";
140                 exec("mtn", "--root=$config{mtnrootdir}",
141                      "explicit_merge", $leftRev, $rightRev,
142                      $branch, "--author", $author, "--key", 
143                      $config{mtnkey}) || error("mtn merge failed to run");
144         }
145
146         while (<MTNMERGE>) {
147                 if (/^mtn.\s.merged.\s($sha1_pattern)$/) {
148                         $mergeRev=$1;
149                 }
150         }
151         
152         close MTNMERGE || return undef;
153
154         debug("merged $leftRev, $rightRev to make $mergeRev");
155
156         return $mergeRev;
157 } #}}}
158
159 sub commit_file_to_new_rev($$$$$$$$) { #{{{
160         my $automator=shift;
161         my $wsfilename=shift;
162         my $oldFileID=shift;
163         my $newFileContents=shift;
164         my $oldrev=shift;
165         my $branch=shift;
166         my $author=shift;
167         my $message=shift;
168         
169         #store the file
170         my ($out, $err) = $automator->call("put_file", $oldFileID, $newFileContents);
171         my ($newFileID) = ($out =~ m/^($sha1_pattern)$/);
172         error("Failed to store file data for $wsfilename in repository")
173                 if (! defined $newFileID || length $newFileID != 40);
174
175         # get the mtn filename rather than the workspace filename
176         ($out, $err) = $automator->call("get_corresponding_path", $oldrev, $wsfilename, $oldrev);
177         my ($filename) = ($out =~ m/^file "(.*)"$/);
178         error("Couldn't find monotone repository path for file $wsfilename") if (! $filename);
179         debug("Converted ws filename of $wsfilename to repos filename of $filename");
180
181         # then stick in a new revision for this file
182         my $manifest = "format_version \"1\"\n\n".
183                        "new_manifest [0000000000000000000000000000000000000000]\n\n".
184                        "old_revision [$oldrev]\n\n".
185                        "patch \"$filename\"\n".
186                        " from [$oldFileID]\n".
187                        "   to [$newFileID]\n";
188         ($out, $err) = $automator->call("put_revision", $manifest);
189         my ($newRevID) = ($out =~ m/^($sha1_pattern)$/);
190         error("Unable to make new monotone repository revision")
191                 if (! defined $newRevID || length $newRevID != 40);
192         debug("put revision: $newRevID");
193         
194         # now we need to add certs for this revision...
195         # author, branch, changelog, date
196         $automator->call("cert", $newRevID, "author", $author);
197         $automator->call("cert", $newRevID, "branch", $branch);
198         $automator->call("cert", $newRevID, "changelog", $message);
199         $automator->call("cert", $newRevID, "date",
200                 time2str("%Y-%m-%dT%T", time, "UTC"));
201         
202         debug("Added certs for rev: $newRevID");
203         return $newRevID;
204 } #}}}
205
206 sub read_certs ($$) { #{{{
207         my $automator=shift;
208         my $rev=shift;
209         my @results = $automator->call("certs", $rev);
210         my @ret;
211
212         my $line = $results[0];
213         while ($line =~ m/\s+key\s"(.*?)"\nsignature\s"(ok|bad|unknown)"\n\s+name\s"(.*?)"\n\s+value\s"(.*?)"\n\s+trust\s"(trusted|untrusted)"\n/sg) {
214                 push @ret, {
215                         key => $1,
216                         signature => $2,
217                         name => $3,
218                         value => $4,
219                         trust => $5,
220                 };
221         }
222
223         return @ret;
224 } #}}}
225
226 sub get_changed_files ($$) { #{{{
227         my $automator=shift;
228         my $rev=shift;
229         
230         my @results = $automator->call("get_revision", $rev);
231         my $changes=$results[0];
232
233         my @ret;
234         my %seen = ();
235         
236         while ($changes =~ m/\s*(add_file|patch|delete|rename)\s"(.*?)(?<!\\)"\n/sg) {
237                 my $file = $2;
238                 # don't add the same file multiple times
239                 if (! $seen{$file}) {
240                         push @ret, $file;
241                         $seen{$file} = 1;
242                 }
243         }
244         
245         return @ret;
246 } #}}}
247
248 sub rcs_update () { #{{{
249         chdir $config{srcdir}
250             or error("Cannot chdir to $config{srcdir}: $!");
251
252         if (defined($config{mtnsync}) && $config{mtnsync}) {
253                 if (system("mtn", "--root=$config{mtnrootdir}", "sync",
254                            "--quiet", "--ticker=none", 
255                            "--key", $config{mtnkey}) != 0) {
256                         debug("monotone sync failed before update");
257                 }
258         }
259
260         if (system("mtn", "--root=$config{mtnrootdir}", "update", "--quiet") != 0) {
261                 debug("monotone update failed");
262         }
263 } #}}}
264
265 sub rcs_prepedit ($) { #{{{
266         my $file=shift;
267
268         chdir $config{srcdir}
269             or error("Cannot chdir to $config{srcdir}: $!");
270
271         # For monotone, return the revision of the file when
272         # editing begins.
273         return get_rev();
274 } #}}}
275
276 sub rcs_commit ($$$;$$) { #{{{
277         # Tries to commit the page; returns undef on _success_ and
278         # a version of the page with the rcs's conflict markers on failure.
279         # The file is relative to the srcdir.
280         my $file=shift;
281         my $message=shift;
282         my $rcstoken=shift;
283         my $user=shift;
284         my $ipaddr=shift;
285         my $author;
286
287         if (defined $user) {
288                 $author="Web user: " . $user;
289         }
290         elsif (defined $ipaddr) {
291                 $author="Web IP: " . $ipaddr;
292         }
293         else {
294                 $author="Web: Anonymous";
295         }
296
297         chdir $config{srcdir}
298             or error("Cannot chdir to $config{srcdir}: $!");
299
300         my ($oldrev)= $rcstoken=~ m/^($sha1_pattern)$/; # untaint
301         my $rev = get_rev();
302         if (defined $rev && defined $oldrev && $rev ne $oldrev) {
303                 my $automator = Monotone->new();
304                 $automator->open_args("--root", $config{mtnrootdir}, "--key", $config{mtnkey});
305
306                 # Something has been committed, has this file changed?
307                 my ($out, $err);
308                 $automator->setOpts("r", $oldrev, "r", $rev);
309                 ($out, $err) = $automator->call("content_diff", $file);
310                 debug("Problem committing $file") if ($err ne "");
311                 my $diff = $out;
312                 
313                 if ($diff) {
314                         # Commit a revision with just this file changed off
315                         # the old revision.
316                         #
317                         # first get the contents
318                         debug("File changed: forming branch");
319                         my $newfile=readfile("$config{srcdir}/$file");
320                         
321                         # then get the old content ID from the diff
322                         if ($diff !~ m/^---\s$file\s+($sha1_pattern)$/m) {
323                                 error("Unable to find previous file ID for $file");
324                         }
325                         my $oldFileID = $1;
326
327                         # get the branch we're working in
328                         ($out, $err) = $automator->call("get_option", "branch");
329                         chomp $out;
330                         error("Illegal branch name in monotone workspace") if ($out !~ m/^([-\@\w\.]+)$/);
331                         my $branch = $1;
332
333                         # then put the new content into the DB (and record the new content ID)
334                         my $newRevID = commit_file_to_new_rev($automator, $file, $oldFileID, $newfile, $oldrev, $branch, $author, $message);
335
336                         $automator->close();
337
338                         # if we made it to here then the file has been committed... revert the local copy
339                         if (system("mtn", "--root=$config{mtnrootdir}", "revert", $file) != 0) {
340                                 debug("Unable to revert $file after merge on conflicted commit!");
341                         }
342                         debug("Divergence created! Attempting auto-merge.");
343
344                         # see if it will merge cleanly
345                         $ENV{MTN_MERGE}="fail";
346                         my $mergeResult = mtn_merge($newRevID, $rev, $branch, $author);
347                         $ENV{MTN_MERGE}="";
348
349                         # push any changes so far
350                         if (defined($config{mtnsync}) && $config{mtnsync}) {
351                                 if (system("mtn", "--root=$config{mtnrootdir}", "push", "--quiet", "--ticker=none", "--key", $config{mtnkey}) != 0) {
352                                         debug("monotone push failed");
353                                 }
354                         }
355                         
356                         if (defined($mergeResult)) {
357                                 # everything is merged - bring outselves up to date
358                                 if (system("mtn", "--root=$config{mtnrootdir}",
359                                            "update", "-r", $mergeResult) != 0) {
360                                         debug("Unable to update to rev $mergeResult after merge on conflicted commit!");
361                                 }
362                         }
363                         else {
364                                 debug("Auto-merge failed.  Using diff-merge to add conflict markers.");
365                                 
366                                 $ENV{MTN_MERGE}="diffutils";
367                                 $ENV{MTN_MERGE_DIFFUTILS}="partial=true";
368                                 $mergeResult = mtn_merge($newRevID, $rev, $branch, $author);
369                                 $ENV{MTN_MERGE}="";
370                                 $ENV{MTN_MERGE_DIFFUTILS}="";
371                                 
372                                 if (!defined($mergeResult)) {
373                                         debug("Unable to insert conflict markers!");
374                                         error("Your commit succeeded. Unfortunately, someone else committed something to the same ".
375                                                 "part of the wiki at the same time. Both versions are stored in the monotone repository, ".
376                                                 "but at present the different versions cannot be reconciled through the web interface. ".
377                                                 "Please use the non-web interface to resolve the conflicts.");
378                                 }
379                                 
380                                 if (system("mtn", "--root=$config{mtnrootdir}",
381                                            "update", "-r", $mergeResult) != 0) {
382                                         debug("Unable to update to rev $mergeResult after conflict-enhanced merge on conflicted commit!");
383                                 }
384                                 
385                                 # return "conflict enhanced" file to the user
386                                 # for cleanup note, this relies on the fact
387                                 # that ikiwiki seems to call rcs_prepedit()
388                                 # again after we return
389                                 return readfile("$config{srcdir}/$file");
390                         }
391                         return undef;
392                 }
393                 $automator->close();
394         }
395
396         # If we reached here then the file we're looking at hasn't changed
397         # since $oldrev. Commit it.
398
399         if (system("mtn", "--root=$config{mtnrootdir}", "commit", "--quiet",
400                    "--author", $author, "--key", $config{mtnkey}, "-m",
401                    possibly_foolish_untaint($message), $file) != 0) {
402                 debug("Traditional commit failed! Returning data as conflict.");
403                 my $conflict=readfile("$config{srcdir}/$file");
404                 if (system("mtn", "--root=$config{mtnrootdir}", "revert",
405                            "--quiet", $file) != 0) {
406                         debug("monotone revert failed");
407                 }
408                 return $conflict;
409         }
410         if (defined($config{mtnsync}) && $config{mtnsync}) {
411                 if (system("mtn", "--root=$config{mtnrootdir}", "push",
412                            "--quiet", "--ticker=none", "--key",
413                            $config{mtnkey}) != 0) {
414                         debug("monotone push failed");
415                 }
416         }
417
418         return undef # success
419 } #}}}
420
421 sub rcs_commit_staged ($$$) {
422         # Commits all staged changes. Changes can be staged using rcs_add,
423         # rcs_remove, and rcs_rename.
424         my ($message, $user, $ipaddr)=@_;
425         
426         # Note - this will also commit any spurious changes that happen to be
427         # lying around in the working copy.  There shouldn't be any, but...
428         
429         chdir $config{srcdir}
430             or error("Cannot chdir to $config{srcdir}: $!");
431
432         my $author;
433
434         if (defined $user) {
435                 $author="Web user: " . $user;
436         }
437         elsif (defined $ipaddr) {
438                 $author="Web IP: " . $ipaddr;
439         }
440         else {
441                 $author="Web: Anonymous";
442         }
443
444         if (system("mtn", "--root=$config{mtnrootdir}", "commit", "--quiet",
445                    "--author", $author, "--key", $config{mtnkey}, "-m",
446                    possibly_foolish_untaint($message)) != 0) {
447                 error("Monotone commit failed");
448         }
449 }
450
451 sub rcs_add ($) { #{{{
452         my $file=shift;
453
454         chdir $config{srcdir}
455             or error("Cannot chdir to $config{srcdir}: $!");
456
457         if (system("mtn", "--root=$config{mtnrootdir}", "add", "--quiet",
458                    $file) != 0) {
459                 error("Monotone add failed");
460         }
461 } #}}}
462
463 sub rcs_remove ($) { # {{{
464         my $file = shift;
465
466         chdir $config{srcdir}
467             or error("Cannot chdir to $config{srcdir}: $!");
468
469         # Note: it is difficult to undo a remove in Monotone at the moment.
470         # Until this is fixed, it might be better to make 'rm' move things
471         # into an attic, rather than actually remove them.
472         # To resurrect a file, you currently add a new file with the contents
473         # you want it to have.  This loses all connectivity and automated
474         # merging with the 'pre-delete' versions of the file.
475
476         if (system("mtn", "--root=$config{mtnrootdir}", "rm", "--quiet",
477                    $file) != 0) {
478                 error("Monotone remove failed");
479         }
480 } #}}}
481
482 sub rcs_rename ($$) { # {{{
483         my ($src, $dest) = @_;
484
485         chdir $config{srcdir}
486             or error("Cannot chdir to $config{srcdir}: $!");
487
488         if (system("mtn", "--root=$config{mtnrootdir}", "rename", "--quiet",
489                    $src, $dest) != 0) {
490                 error("Monotone rename failed");
491         }
492 } #}}}
493
494 sub rcs_recentchanges ($) { #{{{
495         my $num=shift;
496         my @ret;
497
498         chdir $config{srcdir}
499             or error("Cannot chdir to $config{srcdir}: $!");
500
501         # use log --brief to get a list of revs, as this
502         # gives the results in a nice order
503         # (otherwise we'd have to do our own date sorting)
504
505         my @revs;
506
507         my $child = open(MTNLOG, "-|");
508         if (! $child) {
509                 exec("mtn", "log", "--root=$config{mtnrootdir}", "--no-graph",
510                      "--brief") || error("mtn log failed to run");
511         }
512
513         while (($num >= 0) and (my $line = <MTNLOG>)) {
514                 if ($line =~ m/^($sha1_pattern)/) {
515                         push @revs, $1;
516                         $num -= 1;
517                 }
518         }
519         close MTNLOG || debug("mtn log exited $?");
520
521         my $automator = Monotone->new();
522         $automator->open(undef, $config{mtnrootdir});
523
524         while (@revs != 0) {
525                 my $rev = shift @revs;
526                 # first go through and figure out the messages, etc
527
528                 my $certs = [read_certs($automator, $rev)];
529                 
530                 my $user;
531                 my $when;
532                 my $committype;
533                 my (@pages, @message);
534                 
535                 foreach my $cert (@$certs) {
536                         if ($cert->{signature} eq "ok" &&
537                             $cert->{trust} eq "trusted") {
538                                 if ($cert->{name} eq "author") {
539                                         $user = $cert->{value};
540                                         # detect the source of the commit
541                                         # from the changelog
542                                         if ($cert->{key} eq $config{mtnkey}) {
543                                                 $committype = "web";
544                                         } else {
545                                                 $committype = "monotone";
546                                         }
547                                 } elsif ($cert->{name} eq "date") {
548                                         $when = str2time($cert->{value}, 'UTC');
549                                 } elsif ($cert->{name} eq "changelog") {
550                                         my $messageText = $cert->{value};
551                                         # split the changelog into multiple
552                                         # lines
553                                         foreach my $msgline (split(/\n/, $messageText)) {
554                                                 push @message, { line => $msgline };
555                                         }
556                                 }
557                         }
558                 }
559                 
560                 my @changed_files = get_changed_files($automator, $rev);
561                 my $file;
562                 
563                 my ($out, $err) = $automator->call("parents", $rev);
564                 my @parents = ($out =~ m/^($sha1_pattern)$/);
565                 my $parent = $parents[0];
566
567                 foreach $file (@changed_files) {
568                         next unless length $file;
569                         
570                         if (defined $config{diffurl} and (@parents == 1)) {
571                                 my $diffurl=$config{diffurl};
572                                 $diffurl=~s/\[\[r1\]\]/$parent/g;
573                                 $diffurl=~s/\[\[r2\]\]/$rev/g;
574                                 $diffurl=~s/\[\[file\]\]/$file/g;
575                                 push @pages, {
576                                         page => pagename($file),
577                                         diffurl => $diffurl,
578                                 };
579                         }
580                         else {
581                                 push @pages, {
582                                         page => pagename($file),
583                                 }
584                         }
585                 }
586                 
587                 push @ret, {
588                         rev => $rev,
589                         user => $user,
590                         committype => $committype,
591                         when => $when,
592                         message => [@message],
593                         pages => [@pages],
594                 } if @pages;
595         }
596
597         $automator->close();
598
599         return @ret;
600 } #}}}
601
602 sub rcs_diff ($) { #{{{
603         my $rev=shift;
604         my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
605         
606         chdir $config{srcdir}
607             or error("Cannot chdir to $config{srcdir}: $!");
608
609         my $child = open(MTNDIFF, "-|");
610         if (! $child) {
611                 exec("mtn", "diff", "--root=$config{mtnrootdir}", "-r", "p:".$sha1, "-r", $sha1) || error("mtn diff $sha1 failed to run");
612         }
613
614         my (@lines) = <MTNDIFF>;
615
616         close MTNDIFF || debug("mtn diff $sha1 exited $?");
617
618         if (wantarray) {
619                 return @lines;
620         }
621         else {
622                 return join("", @lines);
623         }
624 } #}}}
625
626 sub rcs_getctime ($) { #{{{
627         my $file=shift;
628
629         chdir $config{srcdir}
630             or error("Cannot chdir to $config{srcdir}: $!");
631
632         my $child = open(MTNLOG, "-|");
633         if (! $child) {
634                 exec("mtn", "log", "--root=$config{mtnrootdir}", "--no-graph",
635                      "--brief", $file) || error("mtn log $file failed to run");
636         }
637
638         my $firstRev;
639         while (<MTNLOG>) {
640                 if (/^($sha1_pattern)/) {
641                         $firstRev=$1;
642                 }
643         }
644         close MTNLOG || debug("mtn log $file exited $?");
645
646         if (! defined $firstRev) {
647                 debug "failed to parse mtn log for $file";
648                 return 0;
649         }
650
651         my $automator = Monotone->new();
652         $automator->open(undef, $config{mtnrootdir});
653
654         my $certs = [read_certs($automator, $firstRev)];
655
656         $automator->close();
657
658         my $date;
659
660         foreach my $cert (@$certs) {
661                 if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
662                         if ($cert->{name} eq "date") {
663                                 $date = $cert->{value};
664                         }
665                 }
666         }
667
668         if (! defined $date) {
669                 debug "failed to find date cert for revision $firstRev when looking for creation time of $file";
670                 return 0;
671         }
672
673         $date=str2time($date, 'UTC');
674         debug("found ctime ".localtime($date)." for $file");
675         return $date;
676 } #}}}
677
678 1