summaryrefslogtreecommitdiff
path: root/IkiWiki/Rcs/monotone.pm
blob: be6b36c66e4816f67875d51caba86f49f3582bd3 (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. #my ($out, $err) = $automator->call("content_diff", $file);
  198. #debug("Problem committing $file") if ($err ne "");
  199. # FIXME: use of $file in these backticks is not wise from a
  200. # security POV. Probably safe, but should be avoided
  201. # anyway.
  202. my $diff = `mtn --root=$config{mtnrootdir} au content_diff -r $oldrev -r $rev $file`; # was just $out;
  203. if ($diff) {
  204. # Commit a revision with just this file changed off
  205. # the old revision.
  206. #
  207. # first get the contents
  208. debug("File changed: forming branch");
  209. my $newfile=readfile("$config{srcdir}/$file");
  210. # then get the old content ID from the diff
  211. if ($diff !~ m/^---\s$file\s+($sha1_pattern)$/m) {
  212. error("Unable to find previous file ID for $file");
  213. }
  214. my $oldFileID = $1;
  215. # get the branch we're working in
  216. ($out, $err) = $automator->call("get_option", "branch");
  217. chomp $out;
  218. error("Illegal branch name in monotone workspace") if ($out !~ m/^([-\@\w\.]+)$/);
  219. my $branch = $1;
  220. # then put the new content into the DB (and record the new content ID)
  221. my $newRevID = commit_file_to_new_rev($automator, $file, $oldFileID, $newfile, $oldrev, $branch, $author, $message);
  222. $automator->close();
  223. # if we made it to here then the file has been committed... revert the local copy
  224. if (system("mtn", "--root=$config{mtnrootdir}", "revert", $file) != 0) {
  225. debug("Unable to revert $file after merge on conflicted commit!");
  226. }
  227. debug("Divergence created! Attempting auto-merge.");
  228. check_mergerc();
  229. # see if it will merge cleanly
  230. $ENV{MTN_MERGE}="fail";
  231. my $mergeResult = mtn_merge($newRevID, $rev, $branch, $author);
  232. $ENV{MTN_MERGE}="";
  233. # push any changes so far
  234. if (defined($config{mtnsync}) && $config{mtnsync}) {
  235. if (system("mtn", "--root=$config{mtnrootdir}", "push", "--quiet", "--ticker=none", "--key", $config{mtnkey}) != 0) {
  236. debug("monotone push failed");
  237. }
  238. }
  239. if (defined($mergeResult)) {
  240. # everything is merged - bring outselves up to date
  241. if (system("mtn", "--root=$config{mtnrootdir}",
  242. "update", "-r", $mergeResult) != 0) {
  243. debug("Unable to update to rev $mergeResult after merge on conflicted commit!");
  244. }
  245. }
  246. else {
  247. debug("Auto-merge failed. Using diff-merge to add conflict markers.");
  248. $ENV{MTN_MERGE}="diffutils_force";
  249. $mergeResult = mtn_merge($newRevID, $rev, $branch, $author);
  250. $ENV{MTN_MERGE}="";
  251. if (!defined($mergeResult)) {
  252. debug("Unable to insert conflict markers!");
  253. error("Your commit succeeded. Unfortunately, someone else committed something to the same ".
  254. "part of the wiki at the same time. Both versions are stored in the monotone repository, ".
  255. "but at present the different versions cannot be reconciled through the web interface. ".
  256. "Please use the non-web interface to resolve the conflicts.");
  257. }
  258. # suspend this revision because it has
  259. # conflict markers...
  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}", "sync",
  289. "--quiet", "--ticker=none", "--key",
  290. $config{mtnkey}) != 0) {
  291. debug("monotone sync 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. "$config{srcdir}/$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 = time - 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. foreach $file (@changed_files) {
  361. push @pages, {
  362. page => pagename($file),
  363. } if length $file;
  364. }
  365. push @ret, {
  366. rev => $rev,
  367. user => $user,
  368. committype => $committype,
  369. when => $when,
  370. message => [@message],
  371. pages => [@pages],
  372. } if @pages;
  373. }
  374. $automator->close();
  375. return @ret;
  376. } #}}}
  377. sub rcs_notify () { #{{{
  378. debug("The monotone rcs_notify function is currently untested. Use at own risk!");
  379. if (! exists $ENV{REV}) {
  380. error(gettext("REV is not set, not running from mtn post-commit hook, cannot send notifications"));
  381. }
  382. if ($ENV{REV} !~ m/($sha1_pattern)/) { # sha1 is untainted now
  383. error(gettext("REV is not a valid revision identifier, cannot send notifications"));
  384. }
  385. my $rev = $1;
  386. check_config();
  387. my $automator = Monotone->new();
  388. $automator->open(undef, $config{mtnrootdir});
  389. my $certs = [read_certs($automator, $rev)];
  390. my $user;
  391. my $message;
  392. my $when;
  393. foreach my $cert (@$certs) {
  394. if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
  395. if ($cert->{name} eq "author") {
  396. $user = $cert->{value};
  397. } elsif ($cert->{name} eq "date") {
  398. $when = $cert->{value};
  399. } elsif ($cert->{name} eq "changelog") {
  400. $message = $cert->{value};
  401. }
  402. }
  403. }
  404. my @changed_pages = get_changed_files($automator, $rev);
  405. $automator->close();
  406. require IkiWiki::UserInfo;
  407. send_commit_mails(
  408. sub {
  409. return $message;
  410. },
  411. sub {
  412. `mtn --root=$config{mtnrootdir} au content_diff -r $rev`;
  413. },
  414. $user, @changed_pages);
  415. } #}}}
  416. sub rcs_getctime ($) { #{{{
  417. my $file=shift;
  418. check_config();
  419. my $child = open(MTNLOG, "-|");
  420. if (! $child) {
  421. exec("mtn", "log", "--root=$config{mtnrootdir}", "--no-graph",
  422. "--brief", $file) || error("mtn log $file failed to run");
  423. }
  424. my $firstRev;
  425. while (<MTNLOG>) {
  426. if (/^($sha1_pattern)/) {
  427. $firstRev=$1;
  428. }
  429. }
  430. close MTNLOG || debug("mtn log $file exited $?");
  431. if (! defined $firstRev) {
  432. debug "failed to parse mtn log for $file";
  433. return 0;
  434. }
  435. my $automator = Monotone->new();
  436. $automator->open(undef, $config{mtnrootdir});
  437. my $certs = [read_certs($automator, $firstRev)];
  438. $automator->close();
  439. my $date;
  440. foreach my $cert (@$certs) {
  441. if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
  442. if ($cert->{name} eq "date") {
  443. $date = $cert->{value};
  444. }
  445. }
  446. }
  447. if (! defined $date) {
  448. debug "failed to find date cert for revision $firstRev when looking for creation time of $file";
  449. return 0;
  450. }
  451. $date=str2time($date, 'UTC');
  452. debug("found ctime ".localtime($date)." for $file");
  453. return $date;
  454. } #}}}
  455. 1
  456. # default mergerc content
  457. __DATA__
  458. function local_execute_redirected(stdin, stdout, stderr, path, ...)
  459. local pid
  460. local ret = -1
  461. io.flush();
  462. pid = spawn_redirected(stdin, stdout, stderr, path, unpack(arg))
  463. if (pid ~= -1) then ret, pid = wait(pid) end
  464. return ret
  465. end
  466. if (not execute_redirected) then -- use standard function if available
  467. execute_redirected = local_execute_redirected
  468. end
  469. if (not mergers.fail) then -- use standard merger if available
  470. mergers.fail = {
  471. cmd = function (tbl) return false end,
  472. available = function () return true end,
  473. wanted = function () return true end
  474. }
  475. end
  476. mergers.diffutils_force = {
  477. cmd = function (tbl)
  478. local ret = execute_redirected(
  479. "",
  480. tbl.outfile,
  481. "",
  482. "diff3",
  483. "--merge",
  484. "--show-overlap",
  485. "--label", string.format("[Yours]", tbl.left_path ),
  486. "--label", string.format("[Original]", tbl.anc_path ),
  487. "--label", string.format("[Theirs]", tbl.right_path),
  488. tbl.lfile,
  489. tbl.afile,
  490. tbl.rfile
  491. )
  492. if (ret > 1) then
  493. io.write(gettext("Error running GNU diffutils 3-way difference tool 'diff3'"))
  494. return false
  495. end
  496. return tbl.outfile
  497. end,
  498. available =
  499. function ()
  500. return program_exists_in_path("diff3");
  501. end,
  502. wanted =
  503. function ()
  504. return true
  505. end
  506. }
  507. EOF