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