2 package IkiWiki::Plugin::git;
8 use URI::Escape q{uri_escape_utf8};
9 use open qw{:utf8 :std};
11 my $sha1_pattern = qr/[0-9a-fA-F]{40}/; # pattern to validate Git sha1sums
12 my $dummy_commit_msg = 'dummy commit'; # message to skip in recent changes
15 hook(type => "checkconfig", id => "git", call => \&checkconfig);
16 hook(type => "getsetup", id => "git", call => \&getsetup);
17 hook(type => "genwrapper", id => "git", call => \&genwrapper);
18 hook(type => "rcs", id => "rcs_update", call => \&rcs_update);
19 hook(type => "rcs", id => "rcs_prepedit", call => \&rcs_prepedit);
20 hook(type => "rcs", id => "rcs_commit", call => \&rcs_commit);
21 hook(type => "rcs", id => "rcs_commit_staged", call => \&rcs_commit_staged);
22 hook(type => "rcs", id => "rcs_add", call => \&rcs_add);
23 hook(type => "rcs", id => "rcs_remove", call => \&rcs_remove);
24 hook(type => "rcs", id => "rcs_rename", call => \&rcs_rename);
25 hook(type => "rcs", id => "rcs_recentchanges", call => \&rcs_recentchanges);
26 hook(type => "rcs", id => "rcs_diff", call => \&rcs_diff);
27 hook(type => "rcs", id => "rcs_getctime", call => \&rcs_getctime);
28 hook(type => "rcs", id => "rcs_getmtime", call => \&rcs_getmtime);
29 hook(type => "rcs", id => "rcs_receive", call => \&rcs_receive);
30 hook(type => "rcs", id => "rcs_preprevert", call => \&rcs_preprevert);
31 hook(type => "rcs", id => "rcs_revert", call => \&rcs_revert);
32 hook(type => "rcs", id => "rcs_find_changes", call => \&rcs_find_changes);
33 hook(type => "rcs", id => "rcs_get_current_rev", call => \&rcs_get_current_rev);
37 if (! defined $config{gitorigin_branch}) {
38 $config{gitorigin_branch}="origin";
40 if (! defined $config{gitmaster_branch}) {
41 $config{gitmaster_branch}="master";
43 if (defined $config{git_wrapper} &&
44 length $config{git_wrapper}) {
45 push @{$config{wrappers}}, {
46 wrapper => $config{git_wrapper},
47 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
48 wrapper_background_command => $config{git_wrapper_background_command},
52 if (defined $config{git_test_receive_wrapper} &&
53 length $config{git_test_receive_wrapper} &&
54 defined $config{untrusted_committers} &&
55 @{$config{untrusted_committers}}) {
56 push @{$config{wrappers}}, {
58 wrapper => $config{git_test_receive_wrapper},
59 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
63 # Avoid notes, parser does not handle and they only slow things down.
64 $ENV{GIT_NOTES_REF}="";
66 # Run receive test only if being called by the wrapper, and not
67 # when generating same.
68 if ($config{test_receive} && ! exists $config{wrapper}) {
69 require IkiWiki::Receive;
70 IkiWiki::Receive::test();
77 safe => 0, # rcs plugin
83 example => "/git/wiki.git/hooks/post-update",
84 description => "git hook to generate",
88 git_wrapper_background_command => {
90 example => "git push github",
91 description => "shell command for git_wrapper to run, in the background",
98 description => "mode for git_wrapper (can safely be made suid)",
102 git_test_receive_wrapper => {
104 example => "/git/wiki.git/hooks/pre-receive",
105 description => "git pre-receive hook to generate",
109 untrusted_committers => {
112 description => "unix users whose commits should be checked by the pre-receive hook",
118 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]];hb=HEAD",
119 description => "gitweb url to show file history ([[file]] substituted)",
125 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]]",
126 description => "gitweb url to show a diff ([[file]], [[sha1_to]], [[sha1_from]], [[sha1_commit]], and [[sha1_parent]] substituted)",
130 gitorigin_branch => {
133 description => "where to pull and push changes (set to empty string to disable)",
134 safe => 0, # paranoia
137 gitmaster_branch => {
140 description => "branch that the wiki is stored in",
141 safe => 0, # paranoia
147 if ($config{test_receive}) {
148 require IkiWiki::Receive;
149 return IkiWiki::Receive::genwrapper();
159 sub in_git_dir ($$) {
168 # Start a child process safely without resorting to /bin/sh.
169 # Returns command output (in list content) or success state
170 # (in scalar context), or runs the specified data handler.
172 my ($error_handler, $data_handler, @cmdline) = @_;
174 my $pid = open my $OUT, "-|";
176 error("Cannot fork: $!") if !defined $pid;
180 # Git commands want to be in wc.
181 if (! defined $git_dir) {
182 chdir $config{srcdir}
183 or error("cannot chdir to $config{srcdir}: $!");
187 or error("cannot chdir to $git_dir: $!");
189 exec @cmdline or error("Cannot exec '@cmdline': $!");
193 # git output is probably utf-8 encoded, but may contain
194 # other encodings or invalidly encoded stuff. So do not rely
195 # on the normal utf-8 IO layer, decode it by hand.
200 $_=decode_utf8($_, 0);
204 if (! defined $data_handler) {
208 last unless $data_handler->($_);
214 $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
216 return wantarray ? @lines : ($? == 0);
218 # Convenient wrappers.
219 sub run_or_die ($@) { safe_git(\&error, undef, @_) }
220 sub run_or_cry ($@) { safe_git(sub { warn @_ }, undef, @_) }
221 sub run_or_non ($@) { safe_git(undef, undef, @_) }
223 sub ensure_committer {
224 if (! length $ENV{GIT_AUTHOR_NAME} || ! length $ENV{GIT_COMMITTER_NAME}) {
225 my $name = join('', run_or_non("git", "config", "user.name"));
226 if (! length $name) {
227 run_or_die("git", "config", "user.name", "IkiWiki");
231 if (! length $ENV{GIT_AUTHOR_EMAIL} || ! length $ENV{GIT_COMMITTER_EMAIL}) {
232 my $email = join('', run_or_non("git", "config", "user.email"));
233 if (! length $email) {
234 run_or_die("git", "config", "user.email", "ikiwiki.info");
239 sub merge_past ($$$) {
240 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
241 # Git merge commands work with the committed changes, except in the
242 # implicit case of '-m' of git checkout(1). So we should invent a
243 # kludge here. In principle, we need to create a throw-away branch
244 # in preparing for the merge itself. Since branches are cheap (and
245 # branching is fast), this shouldn't cost high.
247 # The main problem is the presence of _uncommitted_ local changes. One
248 # possible approach to get rid of this situation could be that we first
249 # make a temporary commit in the master branch and later restore the
250 # initial state (this is possible since Git has the ability to undo a
251 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
254 # - create a diff of HEAD:current-sha1
256 # - create a dummy branch and switch to it
257 # - rewind to past (reset --hard to the current-sha1)
258 # - apply the diff and commit
259 # - switch to master and do the merge with the dummy branch
260 # - make a soft reset (undo the last commit of master)
262 # The above method has some drawbacks: (1) it needs a redundant commit
263 # just to get rid of local changes, (2) somewhat slow because of the
264 # required system forks. Until someone points a more straight method
265 # (which I would be grateful) I have implemented an alternative method.
266 # In this approach, we hide all the modified files from Git by renaming
267 # them (using the 'rename' builtin) and later restore those files in
268 # the throw-away branch (that is, we put the files themselves instead
269 # of applying a patch).
271 my ($sha1, $file, $message) = @_;
273 my @undo; # undo stack for cleanup in case of an error
274 my $conflict; # file content with conflict markers
279 # Hide local changes from Git by renaming the modified file.
280 # Relative paths must be converted to absolute for renaming.
281 my ($target, $hidden) = (
282 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
284 rename($target, $hidden)
285 or error("rename '$target' to '$hidden' failed: $!");
286 # Ensure to restore the renamed file on error.
288 return if ! -e "$hidden"; # already renamed
289 rename($hidden, $target)
290 or warn "rename '$hidden' to '$target' failed: $!";
293 my $branch = "throw_away_${sha1}"; # supposed to be unique
295 # Create a throw-away branch and rewind backward.
296 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
297 run_or_die('git', 'branch', $branch, $sha1);
299 # Switch to throw-away branch for the merge operation.
301 if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
302 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
305 run_or_die('git', 'checkout', $branch);
307 # Put the modified file in _this_ branch.
308 rename($hidden, $target)
309 or error("rename '$hidden' to '$target' failed: $!");
311 # _Silently_ commit all modifications in the current branch.
312 run_or_non('git', 'commit', '-m', $message, '-a');
313 # ... and re-switch to master.
314 run_or_die('git', 'checkout', $config{gitmaster_branch});
316 # Attempt to merge without complaining.
317 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
318 $conflict = readfile($target);
319 run_or_die('git', 'reset', '--hard');
324 # Process undo stack (in reverse order). By policy cleanup
325 # actions should normally print a warning on failure.
326 while (my $handle = pop @undo) {
330 error("Git merge failed!\n$failure\n") if $failure;
335 sub decode_git_file ($) {
338 # git does not output utf-8 filenames, but instead
339 # double-quotes them with the utf-8 characters
340 # escaped as \nnn\nnn.
341 if ($file =~ m/^"(.*)"$/) {
342 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
345 # strip prefix if in a subdir
346 if (! defined $prefix) {
347 ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
348 if (! defined $prefix) {
352 $file =~ s/^\Q$prefix\E//;
354 return decode("utf8", $file);
357 sub parse_diff_tree ($) {
358 # Parse the raw diff tree chunk and return the info hash.
359 # See git-diff-tree(1) for the syntax.
363 return if ! @{ $dt_ref } ||
364 !defined $dt_ref->[0] || !length $dt_ref->[0];
368 while (my $line = shift @{ $dt_ref }) {
369 return if $line !~ m/^(.+) ($sha1_pattern)/;
376 # Identification lines for the commit.
377 while (my $line = shift @{ $dt_ref }) {
378 # Regexps are semi-stolen from gitweb.cgi.
379 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
382 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
383 # XXX: collecting in reverse order
384 push @{ $ci{'parents'} }, $1;
386 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
387 my ($who, $name, $epoch, $tz) =
391 $ci{ "${who}_epoch" } = $epoch;
392 $ci{ "${who}_tz" } = $tz;
394 if ($name =~ m/^([^<]+)\s+<([^@>]+)/) {
395 $ci{"${who}_name"} = $1;
396 $ci{"${who}_username"} = $2;
398 elsif ($name =~ m/^([^<]+)\s+<>$/) {
399 $ci{"${who}_username"} = $1;
402 $ci{"${who}_username"} = $name;
405 elsif ($line =~ m/^$/) {
406 # Trailing empty line signals next section.
411 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
413 if (defined $ci{'parents'}) {
414 $ci{'parent'} = @{ $ci{'parents'} }[0];
417 $ci{'parent'} = 0 x 40;
420 # Commit message (optional).
421 while ($dt_ref->[0] =~ /^ /) {
422 my $line = shift @{ $dt_ref };
424 push @{ $ci{'comment'} }, $line;
426 shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
429 while (my $line = shift @{ $dt_ref }) {
431 (:+) # number of parents
432 ([^\t]+)\t # modes, sha1, status
435 my $num_parents = length $1;
436 my @tmp = split(" ", $2);
437 my ($file, $file_to) = split("\t", $3);
438 my @mode_from = splice(@tmp, 0, $num_parents);
439 my $mode_to = shift(@tmp);
440 my @sha1_from = splice(@tmp, 0, $num_parents);
441 my $sha1_to = shift(@tmp);
442 my $status = shift(@tmp);
445 push @{ $ci{'details'} }, {
446 'file' => decode_git_file($file),
447 'sha1_from' => $sha1_from[0],
448 'sha1_to' => $sha1_to,
449 'mode_from' => $mode_from[0],
450 'mode_to' => $mode_to,
462 sub git_commit_info ($;$) {
463 # Return an array of commit info hashes of num commits
464 # starting from the given sha1sum.
465 my ($sha1, $num) = @_;
468 push @opts, "--max-count=$num" if defined $num;
470 my @raw_lines = run_or_die('git', 'log', @opts,
471 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
472 '-r', $sha1, '--no-renames', '--', '.');
475 while (my $parsed = parse_diff_tree(\@raw_lines)) {
479 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
481 return wantarray ? @ci : $ci[0];
484 sub rcs_find_changes ($) {
487 # Note that git log will sometimes show files being added that
488 # don't exist. Particularly, git merge -s ours can result in a
489 # merge commit where some files were not really added.
490 # This is why the code below verifies that the files really
492 my @raw_lines = run_or_die('git', 'log',
493 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
494 '--no-renames', , '--reverse',
495 '-r', "$oldrev..HEAD", '--', '.');
497 # Due to --reverse, we see changes in chronological order.
500 my $nullsha = 0 x 40;
502 while (my $ci = parse_diff_tree(\@raw_lines)) {
504 foreach my $i (@{$ci->{details}}) {
506 if ($i->{sha1_to} eq $nullsha) {
507 if (! -e "$config{srcdir}/$file") {
508 delete $changed{$file};
513 if (-e "$config{srcdir}/$file") {
514 delete $deleted{$file};
521 return (\%changed, \%deleted, $newrev);
524 sub git_sha1_file ($) {
526 git_sha1("--", $file);
530 # Ignore error since a non-existing file might be given.
531 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
534 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
536 return defined $sha1 ? $sha1 : '';
539 sub rcs_get_current_rev () {
544 # Update working directory.
548 if (length $config{gitorigin_branch}) {
549 run_or_cry('git', 'pull', '--prune', $config{gitorigin_branch});
553 sub rcs_prepedit ($) {
554 # Return the commit sha1sum of the file when editing begins.
555 # This will be later used in rcs_commit if a merge is required.
558 return git_sha1_file($file);
562 # Try to commit the page; returns undef on _success_ and
563 # a version of the page with the rcs's conflict markers on
567 # Check to see if the page has been changed by someone else since
568 # rcs_prepedit was called.
569 my $cur = git_sha1_file($params{file});
571 if (defined $params{token}) {
572 ($prev) = $params{token} =~ /^($sha1_pattern)$/; # untaint
575 if (defined $cur && defined $prev && $cur ne $prev) {
576 my $conflict = merge_past($prev, $params{file}, $dummy_commit_msg);
577 return $conflict if defined $conflict;
580 return rcs_commit_helper(@_);
583 sub rcs_commit_staged (@) {
584 # Commits all staged changes. Changes can be staged using rcs_add,
585 # rcs_remove, and rcs_rename.
586 return rcs_commit_helper(@_);
589 sub rcs_commit_helper (@) {
594 if (defined $params{session}) {
595 # Set the commit author and email based on web session info.
597 if (defined $params{session}->param("name")) {
598 $u=$params{session}->param("name");
600 elsif (defined $params{session}->remote_addr()) {
601 $u=$params{session}->remote_addr();
605 $ENV{GIT_AUTHOR_NAME}=$u;
610 if (defined $params{session}->param("nickname")) {
611 $u=encode_utf8($params{session}->param("nickname"));
613 $u=~s/[^-_0-9[:alnum:]]+//g;
616 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
619 $ENV{GIT_AUTHOR_EMAIL}='anonymous@web';
625 $params{message} = IkiWiki::possibly_foolish_untaint($params{message});
627 if ($params{message} !~ /\S/) {
628 # Force git to allow empty commit messages.
629 # (If this version of git supports it.)
630 my ($version)=`git --version` =~ /git version (.*)/;
631 if ($version ge "1.7.8") {
632 push @opts, "--allow-empty-message", "--no-edit";
634 if ($version ge "1.7.2") {
635 push @opts, "--allow-empty-message";
637 elsif ($version ge "1.5.4") {
638 push @opts, '--cleanup=verbatim';
641 $params{message}.=".";
644 if (exists $params{file}) {
645 push @opts, '--', $params{file};
647 # git commit returns non-zero if nothing really changed.
648 # So we should ignore its exit status (hence run_or_non).
649 if (run_or_non('git', 'commit', '-m', $params{message}, '-q', @opts)) {
650 if (length $config{gitorigin_branch}) {
651 run_or_cry('git', 'push', $config{gitorigin_branch}, $config{gitmaster_branch});
656 return undef; # success
660 # Add file to archive.
666 run_or_cry('git', 'add', '--', $file);
670 # Remove file from archive.
676 run_or_cry('git', 'rm', '-f', '--', $file);
679 sub rcs_rename ($$) {
680 my ($src, $dest) = @_;
684 run_or_cry('git', 'mv', '-f', '--', $src, $dest);
687 sub rcs_recentchanges ($) {
688 # List of recent changes.
692 eval q{use Date::Parse};
696 foreach my $ci (git_commit_info('HEAD', $num || 1)) {
697 # Skip redundant commits.
698 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
700 my ($sha1, $when) = (
702 $ci->{'author_epoch'}
706 foreach my $detail (@{ $ci->{'details'} }) {
707 my $file = $detail->{'file'};
708 my $efile = join('/',
709 map { uri_escape_utf8($_) } split('/', $file)
712 my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
713 $diffurl =~ s/\[\[file\]\]/$efile/go;
714 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
715 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
716 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
717 $diffurl =~ s/\[\[sha1_commit\]\]/$sha1/go;
720 page => pagename($file),
727 foreach my $line (@{$ci->{'comment'}}) {
728 $pastblank=1 if $line eq '';
729 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
730 push @messages, { line => $line };
733 my $user=$ci->{'author_username'};
734 my $web_commit = ($ci->{'author'} =~ /\@web>/);
737 # Set nickname only if a non-url author_username is available,
738 # and author_name is an url.
739 if ($user !~ /:\/\// && defined $ci->{'author_name'} &&
740 $ci->{'author_name'} =~ /:\/\//) {
742 $user=$ci->{'author_name'};
745 # compatability code for old web commit messages
747 defined $messages[0] &&
748 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
749 $user = defined $2 ? "$2" : "$3";
750 $messages[0]->{line} = $4;
757 nickname => $nickname,
758 committype => $web_commit ? "web" : "git",
760 message => [@messages],
764 last if @rets >= $num;
773 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
777 return if defined $maxlines && @lines == $maxlines;
778 push @lines, $line."\n"
779 if (@lines || $line=~/^diff --git/);
782 safe_git(undef, $addlines, "git", "show", $sha1);
787 return join("", @lines);
796 my $id=shift; # 0 = mtime ; 1 = ctime
798 if (! keys %time_cache) {
800 foreach my $line (run_or_die('git', 'log',
801 '--pretty=format:%at',
802 '--name-only', '--relative')) {
803 if (! defined $date && $line =~ /^(\d+)$/) {
806 elsif (! length $line) {
810 my $f=decode_git_file($line);
812 if (! $time_cache{$f}) {
813 $time_cache{$f}[0]=$date; # mtime
815 $time_cache{$f}[1]=$date; # ctime
820 return exists $time_cache{$file} ? $time_cache{$file}[$id] : 0;
825 sub rcs_getctime ($) {
828 return findtimes($file, 1);
831 sub rcs_getmtime ($) {
834 return findtimes($file, 0);
840 # The wiki may not be the only thing in the git repo.
841 # Determine if it is in a subdirectory by examining the srcdir,
842 # and its parents, looking for the .git directory.
844 return @$ret if defined $ret;
847 my $dir=$config{srcdir};
848 while (! -d "$dir/.git") {
849 $subdir=IkiWiki::basename($dir)."/".$subdir;
850 $dir=IkiWiki::dirname($dir);
852 error("cannot determine root of git repo");
856 $ret=[$subdir, $dir];
862 sub git_parse_changes {
863 my $reverted = shift;
866 my ($subdir, $rootdir) = git_find_root();
868 foreach my $ci (@changes) {
869 foreach my $detail (@{ $ci->{'details'} }) {
870 my $file = $detail->{'file'};
872 # check that all changed files are in the subdir
873 if (length $subdir &&
874 ! ($file =~ s/^\Q$subdir\E//)) {
875 error sprintf(gettext("you are not allowed to change %s"), $file);
878 my ($action, $mode, $path);
879 if ($detail->{'status'} =~ /^[M]+\d*$/) {
881 $mode=$detail->{'mode_to'};
883 elsif ($detail->{'status'} =~ /^[AM]+\d*$/) {
884 $action= $reverted ? "remove" : "add";
885 $mode=$detail->{'mode_to'};
887 elsif ($detail->{'status'} =~ /^[DAM]+\d*/) {
888 $action= $reverted ? "add" : "remove";
889 $mode=$detail->{'mode_from'};
892 error "unknown status ".$detail->{'status'};
895 # test that the file mode is ok
896 if ($mode !~ /^100[64][64][64]$/) {
897 error sprintf(gettext("you cannot act on a file with mode %s"), $mode);
899 if ($action eq "change") {
900 if ($detail->{'mode_from'} ne $detail->{'mode_to'}) {
901 error gettext("you are not allowed to change file modes");
905 # extract attachment to temp file
906 if (($action eq 'add' || $action eq 'change') &&
908 eval q{use File::Temp};
911 ($fh, $path)=File::Temp::tempfile(undef, UNLINK => 1);
912 my $cmd = "cd $git_dir && ".
913 "git show $detail->{sha1_to} > '$path'";
914 if (system($cmd) != 0) {
915 error("failed writing temp file '$path'.");
934 my ($oldrev, $newrev, $refname) = split(' ', $_, 3);
936 # only allow changes to gitmaster_branch
937 if ($refname !~ /^refs\/heads\/\Q$config{gitmaster_branch}\E$/) {
938 error sprintf(gettext("you are not allowed to change %s"), $refname);
941 # Avoid chdir when running git here, because the changes
942 # are in the master git repo, not the srcdir repo.
943 # (Also, if a subdir is involved, we don't want to chdir to
944 # it and only see changes in it.)
945 # The pre-receive hook already puts us in the right place.
946 in_git_dir(".", sub {
947 push @rets, git_parse_changes(0, git_commit_info($oldrev."..".$newrev));
951 return reverse @rets;
954 sub rcs_preprevert ($) {
956 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
958 # Examine changes from root of git repo, not from any subdir,
959 # in order to see all changes.
960 my ($subdir, $rootdir) = git_find_root();
961 in_git_dir($rootdir, sub {
962 my @commits=git_commit_info($sha1, 1);
965 error "unknown commit"; # just in case
968 # git revert will fail on merge commits. Add a nice message.
969 if (exists $commits[0]->{parents} &&
970 @{$commits[0]->{parents}} > 1) {
971 error gettext("you are not allowed to revert a merge");
974 git_parse_changes(1, @commits);
979 # Try to revert the given rev; returns undef on _success_.
981 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
985 if (run_or_non('git', 'revert', '--no-commit', $sha1)) {
989 run_or_die('git', 'reset', '--hard');
990 return sprintf(gettext("Failed to revert commit %s"), $sha1);