summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/git.pm
blob: 0f92476c94403df7b52a28f62e0f4a17d5988794 (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. }
  450. if (defined $u) {
  451. $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
  452. }
  453. }
  454. $params{message} = IkiWiki::possibly_foolish_untaint($params{message});
  455. my @opts;
  456. if ($params{message} !~ /\S/) {
  457. # Force git to allow empty commit messages.
  458. # (If this version of git supports it.)
  459. my ($version)=`git --version` =~ /git version (.*)/;
  460. if ($version ge "1.5.4") {
  461. push @opts, '--cleanup=verbatim';
  462. }
  463. else {
  464. $params{message}.=".";
  465. }
  466. }
  467. push @opts, '-q';
  468. # git commit returns non-zero if file has not been really changed.
  469. # so we should ignore its exit status (hence run_or_non).
  470. if (run_or_non('git', 'commit', @opts, '-m', $params{message})) {
  471. if (length $config{gitorigin_branch}) {
  472. run_or_cry('git', 'push', $config{gitorigin_branch});
  473. }
  474. }
  475. %ENV=%env;
  476. return undef; # success
  477. }
  478. sub rcs_add ($) {
  479. # Add file to archive.
  480. my ($file) = @_;
  481. run_or_cry('git', 'add', $file);
  482. }
  483. sub rcs_remove ($) {
  484. # Remove file from archive.
  485. my ($file) = @_;
  486. run_or_cry('git', 'rm', '-f', $file);
  487. }
  488. sub rcs_rename ($$) {
  489. my ($src, $dest) = @_;
  490. run_or_cry('git', 'mv', '-f', $src, $dest);
  491. }
  492. sub rcs_recentchanges ($) {
  493. # List of recent changes.
  494. my ($num) = @_;
  495. eval q{use Date::Parse};
  496. error($@) if $@;
  497. my @rets;
  498. foreach my $ci (git_commit_info('HEAD', $num || 1)) {
  499. # Skip redundant commits.
  500. next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
  501. my ($sha1, $when) = (
  502. $ci->{'sha1'},
  503. $ci->{'author_epoch'}
  504. );
  505. my @pages;
  506. foreach my $detail (@{ $ci->{'details'} }) {
  507. my $file = $detail->{'file'};
  508. my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
  509. $diffurl =~ s/\[\[file\]\]/$file/go;
  510. $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
  511. $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
  512. $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
  513. $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
  514. push @pages, {
  515. page => pagename($file),
  516. diffurl => $diffurl,
  517. };
  518. }
  519. my @messages;
  520. my $pastblank=0;
  521. foreach my $line (@{$ci->{'comment'}}) {
  522. $pastblank=1 if $line eq '';
  523. next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
  524. push @messages, { line => $line };
  525. }
  526. my $user=$ci->{'author_username'};
  527. my $web_commit = ($ci->{'author'} =~ /\@web>/);
  528. my $nickname;
  529. # Set nickname only if a non-url author_username is available,
  530. # and author_name is an url.
  531. if ($user !~ /:\/\// && defined $ci->{'author_name'} &&
  532. $ci->{'author_name'} =~ /:\/\//) {
  533. $nickname=$user;
  534. $user=$ci->{'author_name'};
  535. }
  536. # compatability code for old web commit messages
  537. if (! $web_commit &&
  538. defined $messages[0] &&
  539. $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
  540. $user = defined $2 ? "$2" : "$3";
  541. $messages[0]->{line} = $4;
  542. $web_commit=1;
  543. }
  544. push @rets, {
  545. rev => $sha1,
  546. user => $user,
  547. nickname => $nickname,
  548. committype => $web_commit ? "web" : "git",
  549. when => $when,
  550. message => [@messages],
  551. pages => [@pages],
  552. } if @pages;
  553. last if @rets >= $num;
  554. }
  555. return @rets;
  556. }
  557. sub rcs_diff ($) {
  558. my $rev=shift;
  559. my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
  560. my @lines;
  561. foreach my $line (run_or_non("git", "show", $sha1)) {
  562. if (@lines || $line=~/^diff --git/) {
  563. push @lines, $line."\n";
  564. }
  565. }
  566. if (wantarray) {
  567. return @lines;
  568. }
  569. else {
  570. return join("", @lines);
  571. }
  572. }
  573. {
  574. my %time_cache;
  575. sub findtimes ($$) {
  576. my $file=shift;
  577. my $id=shift; # 0 = mtime ; 1 = ctime
  578. if (! keys %time_cache) {
  579. my $date;
  580. foreach my $line (run_or_die('git', 'log',
  581. '--pretty=format:%ct',
  582. '--name-only', '--relative')) {
  583. if (! defined $date && $line =~ /^(\d+)$/) {
  584. $date=$line;
  585. }
  586. elsif (! length $line) {
  587. $date=undef;
  588. }
  589. else {
  590. my $f=decode_git_file($line);
  591. if (! $time_cache{$f}) {
  592. $time_cache{$f}[0]=$date; # mtime
  593. }
  594. $time_cache{$f}[1]=$date; # ctime
  595. }
  596. }
  597. }
  598. return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
  599. }
  600. }
  601. sub rcs_getctime ($) {
  602. my $file=shift;
  603. return findtimes($file, 1);
  604. }
  605. sub rcs_getmtime ($) {
  606. my $file=shift;
  607. return findtimes($file, 0);
  608. }
  609. sub rcs_receive () {
  610. # The wiki may not be the only thing in the git repo.
  611. # Determine if it is in a subdirectory by examining the srcdir,
  612. # and its parents, looking for the .git directory.
  613. my $subdir="";
  614. my $dir=$config{srcdir};
  615. while (! -d "$dir/.git") {
  616. $subdir=IkiWiki::basename($dir)."/".$subdir;
  617. $dir=IkiWiki::dirname($dir);
  618. if (! length $dir) {
  619. error("cannot determine root of git repo");
  620. }
  621. }
  622. my @rets;
  623. while (<>) {
  624. chomp;
  625. my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
  626. # only allow changes to gitmaster_branch
  627. if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
  628. error sprintf(gettext("you are not allowed to change %s"), $refname);
  629. }
  630. # Avoid chdir when running git here, because the changes
  631. # are in the master git repo, not the srcdir repo.
  632. # The pre-recieve hook already puts us in the right place.
  633. $no_chdir=1;
  634. my @changes=git_commit_info($oldrev."..".$newrev);
  635. $no_chdir=0;
  636. foreach my $ci (@changes) {
  637. foreach my $detail (@{ $ci->{'details'} }) {
  638. my $file = $detail->{'file'};
  639. # check that all changed files are in the
  640. # subdir
  641. if (length $subdir &&
  642. ! ($file =~ s/^\Q$subdir\E//)) {
  643. error sprintf(gettext("you are not allowed to change %s"), $file);
  644. }
  645. my ($action, $mode, $path);
  646. if ($detail->{'status'} =~ /^[M]+\d*$/) {
  647. $action="change";
  648. $mode=$detail->{'mode_to'};
  649. }
  650. elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
  651. $action="add";
  652. $mode=$detail->{'mode_to'};
  653. }
  654. elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
  655. $action="remove";
  656. $mode=$detail->{'mode_from'};
  657. }
  658. else {
  659. error "unknown status ".$detail->{'status'};
  660. }
  661. # test that the file mode is ok
  662. if ($mode !~ /^100[64][64][64]$/) {
  663. error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
  664. }
  665. if ($action eq "change") {
  666. if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
  667. error gettext("you are not allowed to change file modes");
  668. }
  669. }
  670. # extract attachment to temp file
  671. if (($action eq 'add' || $action eq 'change') &&
  672. ! pagetype($file)) {
  673. eval q{use File::Temp};
  674. die $@ if $@;
  675. my $fh;
  676. ($fh, $path)=File::Temp::tempfile("XXXXXXXXXX", UNLINK => 1);
  677. if (system("git show ".$detail->{sha1_to}." > '$path'") != 0) {
  678. error("failed writing temp file");
  679. }
  680. }
  681. push @rets, {
  682. file => $file,
  683. action => $action,
  684. path => $path,
  685. };
  686. }
  687. }
  688. }
  689. return reverse @rets;
  690. }
  691. 1