summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/git.pm
blob: 3fa29b22f78b6f47ea27b2f79950782b9ef03223 (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. rcs_add($params{file});
  432. return rcs_commit_staged(
  433. message => $params{message},
  434. session => $params{session},
  435. );
  436. }
  437. sub rcs_commit_staged (@) {
  438. # Commits all staged changes. Changes can be staged using rcs_add,
  439. # rcs_remove, and rcs_rename.
  440. my %params=@_;
  441. my %env=%ENV;
  442. if (defined $params{session}) {
  443. # Set the commit author and email based on web session info.
  444. my $u;
  445. if (defined $params{session}->param("name")) {
  446. $u=$params{session}->param("name");
  447. }
  448. elsif (defined $params{session}->remote_addr()) {
  449. $u=$params{session}->remote_addr();
  450. }
  451. if (defined $u) {
  452. $u=encode_utf8($u);
  453. $ENV{GIT_AUTHOR_NAME}=$u;
  454. }
  455. if (defined $params{session}->param("nickname")) {
  456. $u=encode_utf8($params{session}->param("nickname"));
  457. $u=~s/\s+/_/g;
  458. $u=~s/[^-_0-9[:alnum:]]+//g;
  459. }
  460. if (defined $u) {
  461. $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
  462. }
  463. }
  464. $params{message} = IkiWiki::possibly_foolish_untaint($params{message});
  465. my @opts;
  466. if ($params{message} !~ /\S/) {
  467. # Force git to allow empty commit messages.
  468. # (If this version of git supports it.)
  469. my ($version)=`git --version` =~ /git version (.*)/;
  470. if ($version ge "1.5.4") {
  471. push @opts, '--cleanup=verbatim';
  472. }
  473. else {
  474. $params{message}.=".";
  475. }
  476. }
  477. push @opts, '-q';
  478. # git commit returns non-zero if file has not been really changed.
  479. # so we should ignore its exit status (hence run_or_non).
  480. if (run_or_non('git', 'commit', @opts, '-m', $params{message})) {
  481. if (length $config{gitorigin_branch}) {
  482. run_or_cry('git', 'push', $config{gitorigin_branch});
  483. }
  484. }
  485. %ENV=%env;
  486. return undef; # success
  487. }
  488. sub rcs_add ($) {
  489. # Add file to archive.
  490. my ($file) = @_;
  491. run_or_cry('git', 'add', $file);
  492. }
  493. sub rcs_remove ($) {
  494. # Remove file from archive.
  495. my ($file) = @_;
  496. run_or_cry('git', 'rm', '-f', $file);
  497. }
  498. sub rcs_rename ($$) {
  499. my ($src, $dest) = @_;
  500. run_or_cry('git', 'mv', '-f', $src, $dest);
  501. }
  502. sub rcs_recentchanges ($) {
  503. # List of recent changes.
  504. my ($num) = @_;
  505. eval q{use Date::Parse};
  506. error($@) if $@;
  507. my @rets;
  508. foreach my $ci (git_commit_info('HEAD', $num || 1)) {
  509. # Skip redundant commits.
  510. next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
  511. my ($sha1, $when) = (
  512. $ci->{'sha1'},
  513. $ci->{'author_epoch'}
  514. );
  515. my @pages;
  516. foreach my $detail (@{ $ci->{'details'} }) {
  517. my $file = $detail->{'file'};
  518. my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
  519. $diffurl =~ s/\[\[file\]\]/$file/go;
  520. $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
  521. $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
  522. $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
  523. $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
  524. push @pages, {
  525. page => pagename($file),
  526. diffurl => $diffurl,
  527. };
  528. }
  529. my @messages;
  530. my $pastblank=0;
  531. foreach my $line (@{$ci->{'comment'}}) {
  532. $pastblank=1 if $line eq '';
  533. next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
  534. push @messages, { line => $line };
  535. }
  536. my $user=$ci->{'author_username'};
  537. my $web_commit = ($ci->{'author'} =~ /\@web>/);
  538. my $nickname;
  539. # Set nickname only if a non-url author_username is available,
  540. # and author_name is an url.
  541. if ($user !~ /:\/\// && defined $ci->{'author_name'} &&
  542. $ci->{'author_name'} =~ /:\/\//) {
  543. $nickname=$user;
  544. $user=$ci->{'author_name'};
  545. }
  546. # compatability code for old web commit messages
  547. if (! $web_commit &&
  548. defined $messages[0] &&
  549. $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
  550. $user = defined $2 ? "$2" : "$3";
  551. $messages[0]->{line} = $4;
  552. $web_commit=1;
  553. }
  554. push @rets, {
  555. rev => $sha1,
  556. user => $user,
  557. nickname => $nickname,
  558. committype => $web_commit ? "web" : "git",
  559. when => $when,
  560. message => [@messages],
  561. pages => [@pages],
  562. } if @pages;
  563. last if @rets >= $num;
  564. }
  565. return @rets;
  566. }
  567. sub rcs_diff ($) {
  568. my $rev=shift;
  569. my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
  570. my @lines;
  571. foreach my $line (run_or_non("git", "show", $sha1)) {
  572. if (@lines || $line=~/^diff --git/) {
  573. push @lines, $line."\n";
  574. }
  575. }
  576. if (wantarray) {
  577. return @lines;
  578. }
  579. else {
  580. return join("", @lines);
  581. }
  582. }
  583. {
  584. my %time_cache;
  585. sub findtimes ($$) {
  586. my $file=shift;
  587. my $id=shift; # 0 = mtime ; 1 = ctime
  588. if (! keys %time_cache) {
  589. my $date;
  590. foreach my $line (run_or_die('git', 'log',
  591. '--pretty=format:%at',
  592. '--name-only', '--relative')) {
  593. if (! defined $date && $line =~ /^(\d+)$/) {
  594. $date=$line;
  595. }
  596. elsif (! length $line) {
  597. $date=undef;
  598. }
  599. else {
  600. my $f=decode_git_file($line);
  601. if (! $time_cache{$f}) {
  602. $time_cache{$f}[0]=$date; # mtime
  603. }
  604. $time_cache{$f}[1]=$date; # ctime
  605. }
  606. }
  607. }
  608. return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
  609. }
  610. }
  611. sub rcs_getctime ($) {
  612. my $file=shift;
  613. return findtimes($file, 1);
  614. }
  615. sub rcs_getmtime ($) {
  616. my $file=shift;
  617. return findtimes($file, 0);
  618. }
  619. {
  620. my $ret;
  621. sub git_find_root {
  622. # The wiki may not be the only thing in the git repo.
  623. # Determine if it is in a subdirectory by examining the srcdir,
  624. # and its parents, looking for the .git directory.
  625. return @$ret if defined $ret;
  626. my $subdir="";
  627. my $dir=$config{srcdir};
  628. while (! -d "$dir/.git") {
  629. $subdir=IkiWiki::basename($dir)."/".$subdir;
  630. $dir=IkiWiki::dirname($dir);
  631. if (! length $dir) {
  632. error("cannot determine root of git repo");
  633. }
  634. }
  635. $ret=[$subdir, $dir];
  636. return @$ret;
  637. }
  638. }
  639. sub git_parse_changes {
  640. my @changes = @_;
  641. my ($subdir, $rootdir) = git_find_root();
  642. my @rets;
  643. foreach my $ci (@changes) {
  644. foreach my $detail (@{ $ci->{'details'} }) {
  645. my $file = $detail->{'file'};
  646. # check that all changed files are in the subdir
  647. if (length $subdir &&
  648. ! ($file =~ s/^\Q$subdir\E//)) {
  649. error sprintf(gettext("you are not allowed to change %s"), $file);
  650. }
  651. my ($action, $mode, $path);
  652. if ($detail->{'status'} =~ /^[M]+\d*$/) {
  653. $action="change";
  654. $mode=$detail->{'mode_to'};
  655. }
  656. elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
  657. $action="add";
  658. $mode=$detail->{'mode_to'};
  659. }
  660. elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
  661. $action="remove";
  662. $mode=$detail->{'mode_from'};
  663. }
  664. else {
  665. error "unknown status ".$detail->{'status'};
  666. }
  667. # test that the file mode is ok
  668. if ($mode !~ /^100[64][64][64]$/) {
  669. error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
  670. }
  671. if ($action eq "change") {
  672. if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
  673. error gettext("you are not allowed to change file modes");
  674. }
  675. }
  676. # extract attachment to temp file
  677. if (($action eq 'add' || $action eq 'change') &&
  678. ! pagetype($file)) {
  679. eval q{use File::Temp};
  680. die $@ if $@;
  681. my $fh;
  682. ($fh, $path)=File::Temp::tempfile("XXXXXXXXXX", UNLINK => 1);
  683. my $cmd = "cd $git_dir && ".
  684. "git show $detail->{sha1_to} > '$path'";
  685. if (system($cmd) != 0) {
  686. error("failed writing temp file '$path'.");
  687. }
  688. }
  689. push @rets, {
  690. file => $file,
  691. action => $action,
  692. path => $path,
  693. };
  694. }
  695. }
  696. return @rets;
  697. }
  698. sub rcs_receive () {
  699. my @rets;
  700. while (<>) {
  701. chomp;
  702. my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
  703. # only allow changes to gitmaster_branch
  704. if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
  705. error sprintf(gettext("you are not allowed to change %s"), $refname);
  706. }
  707. # Avoid chdir when running git here, because the changes
  708. # are in the master git repo, not the srcdir repo.
  709. # (Also, if a subdir is involved, we don't want to chdir to
  710. # it and only see changes in it.)
  711. # The pre-receive hook already puts us in the right place.
  712. $git_dir=".";
  713. push @rets, git_parse_changes(git_commit_info($oldrev."..".$newrev));
  714. $git_dir=undef;
  715. }
  716. return reverse @rets;
  717. }
  718. sub rcs_preprevert ($) {
  719. my $rev=shift;
  720. my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
  721. # Examine changes from root of git repo, not from any subdir,
  722. # in order to see all changes.
  723. my ($subdir, $rootdir) = git_find_root();
  724. $git_dir=$rootdir;
  725. my @commits=git_commit_info($sha1, 1);
  726. $git_dir=undef;
  727. if (! @commits) {
  728. error "unknown commit"; # just in case
  729. }
  730. # git revert will fail on merge commits. Add a nice message.
  731. if (exists $commits[0]->{parents} &&
  732. @{$commits[0]->{parents}} > 1) {
  733. error gettext("you are not allowed to revert a merge");
  734. }
  735. return git_parse_changes(@commits);
  736. }
  737. sub rcs_revert ($) {
  738. # Try to revert the given rev; returns undef on _success_.
  739. my $rev = shift;
  740. my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
  741. if (run_or_non('git', 'revert', '--no-commit', $sha1)) {
  742. return undef;
  743. }
  744. else {
  745. run_or_die('git', 'reset', '--hard');
  746. return sprintf(gettext("Failed to revert commit %s"), $sha1);
  747. }
  748. }
  749. 1