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