summaryrefslogtreecommitdiff
path: root/IkiWiki/Rcs/monotone.pm
blob: 6931fd36b4159a32bf97ad417a3c549872fc9716 (plain)
  1. #!/usr/bin/perl
  2. use warnings;
  3. use strict;
  4. use IkiWiki;
  5. use Monotone;
  6. use Date::Parse qw(str2time);
  7. use Date::Format qw(time2str);
  8. package IkiWiki;
  9. my $sha1_pattern = qr/[0-9a-fA-F]{40}/; # pattern to validate sha1sums
  10. sub check_config() { #{{{
  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. chdir $config{srcdir}
  18. or error("Cannot chdir to $config{srcdir}: $!");
  19. my $child = open(MTN, "-|");
  20. if (! $child) {
  21. open STDERR, ">/dev/null";
  22. exec("mtn", "version") || error("mtn version failed to run");
  23. }
  24. my $version=undef;
  25. while (<MTN>) {
  26. if (/^monotone (\d+\.\d+) /) {
  27. $version=$1;
  28. }
  29. }
  30. close MTN || debug("mtn version exited $?");
  31. if (!defined($version)) {
  32. error("Cannot determine monotone version");
  33. }
  34. if ($version < 0.38) {
  35. error("Monotone version too old, is $version but required 0.38");
  36. }
  37. } #}}}
  38. sub get_rev () { #{{{
  39. my $sha1 = `mtn --root=$config{mtnrootdir} automate get_base_revision_id`;
  40. ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
  41. if (! $sha1) {
  42. debug("Unable to get base revision for '$config{srcdir}'.")
  43. }
  44. return $sha1;
  45. } #}}}
  46. sub get_rev_auto ($) { #{{{
  47. my $automator=shift;
  48. my @results = $automator->call("get_base_revision_id");
  49. my $sha1 = $results[0];
  50. ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
  51. if (! $sha1) {
  52. debug("Unable to get base revision for '$config{srcdir}'.")
  53. }
  54. return $sha1;
  55. } #}}}
  56. sub mtn_merge ($$$$) { #{{{
  57. my $leftRev=shift;
  58. my $rightRev=shift;
  59. my $branch=shift;
  60. my $author=shift;
  61. my $mergeRev;
  62. my $child = open(MTNMERGE, "-|");
  63. if (! $child) {
  64. open STDERR, ">&STDOUT";
  65. exec("mtn", "--root=$config{mtnrootdir}",
  66. "explicit_merge", $leftRev, $rightRev,
  67. $branch, "--author", $author, "--key",
  68. $config{mtnkey}) || error("mtn merge failed to run");
  69. }
  70. while (<MTNMERGE>) {
  71. if (/^mtn.\s.merged.\s($sha1_pattern)$/) {
  72. $mergeRev=$1;
  73. }
  74. }
  75. close MTNMERGE || return undef;
  76. debug("merged $leftRev, $rightRev to make $mergeRev");
  77. return $mergeRev;
  78. } #}}}
  79. sub commit_file_to_new_rev($$$$$$$$) { #{{{
  80. my $automator=shift;
  81. my $wsfilename=shift;
  82. my $oldFileID=shift;
  83. my $newFileContents=shift;
  84. my $oldrev=shift;
  85. my $branch=shift;
  86. my $author=shift;
  87. my $message=shift;
  88. #store the file
  89. my ($out, $err) = $automator->call("put_file", $oldFileID, $newFileContents);
  90. my ($newFileID) = ($out =~ m/^($sha1_pattern)$/);
  91. error("Failed to store file data for $wsfilename in repository")
  92. if (! defined $newFileID || length $newFileID != 40);
  93. # get the mtn filename rather than the workspace filename
  94. ($out, $err) = $automator->call("get_corresponding_path", $oldrev, $wsfilename, $oldrev);
  95. my ($filename) = ($out =~ m/^file "(.*)"$/);
  96. error("Couldn't find monotone repository path for file $wsfilename") if (! $filename);
  97. debug("Converted ws filename of $wsfilename to repos filename of $filename");
  98. # then stick in a new revision for this file
  99. my $manifest = "format_version \"1\"\n\n".
  100. "new_manifest [0000000000000000000000000000000000000000]\n\n".
  101. "old_revision [$oldrev]\n\n".
  102. "patch \"$filename\"\n".
  103. " from [$oldFileID]\n".
  104. " to [$newFileID]\n";
  105. ($out, $err) = $automator->call("put_revision", $manifest);
  106. my ($newRevID) = ($out =~ m/^($sha1_pattern)$/);
  107. error("Unable to make new monotone repository revision")
  108. if (! defined $newRevID || length $newRevID != 40);
  109. debug("put revision: $newRevID");
  110. # now we need to add certs for this revision...
  111. # author, branch, changelog, date
  112. $automator->call("cert", $newRevID, "author", $author);
  113. $automator->call("cert", $newRevID, "branch", $branch);
  114. $automator->call("cert", $newRevID, "changelog", $message);
  115. $automator->call("cert", $newRevID, "date",
  116. time2str("%Y-%m-%dT%T", time, "UTC"));
  117. debug("Added certs for rev: $newRevID");
  118. return $newRevID;
  119. } #}}}
  120. sub read_certs ($$) { #{{{
  121. my $automator=shift;
  122. my $rev=shift;
  123. my @results = $automator->call("certs", $rev);
  124. my @ret;
  125. my $line = $results[0];
  126. 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) {
  127. push @ret, {
  128. key => $1,
  129. signature => $2,
  130. name => $3,
  131. value => $4,
  132. trust => $5,
  133. };
  134. }
  135. return @ret;
  136. } #}}}
  137. sub get_changed_files ($$) { #{{{
  138. my $automator=shift;
  139. my $rev=shift;
  140. my @results = $automator->call("get_revision", $rev);
  141. my $changes=$results[0];
  142. my @ret;
  143. my %seen = ();
  144. while ($changes =~ m/\s*(add_file|patch|delete|rename)\s"(.*?)(?<!\\)"\n/sg) {
  145. my $file = $2;
  146. # don't add the same file multiple times
  147. if (! $seen{$file}) {
  148. push @ret, $file;
  149. $seen{$file} = 1;
  150. }
  151. }
  152. return @ret;
  153. } #}}}
  154. sub rcs_update () { #{{{
  155. check_config();
  156. if (defined($config{mtnsync}) && $config{mtnsync}) {
  157. if (system("mtn", "--root=$config{mtnrootdir}", "sync",
  158. "--quiet", "--ticker=none",
  159. "--key", $config{mtnkey}) != 0) {
  160. debug("monotone sync failed before update");
  161. }
  162. }
  163. if (system("mtn", "--root=$config{mtnrootdir}", "update", "--quiet") != 0) {
  164. debug("monotone update failed");
  165. }
  166. } #}}}
  167. sub rcs_prepedit ($) { #{{{
  168. my $file=shift;
  169. check_config();
  170. # For monotone, return the revision of the file when
  171. # editing begins.
  172. return get_rev();
  173. } #}}}
  174. sub rcs_commit ($$$;$$) { #{{{
  175. # Tries to commit the page; returns undef on _success_ and
  176. # a version of the page with the rcs's conflict markers on failure.
  177. # The file is relative to the srcdir.
  178. my $file=shift;
  179. my $message=shift;
  180. my $rcstoken=shift;
  181. my $user=shift;
  182. my $ipaddr=shift;
  183. my $author;
  184. if (defined $user) {
  185. $author="Web user: " . $user;
  186. }
  187. elsif (defined $ipaddr) {
  188. $author="Web IP: " . $ipaddr;
  189. }
  190. else {
  191. $author="Web: Anonymous";
  192. }
  193. check_config();
  194. my ($oldrev)= $rcstoken=~ m/^($sha1_pattern)$/; # untaint
  195. my $rev = get_rev();
  196. if (defined $rev && defined $oldrev && $rev ne $oldrev) {
  197. my $automator = Monotone->new();
  198. $automator->open_args("--root", $config{mtnrootdir}, "--key", $config{mtnkey});
  199. # Something has been committed, has this file changed?
  200. my ($out, $err);
  201. $automator->setOpts("r", $oldrev, "r", $rev);
  202. ($out, $err) = $automator->call("content_diff", $file);
  203. debug("Problem committing $file") if ($err ne "");
  204. my $diff = $out;
  205. if ($diff) {
  206. # Commit a revision with just this file changed off
  207. # the old revision.
  208. #
  209. # first get the contents
  210. debug("File changed: forming branch");
  211. my $newfile=readfile("$config{srcdir}/$file");
  212. # then get the old content ID from the diff
  213. if ($diff !~ m/^---\s$file\s+($sha1_pattern)$/m) {
  214. error("Unable to find previous file ID for $file");
  215. }
  216. my $oldFileID = $1;
  217. # get the branch we're working in
  218. ($out, $err) = $automator->call("get_option", "branch");
  219. chomp $out;
  220. error("Illegal branch name in monotone workspace") if ($out !~ m/^([-\@\w\.]+)$/);
  221. my $branch = $1;
  222. # then put the new content into the DB (and record the new content ID)
  223. my $newRevID = commit_file_to_new_rev($automator, $file, $oldFileID, $newfile, $oldrev, $branch, $author, $message);
  224. $automator->close();
  225. # if we made it to here then the file has been committed... revert the local copy
  226. if (system("mtn", "--root=$config{mtnrootdir}", "revert", $file) != 0) {
  227. debug("Unable to revert $file after merge on conflicted commit!");
  228. }
  229. debug("Divergence created! Attempting auto-merge.");
  230. # see if it will merge cleanly
  231. $ENV{MTN_MERGE}="fail";
  232. my $mergeResult = mtn_merge($newRevID, $rev, $branch, $author);
  233. $ENV{MTN_MERGE}="";
  234. # push any changes so far
  235. if (defined($config{mtnsync}) && $config{mtnsync}) {
  236. if (system("mtn", "--root=$config{mtnrootdir}", "push", "--quiet", "--ticker=none", "--key", $config{mtnkey}) != 0) {
  237. debug("monotone push failed");
  238. }
  239. }
  240. if (defined($mergeResult)) {
  241. # everything is merged - bring outselves up to date
  242. if (system("mtn", "--root=$config{mtnrootdir}",
  243. "update", "-r", $mergeResult) != 0) {
  244. debug("Unable to update to rev $mergeResult after merge on conflicted commit!");
  245. }
  246. }
  247. else {
  248. debug("Auto-merge failed. Using diff-merge to add conflict markers.");
  249. $ENV{MTN_MERGE}="diffutils";
  250. $ENV{MTN_MERGE_DIFFUTILS}="partial=true";
  251. $mergeResult = mtn_merge($newRevID, $rev, $branch, $author);
  252. $ENV{MTN_MERGE}="";
  253. $ENV{MTN_MERGE_DIFFUTILS}="";
  254. if (!defined($mergeResult)) {
  255. debug("Unable to insert conflict markers!");
  256. error("Your commit succeeded. Unfortunately, someone else committed something to the same ".
  257. "part of the wiki at the same time. Both versions are stored in the monotone repository, ".
  258. "but at present the different versions cannot be reconciled through the web interface. ".
  259. "Please use the non-web interface to resolve the conflicts.");
  260. }
  261. if (system("mtn", "--root=$config{mtnrootdir}",
  262. "update", "-r", $mergeResult) != 0) {
  263. debug("Unable to update to rev $mergeResult after conflict-enhanced merge on conflicted commit!");
  264. }
  265. # return "conflict enhanced" file to the user
  266. # for cleanup note, this relies on the fact
  267. # that ikiwiki seems to call rcs_prepedit()
  268. # again after we return
  269. return readfile("$config{srcdir}/$file");
  270. }
  271. return undef;
  272. }
  273. $automator->close();
  274. }
  275. # If we reached here then the file we're looking at hasn't changed
  276. # since $oldrev. Commit it.
  277. if (system("mtn", "--root=$config{mtnrootdir}", "commit", "--quiet",
  278. "--author", $author, "--key", $config{mtnkey}, "-m",
  279. possibly_foolish_untaint($message), $file) != 0) {
  280. debug("Traditional commit failed! Returning data as conflict.");
  281. my $conflict=readfile("$config{srcdir}/$file");
  282. if (system("mtn", "--root=$config{mtnrootdir}", "revert",
  283. "--quiet", $file) != 0) {
  284. debug("monotone revert failed");
  285. }
  286. return $conflict;
  287. }
  288. if (defined($config{mtnsync}) && $config{mtnsync}) {
  289. if (system("mtn", "--root=$config{mtnrootdir}", "push",
  290. "--quiet", "--ticker=none", "--key",
  291. $config{mtnkey}) != 0) {
  292. debug("monotone push failed");
  293. }
  294. }
  295. return undef # success
  296. } #}}}
  297. sub rcs_add ($) { #{{{
  298. my $file=shift;
  299. check_config();
  300. if (system("mtn", "--root=$config{mtnrootdir}", "add", "--quiet",
  301. $file) != 0) {
  302. error("Monotone add failed");
  303. }
  304. } #}}}
  305. sub rcs_recentchanges ($) { #{{{
  306. my $num=shift;
  307. my @ret;
  308. check_config();
  309. # use log --brief to get a list of revs, as this
  310. # gives the results in a nice order
  311. # (otherwise we'd have to do our own date sorting)
  312. my @revs;
  313. my $child = open(MTNLOG, "-|");
  314. if (! $child) {
  315. exec("mtn", "log", "--root=$config{mtnrootdir}", "--no-graph",
  316. "--brief") || error("mtn log failed to run");
  317. }
  318. while (($num >= 0) and (my $line = <MTNLOG>)) {
  319. if ($line =~ m/^($sha1_pattern)/) {
  320. push @revs, $1;
  321. $num -= 1;
  322. }
  323. }
  324. close MTNLOG || debug("mtn log exited $?");
  325. my $automator = Monotone->new();
  326. $automator->open(undef, $config{mtnrootdir});
  327. while (@revs != 0) {
  328. my $rev = shift @revs;
  329. # first go through and figure out the messages, etc
  330. my $certs = [read_certs($automator, $rev)];
  331. my $user;
  332. my $when;
  333. my $committype;
  334. my (@pages, @message);
  335. foreach my $cert (@$certs) {
  336. if ($cert->{signature} eq "ok" &&
  337. $cert->{trust} eq "trusted") {
  338. if ($cert->{name} eq "author") {
  339. $user = $cert->{value};
  340. # detect the source of the commit
  341. # from the changelog
  342. if ($cert->{key} eq $config{mtnkey}) {
  343. $committype = "web";
  344. } else {
  345. $committype = "monotone";
  346. }
  347. } elsif ($cert->{name} eq "date") {
  348. $when = str2time($cert->{value}, 'UTC');
  349. } elsif ($cert->{name} eq "changelog") {
  350. my $messageText = $cert->{value};
  351. # split the changelog into multiple
  352. # lines
  353. foreach my $msgline (split(/\n/, $messageText)) {
  354. push @message, { line => $msgline };
  355. }
  356. }
  357. }
  358. }
  359. my @changed_files = get_changed_files($automator, $rev);
  360. my $file;
  361. my ($out, $err) = $automator->call("parents", $rev);
  362. my @parents = ($out =~ m/^($sha1_pattern)$/);
  363. my $parent = $parents[0];
  364. foreach $file (@changed_files) {
  365. next unless length $file;
  366. if (defined $config{diffurl} and (@parents == 1)) {
  367. my $diffurl=$config{diffurl};
  368. $diffurl=~s/\[\[r1\]\]/$parent/g;
  369. $diffurl=~s/\[\[r2\]\]/$rev/g;
  370. $diffurl=~s/\[\[file\]\]/$file/g;
  371. push @pages, {
  372. page => pagename($file),
  373. diffurl => $diffurl,
  374. };
  375. }
  376. else {
  377. push @pages, {
  378. page => pagename($file),
  379. }
  380. }
  381. }
  382. push @ret, {
  383. rev => $rev,
  384. user => $user,
  385. committype => $committype,
  386. when => $when,
  387. message => [@message],
  388. pages => [@pages],
  389. } if @pages;
  390. }
  391. $automator->close();
  392. return @ret;
  393. } #}}}
  394. sub rcs_diff ($) { #{{{
  395. # TODO
  396. } #}}}
  397. sub rcs_getctime ($) { #{{{
  398. my $file=shift;
  399. check_config();
  400. my $child = open(MTNLOG, "-|");
  401. if (! $child) {
  402. exec("mtn", "log", "--root=$config{mtnrootdir}", "--no-graph",
  403. "--brief", $file) || error("mtn log $file failed to run");
  404. }
  405. my $firstRev;
  406. while (<MTNLOG>) {
  407. if (/^($sha1_pattern)/) {
  408. $firstRev=$1;
  409. }
  410. }
  411. close MTNLOG || debug("mtn log $file exited $?");
  412. if (! defined $firstRev) {
  413. debug "failed to parse mtn log for $file";
  414. return 0;
  415. }
  416. my $automator = Monotone->new();
  417. $automator->open(undef, $config{mtnrootdir});
  418. my $certs = [read_certs($automator, $firstRev)];
  419. $automator->close();
  420. my $date;
  421. foreach my $cert (@$certs) {
  422. if ($cert->{signature} eq "ok" && $cert->{trust} eq "trusted") {
  423. if ($cert->{name} eq "date") {
  424. $date = $cert->{value};
  425. }
  426. }
  427. }
  428. if (! defined $date) {
  429. debug "failed to find date cert for revision $firstRev when looking for creation time of $file";
  430. return 0;
  431. }
  432. $date=str2time($date, 'UTC');
  433. debug("found ctime ".localtime($date)." for $file");
  434. return $date;
  435. } #}}}
  436. 1