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');
55 if ($repo->config_bool("interactive.singlekey")) {
57 require Term::ReadKey;
58 Term::ReadKey->import;
63 my $termcap = Term::Cap->Tgetent;
64 foreach (values %$termcap) {
65 $term_escapes{$_} = 1 if /^\e/;
73 my $string = join("", @_);
76 # Put a color code at the beginning of each line, a reset at the end
77 # color after newlines that are not at the end of the string
78 $string =~ s/(\n+)(.)/$1$color$2/g;
79 # reset before newlines
80 $string =~ s/(\n+)/$normal_color$1/g;
81 # codes at beginning and end (if necessary):
82 $string =~ s/^/$color/;
83 $string =~ s/$/$normal_color/ unless $string =~ /\n$/;
88 # command line options
90 my $patch_mode_revision;
93 sub apply_patch_for_checkout_commit;
94 sub apply_patch_for_stash;
98 DIFF => 'diff-files -p',
99 APPLY => sub { apply_patch 'apply --cached', @_; },
100 APPLY_CHECK => 'apply --cached',
103 PARTICIPLE => 'staging',
104 FILTER => 'file-only',
108 DIFF => 'diff-index -p HEAD',
109 APPLY => sub { apply_patch 'apply --cached', @_; },
110 APPLY_CHECK => 'apply --cached',
113 PARTICIPLE => 'stashing',
118 DIFF => 'diff-index -p --cached',
119 APPLY => sub { apply_patch 'apply -R --cached', @_; },
120 APPLY_CHECK => 'apply -R --cached',
123 PARTICIPLE => 'unstaging',
124 FILTER => 'index-only',
128 DIFF => 'diff-index -R -p --cached',
129 APPLY => sub { apply_patch 'apply --cached', @_; },
130 APPLY_CHECK => 'apply --cached',
132 TARGET => ' to index',
133 PARTICIPLE => 'applying',
134 FILTER => 'index-only',
137 'checkout_index' => {
138 DIFF => 'diff-files -p',
139 APPLY => sub { apply_patch 'apply -R', @_; },
140 APPLY_CHECK => 'apply -R',
142 TARGET => ' from worktree',
143 PARTICIPLE => 'discarding',
144 FILTER => 'file-only',
148 DIFF => 'diff-index -p',
149 APPLY => sub { apply_patch_for_checkout_commit '-R', @_ },
150 APPLY_CHECK => 'apply -R',
152 TARGET => ' from index and worktree',
153 PARTICIPLE => 'discarding',
157 'checkout_nothead' => {
158 DIFF => 'diff-index -R -p',
159 APPLY => sub { apply_patch_for_checkout_commit '', @_ },
160 APPLY_CHECK => 'apply',
162 TARGET => ' to index and worktree',
163 PARTICIPLE => 'applying',
169 my %patch_mode_flavour = %{$patch_modes{stage}};
172 if ($^O eq 'MSWin32') {
173 my @invalid = grep {m/[":*]/} @_;
174 die "$^O does not support: @invalid\n" if @invalid;
175 my @args = map { m/ /o ? "\"$_\"": $_ } @_;
179 open($fh, '-|', @_) or die;
184 my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));
186 if (!defined $GIT_DIR) {
187 exit(1); # rev-parse would have already said "not a git repo"
204 my ($retval, $remainder);
205 if (!/^\042(.*)\042$/) {
208 ($_, $retval) = ($1, "");
209 while (/^([^\\]*)\\(.*)$/) {
213 if (/^([0-3][0-7][0-7])(.*)$/) {
214 $retval .= chr(oct($1));
218 if (/^([\\\042btnvfr])(.*)$/) {
219 $retval .= $cquote_map{$1};
223 # This is malformed -- just return it as-is for now.
234 open $fh, 'git update-index --refresh |'
237 ;# ignore 'needs update'
247 run_cmd_pipe(qw(git ls-files --others --exclude-standard --), @ARGV);
250 my $status_fmt = '%12s %12s %s';
251 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
255 sub is_initial_commit {
256 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
257 unless defined $initial;
263 return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
266 sub get_diff_reference {
268 if (defined $ref and $ref ne 'HEAD') {
270 } elsif (is_initial_commit()) {
271 return get_empty_tree();
277 # Returns list of hashes, contents of each of which are:
279 # BINARY: is a binary path
280 # INDEX: is index different from HEAD?
281 # FILE: is file different from index?
282 # INDEX_ADDDEL: is it add/delete between HEAD and index?
283 # FILE_ADDDEL: is it add/delete between index and file?
284 # UNMERGED: is the path unmerged
289 my ($add, $del, $adddel, $file);
296 } run_cmd_pipe(qw(git ls-files --), @ARGV);
297 return if (!@tracked);
300 my $reference = get_diff_reference($patch_mode_revision);
301 for (run_cmd_pipe(qw(git diff-index --cached
302 --numstat --summary), $reference,
304 if (($add, $del, $file) =
305 /^([-\d]+) ([-\d]+) (.*)/) {
307 $file = unquote_path($file);
308 if ($add eq '-' && $del eq '-') {
313 $change = "+$add/-$del";
321 elsif (($adddel, $file) =
322 /^ (create|delete) mode [0-7]+ (.*)$/) {
323 $file = unquote_path($file);
324 $data{$file}{INDEX_ADDDEL} = $adddel;
328 for (run_cmd_pipe(qw(git diff-files --numstat --summary --raw --), @tracked)) {
329 if (($add, $del, $file) =
330 /^([-\d]+) ([-\d]+) (.*)/) {
331 $file = unquote_path($file);
333 if ($add eq '-' && $del eq '-') {
338 $change = "+$add/-$del";
340 $data{$file}{FILE} = $change;
342 $data{$file}{BINARY} = 1;
345 elsif (($adddel, $file) =
346 /^ (create|delete) mode [0-7]+ (.*)$/) {
347 $file = unquote_path($file);
348 $data{$file}{FILE_ADDDEL} = $adddel;
350 elsif (/^:[0-7]+ [0-7]+ [0-9a-f]+ [0-9a-f]+ (.) (.*)$/) {
351 $file = unquote_path($2);
352 if (!exists $data{$file}) {
354 INDEX => 'unchanged',
359 $data{$file}{UNMERGED} = 1;
364 for (sort keys %data) {
368 if ($only eq 'index-only') {
369 next if ($it->{INDEX} eq 'unchanged');
371 if ($only eq 'file-only') {
372 next if ($it->{FILE} eq 'nothing');
384 my ($string, @stuff) = @_;
386 for (my $i = 0; $i < @stuff; $i++) {
390 if ((ref $it) eq 'ARRAY') {
398 if ($it =~ /^$string/) {
402 if (defined $hit && defined $found) {
412 # inserts string into trie and updates count for each character
414 my ($trie, $string) = @_;
415 foreach (split //, $string) {
416 $trie = $trie->{$_} ||= {COUNT => 0};
421 # returns an array of tuples (prefix, remainder)
422 sub find_unique_prefixes {
426 # any single prefix exceeding the soft limit is omitted
427 # if any prefix exceeds the hard limit all are omitted
428 # 0 indicates no limit
432 # build a trie modelling all possible options
434 foreach my $print (@stuff) {
435 if ((ref $print) eq 'ARRAY') {
436 $print = $print->[0];
438 elsif ((ref $print) eq 'HASH') {
439 $print = $print->{VALUE};
441 update_trie(\%trie, $print);
442 push @return, $print;
445 # use the trie to find the unique prefixes
446 for (my $i = 0; $i < @return; $i++) {
447 my $ret = $return[$i];
448 my @letters = split //, $ret;
450 my ($prefix, $remainder);
452 for ($j = 0; $j < @letters; $j++) {
453 my $letter = $letters[$j];
454 if ($search{$letter}{COUNT} == 1) {
455 $prefix = substr $ret, 0, $j + 1;
456 $remainder = substr $ret, $j + 1;
460 my $prefix = substr $ret, 0, $j;
462 if ($hard_limit && $j + 1 > $hard_limit);
464 %search = %{$search{$letter}};
466 if (ord($letters[0]) > 127 ||
467 ($soft_limit && $j + 1 > $soft_limit)) {
471 $return[$i] = [$prefix, $remainder];
476 # filters out prefixes which have special meaning to list_and_choose()
477 sub is_valid_prefix {
479 return (defined $prefix) &&
480 !($prefix =~ /[\s,]/) && # separators
481 !($prefix =~ /^-/) && # deselection
482 !($prefix =~ /^\d+/) && # selection
483 ($prefix ne '*') && # "all" wildcard
484 ($prefix ne '?'); # prompt help
487 # given a prefix/remainder tuple return a string with the prefix highlighted
488 # for now use square brackets; later might use ANSI colors (underline, bold)
489 sub highlight_prefix {
491 my $remainder = shift;
493 if (!defined $prefix) {
497 if (!is_valid_prefix($prefix)) {
498 return "$prefix$remainder";
501 if (!$menu_use_color) {
502 return "[$prefix]$remainder";
505 return "$prompt_color$prefix$normal_color$remainder";
509 print STDERR colored $error_color, @_;
512 sub list_and_choose {
513 my ($opts, @stuff) = @_;
514 my (@chosen, @return);
516 my @prefixes = find_unique_prefixes(@stuff) unless $opts->{LIST_ONLY};
522 if ($opts->{HEADER}) {
523 if (!$opts->{LIST_FLAT}) {
526 print colored $header_color, "$opts->{HEADER}\n";
528 for ($i = 0; $i < @stuff; $i++) {
529 my $chosen = $chosen[$i] ? '*' : ' ';
530 my $print = $stuff[$i];
531 my $ref = ref $print;
532 my $highlighted = highlight_prefix(@{$prefixes[$i]})
534 if ($ref eq 'ARRAY') {
535 $print = $highlighted || $print->[0];
537 elsif ($ref eq 'HASH') {
538 my $value = $highlighted || $print->{VALUE};
539 $print = sprintf($status_fmt,
545 $print = $highlighted || $print;
547 printf("%s%2d: %s", $chosen, $i+1, $print);
548 if (($opts->{LIST_FLAT}) &&
549 (($i + 1) % ($opts->{LIST_FLAT}))) {
562 return if ($opts->{LIST_ONLY});
564 print colored $prompt_color, $opts->{PROMPT};
565 if ($opts->{SINGLETON}) {
574 $opts->{ON_EOF}->() if $opts->{ON_EOF};
581 singleton_prompt_help_cmd() :
585 for my $choice (split(/[\s,]+/, $line)) {
589 # Input that begins with '-'; unchoose
590 if ($choice =~ s/^-//) {
593 # A range can be specified like 5-7 or 5-.
594 if ($choice =~ /^(\d+)-(\d*)$/) {
595 ($bottom, $top) = ($1, length($2) ? $2 : 1 + @stuff);
597 elsif ($choice =~ /^\d+$/) {
598 $bottom = $top = $choice;
600 elsif ($choice eq '*') {
605 $bottom = $top = find_unique($choice, @stuff);
606 if (!defined $bottom) {
607 error_msg "Huh ($choice)?\n";
611 if ($opts->{SINGLETON} && $bottom != $top) {
612 error_msg "Huh ($choice)?\n";
615 for ($i = $bottom-1; $i <= $top-1; $i++) {
616 next if (@stuff <= $i || $i < 0);
617 $chosen[$i] = $choose;
620 last if ($opts->{IMMEDIATE} || $line eq '*');
622 for ($i = 0; $i < @stuff; $i++) {
624 push @return, $stuff[$i];
630 sub singleton_prompt_help_cmd {
631 print colored $help_color, <<\EOF ;
633 1 - select a numbered item
634 foo - select item based on unique prefix
635 - (empty) select nothing
639 sub prompt_help_cmd {
640 print colored $help_color, <<\EOF ;
642 1 - select a single item
643 3-5 - select a range of items
644 2-3,6-9 - select multiple ranges
645 foo - select item based on unique prefix
646 -... - unselect specified items
648 - (empty) finish selecting
653 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
663 print "$cnt paths\n";
671 my @mods = list_modified('file-only');
674 my @update = list_and_choose({ PROMPT => 'Update',
675 HEADER => $status_head, },
678 system(qw(git update-index --add --remove --),
679 map { $_->{VALUE} } @update);
680 say_n_paths('updated', @update);
686 my @update = list_and_choose({ PROMPT => 'Revert',
687 HEADER => $status_head, },
690 if (is_initial_commit()) {
691 system(qw(git rm --cached),
692 map { $_->{VALUE} } @update);
695 my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
696 map { $_->{VALUE} } @update);
698 open $fh, '| git update-index --index-info'
705 if ($_->{INDEX_ADDDEL} &&
706 $_->{INDEX_ADDDEL} eq 'create') {
707 system(qw(git update-index --force-remove --),
709 print "note: $_->{VALUE} is untracked now.\n";
714 say_n_paths('reverted', @update);
719 sub add_untracked_cmd {
720 my @add = list_and_choose({ PROMPT => 'Add untracked' },
723 system(qw(git update-index --add --), @add);
724 say_n_paths('added', @add);
732 open $fh, '| git ' . $cmd . " --recount --allow-overlap";
739 my @diff_cmd = split(" ", $patch_mode_flavour{DIFF});
740 if (defined $diff_algorithm) {
741 splice @diff_cmd, 1, 0, "--diff-algorithm=${diff_algorithm}";
743 if (defined $patch_mode_revision) {
744 push @diff_cmd, get_diff_reference($patch_mode_revision);
746 my @diff = run_cmd_pipe("git", @diff_cmd, "--", $path);
748 if ($diff_use_color) {
749 @colored = run_cmd_pipe("git", @diff_cmd, qw(--color --), $path);
751 my (@hunk) = { TEXT => [], DISPLAY => [], TYPE => 'header' };
753 for (my $i = 0; $i < @diff; $i++) {
754 if ($diff[$i] =~ /^@@ /) {
755 push @hunk, { TEXT => [], DISPLAY => [],
758 push @{$hunk[-1]{TEXT}}, $diff[$i];
759 push @{$hunk[-1]{DISPLAY}},
760 ($diff_use_color ? $colored[$i] : $diff[$i]);
765 sub parse_diff_header {
768 my $head = { TEXT => [], DISPLAY => [], TYPE => 'header' };
769 my $mode = { TEXT => [], DISPLAY => [], TYPE => 'mode' };
770 my $deletion = { TEXT => [], DISPLAY => [], TYPE => 'deletion' };
772 for (my $i = 0; $i < @{$src->{TEXT}}; $i++) {
774 $src->{TEXT}->[$i] =~ /^(old|new) mode (\d+)$/ ? $mode :
775 $src->{TEXT}->[$i] =~ /^deleted file/ ? $deletion :
777 push @{$dest->{TEXT}}, $src->{TEXT}->[$i];
778 push @{$dest->{DISPLAY}}, $src->{DISPLAY}->[$i];
780 return ($head, $mode, $deletion);
783 sub hunk_splittable {
786 my @s = split_hunk($text);
790 sub parse_hunk_header {
792 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
793 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
794 $o_cnt = 1 unless defined $o_cnt;
795 $n_cnt = 1 unless defined $n_cnt;
796 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
800 my ($text, $display) = @_;
802 if (!defined $display) {
805 # If there are context lines in the middle of a hunk,
806 # it can be split, but we would need to take care of
809 my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
814 my $next_hunk_start = undef;
815 my $i = $hunk_start - 1;
829 while (++$i < @$text) {
830 my $line = $text->[$i];
831 my $display = $display->[$i];
833 if ($this->{ADDDEL} &&
834 !defined $next_hunk_start) {
835 # We have seen leading context and
836 # adds/dels and then here is another
837 # context, which is trailing for this
838 # split hunk and leading for the next
840 $next_hunk_start = $i;
842 push @{$this->{TEXT}}, $line;
843 push @{$this->{DISPLAY}}, $display;
846 if (defined $next_hunk_start) {
853 if (defined $next_hunk_start) {
854 # We are done with the current hunk and
855 # this is the first real change for the
857 $hunk_start = $next_hunk_start;
858 $o_ofs = $this->{OLD} + $this->{OCNT};
859 $n_ofs = $this->{NEW} + $this->{NCNT};
860 $o_ofs -= $this->{POSTCTX};
861 $n_ofs -= $this->{POSTCTX};
865 push @{$this->{TEXT}}, $line;
866 push @{$this->{DISPLAY}}, $display;
880 for my $hunk (@split) {
881 $o_ofs = $hunk->{OLD};
882 $n_ofs = $hunk->{NEW};
883 my $o_cnt = $hunk->{OCNT};
884 my $n_cnt = $hunk->{NCNT};
886 my $head = ("@@ -$o_ofs" .
887 (($o_cnt != 1) ? ",$o_cnt" : '') .
889 (($n_cnt != 1) ? ",$n_cnt" : '') .
891 my $display_head = $head;
892 unshift @{$hunk->{TEXT}}, $head;
893 if ($diff_use_color) {
894 $display_head = colored($fraginfo_color, $head);
896 unshift @{$hunk->{DISPLAY}}, $display_head;
901 sub find_last_o_ctx {
903 my $text = $it->{TEXT};
904 my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
906 my $last_o_ctx = $o_ofs + $o_cnt;
908 my $line = $text->[$i];
919 my ($prev, $this) = @_;
920 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
921 parse_hunk_header($prev->{TEXT}[0]);
922 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
923 parse_hunk_header($this->{TEXT}[0]);
925 my (@line, $i, $ofs, $o_cnt, $n_cnt);
928 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
929 my $line = $prev->{TEXT}[$i];
930 if ($line =~ /^\+/) {
936 last if ($o1_ofs <= $ofs);
946 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
947 my $line = $this->{TEXT}[$i];
948 if ($line =~ /^\+/) {
960 my $head = ("@@ -$o0_ofs" .
961 (($o_cnt != 1) ? ",$o_cnt" : '') .
963 (($n_cnt != 1) ? ",$n_cnt" : '') .
965 @{$prev->{TEXT}} = ($head, @line);
968 sub coalesce_overlapping_hunks {
972 my ($last_o_ctx, $last_was_dirty);
974 for (grep { $_->{USE} } @in) {
975 if ($_->{TYPE} ne 'hunk') {
979 my $text = $_->{TEXT};
980 my ($o_ofs) = parse_hunk_header($text->[0]);
981 if (defined $last_o_ctx &&
982 $o_ofs <= $last_o_ctx &&
985 merge_hunk($out[-1], $_);
990 $last_o_ctx = find_last_o_ctx($out[-1]);
991 $last_was_dirty = $_->{DIRTY};
996 sub reassemble_patch {
1000 # Include everything in the header except the beginning of the diff.
1001 push @patch, (grep { !/^[-+]{3}/ } @$head);
1003 # Then include any headers from the hunk lines, which must
1004 # come before any actual hunk.
1005 while (@_ && $_[0] !~ /^@/) {
1009 # Then begin the diff.
1010 push @patch, grep { /^[-+]{3}/ } @$head;
1012 # And then the actual hunks.
1020 colored((/^@/ ? $fraginfo_color :
1021 /^\+/ ? $diff_new_color :
1022 /^-/ ? $diff_old_color :
1028 sub edit_hunk_manually {
1031 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
1033 open $fh, '>', $hunkfile
1034 or die "failed to open hunk edit file for writing: " . $!;
1035 print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
1036 print $fh @$oldtext;
1037 my $participle = $patch_mode_flavour{PARTICIPLE};
1038 my $is_reverse = $patch_mode_flavour{IS_REVERSE};
1039 my ($remove_plus, $remove_minus) = $is_reverse ? ('-', '+') : ('+', '-');
1042 # To remove '$remove_minus' lines, make them ' ' lines (context).
1043 # To remove '$remove_plus' lines, delete them.
1044 # Lines starting with # will be removed.
1046 # If the patch applies cleanly, the edited hunk will immediately be
1047 # marked for $participle. If it does not apply cleanly, you will be given
1048 # an opportunity to edit again. If all lines of the hunk are removed,
1049 # then the edit is aborted and the hunk is left unchanged.
1053 chomp(my $editor = run_cmd_pipe(qw(git var GIT_EDITOR)));
1054 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
1060 open $fh, '<', $hunkfile
1061 or die "failed to open hunk edit file for reading: " . $!;
1062 my @newtext = grep { !/^#/ } <$fh>;
1066 # Abort if nothing remains
1067 if (!grep { /\S/ } @newtext) {
1071 # Reinsert the first hunk header if the user accidentally deleted it
1072 if ($newtext[0] !~ /^@/) {
1073 unshift @newtext, $oldtext->[0];
1079 return run_git_apply($patch_mode_flavour{APPLY_CHECK} . ' --check',
1080 map { @{$_->{TEXT}} } @_);
1083 sub _restore_terminal_and_die {
1089 sub prompt_single_character {
1091 local $SIG{TERM} = \&_restore_terminal_and_die;
1092 local $SIG{INT} = \&_restore_terminal_and_die;
1094 my $key = ReadKey 0;
1096 if ($use_termcap and $key eq "\e") {
1097 while (!defined $term_escapes{$key}) {
1098 my $next = ReadKey 0.5;
1099 last if (!defined $next);
1104 print "$key" if defined $key;
1115 print colored $prompt_color, $prompt;
1116 my $line = prompt_single_character;
1117 return 0 if $line =~ /^n/i;
1118 return 1 if $line =~ /^y/i;
1122 sub edit_hunk_loop {
1123 my ($head, $hunk, $ix) = @_;
1124 my $text = $hunk->[$ix]->{TEXT};
1127 $text = edit_hunk_manually($text);
1128 if (!defined $text) {
1133 TYPE => $hunk->[$ix]->{TYPE},
1137 if (diff_applies($head,
1140 @{$hunk}[$ix+1..$#{$hunk}])) {
1141 $newhunk->{DISPLAY} = [color_diff(@{$text})];
1146 'Your edited hunk does not apply. Edit again '
1147 . '(saying "no" discards!) [y/n]? '
1153 sub help_patch_cmd {
1154 my $verb = lc $patch_mode_flavour{VERB};
1155 my $target = $patch_mode_flavour{TARGET};
1156 print colored $help_color, <<EOF ;
1157 y - $verb this hunk$target
1158 n - do not $verb this hunk$target
1159 q - quit; do not $verb this hunk or any of the remaining ones
1160 a - $verb this hunk and all later hunks in the file
1161 d - do not $verb this hunk or any of the later hunks in the file
1162 g - select a hunk to go to
1163 / - search for a hunk matching the given regex
1164 j - leave this hunk undecided, see next undecided hunk
1165 J - leave this hunk undecided, see next hunk
1166 k - leave this hunk undecided, see previous undecided hunk
1167 K - leave this hunk undecided, see previous hunk
1168 s - split the current hunk into smaller hunks
1169 e - manually edit the current hunk
1176 my $ret = run_git_apply $cmd, @_;
1183 sub apply_patch_for_checkout_commit {
1184 my $reverse = shift;
1185 my $applies_index = run_git_apply 'apply '.$reverse.' --cached --check', @_;
1186 my $applies_worktree = run_git_apply 'apply '.$reverse.' --check', @_;
1188 if ($applies_worktree && $applies_index) {
1189 run_git_apply 'apply '.$reverse.' --cached', @_;
1190 run_git_apply 'apply '.$reverse, @_;
1192 } elsif (!$applies_index) {
1193 print colored $error_color, "The selected hunks do not apply to the index!\n";
1194 if (prompt_yesno "Apply them to the worktree anyway? ") {
1195 return run_git_apply 'apply '.$reverse, @_;
1197 print colored $error_color, "Nothing was applied.\n";
1206 sub patch_update_cmd {
1207 my @all_mods = list_modified($patch_mode_flavour{FILTER});
1208 error_msg "ignoring unmerged: $_->{VALUE}\n"
1209 for grep { $_->{UNMERGED} } @all_mods;
1210 @all_mods = grep { !$_->{UNMERGED} } @all_mods;
1212 my @mods = grep { !($_->{BINARY}) } @all_mods;
1217 print STDERR "Only binary files changed.\n";
1219 print STDERR "No changes.\n";
1227 @them = list_and_choose({ PROMPT => 'Patch update',
1228 HEADER => $status_head, },
1232 return 0 if patch_update_file($_->{VALUE});
1236 # Generate a one line summary of a hunk.
1237 sub summarize_hunk {
1239 my $summary = $rhunk->{TEXT}[0];
1241 # Keep the line numbers, discard extra context.
1242 $summary =~ s/@@(.*?)@@.*/$1 /s;
1243 $summary .= " " x (20 - length $summary);
1245 # Add some user context.
1246 for my $line (@{$rhunk->{TEXT}}) {
1247 if ($line =~ m/^[+-].*\w/) {
1254 return substr($summary, 0, 80) . "\n";
1258 # Print a one-line summary of each hunk in the array ref in
1259 # the first argument, starting with the index in the 2nd.
1261 my ($hunks, $i) = @_;
1264 for (; $i < @$hunks && $ctr < 20; $i++, $ctr++) {
1266 if (defined $hunks->[$i]{USE}) {
1267 $status = $hunks->[$i]{USE} ? "+" : "-";
1272 summarize_hunk($hunks->[$i]);
1277 sub patch_update_file {
1281 my ($head, @hunk) = parse_diff($path);
1282 ($head, my $mode, my $deletion) = parse_diff_header($head);
1283 for (@{$head->{DISPLAY}}) {
1287 if (@{$mode->{TEXT}}) {
1288 unshift @hunk, $mode;
1290 if (@{$deletion->{TEXT}}) {
1291 foreach my $hunk (@hunk) {
1292 push @{$deletion->{TEXT}}, @{$hunk->{TEXT}};
1293 push @{$deletion->{DISPLAY}}, @{$hunk->{DISPLAY}};
1295 @hunk = ($deletion);
1298 $num = scalar @hunk;
1302 my ($prev, $next, $other, $undecided, $i);
1308 for ($i = 0; $i < $ix; $i++) {
1309 if (!defined $hunk[$i]{USE}) {
1318 for ($i = $ix + 1; $i < $num; $i++) {
1319 if (!defined $hunk[$i]{USE}) {
1325 if ($ix < $num - 1) {
1331 for ($i = 0; $i < $num; $i++) {
1332 if (!defined $hunk[$i]{USE}) {
1337 last if (!$undecided);
1339 if ($hunk[$ix]{TYPE} eq 'hunk' &&
1340 hunk_splittable($hunk[$ix]{TEXT})) {
1343 if ($hunk[$ix]{TYPE} eq 'hunk') {
1346 for (@{$hunk[$ix]{DISPLAY}}) {
1349 print colored $prompt_color, $patch_mode_flavour{VERB},
1350 ($hunk[$ix]{TYPE} eq 'mode' ? ' mode change' :
1351 $hunk[$ix]{TYPE} eq 'deletion' ? ' deletion' :
1353 $patch_mode_flavour{TARGET},
1354 " [y,n,q,a,d,/$other,?]? ";
1355 my $line = prompt_single_character;
1357 if ($line =~ /^y/i) {
1358 $hunk[$ix]{USE} = 1;
1360 elsif ($line =~ /^n/i) {
1361 $hunk[$ix]{USE} = 0;
1363 elsif ($line =~ /^a/i) {
1364 while ($ix < $num) {
1365 if (!defined $hunk[$ix]{USE}) {
1366 $hunk[$ix]{USE} = 1;
1372 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1374 my $no = $ix > 10 ? $ix - 10 : 0;
1375 while ($response eq '') {
1377 $no = display_hunks(\@hunk, $no);
1379 $extra = " (<ret> to see more)";
1381 print "go to which hunk$extra? ";
1382 $response = <STDIN>;
1383 if (!defined $response) {
1388 if ($response !~ /^\s*\d+\s*$/) {
1389 error_msg "Invalid number: '$response'\n";
1390 } elsif (0 < $response && $response <= $num) {
1391 $ix = $response - 1;
1393 error_msg "Sorry, only $num hunks available.\n";
1397 elsif ($line =~ /^d/i) {
1398 while ($ix < $num) {
1399 if (!defined $hunk[$ix]{USE}) {
1400 $hunk[$ix]{USE} = 0;
1406 elsif ($line =~ /^q/i) {
1407 for ($i = 0; $i < $num; $i++) {
1408 if (!defined $hunk[$i]{USE}) {
1415 elsif ($line =~ m|^/(.*)|) {
1418 print colored $prompt_color, "search for regex? ";
1420 if (defined $regex) {
1426 $search_string = qr{$regex}m;
1429 my ($err,$exp) = ($@, $1);
1430 $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1431 error_msg "Malformed search regexp $exp: $err\n";
1436 my $text = join ("", @{$hunk[$iy]{TEXT}});
1437 last if ($text =~ $search_string);
1439 $iy = 0 if ($iy >= $num);
1441 error_msg "No hunk matches the given pattern\n";
1448 elsif ($line =~ /^K/) {
1449 if ($other =~ /K/) {
1453 error_msg "No previous hunk\n";
1457 elsif ($line =~ /^J/) {
1458 if ($other =~ /J/) {
1462 error_msg "No next hunk\n";
1466 elsif ($line =~ /^k/) {
1467 if ($other =~ /k/) {
1471 !defined $hunk[$ix]{USE});
1475 error_msg "No previous hunk\n";
1479 elsif ($line =~ /^j/) {
1480 if ($other !~ /j/) {
1481 error_msg "No next hunk\n";
1485 elsif ($other =~ /s/ && $line =~ /^s/) {
1486 my @split = split_hunk($hunk[$ix]{TEXT}, $hunk[$ix]{DISPLAY});
1488 print colored $header_color, "Split into ",
1489 scalar(@split), " hunks.\n";
1491 splice (@hunk, $ix, 1, @split);
1492 $num = scalar @hunk;
1495 elsif ($other =~ /e/ && $line =~ /^e/) {
1496 my $newhunk = edit_hunk_loop($head, \@hunk, $ix);
1497 if (defined $newhunk) {
1498 splice @hunk, $ix, 1, $newhunk;
1502 help_patch_cmd($other);
1508 last if ($ix >= $num ||
1509 !defined $hunk[$ix]{USE});
1514 @hunk = coalesce_overlapping_hunks(@hunk);
1520 push @result, @{$_->{TEXT}};
1525 my @patch = reassemble_patch($head->{TEXT}, @result);
1526 my $apply_routine = $patch_mode_flavour{APPLY};
1527 &$apply_routine(@patch);
1536 my @mods = list_modified('index-only');
1537 @mods = grep { !($_->{BINARY}) } @mods;
1539 my (@them) = list_and_choose({ PROMPT => 'Review diff',
1541 HEADER => $status_head, },
1544 my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
1545 system(qw(git diff -p --cached), $reference, '--',
1546 map { $_->{VALUE} } @them);
1555 print colored $help_color, <<\EOF ;
1556 status - show paths with changes
1557 update - add working tree state to the staged set of changes
1558 revert - revert staged set of changes back to the HEAD version
1559 patch - pick hunks and update selectively
1560 diff - view diff between HEAD and index
1561 add untracked - add contents of untracked files to the staged set of changes
1566 return unless @ARGV;
1567 my $arg = shift @ARGV;
1568 if ($arg =~ /--patch(?:=(.*))?/) {
1570 if ($1 eq 'reset') {
1571 $patch_mode = 'reset_head';
1572 $patch_mode_revision = 'HEAD';
1573 $arg = shift @ARGV or die "missing --";
1575 $patch_mode_revision = $arg;
1576 $patch_mode = ($arg eq 'HEAD' ?
1577 'reset_head' : 'reset_nothead');
1578 $arg = shift @ARGV or die "missing --";
1580 } elsif ($1 eq 'checkout') {
1581 $arg = shift @ARGV or die "missing --";
1583 $patch_mode = 'checkout_index';
1585 $patch_mode_revision = $arg;
1586 $patch_mode = ($arg eq 'HEAD' ?
1587 'checkout_head' : 'checkout_nothead');
1588 $arg = shift @ARGV or die "missing --";
1590 } elsif ($1 eq 'stage' or $1 eq 'stash') {
1592 $arg = shift @ARGV or die "missing --";
1594 die "unknown --patch mode: $1";
1597 $patch_mode = 'stage';
1598 $arg = shift @ARGV or die "missing --";
1600 die "invalid argument $arg, expecting --"
1601 unless $arg eq "--";
1602 %patch_mode_flavour = %{$patch_modes{$patch_mode}};
1604 elsif ($arg ne "--") {
1605 die "invalid argument $arg, expecting --";
1610 my @cmd = ([ 'status', \&status_cmd, ],
1611 [ 'update', \&update_cmd, ],
1612 [ 'revert', \&revert_cmd, ],
1613 [ 'add untracked', \&add_untracked_cmd, ],
1614 [ 'patch', \&patch_update_cmd, ],
1615 [ 'diff', \&diff_cmd, ],
1616 [ 'quit', \&quit_cmd, ],
1617 [ 'help', \&help_cmd, ],
1620 my ($it) = list_and_choose({ PROMPT => 'What now',
1623 HEADER => '*** Commands ***',
1624 ON_EOF => \&quit_cmd,
1625 IMMEDIATE => 1 }, @cmd);