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