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(DATA, ">$mergerc") or error("can't open $mergerc $!");
134 " function local_execute_redirected(stdin, stdout, stderr, path, ...)\n".
138 " pid = spawn_redirected(stdin, stdout, stderr, path, unpack(arg))\n".
139 " if (pid ~= -1) then ret, pid = wait(pid) end\n".
142 " if (not execute_redirected) then -- use standard function if available\n".
143 " execute_redirected = local_execute_redirected\n".
145 " if (not mergers.fail) then -- use standard merger if available\n".
146 " mergers.fail = {\n".
147 " cmd = function (tbl) return false end,\n".
148 " available = function () return true end,\n".
149 " wanted = function () return true end\n".
152 " mergers.diffutils_force = {\n".
153 " cmd = function (tbl)\n".
154 " local ret = execute_redirected(\n".
160 " \"--show-overlap\",\n".
161 " \"--label\", string.format(\"[Yours]\", tbl.left_path ),\n".
162 " \"--label\", string.format(\"[Original]\", tbl.anc_path ),\n".
163 " \"--label\", string.format(\"[Theirs]\", tbl.right_path),\n".
168 " if (ret > 1) then\n".
169 " io.write(gettext(\"Error running GNU diffutils 3-way difference tool 'diff3'\"))\n".
172 " return tbl.outfile\n".
176 " return program_exists_in_path(\"diff3\");\n".
183 print DATA $defaultrc;
188 sub read_certs ($$) {
191 my @results = $automator->call("certs", $rev);
194 my $line = $results[0];
195 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) {
208 sub get_changed_files ($$) {
212 my @results = $automator->call("get_revision", $rev);
213 my $changes=$results[0];
218 while ($changes =~ m/\s*(add_file|patch|delete|rename)\s"(.*?)(?<!\\)"\n/sg) {
220 if (! $seen{$file}) { # don't add the same file multiple times
229 # The following functions are the ones actually called by Ikiwiki
232 # Update working directory to current version.
236 if (defined($config{mtnsync}) && $config{mtnsync}) {
237 if (system("mtn", "--root=$config{mtnrootdir}", "sync", "--quiet", "--ticker=none", "--key", $config{mtnkey}) != 0) {
238 warn("monotone sync failed before update\n");
242 if (system("mtn", "--root=$config{mtnrootdir}", "update", "--quiet") != 0) {
243 warn("monotone update failed\n");
247 sub rcs_prepedit ($) {
248 # Prepares to edit a file under revision control. Returns a token
249 # that must be passed into rcs_commit when the file is ready
251 # The file is relative to the srcdir.
256 # For monotone, return the revision of the file when
261 sub rcs_commit ($$$;$$) {
262 # Tries to commit the page; returns undef on _success_ and
263 # a version of the page with the rcs's conflict markers on failure.
264 # The file is relative to the srcdir.
273 $author="Web user: " . $user;
275 elsif (defined $ipaddr) {
276 $author="Web IP: " . $ipaddr;
279 $author="Web: Anonymous";
284 my ($oldrev)= $rcstoken=~ m/^($sha1_pattern)$/; # untaint
286 if (defined $rev && defined $oldrev && $rev ne $oldrev) {
287 my $automator = Monotone->new();
288 $automator->open_args("--root", $config{mtnrootdir}, "--key", $config{mtnkey});
290 # Something has been committed, has this file changed?
292 #$automator->setOpts("-r", $oldrev, "-r", $rev);
293 #my ($out, $err) = $automator->call("content_diff", $file);
294 #debug("Problem committing $file") if ($err ne "");
295 # FIXME: use of $file in these backticks is not wise from a
296 # security POV. Probably safe, but should be avoided
298 my $diff = `mtn --root=$config{mtnrootdir} au content_diff -r $oldrev -r $rev $file`; # was just $out;
301 # this file has changed
302 # commit a revision with just this file changed off
304 # first get the contents
305 warn("File changed: forming branch\n");
306 my $newfile=readfile("$config{srcdir}/$file");
308 # then get the old content ID from the diff
309 if ($diff !~ m/^---\s$file\s+($sha1_pattern)$/m) {
310 error("Unable to find previous file ID for $file");
314 # get the branch we're working in
315 ($out, $err) = $automator->call("get_option", "branch");
317 error("Illegal branch name in monotone workspace") if ($out !~ m/^([-\@\w\.]+)$/);
320 # then put the new content into the DB (and record the new content ID)
321 my $newRevID = commit_file_to_new_rev($automator, $file, $oldFileID, $newfile, $oldrev, $branch, $author, $message);
325 # if we made it to here then the file has been committed... revert the local copy
326 if (system("mtn", "--root=$config{mtnrootdir}", "revert", $file) != 0) {
327 warn("Unable to revert $file after merge on conflicted commit!");
329 warn("Divergence created! Attempting auto-merge.");
333 # see if it will merge cleanly
334 $ENV{MTN_MERGE}="fail";
335 my $mergeResult = mtn_merge($newRevID, $rev, $branch, $author, "Auto-merging parallel web edits.");
338 # push any changes so far
339 if (defined($config{mtnsync}) && $config{mtnsync}) {
340 if (system("mtn", "--root=$config{mtnrootdir}", "push", "--quiet", "--ticker=none", "--key", $config{mtnkey}) != 0) {
341 warn("monotone push failed\n");
345 if (defined($mergeResult)) {
346 # everything is merged - bring outselves up to date
347 if (system("mtn", "--root=$config{mtnrootdir}", "update", "-r", $mergeResult) != 0) {
348 warn("Unable to update to rev $mergeResult after merge on conflicted commit!");
351 warn("Auto-merge failed. Using diff-merge to add conflict markers.");
353 $ENV{MTN_MERGE}="diffutils_force";
354 my $mergeResult = mtn_merge($newRevID, $rev, $branch, $author, "Merge parallel conflicting web edits (adding inline conflict markers).\nThis revision should be cleaned up manually.");
357 if (!defined($mergeResult)) {
358 warn("Unable to insert conflict markers!");
359 error("Your commit succeeded. Unfortunately, someone else committed something to the same\n".
360 "part of the wiki at the same time. Both versions are stored in the monotone repository,\n".
361 "but at present the different versions cannot be reconciled through the web interface.\n\n".
362 "Please use the non-web interface to resolve the conflicts.\n");
365 # suspend this revision because it has conflict markers...
366 if (system("mtn", "--root=$config{mtnrootdir}", "update", "-r", $mergeResult) != 0) {
367 warn("Unable to update to rev $mergeResult after conflict-enhanced merge on conflicted commit!");
370 # return "conflict enhanced" file to the user for cleanup
371 # note, this relies on the fact that ikiwiki seems to call rcs_prepedit() again
373 return readfile("$config{srcdir}/$file");
380 # if we reached here then the file we're looking at hasn't changed since $oldrev. Commit it.
382 if (system("mtn", "--root=$config{mtnrootdir}", "commit", "--quiet", "--author", $author, "--key", $config{mtnkey},
383 "-m", possibly_foolish_untaint($message), $file) != 0) {
384 warn("Traditional commit failed!\nReturning data as conflict.\n");
385 my $conflict=readfile("$config{srcdir}/$file");
386 if (system("mtn", "--root=$config{mtnrootdir}", "revert", "--quiet", $file) != 0) {
387 warn("monotone revert failed\n");
391 if (defined($config{mtnsync}) && $config{mtnsync}) {
392 if (system("mtn", "--root=$config{mtnrootdir}", "sync", "--quiet", "--ticker=none", "--key", $config{mtnkey}) != 0) {
393 warn("monotone sync failed\n");
397 return undef # success
401 # Add a file. The filename is relative to the root of the srcdir.
406 if (system("mtn", "--root=$config{mtnrootdir}", "add", "--quiet", "$config{srcdir}/$file") != 0) {
407 error("Monotone add failed");
411 sub rcs_recentchanges ($) {
412 # Examine the RCS history and generate a list of recent changes.
413 # The data structure returned for each change is:
415 # user => # name of user who made the change,
416 # committype => # either "web" or the name of the rcs,
417 # when => # time when the change was made,
419 # { line => "commit message line" },
420 # { line => "commit message line" },
425 # page => # name of page changed,
426 # diffurl => # optional url to a diff showing
429 # # repeat for each page changed in this commit,
438 # use log --brief to get a list of revs, as this
439 # gives the results in a nice order
440 # (otherwise we'd have to do our own date sorting)
444 my $child = open(MTNLOG, "-|");
446 exec("mtn", "log", "--root=$config{mtnrootdir}", "--no-graph", "--brief") || error("mtn log failed to run");
451 while (($num >= 0) and ($line = <MTNLOG>)) {
452 if ($line =~ m/^($sha1_pattern)/) {
457 close MTNLOG || warn "mtn log exited $?";
459 my $automator = Monotone->new();
460 $automator->open(undef, $config{mtnrootdir});
463 my $rev = shift @revs;
464 # first go through and figure out the messages, etc
466 my $certs = [read_certs($automator, $rev)];
471 my (@pages, @message);
473 foreach my $cert (@$certs) {
474 if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
475 if ($cert->{name} eq "author") {
476 $user = $cert->{value};
477 # detect the source of the commit from the changelog
478 if ($cert->{key} eq $config{mtnkey}) {
481 $committype = "monotone";
483 } elsif ($cert->{name} eq "date") {
484 $when = time - str2time($cert->{value}, 'UTC');
485 } elsif ($cert->{name} eq "changelog") {
486 my $messageText = $cert->{value};
487 # split the changelog into multiple lines
488 foreach my $msgline (split(/\n/, $messageText)) {
489 push @message, { line => $msgline };
495 my @changed_files = get_changed_files($automator, $rev);
498 foreach $file (@changed_files) {
500 page => pagename($file),
507 committype => $committype,
509 message => [@message],
520 # This function is called when a change is committed to the wiki,
521 # and ikiwiki is running as a post-commit hook from the RCS.
522 # It should examine the repository to somehow determine what pages
523 # changed, and then send emails to users subscribed to those pages.
525 warn("The monotone rcs_notify function is currently untested. Use at own risk!");
527 if (! exists $ENV{REV}) {
528 error(gettext("REV is not set, not running from mtn post-commit hook, cannot send notifications"));
530 if ($ENV{REV} !~ m/($sha1_pattern)/) { # sha1 is untainted now
531 error(gettext("REV is not a valid revision identifier, cannot send notifications"));
537 my $automator = Monotone->new();
538 $automator->open(undef, $config{mtnrootdir});
540 my $certs = [read_certs($automator, $rev)];
545 foreach my $cert (@$certs) {
546 if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
547 if ($cert->{name} eq "author") {
548 $user = $cert->{value};
549 } elsif ($cert->{name} eq "date") {
550 $when = $cert->{value};
551 } elsif ($cert->{name} eq "changelog") {
552 $message = $cert->{value};
557 my @changed_pages = get_changed_files($automator, $rev);
561 require IkiWiki::UserInfo;
567 `mtn --root=$config{mtnrootdir} au content_diff -r $rev`;
568 }, $user, @changed_pages);
571 sub rcs_getctime ($) {
572 # Optional, used to get the page creation time from the RCS.
573 # error gettext("getctime not implemented");
578 my $child = open(MTNLOG, "-|");
580 exec("mtn", "log", "--root=$config{mtnrootdir}", "--no-graph", "--brief", $file) || error("mtn log $file failed to run");
585 if (/^($sha1_pattern)/) {
589 close MTNLOG || warn "mtn log $file exited $?";
591 if (! defined $firstRev) {
592 warn "failed to parse mtn log for $file\n";
596 my $automator = Monotone->new();
597 $automator->open(undef, $config{mtnrootdir});
599 my $certs = [read_certs($automator, $firstRev)];
605 foreach my $cert (@$certs) {
606 if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
607 if ($cert->{name} eq "date") {
608 $date = $cert->{value};
613 if (! defined $date) {
614 warn "failed to find date cert for revision $firstRev when looking for creation time of $file\n";
618 $date=str2time($date, 'UTC');
619 debug("found ctime ".localtime($date)." for $file");