summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/git.pm
blob: 08ee4cb63c07a5cc572e33f9f1fac262f4d58cd9 (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. if ($file =~ m/^"(.*)"$/) {
  272. ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
  273. }
  274. $file =~ s/^\Q$prefix\E//;
  275. if (length $file) {
  276. push @{ $ci{'details'} }, {
  277. 'file' => decode_utf8($file),
  278. 'sha1_from' => $sha1_from[0],
  279. 'sha1_to' => $sha1_to,
  280. };
  281. }
  282. next;
  283. };
  284. last;
  285. }
  286. return \%ci;
  287. } #}}}
  288. sub git_commit_info ($;$) { #{{{
  289. # Return an array of commit info hashes of num commits (default: 1)
  290. # starting from the given sha1sum.
  291. my ($sha1, $num) = @_;
  292. $num ||= 1;
  293. my @raw_lines = run_or_die('git', 'log', "--max-count=$num",
  294. '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
  295. '-r', $sha1, '--', '.');
  296. my ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
  297. my @ci;
  298. while (my $parsed = parse_diff_tree(($prefix or ""), \@raw_lines)) {
  299. push @ci, $parsed;
  300. }
  301. warn "Cannot parse commit info for '$sha1' commit" if !@ci;
  302. return wantarray ? @ci : $ci[0];
  303. } #}}}
  304. sub git_sha1 (;$) { #{{{
  305. # Return head sha1sum (of given file).
  306. my $file = shift || q{--};
  307. # Ignore error since a non-existing file might be given.
  308. my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
  309. '--', $file);
  310. if ($sha1) {
  311. ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
  312. } else { debug("Empty sha1sum for '$file'.") }
  313. return defined $sha1 ? $sha1 : q{};
  314. } #}}}
  315. sub rcs_update () { #{{{
  316. # Update working directory.
  317. if (length $config{gitorigin_branch}) {
  318. run_or_cry('git', 'pull', $config{gitorigin_branch});
  319. }
  320. } #}}}
  321. sub rcs_prepedit ($) { #{{{
  322. # Return the commit sha1sum of the file when editing begins.
  323. # This will be later used in rcs_commit if a merge is required.
  324. my ($file) = @_;
  325. return git_sha1($file);
  326. } #}}}
  327. sub rcs_commit ($$$;$$) { #{{{
  328. # Try to commit the page; returns undef on _success_ and
  329. # a version of the page with the rcs's conflict markers on
  330. # failure.
  331. my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
  332. # Check to see if the page has been changed by someone else since
  333. # rcs_prepedit was called.
  334. my $cur = git_sha1($file);
  335. my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
  336. if (defined $cur && defined $prev && $cur ne $prev) {
  337. my $conflict = merge_past($prev, $file, $dummy_commit_msg);
  338. return $conflict if defined $conflict;
  339. }
  340. rcs_add($file);
  341. return rcs_commit_staged($message, $user, $ipaddr);
  342. } #}}}
  343. sub rcs_commit_staged ($$$) {
  344. # Commits all staged changes. Changes can be staged using rcs_add,
  345. # rcs_remove, and rcs_rename.
  346. my ($message, $user, $ipaddr)=@_;
  347. # Set the commit author and email to the web committer.
  348. my %env=%ENV;
  349. if (defined $user || defined $ipaddr) {
  350. my $u=defined $user ? $user : $ipaddr;
  351. $ENV{GIT_AUTHOR_NAME}=$u;
  352. $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
  353. }
  354. $message = IkiWiki::possibly_foolish_untaint($message);
  355. my @opts;
  356. if ($message !~ /\S/) {
  357. # Force git to allow empty commit messages.
  358. # (If this version of git supports it.)
  359. my ($version)=`git --version` =~ /git version (.*)/;
  360. if ($version ge "1.5.4") {
  361. push @opts, '--cleanup=verbatim';
  362. }
  363. else {
  364. $message.=".";
  365. }
  366. }
  367. push @opts, '-q';
  368. # git commit returns non-zero if file has not been really changed.
  369. # so we should ignore its exit status (hence run_or_non).
  370. if (run_or_non('git', 'commit', @opts, '-m', $message)) {
  371. if (length $config{gitorigin_branch}) {
  372. run_or_cry('git', 'push', $config{gitorigin_branch});
  373. }
  374. }
  375. %ENV=%env;
  376. return undef; # success
  377. }
  378. sub rcs_add ($) { # {{{
  379. # Add file to archive.
  380. my ($file) = @_;
  381. run_or_cry('git', 'add', $file);
  382. } #}}}
  383. sub rcs_remove ($) { # {{{
  384. # Remove file from archive.
  385. my ($file) = @_;
  386. run_or_cry('git', 'rm', '-f', $file);
  387. } #}}}
  388. sub rcs_rename ($$) { # {{{
  389. my ($src, $dest) = @_;
  390. run_or_cry('git', 'mv', '-f', $src, $dest);
  391. } #}}}
  392. sub rcs_recentchanges ($) { #{{{
  393. # List of recent changes.
  394. my ($num) = @_;
  395. eval q{use Date::Parse};
  396. error($@) if $@;
  397. my @rets;
  398. foreach my $ci (git_commit_info('HEAD', $num)) {
  399. # Skip redundant commits.
  400. next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
  401. my ($sha1, $when) = (
  402. $ci->{'sha1'},
  403. $ci->{'author_epoch'}
  404. );
  405. my @pages;
  406. foreach my $detail (@{ $ci->{'details'} }) {
  407. my $file = $detail->{'file'};
  408. my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
  409. $diffurl =~ s/\[\[file\]\]/$file/go;
  410. $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
  411. $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
  412. $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
  413. push @pages, {
  414. page => pagename($file),
  415. diffurl => $diffurl,
  416. };
  417. }
  418. my @messages;
  419. my $pastblank=0;
  420. foreach my $line (@{$ci->{'comment'}}) {
  421. $pastblank=1 if $line eq '';
  422. next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
  423. push @messages, { line => $line };
  424. }
  425. my $user=$ci->{'author_username'};
  426. my $web_commit = ($ci->{'author'} =~ /\@web>/);
  427. # compatability code for old web commit messages
  428. if (! $web_commit &&
  429. defined $messages[0] &&
  430. $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
  431. $user = defined $2 ? "$2" : "$3";
  432. $messages[0]->{line} = $4;
  433. $web_commit=1;
  434. }
  435. push @rets, {
  436. rev => $sha1,
  437. user => $user,
  438. committype => $web_commit ? "web" : "git",
  439. when => $when,
  440. message => [@messages],
  441. pages => [@pages],
  442. } if @pages;
  443. last if @rets >= $num;
  444. }
  445. return @rets;
  446. } #}}}
  447. sub rcs_diff ($) { #{{{
  448. my $rev=shift;
  449. my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
  450. my @lines;
  451. foreach my $line (run_or_non("git", "show", $sha1)) {
  452. if (@lines || $line=~/^diff --git/) {
  453. push @lines, $line."\n";
  454. }
  455. }
  456. if (wantarray) {
  457. return @lines;
  458. }
  459. else {
  460. return join("", @lines);
  461. }
  462. } #}}}
  463. sub rcs_getctime ($) { #{{{
  464. my $file=shift;
  465. # Remove srcdir prefix
  466. $file =~ s/^\Q$config{srcdir}\E\/?//;
  467. my $sha1 = git_sha1($file);
  468. my $ci = git_commit_info($sha1);
  469. my $ctime = $ci->{'author_epoch'};
  470. debug("ctime for '$file': ". localtime($ctime));
  471. return $ctime;
  472. } #}}}
  473. 1