summaryrefslogtreecommitdiff
path: root/IkiWiki/Rcs/git.pm
blob: 3fedd64f189fd6c4b20a617a14b41076744fcbe5 (plain)
  1. #!/usr/bin/perl
  2. # Git backend for IkiWiki.
  3. # Copyright 2006 Recai Oktaş <roktas@debian.org>
  4. #
  5. # Licensed under the same terms as IkiWiki.
  6. use warnings;
  7. use strict;
  8. use IkiWiki;
  9. package IkiWiki;
  10. my $origin_branch = 'origin'; # Git ref for main repository
  11. my $master_branch = 'master'; # working branch
  12. my $sha1_pattern = qr/[0-9a-fA-F]{40}/; # pattern to validate Git sha1sums
  13. my $dummy_commit_msg = 'dummy commit'; # message to skip in recent changes
  14. my $web_commit_msg = qr/^web commit by (\w+):?(.*)/; # pattern for web commits
  15. sub _safe_git (&@) { #{{{
  16. # Start a child process safely without resorting /bin/sh.
  17. # Return command output or success state (in scalar context).
  18. my ($error_handler, @cmdline) = @_;
  19. my $pid = open my $OUT, "-|";
  20. error("Cannot fork: $!") if !defined $pid;
  21. if (!$pid) {
  22. # In child.
  23. open STDERR, ">&STDOUT"
  24. or error("Cannot dup STDOUT: $!");
  25. # Git commands want to be in wc.
  26. chdir $config{srcdir}
  27. or error("Cannot chdir to $config{srcdir}: $!");
  28. exec @cmdline or error("Cannot exec '@cmdline': $!");
  29. }
  30. # In parent.
  31. my @lines;
  32. while (<$OUT>) {
  33. chomp;
  34. push @lines, $_;
  35. }
  36. close $OUT;
  37. ($error_handler || sub { })->("'@cmdline' failed: $!") if $?;
  38. return wantarray ? @lines : ($? == 0);
  39. }
  40. # Convenient wrappers.
  41. sub run_or_die ($@) { _safe_git(\&IkiWiki::error, @_) }
  42. sub run_or_cry ($@) { _safe_git(sub { warn @_ }, @_) }
  43. sub run_or_non ($@) { _safe_git(undef, @_) }
  44. #}}}
  45. sub _merge_past ($$$) { #{{{
  46. # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
  47. # Git merge commands work with the committed changes, except in the
  48. # implicit case of '-m' of git-checkout(1). So we should invent a
  49. # kludge here. In principle, we need to create a throw-away branch
  50. # in preparing for the merge itself. Since branches are cheap (and
  51. # branching is fast), this shouldn't cost high.
  52. #
  53. # The main problem is the presence of _uncommitted_ local changes. One
  54. # possible approach to get rid of this situation could be that we first
  55. # make a temporary commit in the master branch and later restore the
  56. # initial state (this is possible since Git has the ability to undo a
  57. # commit, i.e. 'git-reset --soft HEAD^'). The method can be summarized
  58. # as follows:
  59. #
  60. # - create a diff of HEAD:current-sha1
  61. # - dummy commit
  62. # - create a dummy branch and switch to it
  63. # - rewind to past (reset --hard to the current-sha1)
  64. # - apply the diff and commit
  65. # - switch to master and do the merge with the dummy branch
  66. # - make a soft reset (undo the last commit of master)
  67. #
  68. # The above method has some drawbacks: (1) it needs a redundant commit
  69. # just to get rid of local changes, (2) somewhat slow because of the
  70. # required system forks. Until someone points a more straight method
  71. # (which I would be grateful) I have implemented an alternative method.
  72. # In this approach, we hide all the modified files from Git by renaming
  73. # them (using the 'rename' builtin) and later restore those files in
  74. # the throw-away branch (that is, we put the files themselves instead
  75. # of applying a patch).
  76. my ($sha1, $file, $message) = @_;
  77. my @undo; # undo stack for cleanup in case of an error
  78. my $conflict; # file content with conflict markers
  79. eval {
  80. # Hide local changes from Git by renaming the modified file.
  81. # Relative paths must be converted to absolute for renaming.
  82. my ($target, $hidden) = (
  83. "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
  84. );
  85. rename($target, $hidden)
  86. or error("rename '$target' to '$hidden' failed: $!");
  87. # Ensure to restore the renamed file on error.
  88. push @undo, sub {
  89. return if ! -e "$hidden"; # already renamed
  90. rename($hidden, $target)
  91. or warn "rename '$hidden' to '$target' failed: $!";
  92. };
  93. my $branch = "throw_away_${sha1}"; # supposed to be unique
  94. # Create a throw-away branch and rewind backward.
  95. push @undo, sub { run_or_cry('git-branch', '-D', $branch) };
  96. run_or_die('git-branch', $branch, $sha1);
  97. # Switch to throw-away branch for the merge operation.
  98. push @undo, sub {
  99. if (!run_or_cry('git-checkout', $master_branch)) {
  100. run_or_cry('git-checkout','-f',$master_branch);
  101. }
  102. };
  103. run_or_die('git-checkout', $branch);
  104. # Put the modified file in _this_ branch.
  105. rename($hidden, $target)
  106. or error("rename '$hidden' to '$target' failed: $!");
  107. # _Silently_ commit all modifications in the current branch.
  108. run_or_non('git-commit', '-m', $message, '-a');
  109. # ... and re-switch to master.
  110. run_or_die('git-checkout', $master_branch);
  111. # Attempt to merge without complaining.
  112. if (!run_or_non('git-pull', '--no-commit', '.', $branch)) {
  113. $conflict = readfile($target);
  114. run_or_die('git-reset', '--hard');
  115. }
  116. };
  117. my $failure = $@;
  118. # Process undo stack (in reverse order). By policy cleanup
  119. # actions should normally print a warning on failure.
  120. while (my $handle = pop @undo) {
  121. $handle->();
  122. }
  123. error("Git merge failed!\n$failure\n") if $failure;
  124. return $conflict;
  125. } #}}}
  126. sub _parse_diff_tree (@) { #{{{
  127. # Parse the raw diff tree chunk and return the info hash.
  128. # See git-diff-tree(1) for the syntax.
  129. my ($dt_ref) = @_;
  130. # End of stream?
  131. return if !defined @{ $dt_ref } || !length @{ $dt_ref }[0];
  132. my %ci;
  133. # Header line.
  134. HEADER: while (my $line = shift @{ $dt_ref }) {
  135. return if $line !~ m/^diff-tree ($sha1_pattern)/;
  136. my $sha1 = $1;
  137. $ci{'sha1'} = $sha1;
  138. last HEADER;
  139. }
  140. # Identification lines for the commit.
  141. IDENT: while (my $line = shift @{ $dt_ref }) {
  142. # Regexps are semi-stolen from gitweb.cgi.
  143. if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
  144. $ci{'tree'} = $1;
  145. } elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
  146. # XXX: collecting in reverse order
  147. push @{ $ci{'parents'} }, $1;
  148. } elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
  149. my ($who, $name, $epoch, $tz) =
  150. ($1, $2, $3, $4 );
  151. $ci{ $who } = $name;
  152. $ci{ "${who}_epoch" } = $epoch;
  153. $ci{ "${who}_tz" } = $tz;
  154. if ($name =~ m/^([^<]+) <([^@]+)/) {
  155. my ($fullname, $username) = ($1, $2);
  156. $ci{"${who}_fullname"} = $fullname;
  157. $ci{"${who}_username"} = $username;
  158. } else {
  159. $ci{"${who}_fullname"} =
  160. $ci{"${who}_username"} = $name;
  161. }
  162. } elsif ($line =~ m/^$/) {
  163. # Trailing empty line signals next section.
  164. last IDENT;
  165. }
  166. }
  167. error("No 'tree' or 'parents' seen in diff-tree output")
  168. if !defined $ci{'tree'} || !defined $ci{'parents'};
  169. $ci{'parent'} = @{ $ci{'parents'} }[0];
  170. # Commit message.
  171. COMMENT: while (my $line = shift @{ $dt_ref }) {
  172. if ($line =~ m/^$/) {
  173. # Trailing empty line signals next section.
  174. last COMMENT;
  175. };
  176. $line =~ s/^ //;
  177. push @{ $ci{'comment'} }, $line;
  178. }
  179. # Modified files.
  180. FILE: while (my $line = shift @{ $dt_ref }) {
  181. if ($line =~ m{^:
  182. ([0-7]{6})[ ] # from mode
  183. ([0-7]{6})[ ] # to mode
  184. ($sha1_pattern)[ ] # from sha1
  185. ($sha1_pattern)[ ] # to sha1
  186. (.) # status
  187. ([0-9]{0,3})\t # similarity
  188. (.*) # file
  189. $}xo) {
  190. my ($sha1_from, $sha1_to, $file) =
  191. ($3, $4, $7 );
  192. if ($file =~ m/^"(.*)"$/) {
  193. ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
  194. }
  195. if (length $file) {
  196. push @{ $ci{'details'} }, {
  197. 'file' => $file,
  198. 'sha1_from' => $sha1_from,
  199. 'sha1_to' => $sha1_to,
  200. };
  201. }
  202. next FILE;
  203. };
  204. last FILE;
  205. }
  206. warn "No detail in diff-tree output" if !defined $ci{'details'};
  207. return \%ci;
  208. } #}}}
  209. sub git_commit_info (;$$) { #{{{
  210. # Return an array of commit info hashes of num commits (default: 1)
  211. # starting from the given sha1sum (default: HEAD).
  212. my ($sha1, $num) = @_;
  213. $num ||= 1;
  214. my @raw_lines =
  215. run_or_die(qq{git-rev-list --max-count=$num $sha1 |
  216. git-diff-tree --stdin --pretty=raw -M -r});
  217. my @ci;
  218. while (my $parsed = _parse_diff_tree(\@raw_lines)) {
  219. push @ci, $parsed;
  220. }
  221. return wantarray ? @ci : $ci[0];
  222. } #}}}
  223. sub git_sha1 (;$) { #{{{
  224. # Return head sha1sum (of given file).
  225. my $file = shift || q{--};
  226. # Ignore error since a non-existing file might be given.
  227. my ($sha1) = run_or_non('git-rev-list', '--max-count=1', 'HEAD', $file);
  228. if ($sha1) {
  229. ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
  230. } else { debug("Empty sha1sum for '$file'.") }
  231. return defined $sha1 ? $sha1 : q{};
  232. } #}}}
  233. sub rcs_update () { #{{{
  234. # Update working directory.
  235. run_or_cry('git-pull', $origin_branch);
  236. } #}}}
  237. sub rcs_prepedit ($) { #{{{
  238. # Return the commit sha1sum of the file when editing begins.
  239. # This will be later used in rcs_commit if a merge is required.
  240. my ($file) = @_;
  241. return git_sha1($file);
  242. } #}}}
  243. sub rcs_commit ($$$) { #{{{
  244. # Try to commit the page; returns undef on _success_ and
  245. # a version of the page with the rcs's conflict markers on
  246. # failure.
  247. my ($file, $message, $rcstoken) = @_;
  248. # XXX: Wiki directory is in the unlocked state when starting this
  249. # action. But it takes time for a Git process to finish its job
  250. # (especially if a merge required), so we must re-lock to prevent
  251. # race conditions. Only when the time of the real commit action
  252. # (i.e. git-push(1)) comes, we'll unlock the directory.
  253. lockwiki();
  254. # Check to see if the page has been changed by someone else since
  255. # rcs_prepedit was called.
  256. my $cur = git_sha1($file);
  257. my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
  258. if (defined $cur && defined $prev && $cur ne $prev) {
  259. my $conflict = _merge_past($prev, $file, $dummy_commit_msg);
  260. return $conflict if defined $conflict;
  261. }
  262. # git-commit(1) returns non-zero if file has not been really changed.
  263. # so we should ignore its exit status (hence run_or_non).
  264. $message = possibly_foolish_untaint($message);
  265. if (run_or_non('git-commit', '-m', $message, '-i', $file)) {
  266. unlockwiki();
  267. run_or_cry('git-push', $origin_branch);
  268. }
  269. return undef; # success
  270. } #}}}
  271. sub rcs_add ($) { # {{{
  272. # Add file to archive.
  273. my ($file) = @_;
  274. run_or_cry('git-add', $file);
  275. } #}}}
  276. sub rcs_recentchanges ($) { #{{{
  277. # List of recent changes.
  278. my ($num) = @_;
  279. eval q{use CGI 'escapeHTML'};
  280. eval q{use Date::Parse};
  281. eval q{use Time::Duration};
  282. my ($sha1, $type, $when, $diffurl, $user, @pages, @message, @rets);
  283. INFO: foreach my $ci (git_commit_info('HEAD', $num)) {
  284. my $title = @{ $ci->{'comment'} }[0];
  285. # Skip redundant commits.
  286. next INFO if ($title eq $dummy_commit_msg);
  287. $sha1 = $ci->{'sha1'};
  288. $type = "web";
  289. $when = concise(ago(time - $ci->{'author_epoch'}));
  290. foreach my $bit (@{ $ci->{'details'} }) {
  291. my $diffurl = $config{'diffurl'};
  292. my $file = $bit->{'file'};
  293. $diffurl =~ s/\[\[file\]\]/$file/go;
  294. $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
  295. $diffurl =~ s/\[\[sha1_from\]\]/$bit->{'sha1_from'}/go;
  296. $diffurl =~ s/\[\[sha1_to\]\]/$bit->{'sha1_to'}/go;
  297. push @pages, {
  298. link => htmllink("", "", pagename($file), 1),
  299. diffurl => $diffurl,
  300. },
  301. }
  302. push @message, { line => escapeHTML($title) };
  303. if (defined $message[0] &&
  304. $message[0]->{line} =~ m/$web_commit_msg/) {
  305. $user = "$1";
  306. $message[0]->{line} = $2;
  307. } else {
  308. $type ="git";
  309. $user = $ci->{'author_username'};
  310. }
  311. push @rets, {
  312. rev => $sha1,
  313. user => htmllink("", "", $user, 1),
  314. committype => $type,
  315. when => $when,
  316. message => [@message],
  317. pages => [@pages],
  318. } if @pages;
  319. $sha1 = $type = $when = $diffurl = $user = undef;
  320. @pages = @message = ();
  321. }
  322. return @rets;
  323. } #}}}
  324. sub rcs_notify () { #{{{
  325. # Send notification mail to subscribed users.
  326. #
  327. # In usual Git usage, hooks/update script is presumed to send
  328. # notification mails (see git-receive-pack(1)). But we prefer
  329. # hooks/post-update to support IkiWiki commits coming from a
  330. # cloned repository (through command line) because post-update
  331. # is called _after_ each ref in repository is updated (update
  332. # hook is called _before_ the repository is updated). Since
  333. # post-update hook does not accept command line arguments, we
  334. # don't have an $ENV variable in this function.
  335. #
  336. # Here, we rely on a simple fact: we can extract all parts of the
  337. # notification content by parsing the "HEAD" commit (which also
  338. # triggers a refresh of IkiWiki pages) and we can obtain the diff
  339. # by comparing HEAD and HEAD^ (the previous commit).
  340. my $sha1 = 'HEAD'; # the commit which triggers this action
  341. my $ci = git_commit_info($sha1);
  342. if (!defined $ci) {
  343. warn "Cannot parse info for '$sha1' commit";
  344. return;
  345. }
  346. my @changed_pages = map { $_->{'file'} } @{ $ci->{'details'} };
  347. my ($user, $message);
  348. if (@{ $ci->{'comment'} }[0] =~ m/$web_commit_msg/) {
  349. $user = "$1";
  350. $message = $2;
  351. } else {
  352. $user = $ci->{'author_username'};
  353. $message = join "\n", @{ $ci->{'comment'} };
  354. }
  355. require IkiWiki::UserInfo;
  356. my @email_recipients = commit_notify_list($user, @changed_pages);
  357. return if !@email_recipients;
  358. # TODO: if a commit spans multiple pages, this will send
  359. # subscribers a diff that might contain pages they did not
  360. # sign up for. Should separate the diff per page and
  361. # reassemble into one mail with just the pages subscribed to.
  362. my $diff = join "\n", run_or_die('git-diff', "${sha1}^", $sha1);
  363. my $subject = "$config{wikiname} update of ";
  364. if (@changed_pages > 2) {
  365. $subject .= "$changed_pages[0] $changed_pages[1] etc";
  366. } else {
  367. $subject .= join " ", @changed_pages;
  368. }
  369. $subject .= " by $user";
  370. my $template = HTML::Template->new(
  371. filename => "$config{templatedir}/notifymail.tmpl"
  372. );
  373. $template->param(
  374. wikiname => $config{wikiname},
  375. diff => $diff,
  376. user => $user,
  377. message => $message,
  378. );
  379. eval q{use Mail::Sendmail};
  380. foreach my $email (@email_recipients) {
  381. sendmail(
  382. To => $email,
  383. From => "$config{wikiname} <$config{adminemail}>",
  384. Subject => $subject,
  385. Message => $template->output,
  386. ) or error("Failed to send update notification mail: $!");
  387. }
  388. } #}}}
  389. sub rcs_getctime ($) { #{{{
  390. # Get the ctime of file.
  391. my ($file) = @_;
  392. my $sha1 = git_sha1($file);
  393. my $ci = git_commit_info($sha1);
  394. my $ctime = $ci->{'author_epoch'};
  395. debug("ctime for '$file': ". localtime($ctime) . "\n");
  396. return $ctime;
  397. } #}}}
  398. 1