6 binmode(STDOUT
, ":raw");
8 my $repo = Git
->repository();
10 my $menu_use_color = $repo->get_colorbool('color.interactive');
11 my ($prompt_color, $header_color, $help_color) =
13 $repo->get_color('color.interactive.prompt', 'bold blue'),
14 $repo->get_color('color.interactive.header', 'bold'),
15 $repo->get_color('color.interactive.help', 'red bold'),
18 if ($menu_use_color) {
19 my $help_color_spec = ($repo->config('color.interactive.help') or
21 $error_color = $repo->get_color('color.interactive.error',
25 my $diff_use_color = $repo->get_colorbool('color.diff');
26 my ($fraginfo_color) =
28 $repo->get_color('color.diff.frag', 'cyan'),
30 my ($diff_plain_color) =
32 $repo->get_color('color.diff.plain', ''),
34 my ($diff_old_color) =
36 $repo->get_color('color.diff.old', 'red'),
38 my ($diff_new_color) =
40 $repo->get_color('color.diff.new', 'green'),
43 my $normal_color = $repo->get_color("", "reset");
48 if ($repo->config_bool("interactive.singlekey")) {
50 require Term
::ReadKey
;
51 Term
::ReadKey
->import;
58 my $string = join("", @_);
61 # Put a color code at the beginning of each line, a reset at the end
62 # color after newlines that are not at the end of the string
63 $string =~ s/(\n+)(.)/$1$color$2/g;
64 # reset before newlines
65 $string =~ s/(\n+)/$normal_color$1/g;
66 # codes at beginning and end (if necessary):
67 $string =~ s/^/$color/;
68 $string =~ s/$/$normal_color/ unless $string =~ /\n$/;
73 # command line options
75 my $patch_mode_revision;
78 sub apply_patch_for_checkout_commit
;
79 sub apply_patch_for_stash
;
83 DIFF
=> 'diff-files -p',
84 APPLY
=> sub { apply_patch
'apply --cached', @_; },
85 APPLY_CHECK
=> 'apply --cached',
88 PARTICIPLE
=> 'staging',
89 FILTER
=> 'file-only',
92 DIFF
=> 'diff-index -p HEAD',
93 APPLY
=> sub { apply_patch
'apply --cached', @_; },
94 APPLY_CHECK
=> 'apply --cached',
97 PARTICIPLE
=> 'stashing',
101 DIFF
=> 'diff-index -p --cached',
102 APPLY
=> sub { apply_patch
'apply -R --cached', @_; },
103 APPLY_CHECK
=> 'apply -R --cached',
106 PARTICIPLE
=> 'unstaging',
107 FILTER
=> 'index-only',
110 DIFF
=> 'diff-index -R -p --cached',
111 APPLY
=> sub { apply_patch
'apply --cached', @_; },
112 APPLY_CHECK
=> 'apply --cached',
114 TARGET
=> ' to index',
115 PARTICIPLE
=> 'applying',
116 FILTER
=> 'index-only',
118 'checkout_index' => {
119 DIFF
=> 'diff-files -p',
120 APPLY
=> sub { apply_patch
'apply -R', @_; },
121 APPLY_CHECK
=> 'apply -R',
123 TARGET
=> ' from worktree',
124 PARTICIPLE
=> 'discarding',
125 FILTER
=> 'file-only',
128 DIFF
=> 'diff-index -p',
129 APPLY
=> sub { apply_patch_for_checkout_commit
'-R', @_ },
130 APPLY_CHECK
=> 'apply -R',
132 TARGET
=> ' from index and worktree',
133 PARTICIPLE
=> 'discarding',
136 'checkout_nothead' => {
137 DIFF
=> 'diff-index -R -p',
138 APPLY
=> sub { apply_patch_for_checkout_commit
'', @_ },
139 APPLY_CHECK
=> 'apply',
141 TARGET
=> ' to index and worktree',
142 PARTICIPLE
=> 'applying',
147 my %patch_mode_flavour = %{$patch_modes{stage
}};
150 if ($^O
eq 'MSWin32' || $^O
eq 'msys') {
151 my @invalid = grep {m/[":*]/} @_;
152 die "$^O does not support: @invalid\n" if @invalid;
153 my @args = map { m/ /o ?
"\"$_\"": $_ } @_;
157 open($fh, '-|', @_) or die;
162 my ($GIT_DIR) = run_cmd_pipe
(qw(git rev-parse --git-dir));
164 if (!defined $GIT_DIR) {
165 exit(1); # rev-parse would have already said "not a git repo"
182 my ($retval, $remainder);
183 if (!/^\042(.*)\042$/) {
186 ($_, $retval) = ($1, "");
187 while (/^([^\\]*)\\(.*)$/) {
191 if (/^([0-3][0-7][0-7])(.*)$/) {
192 $retval .= chr(oct($1));
196 if (/^([\\\042btnvfr])(.*)$/) {
197 $retval .= $cquote_map{$1};
201 # This is malformed -- just return it as-is for now.
212 open $fh, 'git update-index --refresh |'
215 ;# ignore 'needs update'
225 run_cmd_pipe
(qw(git ls-files --others --exclude-standard --), @ARGV);
228 my $status_fmt = '%12s %12s %s';
229 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
233 sub is_initial_commit
{
234 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
235 unless defined $initial;
241 return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
244 # Returns list of hashes, contents of each of which are:
246 # BINARY: is a binary path
247 # INDEX: is index different from HEAD?
248 # FILE: is file different from index?
249 # INDEX_ADDDEL: is it add/delete between HEAD and index?
250 # FILE_ADDDEL: is it add/delete between index and file?
255 my ($add, $del, $adddel, $file);
262 } run_cmd_pipe
(qw(git ls-files --), @ARGV);
263 return if (!@tracked);
267 if (defined $patch_mode_revision and $patch_mode_revision ne 'HEAD') {
268 $reference = $patch_mode_revision;
269 } elsif (is_initial_commit
()) {
270 $reference = get_empty_tree
();
274 for (run_cmd_pipe
(qw(git diff-index --cached
275 --numstat --summary), $reference,
277 if (($add, $del, $file) =
278 /^([-\d]+) ([-\d]+) (.*)/) {
280 $file = unquote_path
($file);
281 if ($add eq '-' && $del eq '-') {
286 $change = "+$add/-$del";
294 elsif (($adddel, $file) =
295 /^ (create|delete) mode [0-7]+ (.*)$/) {
296 $file = unquote_path
($file);
297 $data{$file}{INDEX_ADDDEL
} = $adddel;
301 for (run_cmd_pipe
(qw(git diff-files --numstat --summary --), @tracked)) {
302 if (($add, $del, $file) =
303 /^([-\d]+) ([-\d]+) (.*)/) {
304 $file = unquote_path
($file);
305 if (!exists $data{$file}) {
307 INDEX
=> 'unchanged',
312 if ($add eq '-' && $del eq '-') {
317 $change = "+$add/-$del";
319 $data{$file}{FILE
} = $change;
321 $data{$file}{BINARY
} = 1;
324 elsif (($adddel, $file) =
325 /^ (create|delete) mode [0-7]+ (.*)$/) {
326 $file = unquote_path
($file);
327 $data{$file}{FILE_ADDDEL
} = $adddel;
331 for (sort keys %data) {
335 if ($only eq 'index-only') {
336 next if ($it->{INDEX
} eq 'unchanged');
338 if ($only eq 'file-only') {
339 next if ($it->{FILE
} eq 'nothing');
351 my ($string, @stuff) = @_;
353 for (my $i = 0; $i < @stuff; $i++) {
357 if ((ref $it) eq 'ARRAY') {
365 if ($it =~ /^$string/) {
369 if (defined $hit && defined $found) {
379 # inserts string into trie and updates count for each character
381 my ($trie, $string) = @_;
382 foreach (split //, $string) {
383 $trie = $trie->{$_} ||= {COUNT
=> 0};
388 # returns an array of tuples (prefix, remainder)
389 sub find_unique_prefixes
{
393 # any single prefix exceeding the soft limit is omitted
394 # if any prefix exceeds the hard limit all are omitted
395 # 0 indicates no limit
399 # build a trie modelling all possible options
401 foreach my $print (@stuff) {
402 if ((ref $print) eq 'ARRAY') {
403 $print = $print->[0];
405 elsif ((ref $print) eq 'HASH') {
406 $print = $print->{VALUE
};
408 update_trie
(\
%trie, $print);
409 push @return, $print;
412 # use the trie to find the unique prefixes
413 for (my $i = 0; $i < @return; $i++) {
414 my $ret = $return[$i];
415 my @letters = split //, $ret;
417 my ($prefix, $remainder);
419 for ($j = 0; $j < @letters; $j++) {
420 my $letter = $letters[$j];
421 if ($search{$letter}{COUNT
} == 1) {
422 $prefix = substr $ret, 0, $j + 1;
423 $remainder = substr $ret, $j + 1;
427 my $prefix = substr $ret, 0, $j;
429 if ($hard_limit && $j + 1 > $hard_limit);
431 %search = %{$search{$letter}};
433 if (ord($letters[0]) > 127 ||
434 ($soft_limit && $j + 1 > $soft_limit)) {
438 $return[$i] = [$prefix, $remainder];
443 # filters out prefixes which have special meaning to list_and_choose()
444 sub is_valid_prefix
{
446 return (defined $prefix) &&
447 !($prefix =~ /[\s,]/) && # separators
448 !($prefix =~ /^-/) && # deselection
449 !($prefix =~ /^\d+/) && # selection
450 ($prefix ne '*') && # "all" wildcard
451 ($prefix ne '?'); # prompt help
454 # given a prefix/remainder tuple return a string with the prefix highlighted
455 # for now use square brackets; later might use ANSI colors (underline, bold)
456 sub highlight_prefix
{
458 my $remainder = shift;
460 if (!defined $prefix) {
464 if (!is_valid_prefix
($prefix)) {
465 return "$prefix$remainder";
468 if (!$menu_use_color) {
469 return "[$prefix]$remainder";
472 return "$prompt_color$prefix$normal_color$remainder";
476 print STDERR colored
$error_color, @_;
479 sub list_and_choose
{
480 my ($opts, @stuff) = @_;
481 my (@chosen, @return);
483 my @prefixes = find_unique_prefixes
(@stuff) unless $opts->{LIST_ONLY
};
489 if ($opts->{HEADER
}) {
490 if (!$opts->{LIST_FLAT
}) {
493 print colored
$header_color, "$opts->{HEADER}\n";
495 for ($i = 0; $i < @stuff; $i++) {
496 my $chosen = $chosen[$i] ?
'*' : ' ';
497 my $print = $stuff[$i];
498 my $ref = ref $print;
499 my $highlighted = highlight_prefix
(@
{$prefixes[$i]})
501 if ($ref eq 'ARRAY') {
502 $print = $highlighted || $print->[0];
504 elsif ($ref eq 'HASH') {
505 my $value = $highlighted || $print->{VALUE
};
506 $print = sprintf($status_fmt,
512 $print = $highlighted || $print;
514 printf("%s%2d: %s", $chosen, $i+1, $print);
515 if (($opts->{LIST_FLAT
}) &&
516 (($i + 1) % ($opts->{LIST_FLAT
}))) {
529 return if ($opts->{LIST_ONLY
});
531 print colored
$prompt_color, $opts->{PROMPT
};
532 if ($opts->{SINGLETON
}) {
541 $opts->{ON_EOF
}->() if $opts->{ON_EOF
};
548 singleton_prompt_help_cmd
() :
552 for my $choice (split(/[\s,]+/, $line)) {
556 # Input that begins with '-'; unchoose
557 if ($choice =~ s/^-//) {
560 # A range can be specified like 5-7 or 5-.
561 if ($choice =~ /^(\d+)-(\d*)$/) {
562 ($bottom, $top) = ($1, length($2) ?
$2 : 1 + @stuff);
564 elsif ($choice =~ /^\d+$/) {
565 $bottom = $top = $choice;
567 elsif ($choice eq '*') {
572 $bottom = $top = find_unique
($choice, @stuff);
573 if (!defined $bottom) {
574 error_msg
"Huh ($choice)?\n";
578 if ($opts->{SINGLETON
} && $bottom != $top) {
579 error_msg
"Huh ($choice)?\n";
582 for ($i = $bottom-1; $i <= $top-1; $i++) {
583 next if (@stuff <= $i || $i < 0);
584 $chosen[$i] = $choose;
587 last if ($opts->{IMMEDIATE
} || $line eq '*');
589 for ($i = 0; $i < @stuff; $i++) {
591 push @return, $stuff[$i];
597 sub singleton_prompt_help_cmd
{
598 print colored
$help_color, <<\EOF
;
600 1 - select a numbered item
601 foo
- select item based on unique prefix
602 - (empty
) select nothing
606 sub prompt_help_cmd
{
607 print colored
$help_color, <<\EOF
;
609 1 - select a single item
610 3-5 - select a range of items
611 2-3,6-9 - select multiple ranges
612 foo
- select item based on unique prefix
613 -... - unselect specified items
615 - (empty
) finish selecting
620 list_and_choose
({ LIST_ONLY
=> 1, HEADER
=> $status_head },
630 print "$cnt paths\n";
638 my @mods = list_modified
('file-only');
641 my @update = list_and_choose
({ PROMPT
=> 'Update',
642 HEADER
=> $status_head, },
645 system(qw(git update-index --add --remove --),
646 map { $_->{VALUE
} } @update);
647 say_n_paths
('updated', @update);
653 my @update = list_and_choose
({ PROMPT
=> 'Revert',
654 HEADER
=> $status_head, },
657 if (is_initial_commit
()) {
658 system(qw(git rm --cached),
659 map { $_->{VALUE
} } @update);
662 my @lines = run_cmd_pipe
(qw(git ls-tree HEAD --),
663 map { $_->{VALUE
} } @update);
665 open $fh, '| git update-index --index-info'
672 if ($_->{INDEX_ADDDEL
} &&
673 $_->{INDEX_ADDDEL
} eq 'create') {
674 system(qw(git update-index --force-remove --),
676 print "note: $_->{VALUE} is untracked now.\n";
681 say_n_paths
('reverted', @update);
686 sub add_untracked_cmd
{
687 my @add = list_and_choose
({ PROMPT
=> 'Add untracked' },
690 system(qw(git update-index --add --), @add);
691 say_n_paths
('added', @add);
699 open $fh, '| git ' . $cmd;
706 my @diff_cmd = split(" ", $patch_mode_flavour{DIFF
});
707 if (defined $patch_mode_revision) {
708 push @diff_cmd, $patch_mode_revision;
710 my @diff = run_cmd_pipe
("git", @diff_cmd, "--", $path);
712 if ($diff_use_color) {
713 @colored = run_cmd_pipe
("git", @diff_cmd, qw(--color --), $path);
715 my (@hunk) = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'header' };
717 for (my $i = 0; $i < @diff; $i++) {
718 if ($diff[$i] =~ /^@@ /) {
719 push @hunk, { TEXT
=> [], DISPLAY
=> [],
722 push @
{$hunk[-1]{TEXT
}}, $diff[$i];
723 push @
{$hunk[-1]{DISPLAY
}},
724 ($diff_use_color ?
$colored[$i] : $diff[$i]);
729 sub parse_diff_header
{
732 my $head = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'header' };
733 my $mode = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'mode' };
734 my $deletion = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'deletion' };
736 for (my $i = 0; $i < @
{$src->{TEXT
}}; $i++) {
738 $src->{TEXT
}->[$i] =~ /^(old|new) mode (\d+)$/ ?
$mode :
739 $src->{TEXT
}->[$i] =~ /^deleted file/ ?
$deletion :
741 push @
{$dest->{TEXT
}}, $src->{TEXT
}->[$i];
742 push @
{$dest->{DISPLAY
}}, $src->{DISPLAY
}->[$i];
744 return ($head, $mode, $deletion);
747 sub hunk_splittable
{
750 my @s = split_hunk
($text);
754 sub parse_hunk_header
{
756 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
757 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
758 $o_cnt = 1 unless defined $o_cnt;
759 $n_cnt = 1 unless defined $n_cnt;
760 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
764 my ($text, $display) = @_;
766 if (!defined $display) {
769 # If there are context lines in the middle of a hunk,
770 # it can be split, but we would need to take care of
773 my ($o_ofs, undef, $n_ofs) = parse_hunk_header
($text->[0]);
778 my $next_hunk_start = undef;
779 my $i = $hunk_start - 1;
793 while (++$i < @
$text) {
794 my $line = $text->[$i];
795 my $display = $display->[$i];
797 if ($this->{ADDDEL
} &&
798 !defined $next_hunk_start) {
799 # We have seen leading context and
800 # adds/dels and then here is another
801 # context, which is trailing for this
802 # split hunk and leading for the next
804 $next_hunk_start = $i;
806 push @
{$this->{TEXT
}}, $line;
807 push @
{$this->{DISPLAY
}}, $display;
810 if (defined $next_hunk_start) {
817 if (defined $next_hunk_start) {
818 # We are done with the current hunk and
819 # this is the first real change for the
821 $hunk_start = $next_hunk_start;
822 $o_ofs = $this->{OLD
} + $this->{OCNT
};
823 $n_ofs = $this->{NEW
} + $this->{NCNT
};
824 $o_ofs -= $this->{POSTCTX
};
825 $n_ofs -= $this->{POSTCTX
};
829 push @
{$this->{TEXT
}}, $line;
830 push @
{$this->{DISPLAY
}}, $display;
844 for my $hunk (@split) {
845 $o_ofs = $hunk->{OLD
};
846 $n_ofs = $hunk->{NEW
};
847 my $o_cnt = $hunk->{OCNT
};
848 my $n_cnt = $hunk->{NCNT
};
850 my $head = ("@@ -$o_ofs" .
851 (($o_cnt != 1) ?
",$o_cnt" : '') .
853 (($n_cnt != 1) ?
",$n_cnt" : '') .
855 my $display_head = $head;
856 unshift @
{$hunk->{TEXT
}}, $head;
857 if ($diff_use_color) {
858 $display_head = colored
($fraginfo_color, $head);
860 unshift @
{$hunk->{DISPLAY
}}, $display_head;
865 sub find_last_o_ctx
{
867 my $text = $it->{TEXT
};
868 my ($o_ofs, $o_cnt) = parse_hunk_header
($text->[0]);
870 my $last_o_ctx = $o_ofs + $o_cnt;
872 my $line = $text->[$i];
883 my ($prev, $this) = @_;
884 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
885 parse_hunk_header
($prev->{TEXT
}[0]);
886 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
887 parse_hunk_header
($this->{TEXT
}[0]);
889 my (@line, $i, $ofs, $o_cnt, $n_cnt);
892 for ($i = 1; $i < @
{$prev->{TEXT
}}; $i++) {
893 my $line = $prev->{TEXT
}[$i];
894 if ($line =~ /^\+/) {
900 last if ($o1_ofs <= $ofs);
910 for ($i = 1; $i < @
{$this->{TEXT
}}; $i++) {
911 my $line = $this->{TEXT
}[$i];
912 if ($line =~ /^\+/) {
924 my $head = ("@@ -$o0_ofs" .
925 (($o_cnt != 1) ?
",$o_cnt" : '') .
927 (($n_cnt != 1) ?
",$n_cnt" : '') .
929 @
{$prev->{TEXT
}} = ($head, @line);
932 sub coalesce_overlapping_hunks
{
936 my ($last_o_ctx, $last_was_dirty);
938 for (grep { $_->{USE
} } @in) {
939 if ($_->{TYPE
} ne 'hunk') {
943 my $text = $_->{TEXT
};
944 my ($o_ofs) = parse_hunk_header
($text->[0]);
945 if (defined $last_o_ctx &&
946 $o_ofs <= $last_o_ctx &&
949 merge_hunk
($out[-1], $_);
954 $last_o_ctx = find_last_o_ctx
($out[-1]);
955 $last_was_dirty = $_->{DIRTY
};
960 sub reassemble_patch
{
964 # Include everything in the header except the beginning of the diff.
965 push @patch, (grep { !/^[-+]{3}/ } @
$head);
967 # Then include any headers from the hunk lines, which must
968 # come before any actual hunk.
969 while (@_ && $_[0] !~ /^@/) {
973 # Then begin the diff.
974 push @patch, grep { /^[-+]{3}/ } @
$head;
976 # And then the actual hunks.
984 colored
((/^@/ ?
$fraginfo_color :
985 /^\+/ ?
$diff_new_color :
986 /^-/ ?
$diff_old_color :
992 sub edit_hunk_manually
{
995 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
997 open $fh, '>', $hunkfile
998 or die "failed to open hunk edit file for writing: " . $!;
999 print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
1000 print $fh @
$oldtext;
1001 my $participle = $patch_mode_flavour{PARTICIPLE
};
1004 # To remove '-' lines, make them ' ' lines (context).
1005 # To remove '+' lines, delete them.
1006 # Lines starting with # will be removed.
1008 # If the patch applies cleanly, the edited hunk will immediately be
1009 # marked for $participle. If it does not apply cleanly, you will be given
1010 # an opportunity to edit again. If all lines of the hunk are removed,
1011 # then the edit is aborted and the hunk is left unchanged.
1015 chomp(my $editor = run_cmd_pipe
(qw(git var GIT_EDITOR)));
1016 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
1022 open $fh, '<', $hunkfile
1023 or die "failed to open hunk edit file for reading: " . $!;
1024 my @newtext = grep { !/^#/ } <$fh>;
1028 # Abort if nothing remains
1029 if (!grep { /\S/ } @newtext) {
1033 # Reinsert the first hunk header if the user accidentally deleted it
1034 if ($newtext[0] !~ /^@/) {
1035 unshift @newtext, $oldtext->[0];
1042 return run_git_apply
($patch_mode_flavour{APPLY_CHECK
} . ' --recount --check',
1043 map { @
{$_->{TEXT
}} } @_);
1046 sub _restore_terminal_and_die
{
1052 sub prompt_single_character
{
1054 local $SIG{TERM
} = \
&_restore_terminal_and_die
;
1055 local $SIG{INT
} = \
&_restore_terminal_and_die
;
1057 my $key = ReadKey
0;
1059 print "$key" if defined $key;
1070 print colored
$prompt_color, $prompt;
1071 my $line = prompt_single_character
;
1072 return 0 if $line =~ /^n/i;
1073 return 1 if $line =~ /^y/i;
1077 sub edit_hunk_loop
{
1078 my ($head, $hunk, $ix) = @_;
1079 my $text = $hunk->[$ix]->{TEXT
};
1082 $text = edit_hunk_manually
($text);
1083 if (!defined $text) {
1088 TYPE
=> $hunk->[$ix]->{TYPE
},
1092 if (diff_applies
($head,
1095 @
{$hunk}[$ix+1..$#{$hunk}])) {
1096 $newhunk->{DISPLAY
} = [color_diff
(@
{$text})];
1101 'Your edited hunk does not apply. Edit again '
1102 . '(saying "no" discards!) [y/n]? '
1108 sub help_patch_cmd
{
1109 my $verb = lc $patch_mode_flavour{VERB
};
1110 my $target = $patch_mode_flavour{TARGET
};
1111 print colored
$help_color, <<EOF ;
1112 y - $verb this hunk$target
1113 n - do not $verb this hunk$target
1114 q - quit, do not $verb this hunk nor any of the remaining ones
1115 a - $verb this and all the remaining hunks in the file
1116 d - do not $verb this hunk nor any of the remaining hunks in the file
1117 g - select a hunk to go to
1118 / - search for a hunk matching the given regex
1119 j - leave this hunk undecided, see next undecided hunk
1120 J - leave this hunk undecided, see next hunk
1121 k - leave this hunk undecided, see previous undecided hunk
1122 K - leave this hunk undecided, see previous hunk
1123 s - split the current hunk into smaller hunks
1124 e - manually edit the current hunk
1131 my $ret = run_git_apply
$cmd . ' --recount', @_;
1138 sub apply_patch_for_checkout_commit
{
1139 my $reverse = shift;
1140 my $applies_index = run_git_apply
'apply '.$reverse.' --cached --recount --check', @_;
1141 my $applies_worktree = run_git_apply
'apply '.$reverse.' --recount --check', @_;
1143 if ($applies_worktree && $applies_index) {
1144 run_git_apply
'apply '.$reverse.' --cached --recount', @_;
1145 run_git_apply
'apply '.$reverse.' --recount', @_;
1147 } elsif (!$applies_index) {
1148 print colored
$error_color, "The selected hunks do not apply to the index!\n";
1149 if (prompt_yesno
"Apply them to the worktree anyway? ") {
1150 return run_git_apply
'apply '.$reverse.' --recount', @_;
1152 print colored
$error_color, "Nothing was applied.\n";
1161 sub patch_update_cmd
{
1162 my @all_mods = list_modified
($patch_mode_flavour{FILTER
});
1163 my @mods = grep { !($_->{BINARY
}) } @all_mods;
1168 print STDERR
"Only binary files changed.\n";
1170 print STDERR
"No changes.\n";
1178 @them = list_and_choose
({ PROMPT
=> 'Patch update',
1179 HEADER
=> $status_head, },
1183 return 0 if patch_update_file
($_->{VALUE
});
1187 # Generate a one line summary of a hunk.
1188 sub summarize_hunk
{
1190 my $summary = $rhunk->{TEXT
}[0];
1192 # Keep the line numbers, discard extra context.
1193 $summary =~ s/@@(.*?)@@.*/$1 /s;
1194 $summary .= " " x
(20 - length $summary);
1196 # Add some user context.
1197 for my $line (@
{$rhunk->{TEXT
}}) {
1198 if ($line =~ m/^[+-].*\w/) {
1205 return substr($summary, 0, 80) . "\n";
1209 # Print a one-line summary of each hunk in the array ref in
1210 # the first argument, starting wih the index in the 2nd.
1212 my ($hunks, $i) = @_;
1215 for (; $i < @
$hunks && $ctr < 20; $i++, $ctr++) {
1217 if (defined $hunks->[$i]{USE
}) {
1218 $status = $hunks->[$i]{USE
} ?
"+" : "-";
1223 summarize_hunk
($hunks->[$i]);
1228 sub patch_update_file
{
1232 my ($head, @hunk) = parse_diff
($path);
1233 ($head, my $mode, my $deletion) = parse_diff_header
($head);
1234 for (@
{$head->{DISPLAY
}}) {
1238 if (@
{$mode->{TEXT
}}) {
1239 unshift @hunk, $mode;
1241 if (@
{$deletion->{TEXT
}}) {
1242 foreach my $hunk (@hunk) {
1243 push @
{$deletion->{TEXT
}}, @
{$hunk->{TEXT
}};
1244 push @
{$deletion->{DISPLAY
}}, @
{$hunk->{DISPLAY
}};
1246 @hunk = ($deletion);
1249 $num = scalar @hunk;
1253 my ($prev, $next, $other, $undecided, $i);
1259 for ($i = 0; $i < $ix; $i++) {
1260 if (!defined $hunk[$i]{USE
}) {
1269 for ($i = $ix + 1; $i < $num; $i++) {
1270 if (!defined $hunk[$i]{USE
}) {
1276 if ($ix < $num - 1) {
1282 for ($i = 0; $i < $num; $i++) {
1283 if (!defined $hunk[$i]{USE
}) {
1288 last if (!$undecided);
1290 if ($hunk[$ix]{TYPE
} eq 'hunk' &&
1291 hunk_splittable
($hunk[$ix]{TEXT
})) {
1294 if ($hunk[$ix]{TYPE
} eq 'hunk') {
1297 for (@
{$hunk[$ix]{DISPLAY
}}) {
1300 print colored
$prompt_color, $patch_mode_flavour{VERB
},
1301 ($hunk[$ix]{TYPE
} eq 'mode' ?
' mode change' :
1302 $hunk[$ix]{TYPE
} eq 'deletion' ?
' deletion' :
1304 $patch_mode_flavour{TARGET
},
1305 " [y,n,q,a,d,/$other,?]? ";
1306 my $line = prompt_single_character
;
1308 if ($line =~ /^y/i) {
1309 $hunk[$ix]{USE
} = 1;
1311 elsif ($line =~ /^n/i) {
1312 $hunk[$ix]{USE
} = 0;
1314 elsif ($line =~ /^a/i) {
1315 while ($ix < $num) {
1316 if (!defined $hunk[$ix]{USE
}) {
1317 $hunk[$ix]{USE
} = 1;
1323 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1325 my $no = $ix > 10 ?
$ix - 10 : 0;
1326 while ($response eq '') {
1328 $no = display_hunks
(\
@hunk, $no);
1330 $extra = " (<ret> to see more)";
1332 print "go to which hunk$extra? ";
1333 $response = <STDIN
>;
1334 if (!defined $response) {
1339 if ($response !~ /^\s*\d+\s*$/) {
1340 error_msg
"Invalid number: '$response'\n";
1341 } elsif (0 < $response && $response <= $num) {
1342 $ix = $response - 1;
1344 error_msg
"Sorry, only $num hunks available.\n";
1348 elsif ($line =~ /^d/i) {
1349 while ($ix < $num) {
1350 if (!defined $hunk[$ix]{USE
}) {
1351 $hunk[$ix]{USE
} = 0;
1357 elsif ($line =~ /^q/i) {
1358 while ($ix < $num) {
1359 if (!defined $hunk[$ix]{USE
}) {
1360 $hunk[$ix]{USE
} = 0;
1367 elsif ($line =~ m
|^/(.*)|) {
1370 print colored
$prompt_color, "search for regex? ";
1372 if (defined $regex) {
1378 $search_string = qr{$regex}m;
1381 my ($err,$exp) = ($@
, $1);
1382 $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1383 error_msg
"Malformed search regexp $exp: $err\n";
1388 my $text = join ("", @
{$hunk[$iy]{TEXT
}});
1389 last if ($text =~ $search_string);
1391 $iy = 0 if ($iy >= $num);
1393 error_msg
"No hunk matches the given pattern\n";
1400 elsif ($line =~ /^K/) {
1401 if ($other =~ /K/) {
1405 error_msg
"No previous hunk\n";
1409 elsif ($line =~ /^J/) {
1410 if ($other =~ /J/) {
1414 error_msg
"No next hunk\n";
1418 elsif ($line =~ /^k/) {
1419 if ($other =~ /k/) {
1423 !defined $hunk[$ix]{USE
});
1427 error_msg
"No previous hunk\n";
1431 elsif ($line =~ /^j/) {
1432 if ($other !~ /j/) {
1433 error_msg
"No next hunk\n";
1437 elsif ($other =~ /s/ && $line =~ /^s/) {
1438 my @split = split_hunk
($hunk[$ix]{TEXT
}, $hunk[$ix]{DISPLAY
});
1440 print colored
$header_color, "Split into ",
1441 scalar(@split), " hunks.\n";
1443 splice (@hunk, $ix, 1, @split);
1444 $num = scalar @hunk;
1447 elsif ($other =~ /e/ && $line =~ /^e/) {
1448 my $newhunk = edit_hunk_loop
($head, \
@hunk, $ix);
1449 if (defined $newhunk) {
1450 splice @hunk, $ix, 1, $newhunk;
1454 help_patch_cmd
($other);
1460 last if ($ix >= $num ||
1461 !defined $hunk[$ix]{USE
});
1466 @hunk = coalesce_overlapping_hunks
(@hunk);
1472 push @result, @
{$_->{TEXT
}};
1478 my @patch = reassemble_patch
($head->{TEXT
}, @result);
1479 my $apply_routine = $patch_mode_flavour{APPLY
};
1480 &$apply_routine(@patch);
1489 my @mods = list_modified
('index-only');
1490 @mods = grep { !($_->{BINARY
}) } @mods;
1492 my (@them) = list_and_choose
({ PROMPT
=> 'Review diff',
1494 HEADER
=> $status_head, },
1497 my $reference = is_initial_commit
() ? get_empty_tree
() : 'HEAD';
1498 system(qw(git diff -p --cached), $reference, '--',
1499 map { $_->{VALUE
} } @them);
1508 print colored
$help_color, <<\EOF
;
1509 status
- show paths with changes
1510 update
- add working tree
state to the staged set of changes
1511 revert
- revert staged set of changes back to the HEAD version
1512 patch
- pick hunks
and update selectively
1513 diff
- view diff between HEAD
and index
1514 add untracked
- add contents of untracked files to the staged set of changes
1519 return unless @ARGV;
1520 my $arg = shift @ARGV;
1521 if ($arg =~ /--patch(?:=(.*))?/) {
1523 if ($1 eq 'reset') {
1524 $patch_mode = 'reset_head';
1525 $patch_mode_revision = 'HEAD';
1526 $arg = shift @ARGV or die "missing --";
1528 $patch_mode_revision = $arg;
1529 $patch_mode = ($arg eq 'HEAD' ?
1530 'reset_head' : 'reset_nothead');
1531 $arg = shift @ARGV or die "missing --";
1533 } elsif ($1 eq 'checkout') {
1534 $arg = shift @ARGV or die "missing --";
1536 $patch_mode = 'checkout_index';
1538 $patch_mode_revision = $arg;
1539 $patch_mode = ($arg eq 'HEAD' ?
1540 'checkout_head' : 'checkout_nothead');
1541 $arg = shift @ARGV or die "missing --";
1543 } elsif ($1 eq 'stage' or $1 eq 'stash') {
1545 $arg = shift @ARGV or die "missing --";
1547 die "unknown --patch mode: $1";
1550 $patch_mode = 'stage';
1551 $arg = shift @ARGV or die "missing --";
1553 die "invalid argument $arg, expecting --"
1554 unless $arg eq "--";
1555 %patch_mode_flavour = %{$patch_modes{$patch_mode}};
1557 elsif ($arg ne "--") {
1558 die "invalid argument $arg, expecting --";
1563 my @cmd = ([ 'status', \
&status_cmd
, ],
1564 [ 'update', \
&update_cmd
, ],
1565 [ 'revert', \
&revert_cmd
, ],
1566 [ 'add untracked', \
&add_untracked_cmd
, ],
1567 [ 'patch', \
&patch_update_cmd
, ],
1568 [ 'diff', \
&diff_cmd
, ],
1569 [ 'quit', \
&quit_cmd
, ],
1570 [ 'help', \
&help_cmd
, ],
1573 my ($it) = list_and_choose
({ PROMPT
=> 'What now',
1576 HEADER
=> '*** Commands ***',
1577 ON_EOF
=> \
&quit_cmd
,
1578 IMMEDIATE
=> 1 }, @cmd);