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