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