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