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