2 package IkiWiki::Plugin::git;
8 use File::Path qw{remove_tree};
9 use URI::Escape q{uri_escape_utf8};
10 use open qw{:utf8 :std};
12 my $sha1_pattern = qr/[0-9a-fA-F]{40}/; # pattern to validate Git sha1sums
13 my $dummy_commit_msg = 'dummy commit'; # message to skip in recent changes
16 hook(type => "checkconfig", id => "git", call => \&checkconfig);
17 hook(type => "getsetup", id => "git", call => \&getsetup);
18 hook(type => "genwrapper", id => "git", call => \&genwrapper);
19 hook(type => "rcs", id => "rcs_update", call => \&rcs_update);
20 hook(type => "rcs", id => "rcs_prepedit", call => \&rcs_prepedit);
21 hook(type => "rcs", id => "rcs_commit", call => \&rcs_commit);
22 hook(type => "rcs", id => "rcs_commit_staged", call => \&rcs_commit_staged);
23 hook(type => "rcs", id => "rcs_add", call => \&rcs_add);
24 hook(type => "rcs", id => "rcs_remove", call => \&rcs_remove);
25 hook(type => "rcs", id => "rcs_rename", call => \&rcs_rename);
26 hook(type => "rcs", id => "rcs_recentchanges", call => \&rcs_recentchanges);
27 hook(type => "rcs", id => "rcs_diff", call => \&rcs_diff);
28 hook(type => "rcs", id => "rcs_getctime", call => \&rcs_getctime);
29 hook(type => "rcs", id => "rcs_getmtime", call => \&rcs_getmtime);
30 hook(type => "rcs", id => "rcs_receive", call => \&rcs_receive);
31 hook(type => "rcs", id => "rcs_preprevert", call => \&rcs_preprevert);
32 hook(type => "rcs", id => "rcs_revert", call => \&rcs_revert);
33 hook(type => "rcs", id => "rcs_find_changes", call => \&rcs_find_changes);
34 hook(type => "rcs", id => "rcs_get_current_rev", call => \&rcs_get_current_rev);
38 if (! defined $config{gitorigin_branch}) {
39 $config{gitorigin_branch}="origin";
41 if (! defined $config{gitmaster_branch}) {
42 $config{gitmaster_branch}="master";
44 if (defined $config{git_wrapper} &&
45 length $config{git_wrapper}) {
46 push @{$config{wrappers}}, {
47 wrapper => $config{git_wrapper},
48 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
49 wrapper_background_command => $config{git_wrapper_background_command},
53 if (defined $config{git_test_receive_wrapper} &&
54 length $config{git_test_receive_wrapper} &&
55 defined $config{untrusted_committers} &&
56 @{$config{untrusted_committers}}) {
57 push @{$config{wrappers}}, {
59 wrapper => $config{git_test_receive_wrapper},
60 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
64 # Avoid notes, parser does not handle and they only slow things down.
65 $ENV{GIT_NOTES_REF}="";
67 # Run receive test only if being called by the wrapper, and not
68 # when generating same.
69 if ($config{test_receive} && ! exists $config{wrapper}) {
70 require IkiWiki::Receive;
71 IkiWiki::Receive::test();
78 safe => 0, # rcs plugin
84 example => "/git/wiki.git/hooks/post-update",
85 description => "git hook to generate",
89 git_wrapper_background_command => {
91 example => "git push github",
92 description => "shell command for git_wrapper to run, in the background",
99 description => "mode for git_wrapper (can safely be made suid)",
103 git_test_receive_wrapper => {
105 example => "/git/wiki.git/hooks/pre-receive",
106 description => "git pre-receive hook to generate",
110 untrusted_committers => {
113 description => "unix users whose commits should be checked by the pre-receive hook",
119 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]];hb=HEAD",
120 description => "gitweb url to show file history ([[file]] substituted)",
126 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]]",
127 description => "gitweb url to show a diff ([[file]], [[sha1_to]], [[sha1_from]], [[sha1_commit]], and [[sha1_parent]] substituted)",
131 gitorigin_branch => {
134 description => "where to pull and push changes (set to empty string to disable)",
135 safe => 0, # paranoia
138 gitmaster_branch => {
141 description => "branch that the wiki is stored in",
142 safe => 0, # paranoia
148 if ($config{test_receive}) {
149 require IkiWiki::Receive;
150 return IkiWiki::Receive::genwrapper();
157 # Loosely based on git-new-workdir from git contrib.
158 sub create_temp_working_dir ($$) {
161 my $working = "$rootdir/.git/ikiwiki-temp-working";
162 remove_tree($working);
164 foreach my $dir ("", ".git") {
165 if (!mkdir("$working/$dir")) {
166 error("Unable to create $working/$dir: $!");
170 # Hooks are deliberately not included: we will commit to the temporary
171 # branch that is used in the temporary working tree, and we don't want
172 # to run the post-commit hook there.
174 # logs/refs is not included because we don't use the reflog.
175 # remotes, rr-cache, svn are similarly excluded.
176 foreach my $link ("config", "refs", "objects", "info", "packed-refs") {
177 if (!symlink("../../$link", "$working/.git/$link")) {
178 error("Unable to create symlink $working/.git/$link: $!");
182 open (my $out, '>', "$working/.git/HEAD") or
183 error("failed to write $working.git/HEAD: $!");
184 print $out "ref: refs/heads/$branch\n" or
185 error("failed to write $working.git/HEAD: $!");
187 error("failed to write $working.git/HEAD: $!");
192 # Start a child process safely without resorting to /bin/sh.
193 # Returns command output (in list content) or success state
194 # (in scalar context), or runs the specified data handler.
198 my $pid = open my $OUT, "-|";
200 error("Working directory not specified") unless defined $params{chdir};
201 error("Cannot fork: $!") if !defined $pid;
205 # Git commands want to be in wc.
206 if ($params{chdir} ne '.') {
208 or error("cannot chdir to $params{chdir}: $!");
211 if ($params{stdout}) {
212 open(STDOUT, '>&', $params{stdout}) or error("Cannot reopen stdout: $!");
215 exec @{$params{cmdline}} or error("Cannot exec '@{$params{cmdline}}': $!");
219 # git output is probably utf-8 encoded, but may contain
220 # other encodings or invalidly encoded stuff. So do not rely
221 # on the normal utf-8 IO layer, decode it by hand.
226 $_=decode_utf8($_, 0);
230 if (! defined $params{data_handler}) {
234 last unless $params{data_handler}->($_);
240 $params{error_handler}->("'@{$params{cmdline}}' failed: $!") if $? && $params{error_handler};
242 return wantarray ? @lines : ($? == 0);
244 # Convenient wrappers.
245 sub run_or_die_in ($$@) {
247 safe_git(chdir => $dir, error_handler => \&error, cmdline => \@_);
249 sub run_or_cry_in ($$@) {
251 safe_git(chdir => $dir, error_handler => sub { warn @_ }, cmdline => \@_);
253 sub run_or_non_in ($$@) {
255 safe_git(chdir => $dir, cmdline => \@_);
258 sub ensure_committer ($) {
261 if (! length $ENV{GIT_AUTHOR_NAME} || ! length $ENV{GIT_COMMITTER_NAME}) {
262 my $name = join('', run_or_non_in($dir, "git", "config", "user.name"));
263 if (! length $name) {
264 run_or_die_in($dir, "git", "config", "user.name", "IkiWiki");
268 if (! length $ENV{GIT_AUTHOR_EMAIL} || ! length $ENV{GIT_COMMITTER_EMAIL}) {
269 my $email = join('', run_or_non_in($dir, "git", "config", "user.email"));
270 if (! length $email) {
271 run_or_die_in($dir, "git", "config", "user.email", "ikiwiki.info");
276 sub merge_past ($$$) {
277 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
278 # Git merge commands work with the committed changes, except in the
279 # implicit case of '-m' of git checkout(1). So we should invent a
280 # kludge here. In principle, we need to create a throw-away branch
281 # in preparing for the merge itself. Since branches are cheap (and
282 # branching is fast), this shouldn't cost high.
284 # The main problem is the presence of _uncommitted_ local changes. One
285 # possible approach to get rid of this situation could be that we first
286 # make a temporary commit in the master branch and later restore the
287 # initial state (this is possible since Git has the ability to undo a
288 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
291 # - create a diff of HEAD:current-sha1
293 # - create a dummy branch and switch to it
294 # - rewind to past (reset --hard to the current-sha1)
295 # - apply the diff and commit
296 # - switch to master and do the merge with the dummy branch
297 # - make a soft reset (undo the last commit of master)
299 # The above method has some drawbacks: (1) it needs a redundant commit
300 # just to get rid of local changes, (2) somewhat slow because of the
301 # required system forks. Until someone points a more straight method
302 # (which I would be grateful) I have implemented an alternative method.
303 # In this approach, we hide all the modified files from Git by renaming
304 # them (using the 'rename' builtin) and later restore those files in
305 # the throw-away branch (that is, we put the files themselves instead
306 # of applying a patch).
308 my ($sha1, $file, $message) = @_;
310 my @undo; # undo stack for cleanup in case of an error
311 my $conflict; # file content with conflict markers
313 ensure_committer($config{srcdir});
316 # Hide local changes from Git by renaming the modified file.
317 # Relative paths must be converted to absolute for renaming.
318 my ($target, $hidden) = (
319 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
321 rename($target, $hidden)
322 or error("rename '$target' to '$hidden' failed: $!");
323 # Ensure to restore the renamed file on error.
325 return if ! -e "$hidden"; # already renamed
326 rename($hidden, $target)
327 or warn "rename '$hidden' to '$target' failed: $!";
330 my $branch = "throw_away_${sha1}"; # supposed to be unique
332 # Create a throw-away branch and rewind backward.
333 push @undo, sub { run_or_cry_in($config{srcdir}, 'git', 'branch', '-D', $branch) };
334 run_or_die_in($config{srcdir}, 'git', 'branch', $branch, $sha1);
336 # Switch to throw-away branch for the merge operation.
338 if (!run_or_cry_in($config{srcdir}, 'git', 'checkout', $config{gitmaster_branch})) {
339 run_or_cry_in($config{srcdir}, 'git', 'checkout','-f',$config{gitmaster_branch});
342 run_or_die_in($config{srcdir}, 'git', 'checkout', $branch);
344 # Put the modified file in _this_ branch.
345 rename($hidden, $target)
346 or error("rename '$hidden' to '$target' failed: $!");
348 # _Silently_ commit all modifications in the current branch.
349 run_or_non_in($config{srcdir}, 'git', 'commit', '-m', $message, '-a');
350 # ... and re-switch to master.
351 run_or_die_in($config{srcdir}, 'git', 'checkout', $config{gitmaster_branch});
353 # Attempt to merge without complaining.
354 if (!run_or_non_in($config{srcdir}, 'git', 'pull', '--no-commit', '.', $branch)) {
355 $conflict = readfile($target);
356 run_or_die_in($config{srcdir}, 'git', 'reset', '--hard');
361 # Process undo stack (in reverse order). By policy cleanup
362 # actions should normally print a warning on failure.
363 while (my $handle = pop @undo) {
367 error("Git merge failed!\n$failure\n") if $failure;
375 sub decode_git_file ($$) {
379 # git does not output utf-8 filenames, but instead
380 # double-quotes them with the utf-8 characters
381 # escaped as \nnn\nnn.
382 if ($file =~ m/^"(.*)"$/) {
383 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
386 # strip prefix if in a subdir
387 if (! defined $prefix_cache{$dir}) {
388 ($prefix_cache{$dir}) = run_or_die_in($dir, 'git', 'rev-parse', '--show-prefix');
389 if (! defined $prefix_cache{$dir}) {
390 $prefix_cache{$dir}="";
393 $file =~ s/^\Q$prefix_cache{$dir}\E//;
395 return decode("utf8", $file);
399 sub parse_diff_tree ($$) {
400 # Parse the raw diff tree chunk and return the info hash.
401 # See git-diff-tree(1) for the syntax.
406 return if ! @{ $dt_ref } ||
407 !defined $dt_ref->[0] || !length $dt_ref->[0];
411 while (my $line = shift @{ $dt_ref }) {
412 return if $line !~ m/^(.+) ($sha1_pattern)/;
419 # Identification lines for the commit.
420 while (my $line = shift @{ $dt_ref }) {
421 # Regexps are semi-stolen from gitweb.cgi.
422 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
425 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
426 # XXX: collecting in reverse order
427 push @{ $ci{'parents'} }, $1;
429 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
430 my ($who, $name, $epoch, $tz) =
434 $ci{ "${who}_epoch" } = $epoch;
435 $ci{ "${who}_tz" } = $tz;
437 if ($name =~ m/^([^<]+)\s+<([^@>]+)/) {
438 $ci{"${who}_name"} = $1;
439 $ci{"${who}_username"} = $2;
441 elsif ($name =~ m/^([^<]+)\s+<>$/) {
442 $ci{"${who}_username"} = $1;
445 $ci{"${who}_username"} = $name;
448 elsif ($line =~ m/^$/) {
449 # Trailing empty line signals next section.
454 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
456 if (defined $ci{'parents'}) {
457 $ci{'parent'} = @{ $ci{'parents'} }[0];
460 $ci{'parent'} = 0 x 40;
463 # Commit message (optional).
464 while ($dt_ref->[0] =~ /^ /) {
465 my $line = shift @{ $dt_ref };
467 push @{ $ci{'comment'} }, $line;
469 shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
471 $ci{details} = [parse_changed_files($dir, $dt_ref)];
476 sub parse_changed_files ($$) {
483 while (my $line = shift @{ $dt_ref }) {
485 (:+) # number of parents
486 ([^\t]+)\t # modes, sha1, status
489 my $num_parents = length $1;
490 my @tmp = split(" ", $2);
491 my ($file, $file_to) = split("\t", $3);
492 my @mode_from = splice(@tmp, 0, $num_parents);
493 my $mode_to = shift(@tmp);
494 my @sha1_from = splice(@tmp, 0, $num_parents);
495 my $sha1_to = shift(@tmp);
496 my $status = shift(@tmp);
500 'file' => decode_git_file($dir, $file),
501 'sha1_from' => $sha1_from[0],
502 'sha1_to' => $sha1_to,
503 'mode_from' => $mode_from[0],
504 'mode_to' => $mode_to,
516 sub git_commit_info ($$;$) {
517 # Return an array of commit info hashes of num commits
518 # starting from the given sha1sum.
519 my ($dir, $sha1, $num) = @_;
522 push @opts, "--max-count=$num" if defined $num;
524 my @raw_lines = run_or_die_in($dir, 'git', 'log', @opts,
525 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
526 '-r', $sha1, '--no-renames', '--', '.');
529 while (my $parsed = parse_diff_tree($dir, \@raw_lines)) {
533 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
535 return wantarray ? @ci : $ci[0];
538 sub rcs_find_changes ($) {
541 # Note that git log will sometimes show files being added that
542 # don't exist. Particularly, git merge -s ours can result in a
543 # merge commit where some files were not really added.
544 # This is why the code below verifies that the files really
546 my @raw_lines = run_or_die_in($config{srcdir}, 'git', 'log',
547 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
548 '--no-renames', , '--reverse',
549 '-r', "$oldrev..HEAD", '--', '.');
551 # Due to --reverse, we see changes in chronological order.
554 my $nullsha = 0 x 40;
556 while (my $ci = parse_diff_tree($config{srcdir}, \@raw_lines)) {
558 foreach my $i (@{$ci->{details}}) {
560 if ($i->{sha1_to} eq $nullsha) {
561 if (! -e "$config{srcdir}/$file") {
562 delete $changed{$file};
567 if (-e "$config{srcdir}/$file") {
568 delete $deleted{$file};
575 return (\%changed, \%deleted, $newrev);
578 sub git_sha1_file ($$) {
581 return git_sha1($dir, $file);
586 # Ignore error since a non-existing file might be given.
587 my ($sha1) = run_or_non_in($dir, 'git', 'rev-list', '--max-count=1', 'HEAD',
590 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
592 return defined $sha1 ? $sha1 : '';
595 sub rcs_get_current_rev () {
596 return git_sha1($config{srcdir});
600 # Update working directory.
601 ensure_committer($config{srcdir});
603 if (length $config{gitorigin_branch}) {
604 run_or_cry_in($config{srcdir}, 'git', 'pull', '--prune', $config{gitorigin_branch});
608 sub rcs_prepedit ($) {
609 # Return the commit sha1sum of the file when editing begins.
610 # This will be later used in rcs_commit if a merge is required.
613 return git_sha1_file($config{srcdir}, $file);
617 # Try to commit the page; returns undef on _success_ and
618 # a version of the page with the rcs's conflict markers on
622 # Check to see if the page has been changed by someone else since
623 # rcs_prepedit was called.
624 my $cur = git_sha1_file($config{srcdir}, $params{file});
626 if (defined $params{token}) {
627 ($prev) = $params{token} =~ /^($sha1_pattern)$/; # untaint
630 if (defined $cur && defined $prev && $cur ne $prev) {
631 my $conflict = merge_past($prev, $params{file}, $dummy_commit_msg);
632 return $conflict if defined $conflict;
635 return rcs_commit_helper(@_);
638 sub rcs_commit_staged (@) {
639 # Commits all staged changes. Changes can be staged using rcs_add,
640 # rcs_remove, and rcs_rename.
641 return rcs_commit_helper(@_);
644 sub rcs_commit_helper (@) {
649 if (defined $params{session}) {
650 # Set the commit author and email based on web session info.
652 if (defined $params{session}->param("name")) {
653 $u=$params{session}->param("name");
655 elsif (defined $params{session}->remote_addr()) {
656 $u=$params{session}->remote_addr();
659 $u=encode_utf8(IkiWiki::cloak($u));
660 $ENV{GIT_AUTHOR_NAME}=$u;
665 if (defined $params{session}->param("nickname")) {
666 $u=encode_utf8($params{session}->param("nickname"));
668 $u=~s/[^-_0-9[:alnum:]]+//g;
671 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
674 $ENV{GIT_AUTHOR_EMAIL}='anonymous@web';
678 ensure_committer($config{srcdir});
680 $params{message} = IkiWiki::possibly_foolish_untaint($params{message});
682 if ($params{message} !~ /\S/) {
683 # Force git to allow empty commit messages.
684 # (If this version of git supports it.)
685 my ($version)=`git --version` =~ /git version (.*)/;
686 if ($version ge "1.7.8") {
687 push @opts, "--allow-empty-message", "--no-edit";
689 if ($version ge "1.7.2") {
690 push @opts, "--allow-empty-message";
692 elsif ($version ge "1.5.4") {
693 push @opts, '--cleanup=verbatim';
696 $params{message}.=".";
699 if (exists $params{file}) {
700 push @opts, '--', $params{file};
702 # git commit returns non-zero if nothing really changed.
703 # So we should ignore its exit status (hence run_or_non_in).
704 if (run_or_non_in($config{srcdir}, 'git', 'commit', '-m', $params{message}, '-q', @opts)) {
705 if (length $config{gitorigin_branch}) {
706 run_or_cry_in($config{srcdir}, 'git', 'push', $config{gitorigin_branch}, $config{gitmaster_branch});
711 return undef; # success
715 # Add file to archive.
719 ensure_committer($config{srcdir});
720 run_or_cry_in($config{srcdir}, 'git', 'add', '--', $file);
724 # Remove file from archive.
728 ensure_committer($config{srcdir});
729 run_or_cry_in($config{srcdir}, 'git', 'rm', '-f', '--', $file);
732 sub rcs_rename ($$) {
733 my ($src, $dest) = @_;
735 ensure_committer($config{srcdir});
736 run_or_cry_in($config{srcdir}, 'git', 'mv', '-f', '--', $src, $dest);
739 sub rcs_recentchanges ($) {
740 # List of recent changes.
744 eval q{use Date::Parse};
748 foreach my $ci (git_commit_info($config{srcdir}, 'HEAD', $num || 1)) {
749 # Skip redundant commits.
750 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
752 my ($sha1, $when) = (
754 $ci->{'author_epoch'}
758 foreach my $detail (@{ $ci->{'details'} }) {
759 my $file = $detail->{'file'};
760 my $efile = join('/',
761 map { uri_escape_utf8($_) } split('/', $file)
764 my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
765 $diffurl =~ s/\[\[file\]\]/$efile/go;
766 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
767 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
768 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
769 $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
772 page => pagename($file),
779 foreach my $line (@{$ci->{'comment'}}) {
780 $pastblank=1 if $line eq '';
781 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
782 push @messages, { line => $line };
785 my $user=$ci->{'author_username'};
786 my $web_commit = ($ci->{'author'} =~ /\@web>/);
789 # Set nickname only if a non-url author_username is available,
790 # and author_name is an url.
791 if ($user !~ /:\/\// && defined $ci->{'author_name'} &&
792 $ci->{'author_name'} =~ /:\/\//) {
794 $user=$ci->{'author_name'};
797 # compatability code for old web commit messages
799 defined $messages[0] &&
800 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
801 $user = defined $2 ? "$2" : "$3";
802 $messages[0]->{line} = $4;
809 nickname => $nickname,
810 committype => $web_commit ? "web" : "git",
812 message => [@messages],
816 last if @rets >= $num;
825 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
829 return if defined $maxlines && @lines == $maxlines;
830 push @lines, $line."\n"
831 if (@lines || $line=~/^diff --git/);
835 chdir => $config{srcdir},
836 error_handler => undef,
837 data_handler => $addlines,
838 cmdline => ["git", "show", $sha1],
844 return join("", @lines);
853 my $id=shift; # 0 = mtime ; 1 = ctime
855 if (! keys %time_cache) {
857 foreach my $line (run_or_die_in($config{srcdir}, 'git', 'log',
858 '--pretty=format:%at',
859 '--name-only', '--relative')) {
860 if (! defined $date && $line =~ /^(\d+)$/) {
863 elsif (! length $line) {
867 my $f=decode_git_file($config{srcdir}, $line);
869 if (! $time_cache{$f}) {
870 $time_cache{$f}[0]=$date; # mtime
872 $time_cache{$f}[1]=$date; # ctime
877 return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
882 sub rcs_getctime ($) {
885 return findtimes($file, 1);
888 sub rcs_getmtime ($) {
891 return findtimes($file, 0);
897 # The wiki may not be the only thing in the git repo.
898 # Determine if it is in a subdirectory by examining the srcdir,
899 # and its parents, looking for the .git directory.
901 return @$ret if defined $ret;
904 my $dir=$config{srcdir};
905 while (! -d "$dir/.git") {
906 $subdir=IkiWiki::basename($dir)."/".$subdir;
907 $dir=IkiWiki::dirname($dir);
909 error("cannot determine root of git repo");
913 $ret=[$subdir, $dir];
919 sub git_parse_changes ($$@) {
921 my $reverted = shift;
924 my ($subdir, $rootdir) = git_find_root();
926 foreach my $ci (@changes) {
927 foreach my $detail (@{ $ci->{'details'} }) {
928 my $file = $detail->{'file'};
930 # check that all changed files are in the subdir
931 if (length $subdir &&
932 ! ($file =~ s/^\Q$subdir\E//)) {
933 error sprintf(gettext("you are not allowed to change %s"), $file);
936 my ($action, $mode, $path);
937 if ($detail->{'status'} =~ /^[M]+\d*$/) {
939 $mode=$detail->{'mode_to'};
941 elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
942 $action= $reverted ? "remove" : "add";
943 $mode=$detail->{'mode_to'};
945 elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
946 $action= $reverted ? "add" : "remove";
947 $mode=$detail->{'mode_from'};
950 error "unknown status ".$detail->{'status'};
953 # test that the file mode is ok
954 if ($mode !~ /^100[64][64][64]$/) {
955 error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
957 if ($action eq "change") {
958 if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
959 error gettext("you are not allowed to change file modes");
963 # extract attachment to temp file
964 if (($action eq 'add' || $action eq 'change') &&
966 eval q{use File::Temp};
969 ($fh, $path)=File::Temp::tempfile(undef, UNLINK => 1);
972 error_handler => sub { error("failed writing temp file '$path': ".shift."."); },
974 cmdline => ['git', 'show', $detail->{sha1_to}],
993 my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
995 # only allow changes to gitmaster_branch
996 if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
997 error sprintf(gettext("you are not allowed to change %s"), $refname);
1000 # Avoid chdir when running git here, because the changes
1001 # are in the master git repo, not the srcdir repo.
1002 # (Also, if a subdir is involved, we don't want to chdir to
1003 # it and only see changes in it.)
1004 # The pre-receive hook already puts us in the right place.
1005 push @rets, git_parse_changes('.', 0, git_commit_info('.', $oldrev."..".$newrev));
1008 return reverse @rets;
1011 sub rcs_preprevert ($) {
1013 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
1015 my @undo; # undo stack for cleanup in case of an error
1017 # Examine changes from root of git repo, not from any subdir,
1018 # in order to see all changes.
1019 my ($subdir, $rootdir) = git_find_root();
1020 ensure_committer($rootdir);
1022 # preserve indentation of previous in_git_dir code for now
1024 my @commits=git_commit_info($rootdir, $sha1, 1);
1027 error "unknown commit"; # just in case
1030 # git revert will fail on merge commits. Add a nice message.
1031 if (exists $commits[0]->{parents} &&
1032 @{$commits[0]->{parents}} > 1) {
1033 error gettext("you are not allowed to revert a merge");
1036 # Due to the presence of rename-detection, we cannot actually
1037 # see what will happen in a revert without trying it.
1038 # But we can guess, which is enough to rule out most changes
1039 # that we won't allow reverting.
1040 git_parse_changes($rootdir, 1, @commits);
1045 my $branch = "ikiwiki_revert_${sha1}"; # supposed to be unique
1048 run_or_cry_in($rootdir, 'git', 'branch', '-D', $branch) if $failure;
1050 if (run_or_non_in($rootdir, 'git', 'rev-parse', '--quiet', '--verify', $branch)) {
1051 run_or_non_in($rootdir, 'git', 'branch', '-D', $branch);
1053 run_or_die_in($rootdir, 'git', 'branch', $branch, $config{gitmaster_branch});
1055 my $working = create_temp_working_dir($rootdir, $branch);
1058 remove_tree($working);
1061 run_or_die_in($working, 'git', 'checkout', '--quiet', '--force', $branch);
1062 run_or_die_in($working, 'git', 'revert', '--no-commit', $sha1);
1063 run_or_die_in($working, 'git', 'commit', '-m', "revert $sha1", '-a');
1066 @raw_lines = run_or_die_in($rootdir, 'git', 'diff', '--pretty=raw',
1067 '--raw', '--abbrev=40', '--always', '--no-renames',
1071 details => [parse_changed_files($rootdir, \@raw_lines)],
1074 @ret = git_parse_changes($rootdir, 0, $ci);
1078 # Process undo stack (in reverse order). By policy cleanup
1079 # actions should normally print a warning on failure.
1080 while (my $handle = pop @undo) {
1085 my $message = sprintf(gettext("Failed to revert commit %s"), $sha1);
1086 error("$message\n$failure\n");
1092 sub rcs_revert ($) {
1093 # Try to revert the given rev; returns undef on _success_.
1095 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
1097 ensure_committer($config{srcdir});
1099 if (run_or_non_in($config{srcdir}, 'git', 'cherry-pick', '--no-commit', "ikiwiki_revert_$sha1")) {
1103 run_or_non_in($config{srcdir}, 'git', 'branch', '-D', "ikiwiki_revert_$sha1");
1104 return sprintf(gettext("Failed to revert commit %s"), $sha1);