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.
207 my ($error_handler, $data_handler, @cmdline) = @_;
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]: $!");
224 exec @cmdline or error("Cannot exec '@cmdline': $!");
228 # git output is probably utf-8 encoded, but may contain
229 # other encodings or invalidly encoded stuff. So do not rely
230 # on the normal utf-8 IO layer, decode it by hand.
235 $_=decode_utf8($_, 0);
239 if (! defined $data_handler) {
243 last unless $data_handler->($_);
249 $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
251 return wantarray ? @lines : ($? == 0);
253 # Convenient wrappers.
254 sub run_or_die ($@) { safe_git(\&error, undef, @_) }
255 sub run_or_cry ($@) { safe_git(sub { warn @_ }, undef, @_) }
256 sub run_or_non ($@) { safe_git(undef, undef, @_) }
258 sub ensure_committer {
259 if (! length $ENV{GIT_AUTHOR_NAME} || ! length $ENV{GIT_COMMITTER_NAME}) {
260 my $name = join('', run_or_non("git", "config", "user.name"));
261 if (! length $name) {
262 run_or_die("git", "config", "user.name", "IkiWiki");
266 if (! length $ENV{GIT_AUTHOR_EMAIL} || ! length $ENV{GIT_COMMITTER_EMAIL}) {
267 my $email = join('', run_or_non("git", "config", "user.email"));
268 if (! length $email) {
269 run_or_die("git", "config", "user.email", "ikiwiki.info");
274 sub merge_past ($$$) {
275 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
276 # Git merge commands work with the committed changes, except in the
277 # implicit case of '-m' of git checkout(1). So we should invent a
278 # kludge here. In principle, we need to create a throw-away branch
279 # in preparing for the merge itself. Since branches are cheap (and
280 # branching is fast), this shouldn't cost high.
282 # The main problem is the presence of _uncommitted_ local changes. One
283 # possible approach to get rid of this situation could be that we first
284 # make a temporary commit in the master branch and later restore the
285 # initial state (this is possible since Git has the ability to undo a
286 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
289 # - create a diff of HEAD:current-sha1
291 # - create a dummy branch and switch to it
292 # - rewind to past (reset --hard to the current-sha1)
293 # - apply the diff and commit
294 # - switch to master and do the merge with the dummy branch
295 # - make a soft reset (undo the last commit of master)
297 # The above method has some drawbacks: (1) it needs a redundant commit
298 # just to get rid of local changes, (2) somewhat slow because of the
299 # required system forks. Until someone points a more straight method
300 # (which I would be grateful) I have implemented an alternative method.
301 # In this approach, we hide all the modified files from Git by renaming
302 # them (using the 'rename' builtin) and later restore those files in
303 # the throw-away branch (that is, we put the files themselves instead
304 # of applying a patch).
306 my ($sha1, $file, $message) = @_;
308 my @undo; # undo stack for cleanup in case of an error
309 my $conflict; # file content with conflict markers
314 # Hide local changes from Git by renaming the modified file.
315 # Relative paths must be converted to absolute for renaming.
316 my ($target, $hidden) = (
317 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
319 rename($target, $hidden)
320 or error("rename '$target' to '$hidden' failed: $!");
321 # Ensure to restore the renamed file on error.
323 return if ! -e "$hidden"; # already renamed
324 rename($hidden, $target)
325 or warn "rename '$hidden' to '$target' failed: $!";
328 my $branch = "throw_away_${sha1}"; # supposed to be unique
330 # Create a throw-away branch and rewind backward.
331 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
332 run_or_die('git', 'branch', $branch, $sha1);
334 # Switch to throw-away branch for the merge operation.
336 if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
337 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
340 run_or_die('git', 'checkout', $branch);
342 # Put the modified file in _this_ branch.
343 rename($hidden, $target)
344 or error("rename '$hidden' to '$target' failed: $!");
346 # _Silently_ commit all modifications in the current branch.
347 run_or_non('git', 'commit', '-m', $message, '-a');
348 # ... and re-switch to master.
349 run_or_die('git', 'checkout', $config{gitmaster_branch});
351 # Attempt to merge without complaining.
352 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
353 $conflict = readfile($target);
354 run_or_die('git', 'reset', '--hard');
359 # Process undo stack (in reverse order). By policy cleanup
360 # actions should normally print a warning on failure.
361 while (my $handle = pop @undo) {
365 error("Git merge failed!\n$failure\n") if $failure;
370 sub decode_git_file ($) {
373 # git does not output utf-8 filenames, but instead
374 # double-quotes them with the utf-8 characters
375 # escaped as \nnn\nnn.
376 if ($file =~ m/^"(.*)"$/) {
377 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
380 # strip prefix if in a subdir
381 if (! defined $prefix) {
382 ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
383 if (! defined $prefix) {
387 $file =~ s/^\Q$prefix\E//;
389 return decode("utf8", $file);
392 sub parse_diff_tree ($) {
393 # Parse the raw diff tree chunk and return the info hash.
394 # See git-diff-tree(1) for the syntax.
398 return if ! @{ $dt_ref } ||
399 !defined $dt_ref->[0] || !length $dt_ref->[0];
403 while (my $line = shift @{ $dt_ref }) {
404 return if $line !~ m/^(.+) ($sha1_pattern)/;
411 # Identification lines for the commit.
412 while (my $line = shift @{ $dt_ref }) {
413 # Regexps are semi-stolen from gitweb.cgi.
414 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
417 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
418 # XXX: collecting in reverse order
419 push @{ $ci{'parents'} }, $1;
421 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
422 my ($who, $name, $epoch, $tz) =
426 $ci{ "${who}_epoch" } = $epoch;
427 $ci{ "${who}_tz" } = $tz;
429 if ($name =~ m/^([^<]+)\s+<([^@>]+)/) {
430 $ci{"${who}_name"} = $1;
431 $ci{"${who}_username"} = $2;
433 elsif ($name =~ m/^([^<]+)\s+<>$/) {
434 $ci{"${who}_username"} = $1;
437 $ci{"${who}_username"} = $name;
440 elsif ($line =~ m/^$/) {
441 # Trailing empty line signals next section.
446 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
448 if (defined $ci{'parents'}) {
449 $ci{'parent'} = @{ $ci{'parents'} }[0];
452 $ci{'parent'} = 0 x 40;
455 # Commit message (optional).
456 while ($dt_ref->[0] =~ /^ /) {
457 my $line = shift @{ $dt_ref };
459 push @{ $ci{'comment'} }, $line;
461 shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
463 $ci{details} = [parse_changed_files($dt_ref)];
468 sub parse_changed_files {
474 while (my $line = shift @{ $dt_ref }) {
476 (:+) # number of parents
477 ([^\t]+)\t # modes, sha1, status
480 my $num_parents = length $1;
481 my @tmp = split(" ", $2);
482 my ($file, $file_to) = split("\t", $3);
483 my @mode_from = splice(@tmp, 0, $num_parents);
484 my $mode_to = shift(@tmp);
485 my @sha1_from = splice(@tmp, 0, $num_parents);
486 my $sha1_to = shift(@tmp);
487 my $status = shift(@tmp);
491 'file' => decode_git_file($file),
492 'sha1_from' => $sha1_from[0],
493 'sha1_to' => $sha1_to,
494 'mode_from' => $mode_from[0],
495 'mode_to' => $mode_to,
507 sub git_commit_info ($;$) {
508 # Return an array of commit info hashes of num commits
509 # starting from the given sha1sum.
510 my ($sha1, $num) = @_;
513 push @opts, "--max-count=$num" if defined $num;
515 my @raw_lines = run_or_die('git', 'log', @opts,
516 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
517 '-r', $sha1, '--no-renames', '--', '.');
520 while (my $parsed = parse_diff_tree(\@raw_lines)) {
524 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
526 return wantarray ? @ci : $ci[0];
529 sub rcs_find_changes ($) {
532 # Note that git log will sometimes show files being added that
533 # don't exist. Particularly, git merge -s ours can result in a
534 # merge commit where some files were not really added.
535 # This is why the code below verifies that the files really
537 my @raw_lines = run_or_die('git', 'log',
538 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
539 '--no-renames', , '--reverse',
540 '-r', "$oldrev..HEAD", '--', '.');
542 # Due to --reverse, we see changes in chronological order.
545 my $nullsha = 0 x 40;
547 while (my $ci = parse_diff_tree(\@raw_lines)) {
549 foreach my $i (@{$ci->{details}}) {
551 if ($i->{sha1_to} eq $nullsha) {
552 if (! -e "$config{srcdir}/$file") {
553 delete $changed{$file};
558 if (-e "$config{srcdir}/$file") {
559 delete $deleted{$file};
566 return (\%changed, \%deleted, $newrev);
569 sub git_sha1_file ($) {
571 git_sha1("--", $file);
575 # Ignore error since a non-existing file might be given.
576 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
579 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
581 return defined $sha1 ? $sha1 : '';
584 sub rcs_get_current_rev () {
589 # Update working directory.
593 if (length $config{gitorigin_branch}) {
594 run_or_cry('git', 'pull', '--prune', $config{gitorigin_branch});
598 sub rcs_prepedit ($) {
599 # Return the commit sha1sum of the file when editing begins.
600 # This will be later used in rcs_commit if a merge is required.
603 return git_sha1_file($file);
607 # Try to commit the page; returns undef on _success_ and
608 # a version of the page with the rcs's conflict markers on
612 # Check to see if the page has been changed by someone else since
613 # rcs_prepedit was called.
614 my $cur = git_sha1_file($params{file});
616 if (defined $params{token}) {
617 ($prev) = $params{token} =~ /^($sha1_pattern)$/; # untaint
620 if (defined $cur && defined $prev && $cur ne $prev) {
621 my $conflict = merge_past($prev, $params{file}, $dummy_commit_msg);
622 return $conflict if defined $conflict;
625 return rcs_commit_helper(@_);
628 sub rcs_commit_staged (@) {
629 # Commits all staged changes. Changes can be staged using rcs_add,
630 # rcs_remove, and rcs_rename.
631 return rcs_commit_helper(@_);
634 sub rcs_commit_helper (@) {
639 if (defined $params{session}) {
640 # Set the commit author and email based on web session info.
642 if (defined $params{session}->param("name")) {
643 $u=$params{session}->param("name");
645 elsif (defined $params{session}->remote_addr()) {
646 $u=$params{session}->remote_addr();
649 $u=encode_utf8(IkiWiki::cloak($u));
650 $ENV{GIT_AUTHOR_NAME}=$u;
655 if (defined $params{session}->param("nickname")) {
656 $u=encode_utf8($params{session}->param("nickname"));
658 $u=~s/[^-_0-9[:alnum:]]+//g;
661 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
664 $ENV{GIT_AUTHOR_EMAIL}='anonymous@web';
670 $params{message} = IkiWiki::possibly_foolish_untaint($params{message});
672 if ($params{message} !~ /\S/) {
673 # Force git to allow empty commit messages.
674 # (If this version of git supports it.)
675 my ($version)=`git --version` =~ /git version (.*)/;
676 if ($version ge "1.7.8") {
677 push @opts, "--allow-empty-message", "--no-edit";
679 if ($version ge "1.7.2") {
680 push @opts, "--allow-empty-message";
682 elsif ($version ge "1.5.4") {
683 push @opts, '--cleanup=verbatim';
686 $params{message}.=".";
689 if (exists $params{file}) {
690 push @opts, '--', $params{file};
692 # git commit returns non-zero if nothing really changed.
693 # So we should ignore its exit status (hence run_or_non).
694 if (run_or_non('git', 'commit', '-m', $params{message}, '-q', @opts)) {
695 if (length $config{gitorigin_branch}) {
696 run_or_cry('git', 'push', $config{gitorigin_branch}, $config{gitmaster_branch});
701 return undef; # success
705 # Add file to archive.
711 run_or_cry('git', 'add', '--', $file);
715 # Remove file from archive.
721 run_or_cry('git', 'rm', '-f', '--', $file);
724 sub rcs_rename ($$) {
725 my ($src, $dest) = @_;
729 run_or_cry('git', 'mv', '-f', '--', $src, $dest);
732 sub rcs_recentchanges ($) {
733 # List of recent changes.
737 eval q{use Date::Parse};
741 foreach my $ci (git_commit_info('HEAD', $num || 1)) {
742 # Skip redundant commits.
743 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
745 my ($sha1, $when) = (
747 $ci->{'author_epoch'}
751 foreach my $detail (@{ $ci->{'details'} }) {
752 my $file = $detail->{'file'};
753 my $efile = join('/',
754 map { uri_escape_utf8($_) } split('/', $file)
757 my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
758 $diffurl =~ s/\[\[file\]\]/$efile/go;
759 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
760 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
761 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
762 $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
765 page => pagename($file),
772 foreach my $line (@{$ci->{'comment'}}) {
773 $pastblank=1 if $line eq '';
774 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
775 push @messages, { line => $line };
778 my $user=$ci->{'author_username'};
779 my $web_commit = ($ci->{'author'} =~ /\@web>/);
782 # Set nickname only if a non-url author_username is available,
783 # and author_name is an url.
784 if ($user !~ /:\/\// && defined $ci->{'author_name'} &&
785 $ci->{'author_name'} =~ /:\/\//) {
787 $user=$ci->{'author_name'};
790 # compatability code for old web commit messages
792 defined $messages[0] &&
793 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
794 $user = defined $2 ? "$2" : "$3";
795 $messages[0]->{line} = $4;
802 nickname => $nickname,
803 committype => $web_commit ? "web" : "git",
805 message => [@messages],
809 last if @rets >= $num;
818 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
822 return if defined $maxlines && @lines == $maxlines;
823 push @lines, $line."\n"
824 if (@lines || $line=~/^diff --git/);
827 safe_git(undef, $addlines, "git", "show", $sha1);
832 return join("", @lines);
841 my $id=shift; # 0 = mtime ; 1 = ctime
843 if (! keys %time_cache) {
845 foreach my $line (run_or_die('git', 'log',
846 '--pretty=format:%at',
847 '--name-only', '--relative')) {
848 if (! defined $date && $line =~ /^(\d+)$/) {
851 elsif (! length $line) {
855 my $f=decode_git_file($line);
857 if (! $time_cache{$f}) {
858 $time_cache{$f}[0]=$date; # mtime
860 $time_cache{$f}[1]=$date; # ctime
865 return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
870 sub rcs_getctime ($) {
873 return findtimes($file, 1);
876 sub rcs_getmtime ($) {
879 return findtimes($file, 0);
885 # The wiki may not be the only thing in the git repo.
886 # Determine if it is in a subdirectory by examining the srcdir,
887 # and its parents, looking for the .git directory.
889 return @$ret if defined $ret;
892 my $dir=$config{srcdir};
893 while (! -d "$dir/.git") {
894 $subdir=IkiWiki::basename($dir)."/".$subdir;
895 $dir=IkiWiki::dirname($dir);
897 error("cannot determine root of git repo");
901 $ret=[$subdir, $dir];
907 sub git_parse_changes {
908 my $reverted = shift;
911 my ($subdir, $rootdir) = git_find_root();
913 foreach my $ci (@changes) {
914 foreach my $detail (@{ $ci->{'details'} }) {
915 my $file = $detail->{'file'};
917 # check that all changed files are in the subdir
918 if (length $subdir &&
919 ! ($file =~ s/^\Q$subdir\E//)) {
920 error sprintf(gettext("you are not allowed to change %s"), $file);
923 my ($action, $mode, $path);
924 if ($detail->{'status'} =~ /^[M]+\d*$/) {
926 $mode=$detail->{'mode_to'};
928 elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
929 $action= $reverted ? "remove" : "add";
930 $mode=$detail->{'mode_to'};
932 elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
933 $action= $reverted ? "add" : "remove";
934 $mode=$detail->{'mode_from'};
937 error "unknown status ".$detail->{'status'};
940 # test that the file mode is ok
941 if ($mode !~ /^100[64][64][64]$/) {
942 error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
944 if ($action eq "change") {
945 if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
946 error gettext("you are not allowed to change file modes");
950 # extract attachment to temp file
951 if (($action eq 'add' || $action eq 'change') &&
953 eval q{use File::Temp};
956 ($fh, $path)=File::Temp::tempfile(undef, UNLINK => 1);
957 my $cmd = "cd $git_dir_stack[0] && ".
958 "git show $detail->{sha1_to} > '$path'";
959 if (system($cmd) != 0) {
960 error("failed writing temp file '$path'.");
979 my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
981 # only allow changes to gitmaster_branch
982 if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
983 error sprintf(gettext("you are not allowed to change %s"), $refname);
986 # Avoid chdir when running git here, because the changes
987 # are in the master git repo, not the srcdir repo.
988 # (Also, if a subdir is involved, we don't want to chdir to
989 # it and only see changes in it.)
990 # The pre-receive hook already puts us in the right place.
991 in_git_dir(".", sub {
992 push @rets, git_parse_changes(0, git_commit_info($oldrev."..".$newrev));
996 return reverse @rets;
999 sub rcs_preprevert ($) {
1001 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
1003 my @undo; # undo stack for cleanup in case of an error
1007 # Examine changes from root of git repo, not from any subdir,
1008 # in order to see all changes.
1009 my ($subdir, $rootdir) = git_find_root();
1010 return in_git_dir($rootdir, sub {
1011 my @commits=git_commit_info($sha1, 1);
1014 error "unknown commit"; # just in case
1017 # git revert will fail on merge commits. Add a nice message.
1018 if (exists $commits[0]->{parents} &&
1019 @{$commits[0]->{parents}} > 1) {
1020 error gettext("you are not allowed to revert a merge");
1023 # Due to the presence of rename-detection, we cannot actually
1024 # see what will happen in a revert without trying it.
1025 # But we can guess, which is enough to rule out most changes
1026 # that we won't allow reverting.
1027 git_parse_changes(1, @commits);
1032 IkiWiki::disable_commit_hook();
1034 IkiWiki::enable_commit_hook();
1036 my $branch = "ikiwiki_revert_${sha1}"; # supposed to be unique
1039 run_or_cry('git', 'branch', '-D', $branch) if $failure;
1041 if (run_or_non('git', 'rev-parse', '--quiet', '--verify', $branch)) {
1042 run_or_non('git', 'branch', '-D', $branch);
1044 run_or_die('git', 'branch', $branch, $config{gitmaster_branch});
1046 my $working = create_temp_working_dir($rootdir, $branch);
1049 remove_tree($working);
1052 in_git_dir($working, sub {
1053 run_or_die('git', 'checkout', '--quiet', '--force', $branch);
1054 run_or_die('git', 'revert', '--no-commit', $sha1);
1055 run_or_die('git', 'commit', '-m', "revert $sha1", '-a');
1059 @raw_lines = run_or_die('git', 'diff', '--pretty=raw',
1060 '--raw', '--abbrev=40', '--always', '--no-renames',
1064 details => [parse_changed_files(\@raw_lines)],
1067 @ret = git_parse_changes(0, $ci);
1071 # Process undo stack (in reverse order). By policy cleanup
1072 # actions should normally print a warning on failure.
1073 while (my $handle = pop @undo) {
1078 my $message = sprintf(gettext("Failed to revert commit %s"), $sha1);
1079 error("$message\n$failure\n");
1086 sub rcs_revert ($) {
1087 # Try to revert the given rev; returns undef on _success_.
1089 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
1093 if (run_or_non('git', 'merge', '--ff-only', "ikiwiki_revert_$sha1")) {
1097 run_or_non('git', 'branch', '-D', "ikiwiki_revert_$sha1");
1098 return sprintf(gettext("Failed to revert commit %s"), $sha1);