summaryrefslogtreecommitdiff
path: root/IkiWiki/Rcs/git.pm
blob: b02b286bdc9dc3027fa0daf65b294ece518912e5 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki;
  3. use warnings;
  4. use strict;
  5. use IkiWiki;
  6. use Encode;
  7. use open qw{:utf8 :std};
  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/^[^<]+\s+<([^@>]+)/) {
  151. $ci{"${who}_username"} = $1;
  152. }
  153. elsif ($name =~ m/^([^<]+)\s+<>$/) {
  154. $ci{"${who}_username"} = $1;
  155. }
  156. else {
  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' seen in diff-tree output") if !defined $ci{'tree'};
  166. if (defined $ci{'parents'}) {
  167. $ci{'parent'} = @{ $ci{'parents'} }[0];
  168. }
  169. else {
  170. $ci{'parent'} = 0 x 40;
  171. }
  172. # Commit message (optional).
  173. while ($dt_ref->[0] =~ /^ /) {
  174. my $line = shift @{ $dt_ref };
  175. $line =~ s/^ //;
  176. push @{ $ci{'comment'} }, $line;
  177. }
  178. shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
  179. # Modified files.
  180. while (my $line = shift @{ $dt_ref }) {
  181. if ($line =~ m{^
  182. (:+) # number of parents
  183. ([^\t]+)\t # modes, sha1, status
  184. (.*) # file names
  185. $}xo) {
  186. my $num_parents = length $1;
  187. my @tmp = split(" ", $2);
  188. my ($file, $file_to) = split("\t", $3);
  189. my @mode_from = splice(@tmp, 0, $num_parents);
  190. my $mode_to = shift(@tmp);
  191. my @sha1_from = splice(@tmp, 0, $num_parents);
  192. my $sha1_to = shift(@tmp);
  193. my $status = shift(@tmp);
  194. if ($file =~ m/^"(.*)"$/) {
  195. ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
  196. }
  197. $file =~ s/^\Q$prefix\E//;
  198. if (length $file) {
  199. push @{ $ci{'details'} }, {
  200. 'file' => decode_utf8($file),
  201. 'sha1_from' => $sha1_from[0],
  202. 'sha1_to' => $sha1_to,
  203. };
  204. }
  205. next;
  206. };
  207. last;
  208. }
  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 = run_or_die('git', 'log', "--max-count=$num",
  217. '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
  218. '-r', $sha1, '--', '.');
  219. my ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
  220. my @ci;
  221. while (my $parsed = _parse_diff_tree(($prefix or ""), \@raw_lines)) {
  222. push @ci, $parsed;
  223. }
  224. warn "Cannot parse commit info for '$sha1' commit" if !@ci;
  225. return wantarray ? @ci : $ci[0];
  226. } #}}}
  227. sub git_sha1 (;$) { #{{{
  228. # Return head sha1sum (of given file).
  229. my $file = shift || q{--};
  230. # Ignore error since a non-existing file might be given.
  231. my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
  232. '--', $file);
  233. if ($sha1) {
  234. ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
  235. } else { debug("Empty sha1sum for '$file'.") }
  236. return defined $sha1 ? $sha1 : q{};
  237. } #}}}
  238. sub rcs_update () { #{{{
  239. # Update working directory.
  240. if (length $config{gitorigin_branch}) {
  241. run_or_cry('git', 'pull', $config{gitorigin_branch});
  242. }
  243. } #}}}
  244. sub rcs_prepedit ($) { #{{{
  245. # Return the commit sha1sum of the file when editing begins.
  246. # This will be later used in rcs_commit if a merge is required.
  247. my ($file) = @_;
  248. return git_sha1($file);
  249. } #}}}
  250. sub rcs_commit ($$$;$$) { #{{{
  251. # Try to commit the page; returns undef on _success_ and
  252. # a version of the page with the rcs's conflict markers on
  253. # failure.
  254. my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
  255. # Check to see if the page has been changed by someone else since
  256. # rcs_prepedit was called.
  257. my $cur = git_sha1($file);
  258. my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
  259. if (defined $cur && defined $prev && $cur ne $prev) {
  260. my $conflict = _merge_past($prev, $file, $dummy_commit_msg);
  261. return $conflict if defined $conflict;
  262. }
  263. # Set the commit author and email to the web committer.
  264. my %env=%ENV;
  265. if (defined $user || defined $ipaddr) {
  266. my $u=defined $user ? $user : $ipaddr;
  267. $ENV{GIT_AUTHOR_NAME}=$u;
  268. $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
  269. }
  270. # git commit returns non-zero if file has not been really changed.
  271. # so we should ignore its exit status (hence run_or_non).
  272. $message = possibly_foolish_untaint($message);
  273. if (run_or_non('git', 'commit', '--cleanup=verbatim', '-q', '-m', $message, '-i', $file)) {
  274. if (length $config{gitorigin_branch}) {
  275. run_or_cry('git', 'push', $config{gitorigin_branch});
  276. }
  277. }
  278. %ENV=%env;
  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_remove ($) { # {{{
  287. # Remove file from archive.
  288. my ($file) = @_;
  289. run_or_cry('git', 'rm', '-f', $file);
  290. } #}}}
  291. sub rcs_recentchanges ($) { #{{{
  292. # List of recent changes.
  293. my ($num) = @_;
  294. eval q{use Date::Parse};
  295. error($@) if $@;
  296. my @rets;
  297. foreach my $ci (git_commit_info('HEAD', $num)) {
  298. # Skip redundant commits.
  299. next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
  300. my ($sha1, $when) = (
  301. $ci->{'sha1'},
  302. $ci->{'author_epoch'}
  303. );
  304. my @pages;
  305. foreach my $detail (@{ $ci->{'details'} }) {
  306. my $file = $detail->{'file'};
  307. my $diffurl = $config{'diffurl'};
  308. $diffurl =~ s/\[\[file\]\]/$file/go;
  309. $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
  310. $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
  311. $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
  312. push @pages, {
  313. page => pagename($file),
  314. diffurl => $diffurl,
  315. };
  316. }
  317. my @messages;
  318. my $pastblank=0;
  319. foreach my $line (@{$ci->{'comment'}}) {
  320. $pastblank=1 if $line eq '';
  321. next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
  322. push @messages, { line => $line };
  323. }
  324. my $user=$ci->{'author_username'};
  325. my $web_commit = ($ci->{'author'} =~ /\@web>/);
  326. # compatability code for old web commit messages
  327. if (! $web_commit &&
  328. defined $messages[0] &&
  329. $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
  330. $user = defined $2 ? "$2" : "$3";
  331. $messages[0]->{line} = $4;
  332. $web_commit=1;
  333. }
  334. push @rets, {
  335. rev => $sha1,
  336. user => $user,
  337. committype => $web_commit ? "web" : "git",
  338. when => $when,
  339. message => [@messages],
  340. pages => [@pages],
  341. } if @pages;
  342. last if @rets >= $num;
  343. }
  344. return @rets;
  345. } #}}}
  346. sub rcs_diff ($) { #{{{
  347. my $rev=shift;
  348. my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
  349. my @lines;
  350. foreach my $line (run_or_non("git", "show", $sha1)) {
  351. if (@lines || $line=~/^diff --git/) {
  352. push @lines, $line."\n";
  353. }
  354. }
  355. if (wantarray) {
  356. return @lines;
  357. }
  358. else {
  359. return join("", @lines);
  360. }
  361. } #}}}
  362. sub rcs_getctime ($) { #{{{
  363. my $file=shift;
  364. # Remove srcdir prefix
  365. $file =~ s/^\Q$config{srcdir}\E\/?//;
  366. my $sha1 = git_sha1($file);
  367. my $ci = git_commit_info($sha1);
  368. my $ctime = $ci->{'author_epoch'};
  369. debug("ctime for '$file': ". localtime($ctime));
  370. return $ctime;
  371. } #}}}
  372. 1