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