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