summaryrefslogtreecommitdiff
path: root/IkiWiki/Rcs/monotone.pm
blob: 500af5c587abba1816dd3144c840c54e1afad8a2 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki;
  3. use warnings;
  4. use strict;
  5. use IkiWiki;
  6. use Monotone;
  7. use Date::Parse qw(str2time);
  8. use Date::Format qw(time2str);
  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. chdir $config{srcdir}
  18. or error("Cannot chdir to $config{srcdir}: $!");
  19. my $child = open(MTN, "-|");
  20. if (! $child) {
  21. open STDERR, ">/dev/null";
  22. exec("mtn", "version") || error("mtn version failed to run");
  23. }
  24. my $version=undef;
  25. while (<MTN>) {
  26. if (/^monotone (\d+\.\d+) /) {
  27. $version=$1;
  28. }
  29. }
  30. close MTN || debug("mtn version exited $?");
  31. if (!defined($version)) {
  32. error("Cannot determine monotone version");
  33. }
  34. if ($version < 0.38) {
  35. error("Monotone version too old, is $version but required 0.38");
  36. }
  37. } #}}}
  38. sub get_rev () { #{{{
  39. my $sha1 = `mtn --root=$config{mtnrootdir} automate get_base_revision_id`;
  40. ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
  41. if (! $sha1) {
  42. debug("Unable to get base revision for '$config{srcdir}'.")
  43. }
  44. return $sha1;
  45. } #}}}
  46. sub get_rev_auto ($) { #{{{
  47. my $automator=shift;
  48. my @results = $automator->call("get_base_revision_id");
  49. my $sha1 = $results[0];
  50. ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
  51. if (! $sha1) {
  52. debug("Unable to get base revision for '$config{srcdir}'.")
  53. }
  54. return $sha1;
  55. } #}}}
  56. sub mtn_merge ($$$$) { #{{{
  57. my $leftRev=shift;
  58. my $rightRev=shift;
  59. my $branch=shift;
  60. my $author=shift;
  61. my $mergeRev;
  62. my $child = open(MTNMERGE, "-|");
  63. if (! $child) {
  64. open STDERR, ">&STDOUT";
  65. exec("mtn", "--root=$config{mtnrootdir}",
  66. "explicit_merge", $leftRev, $rightRev,
  67. $branch, "--author", $author, "--key",
  68. $config{mtnkey}) || error("mtn merge failed to run");
  69. }
  70. while (<MTNMERGE>) {
  71. if (/^mtn.\s.merged.\s($sha1_pattern)$/) {
  72. $mergeRev=$1;
  73. }
  74. }
  75. close MTNMERGE || return undef;
  76. debug("merged $leftRev, $rightRev to make $mergeRev");
  77. return $mergeRev;
  78. } #}}}
  79. sub commit_file_to_new_rev($$$$$$$$) { #{{{
  80. my $automator=shift;
  81. my $wsfilename=shift;
  82. my $oldFileID=shift;
  83. my $newFileContents=shift;
  84. my $oldrev=shift;
  85. my $branch=shift;
  86. my $author=shift;
  87. my $message=shift;
  88. #store the file
  89. my ($out, $err) = $automator->call("put_file", $oldFileID, $newFileContents);
  90. my ($newFileID) = ($out =~ m/^($sha1_pattern)$/);
  91. error("Failed to store file data for $wsfilename in repository")
  92. if (! defined $newFileID || length $newFileID != 40);
  93. # get the mtn filename rather than the workspace filename
  94. ($out, $err) = $automator->call("get_corresponding_path", $oldrev, $wsfilename, $oldrev);
  95. my ($filename) = ($out =~ m/^file "(.*)"$/);
  96. error("Couldn't find monotone repository path for file $wsfilename") if (! $filename);
  97. debug("Converted ws filename of $wsfilename to repos filename of $filename");
  98. # then stick in a new revision for this file
  99. my $manifest = "format_version \"1\"\n\n".
  100. "new_manifest [0000000000000000000000000000000000000000]\n\n".
  101. "old_revision [$oldrev]\n\n".
  102. "patch \"$filename\"\n".
  103. " from [$oldFileID]\n".
  104. " to [$newFileID]\n";
  105. ($out, $err) = $automator->call("put_revision", $manifest);
  106. my ($newRevID) = ($out =~ m/^($sha1_pattern)$/);
  107. error("Unable to make new monotone repository revision")
  108. if (! defined $newRevID || length $newRevID != 40);
  109. debug("put revision: $newRevID");
  110. # now we need to add certs for this revision...
  111. # author, branch, changelog, date
  112. $automator->call("cert", $newRevID, "author", $author);
  113. $automator->call("cert", $newRevID, "branch", $branch);
  114. $automator->call("cert", $newRevID, "changelog", $message);
  115. $automator->call("cert", $newRevID, "date",
  116. time2str("%Y-%m-%dT%T", time, "UTC"));
  117. debug("Added certs for rev: $newRevID");
  118. return $newRevID;
  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. # see if it will merge cleanly
  231. $ENV{MTN_MERGE}="fail";
  232. my $mergeResult = mtn_merge($newRevID, $rev, $branch, $author);
  233. $ENV{MTN_MERGE}="";
  234. # push any changes so far
  235. if (defined($config{mtnsync}) && $config{mtnsync}) {
  236. if (system("mtn", "--root=$config{mtnrootdir}", "push", "--quiet", "--ticker=none", "--key", $config{mtnkey}) != 0) {
  237. debug("monotone push failed");
  238. }
  239. }
  240. if (defined($mergeResult)) {
  241. # everything is merged - bring outselves up to date
  242. if (system("mtn", "--root=$config{mtnrootdir}",
  243. "update", "-r", $mergeResult) != 0) {
  244. debug("Unable to update to rev $mergeResult after merge on conflicted commit!");
  245. }
  246. }
  247. else {
  248. debug("Auto-merge failed. Using diff-merge to add conflict markers.");
  249. $ENV{MTN_MERGE}="diffutils";
  250. $ENV{MTN_MERGE_DIFFUTILS}="partial=true";
  251. $mergeResult = mtn_merge($newRevID, $rev, $branch, $author);
  252. $ENV{MTN_MERGE}="";
  253. $ENV{MTN_MERGE_DIFFUTILS}="";
  254. if (!defined($mergeResult)) {
  255. debug("Unable to insert conflict markers!");
  256. error("Your commit succeeded. Unfortunately, someone else committed something to the same ".
  257. "part of the wiki at the same time. Both versions are stored in the monotone repository, ".
  258. "but at present the different versions cannot be reconciled through the web interface. ".
  259. "Please use the non-web interface to resolve the conflicts.");
  260. }
  261. if (system("mtn", "--root=$config{mtnrootdir}",
  262. "update", "-r", $mergeResult) != 0) {
  263. debug("Unable to update to rev $mergeResult after conflict-enhanced merge on conflicted commit!");
  264. }
  265. # return "conflict enhanced" file to the user
  266. # for cleanup note, this relies on the fact
  267. # that ikiwiki seems to call rcs_prepedit()
  268. # again after we return
  269. return readfile("$config{srcdir}/$file");
  270. }
  271. return undef;
  272. }
  273. $automator->close();
  274. }
  275. # If we reached here then the file we're looking at hasn't changed
  276. # since $oldrev. Commit it.
  277. if (system("mtn", "--root=$config{mtnrootdir}", "commit", "--quiet",
  278. "--author", $author, "--key", $config{mtnkey}, "-m",
  279. possibly_foolish_untaint($message), $file) != 0) {
  280. debug("Traditional commit failed! Returning data as conflict.");
  281. my $conflict=readfile("$config{srcdir}/$file");
  282. if (system("mtn", "--root=$config{mtnrootdir}", "revert",
  283. "--quiet", $file) != 0) {
  284. debug("monotone revert failed");
  285. }
  286. return $conflict;
  287. }
  288. if (defined($config{mtnsync}) && $config{mtnsync}) {
  289. if (system("mtn", "--root=$config{mtnrootdir}", "push",
  290. "--quiet", "--ticker=none", "--key",
  291. $config{mtnkey}) != 0) {
  292. debug("monotone push failed");
  293. }
  294. }
  295. return undef # success
  296. } #}}}
  297. sub rcs_commit_staged ($$$) {
  298. # Commits all staged changes. Changes can be staged using rcs_add,
  299. # rcs_remove, and rcs_rename.
  300. my ($message, $user, $ipaddr)=@_;
  301. # Note - this will also commit any spurious changes that happen to be
  302. # lying around in the working copy. There shouldn't be any, but...
  303. check_config();
  304. my $author;
  305. if (defined $user) {
  306. $author="Web user: " . $user;
  307. }
  308. elsif (defined $ipaddr) {
  309. $author="Web IP: " . $ipaddr;
  310. }
  311. else {
  312. $author="Web: Anonymous";
  313. }
  314. if (system("mtn", "--root=$config{mtnrootdir}", "commit", "--quiet",
  315. "--author", $author, "--key", $config{mtnkey}, "-m",
  316. possibly_foolish_untaint($message)) != 0) {
  317. error("Monotone commit failed");
  318. }
  319. }
  320. sub rcs_add ($) { #{{{
  321. my $file=shift;
  322. check_config();
  323. if (system("mtn", "--root=$config{mtnrootdir}", "add", "--quiet",
  324. $file) != 0) {
  325. error("Monotone add failed");
  326. }
  327. } #}}}
  328. sub rcs_remove ($) { # {{{
  329. my $file = shift;
  330. check_config();
  331. # Note: it is difficult to undo a remove in Monotone at the moment.
  332. # Until this is fixed, it might be better to make 'rm' move things
  333. # into an attic, rather than actually remove them.
  334. # To resurrect a file, you currently add a new file with the contents
  335. # you want it to have. This loses all connectivity and automated
  336. # merging with the 'pre-delete' versions of the file.
  337. if (system("mtn", "--root=$config{mtnrootdir}", "rm", "--quiet",
  338. $file) != 0) {
  339. error("Monotone remove failed");
  340. }
  341. } #}}}
  342. sub rcs_rename ($$) { # {{{
  343. my ($src, $dest) = @_;
  344. check_config();
  345. if (system("mtn", "--root=$config{mtnrootdir}", "rename", "--quiet",
  346. $src, $dest) != 0) {
  347. error("Monotone rename failed");
  348. }
  349. } #}}}
  350. sub rcs_recentchanges ($) { #{{{
  351. my $num=shift;
  352. my @ret;
  353. check_config();
  354. # use log --brief to get a list of revs, as this
  355. # gives the results in a nice order
  356. # (otherwise we'd have to do our own date sorting)
  357. my @revs;
  358. my $child = open(MTNLOG, "-|");
  359. if (! $child) {
  360. exec("mtn", "log", "--root=$config{mtnrootdir}", "--no-graph",
  361. "--brief") || error("mtn log failed to run");
  362. }
  363. while (($num >= 0) and (my $line = <MTNLOG>)) {
  364. if ($line =~ m/^($sha1_pattern)/) {
  365. push @revs, $1;
  366. $num -= 1;
  367. }
  368. }
  369. close MTNLOG || debug("mtn log exited $?");
  370. my $automator = Monotone->new();
  371. $automator->open(undef, $config{mtnrootdir});
  372. while (@revs != 0) {
  373. my $rev = shift @revs;
  374. # first go through and figure out the messages, etc
  375. my $certs = [read_certs($automator, $rev)];
  376. my $user;
  377. my $when;
  378. my $committype;
  379. my (@pages, @message);
  380. foreach my $cert (@$certs) {
  381. if ($cert->{signature} eq "ok" &&
  382. $cert->{trust} eq "trusted") {
  383. if ($cert->{name} eq "author") {
  384. $user = $cert->{value};
  385. # detect the source of the commit
  386. # from the changelog
  387. if ($cert->{key} eq $config{mtnkey}) {
  388. $committype = "web";
  389. } else {
  390. $committype = "monotone";
  391. }
  392. } elsif ($cert->{name} eq "date") {
  393. $when = str2time($cert->{value}, 'UTC');
  394. } elsif ($cert->{name} eq "changelog") {
  395. my $messageText = $cert->{value};
  396. # split the changelog into multiple
  397. # lines
  398. foreach my $msgline (split(/\n/, $messageText)) {
  399. push @message, { line => $msgline };
  400. }
  401. }
  402. }
  403. }
  404. my @changed_files = get_changed_files($automator, $rev);
  405. my $file;
  406. my ($out, $err) = $automator->call("parents", $rev);
  407. my @parents = ($out =~ m/^($sha1_pattern)$/);
  408. my $parent = $parents[0];
  409. foreach $file (@changed_files) {
  410. next unless length $file;
  411. if (defined $config{diffurl} and (@parents == 1)) {
  412. my $diffurl=$config{diffurl};
  413. $diffurl=~s/\[\[r1\]\]/$parent/g;
  414. $diffurl=~s/\[\[r2\]\]/$rev/g;
  415. $diffurl=~s/\[\[file\]\]/$file/g;
  416. push @pages, {
  417. page => pagename($file),
  418. diffurl => $diffurl,
  419. };
  420. }
  421. else {
  422. push @pages, {
  423. page => pagename($file),
  424. }
  425. }
  426. }
  427. push @ret, {
  428. rev => $rev,
  429. user => $user,
  430. committype => $committype,
  431. when => $when,
  432. message => [@message],
  433. pages => [@pages],
  434. } if @pages;
  435. }
  436. $automator->close();
  437. return @ret;
  438. } #}}}
  439. sub rcs_diff ($) { #{{{
  440. my $rev=shift;
  441. my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
  442. check_config();
  443. my $child = open(MTNDIFF, "-|");
  444. if (! $child) {
  445. exec("mtn", "diff", "--root=$config{mtnrootdir}", "-r", "p:".$sha1, "-r", $sha1) || error("mtn diff $sha1 failed to run");
  446. }
  447. my (@lines) = <MTNDIFF>;
  448. close MTNDIFF || debug("mtn diff $sha1 exited $?");
  449. if (wantarray) {
  450. return @lines;
  451. }
  452. else {
  453. return join("", @lines);
  454. }
  455. } #}}}
  456. sub rcs_getctime ($) { #{{{
  457. my $file=shift;
  458. check_config();
  459. my $child = open(MTNLOG, "-|");
  460. if (! $child) {
  461. exec("mtn", "log", "--root=$config{mtnrootdir}", "--no-graph",
  462. "--brief", $file) || error("mtn log $file failed to run");
  463. }
  464. my $firstRev;
  465. while (<MTNLOG>) {
  466. if (/^($sha1_pattern)/) {
  467. $firstRev=$1;
  468. }
  469. }
  470. close MTNLOG || debug("mtn log $file exited $?");
  471. if (! defined $firstRev) {
  472. debug "failed to parse mtn log for $file";
  473. return 0;
  474. }
  475. my $automator = Monotone->new();
  476. $automator->open(undef, $config{mtnrootdir});
  477. my $certs = [read_certs($automator, $firstRev)];
  478. $automator->close();
  479. my $date;
  480. foreach my $cert (@$certs) {
  481. if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
  482. if ($cert->{name} eq "date") {
  483. $date = $cert->{value};
  484. }
  485. }
  486. }
  487. if (! defined $date) {
  488. debug "failed to find date cert for revision $firstRev when looking for creation time of $file";
  489. return 0;
  490. }
  491. $date=str2time($date, 'UTC');
  492. debug("found ctime ".localtime($date)." for $file");
  493. return $date;
  494. } #}}}
  495. 1