summaryrefslogtreecommitdiff
path: root/IkiWiki/Rcs/monotone.pm
blob: 0435dc45cb096042e02df4887acfd9af138b9e7f (plain)
  1. #!/usr/bin/perl
  2. use warnings;
  3. use strict;
  4. use IkiWiki;
  5. use Monotone;
  6. use Date::Parse qw(str2time);
  7. use Date::Format qw(time2str);
  8. package IkiWiki;
  9. my $sha1_pattern = qr/[0-9a-fA-F]{40}/; # pattern to validate sha1sums
  10. sub check_config() {
  11. if (!defined($config{mtnrootdir})) {
  12. $config{mtnrootdir} = $config{srcdir};
  13. }
  14. if (! -d "$config{mtnrootdir}/_MTN") {
  15. error("Ikiwiki srcdir does not seem to be a Monotone workspace (or set the mtnrootdir)!");
  16. }
  17. if (!defined($config{mtnmergerc})) {
  18. $config{mtnmergerc} = "$config{mtnrootdir}/_MTN/mergerc";
  19. }
  20. chdir $config{srcdir}
  21. or error("Cannot chdir to $config{srcdir}: $!");
  22. }
  23. sub get_rev () {
  24. my $sha1 = `mtn --root=$config{mtnrootdir} automate get_base_revision_id`;
  25. ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
  26. if (! $sha1) {
  27. warn("Unable to get base revision for '$config{srcdir}'.")
  28. }
  29. return $sha1;
  30. }
  31. sub get_rev_auto ($) {
  32. my $automator=shift;
  33. my @results = $automator->call("get_base_revision_id");
  34. my $sha1 = $results[0];
  35. ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
  36. if (! $sha1) {
  37. warn("Unable to get base revision for '$config{srcdir}'.")
  38. }
  39. return $sha1;
  40. }
  41. sub mtn_merge ($$$$$) {
  42. my $leftRev=shift;
  43. my $rightRev=shift;
  44. my $branch=shift;
  45. my $author=shift;
  46. my $message=shift; # ignored for the moment because mtn doesn't support it
  47. my $mergeRev;
  48. my $mergerc = $config{mtnmergerc};
  49. my $child = open(MTNMERGE, "-|");
  50. if (! $child) {
  51. open STDERR, ">&STDOUT";
  52. exec("mtn", "--root=$config{mtnrootdir}", "--rcfile", $mergerc, "explicit_merge", $leftRev, $rightRev, $branch, "--author", $author, "--key", $config{mtnkey}) || error("mtn merge failed to run");
  53. }
  54. while (<MTNMERGE>) {
  55. if (/^mtn.\s.merged.\s($sha1_pattern)$/) {
  56. $mergeRev=$1;
  57. }
  58. }
  59. close MTNMERGE || return undef;
  60. warn("merged $leftRev, $rightRev to make $mergeRev");
  61. return $mergeRev;
  62. }
  63. sub commit_file_to_new_rev($$$$$$$$) {
  64. my $automator=shift;
  65. my $wsfilename=shift;
  66. my $oldFileID=shift;
  67. my $newFileContents=shift;
  68. my $oldrev=shift;
  69. my $branch=shift;
  70. my $author=shift;
  71. my $message=shift;
  72. #store the file
  73. my ($out, $err) = $automator->call("put_file", $oldFileID, $newFileContents);
  74. my ($newFileID) = ($out =~ m/^($sha1_pattern)$/);
  75. error("Failed to store file data for $wsfilename in repository") if (!defined($newFileID) || 40 != length $newFileID);
  76. # get the mtn filename rather than the workspace filename
  77. ($out, $err) = $automator->call("get_corresponding_path", $oldrev, $wsfilename, $oldrev);
  78. my ($filename) = ($out =~ m/^file "(.*)"$/);
  79. error("Couldn't find monotone repository path for file $wsfilename") if (! $filename);
  80. warn("Converted ws filename of $wsfilename to repos filename of $filename");
  81. # then stick in a new revision for this file
  82. my $manifest = "format_version \"1\"\n\n".
  83. "new_manifest [0000000000000000000000000000000000000000]\n\n".
  84. "old_revision [$oldrev]\n\n".
  85. "patch \"$filename\"\n".
  86. " from [$oldFileID]\n".
  87. " to [$newFileID]\n";
  88. ($out, $err) = $automator->call("put_revision", $manifest);
  89. my ($newRevID) = ($out =~ m/^($sha1_pattern)$/);
  90. error("Unable to make new monotone repository revision") if (!defined($newRevID) || 40 != length $newRevID);
  91. warn("put revision: $newRevID");
  92. # now we need to add certs for this revision...
  93. # author, branch, changelog, date
  94. $automator->call("cert", $newRevID, "author", $author);
  95. $automator->call("cert", $newRevID, "branch", $branch);
  96. $automator->call("cert", $newRevID, "changelog", $message);
  97. $automator->call("cert", $newRevID, "date", time2str("%Y-%m-%dT%T", time, "UTC"));
  98. warn("Added certs for rev: $newRevID");
  99. return $newRevID;
  100. }
  101. sub check_mergerc() {
  102. my $mergerc = $config{mtnmergerc};
  103. if (! -r $mergerc ) {
  104. warn("$mergerc doesn't exist. Creating file with default mergers.");
  105. open(DATA, ">$mergerc") or error("can't open $mergerc $!");
  106. my $defaultrc = "".
  107. " function local_execute_redirected(stdin, stdout, stderr, path, ...)\n".
  108. " local pid\n".
  109. " local ret = -1\n".
  110. " io.flush();\n".
  111. " pid = spawn_redirected(stdin, stdout, stderr, path, unpack(arg))\n".
  112. " if (pid ~= -1) then ret, pid = wait(pid) end\n".
  113. " return ret\n".
  114. " end\n".
  115. " if (not execute_redirected) then -- use standard function if available\n".
  116. " execute_redirected = local_execute_redirected\n".
  117. " end\n".
  118. " if (not mergers.fail) then -- use standard merger if available\n".
  119. " mergers.fail = {\n".
  120. " cmd = function (tbl) return false end,\n".
  121. " available = function () return true end,\n".
  122. " wanted = function () return true end\n".
  123. " }\n".
  124. " end\n".
  125. " mergers.diffutils_force = {\n".
  126. " cmd = function (tbl)\n".
  127. " local ret = execute_redirected(\n".
  128. " \"\",\n".
  129. " tbl.outfile,\n".
  130. " \"\",\n".
  131. " \"diff3\",\n".
  132. " \"--merge\",\n".
  133. " \"--show-overlap\",\n".
  134. " \"--label\", string.format(\"[Yours]\", tbl.left_path ),\n".
  135. " \"--label\", string.format(\"[Original]\", tbl.anc_path ),\n".
  136. " \"--label\", string.format(\"[Theirs]\", tbl.right_path),\n".
  137. " tbl.lfile,\n".
  138. " tbl.afile,\n".
  139. " tbl.rfile\n".
  140. " )\n".
  141. " if (ret > 1) then\n".
  142. " io.write(gettext(\"Error running GNU diffutils 3-way difference tool 'diff3'\"))\n".
  143. " return false\n".
  144. " end\n".
  145. " return tbl.outfile\n".
  146. " end,\n".
  147. " available =\n".
  148. " function ()\n".
  149. " return program_exists_in_path(\"diff3\");\n".
  150. " end,\n".
  151. " wanted =\n".
  152. " function ()\n".
  153. " return true\n".
  154. " end\n".
  155. " }\n";
  156. print DATA $defaultrc;
  157. close(DATA);
  158. }
  159. }
  160. sub read_certs ($$) {
  161. my $automator=shift;
  162. my $rev=shift;
  163. my @results = $automator->call("certs", $rev);
  164. my @ret;
  165. my $line = $results[0];
  166. 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) {
  167. push @ret, {
  168. key => $1,
  169. signature => $2,
  170. name => $3,
  171. value => $4,
  172. trust => $5,
  173. };
  174. }
  175. return @ret;
  176. }
  177. sub get_changed_files ($$) {
  178. my $automator=shift;
  179. my $rev=shift;
  180. my @results = $automator->call("get_revision", $rev);
  181. my $changes=$results[0];
  182. my @ret;
  183. my %seen = ();
  184. while ($changes =~ m/\s*(add_file|patch|delete|rename)\s"(.*?)(?<!\\)"\n/sg) {
  185. my $file = $2;
  186. if (! $seen{$file}) { # don't add the same file multiple times
  187. push @ret, $file;
  188. $seen{$file} = 1;
  189. }
  190. }
  191. return @ret;
  192. }
  193. # The following functions are the ones actually called by Ikiwiki
  194. sub rcs_update () {
  195. # Update working directory to current version.
  196. check_config();
  197. if (defined($config{mtnsync}) && $config{mtnsync}) {
  198. if (system("mtn", "--root=$config{mtnrootdir}", "sync", "--quiet", "--ticker=none", "--key", $config{mtnkey}) != 0) {
  199. warn("monotone sync failed before update\n");
  200. }
  201. }
  202. if (system("mtn", "--root=$config{mtnrootdir}", "update", "--quiet") != 0) {
  203. warn("monotone update failed\n");
  204. }
  205. }
  206. sub rcs_prepedit ($) {
  207. # Prepares to edit a file under revision control. Returns a token
  208. # that must be passed into rcs_commit when the file is ready
  209. # for committing.
  210. # The file is relative to the srcdir.
  211. my $file=shift;
  212. check_config();
  213. # For monotone, return the revision of the file when
  214. # editing begins.
  215. return get_rev();
  216. }
  217. sub rcs_commit ($$$;$$) {
  218. # Tries to commit the page; returns undef on _success_ and
  219. # a version of the page with the rcs's conflict markers on failure.
  220. # The file is relative to the srcdir.
  221. my $file=shift;
  222. my $message=shift;
  223. my $rcstoken=shift;
  224. my $user=shift;
  225. my $ipaddr=shift;
  226. my $author;
  227. if (defined $user) {
  228. $author="Web user: " . $user;
  229. }
  230. elsif (defined $ipaddr) {
  231. $author="Web IP: " . $ipaddr;
  232. }
  233. else {
  234. $author="Web: Anonymous";
  235. }
  236. check_config();
  237. my ($oldrev)= $rcstoken=~ m/^($sha1_pattern)$/; # untaint
  238. my $rev = get_rev();
  239. if (defined $rev && defined $oldrev && $rev ne $oldrev) {
  240. my $automator = Monotone->new();
  241. $automator->open_args("--root", $config{mtnrootdir}, "--key", $config{mtnkey});
  242. # Something has been committed, has this file changed?
  243. my ($out, $err);
  244. #$automator->setOpts("-r", $oldrev, "-r", $rev);
  245. #my ($out, $err) = $automator->call("content_diff", $file);
  246. #debug("Problem committing $file") if ($err ne "");
  247. # FIXME: use of $file in these backticks is not wise from a
  248. # security POV. Probably safe, but should be avoided
  249. # anyway.
  250. my $diff = `mtn --root=$config{mtnrootdir} au content_diff -r $oldrev -r $rev $file`; # was just $out;
  251. if ($diff) {
  252. # this file has changed
  253. # commit a revision with just this file changed off
  254. # the old revision
  255. # first get the contents
  256. warn("File changed: forming branch\n");
  257. 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");
  261. }
  262. my $oldFileID = $1;
  263. # get the branch we're working in
  264. ($out, $err) = $automator->call("get_option", "branch");
  265. chomp $out;
  266. error("Illegal branch name in monotone workspace") if ($out !~ m/^([-\@\w\.]+)$/);
  267. my $branch = $1;
  268. # then put the new content into the DB (and record the new content ID)
  269. my $newRevID = commit_file_to_new_rev($automator, $file, $oldFileID, $newfile, $oldrev, $branch, $author, $message);
  270. $automator->close();
  271. # if we made it to here then the file has been committed... revert the local copy
  272. if (system("mtn", "--root=$config{mtnrootdir}", "revert", $file) != 0) {
  273. warn("Unable to revert $file after merge on conflicted commit!");
  274. }
  275. warn("Divergence created! Attempting auto-merge.");
  276. check_mergerc();
  277. # see if it will merge cleanly
  278. $ENV{MTN_MERGE}="fail";
  279. my $mergeResult = mtn_merge($newRevID, $rev, $branch, $author, "Auto-merging parallel web edits.");
  280. $ENV{MTN_MERGE}="";
  281. # push any changes so far
  282. if (defined($config{mtnsync}) && $config{mtnsync}) {
  283. if (system("mtn", "--root=$config{mtnrootdir}", "push", "--quiet", "--ticker=none", "--key", $config{mtnkey}) != 0) {
  284. warn("monotone push failed\n");
  285. }
  286. }
  287. if (defined($mergeResult)) {
  288. # everything is merged - bring outselves up to date
  289. if (system("mtn", "--root=$config{mtnrootdir}", "update", "-r", $mergeResult) != 0) {
  290. warn("Unable to update to rev $mergeResult after merge on conflicted commit!");
  291. }
  292. } else {
  293. warn("Auto-merge failed. Using diff-merge to add conflict markers.");
  294. $ENV{MTN_MERGE}="diffutils_force";
  295. my $mergeResult = mtn_merge($newRevID, $rev, $branch, $author, "Merge parallel conflicting web edits (adding inline conflict markers).\nThis revision should be cleaned up manually.");
  296. $ENV{MTN_MERGE}="";
  297. if (!defined($mergeResult)) {
  298. warn("Unable to insert conflict markers!");
  299. error("Your commit succeeded. Unfortunately, someone else committed something to the same\n".
  300. "part of the wiki at the same time. Both versions are stored in the monotone repository,\n".
  301. "but at present the different versions cannot be reconciled through the web interface.\n\n".
  302. "Please use the non-web interface to resolve the conflicts.\n");
  303. }
  304. # suspend this revision because it has conflict markers...
  305. if (system("mtn", "--root=$config{mtnrootdir}", "update", "-r", $mergeResult) != 0) {
  306. warn("Unable to update to rev $mergeResult after conflict-enhanced merge on conflicted commit!");
  307. }
  308. # return "conflict enhanced" file to the user for cleanup
  309. # note, this relies on the fact that ikiwiki seems to call rcs_prepedit() again
  310. # after we return
  311. return readfile("$config{srcdir}/$file");
  312. }
  313. return undef;
  314. }
  315. $automator->close();
  316. }
  317. # if we reached here then the file we're looking at hasn't changed since $oldrev. Commit it.
  318. if (system("mtn", "--root=$config{mtnrootdir}", "commit", "--quiet", "--author", $author, "--key", $config{mtnkey},
  319. "-m", possibly_foolish_untaint($message), $file) != 0) {
  320. warn("Traditional commit failed!\nReturning data as conflict.\n");
  321. my $conflict=readfile("$config{srcdir}/$file");
  322. if (system("mtn", "--root=$config{mtnrootdir}", "revert", "--quiet", $file) != 0) {
  323. warn("monotone revert failed\n");
  324. }
  325. return $conflict;
  326. }
  327. if (defined($config{mtnsync}) && $config{mtnsync}) {
  328. if (system("mtn", "--root=$config{mtnrootdir}", "sync", "--quiet", "--ticker=none", "--key", $config{mtnkey}) != 0) {
  329. warn("monotone sync failed\n");
  330. }
  331. }
  332. return undef # success
  333. }
  334. sub rcs_add ($) {
  335. # Add a file. The filename is relative to the root of the srcdir.
  336. my $file=shift;
  337. check_config();
  338. if (system("mtn", "--root=$config{mtnrootdir}", "add", "--quiet", "$config{srcdir}/$file") != 0) {
  339. error("Monotone add failed");
  340. }
  341. }
  342. sub rcs_recentchanges ($) {
  343. # Examine the RCS history and generate a list of recent changes.
  344. # The data structure returned for each change is:
  345. # {
  346. # user => # name of user who made the change,
  347. # committype => # either "web" or the name of the rcs,
  348. # when => # time when the change was made,
  349. # message => [
  350. # { line => "commit message line" },
  351. # { line => "commit message line" },
  352. # # etc,
  353. # ],
  354. # pages => [
  355. # {
  356. # page => # name of page changed,
  357. # diffurl => # optional url to a diff showing
  358. # # the changes,
  359. # },
  360. # # repeat for each page changed in this commit,
  361. # ],
  362. # }
  363. my $num=shift;
  364. my @ret;
  365. check_config();
  366. # use log --brief to get a list of revs, as this
  367. # gives the results in a nice order
  368. # (otherwise we'd have to do our own date sorting)
  369. my @revs;
  370. my $child = open(MTNLOG, "-|");
  371. if (! $child) {
  372. exec("mtn", "log", "--root=$config{mtnrootdir}", "--no-graph", "--brief") || error("mtn log failed to run");
  373. }
  374. my $line;
  375. while (($num >= 0) and ($line = <MTNLOG>)) {
  376. if ($line =~ m/^($sha1_pattern)/) {
  377. push @revs, $1;
  378. $num -= 1;
  379. }
  380. }
  381. close MTNLOG || warn "mtn log exited $?";
  382. my $automator = Monotone->new();
  383. $automator->open(undef, $config{mtnrootdir});
  384. while (@revs != 0) {
  385. my $rev = shift @revs;
  386. # first go through and figure out the messages, etc
  387. my $certs = [read_certs($automator, $rev)];
  388. my $user;
  389. my $when;
  390. my $committype;
  391. my (@pages, @message);
  392. foreach my $cert (@$certs) {
  393. if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
  394. if ($cert->{name} eq "author") {
  395. $user = $cert->{value};
  396. # detect the source of the commit from the changelog
  397. if ($cert->{key} eq $config{mtnkey}) {
  398. $committype = "web";
  399. } else {
  400. $committype = "monotone";
  401. }
  402. } elsif ($cert->{name} eq "date") {
  403. $when = time - str2time($cert->{value}, 'UTC');
  404. } elsif ($cert->{name} eq "changelog") {
  405. my $messageText = $cert->{value};
  406. # split the changelog into multiple lines
  407. foreach my $msgline (split(/\n/, $messageText)) {
  408. push @message, { line => $msgline };
  409. }
  410. }
  411. }
  412. }
  413. my @changed_files = get_changed_files($automator, $rev);
  414. my $file;
  415. foreach $file (@changed_files) {
  416. push @pages, {
  417. page => pagename($file),
  418. } if length $file;
  419. }
  420. push @ret, {
  421. rev => $rev,
  422. user => $user,
  423. committype => $committype,
  424. when => $when,
  425. message => [@message],
  426. pages => [@pages],
  427. } if @pages;
  428. }
  429. $automator->close();
  430. return @ret;
  431. }
  432. sub rcs_notify () {
  433. # This function is called when a change is committed to the wiki,
  434. # and ikiwiki is running as a post-commit hook from the RCS.
  435. # It should examine the repository to somehow determine what pages
  436. # changed, and then send emails to users subscribed to those pages.
  437. warn("The monotone rcs_notify function is currently untested. Use at own risk!");
  438. if (! exists $ENV{REV}) {
  439. error(gettext("REV is not set, not running from mtn post-commit hook, cannot send notifications"));
  440. }
  441. if ($ENV{REV} !~ m/($sha1_pattern)/) { # sha1 is untainted now
  442. error(gettext("REV is not a valid revision identifier, cannot send notifications"));
  443. }
  444. my $rev = $1;
  445. check_config();
  446. my $automator = Monotone->new();
  447. $automator->open(undef, $config{mtnrootdir});
  448. my $certs = [read_certs($automator, $rev)];
  449. my $user;
  450. my $message;
  451. my $when;
  452. foreach my $cert (@$certs) {
  453. if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
  454. if ($cert->{name} eq "author") {
  455. $user = $cert->{value};
  456. } elsif ($cert->{name} eq "date") {
  457. $when = $cert->{value};
  458. } elsif ($cert->{name} eq "changelog") {
  459. $message = $cert->{value};
  460. }
  461. }
  462. }
  463. my @changed_pages = get_changed_files($automator, $rev);
  464. $automator->close();
  465. require IkiWiki::UserInfo;
  466. send_commit_mails(
  467. sub {
  468. return $message;
  469. },
  470. sub {
  471. `mtn --root=$config{mtnrootdir} au content_diff -r $rev`;
  472. }, $user, @changed_pages);
  473. }
  474. sub rcs_getctime ($) {
  475. # Optional, used to get the page creation time from the RCS.
  476. # error gettext("getctime not implemented");
  477. my $file=shift;
  478. check_config();
  479. my $child = open(MTNLOG, "-|");
  480. if (! $child) {
  481. exec("mtn", "log", "--root=$config{mtnrootdir}", "--no-graph", "--brief", $file) || error("mtn log $file failed to run");
  482. }
  483. my $firstRev;
  484. while (<MTNLOG>) {
  485. if (/^($sha1_pattern)/) {
  486. $firstRev=$1;
  487. }
  488. }
  489. close MTNLOG || warn "mtn log $file exited $?";
  490. if (! defined $firstRev) {
  491. warn "failed to parse mtn log for $file\n";
  492. return 0;
  493. }
  494. my $automator = Monotone->new();
  495. $automator->open(undef, $config{mtnrootdir});
  496. my $certs = [read_certs($automator, $firstRev)];
  497. $automator->close();
  498. my $date;
  499. foreach my $cert (@$certs) {
  500. if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
  501. if ($cert->{name} eq "date") {
  502. $date = $cert->{value};
  503. }
  504. }
  505. }
  506. if (! defined $date) {
  507. warn "failed to find date cert for revision $firstRev when looking for creation time of $file\n";
  508. return 0;
  509. }
  510. $date=str2time($date, 'UTC');
  511. debug("found ctime ".localtime($date)." for $file");
  512. return $date;
  513. }