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