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