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