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