summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/git.pm
blob: cf7fbe9b7c43ee53180612d0411e6202074fb9e0 (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. my $git_dir=undef;
  11. sub import {
  12. hook(type => "checkconfig", id => "git", call => \&checkconfig);
  13. hook(type => "getsetup", id => "git", call => \&getsetup);
  14. hook(type => "genwrapper", id => "git", call => \&genwrapper);
  15. hook(type => "rcs", id => "rcs_update", call => \&rcs_update);
  16. hook(type => "rcs", id => "rcs_prepedit", call => \&rcs_prepedit);
  17. hook(type => "rcs", id => "rcs_commit", call => \&rcs_commit);
  18. hook(type => "rcs", id => "rcs_commit_staged", call => \&rcs_commit_staged);
  19. hook(type => "rcs", id => "rcs_add", call => \&rcs_add);
  20. hook(type => "rcs", id => "rcs_remove", call => \&rcs_remove);
  21. hook(type => "rcs", id => "rcs_rename", call => \&rcs_rename);
  22. hook(type => "rcs", id => "rcs_recentchanges", call => \&rcs_recentchanges);
  23. hook(type => "rcs", id => "rcs_diff", call => \&rcs_diff);
  24. hook(type => "rcs", id => "rcs_getctime", call => \&rcs_getctime);
  25. hook(type => "rcs", id => "rcs_getmtime", call => \&rcs_getmtime);
  26. hook(type => "rcs", id => "rcs_receive", call => \&rcs_receive);
  27. hook(type => "rcs", id => "rcs_preprevert", call => \&rcs_preprevert);
  28. hook(type => "rcs", id => "rcs_revert", call => \&rcs_revert);
  29. }
  30. sub checkconfig () {
  31. if (! defined $config{gitorigin_branch}) {
  32. $config{gitorigin_branch}="origin";
  33. }
  34. if (! defined $config{gitmaster_branch}) {
  35. $config{gitmaster_branch}="master";
  36. }
  37. if (defined $config{git_wrapper} &&
  38. length $config{git_wrapper}) {
  39. push @{$config{wrappers}}, {
  40. wrapper => $config{git_wrapper},
  41. wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
  42. wrapper_background_command => $config{git_wrapper_background_command},
  43. };
  44. }
  45. if (defined $config{git_test_receive_wrapper} &&
  46. length $config{git_test_receive_wrapper} &&
  47. defined $config{untrusted_committers} &&
  48. @{$config{untrusted_committers}}) {
  49. push @{$config{wrappers}}, {
  50. test_receive => 1,
  51. wrapper => $config{git_test_receive_wrapper},
  52. wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
  53. };
  54. }
  55. # Avoid notes, parser does not handle and they only slow things down.
  56. $ENV{GIT_NOTES_REF}="";
  57. # Run receive test only if being called by the wrapper, and not
  58. # when generating same.
  59. if ($config{test_receive} && ! exists $config{wrapper}) {
  60. require IkiWiki::Receive;
  61. IkiWiki::Receive::test();
  62. }
  63. }
  64. sub getsetup () {
  65. return
  66. plugin => {
  67. safe => 0, # rcs plugin
  68. rebuild => undef,
  69. section => "rcs",
  70. },
  71. git_wrapper => {
  72. type => "string",
  73. example => "/git/wiki.git/hooks/post-update",
  74. description => "git hook to generate",
  75. safe => 0, # file
  76. rebuild => 0,
  77. },
  78. git_wrapper_background_command => {
  79. type => "string",
  80. example => "git push github",
  81. description => "shell command for git_wrapper to run, in the background",
  82. safe => 0, # command
  83. rebuild => 0,
  84. },
  85. git_wrappermode => {
  86. type => "string",
  87. example => '06755',
  88. description => "mode for git_wrapper (can safely be made suid)",
  89. safe => 0,
  90. rebuild => 0,
  91. },
  92. git_test_receive_wrapper => {
  93. type => "string",
  94. example => "/git/wiki.git/hooks/pre-receive",
  95. description => "git pre-receive hook to generate",
  96. safe => 0, # file
  97. rebuild => 0,
  98. },
  99. untrusted_committers => {
  100. type => "string",
  101. example => [],
  102. description => "unix users whose commits should be checked by the pre-receive hook",
  103. safe => 0,
  104. rebuild => 0,
  105. },
  106. historyurl => {
  107. type => "string",
  108. example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]];hb=HEAD",
  109. description => "gitweb url to show file history ([[file]] substituted)",
  110. safe => 1,
  111. rebuild => 1,
  112. },
  113. diffurl => {
  114. type => "string",
  115. example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=blobdiff;f=[[file]];h=[[sha1_to]];hp=[[sha1_from]];hb=[[sha1_commit]];hpb=[[sha1_parent]]",
  116. description => "gitweb url to show a diff ([[file]], [[sha1_to]], [[sha1_from]], [[sha1_commit]], and [[sha1_parent]] substituted)",
  117. safe => 1,
  118. rebuild => 1,
  119. },
  120. gitorigin_branch => {
  121. type => "string",
  122. example => "origin",
  123. description => "where to pull and push changes (set to empty string to disable)",
  124. safe => 0, # paranoia
  125. rebuild => 0,
  126. },
  127. gitmaster_branch => {
  128. type => "string",
  129. example => "master",
  130. description => "branch that the wiki is stored in",
  131. safe => 0, # paranoia
  132. rebuild => 0,
  133. },
  134. }
  135. sub genwrapper {
  136. if ($config{test_receive}) {
  137. require IkiWiki::Receive;
  138. return IkiWiki::Receive::genwrapper();
  139. }
  140. else {
  141. return "";
  142. }
  143. }
  144. sub safe_git (&@) {
  145. # Start a child process safely without resorting to /bin/sh.
  146. # Returns command output (in list content) or success state
  147. # (in scalar context), or runs the specified data handler.
  148. my ($error_handler, $data_handler, @cmdline) = @_;
  149. my $pid = open my $OUT, "-|";
  150. error("Cannot fork: $!") if !defined $pid;
  151. if (!$pid) {
  152. # In child.
  153. # Git commands want to be in wc.
  154. if (! defined $git_dir) {
  155. chdir $config{srcdir}
  156. or error("cannot chdir to $config{srcdir}: $!");
  157. }
  158. else {
  159. chdir $git_dir
  160. or error("cannot chdir to $git_dir: $!");
  161. }
  162. exec @cmdline or error("Cannot exec '@cmdline': $!");
  163. }
  164. # In parent.
  165. # git output is probably utf-8 encoded, but may contain
  166. # other encodings or invalidly encoded stuff. So do not rely
  167. # on the normal utf-8 IO layer, decode it by hand.
  168. binmode($OUT);
  169. my @lines;
  170. while (<$OUT>) {
  171. $_=decode_utf8($_, 0);
  172. chomp;
  173. if (! defined $data_handler) {
  174. push @lines, $_;
  175. }
  176. else {
  177. last unless $data_handler->($_);
  178. }
  179. }
  180. close $OUT;
  181. $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
  182. return wantarray ? @lines : ($? == 0);
  183. }
  184. # Convenient wrappers.
  185. sub run_or_die ($@) { safe_git(\&error, undef, @_) }
  186. sub run_or_cry ($@) { safe_git(sub { warn @_ }, undef, @_) }
  187. sub run_or_non ($@) { safe_git(undef, undef, @_) }
  188. sub merge_past ($$$) {
  189. # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
  190. # Git merge commands work with the committed changes, except in the
  191. # implicit case of '-m' of git checkout(1). So we should invent a
  192. # kludge here. In principle, we need to create a throw-away branch
  193. # in preparing for the merge itself. Since branches are cheap (and
  194. # branching is fast), this shouldn't cost high.
  195. #
  196. # The main problem is the presence of _uncommitted_ local changes. One
  197. # possible approach to get rid of this situation could be that we first
  198. # make a temporary commit in the master branch and later restore the
  199. # initial state (this is possible since Git has the ability to undo a
  200. # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
  201. # as follows:
  202. #
  203. # - create a diff of HEAD:current-sha1
  204. # - dummy commit
  205. # - create a dummy branch and switch to it
  206. # - rewind to past (reset --hard to the current-sha1)
  207. # - apply the diff and commit
  208. # - switch to master and do the merge with the dummy branch
  209. # - make a soft reset (undo the last commit of master)
  210. #
  211. # The above method has some drawbacks: (1) it needs a redundant commit
  212. # just to get rid of local changes, (2) somewhat slow because of the
  213. # required system forks. Until someone points a more straight method
  214. # (which I would be grateful) I have implemented an alternative method.
  215. # In this approach, we hide all the modified files from Git by renaming
  216. # them (using the 'rename' builtin) and later restore those files in
  217. # the throw-away branch (that is, we put the files themselves instead
  218. # of applying a patch).
  219. my ($sha1, $file, $message) = @_;
  220. my @undo; # undo stack for cleanup in case of an error
  221. my $conflict; # file content with conflict markers
  222. eval {
  223. # Hide local changes from Git by renaming the modified file.
  224. # Relative paths must be converted to absolute for renaming.
  225. my ($target, $hidden) = (
  226. "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
  227. );
  228. rename($target, $hidden)
  229. or error("rename '$target' to '$hidden' failed: $!");
  230. # Ensure to restore the renamed file on error.
  231. push @undo, sub {
  232. return if ! -e "$hidden"; # already renamed
  233. rename($hidden, $target)
  234. or warn "rename '$hidden' to '$target' failed: $!";
  235. };
  236. my $branch = "throw_away_${sha1}"; # supposed to be unique
  237. # Create a throw-away branch and rewind backward.
  238. push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
  239. run_or_die('git', 'branch', $branch, $sha1);
  240. # Switch to throw-away branch for the merge operation.
  241. push @undo, sub {
  242. if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
  243. run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
  244. }
  245. };
  246. run_or_die('git', 'checkout', $branch);
  247. # Put the modified file in _this_ branch.
  248. rename($hidden, $target)
  249. or error("rename '$hidden' to '$target' failed: $!");
  250. # _Silently_ commit all modifications in the current branch.
  251. run_or_non('git', 'commit', '-m', $message, '-a');
  252. # ... and re-switch to master.
  253. run_or_die('git', 'checkout', $config{gitmaster_branch});
  254. # Attempt to merge without complaining.
  255. if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
  256. $conflict = readfile($target);
  257. run_or_die('git', 'reset', '--hard');
  258. }
  259. };
  260. my $failure = $@;
  261. # Process undo stack (in reverse order). By policy cleanup
  262. # actions should normally print a warning on failure.
  263. while (my $handle = pop @undo) {
  264. $handle->();
  265. }
  266. error("Git merge failed!\n$failure\n") if $failure;
  267. return $conflict;
  268. }
  269. {
  270. my $prefix;
  271. sub decode_git_file ($) {
  272. my $file=shift;
  273. # git does not output utf-8 filenames, but instead
  274. # double-quotes them with the utf-8 characters
  275. # escaped as \nnn\nnn.
  276. if ($file =~ m/^"(.*)"$/) {
  277. ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
  278. }
  279. # strip prefix if in a subdir
  280. if (! defined $prefix) {
  281. ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
  282. if (! defined $prefix) {
  283. $prefix="";
  284. }
  285. }
  286. $file =~ s/^\Q$prefix\E//;
  287. return decode("utf8", $file);
  288. }
  289. }
  290. sub parse_diff_tree ($) {
  291. # Parse the raw diff tree chunk and return the info hash.
  292. # See git-diff-tree(1) for the syntax.
  293. my $dt_ref = shift;
  294. # End of stream?
  295. return if !defined @{ $dt_ref } ||
  296. !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
  297. my %ci;
  298. # Header line.
  299. while (my $line = shift @{ $dt_ref }) {
  300. return if $line !~ m/^(.+) ($sha1_pattern)/;
  301. my $sha1 = $2;
  302. $ci{'sha1'} = $sha1;
  303. last;
  304. }
  305. # Identification lines for the commit.
  306. while (my $line = shift @{ $dt_ref }) {
  307. # Regexps are semi-stolen from gitweb.cgi.
  308. if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
  309. $ci{'tree'} = $1;
  310. }
  311. elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
  312. # XXX: collecting in reverse order
  313. push @{ $ci{'parents'} }, $1;
  314. }
  315. elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
  316. my ($who, $name, $epoch, $tz) =
  317. ($1, $2, $3, $4 );
  318. $ci{ $who } = $name;
  319. $ci{ "${who}_epoch" } = $epoch;
  320. $ci{ "${who}_tz" } = $tz;
  321. if ($name =~ m/^([^<]+)\s+<([^@>]+)/) {
  322. $ci{"${who}_name"} = $1;
  323. $ci{"${who}_username"} = $2;
  324. }
  325. elsif ($name =~ m/^([^<]+)\s+<>$/) {
  326. $ci{"${who}_username"} = $1;
  327. }
  328. else {
  329. $ci{"${who}_username"} = $name;
  330. }
  331. }
  332. elsif ($line =~ m/^$/) {
  333. # Trailing empty line signals next section.
  334. last;
  335. }
  336. }
  337. debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
  338. if (defined $ci{'parents'}) {
  339. $ci{'parent'} = @{ $ci{'parents'} }[0];
  340. }
  341. else {
  342. $ci{'parent'} = 0 x 40;
  343. }
  344. # Commit message (optional).
  345. while ($dt_ref->[0] =~ /^ /) {
  346. my $line = shift @{ $dt_ref };
  347. $line =~ s/^ //;
  348. push @{ $ci{'comment'} }, $line;
  349. }
  350. shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
  351. # Modified files.
  352. while (my $line = shift @{ $dt_ref }) {
  353. if ($line =~ m{^
  354. (:+) # number of parents
  355. ([^\t]+)\t # modes, sha1, status
  356. (.*) # file names
  357. $}xo) {
  358. my $num_parents = length $1;
  359. my @tmp = split(" ", $2);
  360. my ($file, $file_to) = split("\t", $3);
  361. my @mode_from = splice(@tmp, 0, $num_parents);
  362. my $mode_to = shift(@tmp);
  363. my @sha1_from = splice(@tmp, 0, $num_parents);
  364. my $sha1_to = shift(@tmp);
  365. my $status = shift(@tmp);
  366. if (length $file) {
  367. push @{ $ci{'details'} }, {
  368. 'file' => decode_git_file($file),
  369. 'sha1_from' => $sha1_from[0],
  370. 'sha1_to' => $sha1_to,
  371. 'mode_from' => $mode_from[0],
  372. 'mode_to' => $mode_to,
  373. 'status' => $status,
  374. };
  375. }
  376. next;
  377. };
  378. last;
  379. }
  380. return \%ci;
  381. }
  382. sub git_commit_info ($;$) {
  383. # Return an array of commit info hashes of num commits
  384. # starting from the given sha1sum.
  385. my ($sha1, $num) = @_;
  386. my @opts;
  387. push @opts, "--max-count=$num" if defined $num;
  388. my @raw_lines = run_or_die('git', 'log', @opts,
  389. '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
  390. '-r', $sha1, '--', '.');
  391. my @ci;
  392. while (my $parsed = parse_diff_tree(\@raw_lines)) {
  393. push @ci, $parsed;
  394. }
  395. warn "Cannot parse commit info for '$sha1' commit" if !@ci;
  396. return wantarray ? @ci : $ci[0];
  397. }
  398. sub git_sha1 (;$) {
  399. # Return head sha1sum (of given file).
  400. my $file = shift || q{--};
  401. # Ignore error since a non-existing file might be given.
  402. my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
  403. '--', $file);
  404. if ($sha1) {
  405. ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
  406. }
  407. else {
  408. debug("Empty sha1sum for '$file'.");
  409. }
  410. return defined $sha1 ? $sha1 : q{};
  411. }
  412. sub rcs_update () {
  413. # Update working directory.
  414. if (length $config{gitorigin_branch}) {
  415. run_or_cry('git', 'pull', '--prune', $config{gitorigin_branch});
  416. }
  417. }
  418. sub rcs_prepedit ($) {
  419. # Return the commit sha1sum of the file when editing begins.
  420. # This will be later used in rcs_commit if a merge is required.
  421. my ($file) = @_;
  422. return git_sha1($file);
  423. }
  424. sub rcs_commit (@) {
  425. # Try to commit the page; returns undef on _success_ and
  426. # a version of the page with the rcs's conflict markers on
  427. # failure.
  428. my %params=@_;
  429. # Check to see if the page has been changed by someone else since
  430. # rcs_prepedit was called.
  431. my $cur = git_sha1($params{file});
  432. my ($prev) = $params{token} =~ /^($sha1_pattern)$/; # untaint
  433. if (defined $cur && defined $prev && $cur ne $prev) {
  434. my $conflict = merge_past($prev, $params{file}, $dummy_commit_msg);
  435. return $conflict if defined $conflict;
  436. }
  437. return rcs_commit_helper(@_);
  438. }
  439. sub rcs_commit_staged (@) {
  440. # Commits all staged changes. Changes can be staged using rcs_add,
  441. # rcs_remove, and rcs_rename.
  442. return rcs_commit_helper(@_);
  443. }
  444. sub rcs_commit_helper (@) {
  445. my %params=@_;
  446. my %env=%ENV;
  447. if (defined $params{session}) {
  448. # Set the commit author and email based on web session info.
  449. my $u;
  450. if (defined $params{session}->param("name")) {
  451. $u=$params{session}->param("name");
  452. }
  453. elsif (defined $params{session}->remote_addr()) {
  454. $u=$params{session}->remote_addr();
  455. }
  456. if (defined $u) {
  457. $u=encode_utf8($u);
  458. $ENV{GIT_AUTHOR_NAME}=$u;
  459. }
  460. if (defined $params{session}->param("nickname")) {
  461. $u=encode_utf8($params{session}->param("nickname"));
  462. $u=~s/\s+/_/g;
  463. $u=~s/[^-_0-9[:alnum:]]+//g;
  464. }
  465. if (defined $u) {
  466. $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
  467. }
  468. }
  469. $params{message} = IkiWiki::possibly_foolish_untaint($params{message});
  470. my @opts;
  471. if ($params{message} !~ /\S/) {
  472. # Force git to allow empty commit messages.
  473. # (If this version of git supports it.)
  474. my ($version)=`git --version` =~ /git version (.*)/;
  475. if ($version ge "1.5.4") {
  476. push @opts, '--cleanup=verbatim';
  477. }
  478. else {
  479. $params{message}.=".";
  480. }
  481. }
  482. if (exists $params{file}) {
  483. push @opts, '--', $params{file};
  484. }
  485. # git commit returns non-zero if nothing really changed.
  486. # So we should ignore its exit status (hence run_or_non).
  487. if (run_or_non('git', 'commit', '-m', $params{message}, '-q', @opts)) {
  488. if (length $config{gitorigin_branch}) {
  489. run_or_cry('git', 'push', $config{gitorigin_branch});
  490. }
  491. }
  492. %ENV=%env;
  493. return undef; # success
  494. }
  495. sub rcs_add ($) {
  496. # Add file to archive.
  497. my ($file) = @_;
  498. run_or_cry('git', 'add', $file);
  499. }
  500. sub rcs_remove ($) {
  501. # Remove file from archive.
  502. my ($file) = @_;
  503. run_or_cry('git', 'rm', '-f', $file);
  504. }
  505. sub rcs_rename ($$) {
  506. my ($src, $dest) = @_;
  507. run_or_cry('git', 'mv', '-f', $src, $dest);
  508. }
  509. sub rcs_recentchanges ($) {
  510. # List of recent changes.
  511. my ($num) = @_;
  512. eval q{use Date::Parse};
  513. error($@) if $@;
  514. my @rets;
  515. foreach my $ci (git_commit_info('HEAD', $num || 1)) {
  516. # Skip redundant commits.
  517. next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
  518. my ($sha1, $when) = (
  519. $ci->{'sha1'},
  520. $ci->{'author_epoch'}
  521. );
  522. my @pages;
  523. foreach my $detail (@{ $ci->{'details'} }) {
  524. my $file = $detail->{'file'};
  525. my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
  526. $diffurl =~ s/\[\[file\]\]/$file/go;
  527. $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
  528. $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
  529. $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
  530. $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
  531. push @pages, {
  532. page => pagename($file),
  533. diffurl => $diffurl,
  534. };
  535. }
  536. my @messages;
  537. my $pastblank=0;
  538. foreach my $line (@{$ci->{'comment'}}) {
  539. $pastblank=1 if $line eq '';
  540. next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
  541. push @messages, { line => $line };
  542. }
  543. my $user=$ci->{'author_username'};
  544. my $web_commit = ($ci->{'author'} =~ /\@web>/);
  545. my $nickname;
  546. # Set nickname only if a non-url author_username is available,
  547. # and author_name is an url.
  548. if ($user !~ /:\/\// && defined $ci->{'author_name'} &&
  549. $ci->{'author_name'} =~ /:\/\//) {
  550. $nickname=$user;
  551. $user=$ci->{'author_name'};
  552. }
  553. # compatability code for old web commit messages
  554. if (! $web_commit &&
  555. defined $messages[0] &&
  556. $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
  557. $user = defined $2 ? "$2" : "$3";
  558. $messages[0]->{line} = $4;
  559. $web_commit=1;
  560. }
  561. push @rets, {
  562. rev => $sha1,
  563. user => $user,
  564. nickname => $nickname,
  565. committype => $web_commit ? "web" : "git",
  566. when => $when,
  567. message => [@messages],
  568. pages => [@pages],
  569. } if @pages;
  570. last if @rets >= $num;
  571. }
  572. return @rets;
  573. }
  574. sub rcs_diff ($;$) {
  575. my $rev=shift;
  576. my $maxlines=shift;
  577. my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
  578. my @lines;
  579. my $addlines=sub {
  580. my $line=shift;
  581. return if defined $maxlines && @lines == $maxlines;
  582. push @lines, $line."\n"
  583. if (@lines || $line=~/^diff --git/);
  584. return 1;
  585. };
  586. safe_git(undef, $addlines, "git", "show", $sha1);
  587. if (wantarray) {
  588. return @lines;
  589. }
  590. else {
  591. return join("", @lines);
  592. }
  593. }
  594. {
  595. my %time_cache;
  596. sub findtimes ($$) {
  597. my $file=shift;
  598. my $id=shift; # 0 = mtime ; 1 = ctime
  599. if (! keys %time_cache) {
  600. my $date;
  601. foreach my $line (run_or_die('git', 'log',
  602. '--pretty=format:%at',
  603. '--name-only', '--relative')) {
  604. if (! defined $date && $line =~ /^(\d+)$/) {
  605. $date=$line;
  606. }
  607. elsif (! length $line) {
  608. $date=undef;
  609. }
  610. else {
  611. my $f=decode_git_file($line);
  612. if (! $time_cache{$f}) {
  613. $time_cache{$f}[0]=$date; # mtime
  614. }
  615. $time_cache{$f}[1]=$date; # ctime
  616. }
  617. }
  618. }
  619. return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
  620. }
  621. }
  622. sub rcs_getctime ($) {
  623. my $file=shift;
  624. return findtimes($file, 1);
  625. }
  626. sub rcs_getmtime ($) {
  627. my $file=shift;
  628. return findtimes($file, 0);
  629. }
  630. {
  631. my $ret;
  632. sub git_find_root {
  633. # The wiki may not be the only thing in the git repo.
  634. # Determine if it is in a subdirectory by examining the srcdir,
  635. # and its parents, looking for the .git directory.
  636. return @$ret if defined $ret;
  637. my $subdir="";
  638. my $dir=$config{srcdir};
  639. while (! -d "$dir/.git") {
  640. $subdir=IkiWiki::basename($dir)."/".$subdir;
  641. $dir=IkiWiki::dirname($dir);
  642. if (! length $dir) {
  643. error("cannot determine root of git repo");
  644. }
  645. }
  646. $ret=[$subdir, $dir];
  647. return @$ret;
  648. }
  649. }
  650. sub git_parse_changes {
  651. my @changes = @_;
  652. my ($subdir, $rootdir) = git_find_root();
  653. my @rets;
  654. foreach my $ci (@changes) {
  655. foreach my $detail (@{ $ci->{'details'} }) {
  656. my $file = $detail->{'file'};
  657. # check that all changed files are in the subdir
  658. if (length $subdir &&
  659. ! ($file =~ s/^\Q$subdir\E//)) {
  660. error sprintf(gettext("you are not allowed to change %s"), $file);
  661. }
  662. my ($action, $mode, $path);
  663. if ($detail->{'status'} =~ /^[M]+\d*$/) {
  664. $action="change";
  665. $mode=$detail->{'mode_to'};
  666. }
  667. elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
  668. $action="add";
  669. $mode=$detail->{'mode_to'};
  670. }
  671. elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
  672. $action="remove";
  673. $mode=$detail->{'mode_from'};
  674. }
  675. else {
  676. error "unknown status ".$detail->{'status'};
  677. }
  678. # test that the file mode is ok
  679. if ($mode !~ /^100[64][64][64]$/) {
  680. error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
  681. }
  682. if ($action eq "change") {
  683. if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
  684. error gettext("you are not allowed to change file modes");
  685. }
  686. }
  687. # extract attachment to temp file
  688. if (($action eq 'add' || $action eq 'change') &&
  689. ! pagetype($file)) {
  690. eval q{use File::Temp};
  691. die $@ if $@;
  692. my $fh;
  693. ($fh, $path)=File::Temp::tempfile(undef, UNLINK => 1);
  694. my $cmd = "cd $git_dir && ".
  695. "git show $detail->{sha1_to} > '$path'";
  696. if (system($cmd) != 0) {
  697. error("failed writing temp file '$path'.");
  698. }
  699. }
  700. push @rets, {
  701. file => $file,
  702. action => $action,
  703. path => $path,
  704. };
  705. }
  706. }
  707. return @rets;
  708. }
  709. sub rcs_receive () {
  710. my @rets;
  711. while (<>) {
  712. chomp;
  713. my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
  714. # only allow changes to gitmaster_branch
  715. if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
  716. error sprintf(gettext("you are not allowed to change %s"), $refname);
  717. }
  718. # Avoid chdir when running git here, because the changes
  719. # are in the master git repo, not the srcdir repo.
  720. # (Also, if a subdir is involved, we don't want to chdir to
  721. # it and only see changes in it.)
  722. # The pre-receive hook already puts us in the right place.
  723. $git_dir=".";
  724. push @rets, git_parse_changes(git_commit_info($oldrev."..".$newrev));
  725. $git_dir=undef;
  726. }
  727. return reverse @rets;
  728. }
  729. sub rcs_preprevert ($) {
  730. my $rev=shift;
  731. my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
  732. # Examine changes from root of git repo, not from any subdir,
  733. # in order to see all changes.
  734. my ($subdir, $rootdir) = git_find_root();
  735. $git_dir=$rootdir;
  736. my @commits=git_commit_info($sha1, 1);
  737. if (! @commits) {
  738. error "unknown commit"; # just in case
  739. }
  740. # git revert will fail on merge commits. Add a nice message.
  741. if (exists $commits[0]->{parents} &&
  742. @{$commits[0]->{parents}} > 1) {
  743. error gettext("you are not allowed to revert a merge");
  744. }
  745. my @ret=git_parse_changes(@commits);
  746. $git_dir=undef;
  747. return @ret;
  748. }
  749. sub rcs_revert ($) {
  750. # Try to revert the given rev; returns undef on _success_.
  751. my $rev = shift;
  752. my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
  753. if (run_or_non('git', 'revert', '--no-commit', $sha1)) {
  754. return undef;
  755. }
  756. else {
  757. run_or_die('git', 'reset', '--hard');
  758. return sprintf(gettext("Failed to revert commit %s"), $sha1);
  759. }
  760. }
  761. 1