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