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