summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/monotone.pm
blob: 40a41c765b7142f5973c4ec63a956c6fd7569494 (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 (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. },
  62. mtn_wrapper => {
  63. type => "string",
  64. example => "/srv/mtn/wiki/_MTN/ikiwiki-netsync-hook",
  65. description => "monotone netsync hook to generate",
  66. safe => 0, # file
  67. rebuild => 0,
  68. },
  69. mtn_wrappermode => {
  70. type => "string",
  71. example => '06755',
  72. description => "mode for mtn_wrapper (can safely be made suid)",
  73. safe => 0,
  74. rebuild => 0,
  75. },
  76. mtnkey => {
  77. type => "string",
  78. example => 'web@example.com',
  79. description => "your monotone key",
  80. safe => 1,
  81. rebuild => 0,
  82. },
  83. historyurl => {
  84. type => "string",
  85. example => "http://viewmtn.example.com/branch/head/filechanges/com.example.branch/[[file]]",
  86. description => "viewmtn url to show file history ([[file]] substituted)",
  87. safe => 1,
  88. rebuild => 1,
  89. },
  90. diffurl => {
  91. type => "string",
  92. example => "http://viewmtn.example.com/revision/diff/[[r1]]/with/[[r2]]/[[file]]",
  93. description => "viewmtn url to show a diff ([[r1]], [[r2]], and [[file]] substituted)",
  94. safe => 1,
  95. rebuild => 1,
  96. },
  97. mtnsync => {
  98. type => "boolean",
  99. example => 0,
  100. description => "sync on update and commit?",
  101. safe => 0, # paranoia
  102. rebuild => 0,
  103. },
  104. mtnrootdir => {
  105. type => "string",
  106. description => "path to your workspace (defaults to the srcdir; specify if the srcdir is a subdirectory of the workspace)",
  107. safe => 0, # path
  108. rebuild => 0,
  109. },
  110. } #}}}
  111. sub get_rev () { #{{{
  112. my $sha1 = `mtn --root=$config{mtnrootdir} automate get_base_revision_id`;
  113. ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
  114. if (! $sha1) {
  115. debug("Unable to get base revision for '$config{srcdir}'.")
  116. }
  117. return $sha1;
  118. } #}}}
  119. sub get_rev_auto ($) { #{{{
  120. my $automator=shift;
  121. my @results = $automator->call("get_base_revision_id");
  122. my $sha1 = $results[0];
  123. ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
  124. if (! $sha1) {
  125. debug("Unable to get base revision for '$config{srcdir}'.")
  126. }
  127. return $sha1;
  128. } #}}}
  129. sub mtn_merge ($$$$) { #{{{
  130. my $leftRev=shift;
  131. my $rightRev=shift;
  132. my $branch=shift;
  133. my $author=shift;
  134. my $mergeRev;
  135. my $child = open(MTNMERGE, "-|");
  136. if (! $child) {
  137. open STDERR, ">&STDOUT";
  138. exec("mtn", "--root=$config{mtnrootdir}",
  139. "explicit_merge", $leftRev, $rightRev,
  140. $branch, "--author", $author, "--key",
  141. $config{mtnkey}) || error("mtn merge failed to run");
  142. }
  143. while (<MTNMERGE>) {
  144. if (/^mtn.\s.merged.\s($sha1_pattern)$/) {
  145. $mergeRev=$1;
  146. }
  147. }
  148. close MTNMERGE || return undef;
  149. debug("merged $leftRev, $rightRev to make $mergeRev");
  150. return $mergeRev;
  151. } #}}}
  152. sub commit_file_to_new_rev ($$$$$$$$) { #{{{
  153. my $automator=shift;
  154. my $wsfilename=shift;
  155. my $oldFileID=shift;
  156. my $newFileContents=shift;
  157. my $oldrev=shift;
  158. my $branch=shift;
  159. my $author=shift;
  160. my $message=shift;
  161. #store the file
  162. my ($out, $err) = $automator->call("put_file", $oldFileID, $newFileContents);
  163. my ($newFileID) = ($out =~ m/^($sha1_pattern)$/);
  164. error("Failed to store file data for $wsfilename in repository")
  165. if (! defined $newFileID || length $newFileID != 40);
  166. # get the mtn filename rather than the workspace filename
  167. ($out, $err) = $automator->call("get_corresponding_path", $oldrev, $wsfilename, $oldrev);
  168. my ($filename) = ($out =~ m/^file "(.*)"$/);
  169. error("Couldn't find monotone repository path for file $wsfilename") if (! $filename);
  170. debug("Converted ws filename of $wsfilename to repos filename of $filename");
  171. # then stick in a new revision for this file
  172. my $manifest = "format_version \"1\"\n\n".
  173. "new_manifest [0000000000000000000000000000000000000000]\n\n".
  174. "old_revision [$oldrev]\n\n".
  175. "patch \"$filename\"\n".
  176. " from [$oldFileID]\n".
  177. " to [$newFileID]\n";
  178. ($out, $err) = $automator->call("put_revision", $manifest);
  179. my ($newRevID) = ($out =~ m/^($sha1_pattern)$/);
  180. error("Unable to make new monotone repository revision")
  181. if (! defined $newRevID || length $newRevID != 40);
  182. debug("put revision: $newRevID");
  183. # now we need to add certs for this revision...
  184. # author, branch, changelog, date
  185. $automator->call("cert", $newRevID, "author", $author);
  186. $automator->call("cert", $newRevID, "branch", $branch);
  187. $automator->call("cert", $newRevID, "changelog", $message);
  188. $automator->call("cert", $newRevID, "date",
  189. time2str("%Y-%m-%dT%T", time, "UTC"));
  190. debug("Added certs for rev: $newRevID");
  191. return $newRevID;
  192. } #}}}
  193. sub read_certs ($$) { #{{{
  194. my $automator=shift;
  195. my $rev=shift;
  196. my @results = $automator->call("certs", $rev);
  197. my @ret;
  198. my $line = $results[0];
  199. 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) {
  200. push @ret, {
  201. key => $1,
  202. signature => $2,
  203. name => $3,
  204. value => $4,
  205. trust => $5,
  206. };
  207. }
  208. return @ret;
  209. } #}}}
  210. sub get_changed_files ($$) { #{{{
  211. my $automator=shift;
  212. my $rev=shift;
  213. my @results = $automator->call("get_revision", $rev);
  214. my $changes=$results[0];
  215. my @ret;
  216. my %seen = ();
  217. while ($changes =~ m/\s*(add_file|patch|delete|rename)\s"(.*?)(?<!\\)"\n/sg) {
  218. my $file = $2;
  219. # don't add the same file multiple times
  220. if (! $seen{$file}) {
  221. push @ret, $file;
  222. $seen{$file} = 1;
  223. }
  224. }
  225. return @ret;
  226. } #}}}
  227. sub rcs_update () { #{{{
  228. chdir $config{srcdir}
  229. or error("Cannot chdir to $config{srcdir}: $!");
  230. if (defined($config{mtnsync}) && $config{mtnsync}) {
  231. if (system("mtn", "--root=$config{mtnrootdir}", "sync",
  232. "--quiet", "--ticker=none",
  233. "--key", $config{mtnkey}) != 0) {
  234. debug("monotone sync failed before update");
  235. }
  236. }
  237. if (system("mtn", "--root=$config{mtnrootdir}", "update", "--quiet") != 0) {
  238. debug("monotone update failed");
  239. }
  240. } #}}}
  241. sub rcs_prepedit ($) { #{{{
  242. my $file=shift;
  243. chdir $config{srcdir}
  244. or error("Cannot chdir to $config{srcdir}: $!");
  245. # For monotone, return the revision of the file when
  246. # editing begins.
  247. return get_rev();
  248. } #}}}
  249. sub rcs_commit ($$$;$$) { #{{{
  250. # Tries to commit the page; returns undef on _success_ and
  251. # a version of the page with the rcs's conflict markers on failure.
  252. # The file is relative to the srcdir.
  253. my $file=shift;
  254. my $message=shift;
  255. my $rcstoken=shift;
  256. my $user=shift;
  257. my $ipaddr=shift;
  258. my $author;
  259. if (defined $user) {
  260. $author="Web user: " . $user;
  261. }
  262. elsif (defined $ipaddr) {
  263. $author="Web IP: " . $ipaddr;
  264. }
  265. else {
  266. $author="Web: Anonymous";
  267. }
  268. chdir $config{srcdir}
  269. or error("Cannot chdir to $config{srcdir}: $!");
  270. my ($oldrev)= $rcstoken=~ m/^($sha1_pattern)$/; # untaint
  271. my $rev = get_rev();
  272. if (defined $rev && defined $oldrev && $rev ne $oldrev) {
  273. my $automator = Monotone->new();
  274. $automator->open_args("--root", $config{mtnrootdir}, "--key", $config{mtnkey});
  275. # Something has been committed, has this file changed?
  276. my ($out, $err);
  277. $automator->setOpts("r", $oldrev, "r", $rev);
  278. ($out, $err) = $automator->call("content_diff", $file);
  279. debug("Problem committing $file") if ($err ne "");
  280. my $diff = $out;
  281. if ($diff) {
  282. # Commit a revision with just this file changed off
  283. # the old revision.
  284. #
  285. # first get the contents
  286. debug("File changed: forming branch");
  287. my $newfile=readfile("$config{srcdir}/$file");
  288. # then get the old content ID from the diff
  289. if ($diff !~ m/^---\s$file\s+($sha1_pattern)$/m) {
  290. error("Unable to find previous file ID for $file");
  291. }
  292. my $oldFileID = $1;
  293. # get the branch we're working in
  294. ($out, $err) = $automator->call("get_option", "branch");
  295. chomp $out;
  296. error("Illegal branch name in monotone workspace") if ($out !~ m/^([-\@\w\.]+)$/);
  297. my $branch = $1;
  298. # then put the new content into the DB (and record the new content ID)
  299. my $newRevID = commit_file_to_new_rev($automator, $file, $oldFileID, $newfile, $oldrev, $branch, $author, $message);
  300. $automator->close();
  301. # if we made it to here then the file has been committed... revert the local copy
  302. if (system("mtn", "--root=$config{mtnrootdir}", "revert", $file) != 0) {
  303. debug("Unable to revert $file after merge on conflicted commit!");
  304. }
  305. debug("Divergence created! Attempting auto-merge.");
  306. # see if it will merge cleanly
  307. $ENV{MTN_MERGE}="fail";
  308. my $mergeResult = mtn_merge($newRevID, $rev, $branch, $author);
  309. $ENV{MTN_MERGE}="";
  310. # push any changes so far
  311. if (defined($config{mtnsync}) && $config{mtnsync}) {
  312. if (system("mtn", "--root=$config{mtnrootdir}", "push", "--quiet", "--ticker=none", "--key", $config{mtnkey}) != 0) {
  313. debug("monotone push failed");
  314. }
  315. }
  316. if (defined($mergeResult)) {
  317. # everything is merged - bring outselves up to date
  318. if (system("mtn", "--root=$config{mtnrootdir}",
  319. "update", "-r", $mergeResult) != 0) {
  320. debug("Unable to update to rev $mergeResult after merge on conflicted commit!");
  321. }
  322. }
  323. else {
  324. debug("Auto-merge failed. Using diff-merge to add conflict markers.");
  325. $ENV{MTN_MERGE}="diffutils";
  326. $ENV{MTN_MERGE_DIFFUTILS}="partial=true";
  327. $mergeResult = mtn_merge($newRevID, $rev, $branch, $author);
  328. $ENV{MTN_MERGE}="";
  329. $ENV{MTN_MERGE_DIFFUTILS}="";
  330. if (!defined($mergeResult)) {
  331. debug("Unable to insert conflict markers!");
  332. error("Your commit succeeded. Unfortunately, someone else committed something to the same ".
  333. "part of the wiki at the same time. Both versions are stored in the monotone repository, ".
  334. "but at present the different versions cannot be reconciled through the web interface. ".
  335. "Please use the non-web interface to resolve the conflicts.");
  336. }
  337. if (system("mtn", "--root=$config{mtnrootdir}",
  338. "update", "-r", $mergeResult) != 0) {
  339. debug("Unable to update to rev $mergeResult after conflict-enhanced merge on conflicted commit!");
  340. }
  341. # return "conflict enhanced" file to the user
  342. # for cleanup note, this relies on the fact
  343. # that ikiwiki seems to call rcs_prepedit()
  344. # again after we return
  345. return readfile("$config{srcdir}/$file");
  346. }
  347. return undef;
  348. }
  349. $automator->close();
  350. }
  351. # If we reached here then the file we're looking at hasn't changed
  352. # since $oldrev. Commit it.
  353. if (system("mtn", "--root=$config{mtnrootdir}", "commit", "--quiet",
  354. "--author", $author, "--key", $config{mtnkey}, "-m",
  355. IkiWiki::possibly_foolish_untaint($message), $file) != 0) {
  356. debug("Traditional commit failed! Returning data as conflict.");
  357. my $conflict=readfile("$config{srcdir}/$file");
  358. if (system("mtn", "--root=$config{mtnrootdir}", "revert",
  359. "--quiet", $file) != 0) {
  360. debug("monotone revert failed");
  361. }
  362. return $conflict;
  363. }
  364. if (defined($config{mtnsync}) && $config{mtnsync}) {
  365. if (system("mtn", "--root=$config{mtnrootdir}", "push",
  366. "--quiet", "--ticker=none", "--key",
  367. $config{mtnkey}) != 0) {
  368. debug("monotone push failed");
  369. }
  370. }
  371. return undef # success
  372. } #}}}
  373. sub rcs_commit_staged ($$$) {
  374. # Commits all staged changes. Changes can be staged using rcs_add,
  375. # rcs_remove, and rcs_rename.
  376. my ($message, $user, $ipaddr)=@_;
  377. # Note - this will also commit any spurious changes that happen to be
  378. # lying around in the working copy. There shouldn't be any, but...
  379. chdir $config{srcdir}
  380. or error("Cannot chdir to $config{srcdir}: $!");
  381. my $author;
  382. if (defined $user) {
  383. $author="Web user: " . $user;
  384. }
  385. elsif (defined $ipaddr) {
  386. $author="Web IP: " . $ipaddr;
  387. }
  388. else {
  389. $author="Web: Anonymous";
  390. }
  391. if (system("mtn", "--root=$config{mtnrootdir}", "commit", "--quiet",
  392. "--author", $author, "--key", $config{mtnkey}, "-m",
  393. IkiWiki::possibly_foolish_untaint($message)) != 0) {
  394. error("Monotone commit failed");
  395. }
  396. }
  397. sub rcs_add ($) { #{{{
  398. my $file=shift;
  399. chdir $config{srcdir}
  400. or error("Cannot chdir to $config{srcdir}: $!");
  401. if (system("mtn", "--root=$config{mtnrootdir}", "add", "--quiet",
  402. $file) != 0) {
  403. error("Monotone add failed");
  404. }
  405. } #}}}
  406. sub rcs_remove ($) { # {{{
  407. my $file = shift;
  408. chdir $config{srcdir}
  409. or error("Cannot chdir to $config{srcdir}: $!");
  410. # Note: it is difficult to undo a remove in Monotone at the moment.
  411. # Until this is fixed, it might be better to make 'rm' move things
  412. # into an attic, rather than actually remove them.
  413. # To resurrect a file, you currently add a new file with the contents
  414. # you want it to have. This loses all connectivity and automated
  415. # merging with the 'pre-delete' versions of the file.
  416. if (system("mtn", "--root=$config{mtnrootdir}", "rm", "--quiet",
  417. $file) != 0) {
  418. error("Monotone remove failed");
  419. }
  420. } #}}}
  421. sub rcs_rename ($$) { # {{{
  422. my ($src, $dest) = @_;
  423. chdir $config{srcdir}
  424. or error("Cannot chdir to $config{srcdir}: $!");
  425. if (system("mtn", "--root=$config{mtnrootdir}", "rename", "--quiet",
  426. $src, $dest) != 0) {
  427. error("Monotone rename failed");
  428. }
  429. } #}}}
  430. sub rcs_recentchanges ($) { #{{{
  431. my $num=shift;
  432. my @ret;
  433. chdir $config{srcdir}
  434. or error("Cannot chdir to $config{srcdir}: $!");
  435. # use log --brief to get a list of revs, as this
  436. # gives the results in a nice order
  437. # (otherwise we'd have to do our own date sorting)
  438. my @revs;
  439. my $child = open(MTNLOG, "-|");
  440. if (! $child) {
  441. exec("mtn", "log", "--root=$config{mtnrootdir}", "--no-graph",
  442. "--brief") || error("mtn log failed to run");
  443. }
  444. while (($num >= 0) and (my $line = <MTNLOG>)) {
  445. if ($line =~ m/^($sha1_pattern)/) {
  446. push @revs, $1;
  447. $num -= 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. } else {
  471. $committype = "monotone";
  472. }
  473. } elsif ($cert->{name} eq "date") {
  474. $when = str2time($cert->{value}, 'UTC');
  475. } elsif ($cert->{name} eq "changelog") {
  476. my $messageText = $cert->{value};
  477. # split the changelog into multiple
  478. # lines
  479. foreach my $msgline (split(/\n/, $messageText)) {
  480. push @message, { line => $msgline };
  481. }
  482. }
  483. }
  484. }
  485. my @changed_files = get_changed_files($automator, $rev);
  486. my $file;
  487. my ($out, $err) = $automator->call("parents", $rev);
  488. my @parents = ($out =~ m/^($sha1_pattern)$/);
  489. my $parent = $parents[0];
  490. foreach $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