9 binmode(STDOUT, ":raw");
11 my $repo = Git->repository();
13 my $menu_use_color = $repo->get_colorbool('color.interactive');
14 my ($prompt_color, $header_color, $help_color) =
16 $repo->get_color('color.interactive.prompt', 'bold blue'),
17 $repo->get_color('color.interactive.header', 'bold'),
18 $repo->get_color('color.interactive.help', 'red bold'),
21 if ($menu_use_color) {
22 my $help_color_spec = ($repo->config('color.interactive.help') or
24 $error_color = $repo->get_color('color.interactive.error',
28 my $diff_use_color = $repo->get_colorbool('color.diff');
29 my ($fraginfo_color) =
31 $repo->get_color('color.diff.frag', 'cyan'),
33 my ($diff_plain_color) =
35 $repo->get_color('color.diff.plain', ''),
37 my ($diff_old_color) =
39 $repo->get_color('color.diff.old', 'red'),
41 my ($diff_new_color) =
43 $repo->get_color('color.diff.new', 'green'),
46 my $normal_color = $repo->get_color("", "reset");
48 my $diff_algorithm = $repo->config('diff.algorithm');
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 # TRANSLATORS: you can adjust this to align "git add -i" status menu
257 my $status_fmt = __('%12s %12s %s');
258 my $status_head = sprintf($status_fmt, __('staged'), __('unstaged'), __('path'));
262 sub is_initial_commit {
263 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
264 unless defined $initial;
270 return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
273 sub get_diff_reference {
275 if (defined $ref and $ref ne 'HEAD') {
277 } elsif (is_initial_commit()) {
278 return get_empty_tree();
284 # Returns list of hashes, contents of each of which are:
286 # BINARY: is a binary path
287 # INDEX: is index different from HEAD?
288 # FILE: is file different from index?
289 # INDEX_ADDDEL: is it add/delete between HEAD and index?
290 # FILE_ADDDEL: is it add/delete between index and file?
291 # UNMERGED: is the path unmerged
296 my ($add, $del, $adddel, $file);
303 } run_cmd_pipe(qw(git ls-files --), @ARGV);
304 return if (!@tracked);
307 my $reference = get_diff_reference($patch_mode_revision);
308 for (run_cmd_pipe(qw(git diff-index --cached
309 --numstat --summary), $reference,
311 if (($add, $del, $file) =
312 /^([-\d]+) ([-\d]+) (.*)/) {
314 $file = unquote_path($file);
315 if ($add eq '-' && $del eq '-') {
320 $change = "+$add/-$del";
328 elsif (($adddel, $file) =
329 /^ (create|delete) mode [0-7]+ (.*)$/) {
330 $file = unquote_path($file);
331 $data{$file}{INDEX_ADDDEL} = $adddel;
335 for (run_cmd_pipe(qw(git diff-files --numstat --summary --raw --), @tracked)) {
336 if (($add, $del, $file) =
337 /^([-\d]+) ([-\d]+) (.*)/) {
338 $file = unquote_path($file);
340 if ($add eq '-' && $del eq '-') {
345 $change = "+$add/-$del";
347 $data{$file}{FILE} = $change;
349 $data{$file}{BINARY} = 1;
352 elsif (($adddel, $file) =
353 /^ (create|delete) mode [0-7]+ (.*)$/) {
354 $file = unquote_path($file);
355 $data{$file}{FILE_ADDDEL} = $adddel;
357 elsif (/^:[0-7]+ [0-7]+ [0-9a-f]+ [0-9a-f]+ (.) (.*)$/) {
358 $file = unquote_path($2);
359 if (!exists $data{$file}) {
361 INDEX => 'unchanged',
366 $data{$file}{UNMERGED} = 1;
371 for (sort keys %data) {
375 if ($only eq 'index-only') {
376 next if ($it->{INDEX} eq 'unchanged');
378 if ($only eq 'file-only') {
379 next if ($it->{FILE} eq 'nothing');
391 my ($string, @stuff) = @_;
393 for (my $i = 0; $i < @stuff; $i++) {
397 if ((ref $it) eq 'ARRAY') {
405 if ($it =~ /^$string/) {
409 if (defined $hit && defined $found) {
419 # inserts string into trie and updates count for each character
421 my ($trie, $string) = @_;
422 foreach (split //, $string) {
423 $trie = $trie->{$_} ||= {COUNT => 0};
428 # returns an array of tuples (prefix, remainder)
429 sub find_unique_prefixes {
433 # any single prefix exceeding the soft limit is omitted
434 # if any prefix exceeds the hard limit all are omitted
435 # 0 indicates no limit
439 # build a trie modelling all possible options
441 foreach my $print (@stuff) {
442 if ((ref $print) eq 'ARRAY') {
443 $print = $print->[0];
445 elsif ((ref $print) eq 'HASH') {
446 $print = $print->{VALUE};
448 update_trie(\%trie, $print);
449 push @return, $print;
452 # use the trie to find the unique prefixes
453 for (my $i = 0; $i < @return; $i++) {
454 my $ret = $return[$i];
455 my @letters = split //, $ret;
457 my ($prefix, $remainder);
459 for ($j = 0; $j < @letters; $j++) {
460 my $letter = $letters[$j];
461 if ($search{$letter}{COUNT} == 1) {
462 $prefix = substr $ret, 0, $j + 1;
463 $remainder = substr $ret, $j + 1;
467 my $prefix = substr $ret, 0, $j;
469 if ($hard_limit && $j + 1 > $hard_limit);
471 %search = %{$search{$letter}};
473 if (ord($letters[0]) > 127 ||
474 ($soft_limit && $j + 1 > $soft_limit)) {
478 $return[$i] = [$prefix, $remainder];
483 # filters out prefixes which have special meaning to list_and_choose()
484 sub is_valid_prefix {
486 return (defined $prefix) &&
487 !($prefix =~ /[\s,]/) && # separators
488 !($prefix =~ /^-/) && # deselection
489 !($prefix =~ /^\d+/) && # selection
490 ($prefix ne '*') && # "all" wildcard
491 ($prefix ne '?'); # prompt help
494 # given a prefix/remainder tuple return a string with the prefix highlighted
495 # for now use square brackets; later might use ANSI colors (underline, bold)
496 sub highlight_prefix {
498 my $remainder = shift;
500 if (!defined $prefix) {
504 if (!is_valid_prefix($prefix)) {
505 return "$prefix$remainder";
508 if (!$menu_use_color) {
509 return "[$prefix]$remainder";
512 return "$prompt_color$prefix$normal_color$remainder";
516 print STDERR colored $error_color, @_;
519 sub list_and_choose {
520 my ($opts, @stuff) = @_;
521 my (@chosen, @return);
526 my @prefixes = find_unique_prefixes(@stuff) unless $opts->{LIST_ONLY};
532 if ($opts->{HEADER}) {
533 if (!$opts->{LIST_FLAT}) {
536 print colored $header_color, "$opts->{HEADER}\n";
538 for ($i = 0; $i < @stuff; $i++) {
539 my $chosen = $chosen[$i] ? '*' : ' ';
540 my $print = $stuff[$i];
541 my $ref = ref $print;
542 my $highlighted = highlight_prefix(@{$prefixes[$i]})
544 if ($ref eq 'ARRAY') {
545 $print = $highlighted || $print->[0];
547 elsif ($ref eq 'HASH') {
548 my $value = $highlighted || $print->{VALUE};
549 $print = sprintf($status_fmt,
555 $print = $highlighted || $print;
557 printf("%s%2d: %s", $chosen, $i+1, $print);
558 if (($opts->{LIST_FLAT}) &&
559 (($i + 1) % ($opts->{LIST_FLAT}))) {
572 return if ($opts->{LIST_ONLY});
574 print colored $prompt_color, $opts->{PROMPT};
575 if ($opts->{SINGLETON}) {
584 $opts->{ON_EOF}->() if $opts->{ON_EOF};
591 singleton_prompt_help_cmd() :
595 for my $choice (split(/[\s,]+/, $line)) {
599 # Input that begins with '-'; unchoose
600 if ($choice =~ s/^-//) {
603 # A range can be specified like 5-7 or 5-.
604 if ($choice =~ /^(\d+)-(\d*)$/) {
605 ($bottom, $top) = ($1, length($2) ? $2 : 1 + @stuff);
607 elsif ($choice =~ /^\d+$/) {
608 $bottom = $top = $choice;
610 elsif ($choice eq '*') {
615 $bottom = $top = find_unique($choice, @stuff);
616 if (!defined $bottom) {
617 error_msg sprintf(__("Huh (%s)?\n"), $choice);
621 if ($opts->{SINGLETON} && $bottom != $top) {
622 error_msg sprintf(__("Huh (%s)?\n"), $choice);
625 for ($i = $bottom-1; $i <= $top-1; $i++) {
626 next if (@stuff <= $i || $i < 0);
627 $chosen[$i] = $choose;
630 last if ($opts->{IMMEDIATE} || $line eq '*');
632 for ($i = 0; $i < @stuff; $i++) {
634 push @return, $stuff[$i];
640 sub singleton_prompt_help_cmd {
641 print colored $help_color, __ <<'EOF' ;
643 1 - select a numbered item
644 foo - select item based on unique prefix
645 - (empty) select nothing
649 sub prompt_help_cmd {
650 print colored $help_color, __ <<'EOF' ;
652 1 - select a single item
653 3-5 - select a range of items
654 2-3,6-9 - select multiple ranges
655 foo - select item based on unique prefix
656 -... - unselect specified items
658 - (empty) finish selecting
663 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
671 if ($did eq 'added') {
672 printf(__n("added %d path\n", "added %d paths\n",
674 } elsif ($did eq 'updated') {
675 printf(__n("updated %d path\n", "updated %d paths\n",
677 } elsif ($did eq 'reverted') {
678 printf(__n("reverted %d path\n", "reverted %d paths\n",
681 printf(__n("touched %d path\n", "touched %d paths\n",
687 my @mods = list_modified('file-only');
690 my @update = list_and_choose({ PROMPT => __('Update'),
691 HEADER => $status_head, },
694 system(qw(git update-index --add --remove --),
695 map { $_->{VALUE} } @update);
696 say_n_paths('updated', @update);
702 my @update = list_and_choose({ PROMPT => __('Revert'),
703 HEADER => $status_head, },
706 if (is_initial_commit()) {
707 system(qw(git rm --cached),
708 map { $_->{VALUE} } @update);
711 my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
712 map { $_->{VALUE} } @update);
714 open $fh, '| git update-index --index-info'
721 if ($_->{INDEX_ADDDEL} &&
722 $_->{INDEX_ADDDEL} eq 'create') {
723 system(qw(git update-index --force-remove --),
725 printf(__("note: %s is untracked now.\n"), $_->{VALUE});
730 say_n_paths('reverted', @update);
735 sub add_untracked_cmd {
736 my @add = list_and_choose({ PROMPT => __('Add untracked') },
739 system(qw(git update-index --add --), @add);
740 say_n_paths('added', @add);
742 print __("No untracked files.\n");
750 open $fh, '| git ' . $cmd . " --recount --allow-overlap";
757 my @diff_cmd = split(" ", $patch_mode_flavour{DIFF});
758 if (defined $diff_algorithm) {
759 splice @diff_cmd, 1, 0, "--diff-algorithm=${diff_algorithm}";
761 if ($diff_compaction_heuristic) {
762 splice @diff_cmd, 1, 0, "--compaction-heuristic";
764 if (defined $patch_mode_revision) {
765 push @diff_cmd, get_diff_reference($patch_mode_revision);
767 my @diff = run_cmd_pipe("git", @diff_cmd, "--", $path);
769 if ($diff_use_color) {
770 my @display_cmd = ("git", @diff_cmd, qw(--color --), $path);
771 if (defined $diff_filter) {
772 # quotemeta is overkill, but sufficient for shell-quoting
773 my $diff = join(' ', map { quotemeta } @display_cmd);
774 @display_cmd = ("$diff | $diff_filter");
777 @colored = run_cmd_pipe(@display_cmd);
779 my (@hunk) = { TEXT => [], DISPLAY => [], TYPE => 'header' };
781 for (my $i = 0; $i < @diff; $i++) {
782 if ($diff[$i] =~ /^@@ /) {
783 push @hunk, { TEXT => [], DISPLAY => [],
786 push @{$hunk[-1]{TEXT}}, $diff[$i];
787 push @{$hunk[-1]{DISPLAY}},
788 (@colored ? $colored[$i] : $diff[$i]);
793 sub parse_diff_header {
796 my $head = { TEXT => [], DISPLAY => [], TYPE => 'header' };
797 my $mode = { TEXT => [], DISPLAY => [], TYPE => 'mode' };
798 my $deletion = { TEXT => [], DISPLAY => [], TYPE => 'deletion' };
800 for (my $i = 0; $i < @{$src->{TEXT}}; $i++) {
802 $src->{TEXT}->[$i] =~ /^(old|new) mode (\d+)$/ ? $mode :
803 $src->{TEXT}->[$i] =~ /^deleted file/ ? $deletion :
805 push @{$dest->{TEXT}}, $src->{TEXT}->[$i];
806 push @{$dest->{DISPLAY}}, $src->{DISPLAY}->[$i];
808 return ($head, $mode, $deletion);
811 sub hunk_splittable {
814 my @s = split_hunk($text);
818 sub parse_hunk_header {
820 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
821 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
822 $o_cnt = 1 unless defined $o_cnt;
823 $n_cnt = 1 unless defined $n_cnt;
824 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
828 my ($text, $display) = @_;
830 if (!defined $display) {
833 # If there are context lines in the middle of a hunk,
834 # it can be split, but we would need to take care of
837 my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
842 my $next_hunk_start = undef;
843 my $i = $hunk_start - 1;
857 while (++$i < @$text) {
858 my $line = $text->[$i];
859 my $display = $display->[$i];
861 if ($this->{ADDDEL} &&
862 !defined $next_hunk_start) {
863 # We have seen leading context and
864 # adds/dels and then here is another
865 # context, which is trailing for this
866 # split hunk and leading for the next
868 $next_hunk_start = $i;
870 push @{$this->{TEXT}}, $line;
871 push @{$this->{DISPLAY}}, $display;
874 if (defined $next_hunk_start) {
881 if (defined $next_hunk_start) {
882 # We are done with the current hunk and
883 # this is the first real change for the
885 $hunk_start = $next_hunk_start;
886 $o_ofs = $this->{OLD} + $this->{OCNT};
887 $n_ofs = $this->{NEW} + $this->{NCNT};
888 $o_ofs -= $this->{POSTCTX};
889 $n_ofs -= $this->{POSTCTX};
893 push @{$this->{TEXT}}, $line;
894 push @{$this->{DISPLAY}}, $display;
908 for my $hunk (@split) {
909 $o_ofs = $hunk->{OLD};
910 $n_ofs = $hunk->{NEW};
911 my $o_cnt = $hunk->{OCNT};
912 my $n_cnt = $hunk->{NCNT};
914 my $head = ("@@ -$o_ofs" .
915 (($o_cnt != 1) ? ",$o_cnt" : '') .
917 (($n_cnt != 1) ? ",$n_cnt" : '') .
919 my $display_head = $head;
920 unshift @{$hunk->{TEXT}}, $head;
921 if ($diff_use_color) {
922 $display_head = colored($fraginfo_color, $head);
924 unshift @{$hunk->{DISPLAY}}, $display_head;
929 sub find_last_o_ctx {
931 my $text = $it->{TEXT};
932 my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
934 my $last_o_ctx = $o_ofs + $o_cnt;
936 my $line = $text->[$i];
947 my ($prev, $this) = @_;
948 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
949 parse_hunk_header($prev->{TEXT}[0]);
950 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
951 parse_hunk_header($this->{TEXT}[0]);
953 my (@line, $i, $ofs, $o_cnt, $n_cnt);
956 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
957 my $line = $prev->{TEXT}[$i];
958 if ($line =~ /^\+/) {
964 last if ($o1_ofs <= $ofs);
974 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
975 my $line = $this->{TEXT}[$i];
976 if ($line =~ /^\+/) {
988 my $head = ("@@ -$o0_ofs" .
989 (($o_cnt != 1) ? ",$o_cnt" : '') .
991 (($n_cnt != 1) ? ",$n_cnt" : '') .
993 @{$prev->{TEXT}} = ($head, @line);
996 sub coalesce_overlapping_hunks {
1000 my ($last_o_ctx, $last_was_dirty);
1002 for (grep { $_->{USE} } @in) {
1003 if ($_->{TYPE} ne 'hunk') {
1007 my $text = $_->{TEXT};
1008 my ($o_ofs) = parse_hunk_header($text->[0]);
1009 if (defined $last_o_ctx &&
1010 $o_ofs <= $last_o_ctx &&
1013 merge_hunk($out[-1], $_);
1018 $last_o_ctx = find_last_o_ctx($out[-1]);
1019 $last_was_dirty = $_->{DIRTY};
1024 sub reassemble_patch {
1028 # Include everything in the header except the beginning of the diff.
1029 push @patch, (grep { !/^[-+]{3}/ } @$head);
1031 # Then include any headers from the hunk lines, which must
1032 # come before any actual hunk.
1033 while (@_ && $_[0] !~ /^@/) {
1037 # Then begin the diff.
1038 push @patch, grep { /^[-+]{3}/ } @$head;
1040 # And then the actual hunks.
1048 colored((/^@/ ? $fraginfo_color :
1049 /^\+/ ? $diff_new_color :
1050 /^-/ ? $diff_old_color :
1056 sub edit_hunk_manually {
1059 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
1061 open $fh, '>', $hunkfile
1062 or die sprintf(__("failed to open hunk edit file for writing: %s"), $!);
1063 print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
1064 print $fh @$oldtext;
1065 my $participle = $patch_mode_flavour{PARTICIPLE};
1066 my $is_reverse = $patch_mode_flavour{IS_REVERSE};
1067 my ($remove_plus, $remove_minus) = $is_reverse ? ('-', '+') : ('+', '-');
1070 # To remove '$remove_minus' lines, make them ' ' lines (context).
1071 # To remove '$remove_plus' lines, delete them.
1072 # Lines starting with # will be removed.
1074 # If the patch applies cleanly, the edited hunk will immediately be
1075 # marked for $participle. If it does not apply cleanly, you will be given
1076 # an opportunity to edit again. If all lines of the hunk are removed,
1077 # then the edit is aborted and the hunk is left unchanged.
1081 chomp(my $editor = run_cmd_pipe(qw(git var GIT_EDITOR)));
1082 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
1088 open $fh, '<', $hunkfile
1089 or die sprintf(__("failed to open hunk edit file for reading: %s"), $!);
1090 my @newtext = grep { !/^#/ } <$fh>;
1094 # Abort if nothing remains
1095 if (!grep { /\S/ } @newtext) {
1099 # Reinsert the first hunk header if the user accidentally deleted it
1100 if ($newtext[0] !~ /^@/) {
1101 unshift @newtext, $oldtext->[0];
1107 return run_git_apply($patch_mode_flavour{APPLY_CHECK} . ' --check',
1108 map { @{$_->{TEXT}} } @_);
1111 sub _restore_terminal_and_die {
1117 sub prompt_single_character {
1119 local $SIG{TERM} = \&_restore_terminal_and_die;
1120 local $SIG{INT} = \&_restore_terminal_and_die;
1122 my $key = ReadKey 0;
1124 if ($use_termcap and $key eq "\e") {
1125 while (!defined $term_escapes{$key}) {
1126 my $next = ReadKey 0.5;
1127 last if (!defined $next);
1132 print "$key" if defined $key;
1143 print colored $prompt_color, $prompt;
1144 my $line = prompt_single_character;
1145 return 0 if $line =~ /^n/i;
1146 return 1 if $line =~ /^y/i;
1150 sub edit_hunk_loop {
1151 my ($head, $hunk, $ix) = @_;
1152 my $text = $hunk->[$ix]->{TEXT};
1155 $text = edit_hunk_manually($text);
1156 if (!defined $text) {
1161 TYPE => $hunk->[$ix]->{TYPE},
1165 if (diff_applies($head,
1168 @{$hunk}[$ix+1..$#{$hunk}])) {
1169 $newhunk->{DISPLAY} = [color_diff(@{$text})];
1174 # TRANSLATORS: do not translate [y/n]
1175 # The program will only accept that input
1177 # Consider translating (saying "no" discards!) as
1178 # (saying "n" for "no" discards!) if the translation
1179 # of the word "no" does not start with n.
1180 __('Your edited hunk does not apply. Edit again '
1181 . '(saying "no" discards!) [y/n]? ')
1187 sub help_patch_cmd {
1188 my $verb = lc $patch_mode_flavour{VERB};
1189 my $target = $patch_mode_flavour{TARGET};
1190 print colored $help_color, <<EOF ;
1191 y - $verb this hunk$target
1192 n - do not $verb this hunk$target
1193 q - quit; do not $verb this hunk or any of the remaining ones
1194 a - $verb this hunk and all later hunks in the file
1195 d - do not $verb this hunk or any of the later hunks in the file
1196 g - select a hunk to go to
1197 / - search for a hunk matching the given regex
1198 j - leave this hunk undecided, see next undecided hunk
1199 J - leave this hunk undecided, see next hunk
1200 k - leave this hunk undecided, see previous undecided hunk
1201 K - leave this hunk undecided, see previous hunk
1202 s - split the current hunk into smaller hunks
1203 e - manually edit the current hunk
1210 my $ret = run_git_apply $cmd, @_;
1217 sub apply_patch_for_checkout_commit {
1218 my $reverse = shift;
1219 my $applies_index = run_git_apply 'apply '.$reverse.' --cached --check', @_;
1220 my $applies_worktree = run_git_apply 'apply '.$reverse.' --check', @_;
1222 if ($applies_worktree && $applies_index) {
1223 run_git_apply 'apply '.$reverse.' --cached', @_;
1224 run_git_apply 'apply '.$reverse, @_;
1226 } elsif (!$applies_index) {
1227 print colored $error_color, __("The selected hunks do not apply to the index!\n");
1228 if (prompt_yesno __("Apply them to the worktree anyway? ")) {
1229 return run_git_apply 'apply '.$reverse, @_;
1231 print colored $error_color, __("Nothing was applied.\n");
1240 sub patch_update_cmd {
1241 my @all_mods = list_modified($patch_mode_flavour{FILTER});
1242 error_msg sprintf(__("ignoring unmerged: %s\n"), $_->{VALUE})
1243 for grep { $_->{UNMERGED} } @all_mods;
1244 @all_mods = grep { !$_->{UNMERGED} } @all_mods;
1246 my @mods = grep { !($_->{BINARY}) } @all_mods;
1251 print STDERR __("Only binary files changed.\n");
1253 print STDERR __("No changes.\n");
1261 @them = list_and_choose({ PROMPT => __('Patch update'),
1262 HEADER => $status_head, },
1266 return 0 if patch_update_file($_->{VALUE});
1270 # Generate a one line summary of a hunk.
1271 sub summarize_hunk {
1273 my $summary = $rhunk->{TEXT}[0];
1275 # Keep the line numbers, discard extra context.
1276 $summary =~ s/@@(.*?)@@.*/$1 /s;
1277 $summary .= " " x (20 - length $summary);
1279 # Add some user context.
1280 for my $line (@{$rhunk->{TEXT}}) {
1281 if ($line =~ m/^[+-].*\w/) {
1288 return substr($summary, 0, 80) . "\n";
1292 # Print a one-line summary of each hunk in the array ref in
1293 # the first argument, starting with the index in the 2nd.
1295 my ($hunks, $i) = @_;
1298 for (; $i < @$hunks && $ctr < 20; $i++, $ctr++) {
1300 if (defined $hunks->[$i]{USE}) {
1301 $status = $hunks->[$i]{USE} ? "+" : "-";
1306 summarize_hunk($hunks->[$i]);
1311 sub patch_update_file {
1315 my ($head, @hunk) = parse_diff($path);
1316 ($head, my $mode, my $deletion) = parse_diff_header($head);
1317 for (@{$head->{DISPLAY}}) {
1321 if (@{$mode->{TEXT}}) {
1322 unshift @hunk, $mode;
1324 if (@{$deletion->{TEXT}}) {
1325 foreach my $hunk (@hunk) {
1326 push @{$deletion->{TEXT}}, @{$hunk->{TEXT}};
1327 push @{$deletion->{DISPLAY}}, @{$hunk->{DISPLAY}};
1329 @hunk = ($deletion);
1332 $num = scalar @hunk;
1336 my ($prev, $next, $other, $undecided, $i);
1342 for ($i = 0; $i < $ix; $i++) {
1343 if (!defined $hunk[$i]{USE}) {
1352 for ($i = $ix + 1; $i < $num; $i++) {
1353 if (!defined $hunk[$i]{USE}) {
1359 if ($ix < $num - 1) {
1365 for ($i = 0; $i < $num; $i++) {
1366 if (!defined $hunk[$i]{USE}) {
1371 last if (!$undecided);
1373 if ($hunk[$ix]{TYPE} eq 'hunk' &&
1374 hunk_splittable($hunk[$ix]{TEXT})) {
1377 if ($hunk[$ix]{TYPE} eq 'hunk') {
1380 for (@{$hunk[$ix]{DISPLAY}}) {
1383 print colored $prompt_color, $patch_mode_flavour{VERB},
1384 ($hunk[$ix]{TYPE} eq 'mode' ? ' mode change' :
1385 $hunk[$ix]{TYPE} eq 'deletion' ? ' deletion' :
1387 $patch_mode_flavour{TARGET},
1388 " [y,n,q,a,d,/$other,?]? ";
1389 my $line = prompt_single_character;
1390 last unless defined $line;
1392 if ($line =~ /^y/i) {
1393 $hunk[$ix]{USE} = 1;
1395 elsif ($line =~ /^n/i) {
1396 $hunk[$ix]{USE} = 0;
1398 elsif ($line =~ /^a/i) {
1399 while ($ix < $num) {
1400 if (!defined $hunk[$ix]{USE}) {
1401 $hunk[$ix]{USE} = 1;
1407 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1409 my $no = $ix > 10 ? $ix - 10 : 0;
1410 while ($response eq '') {
1411 $no = display_hunks(\@hunk, $no);
1413 print __("go to which hunk (<ret> to see more)? ");
1415 print __("go to which hunk? ");
1417 $response = <STDIN>;
1418 if (!defined $response) {
1423 if ($response !~ /^\s*\d+\s*$/) {
1424 error_msg sprintf(__("Invalid number: '%s'\n"),
1426 } elsif (0 < $response && $response <= $num) {
1427 $ix = $response - 1;
1429 error_msg sprintf(__n("Sorry, only %d hunk available.\n",
1430 "Sorry, only %d hunks available.\n", $num), $num);
1434 elsif ($line =~ /^d/i) {
1435 while ($ix < $num) {
1436 if (!defined $hunk[$ix]{USE}) {
1437 $hunk[$ix]{USE} = 0;
1443 elsif ($line =~ /^q/i) {
1444 for ($i = 0; $i < $num; $i++) {
1445 if (!defined $hunk[$i]{USE}) {
1452 elsif ($line =~ m|^/(.*)|) {
1455 print colored $prompt_color, __("search for regex? ");
1457 if (defined $regex) {
1463 $search_string = qr{$regex}m;
1466 my ($err,$exp) = ($@, $1);
1467 $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1468 error_msg sprintf(__("Malformed search regexp %s: %s\n"), $exp, $err);
1473 my $text = join ("", @{$hunk[$iy]{TEXT}});
1474 last if ($text =~ $search_string);
1476 $iy = 0 if ($iy >= $num);
1478 error_msg __("No hunk matches the given pattern\n");
1485 elsif ($line =~ /^K/) {
1486 if ($other =~ /K/) {
1490 error_msg __("No previous hunk\n");
1494 elsif ($line =~ /^J/) {
1495 if ($other =~ /J/) {
1499 error_msg __("No next hunk\n");
1503 elsif ($line =~ /^k/) {
1504 if ($other =~ /k/) {
1508 !defined $hunk[$ix]{USE});
1512 error_msg __("No previous hunk\n");
1516 elsif ($line =~ /^j/) {
1517 if ($other !~ /j/) {
1518 error_msg __("No next hunk\n");
1522 elsif ($other =~ /s/ && $line =~ /^s/) {
1523 my @split = split_hunk($hunk[$ix]{TEXT}, $hunk[$ix]{DISPLAY});
1525 print colored $header_color, sprintf(
1526 __n("Split into %d hunk.\n",
1527 "Split into %d hunks.\n",
1528 scalar(@split)), scalar(@split));
1530 splice (@hunk, $ix, 1, @split);
1531 $num = scalar @hunk;
1534 elsif ($other =~ /e/ && $line =~ /^e/) {
1535 my $newhunk = edit_hunk_loop($head, \@hunk, $ix);
1536 if (defined $newhunk) {
1537 splice @hunk, $ix, 1, $newhunk;
1541 help_patch_cmd($other);
1547 last if ($ix >= $num ||
1548 !defined $hunk[$ix]{USE});
1553 @hunk = coalesce_overlapping_hunks(@hunk);
1559 push @result, @{$_->{TEXT}};
1564 my @patch = reassemble_patch($head->{TEXT}, @result);
1565 my $apply_routine = $patch_mode_flavour{APPLY};
1566 &$apply_routine(@patch);
1575 my @mods = list_modified('index-only');
1576 @mods = grep { !($_->{BINARY}) } @mods;
1578 my (@them) = list_and_choose({ PROMPT => __('Review diff'),
1580 HEADER => $status_head, },
1583 my $reference = (is_initial_commit()) ? get_empty_tree() : 'HEAD';
1584 system(qw(git diff -p --cached), $reference, '--',
1585 map { $_->{VALUE} } @them);
1594 # TRANSLATORS: please do not translate the command names
1595 # 'status', 'update', 'revert', etc.
1596 print colored $help_color, __ <<'EOF' ;
1597 status - show paths with changes
1598 update - add working tree state to the staged set of changes
1599 revert - revert staged set of changes back to the HEAD version
1600 patch - pick hunks and update selectively
1601 diff - view diff between HEAD and index
1602 add untracked - add contents of untracked files to the staged set of changes
1607 return unless @ARGV;
1608 my $arg = shift @ARGV;
1609 if ($arg =~ /--patch(?:=(.*))?/) {
1611 if ($1 eq 'reset') {
1612 $patch_mode = 'reset_head';
1613 $patch_mode_revision = 'HEAD';
1614 $arg = shift @ARGV or die __("missing --");
1616 $patch_mode_revision = $arg;
1617 $patch_mode = ($arg eq 'HEAD' ?
1618 'reset_head' : 'reset_nothead');
1619 $arg = shift @ARGV or die __("missing --");
1621 } elsif ($1 eq 'checkout') {
1622 $arg = shift @ARGV or die __("missing --");
1624 $patch_mode = 'checkout_index';
1626 $patch_mode_revision = $arg;
1627 $patch_mode = ($arg eq 'HEAD' ?
1628 'checkout_head' : 'checkout_nothead');
1629 $arg = shift @ARGV or die __("missing --");
1631 } elsif ($1 eq 'stage' or $1 eq 'stash') {
1633 $arg = shift @ARGV or die __("missing --");
1635 die sprintf(__("unknown --patch mode: %s"), $1);
1638 $patch_mode = 'stage';
1639 $arg = shift @ARGV or die __("missing --");
1641 die sprintf(__("invalid argument %s, expecting --"),
1642 $arg) unless $arg eq "--";
1643 %patch_mode_flavour = %{$patch_modes{$patch_mode}};
1645 elsif ($arg ne "--") {
1646 die sprintf(__("invalid argument %s, expecting --"), $arg);
1651 my @cmd = ([ 'status', \&status_cmd, ],
1652 [ 'update', \&update_cmd, ],
1653 [ 'revert', \&revert_cmd, ],
1654 [ 'add untracked', \&add_untracked_cmd, ],
1655 [ 'patch', \&patch_update_cmd, ],
1656 [ 'diff', \&diff_cmd, ],
1657 [ 'quit', \&quit_cmd, ],
1658 [ 'help', \&help_cmd, ],
1661 my ($it) = list_and_choose({ PROMPT => __('What now'),
1664 HEADER => __('*** Commands ***'),
1665 ON_EOF => \&quit_cmd,
1666 IMMEDIATE => 1 }, @cmd);