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
13 sub check_config() { #{{{
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 debug("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 debug("Unable to get base revision for '$config{srcdir}'.")
54 sub mtn_merge ($$$$) { #{{{
62 my $mergerc = $config{mtnmergerc};
64 my $child = open(MTNMERGE, "-|");
66 open STDERR, ">&STDOUT";
67 exec("mtn", "--root=$config{mtnrootdir}", "--rcfile",
68 $mergerc, "explicit_merge", $leftRev, $rightRev,
69 $branch, "--author", $author, "--key",
70 $config{mtnkey}) || error("mtn merge failed to run");
74 if (/^mtn.\s.merged.\s($sha1_pattern)$/) {
79 close MTNMERGE || return undef;
81 debug("merged $leftRev, $rightRev to make $mergeRev");
86 sub commit_file_to_new_rev($$$$$$$$) { #{{{
90 my $newFileContents=shift;
97 my ($out, $err) = $automator->call("put_file", $oldFileID, $newFileContents);
98 my ($newFileID) = ($out =~ m/^($sha1_pattern)$/);
99 error("Failed to store file data for $wsfilename in repository")
100 if (! defined $newFileID || length $newFileID != 40);
102 # get the mtn filename rather than the workspace filename
103 ($out, $err) = $automator->call("get_corresponding_path", $oldrev, $wsfilename, $oldrev);
104 my ($filename) = ($out =~ m/^file "(.*)"$/);
105 error("Couldn't find monotone repository path for file $wsfilename") if (! $filename);
106 debug("Converted ws filename of $wsfilename to repos filename of $filename");
108 # then stick in a new revision for this file
109 my $manifest = "format_version \"1\"\n\n".
110 "new_manifest [0000000000000000000000000000000000000000]\n\n".
111 "old_revision [$oldrev]\n\n".
112 "patch \"$filename\"\n".
113 " from [$oldFileID]\n".
114 " to [$newFileID]\n";
115 ($out, $err) = $automator->call("put_revision", $manifest);
116 my ($newRevID) = ($out =~ m/^($sha1_pattern)$/);
117 error("Unable to make new monotone repository revision")
118 if (! defined $newRevID || length $newRevID != 40);
119 debug("put revision: $newRevID");
121 # now we need to add certs for this revision...
122 # author, branch, changelog, date
123 $automator->call("cert", $newRevID, "author", $author);
124 $automator->call("cert", $newRevID, "branch", $branch);
125 $automator->call("cert", $newRevID, "changelog", $message);
126 $automator->call("cert", $newRevID, "date",
127 time2str("%Y-%m-%dT%T", time, "UTC"));
129 debug("Added certs for rev: $newRevID");
133 sub check_mergerc () { #{{{
134 my $mergerc = $config{mtnmergerc};
135 if (! -r $mergerc ) {
136 debug("$mergerc doesn't exist. Creating file with default mergers.");
137 open (my $out, ">", $mergerc) or error("can't open $mergerc: $!");
143 sub read_certs ($$) { #{{{
146 my @results = $automator->call("certs", $rev);
149 my $line = $results[0];
150 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) {
163 sub get_changed_files ($$) { #{{{
167 my @results = $automator->call("get_revision", $rev);
168 my $changes=$results[0];
173 while ($changes =~ m/\s*(add_file|patch|delete|rename)\s"(.*?)(?<!\\)"\n/sg) {
175 # don't add the same file multiple times
176 if (! $seen{$file}) {
185 sub rcs_update () { #{{{
188 if (defined($config{mtnsync}) && $config{mtnsync}) {
189 if (system("mtn", "--root=$config{mtnrootdir}", "sync",
190 "--quiet", "--ticker=none",
191 "--key", $config{mtnkey}) != 0) {
192 debug("monotone sync failed before update");
196 if (system("mtn", "--root=$config{mtnrootdir}", "update", "--quiet") != 0) {
197 debug("monotone update failed");
201 sub rcs_prepedit ($) { #{{{
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 # Commit a revision with just this file changed off
254 # first get the contents
255 debug("File changed: forming branch");
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 debug("Unable to revert $file after merge on conflicted commit!");
279 debug("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);
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 debug("monotone push failed");
295 if (defined($mergeResult)) {
296 # everything is merged - bring outselves up to date
297 if (system("mtn", "--root=$config{mtnrootdir}",
298 "update", "-r", $mergeResult) != 0) {
299 debug("Unable to update to rev $mergeResult after merge on conflicted commit!");
303 debug("Auto-merge failed. Using diff-merge to add conflict markers.");
305 $ENV{MTN_MERGE}="diffutils_force";
306 $mergeResult = mtn_merge($newRevID, $rev, $branch, $author);
309 if (!defined($mergeResult)) {
310 debug("Unable to insert conflict markers!");
311 error("Your commit succeeded. Unfortunately, someone else committed something to the same ".
312 "part of the wiki at the same time. Both versions are stored in the monotone repository, ".
313 "but at present the different versions cannot be reconciled through the web interface. ".
314 "Please use the non-web interface to resolve the conflicts.");
317 # suspend this revision because it has
318 # conflict markers...
319 if (system("mtn", "--root=$config{mtnrootdir}",
320 "update", "-r", $mergeResult) != 0) {
321 debug("Unable to update to rev $mergeResult after conflict-enhanced merge on conflicted commit!");
324 # return "conflict enhanced" file to the user
325 # for cleanup note, this relies on the fact
326 # that ikiwiki seems to call rcs_prepedit()
327 # again after we return
328 return readfile("$config{srcdir}/$file");
335 # If we reached here then the file we're looking at hasn't changed
336 # since $oldrev. Commit it.
338 if (system("mtn", "--root=$config{mtnrootdir}", "commit", "--quiet",
339 "--author", $author, "--key", $config{mtnkey}, "-m",
340 possibly_foolish_untaint($message), $file) != 0) {
341 debug("Traditional commit failed! Returning data as conflict.");
342 my $conflict=readfile("$config{srcdir}/$file");
343 if (system("mtn", "--root=$config{mtnrootdir}", "revert",
344 "--quiet", $file) != 0) {
345 debug("monotone revert failed");
349 if (defined($config{mtnsync}) && $config{mtnsync}) {
350 if (system("mtn", "--root=$config{mtnrootdir}", "sync",
351 "--quiet", "--ticker=none", "--key",
352 $config{mtnkey}) != 0) {
353 debug("monotone sync failed");
357 return undef # success
360 sub rcs_add ($) { #{{{
365 if (system("mtn", "--root=$config{mtnrootdir}", "add", "--quiet",
366 "$config{srcdir}/$file") != 0) {
367 error("Monotone add failed");
371 sub rcs_recentchanges ($) { #{{{
377 # use log --brief to get a list of revs, as this
378 # gives the results in a nice order
379 # (otherwise we'd have to do our own date sorting)
383 my $child = open(MTNLOG, "-|");
385 exec("mtn", "log", "--root=$config{mtnrootdir}", "--no-graph",
386 "--brief") || error("mtn log failed to run");
389 while (($num >= 0) and (my $line = <MTNLOG>)) {
390 if ($line =~ m/^($sha1_pattern)/) {
395 close MTNLOG || debug("mtn log exited $?");
397 my $automator = Monotone->new();
398 $automator->open(undef, $config{mtnrootdir});
401 my $rev = shift @revs;
402 # first go through and figure out the messages, etc
404 my $certs = [read_certs($automator, $rev)];
409 my (@pages, @message);
411 foreach my $cert (@$certs) {
412 if ($cert->{signature} eq "ok" &&
413 $cert->{trust} eq "trusted") {
414 if ($cert->{name} eq "author") {
415 $user = $cert->{value};
416 # detect the source of the commit
418 if ($cert->{key} eq $config{mtnkey}) {
421 $committype = "monotone";
423 } elsif ($cert->{name} eq "date") {
424 $when = time - str2time($cert->{value}, 'UTC');
425 } elsif ($cert->{name} eq "changelog") {
426 my $messageText = $cert->{value};
427 # split the changelog into multiple
429 foreach my $msgline (split(/\n/, $messageText)) {
430 push @message, { line => $msgline };
436 my @changed_files = get_changed_files($automator, $rev);
439 foreach $file (@changed_files) {
441 page => pagename($file),
448 committype => $committype,
450 message => [@message],
460 sub rcs_notify () { #{{{
461 debug("The monotone rcs_notify function is currently untested. Use at own risk!");
463 if (! exists $ENV{REV}) {
464 error(gettext("REV is not set, not running from mtn post-commit hook, cannot send notifications"));
466 if ($ENV{REV} !~ m/($sha1_pattern)/) { # sha1 is untainted now
467 error(gettext("REV is not a valid revision identifier, cannot send notifications"));
473 my $automator = Monotone->new();
474 $automator->open(undef, $config{mtnrootdir});
476 my $certs = [read_certs($automator, $rev)];
481 foreach my $cert (@$certs) {
482 if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
483 if ($cert->{name} eq "author") {
484 $user = $cert->{value};
485 } elsif ($cert->{name} eq "date") {
486 $when = $cert->{value};
487 } elsif ($cert->{name} eq "changelog") {
488 $message = $cert->{value};
493 my @changed_pages = get_changed_files($automator, $rev);
497 require IkiWiki::UserInfo;
503 `mtn --root=$config{mtnrootdir} au content_diff -r $rev`;
505 $user, @changed_pages);
508 sub rcs_getctime ($) { #{{{
513 my $child = open(MTNLOG, "-|");
515 exec("mtn", "log", "--root=$config{mtnrootdir}", "--no-graph",
516 "--brief", $file) || error("mtn log $file failed to run");
521 if (/^($sha1_pattern)/) {
525 close MTNLOG || debug("mtn log $file exited $?");
527 if (! defined $firstRev) {
528 debug "failed to parse mtn log for $file";
532 my $automator = Monotone->new();
533 $automator->open(undef, $config{mtnrootdir});
535 my $certs = [read_certs($automator, $firstRev)];
541 foreach my $cert (@$certs) {
542 if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
543 if ($cert->{name} eq "date") {
544 $date = $cert->{value};
549 if (! defined $date) {
550 debug "failed to find date cert for revision $firstRev when looking for creation time of $file";
554 $date=str2time($date, 'UTC');
555 debug("found ctime ".localtime($date)." for $file");
561 # default mergerc content
563 function local_execute_redirected(stdin, stdout, stderr, path, ...)
567 pid = spawn_redirected(stdin, stdout, stderr, path, unpack(arg))
568 if (pid ~= -1) then ret, pid = wait(pid) end
571 if (not execute_redirected) then -- use standard function if available
572 execute_redirected = local_execute_redirected
574 if (not mergers.fail) then -- use standard merger if available
576 cmd = function (tbl) return false end,
577 available = function () return true end,
578 wanted = function () return true end
581 mergers.diffutils_force = {
583 local ret = execute_redirected(
590 "--label", string.format("[Yours]", tbl.left_path ),
591 "--label", string.format("[Original]", tbl.anc_path ),
592 "--label", string.format("[Theirs]", tbl.right_path),
598 io.write(gettext("Error running GNU diffutils 3-way difference tool 'diff3'"))
605 return program_exists_in_path("diff3");