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