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