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