6 use Date::Parse qw(str2time);
7 use Date::Format qw(time2str);
11 my $sha1_pattern = qr/[0-9a-fA-F]{40}/; # pattern to validate sha1sums
14 if (!defined($config{mtnrootdir})) {
15 $config{mtnrootdir} = $config{srcdir};
17 if (! -d "$config{mtnrootdir}/_MTN") {
18 error("Ikiwiki srcdir does not seem to be a Monotone workspace (or set the mtnrootdir)!");
21 if (!defined($config{mtnmergerc})) {
22 $config{mtnmergerc} = "$config{mtnrootdir}/_MTN/mergerc";
26 or error("Cannot chdir to $config{srcdir}: $!");
30 my $sha1 = `mtn --root=$config{mtnrootdir} automate get_base_revision_id`;
32 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
34 warn("Unable to get base revision for '$config{srcdir}'.")
40 sub get_rev_auto ($) {
43 my @results = $automator->call("get_base_revision_id");
45 my $sha1 = $results[0];
46 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
48 warn("Unable to get base revision for '$config{srcdir}'.")
54 sub mtn_merge ($$$$$) {
59 my $message=shift; # ignored for the moment because mtn doesn't support it
63 my $mergerc = $config{mtnmergerc};
65 my $child = open(MTNMERGE, "-|");
67 open STDERR, ">&STDOUT";
68 exec("mtn", "--root=$config{mtnrootdir}", "--rcfile", $mergerc, "explicit_merge", $leftRev, $rightRev, $branch, "--author", $author, "--key", $config{mtnkey}) || error("mtn merge failed to run");
72 if (/^mtn.\s.merged.\s($sha1_pattern)$/) {
77 close MTNMERGE || return undef;
79 warn("merged $leftRev, $rightRev to make $mergeRev");
84 sub commit_file_to_new_rev($$$$$$$$) {
88 my $newFileContents=shift;
95 my ($out, $err) = $automator->call("put_file", $oldFileID, $newFileContents);
96 my ($newFileID) = ($out =~ m/^($sha1_pattern)$/);
97 error("Failed to store file data for $wsfilename in repository") if (!defined($newFileID) || 40 != length $newFileID);
99 # get the mtn filename rather than the workspace filename
100 ($out, $err) = $automator->call("get_corresponding_path", $oldrev, $wsfilename, $oldrev);
101 my ($filename) = ($out =~ m/^file "(.*)"$/);
102 error("Couldn't find monotone repository path for file $wsfilename") if (! $filename);
103 warn("Converted ws filename of $wsfilename to repos filename of $filename");
105 # then stick in a new revision for this file
106 my $manifest = "format_version \"1\"\n\n".
107 "new_manifest [0000000000000000000000000000000000000000]\n\n".
108 "old_revision [$oldrev]\n\n".
109 "patch \"$filename\"\n".
110 " from [$oldFileID]\n".
111 " to [$newFileID]\n";
112 ($out, $err) = $automator->call("put_revision", $manifest);
113 my ($newRevID) = ($out =~ m/^($sha1_pattern)$/);
114 error("Unable to make new monotone repository revision") if (!defined($newRevID) || 40 != length $newRevID);
115 warn("put revision: $newRevID");
117 # now we need to add certs for this revision...
118 # author, branch, changelog, date
119 $automator->call("cert", $newRevID, "author", $author);
120 $automator->call("cert", $newRevID, "branch", $branch);
121 $automator->call("cert", $newRevID, "changelog", $message);
122 $automator->call("cert", $newRevID, "date", time2str("%Y-%m-%dT%T", time, "UTC"));
124 warn("Added certs for rev: $newRevID");
128 sub check_mergerc() {
129 my $mergerc = $config{mtnmergerc};
130 if (! -r $mergerc ) {
131 warn("$mergerc doesn't exist. Creating file with default mergers.");
132 open(my $out, ">$mergerc") or error("can't open $mergerc: $!");
138 sub read_certs ($$) {
141 my @results = $automator->call("certs", $rev);
144 my $line = $results[0];
145 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) {
158 sub get_changed_files ($$) {
162 my @results = $automator->call("get_revision", $rev);
163 my $changes=$results[0];
168 while ($changes =~ m/\s*(add_file|patch|delete|rename)\s"(.*?)(?<!\\)"\n/sg) {
170 if (! $seen{$file}) { # don't add the same file multiple times
179 # The following functions are the ones actually called by Ikiwiki
182 # Update working directory to current version.
186 if (defined($config{mtnsync}) && $config{mtnsync}) {
187 if (system("mtn", "--root=$config{mtnrootdir}", "sync", "--quiet", "--ticker=none", "--key", $config{mtnkey}) != 0) {
188 warn("monotone sync failed before update\n");
192 if (system("mtn", "--root=$config{mtnrootdir}", "update", "--quiet") != 0) {
193 warn("monotone update failed\n");
197 sub rcs_prepedit ($) {
198 # Prepares to edit a file under revision control. Returns a token
199 # that must be passed into rcs_commit when the file is ready
201 # The file is relative to the srcdir.
206 # For monotone, return the revision of the file when
211 sub rcs_commit ($$$;$$) {
212 # Tries to commit the page; returns undef on _success_ and
213 # a version of the page with the rcs's conflict markers on failure.
214 # The file is relative to the srcdir.
223 $author="Web user: " . $user;
225 elsif (defined $ipaddr) {
226 $author="Web IP: " . $ipaddr;
229 $author="Web: Anonymous";
234 my ($oldrev)= $rcstoken=~ m/^($sha1_pattern)$/; # untaint
236 if (defined $rev && defined $oldrev && $rev ne $oldrev) {
237 my $automator = Monotone->new();
238 $automator->open_args("--root", $config{mtnrootdir}, "--key", $config{mtnkey});
240 # Something has been committed, has this file changed?
242 #$automator->setOpts("-r", $oldrev, "-r", $rev);
243 #my ($out, $err) = $automator->call("content_diff", $file);
244 #debug("Problem committing $file") if ($err ne "");
245 # FIXME: use of $file in these backticks is not wise from a
246 # security POV. Probably safe, but should be avoided
248 my $diff = `mtn --root=$config{mtnrootdir} au content_diff -r $oldrev -r $rev $file`; # was just $out;
251 # this file has changed
252 # commit a revision with just this file changed off
254 # first get the contents
255 warn("File changed: forming branch\n");
256 my $newfile=readfile("$config{srcdir}/$file");
258 # then get the old content ID from the diff
259 if ($diff !~ m/^---\s$file\s+($sha1_pattern)$/m) {
260 error("Unable to find previous file ID for $file");
264 # get the branch we're working in
265 ($out, $err) = $automator->call("get_option", "branch");
267 error("Illegal branch name in monotone workspace") if ($out !~ m/^([-\@\w\.]+)$/);
270 # then put the new content into the DB (and record the new content ID)
271 my $newRevID = commit_file_to_new_rev($automator, $file, $oldFileID, $newfile, $oldrev, $branch, $author, $message);
275 # if we made it to here then the file has been committed... revert the local copy
276 if (system("mtn", "--root=$config{mtnrootdir}", "revert", $file) != 0) {
277 warn("Unable to revert $file after merge on conflicted commit!");
279 warn("Divergence created! Attempting auto-merge.");
283 # see if it will merge cleanly
284 $ENV{MTN_MERGE}="fail";
285 my $mergeResult = mtn_merge($newRevID, $rev, $branch, $author, "Auto-merging parallel web edits.");
288 # push any changes so far
289 if (defined($config{mtnsync}) && $config{mtnsync}) {
290 if (system("mtn", "--root=$config{mtnrootdir}", "push", "--quiet", "--ticker=none", "--key", $config{mtnkey}) != 0) {
291 warn("monotone push failed\n");
295 if (defined($mergeResult)) {
296 # everything is merged - bring outselves up to date
297 if (system("mtn", "--root=$config{mtnrootdir}", "update", "-r", $mergeResult) != 0) {
298 warn("Unable to update to rev $mergeResult after merge on conflicted commit!");
301 warn("Auto-merge failed. Using diff-merge to add conflict markers.");
303 $ENV{MTN_MERGE}="diffutils_force";
304 $mergeResult = mtn_merge($newRevID, $rev, $branch, $author, "Merge parallel conflicting web edits (adding inline conflict markers).\nThis revision should be cleaned up manually.");
307 if (!defined($mergeResult)) {
308 warn("Unable to insert conflict markers!");
309 error("Your commit succeeded. Unfortunately, someone else committed something to the same\n".
310 "part of the wiki at the same time. Both versions are stored in the monotone repository,\n".
311 "but at present the different versions cannot be reconciled through the web interface.\n\n".
312 "Please use the non-web interface to resolve the conflicts.\n");
315 # suspend this revision because it has conflict markers...
316 if (system("mtn", "--root=$config{mtnrootdir}", "update", "-r", $mergeResult) != 0) {
317 warn("Unable to update to rev $mergeResult after conflict-enhanced merge on conflicted commit!");
320 # return "conflict enhanced" file to the user for cleanup
321 # note, this relies on the fact that ikiwiki seems to call rcs_prepedit() again
323 return readfile("$config{srcdir}/$file");
330 # if we reached here then the file we're looking at hasn't changed since $oldrev. Commit it.
332 if (system("mtn", "--root=$config{mtnrootdir}", "commit", "--quiet", "--author", $author, "--key", $config{mtnkey},
333 "-m", possibly_foolish_untaint($message), $file) != 0) {
334 warn("Traditional commit failed!\nReturning data as conflict.\n");
335 my $conflict=readfile("$config{srcdir}/$file");
336 if (system("mtn", "--root=$config{mtnrootdir}", "revert", "--quiet", $file) != 0) {
337 warn("monotone revert failed\n");
341 if (defined($config{mtnsync}) && $config{mtnsync}) {
342 if (system("mtn", "--root=$config{mtnrootdir}", "sync", "--quiet", "--ticker=none", "--key", $config{mtnkey}) != 0) {
343 warn("monotone sync failed\n");
347 return undef # success
351 # Add a file. The filename is relative to the root of the srcdir.
356 if (system("mtn", "--root=$config{mtnrootdir}", "add", "--quiet", "$config{srcdir}/$file") != 0) {
357 error("Monotone add failed");
361 sub rcs_recentchanges ($) {
362 # Examine the RCS history and generate a list of recent changes.
363 # The data structure returned for each change is:
365 # user => # name of user who made the change,
366 # committype => # either "web" or the name of the rcs,
367 # when => # time when the change was made,
369 # { line => "commit message line" },
370 # { line => "commit message line" },
375 # page => # name of page changed,
376 # diffurl => # optional url to a diff showing
379 # # repeat for each page changed in this commit,
388 # use log --brief to get a list of revs, as this
389 # gives the results in a nice order
390 # (otherwise we'd have to do our own date sorting)
394 my $child = open(MTNLOG, "-|");
396 exec("mtn", "log", "--root=$config{mtnrootdir}", "--no-graph", "--brief") || error("mtn log failed to run");
401 while (($num >= 0) and ($line = <MTNLOG>)) {
402 if ($line =~ m/^($sha1_pattern)/) {
407 close MTNLOG || warn "mtn log exited $?";
409 my $automator = Monotone->new();
410 $automator->open(undef, $config{mtnrootdir});
413 my $rev = shift @revs;
414 # first go through and figure out the messages, etc
416 my $certs = [read_certs($automator, $rev)];
421 my (@pages, @message);
423 foreach my $cert (@$certs) {
424 if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
425 if ($cert->{name} eq "author") {
426 $user = $cert->{value};
427 # detect the source of the commit from the changelog
428 if ($cert->{key} eq $config{mtnkey}) {
431 $committype = "monotone";
433 } elsif ($cert->{name} eq "date") {
434 $when = time - str2time($cert->{value}, 'UTC');
435 } elsif ($cert->{name} eq "changelog") {
436 my $messageText = $cert->{value};
437 # split the changelog into multiple lines
438 foreach my $msgline (split(/\n/, $messageText)) {
439 push @message, { line => $msgline };
445 my @changed_files = get_changed_files($automator, $rev);
448 foreach $file (@changed_files) {
450 page => pagename($file),
457 committype => $committype,
459 message => [@message],
470 # This function is called when a change is committed to the wiki,
471 # and ikiwiki is running as a post-commit hook from the RCS.
472 # It should examine the repository to somehow determine what pages
473 # changed, and then send emails to users subscribed to those pages.
475 warn("The monotone rcs_notify function is currently untested. Use at own risk!");
477 if (! exists $ENV{REV}) {
478 error(gettext("REV is not set, not running from mtn post-commit hook, cannot send notifications"));
480 if ($ENV{REV} !~ m/($sha1_pattern)/) { # sha1 is untainted now
481 error(gettext("REV is not a valid revision identifier, cannot send notifications"));
487 my $automator = Monotone->new();
488 $automator->open(undef, $config{mtnrootdir});
490 my $certs = [read_certs($automator, $rev)];
495 foreach my $cert (@$certs) {
496 if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
497 if ($cert->{name} eq "author") {
498 $user = $cert->{value};
499 } elsif ($cert->{name} eq "date") {
500 $when = $cert->{value};
501 } elsif ($cert->{name} eq "changelog") {
502 $message = $cert->{value};
507 my @changed_pages = get_changed_files($automator, $rev);
511 require IkiWiki::UserInfo;
517 `mtn --root=$config{mtnrootdir} au content_diff -r $rev`;
518 }, $user, @changed_pages);
521 sub rcs_getctime ($) {
522 # Optional, used to get the page creation time from the RCS.
523 # error gettext("getctime not implemented");
528 my $child = open(MTNLOG, "-|");
530 exec("mtn", "log", "--root=$config{mtnrootdir}", "--no-graph", "--brief", $file) || error("mtn log $file failed to run");
535 if (/^($sha1_pattern)/) {
539 close MTNLOG || warn "mtn log $file exited $?";
541 if (! defined $firstRev) {
542 warn "failed to parse mtn log for $file\n";
546 my $automator = Monotone->new();
547 $automator->open(undef, $config{mtnrootdir});
549 my $certs = [read_certs($automator, $firstRev)];
555 foreach my $cert (@$certs) {
556 if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
557 if ($cert->{name} eq "date") {
558 $date = $cert->{value};
563 if (! defined $date) {
564 warn "failed to find date cert for revision $firstRev when looking for creation time of $file\n";
568 $date=str2time($date, 'UTC');
569 debug("found ctime ".localtime($date)." for $file");
575 # default mergerc content
577 function local_execute_redirected(stdin, stdout, stderr, path, ...)
581 pid = spawn_redirected(stdin, stdout, stderr, path, unpack(arg))
582 if (pid ~= -1) then ret, pid = wait(pid) end
585 if (not execute_redirected) then -- use standard function if available
586 execute_redirected = local_execute_redirected
588 if (not mergers.fail) then -- use standard merger if available
590 cmd = function (tbl) return false end,
591 available = function () return true end,
592 wanted = function () return true end
595 mergers.diffutils_force = {
597 local ret = execute_redirected(
604 "--label", string.format("[Yours]", tbl.left_path ),
605 "--label", string.format("[Original]", tbl.anc_path ),
606 "--label", string.format("[Theirs]", tbl.right_path),
612 io.write(gettext("Error running GNU diffutils 3-way difference tool 'diff3'"))
619 return program_exists_in_path("diff3");