7 binmode(STDOUT
, ":raw");
9 my $repo = Git
->repository();
11 my $menu_use_color = $repo->get_colorbool('color.interactive');
12 my ($prompt_color, $header_color, $help_color) =
14 $repo->get_color('color.interactive.prompt', 'bold blue'),
15 $repo->get_color('color.interactive.header', 'bold'),
16 $repo->get_color('color.interactive.help', 'red bold'),
19 if ($menu_use_color) {
20 my $help_color_spec = ($repo->config('color.interactive.help') or
22 $error_color = $repo->get_color('color.interactive.error',
26 my $diff_use_color = $repo->get_colorbool('color.diff');
27 my ($fraginfo_color) =
29 $repo->get_color('color.diff.frag', 'cyan'),
31 my ($diff_plain_color) =
33 $repo->get_color('color.diff.plain', ''),
35 my ($diff_old_color) =
37 $repo->get_color('color.diff.old', 'red'),
39 my ($diff_new_color) =
41 $repo->get_color('color.diff.new', 'green'),
44 my $normal_color = $repo->get_color("", "reset");
49 if ($repo->config_bool("interactive.singlekey")) {
51 require Term
::ReadKey
;
52 Term
::ReadKey
->import;
59 my $string = join("", @_);
62 # Put a color code at the beginning of each line, a reset at the end
63 # color after newlines that are not at the end of the string
64 $string =~ s/(\n+)(.)/$1$color$2/g;
65 # reset before newlines
66 $string =~ s/(\n+)/$normal_color$1/g;
67 # codes at beginning and end (if necessary):
68 $string =~ s/^/$color/;
69 $string =~ s/$/$normal_color/ unless $string =~ /\n$/;
74 # command line options
76 my $patch_mode_revision;
79 sub apply_patch_for_checkout_commit
;
80 sub apply_patch_for_stash
;
84 DIFF
=> 'diff-files -p',
85 APPLY
=> sub { apply_patch
'apply --cached', @_; },
86 APPLY_CHECK
=> 'apply --cached',
89 PARTICIPLE
=> 'staging',
90 FILTER
=> 'file-only',
93 DIFF
=> 'diff-index -p HEAD',
94 APPLY
=> sub { apply_patch
'apply --cached', @_; },
95 APPLY_CHECK
=> 'apply --cached',
98 PARTICIPLE
=> 'stashing',
102 DIFF
=> 'diff-index -p --cached',
103 APPLY
=> sub { apply_patch
'apply -R --cached', @_; },
104 APPLY_CHECK
=> 'apply -R --cached',
107 PARTICIPLE
=> 'unstaging',
108 FILTER
=> 'index-only',
111 DIFF
=> 'diff-index -R -p --cached',
112 APPLY
=> sub { apply_patch
'apply --cached', @_; },
113 APPLY_CHECK
=> 'apply --cached',
115 TARGET
=> ' to index',
116 PARTICIPLE
=> 'applying',
117 FILTER
=> 'index-only',
119 'checkout_index' => {
120 DIFF
=> 'diff-files -p',
121 APPLY
=> sub { apply_patch
'apply -R', @_; },
122 APPLY_CHECK
=> 'apply -R',
124 TARGET
=> ' from worktree',
125 PARTICIPLE
=> 'discarding',
126 FILTER
=> 'file-only',
129 DIFF
=> 'diff-index -p',
130 APPLY
=> sub { apply_patch_for_checkout_commit
'-R', @_ },
131 APPLY_CHECK
=> 'apply -R',
133 TARGET
=> ' from index and worktree',
134 PARTICIPLE
=> 'discarding',
137 'checkout_nothead' => {
138 DIFF
=> 'diff-index -R -p',
139 APPLY
=> sub { apply_patch_for_checkout_commit
'', @_ },
140 APPLY_CHECK
=> 'apply',
142 TARGET
=> ' to index and worktree',
143 PARTICIPLE
=> 'applying',
148 my %patch_mode_flavour = %{$patch_modes{stage
}};
151 if ($^O
eq 'MSWin32' || $^O
eq 'msys') {
152 my @invalid = grep {m/[":*]/} @_;
153 die "$^O does not support: @invalid\n" if @invalid;
154 my @args = map { m/ /o ?
"\"$_\"": $_ } @_;
158 open($fh, '-|', @_) or die;
163 my ($GIT_DIR) = run_cmd_pipe
(qw(git rev-parse --git-dir));
165 if (!defined $GIT_DIR) {
166 exit(1); # rev-parse would have already said "not a git repo"
183 my ($retval, $remainder);
184 if (!/^\042(.*)\042$/) {
187 ($_, $retval) = ($1, "");
188 while (/^([^\\]*)\\(.*)$/) {
192 if (/^([0-3][0-7][0-7])(.*)$/) {
193 $retval .= chr(oct($1));
197 if (/^([\\\042btnvfr])(.*)$/) {
198 $retval .= $cquote_map{$1};
202 # This is malformed -- just return it as-is for now.
213 open $fh, 'git update-index --refresh |'
216 ;# ignore 'needs update'
226 run_cmd_pipe
(qw(git ls-files --others --exclude-standard --), @ARGV);
229 my $status_fmt = '%12s %12s %s';
230 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
234 sub is_initial_commit
{
235 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
236 unless defined $initial;
242 return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
245 # Returns list of hashes, contents of each of which are:
247 # BINARY: is a binary path
248 # INDEX: is index different from HEAD?
249 # FILE: is file different from index?
250 # INDEX_ADDDEL: is it add/delete between HEAD and index?
251 # FILE_ADDDEL: is it add/delete between index and file?
256 my ($add, $del, $adddel, $file);
263 } run_cmd_pipe
(qw(git ls-files --), @ARGV);
264 return if (!@tracked);
268 if (defined $patch_mode_revision and $patch_mode_revision ne 'HEAD') {
269 $reference = $patch_mode_revision;
270 } elsif (is_initial_commit
()) {
271 $reference = get_empty_tree
();
275 for (run_cmd_pipe
(qw(git diff-index --cached
276 --numstat --summary), $reference,
278 if (($add, $del, $file) =
279 /^([-\d]+) ([-\d]+) (.*)/) {
281 $file = unquote_path
($file);
282 if ($add eq '-' && $del eq '-') {
287 $change = "+$add/-$del";
295 elsif (($adddel, $file) =
296 /^ (create|delete) mode [0-7]+ (.*)$/) {
297 $file = unquote_path
($file);
298 $data{$file}{INDEX_ADDDEL
} = $adddel;
302 for (run_cmd_pipe
(qw(git diff-files --numstat --summary --), @tracked)) {
303 if (($add, $del, $file) =
304 /^([-\d]+) ([-\d]+) (.*)/) {
305 $file = unquote_path
($file);
306 if (!exists $data{$file}) {
308 INDEX
=> 'unchanged',
313 if ($add eq '-' && $del eq '-') {
318 $change = "+$add/-$del";
320 $data{$file}{FILE
} = $change;
322 $data{$file}{BINARY
} = 1;
325 elsif (($adddel, $file) =
326 /^ (create|delete) mode [0-7]+ (.*)$/) {
327 $file = unquote_path
($file);
328 $data{$file}{FILE_ADDDEL
} = $adddel;
332 for (sort keys %data) {
336 if ($only eq 'index-only') {
337 next if ($it->{INDEX
} eq 'unchanged');
339 if ($only eq 'file-only') {
340 next if ($it->{FILE
} eq 'nothing');
352 my ($string, @stuff) = @_;
354 for (my $i = 0; $i < @stuff; $i++) {
358 if ((ref $it) eq 'ARRAY') {
366 if ($it =~ /^$string/) {
370 if (defined $hit && defined $found) {
380 # inserts string into trie and updates count for each character
382 my ($trie, $string) = @_;
383 foreach (split //, $string) {
384 $trie = $trie->{$_} ||= {COUNT
=> 0};
389 # returns an array of tuples (prefix, remainder)
390 sub find_unique_prefixes
{
394 # any single prefix exceeding the soft limit is omitted
395 # if any prefix exceeds the hard limit all are omitted
396 # 0 indicates no limit
400 # build a trie modelling all possible options
402 foreach my $print (@stuff) {
403 if ((ref $print) eq 'ARRAY') {
404 $print = $print->[0];
406 elsif ((ref $print) eq 'HASH') {
407 $print = $print->{VALUE
};
409 update_trie
(\
%trie, $print);
410 push @return, $print;
413 # use the trie to find the unique prefixes
414 for (my $i = 0; $i < @return; $i++) {
415 my $ret = $return[$i];
416 my @letters = split //, $ret;
418 my ($prefix, $remainder);
420 for ($j = 0; $j < @letters; $j++) {
421 my $letter = $letters[$j];
422 if ($search{$letter}{COUNT
} == 1) {
423 $prefix = substr $ret, 0, $j + 1;
424 $remainder = substr $ret, $j + 1;
428 my $prefix = substr $ret, 0, $j;
430 if ($hard_limit && $j + 1 > $hard_limit);
432 %search = %{$search{$letter}};
434 if (ord($letters[0]) > 127 ||
435 ($soft_limit && $j + 1 > $soft_limit)) {
439 $return[$i] = [$prefix, $remainder];
444 # filters out prefixes which have special meaning to list_and_choose()
445 sub is_valid_prefix
{
447 return (defined $prefix) &&
448 !($prefix =~ /[\s,]/) && # separators
449 !($prefix =~ /^-/) && # deselection
450 !($prefix =~ /^\d+/) && # selection
451 ($prefix ne '*') && # "all" wildcard
452 ($prefix ne '?'); # prompt help
455 # given a prefix/remainder tuple return a string with the prefix highlighted
456 # for now use square brackets; later might use ANSI colors (underline, bold)
457 sub highlight_prefix
{
459 my $remainder = shift;
461 if (!defined $prefix) {
465 if (!is_valid_prefix
($prefix)) {
466 return "$prefix$remainder";
469 if (!$menu_use_color) {
470 return "[$prefix]$remainder";
473 return "$prompt_color$prefix$normal_color$remainder";
477 print STDERR colored
$error_color, @_;
480 sub list_and_choose
{
481 my ($opts, @stuff) = @_;
482 my (@chosen, @return);
484 my @prefixes = find_unique_prefixes
(@stuff) unless $opts->{LIST_ONLY
};
490 if ($opts->{HEADER
}) {
491 if (!$opts->{LIST_FLAT
}) {
494 print colored
$header_color, "$opts->{HEADER}\n";
496 for ($i = 0; $i < @stuff; $i++) {
497 my $chosen = $chosen[$i] ?
'*' : ' ';
498 my $print = $stuff[$i];
499 my $ref = ref $print;
500 my $highlighted = highlight_prefix
(@
{$prefixes[$i]})
502 if ($ref eq 'ARRAY') {
503 $print = $highlighted || $print->[0];
505 elsif ($ref eq 'HASH') {
506 my $value = $highlighted || $print->{VALUE
};
507 $print = sprintf($status_fmt,
513 $print = $highlighted || $print;
515 printf("%s%2d: %s", $chosen, $i+1, $print);
516 if (($opts->{LIST_FLAT
}) &&
517 (($i + 1) % ($opts->{LIST_FLAT
}))) {
530 return if ($opts->{LIST_ONLY
});
532 print colored
$prompt_color, $opts->{PROMPT
};
533 if ($opts->{SINGLETON
}) {
542 $opts->{ON_EOF
}->() if $opts->{ON_EOF
};
549 singleton_prompt_help_cmd
() :
553 for my $choice (split(/[\s,]+/, $line)) {
557 # Input that begins with '-'; unchoose
558 if ($choice =~ s/^-//) {
561 # A range can be specified like 5-7 or 5-.
562 if ($choice =~ /^(\d+)-(\d*)$/) {
563 ($bottom, $top) = ($1, length($2) ?
$2 : 1 + @stuff);
565 elsif ($choice =~ /^\d+$/) {
566 $bottom = $top = $choice;
568 elsif ($choice eq '*') {
573 $bottom = $top = find_unique
($choice, @stuff);
574 if (!defined $bottom) {
575 error_msg
"Huh ($choice)?\n";
579 if ($opts->{SINGLETON
} && $bottom != $top) {
580 error_msg
"Huh ($choice)?\n";
583 for ($i = $bottom-1; $i <= $top-1; $i++) {
584 next if (@stuff <= $i || $i < 0);
585 $chosen[$i] = $choose;
588 last if ($opts->{IMMEDIATE
} || $line eq '*');
590 for ($i = 0; $i < @stuff; $i++) {
592 push @return, $stuff[$i];
598 sub singleton_prompt_help_cmd
{
599 print colored
$help_color, <<\EOF
;
601 1 - select a numbered item
602 foo
- select item based on unique prefix
603 - (empty
) select nothing
607 sub prompt_help_cmd
{
608 print colored
$help_color, <<\EOF
;
610 1 - select a single item
611 3-5 - select a range of items
612 2-3,6-9 - select multiple ranges
613 foo
- select item based on unique prefix
614 -... - unselect specified items
616 - (empty
) finish selecting
621 list_and_choose
({ LIST_ONLY
=> 1, HEADER
=> $status_head },
631 print "$cnt paths\n";
639 my @mods = list_modified
('file-only');
642 my @update = list_and_choose
({ PROMPT
=> 'Update',
643 HEADER
=> $status_head, },
646 system(qw(git update-index --add --remove --),
647 map { $_->{VALUE
} } @update);
648 say_n_paths
('updated', @update);
654 my @update = list_and_choose
({ PROMPT
=> 'Revert',
655 HEADER
=> $status_head, },
658 if (is_initial_commit
()) {
659 system(qw(git rm --cached),
660 map { $_->{VALUE
} } @update);
663 my @lines = run_cmd_pipe
(qw(git ls-tree HEAD --),
664 map { $_->{VALUE
} } @update);
666 open $fh, '| git update-index --index-info'
673 if ($_->{INDEX_ADDDEL
} &&
674 $_->{INDEX_ADDDEL
} eq 'create') {
675 system(qw(git update-index --force-remove --),
677 print "note: $_->{VALUE} is untracked now.\n";
682 say_n_paths
('reverted', @update);
687 sub add_untracked_cmd
{
688 my @add = list_and_choose
({ PROMPT
=> 'Add untracked' },
691 system(qw(git update-index --add --), @add);
692 say_n_paths
('added', @add);
700 open $fh, '| git ' . $cmd;
707 my @diff_cmd = split(" ", $patch_mode_flavour{DIFF
});
708 if (defined $patch_mode_revision) {
709 push @diff_cmd, $patch_mode_revision;
711 my @diff = run_cmd_pipe
("git", @diff_cmd, "--", $path);
713 if ($diff_use_color) {
714 @colored = run_cmd_pipe
("git", @diff_cmd, qw(--color --), $path);
716 my (@hunk) = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'header' };
718 for (my $i = 0; $i < @diff; $i++) {
719 if ($diff[$i] =~ /^@@ /) {
720 push @hunk, { TEXT
=> [], DISPLAY
=> [],
723 push @
{$hunk[-1]{TEXT
}}, $diff[$i];
724 push @
{$hunk[-1]{DISPLAY
}},
725 ($diff_use_color ?
$colored[$i] : $diff[$i]);
730 sub parse_diff_header
{
733 my $head = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'header' };
734 my $mode = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'mode' };
735 my $deletion = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'deletion' };
737 for (my $i = 0; $i < @
{$src->{TEXT
}}; $i++) {
739 $src->{TEXT
}->[$i] =~ /^(old|new) mode (\d+)$/ ?
$mode :
740 $src->{TEXT
}->[$i] =~ /^deleted file/ ?
$deletion :
742 push @
{$dest->{TEXT
}}, $src->{TEXT
}->[$i];
743 push @
{$dest->{DISPLAY
}}, $src->{DISPLAY
}->[$i];
745 return ($head, $mode, $deletion);
748 sub hunk_splittable
{
751 my @s = split_hunk
($text);
755 sub parse_hunk_header
{
757 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
758 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
759 $o_cnt = 1 unless defined $o_cnt;
760 $n_cnt = 1 unless defined $n_cnt;
761 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
765 my ($text, $display) = @_;
767 if (!defined $display) {
770 # If there are context lines in the middle of a hunk,
771 # it can be split, but we would need to take care of
774 my ($o_ofs, undef, $n_ofs) = parse_hunk_header
($text->[0]);
779 my $next_hunk_start = undef;
780 my $i = $hunk_start - 1;
794 while (++$i < @
$text) {
795 my $line = $text->[$i];
796 my $display = $display->[$i];
798 if ($this->{ADDDEL
} &&
799 !defined $next_hunk_start) {
800 # We have seen leading context and
801 # adds/dels and then here is another
802 # context, which is trailing for this
803 # split hunk and leading for the next
805 $next_hunk_start = $i;
807 push @
{$this->{TEXT
}}, $line;
808 push @
{$this->{DISPLAY
}}, $display;
811 if (defined $next_hunk_start) {
818 if (defined $next_hunk_start) {
819 # We are done with the current hunk and
820 # this is the first real change for the
822 $hunk_start = $next_hunk_start;
823 $o_ofs = $this->{OLD
} + $this->{OCNT
};
824 $n_ofs = $this->{NEW
} + $this->{NCNT
};
825 $o_ofs -= $this->{POSTCTX
};
826 $n_ofs -= $this->{POSTCTX
};
830 push @
{$this->{TEXT
}}, $line;
831 push @
{$this->{DISPLAY
}}, $display;
845 for my $hunk (@split) {
846 $o_ofs = $hunk->{OLD
};
847 $n_ofs = $hunk->{NEW
};
848 my $o_cnt = $hunk->{OCNT
};
849 my $n_cnt = $hunk->{NCNT
};
851 my $head = ("@@ -$o_ofs" .
852 (($o_cnt != 1) ?
",$o_cnt" : '') .
854 (($n_cnt != 1) ?
",$n_cnt" : '') .
856 my $display_head = $head;
857 unshift @
{$hunk->{TEXT
}}, $head;
858 if ($diff_use_color) {
859 $display_head = colored
($fraginfo_color, $head);
861 unshift @
{$hunk->{DISPLAY
}}, $display_head;
866 sub find_last_o_ctx
{
868 my $text = $it->{TEXT
};
869 my ($o_ofs, $o_cnt) = parse_hunk_header
($text->[0]);
871 my $last_o_ctx = $o_ofs + $o_cnt;
873 my $line = $text->[$i];
884 my ($prev, $this) = @_;
885 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
886 parse_hunk_header
($prev->{TEXT
}[0]);
887 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
888 parse_hunk_header
($this->{TEXT
}[0]);
890 my (@line, $i, $ofs, $o_cnt, $n_cnt);
893 for ($i = 1; $i < @
{$prev->{TEXT
}}; $i++) {
894 my $line = $prev->{TEXT
}[$i];
895 if ($line =~ /^\+/) {
901 last if ($o1_ofs <= $ofs);
911 for ($i = 1; $i < @
{$this->{TEXT
}}; $i++) {
912 my $line = $this->{TEXT
}[$i];
913 if ($line =~ /^\+/) {
925 my $head = ("@@ -$o0_ofs" .
926 (($o_cnt != 1) ?
",$o_cnt" : '') .
928 (($n_cnt != 1) ?
",$n_cnt" : '') .
930 @
{$prev->{TEXT
}} = ($head, @line);
933 sub coalesce_overlapping_hunks
{
937 my ($last_o_ctx, $last_was_dirty);
939 for (grep { $_->{USE
} } @in) {
940 if ($_->{TYPE
} ne 'hunk') {
944 my $text = $_->{TEXT
};
945 my ($o_ofs) = parse_hunk_header
($text->[0]);
946 if (defined $last_o_ctx &&
947 $o_ofs <= $last_o_ctx &&
950 merge_hunk
($out[-1], $_);
955 $last_o_ctx = find_last_o_ctx
($out[-1]);
956 $last_was_dirty = $_->{DIRTY
};
961 sub reassemble_patch
{
965 # Include everything in the header except the beginning of the diff.
966 push @patch, (grep { !/^[-+]{3}/ } @
$head);
968 # Then include any headers from the hunk lines, which must
969 # come before any actual hunk.
970 while (@_ && $_[0] !~ /^@/) {
974 # Then begin the diff.
975 push @patch, grep { /^[-+]{3}/ } @
$head;
977 # And then the actual hunks.
985 colored
((/^@/ ?
$fraginfo_color :
986 /^\+/ ?
$diff_new_color :
987 /^-/ ?
$diff_old_color :
993 sub edit_hunk_manually
{
996 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
998 open $fh, '>', $hunkfile
999 or die "failed to open hunk edit file for writing: " . $!;
1000 print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
1001 print $fh @
$oldtext;
1002 my $participle = $patch_mode_flavour{PARTICIPLE
};
1005 # To remove '-' lines, make them ' ' lines (context).
1006 # To remove '+' lines, delete them.
1007 # Lines starting with # will be removed.
1009 # If the patch applies cleanly, the edited hunk will immediately be
1010 # marked for $participle. If it does not apply cleanly, you will be given
1011 # an opportunity to edit again. If all lines of the hunk are removed,
1012 # then the edit is aborted and the hunk is left unchanged.
1016 chomp(my $editor = run_cmd_pipe
(qw(git var GIT_EDITOR)));
1017 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
1023 open $fh, '<', $hunkfile
1024 or die "failed to open hunk edit file for reading: " . $!;
1025 my @newtext = grep { !/^#/ } <$fh>;
1029 # Abort if nothing remains
1030 if (!grep { /\S/ } @newtext) {
1034 # Reinsert the first hunk header if the user accidentally deleted it
1035 if ($newtext[0] !~ /^@/) {
1036 unshift @newtext, $oldtext->[0];
1043 return run_git_apply
($patch_mode_flavour{APPLY_CHECK
} . ' --recount --check',
1044 map { @
{$_->{TEXT
}} } @_);
1047 sub _restore_terminal_and_die
{
1053 sub prompt_single_character
{
1055 local $SIG{TERM
} = \
&_restore_terminal_and_die
;
1056 local $SIG{INT
} = \
&_restore_terminal_and_die
;
1058 my $key = ReadKey
0;
1060 print "$key" if defined $key;
1071 print colored
$prompt_color, $prompt;
1072 my $line = prompt_single_character
;
1073 return 0 if $line =~ /^n/i;
1074 return 1 if $line =~ /^y/i;
1078 sub edit_hunk_loop
{
1079 my ($head, $hunk, $ix) = @_;
1080 my $text = $hunk->[$ix]->{TEXT
};
1083 $text = edit_hunk_manually
($text);
1084 if (!defined $text) {
1089 TYPE
=> $hunk->[$ix]->{TYPE
},
1093 if (diff_applies
($head,
1096 @
{$hunk}[$ix+1..$#{$hunk}])) {
1097 $newhunk->{DISPLAY
} = [color_diff
(@
{$text})];
1102 'Your edited hunk does not apply. Edit again '
1103 . '(saying "no" discards!) [y/n]? '
1109 sub help_patch_cmd
{
1110 my $verb = lc $patch_mode_flavour{VERB
};
1111 my $target = $patch_mode_flavour{TARGET
};
1112 print colored
$help_color, <<EOF ;
1113 y - $verb this hunk$target
1114 n - do not $verb this hunk$target
1115 q - quit; do not $verb this hunk nor any of the remaining ones
1116 a - $verb this hunk and all later hunks in the file
1117 d - do not $verb this hunk nor any of the later hunks in the file
1118 g - select a hunk to go to
1119 / - search for a hunk matching the given regex
1120 j - leave this hunk undecided, see next undecided hunk
1121 J - leave this hunk undecided, see next hunk
1122 k - leave this hunk undecided, see previous undecided hunk
1123 K - leave this hunk undecided, see previous hunk
1124 s - split the current hunk into smaller hunks
1125 e - manually edit the current hunk
1132 my $ret = run_git_apply
$cmd . ' --recount', @_;
1139 sub apply_patch_for_checkout_commit
{
1140 my $reverse = shift;
1141 my $applies_index = run_git_apply
'apply '.$reverse.' --cached --recount --check', @_;
1142 my $applies_worktree = run_git_apply
'apply '.$reverse.' --recount --check', @_;
1144 if ($applies_worktree && $applies_index) {
1145 run_git_apply
'apply '.$reverse.' --cached --recount', @_;
1146 run_git_apply
'apply '.$reverse.' --recount', @_;
1148 } elsif (!$applies_index) {
1149 print colored
$error_color, "The selected hunks do not apply to the index!\n";
1150 if (prompt_yesno
"Apply them to the worktree anyway? ") {
1151 return run_git_apply
'apply '.$reverse.' --recount', @_;
1153 print colored
$error_color, "Nothing was applied.\n";
1162 sub patch_update_cmd
{
1163 my @all_mods = list_modified
($patch_mode_flavour{FILTER
});
1164 my @mods = grep { !($_->{BINARY
}) } @all_mods;
1169 print STDERR
"Only binary files changed.\n";
1171 print STDERR
"No changes.\n";
1179 @them = list_and_choose
({ PROMPT
=> 'Patch update',
1180 HEADER
=> $status_head, },
1184 return 0 if patch_update_file
($_->{VALUE
});
1188 # Generate a one line summary of a hunk.
1189 sub summarize_hunk
{
1191 my $summary = $rhunk->{TEXT
}[0];
1193 # Keep the line numbers, discard extra context.
1194 $summary =~ s/@@(.*?)@@.*/$1 /s;
1195 $summary .= " " x
(20 - length $summary);
1197 # Add some user context.
1198 for my $line (@
{$rhunk->{TEXT
}}) {
1199 if ($line =~ m/^[+-].*\w/) {
1206 return substr($summary, 0, 80) . "\n";
1210 # Print a one-line summary of each hunk in the array ref in
1211 # the first argument, starting wih the index in the 2nd.
1213 my ($hunks, $i) = @_;
1216 for (; $i < @
$hunks && $ctr < 20; $i++, $ctr++) {
1218 if (defined $hunks->[$i]{USE
}) {
1219 $status = $hunks->[$i]{USE
} ?
"+" : "-";
1224 summarize_hunk
($hunks->[$i]);
1229 sub patch_update_file
{
1233 my ($head, @hunk) = parse_diff
($path);
1234 ($head, my $mode, my $deletion) = parse_diff_header
($head);
1235 for (@
{$head->{DISPLAY
}}) {
1239 if (@
{$mode->{TEXT
}}) {
1240 unshift @hunk, $mode;
1242 if (@
{$deletion->{TEXT
}}) {
1243 foreach my $hunk (@hunk) {
1244 push @
{$deletion->{TEXT
}}, @
{$hunk->{TEXT
}};
1245 push @
{$deletion->{DISPLAY
}}, @
{$hunk->{DISPLAY
}};
1247 @hunk = ($deletion);
1250 $num = scalar @hunk;
1254 my ($prev, $next, $other, $undecided, $i);
1260 for ($i = 0; $i < $ix; $i++) {
1261 if (!defined $hunk[$i]{USE
}) {
1270 for ($i = $ix + 1; $i < $num; $i++) {
1271 if (!defined $hunk[$i]{USE
}) {
1277 if ($ix < $num - 1) {
1283 for ($i = 0; $i < $num; $i++) {
1284 if (!defined $hunk[$i]{USE
}) {
1289 last if (!$undecided);
1291 if ($hunk[$ix]{TYPE
} eq 'hunk' &&
1292 hunk_splittable
($hunk[$ix]{TEXT
})) {
1295 if ($hunk[$ix]{TYPE
} eq 'hunk') {
1298 for (@
{$hunk[$ix]{DISPLAY
}}) {
1301 print colored
$prompt_color, $patch_mode_flavour{VERB
},
1302 ($hunk[$ix]{TYPE
} eq 'mode' ?
' mode change' :
1303 $hunk[$ix]{TYPE
} eq 'deletion' ?
' deletion' :
1305 $patch_mode_flavour{TARGET
},
1306 " [y,n,q,a,d,/$other,?]? ";
1307 my $line = prompt_single_character
;
1309 if ($line =~ /^y/i) {
1310 $hunk[$ix]{USE
} = 1;
1312 elsif ($line =~ /^n/i) {
1313 $hunk[$ix]{USE
} = 0;
1315 elsif ($line =~ /^a/i) {
1316 while ($ix < $num) {
1317 if (!defined $hunk[$ix]{USE
}) {
1318 $hunk[$ix]{USE
} = 1;
1324 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1326 my $no = $ix > 10 ?
$ix - 10 : 0;
1327 while ($response eq '') {
1329 $no = display_hunks
(\
@hunk, $no);
1331 $extra = " (<ret> to see more)";
1333 print "go to which hunk$extra? ";
1334 $response = <STDIN
>;
1335 if (!defined $response) {
1340 if ($response !~ /^\s*\d+\s*$/) {
1341 error_msg
"Invalid number: '$response'\n";
1342 } elsif (0 < $response && $response <= $num) {
1343 $ix = $response - 1;
1345 error_msg
"Sorry, only $num hunks available.\n";
1349 elsif ($line =~ /^d/i) {
1350 while ($ix < $num) {
1351 if (!defined $hunk[$ix]{USE
}) {
1352 $hunk[$ix]{USE
} = 0;
1358 elsif ($line =~ /^q/i) {
1359 while ($ix < $num) {
1360 if (!defined $hunk[$ix]{USE
}) {
1361 $hunk[$ix]{USE
} = 0;
1368 elsif ($line =~ m
|^/(.*)|) {
1371 print colored
$prompt_color, "search for regex? ";
1373 if (defined $regex) {
1379 $search_string = qr{$regex}m;
1382 my ($err,$exp) = ($@
, $1);
1383 $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1384 error_msg
"Malformed search regexp $exp: $err\n";
1389 my $text = join ("", @
{$hunk[$iy]{TEXT
}});
1390 last if ($text =~ $search_string);
1392 $iy = 0 if ($iy >= $num);
1394 error_msg
"No hunk matches the given pattern\n";
1401 elsif ($line =~ /^K/) {
1402 if ($other =~ /K/) {
1406 error_msg
"No previous hunk\n";
1410 elsif ($line =~ /^J/) {
1411 if ($other =~ /J/) {
1415 error_msg
"No next hunk\n";
1419 elsif ($line =~ /^k/) {
1420 if ($other =~ /k/) {
1424 !defined $hunk[$ix]{USE
});
1428 error_msg
"No previous hunk\n";
1432 elsif ($line =~ /^j/) {
1433 if ($other !~ /j/) {
1434 error_msg
"No next hunk\n";
1438 elsif ($other =~ /s/ && $line =~ /^s/) {
1439 my @split = split_hunk
($hunk[$ix]{TEXT
}, $hunk[$ix]{DISPLAY
});
1441 print colored
$header_color, "Split into ",
1442 scalar(@split), " hunks.\n";
1444 splice (@hunk, $ix, 1, @split);
1445 $num = scalar @hunk;
1448 elsif ($other =~ /e/ && $line =~ /^e/) {
1449 my $newhunk = edit_hunk_loop
($head, \
@hunk, $ix);
1450 if (defined $newhunk) {
1451 splice @hunk, $ix, 1, $newhunk;
1455 help_patch_cmd
($other);
1461 last if ($ix >= $num ||
1462 !defined $hunk[$ix]{USE
});
1467 @hunk = coalesce_overlapping_hunks
(@hunk);
1473 push @result, @
{$_->{TEXT
}};
1479 my @patch = reassemble_patch
($head->{TEXT
}, @result);
1480 my $apply_routine = $patch_mode_flavour{APPLY
};
1481 &$apply_routine(@patch);
1490 my @mods = list_modified
('index-only');
1491 @mods = grep { !($_->{BINARY
}) } @mods;
1493 my (@them) = list_and_choose
({ PROMPT
=> 'Review diff',
1495 HEADER
=> $status_head, },
1498 my $reference = is_initial_commit
() ? get_empty_tree
() : 'HEAD';
1499 system(qw(git diff -p --cached), $reference, '--',
1500 map { $_->{VALUE
} } @them);
1509 print colored
$help_color, <<\EOF
;
1510 status
- show paths with changes
1511 update
- add working tree
state to the staged set of changes
1512 revert
- revert staged set of changes back to the HEAD version
1513 patch
- pick hunks
and update selectively
1514 diff
- view diff between HEAD
and index
1515 add untracked
- add contents of untracked files to the staged set of changes
1520 return unless @ARGV;
1521 my $arg = shift @ARGV;
1522 if ($arg =~ /--patch(?:=(.*))?/) {
1524 if ($1 eq 'reset') {
1525 $patch_mode = 'reset_head';
1526 $patch_mode_revision = 'HEAD';
1527 $arg = shift @ARGV or die "missing --";
1529 $patch_mode_revision = $arg;
1530 $patch_mode = ($arg eq 'HEAD' ?
1531 'reset_head' : 'reset_nothead');
1532 $arg = shift @ARGV or die "missing --";
1534 } elsif ($1 eq 'checkout') {
1535 $arg = shift @ARGV or die "missing --";
1537 $patch_mode = 'checkout_index';
1539 $patch_mode_revision = $arg;
1540 $patch_mode = ($arg eq 'HEAD' ?
1541 'checkout_head' : 'checkout_nothead');
1542 $arg = shift @ARGV or die "missing --";
1544 } elsif ($1 eq 'stage' or $1 eq 'stash') {
1546 $arg = shift @ARGV or die "missing --";
1548 die "unknown --patch mode: $1";
1551 $patch_mode = 'stage';
1552 $arg = shift @ARGV or die "missing --";
1554 die "invalid argument $arg, expecting --"
1555 unless $arg eq "--";
1556 %patch_mode_flavour = %{$patch_modes{$patch_mode}};
1558 elsif ($arg ne "--") {
1559 die "invalid argument $arg, expecting --";
1564 my @cmd = ([ 'status', \
&status_cmd
, ],
1565 [ 'update', \
&update_cmd
, ],
1566 [ 'revert', \
&revert_cmd
, ],
1567 [ 'add untracked', \
&add_untracked_cmd
, ],
1568 [ 'patch', \
&patch_update_cmd
, ],
1569 [ 'diff', \
&diff_cmd
, ],
1570 [ 'quit', \
&quit_cmd
, ],
1571 [ 'help', \
&help_cmd
, ],
1574 my ($it) = list_and_choose
({ PROMPT
=> 'What now',
1577 HEADER
=> '*** Commands ***',
1578 ON_EOF
=> \
&quit_cmd
,
1579 IMMEDIATE
=> 1 }, @cmd);