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