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