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