summaryrefslogtreecommitdiff
path: root/IkiWiki/Rcs/git.pm
blob: 636eb57f552863bbdc76bebc9c14ad5e25c728e2 (plain)
  1. #!/usr/bin/perl
  2. use warnings;
  3. use strict;
  4. use IkiWiki;
  5. package IkiWiki;
  6. my $origin_branch = 'origin'; # Git ref for main repository
  7. my $master_branch = 'master'; # working branch
  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. my $web_commit_msg = qr/^web commit by (\w+):?(.*)/; # pattern for web commits
  11. sub _safe_git (&@) { #{{{
  12. # Start a child process safely without resorting /bin/sh.
  13. # Return command output or success state (in scalar context).
  14. my ($error_handler, @cmdline) = @_;
  15. my $pid = open my $OUT, "-|";
  16. error("Cannot fork: $!") if !defined $pid;
  17. if (!$pid) {
  18. # In child.
  19. open STDERR, ">&STDOUT"
  20. or error("Cannot dup STDOUT: $!");
  21. # Git commands want to be in wc.
  22. chdir $config{srcdir}
  23. or error("Cannot chdir to $config{srcdir}: $!");
  24. exec @cmdline or error("Cannot exec '@cmdline': $!");
  25. }
  26. # In parent.
  27. my @lines;
  28. while (<$OUT>) {
  29. chomp;
  30. push @lines, $_;
  31. }
  32. close $OUT;
  33. ($error_handler || sub { })->("'@cmdline' failed: $!") if $?;
  34. return wantarray ? @lines : ($? == 0);
  35. }
  36. # Convenient wrappers.
  37. sub run_or_die ($@) { _safe_git(\&IkiWiki::error, @_) }
  38. sub run_or_cry ($@) { _safe_git(sub { warn @_ }, @_) }
  39. sub run_or_non ($@) { _safe_git(undef, @_) }
  40. #}}}
  41. sub _merge_past ($$$) { #{{{
  42. # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
  43. # Git merge commands work with the committed changes, except in the
  44. # implicit case of '-m' of git-checkout(1). So we should invent a
  45. # kludge here. In principle, we need to create a throw-away branch
  46. # in preparing for the merge itself. Since branches are cheap (and
  47. # branching is fast), this shouldn't cost high.
  48. #
  49. # The main problem is the presence of _uncommitted_ local changes. One
  50. # possible approach to get rid of this situation could be that we first
  51. # make a temporary commit in the master branch and later restore the
  52. # initial state (this is possible since Git has the ability to undo a
  53. # commit, i.e. 'git-reset --soft HEAD^'). The method can be summarized
  54. # as follows:
  55. #
  56. # - create a diff of HEAD:current-sha1
  57. # - dummy commit
  58. # - create a dummy branch and switch to it
  59. # - rewind to past (reset --hard to the current-sha1)
  60. # - apply the diff and commit
  61. # - switch to master and do the merge with the dummy branch
  62. # - make a soft reset (undo the last commit of master)
  63. #
  64. # The above method has some drawbacks: (1) it needs a redundant commit
  65. # just to get rid of local changes, (2) somewhat slow because of the
  66. # required system forks. Until someone points a more straight method
  67. # (which I would be grateful) I have implemented an alternative method.
  68. # In this approach, we hide all the modified files from Git by renaming
  69. # them (using the 'rename' builtin) and later restore those files in
  70. # the throw-away branch (that is, we put the files themselves instead
  71. # of applying a patch).
  72. my ($sha1, $file, $message) = @_;
  73. my @undo; # undo stack for cleanup in case of an error
  74. my $conflict; # file content with conflict markers
  75. eval {
  76. # Hide local changes from Git by renaming the modified file.
  77. # Relative paths must be converted to absolute for renaming.
  78. my ($target, $hidden) = (
  79. "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
  80. );
  81. rename($target, $hidden)
  82. or error("rename '$target' to '$hidden' failed: $!");
  83. # Ensure to restore the renamed file on error.
  84. push @undo, sub {
  85. return if ! -e "$hidden"; # already renamed
  86. rename($hidden, $target)
  87. or warn "rename '$hidden' to '$target' failed: $!";
  88. };
  89. my $branch = "throw_away_${sha1}"; # supposed to be unique
  90. # Create a throw-away branch and rewind backward.
  91. push @undo, sub { run_or_cry('git-branch', '-D', $branch) };
  92. run_or_die('git-branch', $branch, $sha1);
  93. # Switch to throw-away branch for the merge operation.
  94. push @undo, sub {
  95. if (!run_or_cry('git-checkout', $master_branch)) {
  96. run_or_cry('git-checkout','-f',$master_branch);
  97. }
  98. };
  99. run_or_die('git-checkout', $branch);
  100. # Put the modified file in _this_ branch.
  101. rename($hidden, $target)
  102. or error("rename '$hidden' to '$target' failed: $!");
  103. # _Silently_ commit all modifications in the current branch.
  104. run_or_non('git-commit', '-m', $message, '-a');
  105. # ... and re-switch to master.
  106. run_or_die('git-checkout', $master_branch);
  107. # Attempt to merge without complaining.
  108. if (!run_or_non('git-pull', '--no-commit', '.', $branch)) {
  109. $conflict = readfile($target);
  110. run_or_die('git-reset', '--hard');
  111. }
  112. };
  113. my $failure = $@;
  114. # Process undo stack (in reverse order). By policy cleanup
  115. # actions should normally print a warning on failure.
  116. while (my $handle = pop @undo) {
  117. $handle->();
  118. }
  119. error("Git merge failed!\n$failure\n") if $failure;
  120. return $conflict;
  121. } #}}}
  122. sub _parse_diff_tree (@) { #{{{
  123. # Parse the raw diff tree chunk and return the info hash.
  124. # See git-diff-tree(1) for the syntax.
  125. my ($dt_ref) = @_;
  126. # End of stream?
  127. return if !defined @{ $dt_ref } || !length @{ $dt_ref }[0];
  128. my %ci;
  129. # Header line.
  130. HEADER: while (my $line = shift @{ $dt_ref }) {
  131. return if $line !~ m/^(.+) ($sha1_pattern)/;
  132. my $sha1 = $1;
  133. $ci{'sha1'} = $sha1;
  134. last HEADER;
  135. }
  136. # Identification lines for the commit.
  137. IDENT: 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. } elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
  142. # XXX: collecting in reverse order
  143. push @{ $ci{'parents'} }, $1;
  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. } else {
  155. $ci{"${who}_fullname"} =
  156. $ci{"${who}_username"} = $name;
  157. }
  158. } elsif ($line =~ m/^$/) {
  159. # Trailing empty line signals next section.
  160. last IDENT;
  161. }
  162. }
  163. error("No 'tree' or 'parents' seen in diff-tree output")
  164. if !defined $ci{'tree'} || !defined $ci{'parents'};
  165. $ci{'parent'} = @{ $ci{'parents'} }[0];
  166. # Commit message.
  167. COMMENT: while (my $line = shift @{ $dt_ref }) {
  168. if ($line =~ m/^$/) {
  169. # Trailing empty line signals next section.
  170. last COMMENT;
  171. };
  172. $line =~ s/^ //;
  173. push @{ $ci{'comment'} }, $line;
  174. }
  175. # Modified files.
  176. FILE: while (my $line = shift @{ $dt_ref }) {
  177. if ($line =~ m{^:
  178. ([0-7]{6})[ ] # from mode
  179. ([0-7]{6})[ ] # to mode
  180. ($sha1_pattern)[ ] # from sha1
  181. ($sha1_pattern)[ ] # to sha1
  182. (.) # status
  183. ([0-9]{0,3})\t # similarity
  184. (.*) # file
  185. $}xo) {
  186. my ($sha1_from, $sha1_to, $file) =
  187. ($3, $4, $7 );
  188. if ($file =~ m/^"(.*)"$/) {
  189. ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
  190. }
  191. if (length $file) {
  192. push @{ $ci{'details'} }, {
  193. 'file' => $file,
  194. 'sha1_from' => $sha1_from,
  195. 'sha1_to' => $sha1_to,
  196. };
  197. }
  198. next FILE;
  199. };
  200. last FILE;
  201. }
  202. warn "No detail in diff-tree output" if !defined $ci{'details'};
  203. return \%ci;
  204. } #}}}
  205. sub git_commit_info (;$$) { #{{{
  206. # Return an array of commit info hashes of num commits (default: 1)
  207. # starting from the given sha1sum (default: HEAD).
  208. my ($sha1, $num) = @_;
  209. $num ||= 1;
  210. my @raw_lines =
  211. run_or_die(qq{git-rev-list --max-count=$num $sha1 |
  212. git-diff-tree --stdin --pretty=raw -M -r});
  213. my @ci;
  214. while (my $parsed = _parse_diff_tree(\@raw_lines)) {
  215. push @ci, $parsed;
  216. }
  217. warn "Cannot parse commit info for '$sha1' commit" if !@ci;
  218. return wantarray ? @ci : $ci[0];
  219. } #}}}
  220. sub git_sha1 (;$) { #{{{
  221. # Return head sha1sum (of given file).
  222. my $file = shift || q{--};
  223. # Ignore error since a non-existing file might be given.
  224. my ($sha1) = run_or_non('git-rev-list', '--max-count=1', 'HEAD', $file);
  225. if ($sha1) {
  226. ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
  227. } else { debug("Empty sha1sum for '$file'.") }
  228. return defined $sha1 ? $sha1 : q{};
  229. } #}}}
  230. sub rcs_update () { #{{{
  231. # Update working directory.
  232. run_or_cry('git-pull', $origin_branch);
  233. } #}}}
  234. sub rcs_prepedit ($) { #{{{
  235. # Return the commit sha1sum of the file when editing begins.
  236. # This will be later used in rcs_commit if a merge is required.
  237. my ($file) = @_;
  238. return git_sha1($file);
  239. } #}}}
  240. sub rcs_commit ($$$) { #{{{
  241. # Try to commit the page; returns undef on _success_ and
  242. # a version of the page with the rcs's conflict markers on
  243. # failure.
  244. my ($file, $message, $rcstoken) = @_;
  245. # XXX: Wiki directory is in the unlocked state when starting this
  246. # action. But it takes time for a Git process to finish its job
  247. # (especially if a merge required), so we must re-lock to prevent
  248. # race conditions. Only when the time of the real commit action
  249. # (i.e. git-push(1)) comes, we'll unlock the directory.
  250. lockwiki();
  251. # Check to see if the page has been changed by someone else since
  252. # rcs_prepedit was called.
  253. my $cur = git_sha1($file);
  254. my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
  255. if (defined $cur && defined $prev && $cur ne $prev) {
  256. my $conflict = _merge_past($prev, $file, $dummy_commit_msg);
  257. return $conflict if defined $conflict;
  258. }
  259. # git-commit(1) returns non-zero if file has not been really changed.
  260. # so we should ignore its exit status (hence run_or_non).
  261. $message = possibly_foolish_untaint($message);
  262. if (run_or_non('git-commit', '-m', $message, '-i', $file)) {
  263. unlockwiki();
  264. run_or_cry('git-push', $origin_branch);
  265. }
  266. return undef; # success
  267. } #}}}
  268. sub rcs_add ($) { # {{{
  269. # Add file to archive.
  270. my ($file) = @_;
  271. run_or_cry('git-add', $file);
  272. } #}}}
  273. sub rcs_recentchanges ($) { #{{{
  274. # List of recent changes.
  275. my ($num) = @_;
  276. eval q{use CGI 'escapeHTML'};
  277. eval q{use Date::Parse};
  278. eval q{use Time::Duration};
  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 = concise(ago(time - $ci->{'author_epoch'}));
  287. foreach my $bit (@{ $ci->{'details'} }) {
  288. my $diffurl = $config{'diffurl'};
  289. my $file = $bit->{'file'};
  290. $diffurl =~ s/\[\[file\]\]/$file/go;
  291. $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
  292. $diffurl =~ s/\[\[sha1_from\]\]/$bit->{'sha1_from'}/go;
  293. $diffurl =~ s/\[\[sha1_to\]\]/$bit->{'sha1_to'}/go;
  294. push @pages, {
  295. link => htmllink("", "", pagename($file), 1),
  296. diffurl => $diffurl,
  297. },
  298. }
  299. push @message, { line => escapeHTML($title) };
  300. if (defined $message[0] &&
  301. $message[0]->{line} =~ m/$web_commit_msg/) {
  302. $user = "$1";
  303. $message[0]->{line} = $2;
  304. } else {
  305. $type ="git";
  306. $user = $ci->{'author_username'};
  307. }
  308. push @rets, {
  309. rev => $sha1,
  310. user => htmllink("", "", $user, 1),
  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 = "$1";
  344. $message = $2;
  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