summaryrefslogtreecommitdiff
path: root/IkiWiki/Rcs/git.pm
blob: 7c3ae9276edc3c924831ecc3ae246181cb89f846 (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. hook(type => "getsetup", id => "git", call => sub { #{{{
  11. return
  12. historyurl => {
  13. type => "string",
  14. default => "",
  15. example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]]",
  16. description => "gitweb url to show file history ([[file]] substituted)",
  17. safe => 1,
  18. rebuild => 1,
  19. },
  20. diffurl => {
  21. type => "string",
  22. default => "",
  23. example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=blobdiff;h=[[sha1_to]];hp=[[sha1_from]];hb=[[sha1_parent]];f=[[file]]",
  24. description => "gitweb url to show a diff ([[sha1_to]], [[sha1_from]], [[sha1_parent]], and [[file]] substituted)",
  25. safe => 1,
  26. rebuild => 1,
  27. },
  28. gitorigin_branch => {
  29. type => "string",
  30. default => "origin",
  31. description => "where to pull and push changes (unset to not pull/push)",
  32. safe => 0, # paranoia
  33. rebuild => 0,
  34. },
  35. gitmaster_branch => {
  36. type => "string",
  37. default => "master",
  38. description => "branch that the wiki is stored in",
  39. safe => 0, # paranoia
  40. rebuild => 0,
  41. },
  42. }); #}}}
  43. sub _safe_git (&@) { #{{{
  44. # Start a child process safely without resorting /bin/sh.
  45. # Return command output or success state (in scalar context).
  46. my ($error_handler, @cmdline) = @_;
  47. my $pid = open my $OUT, "-|";
  48. error("Cannot fork: $!") if !defined $pid;
  49. if (!$pid) {
  50. # In child.
  51. # Git commands want to be in wc.
  52. chdir $config{srcdir}
  53. or error("Cannot chdir to $config{srcdir}: $!");
  54. exec @cmdline or error("Cannot exec '@cmdline': $!");
  55. }
  56. # In parent.
  57. my @lines;
  58. while (<$OUT>) {
  59. chomp;
  60. push @lines, $_;
  61. }
  62. close $OUT;
  63. $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
  64. return wantarray ? @lines : ($? == 0);
  65. }
  66. # Convenient wrappers.
  67. sub run_or_die ($@) { _safe_git(\&error, @_) }
  68. sub run_or_cry ($@) { _safe_git(sub { warn @_ }, @_) }
  69. sub run_or_non ($@) { _safe_git(undef, @_) }
  70. #}}}
  71. sub _merge_past ($$$) { #{{{
  72. # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
  73. # Git merge commands work with the committed changes, except in the
  74. # implicit case of '-m' of git checkout(1). So we should invent a
  75. # kludge here. In principle, we need to create a throw-away branch
  76. # in preparing for the merge itself. Since branches are cheap (and
  77. # branching is fast), this shouldn't cost high.
  78. #
  79. # The main problem is the presence of _uncommitted_ local changes. One
  80. # possible approach to get rid of this situation could be that we first
  81. # make a temporary commit in the master branch and later restore the
  82. # initial state (this is possible since Git has the ability to undo a
  83. # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
  84. # as follows:
  85. #
  86. # - create a diff of HEAD:current-sha1
  87. # - dummy commit
  88. # - create a dummy branch and switch to it
  89. # - rewind to past (reset --hard to the current-sha1)
  90. # - apply the diff and commit
  91. # - switch to master and do the merge with the dummy branch
  92. # - make a soft reset (undo the last commit of master)
  93. #
  94. # The above method has some drawbacks: (1) it needs a redundant commit
  95. # just to get rid of local changes, (2) somewhat slow because of the
  96. # required system forks. Until someone points a more straight method
  97. # (which I would be grateful) I have implemented an alternative method.
  98. # In this approach, we hide all the modified files from Git by renaming
  99. # them (using the 'rename' builtin) and later restore those files in
  100. # the throw-away branch (that is, we put the files themselves instead
  101. # of applying a patch).
  102. my ($sha1, $file, $message) = @_;
  103. my @undo; # undo stack for cleanup in case of an error
  104. my $conflict; # file content with conflict markers
  105. eval {
  106. # Hide local changes from Git by renaming the modified file.
  107. # Relative paths must be converted to absolute for renaming.
  108. my ($target, $hidden) = (
  109. "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
  110. );
  111. rename($target, $hidden)
  112. or error("rename '$target' to '$hidden' failed: $!");
  113. # Ensure to restore the renamed file on error.
  114. push @undo, sub {
  115. return if ! -e "$hidden"; # already renamed
  116. rename($hidden, $target)
  117. or warn "rename '$hidden' to '$target' failed: $!";
  118. };
  119. my $branch = "throw_away_${sha1}"; # supposed to be unique
  120. # Create a throw-away branch and rewind backward.
  121. push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
  122. run_or_die('git', 'branch', $branch, $sha1);
  123. # Switch to throw-away branch for the merge operation.
  124. push @undo, sub {
  125. if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
  126. run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
  127. }
  128. };
  129. run_or_die('git', 'checkout', $branch);
  130. # Put the modified file in _this_ branch.
  131. rename($hidden, $target)
  132. or error("rename '$hidden' to '$target' failed: $!");
  133. # _Silently_ commit all modifications in the current branch.
  134. run_or_non('git', 'commit', '-m', $message, '-a');
  135. # ... and re-switch to master.
  136. run_or_die('git', 'checkout', $config{gitmaster_branch});
  137. # Attempt to merge without complaining.
  138. if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
  139. $conflict = readfile($target);
  140. run_or_die('git', 'reset', '--hard');
  141. }
  142. };
  143. my $failure = $@;
  144. # Process undo stack (in reverse order). By policy cleanup
  145. # actions should normally print a warning on failure.
  146. while (my $handle = pop @undo) {
  147. $handle->();
  148. }
  149. error("Git merge failed!\n$failure\n") if $failure;
  150. return $conflict;
  151. } #}}}
  152. sub _parse_diff_tree ($@) { #{{{
  153. # Parse the raw diff tree chunk and return the info hash.
  154. # See git-diff-tree(1) for the syntax.
  155. my ($prefix, $dt_ref) = @_;
  156. # End of stream?
  157. return if !defined @{ $dt_ref } ||
  158. !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
  159. my %ci;
  160. # Header line.
  161. while (my $line = shift @{ $dt_ref }) {
  162. return if $line !~ m/^(.+) ($sha1_pattern)/;
  163. my $sha1 = $2;
  164. $ci{'sha1'} = $sha1;
  165. last;
  166. }
  167. # Identification lines for the commit.
  168. while (my $line = shift @{ $dt_ref }) {
  169. # Regexps are semi-stolen from gitweb.cgi.
  170. if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
  171. $ci{'tree'} = $1;
  172. }
  173. elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
  174. # XXX: collecting in reverse order
  175. push @{ $ci{'parents'} }, $1;
  176. }
  177. elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
  178. my ($who, $name, $epoch, $tz) =
  179. ($1, $2, $3, $4 );
  180. $ci{ $who } = $name;
  181. $ci{ "${who}_epoch" } = $epoch;
  182. $ci{ "${who}_tz" } = $tz;
  183. if ($name =~ m/^[^<]+\s+<([^@>]+)/) {
  184. $ci{"${who}_username"} = $1;
  185. }
  186. elsif ($name =~ m/^([^<]+)\s+<>$/) {
  187. $ci{"${who}_username"} = $1;
  188. }
  189. else {
  190. $ci{"${who}_username"} = $name;
  191. }
  192. }
  193. elsif ($line =~ m/^$/) {
  194. # Trailing empty line signals next section.
  195. last;
  196. }
  197. }
  198. debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
  199. if (defined $ci{'parents'}) {
  200. $ci{'parent'} = @{ $ci{'parents'} }[0];
  201. }
  202. else {
  203. $ci{'parent'} = 0 x 40;
  204. }
  205. # Commit message (optional).
  206. while ($dt_ref->[0] =~ /^ /) {
  207. my $line = shift @{ $dt_ref };
  208. $line =~ s/^ //;
  209. push @{ $ci{'comment'} }, $line;
  210. }
  211. shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
  212. # Modified files.
  213. while (my $line = shift @{ $dt_ref }) {
  214. if ($line =~ m{^
  215. (:+) # number of parents
  216. ([^\t]+)\t # modes, sha1, status
  217. (.*) # file names
  218. $}xo) {
  219. my $num_parents = length $1;
  220. my @tmp = split(" ", $2);
  221. my ($file, $file_to) = split("\t", $3);
  222. my @mode_from = splice(@tmp, 0, $num_parents);
  223. my $mode_to = shift(@tmp);
  224. my @sha1_from = splice(@tmp, 0, $num_parents);
  225. my $sha1_to = shift(@tmp);
  226. my $status = shift(@tmp);
  227. if ($file =~ m/^"(.*)"$/) {
  228. ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
  229. }
  230. $file =~ s/^\Q$prefix\E//;
  231. if (length $file) {
  232. push @{ $ci{'details'} }, {
  233. 'file' => decode_utf8($file),
  234. 'sha1_from' => $sha1_from[0],
  235. 'sha1_to' => $sha1_to,
  236. };
  237. }
  238. next;
  239. };
  240. last;
  241. }
  242. return \%ci;
  243. } #}}}
  244. sub git_commit_info ($;$) { #{{{
  245. # Return an array of commit info hashes of num commits (default: 1)
  246. # starting from the given sha1sum.
  247. my ($sha1, $num) = @_;
  248. $num ||= 1;
  249. my @raw_lines = run_or_die('git', 'log', "--max-count=$num",
  250. '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
  251. '-r', $sha1, '--', '.');
  252. my ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
  253. my @ci;
  254. while (my $parsed = _parse_diff_tree(($prefix or ""), \@raw_lines)) {
  255. push @ci, $parsed;
  256. }
  257. warn "Cannot parse commit info for '$sha1' commit" if !@ci;
  258. return wantarray ? @ci : $ci[0];
  259. } #}}}
  260. sub git_sha1 (;$) { #{{{
  261. # Return head sha1sum (of given file).
  262. my $file = shift || q{--};
  263. # Ignore error since a non-existing file might be given.
  264. my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
  265. '--', $file);
  266. if ($sha1) {
  267. ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
  268. } else { debug("Empty sha1sum for '$file'.") }
  269. return defined $sha1 ? $sha1 : q{};
  270. } #}}}
  271. sub rcs_update () { #{{{
  272. # Update working directory.
  273. if (length $config{gitorigin_branch}) {
  274. run_or_cry('git', 'pull', $config{gitorigin_branch});
  275. }
  276. } #}}}
  277. sub rcs_prepedit ($) { #{{{
  278. # Return the commit sha1sum of the file when editing begins.
  279. # This will be later used in rcs_commit if a merge is required.
  280. my ($file) = @_;
  281. return git_sha1($file);
  282. } #}}}
  283. sub rcs_commit ($$$;$$) { #{{{
  284. # Try to commit the page; returns undef on _success_ and
  285. # a version of the page with the rcs's conflict markers on
  286. # failure.
  287. my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
  288. # Check to see if the page has been changed by someone else since
  289. # rcs_prepedit was called.
  290. my $cur = git_sha1($file);
  291. my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
  292. if (defined $cur && defined $prev && $cur ne $prev) {
  293. my $conflict = _merge_past($prev, $file, $dummy_commit_msg);
  294. return $conflict if defined $conflict;
  295. }
  296. rcs_add($file);
  297. return rcs_commit_staged($message, $user, $ipaddr);
  298. } #}}}
  299. sub rcs_commit_staged ($$$) {
  300. # Commits all staged changes. Changes can be staged using rcs_add,
  301. # rcs_remove, and rcs_rename.
  302. my ($message, $user, $ipaddr)=@_;
  303. # Set the commit author and email to the web committer.
  304. my %env=%ENV;
  305. if (defined $user || defined $ipaddr) {
  306. my $u=defined $user ? $user : $ipaddr;
  307. $ENV{GIT_AUTHOR_NAME}=$u;
  308. $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
  309. }
  310. # git commit returns non-zero if file has not been really changed.
  311. # so we should ignore its exit status (hence run_or_non).
  312. $message = possibly_foolish_untaint($message);
  313. if (run_or_non('git', 'commit', '--cleanup=verbatim',
  314. '-q', '-m', $message)) {
  315. if (length $config{gitorigin_branch}) {
  316. run_or_cry('git', 'push', $config{gitorigin_branch});
  317. }
  318. }
  319. %ENV=%env;
  320. return undef; # success
  321. }
  322. sub rcs_add ($) { # {{{
  323. # Add file to archive.
  324. my ($file) = @_;
  325. run_or_cry('git', 'add', $file);
  326. } #}}}
  327. sub rcs_remove ($) { # {{{
  328. # Remove file from archive.
  329. my ($file) = @_;
  330. run_or_cry('git', 'rm', '-f', $file);
  331. } #}}}
  332. sub rcs_rename ($$) { # {{{
  333. my ($src, $dest) = @_;
  334. run_or_cry('git', 'mv', '-f', $src, $dest);
  335. } #}}}
  336. sub rcs_recentchanges ($) { #{{{
  337. # List of recent changes.
  338. my ($num) = @_;
  339. eval q{use Date::Parse};
  340. error($@) if $@;
  341. my @rets;
  342. foreach my $ci (git_commit_info('HEAD', $num)) {
  343. # Skip redundant commits.
  344. next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
  345. my ($sha1, $when) = (
  346. $ci->{'sha1'},
  347. $ci->{'author_epoch'}
  348. );
  349. my @pages;
  350. foreach my $detail (@{ $ci->{'details'} }) {
  351. my $file = $detail->{'file'};
  352. my $diffurl = $config{'diffurl'};
  353. $diffurl =~ s/\[\[file\]\]/$file/go;
  354. $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
  355. $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
  356. $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
  357. push @pages, {
  358. page => pagename($file),
  359. diffurl => $diffurl,
  360. };
  361. }
  362. my @messages;
  363. my $pastblank=0;
  364. foreach my $line (@{$ci->{'comment'}}) {
  365. $pastblank=1 if $line eq '';
  366. next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
  367. push @messages, { line => $line };
  368. }
  369. my $user=$ci->{'author_username'};
  370. my $web_commit = ($ci->{'author'} =~ /\@web>/);
  371. # compatability code for old web commit messages
  372. if (! $web_commit &&
  373. defined $messages[0] &&
  374. $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
  375. $user = defined $2 ? "$2" : "$3";
  376. $messages[0]->{line} = $4;
  377. $web_commit=1;
  378. }
  379. push @rets, {
  380. rev => $sha1,
  381. user => $user,
  382. committype => $web_commit ? "web" : "git",
  383. when => $when,
  384. message => [@messages],
  385. pages => [@pages],
  386. } if @pages;
  387. last if @rets >= $num;
  388. }
  389. return @rets;
  390. } #}}}
  391. sub rcs_diff ($) { #{{{
  392. my $rev=shift;
  393. my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
  394. my @lines;
  395. foreach my $line (run_or_non("git", "show", $sha1)) {
  396. if (@lines || $line=~/^diff --git/) {
  397. push @lines, $line."\n";
  398. }
  399. }
  400. if (wantarray) {
  401. return @lines;
  402. }
  403. else {
  404. return join("", @lines);
  405. }
  406. } #}}}
  407. sub rcs_getctime ($) { #{{{
  408. my $file=shift;
  409. # Remove srcdir prefix
  410. $file =~ s/^\Q$config{srcdir}\E\/?//;
  411. my $sha1 = git_sha1($file);
  412. my $ci = git_commit_info($sha1);
  413. my $ctime = $ci->{'author_epoch'};
  414. debug("ctime for '$file': ". localtime($ctime));
  415. return $ctime;
  416. } #}}}
  417. 1