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();
160 sub in_git_dir ($$) {
161 unshift @git_dir_stack, shift;
163 shift @git_dir_stack;
168 # Loosely based on git-new-workdir from git contrib.
169 sub create_temp_working_dir ($$) {
172 my $working = "$rootdir/.git/ikiwiki-temp-working";
173 remove_tree($working);
175 foreach my $dir ("", ".git") {
176 if (!mkdir("$working/$dir")) {
177 error("Unable to create $working/$dir: $!");
181 # Hooks are deliberately not included: we will commit to the temporary
182 # branch that is used in the temporary working tree, and we don't want
183 # to run the post-commit hook there.
185 # logs/refs is not included because we don't use the reflog.
186 # remotes, rr-cache, svn are similarly excluded.
187 foreach my $link ("config", "refs", "objects", "info", "packed-refs") {
188 if (!symlink("../../$link", "$working/.git/$link")) {
189 error("Unable to create symlink $working/.git/$link: $!");
193 open (my $out, '>', "$working/.git/HEAD") or
194 error("failed to write $working.git/HEAD: $!");
195 print $out "ref: refs/heads/$branch\n" or
196 error("failed to write $working.git/HEAD: $!");
198 error("failed to write $working.git/HEAD: $!");
203 # Start a child process safely without resorting to /bin/sh.
204 # Returns command output (in list content) or success state
205 # (in scalar context), or runs the specified data handler.
209 my $pid = open my $OUT, "-|";
211 error("Cannot fork: $!") if !defined $pid;
215 # Git commands want to be in wc.
216 if (! @git_dir_stack) {
217 chdir $config{srcdir}
218 or error("cannot chdir to $config{srcdir}: $!");
221 chdir $git_dir_stack[0]
222 or error("cannot chdir to $git_dir_stack[0]: $!");
225 if ($params{stdout}) {
226 open(STDOUT, '>&', $params{stdout}) or error("Cannot reopen stdout: $!");
229 exec @{$params{cmdline}} or error("Cannot exec '@{$params{cmdline}}': $!");
233 # git output is probably utf-8 encoded, but may contain
234 # other encodings or invalidly encoded stuff. So do not rely
235 # on the normal utf-8 IO layer, decode it by hand.
240 $_=decode_utf8($_, 0);
244 if (! defined $params{data_handler}) {
248 last unless $params{data_handler}->($_);
254 $params{error_handler}->("'@{$params{cmdline}}' failed: $!") if $? && $params{error_handler};
256 return wantarray ? @lines : ($? == 0);
258 # Convenient wrappers.
259 sub run_or_die ($@) { safe_git(error_handler => \&error, cmdline => \@_) }
260 sub run_or_cry ($@) { safe_git(error_handler => sub { warn @_ }, cmdline => \@_) }
261 sub run_or_non ($@) { safe_git(cmdline => \@_) }
263 sub ensure_committer {
264 if (! length $ENV{GIT_AUTHOR_NAME} || ! length $ENV{GIT_COMMITTER_NAME}) {
265 my $name = join('', run_or_non("git", "config", "user.name"));
266 if (! length $name) {
267 run_or_die("git", "config", "user.name", "IkiWiki");
271 if (! length $ENV{GIT_AUTHOR_EMAIL} || ! length $ENV{GIT_COMMITTER_EMAIL}) {
272 my $email = join('', run_or_non("git", "config", "user.email"));
273 if (! length $email) {
274 run_or_die("git", "config", "user.email", "ikiwiki.info");
279 sub merge_past ($$$) {
280 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
281 # Git merge commands work with the committed changes, except in the
282 # implicit case of '-m' of git checkout(1). So we should invent a
283 # kludge here. In principle, we need to create a throw-away branch
284 # in preparing for the merge itself. Since branches are cheap (and
285 # branching is fast), this shouldn't cost high.
287 # The main problem is the presence of _uncommitted_ local changes. One
288 # possible approach to get rid of this situation could be that we first
289 # make a temporary commit in the master branch and later restore the
290 # initial state (this is possible since Git has the ability to undo a
291 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
294 # - create a diff of HEAD:current-sha1
296 # - create a dummy branch and switch to it
297 # - rewind to past (reset --hard to the current-sha1)
298 # - apply the diff and commit
299 # - switch to master and do the merge with the dummy branch
300 # - make a soft reset (undo the last commit of master)
302 # The above method has some drawbacks: (1) it needs a redundant commit
303 # just to get rid of local changes, (2) somewhat slow because of the
304 # required system forks. Until someone points a more straight method
305 # (which I would be grateful) I have implemented an alternative method.
306 # In this approach, we hide all the modified files from Git by renaming
307 # them (using the 'rename' builtin) and later restore those files in
308 # the throw-away branch (that is, we put the files themselves instead
309 # of applying a patch).
311 my ($sha1, $file, $message) = @_;
313 my @undo; # undo stack for cleanup in case of an error
314 my $conflict; # file content with conflict markers
319 # Hide local changes from Git by renaming the modified file.
320 # Relative paths must be converted to absolute for renaming.
321 my ($target, $hidden) = (
322 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
324 rename($target, $hidden)
325 or error("rename '$target' to '$hidden' failed: $!");
326 # Ensure to restore the renamed file on error.
328 return if ! -e "$hidden"; # already renamed
329 rename($hidden, $target)
330 or warn "rename '$hidden' to '$target' failed: $!";
333 my $branch = "throw_away_${sha1}"; # supposed to be unique
335 # Create a throw-away branch and rewind backward.
336 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
337 run_or_die('git', 'branch', $branch, $sha1);
339 # Switch to throw-away branch for the merge operation.
341 if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
342 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
345 run_or_die('git', 'checkout', $branch);
347 # Put the modified file in _this_ branch.
348 rename($hidden, $target)
349 or error("rename '$hidden' to '$target' failed: $!");
351 # _Silently_ commit all modifications in the current branch.
352 run_or_non('git', 'commit', '-m', $message, '-a');
353 # ... and re-switch to master.
354 run_or_die('git', 'checkout', $config{gitmaster_branch});
356 # Attempt to merge without complaining.
357 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
358 $conflict = readfile($target);
359 run_or_die('git', 'reset', '--hard');
364 # Process undo stack (in reverse order). By policy cleanup
365 # actions should normally print a warning on failure.
366 while (my $handle = pop @undo) {
370 error("Git merge failed!\n$failure\n") if $failure;
375 sub decode_git_file ($) {
378 # git does not output utf-8 filenames, but instead
379 # double-quotes them with the utf-8 characters
380 # escaped as \nnn\nnn.
381 if ($file =~ m/^"(.*)"$/) {
382 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
385 # strip prefix if in a subdir
386 if (! defined $prefix) {
387 ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
388 if (! defined $prefix) {
392 $file =~ s/^\Q$prefix\E//;
394 return decode("utf8", $file);
397 sub parse_diff_tree ($) {
398 # Parse the raw diff tree chunk and return the info hash.
399 # See git-diff-tree(1) for the syntax.
403 return if ! @{ $dt_ref } ||
404 !defined $dt_ref->[0] || !length $dt_ref->[0];
408 while (my $line = shift @{ $dt_ref }) {
409 return if $line !~ m/^(.+) ($sha1_pattern)/;
416 # Identification lines for the commit.
417 while (my $line = shift @{ $dt_ref }) {
418 # Regexps are semi-stolen from gitweb.cgi.
419 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
422 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
423 # XXX: collecting in reverse order
424 push @{ $ci{'parents'} }, $1;
426 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
427 my ($who, $name, $epoch, $tz) =
431 $ci{ "${who}_epoch" } = $epoch;
432 $ci{ "${who}_tz" } = $tz;
434 if ($name =~ m/^([^<]+)\s+<([^@>]+)/) {
435 $ci{"${who}_name"} = $1;
436 $ci{"${who}_username"} = $2;
438 elsif ($name =~ m/^([^<]+)\s+<>$/) {
439 $ci{"${who}_username"} = $1;
442 $ci{"${who}_username"} = $name;
445 elsif ($line =~ m/^$/) {
446 # Trailing empty line signals next section.
451 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
453 if (defined $ci{'parents'}) {
454 $ci{'parent'} = @{ $ci{'parents'} }[0];
457 $ci{'parent'} = 0 x 40;
460 # Commit message (optional).
461 while ($dt_ref->[0] =~ /^ /) {
462 my $line = shift @{ $dt_ref };
464 push @{ $ci{'comment'} }, $line;
466 shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
468 $ci{details} = [parse_changed_files($dt_ref)];
473 sub parse_changed_files {
479 while (my $line = shift @{ $dt_ref }) {
481 (:+) # number of parents
482 ([^\t]+)\t # modes, sha1, status
485 my $num_parents = length $1;
486 my @tmp = split(" ", $2);
487 my ($file, $file_to) = split("\t", $3);
488 my @mode_from = splice(@tmp, 0, $num_parents);
489 my $mode_to = shift(@tmp);
490 my @sha1_from = splice(@tmp, 0, $num_parents);
491 my $sha1_to = shift(@tmp);
492 my $status = shift(@tmp);
496 'file' => decode_git_file($file),
497 'sha1_from' => $sha1_from[0],
498 'sha1_to' => $sha1_to,
499 'mode_from' => $mode_from[0],
500 'mode_to' => $mode_to,
512 sub git_commit_info ($;$) {
513 # Return an array of commit info hashes of num commits
514 # starting from the given sha1sum.
515 my ($sha1, $num) = @_;
518 push @opts, "--max-count=$num" if defined $num;
520 my @raw_lines = run_or_die('git', 'log', @opts,
521 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
522 '-r', $sha1, '--no-renames', '--', '.');
525 while (my $parsed = parse_diff_tree(\@raw_lines)) {
529 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
531 return wantarray ? @ci : $ci[0];
534 sub rcs_find_changes ($) {
537 # Note that git log will sometimes show files being added that
538 # don't exist. Particularly, git merge -s ours can result in a
539 # merge commit where some files were not really added.
540 # This is why the code below verifies that the files really
542 my @raw_lines = run_or_die('git', 'log',
543 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
544 '--no-renames', , '--reverse',
545 '-r', "$oldrev..HEAD", '--', '.');
547 # Due to --reverse, we see changes in chronological order.
550 my $nullsha = 0 x 40;
552 while (my $ci = parse_diff_tree(\@raw_lines)) {
554 foreach my $i (@{$ci->{details}}) {
556 if ($i->{sha1_to} eq $nullsha) {
557 if (! -e "$config{srcdir}/$file") {
558 delete $changed{$file};
563 if (-e "$config{srcdir}/$file") {
564 delete $deleted{$file};
571 return (\%changed, \%deleted, $newrev);
574 sub git_sha1_file ($) {
576 git_sha1("--", $file);
580 # Ignore error since a non-existing file might be given.
581 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
584 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
586 return defined $sha1 ? $sha1 : '';
589 sub rcs_get_current_rev () {
594 # Update working directory.
598 if (length $config{gitorigin_branch}) {
599 run_or_cry('git', 'pull', '--prune', $config{gitorigin_branch});
603 sub rcs_prepedit ($) {
604 # Return the commit sha1sum of the file when editing begins.
605 # This will be later used in rcs_commit if a merge is required.
608 return git_sha1_file($file);
612 # Try to commit the page; returns undef on _success_ and
613 # a version of the page with the rcs's conflict markers on
617 # Check to see if the page has been changed by someone else since
618 # rcs_prepedit was called.
619 my $cur = git_sha1_file($params{file});
621 if (defined $params{token}) {
622 ($prev) = $params{token} =~ /^($sha1_pattern)$/; # untaint
625 if (defined $cur && defined $prev && $cur ne $prev) {
626 my $conflict = merge_past($prev, $params{file}, $dummy_commit_msg);
627 return $conflict if defined $conflict;
630 return rcs_commit_helper(@_);
633 sub rcs_commit_staged (@) {
634 # Commits all staged changes. Changes can be staged using rcs_add,
635 # rcs_remove, and rcs_rename.
636 return rcs_commit_helper(@_);
639 sub rcs_commit_helper (@) {
644 if (defined $params{session}) {
645 # Set the commit author and email based on web session info.
647 if (defined $params{session}->param("name")) {
648 $u=$params{session}->param("name");
650 elsif (defined $params{session}->remote_addr()) {
651 $u=$params{session}->remote_addr();
655 $ENV{GIT_AUTHOR_NAME}=$u;
660 if (defined $params{session}->param("nickname")) {
661 $u=encode_utf8($params{session}->param("nickname"));
663 $u=~s/[^-_0-9[:alnum:]]+//g;
666 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
669 $ENV{GIT_AUTHOR_EMAIL}='anonymous@web';
675 $params{message} = IkiWiki::possibly_foolish_untaint($params{message});
677 if ($params{message} !~ /\S/) {
678 # Force git to allow empty commit messages.
679 # (If this version of git supports it.)
680 my ($version)=`git --version` =~ /git version (.*)/;
681 if ($version ge "1.7.8") {
682 push @opts, "--allow-empty-message", "--no-edit";
684 if ($version ge "1.7.2") {
685 push @opts, "--allow-empty-message";
687 elsif ($version ge "1.5.4") {
688 push @opts, '--cleanup=verbatim';
691 $params{message}.=".";
694 if (exists $params{file}) {
695 push @opts, '--', $params{file};
697 # git commit returns non-zero if nothing really changed.
698 # So we should ignore its exit status (hence run_or_non).
699 if (run_or_non('git', 'commit', '-m', $params{message}, '-q', @opts)) {
700 if (length $config{gitorigin_branch}) {
701 run_or_cry('git', 'push', $config{gitorigin_branch}, $config{gitmaster_branch});
706 return undef; # success
710 # Add file to archive.
716 run_or_cry('git', 'add', '--', $file);
720 # Remove file from archive.
726 run_or_cry('git', 'rm', '-f', '--', $file);
729 sub rcs_rename ($$) {
730 my ($src, $dest) = @_;
734 run_or_cry('git', 'mv', '-f', '--', $src, $dest);
737 sub rcs_recentchanges ($) {
738 # List of recent changes.
742 eval q{use Date::Parse};
746 foreach my $ci (git_commit_info('HEAD', $num || 1)) {
747 # Skip redundant commits.
748 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
750 my ($sha1, $when) = (
752 $ci->{'author_epoch'}
756 foreach my $detail (@{ $ci->{'details'} }) {
757 my $file = $detail->{'file'};
758 my $efile = join('/',
759 map { uri_escape_utf8($_) } split('/', $file)
762 my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
763 $diffurl =~ s/\[\[file\]\]/$efile/go;
764 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
765 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
766 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
767 $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
770 page => pagename($file),
777 foreach my $line (@{$ci->{'comment'}}) {
778 $pastblank=1 if $line eq '';
779 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
780 push @messages, { line => $line };
783 my $user=$ci->{'author_username'};
784 my $web_commit = ($ci->{'author'} =~ /\@web>/);
787 # Set nickname only if a non-url author_username is available,
788 # and author_name is an url.
789 if ($user !~ /:\/\// && defined $ci->{'author_name'} &&
790 $ci->{'author_name'} =~ /:\/\//) {
792 $user=$ci->{'author_name'};
795 # compatability code for old web commit messages
797 defined $messages[0] &&
798 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
799 $user = defined $2 ? "$2" : "$3";
800 $messages[0]->{line} = $4;
807 nickname => $nickname,
808 committype => $web_commit ? "web" : "git",
810 message => [@messages],
814 last if @rets >= $num;
823 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
827 return if defined $maxlines && @lines == $maxlines;
828 push @lines, $line."\n"
829 if (@lines || $line=~/^diff --git/);
833 error_handler => undef,
834 data_handler => $addlines,
835 cmdline => ["git", "show", $sha1],
841 return join("", @lines);
850 my $id=shift; # 0 = mtime ; 1 = ctime
852 if (! keys %time_cache) {
854 foreach my $line (run_or_die('git', 'log',
855 '--pretty=format:%at',
856 '--name-only', '--relative')) {
857 if (! defined $date && $line =~ /^(\d+)$/) {
860 elsif (! length $line) {
864 my $f=decode_git_file($line);
866 if (! $time_cache{$f}) {
867 $time_cache{$f}[0]=$date; # mtime
869 $time_cache{$f}[1]=$date; # ctime
874 return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
879 sub rcs_getctime ($) {
882 return findtimes($file, 1);
885 sub rcs_getmtime ($) {
888 return findtimes($file, 0);
894 # The wiki may not be the only thing in the git repo.
895 # Determine if it is in a subdirectory by examining the srcdir,
896 # and its parents, looking for the .git directory.
898 return @$ret if defined $ret;
901 my $dir=$config{srcdir};
902 while (! -d "$dir/.git") {
903 $subdir=IkiWiki::basename($dir)."/".$subdir;
904 $dir=IkiWiki::dirname($dir);
906 error("cannot determine root of git repo");
910 $ret=[$subdir, $dir];
916 sub git_parse_changes {
917 my $reverted = shift;
920 my ($subdir, $rootdir) = git_find_root();
922 foreach my $ci (@changes) {
923 foreach my $detail (@{ $ci->{'details'} }) {
924 my $file = $detail->{'file'};
926 # check that all changed files are in the subdir
927 if (length $subdir &&
928 ! ($file =~ s/^\Q$subdir\E//)) {
929 error sprintf(gettext("you are not allowed to change %s"), $file);
932 my ($action, $mode, $path);
933 if ($detail->{'status'} =~ /^[M]+\d*$/) {
935 $mode=$detail->{'mode_to'};
937 elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
938 $action= $reverted ? "remove" : "add";
939 $mode=$detail->{'mode_to'};
941 elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
942 $action= $reverted ? "add" : "remove";
943 $mode=$detail->{'mode_from'};
946 error "unknown status ".$detail->{'status'};
949 # test that the file mode is ok
950 if ($mode !~ /^100[64][64][64]$/) {
951 error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
953 if ($action eq "change") {
954 if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
955 error gettext("you are not allowed to change file modes");
959 # extract attachment to temp file
960 if (($action eq 'add' || $action eq 'change') &&
962 eval q{use File::Temp};
965 ($fh, $path)=File::Temp::tempfile(undef, UNLINK => 1);
967 error_handler => sub { error("failed writing temp file '$path': ".shift."."); },
969 cmdline => ['git', 'show', $detail->{sha1_to}],
988 my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
990 # only allow changes to gitmaster_branch
991 if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
992 error sprintf(gettext("you are not allowed to change %s"), $refname);
995 # Avoid chdir when running git here, because the changes
996 # are in the master git repo, not the srcdir repo.
997 # (Also, if a subdir is involved, we don't want to chdir to
998 # it and only see changes in it.)
999 # The pre-receive hook already puts us in the right place.
1000 in_git_dir(".", sub {
1001 push @rets, git_parse_changes(0, git_commit_info($oldrev."..".$newrev));
1005 return reverse @rets;
1008 sub rcs_preprevert ($) {
1010 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
1012 my @undo; # undo stack for cleanup in case of an error
1016 # Examine changes from root of git repo, not from any subdir,
1017 # in order to see all changes.
1018 my ($subdir, $rootdir) = git_find_root();
1019 return in_git_dir($rootdir, sub {
1020 my @commits=git_commit_info($sha1, 1);
1023 error "unknown commit"; # just in case
1026 # git revert will fail on merge commits. Add a nice message.
1027 if (exists $commits[0]->{parents} &&
1028 @{$commits[0]->{parents}} > 1) {
1029 error gettext("you are not allowed to revert a merge");
1032 # Due to the presence of rename-detection, we cannot actually
1033 # see what will happen in a revert without trying it.
1034 # But we can guess, which is enough to rule out most changes
1035 # that we won't allow reverting.
1036 git_parse_changes(1, @commits);
1041 IkiWiki::disable_commit_hook();
1043 IkiWiki::enable_commit_hook();
1045 my $branch = "ikiwiki_revert_${sha1}"; # supposed to be unique
1048 run_or_cry('git', 'branch', '-D', $branch) if $failure;
1050 if (run_or_non('git', 'rev-parse', '--quiet', '--verify', $branch)) {
1051 run_or_non('git', 'branch', '-D', $branch);
1053 run_or_die('git', 'branch', $branch, $config{gitmaster_branch});
1055 my $working = create_temp_working_dir($rootdir, $branch);
1058 remove_tree($working);
1061 in_git_dir($working, sub {
1062 run_or_die('git', 'checkout', '--quiet', '--force', $branch);
1063 run_or_die('git', 'revert', '--no-commit', $sha1);
1064 run_or_die('git', 'commit', '-m', "revert $sha1", '-a');
1068 @raw_lines = run_or_die('git', 'diff', '--pretty=raw',
1069 '--raw', '--abbrev=40', '--always', '--no-renames',
1073 details => [parse_changed_files(\@raw_lines)],
1076 @ret = git_parse_changes(0, $ci);
1080 # Process undo stack (in reverse order). By policy cleanup
1081 # actions should normally print a warning on failure.
1082 while (my $handle = pop @undo) {
1087 my $message = sprintf(gettext("Failed to revert commit %s"), $sha1);
1088 error("$message\n$failure\n");
1095 sub rcs_revert ($) {
1096 # Try to revert the given rev; returns undef on _success_.
1098 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
1102 if (run_or_non('git', 'cherry-pick', '--no-commit', "ikiwiki_revert_$sha1")) {
1106 run_or_non('git', 'branch', '-D', "ikiwiki_revert_$sha1");
1107 return sprintf(gettext("Failed to revert commit %s"), $sha1);