2 # Monotone revision control.
5 # This requires the Monotone perl module from the monotone contrib/ directory to be installed.
6 # In particlar, we require version 0.03 or higher of that module.
7 # It is available from the monotone source repository at:
8 # http://viewmtn.angrygoats.net/branch/changes/net.venge.monotone
14 use Date::Parse qw(str2time);
15 use Date::Format qw(time2str);
19 my $sha1_pattern = qr/[0-9a-fA-F]{40}/; # pattern to validate sha1sums
22 if (!defined($config{srcdir})) {
23 error("Ikiwiki srcdir not defined!");
25 if (!defined($config{mtnrootdir})) {
26 $config{mtnrootdir} = $config{srcdir};
28 if (! -d "$config{mtnrootdir}/_MTN") {
29 error("Ikiwiki srcdir does not seem to be a Monotone workspace (or set the mtnrootdir)!");
32 if (!defined($config{mtnmergerc})) {
33 $config{mtnmergerc} = "$config{mtnrootdir}/_MTN/mergerc";
37 or error("Cannot chdir to $config{srcdir}: $!");
41 my $sha1 = `mtn --root=$config{mtnrootdir} automate get_base_revision_id`;
43 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
45 warn("Unable to get base revision for '$config{srcdir}'.")
51 sub get_rev_auto ($) {
54 my @results = $automator->call("get_base_revision_id");
56 my $sha1 = $results[0];
57 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
59 warn("Unable to get base revision for '$config{srcdir}'.")
65 sub mtn_merge ($$$$$) {
70 my $message=shift; # ignored for the moment because mtn doesn't support it
74 my $mergerc = $config{mtnmergerc};
76 my $child = open(MTNMERGE, "-|");
78 open STDERR, ">&STDOUT";
79 exec("mtn", "--root=$config{mtnrootdir}", "--rcfile", $mergerc, "explicit_merge", $leftRev, $rightRev, $branch, "--author", $author, "--key", $config{mtnkey}) || error("mtn merge failed to run");
83 if (/^mtn.\s.merged.\s($sha1_pattern)$/) {
88 close MTNMERGE || return undef;
90 warn("merged $leftRev, $rightRev to make $mergeRev");
95 sub commit_file_to_new_rev($$$$$$$$) {
99 my $newFileContents=shift;
106 my ($out, $err) = $automator->call("put_file", $oldFileID, $newFileContents);
107 my ($newFileID) = ($out =~ m/^($sha1_pattern)$/);
108 error("Failed to store file data for $wsfilename in repository") if (!defined($newFileID) || 40 != length $newFileID);
110 # get the mtn filename rather than the workspace filename
111 ($out, $err) = $automator->call("get_corresponding_path", $oldrev, $wsfilename, $oldrev);
112 my ($filename) = ($out =~ m/^file "(.*)"$/);
113 error("Couldn't find monotone repository path for file $wsfilename") if (! $filename);
114 warn("Converted ws filename of $wsfilename to repos filename of $filename");
116 # then stick in a new revision for this file
117 my $manifest = "format_version \"1\"\n\n".
118 "new_manifest [0000000000000000000000000000000000000000]\n\n".
119 "old_revision [$oldrev]\n\n".
120 "patch \"$filename\"\n".
121 " from [$oldFileID]\n".
122 " to [$newFileID]\n";
123 ($out, $err) = $automator->call("put_revision", $manifest);
124 my ($newRevID) = ($out =~ m/^($sha1_pattern)$/);
125 error("Unable to make new monotone repository revision") if (!defined($newRevID) || 40 != length $newRevID);
126 warn("put revision: $newRevID");
128 # now we need to add certs for this revision...
129 # author, branch, changelog, date
130 $automator->call("cert", $newRevID, "author", $author);
131 $automator->call("cert", $newRevID, "branch", $branch);
132 $automator->call("cert", $newRevID, "changelog", $message);
133 $automator->call("cert", $newRevID, "date", time2str("%Y-%m-%dT%T", time, "UTC"));
135 warn("Added certs for rev: $newRevID");
139 sub check_mergerc() {
140 my $mergerc = $config{mtnmergerc};
141 if (! -r $mergerc ) {
142 warn("$mergerc doesn't exist. Creating file with default mergers.");
143 open(DATA, ">$mergerc") or error("can't open $mergerc $!");
145 " function local_execute_redirected(stdin, stdout, stderr, path, ...)\n".
149 " pid = spawn_redirected(stdin, stdout, stderr, path, unpack(arg))\n".
150 " if (pid ~= -1) then ret, pid = wait(pid) end\n".
153 " if (not execute_redirected) then -- use standard function if available\n".
154 " execute_redirected = local_execute_redirected\n".
156 " if (not mergers.fail) then -- use standard merger if available\n".
157 " mergers.fail = {\n".
158 " cmd = function (tbl) return false end,\n".
159 " available = function () return true end,\n".
160 " wanted = function () return true end\n".
163 " mergers.diffutils_force = {\n".
164 " cmd = function (tbl)\n".
165 " local ret = execute_redirected(\n".
171 " \"--show-overlap\",\n".
172 " \"--label\", string.format(\"[Yours]\", tbl.left_path ),\n".
173 " \"--label\", string.format(\"[Original]\", tbl.anc_path ),\n".
174 " \"--label\", string.format(\"[Theirs]\", tbl.right_path),\n".
179 " if (ret > 1) then\n".
180 " io.write(gettext(\"Error running GNU diffutils 3-way difference tool 'diff3'\"))\n".
183 " return tbl.outfile\n".
187 " return program_exists_in_path(\"diff3\");\n".
194 print DATA $defaultrc;
199 sub read_certs ($$) {
202 my @results = $automator->call("certs", $rev);
205 my $line = $results[0];
206 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) {
219 sub get_changed_files ($$) {
223 my @results = $automator->call("get_revision", $rev);
224 my $changes=$results[0];
229 while ($changes =~ m/\s*(add_file|patch|delete|rename)\s"(.*?)(?<!\\)"\n/sg) {
231 if (! $seen{$file}) { # don't add the same file multiple times
240 # The following functions are the ones actually called by Ikiwiki
243 # Update working directory to current version.
247 if (defined($config{mtnsync}) && $config{mtnsync}) {
248 if (system("mtn", "--root=$config{mtnrootdir}", "sync", "--quiet", "--ticker=none", "--key", $config{mtnkey}) != 0) {
249 warn("monotone sync failed before update\n");
253 if (system("mtn", "--root=$config{mtnrootdir}", "update", "--quiet") != 0) {
254 warn("monotone update failed\n");
258 sub rcs_prepedit ($) {
259 # Prepares to edit a file under revision control. Returns a token
260 # that must be passed into rcs_commit when the file is ready
262 # The file is relative to the srcdir.
267 # For monotone, return the revision of the file when
272 sub rcs_commit ($$$;$$) {
273 # Tries to commit the page; returns undef on _success_ and
274 # a version of the page with the rcs's conflict markers on failure.
275 # The file is relative to the srcdir.
284 $author="Web user: " . $user;
286 elsif (defined $ipaddr) {
287 $author="Web IP: " . $ipaddr;
290 $author="Web: Anonymous";
295 my ($oldrev)= $rcstoken=~ m/^($sha1_pattern)$/; # untaint
297 if (defined $rev && defined $oldrev && $rev ne $oldrev) {
298 my $automator = Monotone->new();
299 $automator->open_args("--root", $config{mtnrootdir}, "--key", $config{mtnkey});
301 # Something has been committed, has this file changed?
303 #$automator->setOpts("-r", $oldrev, "-r", $rev);
304 #my ($out, $err) = $automator->call("content_diff", $file);
305 #debug("Problem committing $file") if ($err ne "");
306 my $diff = `mtn --root=$config{mtnrootdir} au content_diff -r $oldrev -r $rev $file`; # was just $out;
309 # this file has changed
310 # commit a revision with just this file changed off the old revision
311 # first get the contents
312 warn("File changed: forming branch\n");
313 my $newfile=readfile("$config{srcdir}/$file");
315 # then get the old content ID from the diff
316 if ($diff !~ m/^---\s$file\s+($sha1_pattern)$/m) {
317 error("Unable to find previous file ID for $file");
321 # get the branch we're working in
322 ($out, $err) = $automator->call("get_option", "branch");
324 error("Illegal branch name in monotone workspace") if ($out !~ m/^([-\@\w\.]+)$/);
327 # then put the new content into the DB (and record the new content ID)
328 my $newRevID = commit_file_to_new_rev($automator, $file, $oldFileID, $newfile, $oldrev, $branch, $author, $message);
332 # if we made it to here then the file has been committed... revert the local copy
333 if (system($config{mtnbinpath}, "--root=$config{mtnrootdir}", "revert", $file) != 0) {
334 warn("Unable to revert $file after merge on conflicted commit!");
336 warn("Divergence created! Attempting auto-merge.");
340 # see if it will merge cleanly
341 $ENV{MTN_MERGE}="fail";
342 my $mergeResult = mtn_merge($newRevID, $rev, $branch, $author, "Auto-merging parallel web edits.");
345 # push any changes so far
346 if (defined($config{mtnsync}) && $config{mtnsync}) {
347 if (system($config{mtnbinpath}, "--root=$config{mtnrootdir}", "push", "--quiet", "--ticker=none", "--key", $config{mtnkey}) != 0) {
348 warn("monotone push failed\n");
352 if (defined($mergeResult)) {
353 # everything is merged - bring outselves up to date
354 if (system($config{mtnbinpath}, "--root=$config{mtnrootdir}", "update", "-r", $mergeResult) != 0) {
355 warn("Unable to update to rev $mergeResult after merge on conflicted commit!");
358 warn("Auto-merge failed. Using diff-merge to add conflict markers.");
360 $ENV{MTN_MERGE}="diffutils_force";
361 my $mergeResult = mtn_merge($newRevID, $rev, $branch, $author, "Merge parallel conflicting web edits (adding inline conflict markers).\nThis revision should be cleaned up manually.");
364 if (!defined($mergeResult)) {
365 warn("Unable to insert conflict markers!");
366 error("Your commit succeeded. Unfortunately, someone else committed something to the same\n".
367 "part of the wiki at the same time. Both versions are stored in the monotone repository,\n".
368 "but at present the different versions cannot be reconciled through the web interface.\n\n".
369 "Please use the non-web interface to resolve the conflicts.\n");
372 # suspend this revision because it has conflict markers...
373 if (system($config{mtnbinpath}, "--root=$config{mtnrootdir}", "update", "-r", $mergeResult) != 0) {
374 warn("Unable to update to rev $mergeResult after conflict-enhanced merge on conflicted commit!");
377 # return "conflict enhanced" file to the user for cleanup
378 # note, this relies on the fact that ikiwiki seems to call rcs_prepedit() again
380 return readfile("$config{srcdir}/$file");
387 # if we reached here then the file we're looking at hasn't changed since $oldrev. Commit it.
389 if (system($config{mtnbinpath}, "--root=$config{mtnrootdir}", "commit", "--quiet", "--author", $author, "--key", $config{mtnkey},
390 "-m", possibly_foolish_untaint($message), $file) != 0) {
391 warn("Traditional commit failed!\nReturning data as conflict.\n");
392 my $conflict=readfile("$config{srcdir}/$file");
393 if (system($config{mtnbinpath}, "--root=$config{mtnrootdir}", "revert", "--quiet", $file) != 0) {
394 warn("monotone revert failed\n");
398 if (defined($config{mtnsync}) && $config{mtnsync}) {
399 if (system($config{mtnbinpath}, "--root=$config{mtnrootdir}", "sync", "--quiet", "--ticker=none", "--key", $config{mtnkey}) != 0) {
400 warn("monotone sync failed\n");
404 return undef # success
408 # Add a file. The filename is relative to the root of the srcdir.
413 if (system($config{mtnbinpath}, "--root=$config{mtnrootdir}", "add", "--quiet", "$config{srcdir}/$file") != 0) {
414 error("Monotone add failed");
418 sub rcs_recentchanges ($) {
419 # Examine the RCS history and generate a list of recent changes.
420 # The data structure returned for each change is:
422 # user => # name of user who made the change,
423 # committype => # either "web" or the name of the rcs,
424 # when => # time when the change was made,
426 # { line => "commit message line" },
427 # { line => "commit message line" },
432 # page => # name of page changed,
433 # diffurl => # optional url to a diff showing
436 # # repeat for each page changed in this commit,
445 # use log --brief to get a list of revs, as this
446 # gives the results in a nice order
447 # (otherwise we'd have to do our own date sorting)
451 my $child = open(MTNLOG, "-|");
453 exec($config{mtnbinpath}, "log", "--root=$config{mtnrootdir}", "--no-graph", "--brief") || error("mtn log failed to run");
458 while (($num >= 0) and ($line = <MTNLOG>)) {
459 if ($line =~ m/^($sha1_pattern)/) {
464 close MTNLOG || warn "mtn log exited $?";
466 my $automator = Monotone->new();
467 $automator->open(undef, $config{mtnrootdir});
470 my $rev = shift @revs;
471 # first go through and figure out the messages, etc
473 my $certs = [read_certs($automator, $rev)];
478 my (@pages, @message);
480 foreach my $cert (@$certs) {
481 if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
482 if ($cert->{name} eq "author") {
483 $user = $cert->{value};
484 # detect the source of the commit from the changelog
485 if ($cert->{key} eq $config{mtnkey}) {
488 $committype = "monotone";
490 } elsif ($cert->{name} eq "date") {
491 $when = time - str2time($cert->{value}, 'UTC');
492 } elsif ($cert->{name} eq "changelog") {
493 my $messageText = $cert->{value};
494 # split the changelog into multiple lines
495 foreach my $msgline (split(/\n/, $messageText)) {
496 push @message, { line => $msgline };
502 my @changed_files = get_changed_files($automator, $rev);
505 foreach $file (@changed_files) {
507 page => pagename($file),
514 committype => $committype,
516 message => [@message],
527 # This function is called when a change is committed to the wiki,
528 # and ikiwiki is running as a post-commit hook from the RCS.
529 # It should examine the repository to somehow determine what pages
530 # changed, and then send emails to users subscribed to those pages.
532 warn("The monotone rcs_notify function is currently untested. Use at own risk!");
534 if (! exists $ENV{REV}) {
535 error(gettext("REV is not set, not running from mtn post-commit hook, cannot send notifications"));
537 if ($ENV{REV} !~ m/($sha1_pattern)/) { # sha1 is untainted now
538 error(gettext("REV is not a valid revision identifier, cannot send notifications"));
544 my $automator = Monotone->new();
545 $automator->open(undef, $config{mtnrootdir});
547 my $certs = [read_certs($automator, $rev)];
552 foreach my $cert (@$certs) {
553 if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
554 if ($cert->{name} eq "author") {
555 $user = $cert->{value};
556 } elsif ($cert->{name} eq "date") {
557 $when = $cert->{value};
558 } elsif ($cert->{name} eq "changelog") {
559 $message = $cert->{value};
564 my @changed_pages = get_changed_files($automator, $rev);
568 require IkiWiki::UserInfo;
574 `$config{mtnbinpath} --root=$config{mtnrootdir} au content_diff -r $rev`;
575 }, $user, @changed_pages);
578 sub rcs_getctime ($) {
579 # Optional, used to get the page creation time from the RCS.
580 # error gettext("getctime not implemented");
585 my $child = open(MTNLOG, "-|");
587 exec($config{mtnbinpath}, "log", "--root=$config{mtnrootdir}", "--no-graph", "--brief", $file) || error("mtn log $file failed to run");
592 if (/^($sha1_pattern)/) {
596 close MTNLOG || warn "mtn log $file exited $?";
598 if (! defined $firstRev) {
599 warn "failed to parse mtn log for $file\n";
603 my $automator = Monotone->new();
604 $automator->open(undef, $config{mtnrootdir});
606 my $certs = [read_certs($automator, $firstRev)];
612 foreach my $cert (@$certs) {
613 if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
614 if ($cert->{name} eq "date") {
615 $date = $cert->{value};
620 if (! defined $date) {
621 warn "failed to find date cert for revision $firstRev when looking for creation time of $file\n";
625 $date=str2time($date, 'UTC');
626 debug("found ctime ".localtime($date)." for $file");