summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/monotone.pm
blob: c33cf7e3a0dad0c0f052400c00da2b928f8fd289 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki::Plugin::monotone;
  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 import {
  11. hook(type => "checkconfig", id => "monotone", call => \&checkconfig);
  12. hook(type => "getsetup", id => "monotone", call => \&getsetup);
  13. hook(type => "rcs", id => "rcs_update", call => \&rcs_update);
  14. hook(type => "rcs", id => "rcs_prepedit", call => \&rcs_prepedit);
  15. hook(type => "rcs", id => "rcs_commit", call => \&rcs_commit);
  16. hook(type => "rcs", id => "rcs_commit_staged", call => \&rcs_commit_staged);
  17. hook(type => "rcs", id => "rcs_add", call => \&rcs_add);
  18. hook(type => "rcs", id => "rcs_remove", call => \&rcs_remove);
  19. hook(type => "rcs", id => "rcs_rename", call => \&rcs_rename);
  20. hook(type => "rcs", id => "rcs_recentchanges", call => \&rcs_recentchanges);
  21. hook(type => "rcs", id => "rcs_diff", call => \&rcs_diff);
  22. hook(type => "rcs", id => "rcs_getctime", call => \&rcs_getctime);
  23. }
  24. sub checkconfig () {
  25. if (!defined($config{mtnrootdir})) {
  26. $config{mtnrootdir} = $config{srcdir};
  27. }
  28. if (! -d "$config{mtnrootdir}/_MTN") {
  29. error("Ikiwiki srcdir does not seem to be a Monotone workspace (or set the mtnrootdir)!");
  30. }
  31. my $child = open(MTN, "-|");
  32. if (! $child) {
  33. open STDERR, ">/dev/null";
  34. exec("mtn", "version") || error("mtn version failed to run");
  35. }
  36. my $version=undef;
  37. while (<MTN>) {
  38. if (/^monotone (\d+\.\d+) /) {
  39. $version=$1;
  40. }
  41. }
  42. close MTN || debug("mtn version exited $?");
  43. if (!defined($version)) {
  44. error("Cannot determine monotone version");
  45. }
  46. if ($version < 0.38) {
  47. error("Monotone version too old, is $version but required 0.38");
  48. }
  49. if (defined $config{mtn_wrapper} && length $config{mtn_wrapper}) {
  50. push @{$config{wrappers}}, {
  51. wrapper => $config{mtn_wrapper},
  52. wrappermode => (defined $config{mtn_wrappermode} ? $config{mtn_wrappermode} : "06755"),
  53. };
  54. }
  55. }
  56. sub getsetup () {
  57. return
  58. plugin => {
  59. safe => 0, # rcs plugin
  60. rebuild => undef,
  61. section => "rcs",
  62. },
  63. mtn_wrapper => {
  64. type => "string",
  65. example => "/srv/mtn/wiki/_MTN/ikiwiki-netsync-hook",
  66. description => "monotone netsync hook to generate",
  67. safe => 0, # file
  68. rebuild => 0,
  69. },
  70. mtn_wrappermode => {
  71. type => "string",
  72. example => '06755',
  73. description => "mode for mtn_wrapper (can safely be made suid)",
  74. safe => 0,
  75. rebuild => 0,
  76. },
  77. mtnkey => {
  78. type => "string",
  79. example => 'web@example.com',
  80. description => "your monotone key",
  81. safe => 1,
  82. rebuild => 0,
  83. },
  84. historyurl => {
  85. type => "string",
  86. example => "http://viewmtn.example.com/branch/head/filechanges/com.example.branch/[[file]]",
  87. description => "viewmtn url to show file history ([[file]] substituted)",
  88. safe => 1,
  89. rebuild => 1,
  90. },
  91. diffurl => {
  92. type => "string",
  93. example => "http://viewmtn.example.com/revision/diff/[[r1]]/with/[[r2]]/[[file]]",
  94. description => "viewmtn url to show a diff ([[r1]], [[r2]], and [[file]] substituted)",
  95. safe => 1,
  96. rebuild => 1,
  97. },
  98. mtnsync => {
  99. type => "boolean",
  100. example => 0,
  101. description => "sync on update and commit?",
  102. safe => 0, # paranoia
  103. rebuild => 0,
  104. },
  105. mtnrootdir => {
  106. type => "string",
  107. description => "path to your workspace (defaults to the srcdir; specify if the srcdir is a subdirectory of the workspace)",
  108. safe => 0, # path
  109. rebuild => 0,
  110. },
  111. }
  112. sub get_rev () {
  113. my $sha1 = `mtn --root=$config{mtnrootdir} automate get_base_revision_id`;
  114. ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
  115. if (! $sha1) {
  116. debug("Unable to get base revision for '$config{srcdir}'.")
  117. }
  118. return $sha1;
  119. }
  120. sub get_rev_auto ($) {
  121. my $automator=shift;
  122. my @results = $automator->call("get_base_revision_id");
  123. my $sha1 = $results[0];
  124. ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
  125. if (! $sha1) {
  126. debug("Unable to get base revision for '$config{srcdir}'.")
  127. }
  128. return $sha1;
  129. }
  130. sub mtn_merge ($$$$) {
  131. my $leftRev=shift;
  132. my $rightRev=shift;
  133. my $branch=shift;
  134. my $author=shift;
  135. my $mergeRev;
  136. my $child = open(MTNMERGE, "-|");
  137. if (! $child) {
  138. open STDERR, ">&STDOUT";
  139. exec("mtn", "--root=$config{mtnrootdir}",
  140. "explicit_merge", $leftRev, $rightRev,
  141. $branch, "--author", $author, "--key",
  142. $config{mtnkey}) || error("mtn merge failed to run");
  143. }
  144. while (<MTNMERGE>) {
  145. if (/^mtn.\s.merged.\s($sha1_pattern)$/) {
  146. $mergeRev=$1;
  147. }
  148. }
  149. close MTNMERGE || return undef;
  150. debug("merged $leftRev, $rightRev to make $mergeRev");
  151. return $mergeRev;
  152. }
  153. sub commit_file_to_new_rev ($$$$$$$$) {
  154. my $automator=shift;
  155. my $wsfilename=shift;
  156. my $oldFileID=shift;
  157. my $newFileContents=shift;
  158. my $oldrev=shift;
  159. my $branch=shift;
  160. my $author=shift;
  161. my $message=shift;
  162. #store the file
  163. my ($out, $err) = $automator->call("put_file", $oldFileID, $newFileContents);
  164. my ($newFileID) = ($out =~ m/^($sha1_pattern)$/);
  165. error("Failed to store file data for $wsfilename in repository")
  166. if (! defined $newFileID || length $newFileID != 40);
  167. # get the mtn filename rather than the workspace filename
  168. ($out, $err) = $automator->call("get_corresponding_path", $oldrev, $wsfilename, $oldrev);
  169. my ($filename) = ($out =~ m/^file "(.*)"$/);
  170. error("Couldn't find monotone repository path for file $wsfilename") if (! $filename);
  171. debug("Converted ws filename of $wsfilename to repos filename of $filename");
  172. # then stick in a new revision for this file
  173. my $manifest = "format_version \"1\"\n\n".
  174. "new_manifest [0000000000000000000000000000000000000000]\n\n".
  175. "old_revision [$oldrev]\n\n".
  176. "patch \"$filename\"\n".
  177. " from [$oldFileID]\n".
  178. " to [$newFileID]\n";
  179. ($out, $err) = $automator->call("put_revision", $manifest);
  180. my ($newRevID) = ($out =~ m/^($sha1_pattern)$/);
  181. error("Unable to make new monotone repository revision")
  182. if (! defined $newRevID || length $newRevID != 40);
  183. debug("put revision: $newRevID");
  184. # now we need to add certs for this revision...
  185. # author, branch, changelog, date
  186. $automator->call("cert", $newRevID, "author", $author);
  187. $automator->call("cert", $newRevID, "branch", $branch);
  188. $automator->call("cert", $newRevID, "changelog", $message);
  189. $automator->call("cert", $newRevID, "date",
  190. time2str("%Y-%m-%dT%T", time, "UTC"));
  191. debug("Added certs for rev: $newRevID");
  192. return $newRevID;
  193. }
  194. sub read_certs ($$) {
  195. my $automator=shift;
  196. my $rev=shift;
  197. my @results = $automator->call("certs", $rev);
  198. my @ret;
  199. my $line = $results[0];
  200. 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) {
  201. push @ret, {
  202. key => $1,
  203. signature => $2,
  204. name => $3,
  205. value => $4,
  206. trust => $5,
  207. };
  208. }
  209. return @ret;
  210. }
  211. sub get_changed_files ($$) {
  212. my $automator=shift;
  213. my $rev=shift;
  214. my @results = $automator->call("get_revision", $rev);
  215. my $changes=$results[0];
  216. my @ret;
  217. my %seen = ();
  218. while ($changes =~ m/\s*(add_file|patch|delete|rename)\s"(.*?)(?<!\\)"\n/sg) {
  219. my $file = $2;
  220. # don't add the same file multiple times
  221. if (! $seen{$file}) {
  222. push @ret, $file;
  223. $seen{$file} = 1;
  224. }
  225. }
  226. return @ret;
  227. }
  228. sub rcs_update () {
  229. chdir $config{srcdir}
  230. or error("Cannot chdir to $config{srcdir}: $!");
  231. if (defined($config{mtnsync}) && $config{mtnsync}) {
  232. if (system("mtn", "--root=$config{mtnrootdir}", "sync",
  233. "--quiet", "--ticker=none",
  234. "--key", $config{mtnkey}) != 0) {
  235. debug("monotone sync failed before update");
  236. }
  237. }
  238. if (system("mtn", "--root=$config{mtnrootdir}", "update", "--quiet") != 0) {
  239. debug("monotone update failed");
  240. }
  241. }
  242. sub rcs_prepedit ($) {
  243. my $file=shift;
  244. chdir $config{srcdir}
  245. or error("Cannot chdir to $config{srcdir}: $!");
  246. # For monotone, return the revision of the file when
  247. # editing begins.
  248. return get_rev();
  249. }
  250. sub rcs_commit ($$$;$$) {
  251. # Tries to commit the page; returns undef on _success_ and
  252. # a version of the page with the rcs's conflict markers on failure.
  253. # The file is relative to the srcdir.
  254. my $file=shift;
  255. my $message=shift;
  256. my $rcstoken=shift;
  257. my $user=shift;
  258. my $ipaddr=shift;
  259. my $author;
  260. if (defined $user) {
  261. $author="Web user: " . $user;
  262. }
  263. elsif (defined $ipaddr) {
  264. $author="Web IP: " . $ipaddr;
  265. }
  266. else {
  267. $author="Web: Anonymous";
  268. }
  269. chdir $config{srcdir}
  270. or error("Cannot chdir to $config{srcdir}: $!");
  271. my ($oldrev)= $rcstoken=~ m/^($sha1_pattern)$/; # untaint
  272. my $rev = get_rev();
  273. if (defined $rev && defined $oldrev && $rev ne $oldrev) {
  274. my $automator = Monotone->new();
  275. $automator->open_args("--root", $config{mtnrootdir}, "--key", $config{mtnkey});
  276. # Something has been committed, has this file changed?
  277. my ($out, $err);
  278. $automator->setOpts("r", $oldrev, "r", $rev);
  279. ($out, $err) = $automator->call("content_diff", $file);
  280. debug("Problem committing $file") if ($err ne "");
  281. my $diff = $out;
  282. if ($diff) {
  283. # Commit a revision with just this file changed off
  284. # the old revision.
  285. #
  286. # first get the contents
  287. debug("File changed: forming branch");
  288. my $newfile=readfile("$config{srcdir}/$file");
  289. # then get the old content ID from the diff
  290. if ($diff !~ m/^---\s$file\s+($sha1_pattern)$/m) {
  291. error("Unable to find previous file ID for $file");
  292. }
  293. my $oldFileID = $1;
  294. # get the branch we're working in
  295. ($out, $err) = $automator->call("get_option", "branch");
  296. chomp $out;
  297. error("Illegal branch name in monotone workspace") if ($out !~ m/^([-\@\w\.]+)$/);
  298. my $branch = $1;
  299. # then put the new content into the DB (and record the new content ID)
  300. my $newRevID = commit_file_to_new_rev($automator, $file, $oldFileID, $newfile, $oldrev, $branch, $author, $message);
  301. $automator->close();
  302. # if we made it to here then the file has been committed... revert the local copy
  303. if (system("mtn", "--root=$config{mtnrootdir}", "revert", $file) != 0) {
  304. debug("Unable to revert $file after merge on conflicted commit!");
  305. }
  306. debug("Divergence created! Attempting auto-merge.");
  307. # see if it will merge cleanly
  308. $ENV{MTN_MERGE}="fail";
  309. my $mergeResult = mtn_merge($newRevID, $rev, $branch, $author);
  310. $ENV{MTN_MERGE}="";
  311. # push any changes so far
  312. if (defined($config{mtnsync}) && $config{mtnsync}) {
  313. if (system("mtn", "--root=$config{mtnrootdir}", "push", "--quiet", "--ticker=none", "--key", $config{mtnkey}) != 0) {
  314. debug("monotone push failed");
  315. }
  316. }
  317. if (defined($mergeResult)) {
  318. # everything is merged - bring outselves up to date
  319. if (system("mtn", "--root=$config{mtnrootdir}",
  320. "update", "-r", $mergeResult) != 0) {
  321. debug("Unable to update to rev $mergeResult after merge on conflicted commit!");
  322. }
  323. }
  324. else {
  325. debug("Auto-merge failed. Using diff-merge to add conflict markers.");
  326. $ENV{MTN_MERGE}="diffutils";
  327. $ENV{MTN_MERGE_DIFFUTILS}="partial=true";
  328. $mergeResult = mtn_merge($newRevID, $rev, $branch, $author);
  329. $ENV{MTN_MERGE}="";
  330. $ENV{MTN_MERGE_DIFFUTILS}="";
  331. if (!defined($mergeResult)) {
  332. debug("Unable to insert conflict markers!");
  333. error("Your commit succeeded. Unfortunately, someone else committed something to the same ".
  334. "part of the wiki at the same time. Both versions are stored in the monotone repository, ".
  335. "but at present the different versions cannot be reconciled through the web interface. ".
  336. "Please use the non-web interface to resolve the conflicts.");
  337. }
  338. if (system("mtn", "--root=$config{mtnrootdir}",
  339. "update", "-r", $mergeResult) != 0) {
  340. debug("Unable to update to rev $mergeResult after conflict-enhanced merge on conflicted commit!");
  341. }
  342. # return "conflict enhanced" file to the user
  343. # for cleanup note, this relies on the fact
  344. # that ikiwiki seems to call rcs_prepedit()
  345. # again after we return
  346. return readfile("$config{srcdir}/$file");
  347. }
  348. return undef;
  349. }
  350. $automator->close();
  351. }
  352. # If we reached here then the file we're looking at hasn't changed
  353. # since $oldrev. Commit it.
  354. if (system("mtn", "--root=$config{mtnrootdir}", "commit", "--quiet",
  355. "--author", $author, "--key", $config{mtnkey}, "-m",
  356. IkiWiki::possibly_foolish_untaint($message), $file) != 0) {
  357. debug("Traditional commit failed! Returning data as conflict.");
  358. my $conflict=readfile("$config{srcdir}/$file");
  359. if (system("mtn", "--root=$config{mtnrootdir}", "revert",
  360. "--quiet", $file) != 0) {
  361. debug("monotone revert failed");
  362. }
  363. return $conflict;
  364. }
  365. if (defined($config{mtnsync}) && $config{mtnsync}) {
  366. if (system("mtn", "--root=$config{mtnrootdir}", "push",
  367. "--quiet", "--ticker=none", "--key",
  368. $config{mtnkey}) != 0) {
  369. debug("monotone push failed");
  370. }
  371. }
  372. return undef # success
  373. }
  374. sub rcs_commit_staged ($$$) {
  375. # Commits all staged changes. Changes can be staged using rcs_add,
  376. # rcs_remove, and rcs_rename.
  377. my ($message, $user, $ipaddr)=@_;
  378. # Note - this will also commit any spurious changes that happen to be
  379. # lying around in the working copy. There shouldn't be any, but...
  380. chdir $config{srcdir}
  381. or error("Cannot chdir to $config{srcdir}: $!");
  382. my $author;
  383. if (defined $user) {
  384. $author="Web user: " . $user;
  385. }
  386. elsif (defined $ipaddr) {
  387. $author="Web IP: " . $ipaddr;
  388. }
  389. else {
  390. $author="Web: Anonymous";
  391. }
  392. if (system("mtn", "--root=$config{mtnrootdir}", "commit", "--quiet",
  393. "--author", $author, "--key", $config{mtnkey}, "-m",
  394. IkiWiki::possibly_foolish_untaint($message)) != 0) {
  395. error("Monotone commit failed");
  396. }
  397. }
  398. sub rcs_add ($) {
  399. my $file=shift;
  400. chdir $config{srcdir}
  401. or error("Cannot chdir to $config{srcdir}: $!");
  402. if (system("mtn", "--root=$config{mtnrootdir}", "add", "--quiet",
  403. $file) != 0) {
  404. error("Monotone add failed");
  405. }
  406. }
  407. sub rcs_remove ($) {
  408. my $file = shift;
  409. chdir $config{srcdir}
  410. or error("Cannot chdir to $config{srcdir}: $!");
  411. # Note: it is difficult to undo a remove in Monotone at the moment.
  412. # Until this is fixed, it might be better to make 'rm' move things
  413. # into an attic, rather than actually remove them.
  414. # To resurrect a file, you currently add a new file with the contents
  415. # you want it to have. This loses all connectivity and automated
  416. # merging with the 'pre-delete' versions of the file.
  417. if (system("mtn", "--root=$config{mtnrootdir}", "rm", "--quiet",
  418. $file) != 0) {
  419. error("Monotone remove failed");
  420. }
  421. }
  422. sub rcs_rename ($$) {
  423. my ($src, $dest) = @_;
  424. chdir $config{srcdir}
  425. or error("Cannot chdir to $config{srcdir}: $!");
  426. if (system("mtn", "--root=$config{mtnrootdir}", "rename", "--quiet",
  427. $src, $dest) != 0) {
  428. error("Monotone rename failed");
  429. }
  430. }
  431. sub rcs_recentchanges ($) {
  432. my $num=shift;
  433. my @ret;
  434. chdir $config{srcdir}
  435. or error("Cannot chdir to $config{srcdir}: $!");
  436. # use log --brief to get a list of revs, as this
  437. # gives the results in a nice order
  438. # (otherwise we'd have to do our own date sorting)
  439. my @revs;
  440. my $child = open(MTNLOG, "-|");
  441. if (! $child) {
  442. exec("mtn", "log", "--root=$config{mtnrootdir}", "--no-graph",
  443. "--brief", "--last=$num") || error("mtn log failed to run");
  444. }
  445. while (my $line = <MTNLOG>) {
  446. if ($line =~ m/^($sha1_pattern)/) {
  447. push @revs, $1;
  448. }
  449. }
  450. close MTNLOG || debug("mtn log exited $?");
  451. my $automator = Monotone->new();
  452. $automator->open(undef, $config{mtnrootdir});
  453. while (@revs != 0) {
  454. my $rev = shift @revs;
  455. # first go through and figure out the messages, etc
  456. my $certs = [read_certs($automator, $rev)];
  457. my $user;
  458. my $when;
  459. my $committype;
  460. my (@pages, @message);
  461. foreach my $cert (@$certs) {
  462. if ($cert->{signature} eq "ok" &&
  463. $cert->{trust} eq "trusted") {
  464. if ($cert->{name} eq "author") {
  465. $user = $cert->{value};
  466. # detect the source of the commit
  467. # from the changelog
  468. if ($cert->{key} eq $config{mtnkey}) {
  469. $committype = "web";
  470. }
  471. else {
  472. $committype = "mtn";
  473. }
  474. } elsif ($cert->{name} eq "date") {
  475. $when = str2time($cert->{value}, 'UTC');
  476. } elsif ($cert->{name} eq "changelog") {
  477. my $messageText = $cert->{value};
  478. # split the changelog into multiple
  479. # lines
  480. foreach my $msgline (split(/\n/, $messageText)) {
  481. push @message, { line => $msgline };
  482. }
  483. }
  484. }
  485. }
  486. my @changed_files = get_changed_files($automator, $rev);
  487. my ($out, $err) = $automator->call("parents", $rev);
  488. my @parents = ($out =~ m/^($sha1_pattern)$/);
  489. my $parent = $parents[0];
  490. foreach my $file (@changed_files) {
  491. next unless length $file;
  492. if (defined $config{diffurl} and (@parents == 1)) {
  493. my $diffurl=$config{diffurl};
  494. $diffurl=~s/\[\[r1\]\]/$parent/g;
  495. $diffurl=~s/\[\[r2\]\]/$rev/g;
  496. $diffurl=~s/\[\[file\]\]/$file/g;
  497. push @pages, {
  498. page => pagename($file),
  499. diffurl => $diffurl,
  500. };
  501. }
  502. else {
  503. push @pages, {
  504. page => pagename($file),
  505. }
  506. }
  507. }
  508. push @ret, {
  509. rev => $rev,
  510. user => $user,
  511. committype => $committype,
  512. when => $when,
  513. message => [@message],
  514. pages => [@pages],
  515. } if @pages;
  516. }
  517. $automator->close();
  518. return @ret;
  519. }
  520. sub rcs_diff ($) {
  521. my $rev=shift;
  522. my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
  523. chdir $config{srcdir}
  524. or error("Cannot chdir to $config{srcdir}: $!");
  525. my $child = open(MTNDIFF, "-|");
  526. if (! $child) {
  527. exec("mtn", "diff", "--root=$config{mtnrootdir}", "-r", "p:".$sha1, "-r", $sha1) || error("mtn diff $sha1 failed to run");
  528. }
  529. my (@lines) = <MTNDIFF>;
  530. close MTNDIFF || debug("mtn diff $sha1 exited $?");
  531. if (wantarray) {
  532. return @lines;
  533. }
  534. else {
  535. return join("", @lines);
  536. }
  537. }
  538. sub rcs_getctime ($) {
  539. my $file=shift;
  540. chdir $config{srcdir}
  541. or error("Cannot chdir to $config{srcdir}: $!");
  542. my $child = open(MTNLOG, "-|");
  543. if (! $child) {
  544. exec("mtn", "log", "--root=$config{mtnrootdir}", "--no-graph",
  545. "--brief", $file) || error("mtn log $file failed to run");
  546. }
  547. my $firstRev;
  548. while (<MTNLOG>) {
  549. if (/^($sha1_pattern)/) {
  550. $firstRev=$1;
  551. }
  552. }
  553. close MTNLOG || debug("mtn log $file exited $?");
  554. if (! defined $firstRev) {
  555. debug "failed to parse mtn log for $file";
  556. return 0;
  557. }
  558. my $automator = Monotone->new();
  559. $automator->open(undef, $config{mtnrootdir});
  560. my $certs = [read_certs($automator, $firstRev)];
  561. $automator->close();
  562. my $date;
  563. foreach my $cert (@$certs) {
  564. if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
  565. if ($cert->{name} eq "date") {
  566. $date = $cert->{value};
  567. }
  568. }
  569. }
  570. if (! defined $date) {
  571. debug "failed to find date cert for revision $firstRev when looking for creation time of $file";
  572. return 0;
  573. }
  574. $date=str2time($date, 'UTC');
  575. debug("found ctime ".localtime($date)." for $file");
  576. return $date;
  577. }
  578. 1