8 binmode(STDOUT
, ":raw");
10 my $repo = Git
->repository();
12 my $menu_use_color = $repo->get_colorbool('color.interactive');
13 my ($prompt_color, $header_color, $help_color) =
15 $repo->get_color('color.interactive.prompt', 'bold blue'),
16 $repo->get_color('color.interactive.header', 'bold'),
17 $repo->get_color('color.interactive.help', 'red bold'),
20 if ($menu_use_color) {
21 my $help_color_spec = ($repo->config('color.interactive.help') or
23 $error_color = $repo->get_color('color.interactive.error',
27 my $diff_use_color = $repo->get_colorbool('color.diff');
28 my ($fraginfo_color) =
30 $repo->get_color('color.diff.frag', 'cyan'),
32 my ($diff_plain_color) =
34 $repo->get_color('color.diff.plain', ''),
36 my ($diff_old_color) =
38 $repo->get_color('color.diff.old', 'red'),
40 my ($diff_new_color) =
42 $repo->get_color('color.diff.new', 'green'),
45 my $normal_color = $repo->get_color("", "reset");
47 my $diff_algorithm = $repo->config('diff.algorithm');
48 my $diff_indent_heuristic = $repo->config_bool('diff.indentheuristic');
49 my $diff_compaction_heuristic = $repo->config_bool('diff.compactionheuristic');
50 my $diff_filter = $repo->config('interactive.difffilter');
58 if ($repo->config_bool("interactive.singlekey")) {
60 require Term
::ReadKey
;
61 Term
::ReadKey
->import;
65 print STDERR
"missing Term::ReadKey, disabling interactive.singlekey\n";
69 my $termcap = Term
::Cap
->Tgetent;
70 foreach (values %$termcap) {
71 $term_escapes{$_} = 1 if /^\e/;
79 my $string = join("", @_);
82 # Put a color code at the beginning of each line, a reset at the end
83 # color after newlines that are not at the end of the string
84 $string =~ s/(\n+)(.)/$1$color$2/g;
85 # reset before newlines
86 $string =~ s/(\n+)/$normal_color$1/g;
87 # codes at beginning and end (if necessary):
88 $string =~ s/^/$color/;
89 $string =~ s/$/$normal_color/ unless $string =~ /\n$/;
94 # command line options
96 my $patch_mode_revision;
99 sub apply_patch_for_checkout_commit
;
100 sub apply_patch_for_stash
;
104 DIFF
=> 'diff-files -p',
105 APPLY
=> sub { apply_patch
'apply --cached', @_; },
106 APPLY_CHECK
=> 'apply --cached',
109 PARTICIPLE
=> 'staging',
110 FILTER
=> 'file-only',
114 DIFF
=> 'diff-index -p HEAD',
115 APPLY
=> sub { apply_patch
'apply --cached', @_; },
116 APPLY_CHECK
=> 'apply --cached',
119 PARTICIPLE
=> 'stashing',
124 DIFF
=> 'diff-index -p --cached',
125 APPLY
=> sub { apply_patch
'apply -R --cached', @_; },
126 APPLY_CHECK
=> 'apply -R --cached',
129 PARTICIPLE
=> 'unstaging',
130 FILTER
=> 'index-only',
134 DIFF
=> 'diff-index -R -p --cached',
135 APPLY
=> sub { apply_patch
'apply --cached', @_; },
136 APPLY_CHECK
=> 'apply --cached',
138 TARGET
=> ' to index',
139 PARTICIPLE
=> 'applying',
140 FILTER
=> 'index-only',
143 'checkout_index' => {
144 DIFF
=> 'diff-files -p',
145 APPLY
=> sub { apply_patch
'apply -R', @_; },
146 APPLY_CHECK
=> 'apply -R',
148 TARGET
=> ' from worktree',
149 PARTICIPLE
=> 'discarding',
150 FILTER
=> 'file-only',
154 DIFF
=> 'diff-index -p',
155 APPLY
=> sub { apply_patch_for_checkout_commit
'-R', @_ },
156 APPLY_CHECK
=> 'apply -R',
158 TARGET
=> ' from index and worktree',
159 PARTICIPLE
=> 'discarding',
163 'checkout_nothead' => {
164 DIFF
=> 'diff-index -R -p',
165 APPLY
=> sub { apply_patch_for_checkout_commit
'', @_ },
166 APPLY_CHECK
=> 'apply',
168 TARGET
=> ' to index and worktree',
169 PARTICIPLE
=> 'applying',
175 my %patch_mode_flavour = %{$patch_modes{stage
}};
178 if ($^O
eq 'MSWin32') {
179 my @invalid = grep {m/[":*]/} @_;
180 die "$^O does not support: @invalid\n" if @invalid;
181 my @args = map { m/ /o ?
"\"$_\"": $_ } @_;
185 open($fh, '-|', @_) or die;
190 my ($GIT_DIR) = run_cmd_pipe
(qw(git rev-parse --git-dir));
192 if (!defined $GIT_DIR) {
193 exit(1); # rev-parse would have already said "not a git repo"
210 my ($retval, $remainder);
211 if (!/^\042(.*)\042$/) {
214 ($_, $retval) = ($1, "");
215 while (/^([^\\]*)\\(.*)$/) {
219 if (/^([0-3][0-7][0-7])(.*)$/) {
220 $retval .= chr(oct($1));
224 if (/^([\\\042btnvfr])(.*)$/) {
225 $retval .= $cquote_map{$1};
229 # This is malformed -- just return it as-is for now.
240 open $fh, 'git update-index --refresh |'
243 ;# ignore 'needs update'
253 run_cmd_pipe
(qw(git ls-files --others --exclude-standard --), @ARGV);
256 my $status_fmt = '%12s %12s %s';
257 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
261 sub is_initial_commit
{
262 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
263 unless defined $initial;
269 return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
272 sub get_diff_reference
{
274 if (defined $ref and $ref ne 'HEAD') {
276 } elsif (is_initial_commit
()) {
277 return get_empty_tree
();
283 # Returns list of hashes, contents of each of which are:
285 # BINARY: is a binary path
286 # INDEX: is index different from HEAD?
287 # FILE: is file different from index?
288 # INDEX_ADDDEL: is it add/delete between HEAD and index?
289 # FILE_ADDDEL: is it add/delete between index and file?
290 # UNMERGED: is the path unmerged
295 my ($add, $del, $adddel, $file);
302 } run_cmd_pipe
(qw(git ls-files --), @ARGV);
303 return if (!@tracked);
306 my $reference = get_diff_reference
($patch_mode_revision);
307 for (run_cmd_pipe
(qw(git diff-index --cached
308 --numstat --summary), $reference,
310 if (($add, $del, $file) =
311 /^([-\d]+) ([-\d]+) (.*)/) {
313 $file = unquote_path
($file);
314 if ($add eq '-' && $del eq '-') {
319 $change = "+$add/-$del";
327 elsif (($adddel, $file) =
328 /^ (create|delete) mode [0-7]+ (.*)$/) {
329 $file = unquote_path
($file);
330 $data{$file}{INDEX_ADDDEL
} = $adddel;
334 for (run_cmd_pipe
(qw(git diff-files --numstat --summary --raw --), @tracked)) {
335 if (($add, $del, $file) =
336 /^([-\d]+) ([-\d]+) (.*)/) {
337 $file = unquote_path
($file);
339 if ($add eq '-' && $del eq '-') {
344 $change = "+$add/-$del";
346 $data{$file}{FILE
} = $change;
348 $data{$file}{BINARY
} = 1;
351 elsif (($adddel, $file) =
352 /^ (create|delete) mode [0-7]+ (.*)$/) {
353 $file = unquote_path
($file);
354 $data{$file}{FILE_ADDDEL
} = $adddel;
356 elsif (/^:[0-7]+ [0-7]+ [0-9a-f]+ [0-9a-f]+ (.) (.*)$/) {
357 $file = unquote_path
($2);
358 if (!exists $data{$file}) {
360 INDEX
=> 'unchanged',
365 $data{$file}{UNMERGED
} = 1;
370 for (sort keys %data) {
374 if ($only eq 'index-only') {
375 next if ($it->{INDEX
} eq 'unchanged');
377 if ($only eq 'file-only') {
378 next if ($it->{FILE
} eq 'nothing');
390 my ($string, @stuff) = @_;
392 for (my $i = 0; $i < @stuff; $i++) {
396 if ((ref $it) eq 'ARRAY') {
404 if ($it =~ /^$string/) {
408 if (defined $hit && defined $found) {
418 # inserts string into trie and updates count for each character
420 my ($trie, $string) = @_;
421 foreach (split //, $string) {
422 $trie = $trie->{$_} ||= {COUNT
=> 0};
427 # returns an array of tuples (prefix, remainder)
428 sub find_unique_prefixes
{
432 # any single prefix exceeding the soft limit is omitted
433 # if any prefix exceeds the hard limit all are omitted
434 # 0 indicates no limit
438 # build a trie modelling all possible options
440 foreach my $print (@stuff) {
441 if ((ref $print) eq 'ARRAY') {
442 $print = $print->[0];
444 elsif ((ref $print) eq 'HASH') {
445 $print = $print->{VALUE
};
447 update_trie
(\
%trie, $print);
448 push @return, $print;
451 # use the trie to find the unique prefixes
452 for (my $i = 0; $i < @return; $i++) {
453 my $ret = $return[$i];
454 my @letters = split //, $ret;
456 my ($prefix, $remainder);
458 for ($j = 0; $j < @letters; $j++) {
459 my $letter = $letters[$j];
460 if ($search{$letter}{COUNT
} == 1) {
461 $prefix = substr $ret, 0, $j + 1;
462 $remainder = substr $ret, $j + 1;
466 my $prefix = substr $ret, 0, $j;
468 if ($hard_limit && $j + 1 > $hard_limit);
470 %search = %{$search{$letter}};
472 if (ord($letters[0]) > 127 ||
473 ($soft_limit && $j + 1 > $soft_limit)) {
477 $return[$i] = [$prefix, $remainder];
482 # filters out prefixes which have special meaning to list_and_choose()
483 sub is_valid_prefix
{
485 return (defined $prefix) &&
486 !($prefix =~ /[\s,]/) && # separators
487 !($prefix =~ /^-/) && # deselection
488 !($prefix =~ /^\d+/) && # selection
489 ($prefix ne '*') && # "all" wildcard
490 ($prefix ne '?'); # prompt help
493 # given a prefix/remainder tuple return a string with the prefix highlighted
494 # for now use square brackets; later might use ANSI colors (underline, bold)
495 sub highlight_prefix
{
497 my $remainder = shift;
499 if (!defined $prefix) {
503 if (!is_valid_prefix
($prefix)) {
504 return "$prefix$remainder";
507 if (!$menu_use_color) {
508 return "[$prefix]$remainder";
511 return "$prompt_color$prefix$normal_color$remainder";
515 print STDERR colored
$error_color, @_;
518 sub list_and_choose
{
519 my ($opts, @stuff) = @_;
520 my (@chosen, @return);
525 my @prefixes = find_unique_prefixes
(@stuff) unless $opts->{LIST_ONLY
};
531 if ($opts->{HEADER
}) {
532 if (!$opts->{LIST_FLAT
}) {
535 print colored
$header_color, "$opts->{HEADER}\n";
537 for ($i = 0; $i < @stuff; $i++) {
538 my $chosen = $chosen[$i] ?
'*' : ' ';
539 my $print = $stuff[$i];
540 my $ref = ref $print;
541 my $highlighted = highlight_prefix
(@
{$prefixes[$i]})
543 if ($ref eq 'ARRAY') {
544 $print = $highlighted || $print->[0];
546 elsif ($ref eq 'HASH') {
547 my $value = $highlighted || $print->{VALUE
};
548 $print = sprintf($status_fmt,
554 $print = $highlighted || $print;
556 printf("%s%2d: %s", $chosen, $i+1, $print);
557 if (($opts->{LIST_FLAT
}) &&
558 (($i + 1) % ($opts->{LIST_FLAT
}))) {
571 return if ($opts->{LIST_ONLY
});
573 print colored
$prompt_color, $opts->{PROMPT
};
574 if ($opts->{SINGLETON
}) {
583 $opts->{ON_EOF
}->() if $opts->{ON_EOF
};
590 singleton_prompt_help_cmd
() :
594 for my $choice (split(/[\s,]+/, $line)) {
598 # Input that begins with '-'; unchoose
599 if ($choice =~ s/^-//) {
602 # A range can be specified like 5-7 or 5-.
603 if ($choice =~ /^(\d+)-(\d*)$/) {
604 ($bottom, $top) = ($1, length($2) ?
$2 : 1 + @stuff);
606 elsif ($choice =~ /^\d+$/) {
607 $bottom = $top = $choice;
609 elsif ($choice eq '*') {
614 $bottom = $top = find_unique
($choice, @stuff);
615 if (!defined $bottom) {
616 error_msg
"Huh ($choice)?\n";
620 if ($opts->{SINGLETON
} && $bottom != $top) {
621 error_msg
"Huh ($choice)?\n";
624 for ($i = $bottom-1; $i <= $top-1; $i++) {
625 next if (@stuff <= $i || $i < 0);
626 $chosen[$i] = $choose;
629 last if ($opts->{IMMEDIATE
} || $line eq '*');
631 for ($i = 0; $i < @stuff; $i++) {
633 push @return, $stuff[$i];
639 sub singleton_prompt_help_cmd
{
640 print colored
$help_color, <<\EOF
;
642 1 - select a numbered item
643 foo
- select item based on unique prefix
644 - (empty
) select nothing
648 sub prompt_help_cmd
{
649 print colored
$help_color, <<\EOF
;
651 1 - select a single item
652 3-5 - select a range of items
653 2-3,6-9 - select multiple ranges
654 foo
- select item based on unique prefix
655 -... - unselect specified items
657 - (empty
) finish selecting
662 list_and_choose
({ LIST_ONLY
=> 1, HEADER
=> $status_head },
672 print "$cnt paths\n";
680 my @mods = list_modified
('file-only');
683 my @update = list_and_choose
({ PROMPT
=> 'Update',
684 HEADER
=> $status_head, },
687 system(qw(git update-index --add --remove --),
688 map { $_->{VALUE
} } @update);
689 say_n_paths
('updated', @update);
695 my @update = list_and_choose
({ PROMPT
=> 'Revert',
696 HEADER
=> $status_head, },
699 if (is_initial_commit
()) {
700 system(qw(git rm --cached),
701 map { $_->{VALUE
} } @update);
704 my @lines = run_cmd_pipe
(qw(git ls-tree HEAD --),
705 map { $_->{VALUE
} } @update);
707 open $fh, '| git update-index --index-info'
714 if ($_->{INDEX_ADDDEL
} &&
715 $_->{INDEX_ADDDEL
} eq 'create') {
716 system(qw(git update-index --force-remove --),
718 print "note: $_->{VALUE} is untracked now.\n";
723 say_n_paths
('reverted', @update);
728 sub add_untracked_cmd
{
729 my @add = list_and_choose
({ PROMPT
=> 'Add untracked' },
732 system(qw(git update-index --add --), @add);
733 say_n_paths
('added', @add);
735 print "No untracked files.\n";
743 open $fh, '| git ' . $cmd . " --recount --allow-overlap";
750 my @diff_cmd = split(" ", $patch_mode_flavour{DIFF
});
751 if (defined $diff_algorithm) {
752 splice @diff_cmd, 1, 0, "--diff-algorithm=${diff_algorithm}";
754 if ($diff_indent_heuristic) {
755 splice @diff_cmd, 1, 0, "--indent-heuristic";
756 } elsif ($diff_compaction_heuristic) {
757 splice @diff_cmd, 1, 0, "--compaction-heuristic";
759 if (defined $patch_mode_revision) {
760 push @diff_cmd, get_diff_reference
($patch_mode_revision);
762 my @diff = run_cmd_pipe
("git", @diff_cmd, "--", $path);
764 if ($diff_use_color) {
765 my @display_cmd = ("git", @diff_cmd, qw(--color --), $path);
766 if (defined $diff_filter) {
767 # quotemeta is overkill, but sufficient for shell-quoting
768 my $diff = join(' ', map { quotemeta } @display_cmd);
769 @display_cmd = ("$diff | $diff_filter");
772 @colored = run_cmd_pipe
(@display_cmd);
774 my (@hunk) = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'header' };
776 for (my $i = 0; $i < @diff; $i++) {
777 if ($diff[$i] =~ /^@@ /) {
778 push @hunk, { TEXT
=> [], DISPLAY
=> [],
781 push @
{$hunk[-1]{TEXT
}}, $diff[$i];
782 push @
{$hunk[-1]{DISPLAY
}},
783 (@colored ?
$colored[$i] : $diff[$i]);
788 sub parse_diff_header
{
791 my $head = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'header' };
792 my $mode = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'mode' };
793 my $deletion = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'deletion' };
795 for (my $i = 0; $i < @
{$src->{TEXT
}}; $i++) {
797 $src->{TEXT
}->[$i] =~ /^(old|new) mode (\d+)$/ ?
$mode :
798 $src->{TEXT
}->[$i] =~ /^deleted file/ ?
$deletion :
800 push @
{$dest->{TEXT
}}, $src->{TEXT
}->[$i];
801 push @
{$dest->{DISPLAY
}}, $src->{DISPLAY
}->[$i];
803 return ($head, $mode, $deletion);
806 sub hunk_splittable
{
809 my @s = split_hunk
($text);
813 sub parse_hunk_header
{
815 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
816 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
817 $o_cnt = 1 unless defined $o_cnt;
818 $n_cnt = 1 unless defined $n_cnt;
819 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
823 my ($text, $display) = @_;
825 if (!defined $display) {
828 # If there are context lines in the middle of a hunk,
829 # it can be split, but we would need to take care of
832 my ($o_ofs, undef, $n_ofs) = parse_hunk_header
($text->[0]);
837 my $next_hunk_start = undef;
838 my $i = $hunk_start - 1;
852 while (++$i < @
$text) {
853 my $line = $text->[$i];
854 my $display = $display->[$i];
856 if ($this->{ADDDEL
} &&
857 !defined $next_hunk_start) {
858 # We have seen leading context and
859 # adds/dels and then here is another
860 # context, which is trailing for this
861 # split hunk and leading for the next
863 $next_hunk_start = $i;
865 push @
{$this->{TEXT
}}, $line;
866 push @
{$this->{DISPLAY
}}, $display;
869 if (defined $next_hunk_start) {
876 if (defined $next_hunk_start) {
877 # We are done with the current hunk and
878 # this is the first real change for the
880 $hunk_start = $next_hunk_start;
881 $o_ofs = $this->{OLD
} + $this->{OCNT
};
882 $n_ofs = $this->{NEW
} + $this->{NCNT
};
883 $o_ofs -= $this->{POSTCTX
};
884 $n_ofs -= $this->{POSTCTX
};
888 push @
{$this->{TEXT
}}, $line;
889 push @
{$this->{DISPLAY
}}, $display;
903 for my $hunk (@split) {
904 $o_ofs = $hunk->{OLD
};
905 $n_ofs = $hunk->{NEW
};
906 my $o_cnt = $hunk->{OCNT
};
907 my $n_cnt = $hunk->{NCNT
};
909 my $head = ("@@ -$o_ofs" .
910 (($o_cnt != 1) ?
",$o_cnt" : '') .
912 (($n_cnt != 1) ?
",$n_cnt" : '') .
914 my $display_head = $head;
915 unshift @
{$hunk->{TEXT
}}, $head;
916 if ($diff_use_color) {
917 $display_head = colored
($fraginfo_color, $head);
919 unshift @
{$hunk->{DISPLAY
}}, $display_head;
924 sub find_last_o_ctx
{
926 my $text = $it->{TEXT
};
927 my ($o_ofs, $o_cnt) = parse_hunk_header
($text->[0]);
929 my $last_o_ctx = $o_ofs + $o_cnt;
931 my $line = $text->[$i];
942 my ($prev, $this) = @_;
943 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
944 parse_hunk_header
($prev->{TEXT
}[0]);
945 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
946 parse_hunk_header
($this->{TEXT
}[0]);
948 my (@line, $i, $ofs, $o_cnt, $n_cnt);
951 for ($i = 1; $i < @
{$prev->{TEXT
}}; $i++) {
952 my $line = $prev->{TEXT
}[$i];
953 if ($line =~ /^\+/) {
959 last if ($o1_ofs <= $ofs);
969 for ($i = 1; $i < @
{$this->{TEXT
}}; $i++) {
970 my $line = $this->{TEXT
}[$i];
971 if ($line =~ /^\+/) {
983 my $head = ("@@ -$o0_ofs" .
984 (($o_cnt != 1) ?
",$o_cnt" : '') .
986 (($n_cnt != 1) ?
",$n_cnt" : '') .
988 @
{$prev->{TEXT
}} = ($head, @line);
991 sub coalesce_overlapping_hunks
{
995 my ($last_o_ctx, $last_was_dirty);
997 for (grep { $_->{USE
} } @in) {
998 if ($_->{TYPE
} ne 'hunk') {
1002 my $text = $_->{TEXT
};
1003 my ($o_ofs) = parse_hunk_header
($text->[0]);
1004 if (defined $last_o_ctx &&
1005 $o_ofs <= $last_o_ctx &&
1008 merge_hunk
($out[-1], $_);
1013 $last_o_ctx = find_last_o_ctx
($out[-1]);
1014 $last_was_dirty = $_->{DIRTY
};
1019 sub reassemble_patch
{
1023 # Include everything in the header except the beginning of the diff.
1024 push @patch, (grep { !/^[-+]{3}/ } @
$head);
1026 # Then include any headers from the hunk lines, which must
1027 # come before any actual hunk.
1028 while (@_ && $_[0] !~ /^@/) {
1032 # Then begin the diff.
1033 push @patch, grep { /^[-+]{3}/ } @
$head;
1035 # And then the actual hunks.
1043 colored
((/^@/ ?
$fraginfo_color :
1044 /^\+/ ?
$diff_new_color :
1045 /^-/ ?
$diff_old_color :
1051 sub edit_hunk_manually
{
1054 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
1056 open $fh, '>', $hunkfile
1057 or die "failed to open hunk edit file for writing: " . $!;
1058 print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
1059 print $fh @
$oldtext;
1060 my $participle = $patch_mode_flavour{PARTICIPLE
};
1061 my $is_reverse = $patch_mode_flavour{IS_REVERSE
};
1062 my ($remove_plus, $remove_minus) = $is_reverse ?
('-', '+') : ('+', '-');
1065 # To remove '$remove_minus' lines, make them ' ' lines (context).
1066 # To remove '$remove_plus' lines, delete them.
1067 # Lines starting with # will be removed.
1069 # If the patch applies cleanly, the edited hunk will immediately be
1070 # marked for $participle. If it does not apply cleanly, you will be given
1071 # an opportunity to edit again. If all lines of the hunk are removed,
1072 # then the edit is aborted and the hunk is left unchanged.
1076 chomp(my $editor = run_cmd_pipe
(qw(git var GIT_EDITOR)));
1077 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
1083 open $fh, '<', $hunkfile
1084 or die "failed to open hunk edit file for reading: " . $!;
1085 my @newtext = grep { !/^#/ } <$fh>;
1089 # Abort if nothing remains
1090 if (!grep { /\S/ } @newtext) {
1094 # Reinsert the first hunk header if the user accidentally deleted it
1095 if ($newtext[0] !~ /^@/) {
1096 unshift @newtext, $oldtext->[0];
1102 return run_git_apply
($patch_mode_flavour{APPLY_CHECK
} . ' --check',
1103 map { @
{$_->{TEXT
}} } @_);
1106 sub _restore_terminal_and_die
{
1112 sub prompt_single_character
{
1114 local $SIG{TERM
} = \
&_restore_terminal_and_die
;
1115 local $SIG{INT
} = \
&_restore_terminal_and_die
;
1117 my $key = ReadKey
0;
1119 if ($use_termcap and $key eq "\e") {
1120 while (!defined $term_escapes{$key}) {
1121 my $next = ReadKey
0.5;
1122 last if (!defined $next);
1127 print "$key" if defined $key;
1138 print colored
$prompt_color, $prompt;
1139 my $line = prompt_single_character
;
1140 return 0 if $line =~ /^n/i;
1141 return 1 if $line =~ /^y/i;
1145 sub edit_hunk_loop
{
1146 my ($head, $hunk, $ix) = @_;
1147 my $text = $hunk->[$ix]->{TEXT
};
1150 $text = edit_hunk_manually
($text);
1151 if (!defined $text) {
1156 TYPE
=> $hunk->[$ix]->{TYPE
},
1160 if (diff_applies
($head,
1163 @
{$hunk}[$ix+1..$#{$hunk}])) {
1164 $newhunk->{DISPLAY
} = [color_diff
(@
{$text})];
1169 'Your edited hunk does not apply. Edit again '
1170 . '(saying "no" discards!) [y/n]? '
1176 sub help_patch_cmd
{
1177 my $verb = lc $patch_mode_flavour{VERB
};
1178 my $target = $patch_mode_flavour{TARGET
};
1179 print colored
$help_color, <<EOF ;
1180 y - $verb this hunk$target
1181 n - do not $verb this hunk$target
1182 q - quit; do not $verb this hunk or any of the remaining ones
1183 a - $verb this hunk and all later hunks in the file
1184 d - do not $verb this hunk or any of the later hunks in the file
1185 g - select a hunk to go to
1186 / - search for a hunk matching the given regex
1187 j - leave this hunk undecided, see next undecided hunk
1188 J - leave this hunk undecided, see next hunk
1189 k - leave this hunk undecided, see previous undecided hunk
1190 K - leave this hunk undecided, see previous hunk
1191 s - split the current hunk into smaller hunks
1192 e - manually edit the current hunk
1199 my $ret = run_git_apply
$cmd, @_;
1206 sub apply_patch_for_checkout_commit
{
1207 my $reverse = shift;
1208 my $applies_index = run_git_apply
'apply '.$reverse.' --cached --check', @_;
1209 my $applies_worktree = run_git_apply
'apply '.$reverse.' --check', @_;
1211 if ($applies_worktree && $applies_index) {
1212 run_git_apply
'apply '.$reverse.' --cached', @_;
1213 run_git_apply
'apply '.$reverse, @_;
1215 } elsif (!$applies_index) {
1216 print colored
$error_color, "The selected hunks do not apply to the index!\n";
1217 if (prompt_yesno
"Apply them to the worktree anyway? ") {
1218 return run_git_apply
'apply '.$reverse, @_;
1220 print colored
$error_color, "Nothing was applied.\n";
1229 sub patch_update_cmd
{
1230 my @all_mods = list_modified
($patch_mode_flavour{FILTER
});
1231 error_msg
"ignoring unmerged: $_->{VALUE}\n"
1232 for grep { $_->{UNMERGED
} } @all_mods;
1233 @all_mods = grep { !$_->{UNMERGED
} } @all_mods;
1235 my @mods = grep { !($_->{BINARY
}) } @all_mods;
1240 print STDERR
"Only binary files changed.\n";
1242 print STDERR
"No changes.\n";
1250 @them = list_and_choose
({ PROMPT
=> 'Patch update',
1251 HEADER
=> $status_head, },
1255 return 0 if patch_update_file
($_->{VALUE
});
1259 # Generate a one line summary of a hunk.
1260 sub summarize_hunk
{
1262 my $summary = $rhunk->{TEXT
}[0];
1264 # Keep the line numbers, discard extra context.
1265 $summary =~ s/@@(.*?)@@.*/$1 /s;
1266 $summary .= " " x
(20 - length $summary);
1268 # Add some user context.
1269 for my $line (@
{$rhunk->{TEXT
}}) {
1270 if ($line =~ m/^[+-].*\w/) {
1277 return substr($summary, 0, 80) . "\n";
1281 # Print a one-line summary of each hunk in the array ref in
1282 # the first argument, starting with the index in the 2nd.
1284 my ($hunks, $i) = @_;
1287 for (; $i < @
$hunks && $ctr < 20; $i++, $ctr++) {
1289 if (defined $hunks->[$i]{USE
}) {
1290 $status = $hunks->[$i]{USE
} ?
"+" : "-";
1295 summarize_hunk
($hunks->[$i]);
1300 sub patch_update_file
{
1304 my ($head, @hunk) = parse_diff
($path);
1305 ($head, my $mode, my $deletion) = parse_diff_header
($head);
1306 for (@
{$head->{DISPLAY
}}) {
1310 if (@
{$mode->{TEXT
}}) {
1311 unshift @hunk, $mode;
1313 if (@
{$deletion->{TEXT
}}) {
1314 foreach my $hunk (@hunk) {
1315 push @
{$deletion->{TEXT
}}, @
{$hunk->{TEXT
}};
1316 push @
{$deletion->{DISPLAY
}}, @
{$hunk->{DISPLAY
}};
1318 @hunk = ($deletion);
1321 $num = scalar @hunk;
1325 my ($prev, $next, $other, $undecided, $i);
1331 for ($i = 0; $i < $ix; $i++) {
1332 if (!defined $hunk[$i]{USE
}) {
1341 for ($i = $ix + 1; $i < $num; $i++) {
1342 if (!defined $hunk[$i]{USE
}) {
1348 if ($ix < $num - 1) {
1354 for ($i = 0; $i < $num; $i++) {
1355 if (!defined $hunk[$i]{USE
}) {
1360 last if (!$undecided);
1362 if ($hunk[$ix]{TYPE
} eq 'hunk' &&
1363 hunk_splittable
($hunk[$ix]{TEXT
})) {
1366 if ($hunk[$ix]{TYPE
} eq 'hunk') {
1369 for (@
{$hunk[$ix]{DISPLAY
}}) {
1372 print colored
$prompt_color, $patch_mode_flavour{VERB
},
1373 ($hunk[$ix]{TYPE
} eq 'mode' ?
' mode change' :
1374 $hunk[$ix]{TYPE
} eq 'deletion' ?
' deletion' :
1376 $patch_mode_flavour{TARGET
},
1377 " [y,n,q,a,d,/$other,?]? ";
1378 my $line = prompt_single_character
;
1379 last unless defined $line;
1381 if ($line =~ /^y/i) {
1382 $hunk[$ix]{USE
} = 1;
1384 elsif ($line =~ /^n/i) {
1385 $hunk[$ix]{USE
} = 0;
1387 elsif ($line =~ /^a/i) {
1388 while ($ix < $num) {
1389 if (!defined $hunk[$ix]{USE
}) {
1390 $hunk[$ix]{USE
} = 1;
1396 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1398 my $no = $ix > 10 ?
$ix - 10 : 0;
1399 while ($response eq '') {
1401 $no = display_hunks
(\
@hunk, $no);
1403 $extra = " (<ret> to see more)";
1405 print "go to which hunk$extra? ";
1406 $response = <STDIN
>;
1407 if (!defined $response) {
1412 if ($response !~ /^\s*\d+\s*$/) {
1413 error_msg
"Invalid number: '$response'\n";
1414 } elsif (0 < $response && $response <= $num) {
1415 $ix = $response - 1;
1417 error_msg
"Sorry, only $num hunks available.\n";
1421 elsif ($line =~ /^d/i) {
1422 while ($ix < $num) {
1423 if (!defined $hunk[$ix]{USE
}) {
1424 $hunk[$ix]{USE
} = 0;
1430 elsif ($line =~ /^q/i) {
1431 for ($i = 0; $i < $num; $i++) {
1432 if (!defined $hunk[$i]{USE
}) {
1439 elsif ($line =~ m
|^/(.*)|) {
1442 print colored
$prompt_color, "search for regex? ";
1444 if (defined $regex) {
1450 $search_string = qr{$regex}m;
1453 my ($err,$exp) = ($@
, $1);
1454 $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1455 error_msg
"Malformed search regexp $exp: $err\n";
1460 my $text = join ("", @
{$hunk[$iy]{TEXT
}});
1461 last if ($text =~ $search_string);
1463 $iy = 0 if ($iy >= $num);
1465 error_msg
"No hunk matches the given pattern\n";
1472 elsif ($line =~ /^K/) {
1473 if ($other =~ /K/) {
1477 error_msg
"No previous hunk\n";
1481 elsif ($line =~ /^J/) {
1482 if ($other =~ /J/) {
1486 error_msg
"No next hunk\n";
1490 elsif ($line =~ /^k/) {
1491 if ($other =~ /k/) {
1495 !defined $hunk[$ix]{USE
});
1499 error_msg
"No previous hunk\n";
1503 elsif ($line =~ /^j/) {
1504 if ($other !~ /j/) {
1505 error_msg
"No next hunk\n";
1509 elsif ($other =~ /s/ && $line =~ /^s/) {
1510 my @split = split_hunk
($hunk[$ix]{TEXT
}, $hunk[$ix]{DISPLAY
});
1512 print colored
$header_color, "Split into ",
1513 scalar(@split), " hunks.\n";
1515 splice (@hunk, $ix, 1, @split);
1516 $num = scalar @hunk;
1519 elsif ($other =~ /e/ && $line =~ /^e/) {
1520 my $newhunk = edit_hunk_loop
($head, \
@hunk, $ix);
1521 if (defined $newhunk) {
1522 splice @hunk, $ix, 1, $newhunk;
1526 help_patch_cmd
($other);
1532 last if ($ix >= $num ||
1533 !defined $hunk[$ix]{USE
});
1538 @hunk = coalesce_overlapping_hunks
(@hunk);
1544 push @result, @
{$_->{TEXT
}};
1549 my @patch = reassemble_patch
($head->{TEXT
}, @result);
1550 my $apply_routine = $patch_mode_flavour{APPLY
};
1551 &$apply_routine(@patch);
1560 my @mods = list_modified
('index-only');
1561 @mods = grep { !($_->{BINARY
}) } @mods;
1563 my (@them) = list_and_choose
({ PROMPT
=> 'Review diff',
1565 HEADER
=> $status_head, },
1568 my $reference = is_initial_commit
() ? get_empty_tree
() : 'HEAD';
1569 system(qw(git diff -p --cached), $reference, '--',
1570 map { $_->{VALUE
} } @them);
1579 print colored
$help_color, <<\EOF
;
1580 status
- show paths with changes
1581 update
- add working tree
state to the staged set of changes
1582 revert
- revert staged set of changes back to the HEAD version
1583 patch
- pick hunks
and update selectively
1584 diff
- view diff between HEAD
and index
1585 add untracked
- add contents of untracked files to the staged set of changes
1590 return unless @ARGV;
1591 my $arg = shift @ARGV;
1592 if ($arg =~ /--patch(?:=(.*))?/) {
1594 if ($1 eq 'reset') {
1595 $patch_mode = 'reset_head';
1596 $patch_mode_revision = 'HEAD';
1597 $arg = shift @ARGV or die "missing --";
1599 $patch_mode_revision = $arg;
1600 $patch_mode = ($arg eq 'HEAD' ?
1601 'reset_head' : 'reset_nothead');
1602 $arg = shift @ARGV or die "missing --";
1604 } elsif ($1 eq 'checkout') {
1605 $arg = shift @ARGV or die "missing --";
1607 $patch_mode = 'checkout_index';
1609 $patch_mode_revision = $arg;
1610 $patch_mode = ($arg eq 'HEAD' ?
1611 'checkout_head' : 'checkout_nothead');
1612 $arg = shift @ARGV or die "missing --";
1614 } elsif ($1 eq 'stage' or $1 eq 'stash') {
1616 $arg = shift @ARGV or die "missing --";
1618 die "unknown --patch mode: $1";
1621 $patch_mode = 'stage';
1622 $arg = shift @ARGV or die "missing --";
1624 die "invalid argument $arg, expecting --"
1625 unless $arg eq "--";
1626 %patch_mode_flavour = %{$patch_modes{$patch_mode}};
1628 elsif ($arg ne "--") {
1629 die "invalid argument $arg, expecting --";
1634 my @cmd = ([ 'status', \
&status_cmd
, ],
1635 [ 'update', \
&update_cmd
, ],
1636 [ 'revert', \
&revert_cmd
, ],
1637 [ 'add untracked', \
&add_untracked_cmd
, ],
1638 [ 'patch', \
&patch_update_cmd
, ],
1639 [ 'diff', \
&diff_cmd
, ],
1640 [ 'quit', \
&quit_cmd
, ],
1641 [ 'help', \
&help_cmd
, ],
1644 my ($it) = list_and_choose
({ PROMPT
=> 'What now',
1647 HEADER
=> '*** Commands ***',
1648 ON_EOF
=> \
&quit_cmd
,
1649 IMMEDIATE
=> 1 }, @cmd);