summaryrefslogtreecommitdiff
path: root/IkiWiki/Rcs/monotone.pm
blob: 5717e004342875e97259cc09fe22b77f7b981810 (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}", "sync",
  284. "--quiet", "--ticker=none", "--key",
  285. $config{mtnkey}) != 0) {
  286. debug("monotone sync 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 = time - 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. foreach $file (@changed_files) {
  356. push @pages, {
  357. page => pagename($file),
  358. } if length $file;
  359. }
  360. push @ret, {
  361. rev => $rev,
  362. user => $user,
  363. committype => $committype,
  364. when => $when,
  365. message => [@message],
  366. pages => [@pages],
  367. } if @pages;
  368. }
  369. $automator->close();
  370. return @ret;
  371. } #}}}
  372. sub rcs_notify () { #{{{
  373. debug("The monotone rcs_notify function is currently untested. Use at own risk!");
  374. if (! exists $ENV{REV}) {
  375. error(gettext("REV is not set, not running from mtn post-commit hook, cannot send notifications"));
  376. }
  377. if ($ENV{REV} !~ m/($sha1_pattern)/) { # sha1 is untainted now
  378. error(gettext("REV is not a valid revision identifier, cannot send notifications"));
  379. }
  380. my $rev = $1;
  381. check_config();
  382. my $automator = Monotone->new();
  383. $automator->open(undef, $config{mtnrootdir});
  384. my $certs = [read_certs($automator, $rev)];
  385. my $user;
  386. my $message;
  387. my $when;
  388. foreach my $cert (@$certs) {
  389. if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
  390. if ($cert->{name} eq "author") {
  391. $user = $cert->{value};
  392. } elsif ($cert->{name} eq "date") {
  393. $when = $cert->{value};
  394. } elsif ($cert->{name} eq "changelog") {
  395. $message = $cert->{value};
  396. }
  397. }
  398. }
  399. my @changed_pages = get_changed_files($automator, $rev);
  400. $automator->close();
  401. require IkiWiki::UserInfo;
  402. send_commit_mails(
  403. sub {
  404. return $message;
  405. },
  406. sub {
  407. `mtn --root=$config{mtnrootdir} au content_diff -r $rev`;
  408. },
  409. $user, @changed_pages);
  410. } #}}}
  411. sub rcs_getctime ($) { #{{{
  412. my $file=shift;
  413. check_config();
  414. my $child = open(MTNLOG, "-|");
  415. if (! $child) {
  416. exec("mtn", "log", "--root=$config{mtnrootdir}", "--no-graph",
  417. "--brief", $file) || error("mtn log $file failed to run");
  418. }
  419. my $firstRev;
  420. while (<MTNLOG>) {
  421. if (/^($sha1_pattern)/) {
  422. $firstRev=$1;
  423. }
  424. }
  425. close MTNLOG || debug("mtn log $file exited $?");
  426. if (! defined $firstRev) {
  427. debug "failed to parse mtn log for $file";
  428. return 0;
  429. }
  430. my $automator = Monotone->new();
  431. $automator->open(undef, $config{mtnrootdir});
  432. my $certs = [read_certs($automator, $firstRev)];
  433. $automator->close();
  434. my $date;
  435. foreach my $cert (@$certs) {
  436. if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
  437. if ($cert->{name} eq "date") {
  438. $date = $cert->{value};
  439. }
  440. }
  441. }
  442. if (! defined $date) {
  443. debug "failed to find date cert for revision $firstRev when looking for creation time of $file";
  444. return 0;
  445. }
  446. $date=str2time($date, 'UTC');
  447. debug("found ctime ".localtime($date)." for $file");
  448. return $date;
  449. } #}}}
  450. 1
  451. # default mergerc content
  452. __DATA__
  453. function local_execute_redirected(stdin, stdout, stderr, path, ...)
  454. local pid
  455. local ret = -1
  456. io.flush();
  457. pid = spawn_redirected(stdin, stdout, stderr, path, unpack(arg))
  458. if (pid ~= -1) then ret, pid = wait(pid) end
  459. return ret
  460. end
  461. if (not execute_redirected) then -- use standard function if available
  462. execute_redirected = local_execute_redirected
  463. end
  464. if (not mergers.fail) then -- use standard merger if available
  465. mergers.fail = {
  466. cmd = function (tbl) return false end,
  467. available = function () return true end,
  468. wanted = function () return true end
  469. }
  470. end
  471. mergers.diffutils_force = {
  472. cmd = function (tbl)
  473. local ret = execute_redirected(
  474. "",
  475. tbl.outfile,
  476. "",
  477. "diff3",
  478. "--merge",
  479. "--show-overlap",
  480. "--label", string.format("[Yours]", tbl.left_path ),
  481. "--label", string.format("[Original]", tbl.anc_path ),
  482. "--label", string.format("[Theirs]", tbl.right_path),
  483. tbl.lfile,
  484. tbl.afile,
  485. tbl.rfile
  486. )
  487. if (ret > 1) then
  488. io.write(gettext("Error running GNU diffutils 3-way difference tool 'diff3'"))
  489. return false
  490. end
  491. return tbl.outfile
  492. end,
  493. available =
  494. function ()
  495. return program_exists_in_path("diff3");
  496. end,
  497. wanted =
  498. function ()
  499. return true
  500. end
  501. }
  502. EOF