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_compaction_heuristic = $repo->config_bool('diff.compactionheuristic');
49 my $diff_filter = $repo->config('interactive.difffilter');
57 if ($repo->config_bool("interactive.singlekey")) {
59 require Term::ReadKey;
60 Term::ReadKey->import;
64 print STDERR "missing Term::ReadKey, disabling interactive.singlekey\n";
68 my $termcap = Term::Cap->Tgetent;
69 foreach (values %$termcap) {
70 $term_escapes{$_} = 1 if /^\e/;
78 my $string = join("", @_);
81 # Put a color code at the beginning of each line, a reset at the end
82 # color after newlines that are not at the end of the string
83 $string =~ s/(\n+)(.)/$1$color$2/g;
84 # reset before newlines
85 $string =~ s/(\n+)/$normal_color$1/g;
86 # codes at beginning and end (if necessary):
87 $string =~ s/^/$color/;
88 $string =~ s/$/$normal_color/ unless $string =~ /\n$/;
93 # command line options
95 my $patch_mode_revision;
98 sub apply_patch_for_checkout_commit;
99 sub apply_patch_for_stash;
103 DIFF => 'diff-files -p',
104 APPLY => sub { apply_patch 'apply --cached', @_; },
105 APPLY_CHECK => 'apply --cached',
108 PARTICIPLE => 'staging',
109 FILTER => 'file-only',
113 DIFF => 'diff-index -p HEAD',
114 APPLY => sub { apply_patch 'apply --cached', @_; },
115 APPLY_CHECK => 'apply --cached',
118 PARTICIPLE => 'stashing',
123 DIFF => 'diff-index -p --cached',
124 APPLY => sub { apply_patch 'apply -R --cached', @_; },
125 APPLY_CHECK => 'apply -R --cached',
128 PARTICIPLE => 'unstaging',
129 FILTER => 'index-only',
133 DIFF => 'diff-index -R -p --cached',
134 APPLY => sub { apply_patch 'apply --cached', @_; },
135 APPLY_CHECK => 'apply --cached',
137 TARGET => ' to index',
138 PARTICIPLE => 'applying',
139 FILTER => 'index-only',
142 'checkout_index' => {
143 DIFF => 'diff-files -p',
144 APPLY => sub { apply_patch 'apply -R', @_; },
145 APPLY_CHECK => 'apply -R',
147 TARGET => ' from worktree',
148 PARTICIPLE => 'discarding',
149 FILTER => 'file-only',
153 DIFF => 'diff-index -p',
154 APPLY => sub { apply_patch_for_checkout_commit '-R', @_ },
155 APPLY_CHECK => 'apply -R',
157 TARGET => ' from index and worktree',
158 PARTICIPLE => 'discarding',
162 'checkout_nothead' => {
163 DIFF => 'diff-index -R -p',
164 APPLY => sub { apply_patch_for_checkout_commit '', @_ },
165 APPLY_CHECK => 'apply',
167 TARGET => ' to index and worktree',
168 PARTICIPLE => 'applying',
174 my %patch_mode_flavour = %{$patch_modes{stage}};
177 if ($^O eq 'MSWin32') {
178 my @invalid = grep {m/[":*]/} @_;
179 die "$^O does not support: @invalid\n" if @invalid;
180 my @args = map { m/ /o ? "\"$_\"": $_ } @_;
184 open($fh, '-|', @_) or die;
189 my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));
191 if (!defined $GIT_DIR) {
192 exit(1); # rev-parse would have already said "not a git repo"
209 my ($retval, $remainder);
210 if (!/^\042(.*)\042$/) {
213 ($_, $retval) = ($1, "");
214 while (/^([^\\]*)\\(.*)$/) {
218 if (/^([0-3][0-7][0-7])(.*)$/) {
219 $retval .= chr(oct($1));
223 if (/^([\\\042btnvfr])(.*)$/) {
224 $retval .= $cquote_map{$1};
228 # This is malformed -- just return it as-is for now.
239 open $fh, 'git update-index --refresh |'
242 ;# ignore 'needs update'
252 run_cmd_pipe(qw(git ls-files --others --exclude-standard --), @ARGV);
255 my $status_fmt = '%12s %12s %s';
256 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
260 sub is_initial_commit {
261 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
262 unless defined $initial;
268 return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
271 sub get_diff_reference {
273 if (defined $ref and $ref ne 'HEAD') {
275 } elsif (is_initial_commit()) {
276 return get_empty_tree();
282 # Returns list of hashes, contents of each of which are:
284 # BINARY: is a binary path
285 # INDEX: is index different from HEAD?
286 # FILE: is file different from index?
287 # INDEX_ADDDEL: is it add/delete between HEAD and index?
288 # FILE_ADDDEL: is it add/delete between index and file?
289 # UNMERGED: is the path unmerged
294 my ($add, $del, $adddel, $file);
301 } run_cmd_pipe(qw(git ls-files --), @ARGV);
302 return if (!@tracked);
305 my $reference = get_diff_reference($patch_mode_revision);
306 for (run_cmd_pipe(qw(git diff-index --cached
307 --numstat --summary), $reference,
309 if (($add, $del, $file) =
310 /^([-\d]+) ([-\d]+) (.*)/) {
312 $file = unquote_path($file);
313 if ($add eq '-' && $del eq '-') {
318 $change = "+$add/-$del";
326 elsif (($adddel, $file) =
327 /^ (create|delete) mode [0-7]+ (.*)$/) {
328 $file = unquote_path($file);
329 $data{$file}{INDEX_ADDDEL} = $adddel;
333 for (run_cmd_pipe(qw(git diff-files --numstat --summary --raw --), @tracked)) {
334 if (($add, $del, $file) =
335 /^([-\d]+) ([-\d]+) (.*)/) {
336 $file = unquote_path($file);
338 if ($add eq '-' && $del eq '-') {
343 $change = "+$add/-$del";
345 $data{$file}{FILE} = $change;
347 $data{$file}{BINARY} = 1;
350 elsif (($adddel, $file) =
351 /^ (create|delete) mode [0-7]+ (.*)$/) {
352 $file = unquote_path($file);
353 $data{$file}{FILE_ADDDEL} = $adddel;
355 elsif (/^:[0-7]+ [0-7]+ [0-9a-f]+ [0-9a-f]+ (.) (.*)$/) {
356 $file = unquote_path($2);
357 if (!exists $data{$file}) {
359 INDEX => 'unchanged',
364 $data{$file}{UNMERGED} = 1;
369 for (sort keys %data) {
373 if ($only eq 'index-only') {
374 next if ($it->{INDEX} eq 'unchanged');
376 if ($only eq 'file-only') {
377 next if ($it->{FILE} eq 'nothing');
389 my ($string, @stuff) = @_;
391 for (my $i = 0; $i < @stuff; $i++) {
395 if ((ref $it) eq 'ARRAY') {
403 if ($it =~ /^$string/) {
407 if (defined $hit && defined $found) {
417 # inserts string into trie and updates count for each character
419 my ($trie, $string) = @_;
420 foreach (split //, $string) {
421 $trie = $trie->{$_} ||= {COUNT => 0};
426 # returns an array of tuples (prefix, remainder)
427 sub find_unique_prefixes {
431 # any single prefix exceeding the soft limit is omitted
432 # if any prefix exceeds the hard limit all are omitted
433 # 0 indicates no limit
437 # build a trie modelling all possible options
439 foreach my $print (@stuff) {
440 if ((ref $print) eq 'ARRAY') {
441 $print = $print->[0];
443 elsif ((ref $print) eq 'HASH') {
444 $print = $print->{VALUE};
446 update_trie(\%trie, $print);
447 push @return, $print;
450 # use the trie to find the unique prefixes
451 for (my $i = 0; $i < @return; $i++) {
452 my $ret = $return[$i];
453 my @letters = split //, $ret;
455 my ($prefix, $remainder);
457 for ($j = 0; $j < @letters; $j++) {
458 my $letter = $letters[$j];
459 if ($search{$letter}{COUNT} == 1) {
460 $prefix = substr $ret, 0, $j + 1;
461 $remainder = substr $ret, $j + 1;
465 my $prefix = substr $ret, 0, $j;
467 if ($hard_limit && $j + 1 > $hard_limit);
469 %search = %{$search{$letter}};
471 if (ord($letters[0]) > 127 ||
472 ($soft_limit && $j + 1 > $soft_limit)) {
476 $return[$i] = [$prefix, $remainder];
481 # filters out prefixes which have special meaning to list_and_choose()
482 sub is_valid_prefix {
484 return (defined $prefix) &&
485 !($prefix =~ /[\s,]/) && # separators
486 !($prefix =~ /^-/) && # deselection
487 !($prefix =~ /^\d+/) && # selection
488 ($prefix ne '*') && # "all" wildcard
489 ($prefix ne '?'); # prompt help
492 # given a prefix/remainder tuple return a string with the prefix highlighted
493 # for now use square brackets; later might use ANSI colors (underline, bold)
494 sub highlight_prefix {
496 my $remainder = shift;
498 if (!defined $prefix) {
502 if (!is_valid_prefix($prefix)) {
503 return "$prefix$remainder";
506 if (!$menu_use_color) {
507 return "[$prefix]$remainder";
510 return "$prompt_color$prefix$normal_color$remainder";
514 print STDERR colored $error_color, @_;
517 sub list_and_choose {
518 my ($opts, @stuff) = @_;
519 my (@chosen, @return);
524 my @prefixes = find_unique_prefixes(@stuff) unless $opts->{LIST_ONLY};
530 if ($opts->{HEADER}) {
531 if (!$opts->{LIST_FLAT}) {
534 print colored $header_color, "$opts->{HEADER}\n";
536 for ($i = 0; $i < @stuff; $i++) {
537 my $chosen = $chosen[$i] ? '*' : ' ';
538 my $print = $stuff[$i];
539 my $ref = ref $print;
540 my $highlighted = highlight_prefix(@{$prefixes[$i]})
542 if ($ref eq 'ARRAY') {
543 $print = $highlighted || $print->[0];
545 elsif ($ref eq 'HASH') {
546 my $value = $highlighted || $print->{VALUE};
547 $print = sprintf($status_fmt,
553 $print = $highlighted || $print;
555 printf("%s%2d: %s", $chosen, $i+1, $print);
556 if (($opts->{LIST_FLAT}) &&
557 (($i + 1) % ($opts->{LIST_FLAT}))) {
570 return if ($opts->{LIST_ONLY});
572 print colored $prompt_color, $opts->{PROMPT};
573 if ($opts->{SINGLETON}) {
582 $opts->{ON_EOF}->() if $opts->{ON_EOF};
589 singleton_prompt_help_cmd() :
593 for my $choice (split(/[\s,]+/, $line)) {
597 # Input that begins with '-'; unchoose
598 if ($choice =~ s/^-//) {
601 # A range can be specified like 5-7 or 5-.
602 if ($choice =~ /^(\d+)-(\d*)$/) {
603 ($bottom, $top) = ($1, length($2) ? $2 : 1 + @stuff);
605 elsif ($choice =~ /^\d+$/) {
606 $bottom = $top = $choice;
608 elsif ($choice eq '*') {
613 $bottom = $top = find_unique($choice, @stuff);
614 if (!defined $bottom) {
615 error_msg "Huh ($choice)?\n";
619 if ($opts->{SINGLETON} && $bottom != $top) {
620 error_msg "Huh ($choice)?\n";
623 for ($i = $bottom-1; $i <= $top-1; $i++) {
624 next if (@stuff <= $i || $i < 0);
625 $chosen[$i] = $choose;
628 last if ($opts->{IMMEDIATE} || $line eq '*');
630 for ($i = 0; $i < @stuff; $i++) {
632 push @return, $stuff[$i];
638 sub singleton_prompt_help_cmd {
639 print colored $help_color, <<\EOF ;
641 1 - select a numbered item
642 foo - select item based on unique prefix
643 - (empty) select nothing
647 sub prompt_help_cmd {
648 print colored $help_color, <<\EOF ;
650 1 - select a single item
651 3-5 - select a range of items
652 2-3,6-9 - select multiple ranges
653 foo - select item based on unique prefix
654 -... - unselect specified items
656 - (empty) finish selecting
661 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
671 print "$cnt paths\n";
679 my @mods = list_modified('file-only');
682 my @update = list_and_choose({ PROMPT => 'Update',
683 HEADER => $status_head, },
686 system(qw(git update-index --add --remove --),
687 map { $_->{VALUE} } @update);
688 say_n_paths('updated', @update);
694 my @update = list_and_choose({ PROMPT => 'Revert',
695 HEADER => $status_head, },
698 if (is_initial_commit()) {
699 system(qw(git rm --cached),
700 map { $_->{VALUE} } @update);
703 my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
704 map { $_->{VALUE} } @update);
706 open $fh, '| git update-index --index-info'
713 if ($_->{INDEX_ADDDEL} &&
714 $_->{INDEX_ADDDEL} eq 'create') {
715 system(qw(git update-index --force-remove --),
717 print "note: $_->{VALUE} is untracked now.\n";
722 say_n_paths('reverted', @update);
727 sub add_untracked_cmd {
728 my @add = list_and_choose({ PROMPT => 'Add untracked' },
731 system(qw(git update-index --add --), @add);
732 say_n_paths('added', @add);
734 print "No untracked files.\n";
742 open $fh, '| git ' . $cmd . " --recount --allow-overlap";
749 my @diff_cmd = split(" ", $patch_mode_flavour{DIFF});
750 if (defined $diff_algorithm) {
751 splice @diff_cmd, 1, 0, "--diff-algorithm=${diff_algorithm}";
753 if ($diff_compaction_heuristic) {
754 splice @diff_cmd, 1, 0, "--compaction-heuristic";
756 if (defined $patch_mode_revision) {
757 push @diff_cmd, get_diff_reference($patch_mode_revision);
759 my @diff = run_cmd_pipe("git", @diff_cmd, "--", $path);
761 if ($diff_use_color) {
762 my @display_cmd = ("git", @diff_cmd, qw(--color --), $path);
763 if (defined $diff_filter) {
764 # quotemeta is overkill, but sufficient for shell-quoting
765 my $diff = join(' ', map { quotemeta } @display_cmd);
766 @display_cmd = ("$diff | $diff_filter");
769 @colored = run_cmd_pipe(@display_cmd);
771 my (@hunk) = { TEXT => [], DISPLAY => [], TYPE => 'header' };
773 for (my $i = 0; $i < @diff; $i++) {
774 if ($diff[$i] =~ /^@@ /) {
775 push @hunk, { TEXT => [], DISPLAY => [],
778 push @{$hunk[-1]{TEXT}}, $diff[$i];
779 push @{$hunk[-1]{DISPLAY}},
780 (@colored ? $colored[$i] : $diff[$i]);
785 sub parse_diff_header {
788 my $head = { TEXT => [], DISPLAY => [], TYPE => 'header' };
789 my $mode = { TEXT => [], DISPLAY => [], TYPE => 'mode' };
790 my $deletion = { TEXT => [], DISPLAY => [], TYPE => 'deletion' };
792 for (my $i = 0; $i < @{$src->{TEXT}}; $i++) {
794 $src->{TEXT}->[$i] =~ /^(old|new) mode (\d+)$/ ? $mode :
795 $src->{TEXT}->[$i] =~ /^deleted file/ ? $deletion :
797 push @{$dest->{TEXT}}, $src->{TEXT}->[$i];
798 push @{$dest->{DISPLAY}}, $src->{DISPLAY}->[$i];
800 return ($head, $mode, $deletion);
803 sub hunk_splittable {
806 my @s = split_hunk($text);
810 sub parse_hunk_header {
812 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
813 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
814 $o_cnt = 1 unless defined $o_cnt;
815 $n_cnt = 1 unless defined $n_cnt;
816 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
820 my ($text, $display) = @_;
822 if (!defined $display) {
825 # If there are context lines in the middle of a hunk,
826 # it can be split, but we would need to take care of
829 my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
834 my $next_hunk_start = undef;
835 my $i = $hunk_start - 1;
849 while (++$i < @$text) {
850 my $line = $text->[$i];
851 my $display = $display->[$i];
853 if ($this->{ADDDEL} &&
854 !defined $next_hunk_start) {
855 # We have seen leading context and
856 # adds/dels and then here is another
857 # context, which is trailing for this
858 # split hunk and leading for the next
860 $next_hunk_start = $i;
862 push @{$this->{TEXT}}, $line;
863 push @{$this->{DISPLAY}}, $display;
866 if (defined $next_hunk_start) {
873 if (defined $next_hunk_start) {
874 # We are done with the current hunk and
875 # this is the first real change for the
877 $hunk_start = $next_hunk_start;
878 $o_ofs = $this->{OLD} + $this->{OCNT};
879 $n_ofs = $this->{NEW} + $this->{NCNT};
880 $o_ofs -= $this->{POSTCTX};
881 $n_ofs -= $this->{POSTCTX};
885 push @{$this->{TEXT}}, $line;
886 push @{$this->{DISPLAY}}, $display;
900 for my $hunk (@split) {
901 $o_ofs = $hunk->{OLD};
902 $n_ofs = $hunk->{NEW};
903 my $o_cnt = $hunk->{OCNT};
904 my $n_cnt = $hunk->{NCNT};
906 my $head = ("@@ -$o_ofs" .
907 (($o_cnt != 1) ? ",$o_cnt" : '') .
909 (($n_cnt != 1) ? ",$n_cnt" : '') .
911 my $display_head = $head;
912 unshift @{$hunk->{TEXT}}, $head;
913 if ($diff_use_color) {
914 $display_head = colored($fraginfo_color, $head);
916 unshift @{$hunk->{DISPLAY}}, $display_head;
921 sub find_last_o_ctx {
923 my $text = $it->{TEXT};
924 my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
926 my $last_o_ctx = $o_ofs + $o_cnt;
928 my $line = $text->[$i];
939 my ($prev, $this) = @_;
940 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
941 parse_hunk_header($prev->{TEXT}[0]);
942 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
943 parse_hunk_header($this->{TEXT}[0]);
945 my (@line, $i, $ofs, $o_cnt, $n_cnt);
948 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
949 my $line = $prev->{TEXT}[$i];
950 if ($line =~ /^\+/) {
956 last if ($o1_ofs <= $ofs);
966 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
967 my $line = $this->{TEXT}[$i];
968 if ($line =~ /^\+/) {
980 my $head = ("@@ -$o0_ofs" .
981 (($o_cnt != 1) ? ",$o_cnt" : '') .
983 (($n_cnt != 1) ? ",$n_cnt" : '') .
985 @{$prev->{TEXT}} = ($head, @line);
988 sub coalesce_overlapping_hunks {
992 my ($last_o_ctx, $last_was_dirty);
994 for (grep { $_->{USE} } @in) {
995 if ($_->{TYPE} ne 'hunk') {
999 my $text = $_->{TEXT};
1000 my ($o_ofs) = parse_hunk_header($text->[0]);
1001 if (defined $last_o_ctx &&
1002 $o_ofs <= $last_o_ctx &&
1005 merge_hunk($out[-1], $_);
1010 $last_o_ctx = find_last_o_ctx($out[-1]);
1011 $last_was_dirty = $_->{DIRTY};
1016 sub reassemble_patch {
1020 # Include everything in the header except the beginning of the diff.
1021 push @patch, (grep { !/^[-+]{3}/ } @$head);
1023 # Then include any headers from the hunk lines, which must
1024 # come before any actual hunk.
1025 while (@_ && $_[0] !~ /^@/) {
1029 # Then begin the diff.
1030 push @patch, grep { /^[-+]{3}/ } @$head;
1032 # And then the actual hunks.
1040 colored((/^@/ ? $fraginfo_color :
1041 /^\+/ ? $diff_new_color :
1042 /^-/ ? $diff_old_color :
1048 sub edit_hunk_manually {
1051 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
1053 open $fh, '>', $hunkfile
1054 or die "failed to open hunk edit file for writing: " . $!;
1055 print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
1056 print $fh @$oldtext;
1057 my $participle = $patch_mode_flavour{PARTICIPLE};
1058 my $is_reverse = $patch_mode_flavour{IS_REVERSE};
1059 my ($remove_plus, $remove_minus) = $is_reverse ? ('-', '+') : ('+', '-');
1062 # To remove '$remove_minus' lines, make them ' ' lines (context).
1063 # To remove '$remove_plus' lines, delete them.
1064 # Lines starting with # will be removed.
1066 # If the patch applies cleanly, the edited hunk will immediately be
1067 # marked for $participle. If it does not apply cleanly, you will be given
1068 # an opportunity to edit again. If all lines of the hunk are removed,
1069 # then the edit is aborted and the hunk is left unchanged.
1073 chomp(my $editor = run_cmd_pipe(qw(git var GIT_EDITOR)));
1074 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
1080 open $fh, '<', $hunkfile
1081 or die "failed to open hunk edit file for reading: " . $!;
1082 my @newtext = grep { !/^#/ } <$fh>;
1086 # Abort if nothing remains
1087 if (!grep { /\S/ } @newtext) {
1091 # Reinsert the first hunk header if the user accidentally deleted it
1092 if ($newtext[0] !~ /^@/) {
1093 unshift @newtext, $oldtext->[0];
1099 return run_git_apply($patch_mode_flavour{APPLY_CHECK} . ' --check',
1100 map { @{$_->{TEXT}} } @_);
1103 sub _restore_terminal_and_die {
1109 sub prompt_single_character {
1111 local $SIG{TERM} = \&_restore_terminal_and_die;
1112 local $SIG{INT} = \&_restore_terminal_and_die;
1114 my $key = ReadKey 0;
1116 if ($use_termcap and $key eq "\e") {
1117 while (!defined $term_escapes{$key}) {
1118 my $next = ReadKey 0.5;
1119 last if (!defined $next);
1124 print "$key" if defined $key;
1135 print colored $prompt_color, $prompt;
1136 my $line = prompt_single_character;
1137 return 0 if $line =~ /^n/i;
1138 return 1 if $line =~ /^y/i;
1142 sub edit_hunk_loop {
1143 my ($head, $hunk, $ix) = @_;
1144 my $text = $hunk->[$ix]->{TEXT};
1147 $text = edit_hunk_manually($text);
1148 if (!defined $text) {
1153 TYPE => $hunk->[$ix]->{TYPE},
1157 if (diff_applies($head,
1160 @{$hunk}[$ix+1..$#{$hunk}])) {
1161 $newhunk->{DISPLAY} = [color_diff(@{$text})];
1166 'Your edited hunk does not apply. Edit again '
1167 . '(saying "no" discards!) [y/n]? '
1173 sub help_patch_cmd {
1174 my $verb = lc $patch_mode_flavour{VERB};
1175 my $target = $patch_mode_flavour{TARGET};
1176 print colored $help_color, <<EOF ;
1177 y - $verb this hunk$target
1178 n - do not $verb this hunk$target
1179 q - quit; do not $verb this hunk or any of the remaining ones
1180 a - $verb this hunk and all later hunks in the file
1181 d - do not $verb this hunk or any of the later hunks in the file
1182 g - select a hunk to go to
1183 / - search for a hunk matching the given regex
1184 j - leave this hunk undecided, see next undecided hunk
1185 J - leave this hunk undecided, see next hunk
1186 k - leave this hunk undecided, see previous undecided hunk
1187 K - leave this hunk undecided, see previous hunk
1188 s - split the current hunk into smaller hunks
1189 e - manually edit the current hunk
1196 my $ret = run_git_apply $cmd, @_;
1203 sub apply_patch_for_checkout_commit {
1204 my $reverse = shift;
1205 my $applies_index = run_git_apply 'apply '.$reverse.' --cached --check', @_;
1206 my $applies_worktree = run_git_apply 'apply '.$reverse.' --check', @_;
1208 if ($applies_worktree && $applies_index) {
1209 run_git_apply 'apply '.$reverse.' --cached', @_;
1210 run_git_apply 'apply '.$reverse, @_;
1212 } elsif (!$applies_index) {
1213 print colored $error_color, "The selected hunks do not apply to the index!\n";
1214 if (prompt_yesno "Apply them to the worktree anyway? ") {
1215 return run_git_apply 'apply '.$reverse, @_;
1217 print colored $error_color, "Nothing was applied.\n";
1226 sub patch_update_cmd {
1227 my @all_mods = list_modified($patch_mode_flavour{FILTER});
1228 error_msg "ignoring unmerged: $_->{VALUE}\n"
1229 for grep { $_->{UNMERGED} } @all_mods;
1230 @all_mods = grep { !$_->{UNMERGED} } @all_mods;
1232 my @mods = grep { !($_->{BINARY}) } @all_mods;
1237 print STDERR "Only binary files changed.\n";
1239 print STDERR "No changes.\n";
1247 @them = list_and_choose({ PROMPT => 'Patch update',
1248 HEADER => $status_head, },
1252 return 0 if patch_update_file($_->{VALUE});
1256 # Generate a one line summary of a hunk.
1257 sub summarize_hunk {
1259 my $summary = $rhunk->{TEXT}[0];
1261 # Keep the line numbers, discard extra context.
1262 $summary =~ s/@@(.*?)@@.*/$1 /s;
1263 $summary .= " " x (20 - length $summary);
1265 # Add some user context.
1266 for my $line (@{$rhunk->{TEXT}}) {
1267 if ($line =~ m/^[+-].*\w/) {
1274 return substr($summary, 0, 80) . "\n";
1278 # Print a one-line summary of each hunk in the array ref in
1279 # the first argument, starting with the index in the 2nd.
1281 my ($hunks, $i) = @_;
1284 for (; $i < @$hunks && $ctr < 20; $i++, $ctr++) {
1286 if (defined $hunks->[$i]{USE}) {
1287 $status = $hunks->[$i]{USE} ? "+" : "-";
1292 summarize_hunk($hunks->[$i]);
1297 sub patch_update_file {
1301 my ($head, @hunk) = parse_diff($path);
1302 ($head, my $mode, my $deletion) = parse_diff_header($head);
1303 for (@{$head->{DISPLAY}}) {
1307 if (@{$mode->{TEXT}}) {
1308 unshift @hunk, $mode;
1310 if (@{$deletion->{TEXT}}) {
1311 foreach my $hunk (@hunk) {
1312 push @{$deletion->{TEXT}}, @{$hunk->{TEXT}};
1313 push @{$deletion->{DISPLAY}}, @{$hunk->{DISPLAY}};
1315 @hunk = ($deletion);
1318 $num = scalar @hunk;
1322 my ($prev, $next, $other, $undecided, $i);
1328 for ($i = 0; $i < $ix; $i++) {
1329 if (!defined $hunk[$i]{USE}) {
1338 for ($i = $ix + 1; $i < $num; $i++) {
1339 if (!defined $hunk[$i]{USE}) {
1345 if ($ix < $num - 1) {
1351 for ($i = 0; $i < $num; $i++) {
1352 if (!defined $hunk[$i]{USE}) {
1357 last if (!$undecided);
1359 if ($hunk[$ix]{TYPE} eq 'hunk' &&
1360 hunk_splittable($hunk[$ix]{TEXT})) {
1363 if ($hunk[$ix]{TYPE} eq 'hunk') {
1366 for (@{$hunk[$ix]{DISPLAY}}) {
1369 print colored $prompt_color, $patch_mode_flavour{VERB},
1370 ($hunk[$ix]{TYPE} eq 'mode' ? ' mode change' :
1371 $hunk[$ix]{TYPE} eq 'deletion' ? ' deletion' :
1373 $patch_mode_flavour{TARGET},
1374 " [y,n,q,a,d,/$other,?]? ";
1375 my $line = prompt_single_character;
1376 last unless defined $line;
1378 if ($line =~ /^y/i) {
1379 $hunk[$ix]{USE} = 1;
1381 elsif ($line =~ /^n/i) {
1382 $hunk[$ix]{USE} = 0;
1384 elsif ($line =~ /^a/i) {
1385 while ($ix < $num) {
1386 if (!defined $hunk[$ix]{USE}) {
1387 $hunk[$ix]{USE} = 1;
1393 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1395 my $no = $ix > 10 ? $ix - 10 : 0;
1396 while ($response eq '') {
1398 $no = display_hunks(\@hunk, $no);
1400 $extra = " (<ret> to see more)";
1402 print "go to which hunk$extra? ";
1403 $response = <STDIN>;
1404 if (!defined $response) {
1409 if ($response !~ /^\s*\d+\s*$/) {
1410 error_msg "Invalid number: '$response'\n";
1411 } elsif (0 < $response && $response <= $num) {
1412 $ix = $response - 1;
1414 error_msg "Sorry, only $num hunks available.\n";
1418 elsif ($line =~ /^d/i) {
1419 while ($ix < $num) {
1420 if (!defined $hunk[$ix]{USE}) {
1421 $hunk[$ix]{USE} = 0;
1427 elsif ($line =~ /^q/i) {
1428 for ($i = 0; $i < $num; $i++) {
1429 if (!defined $hunk[$i]{USE}) {
1436 elsif ($line =~ m|^/(.*)|) {
1439 print colored $prompt_color, "search for regex? ";
1441 if (defined $regex) {
1447 $search_string = qr{$regex}m;
1450 my ($err,$exp) = ($@, $1);
1451 $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1452 error_msg "Malformed search regexp $exp: $err\n";
1457 my $text = join ("", @{$hunk[$iy]{TEXT}});
1458 last if ($text =~ $search_string);
1460 $iy = 0 if ($iy >= $num);
1462 error_msg "No hunk matches the given pattern\n";
1469 elsif ($line =~ /^K/) {
1470 if ($other =~ /K/) {
1474 error_msg "No previous hunk\n";
1478 elsif ($line =~ /^J/) {
1479 if ($other =~ /J/) {
1483 error_msg "No next hunk\n";
1487 elsif ($line =~ /^k/) {
1488 if ($other =~ /k/) {
1492 !defined $hunk[$ix]{USE});
1496 error_msg "No previous hunk\n";
1500 elsif ($line =~ /^j/) {
1501 if ($other !~ /j/) {
1502 error_msg "No next hunk\n";
1506 elsif ($other =~ /s/ && $line =~ /^s/) {
1507 my @split = split_hunk($hunk[$ix]{TEXT}, $hunk[$ix]{DISPLAY});
1509 print colored $header_color, "Split into ",
1510 scalar(@split), " hunks.\n";
1512 splice (@hunk, $ix, 1, @split);
1513 $num = scalar @hunk;
1516 elsif ($other =~ /e/ && $line =~ /^e/) {
1517 my $newhunk = edit_hunk_loop($head, \@hunk, $ix);
1518 if (defined $newhunk) {
1519 splice @hunk, $ix, 1, $newhunk;
1523 help_patch_cmd($other);
1529 last if ($ix >= $num ||
1530 !defined $hunk[$ix]{USE});
1535 @hunk = coalesce_overlapping_hunks(@hunk);
1541 push @result, @{$_->{TEXT}};
1546 my @patch = reassemble_patch($head->{TEXT}, @result);
1547 my $apply_routine = $patch_mode_flavour{APPLY};
1548 &$apply_routine(@patch);
1557 my @mods = list_modified('index-only');
1558 @mods = grep { !($_->{BINARY}) } @mods;
1560 my (@them) = list_and_choose({ PROMPT => 'Review diff',
1562 HEADER => $status_head, },
1565 my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
1566 system(qw(git diff -p --cached), $reference, '--',
1567 map { $_->{VALUE} } @them);
1576 print colored $help_color, <<\EOF ;
1577 status - show paths with changes
1578 update - add working tree state to the staged set of changes
1579 revert - revert staged set of changes back to the HEAD version
1580 patch - pick hunks and update selectively
1581 diff - view diff between HEAD and index
1582 add untracked - add contents of untracked files to the staged set of changes
1587 return unless @ARGV;
1588 my $arg = shift @ARGV;
1589 if ($arg =~ /--patch(?:=(.*))?/) {
1591 if ($1 eq 'reset') {
1592 $patch_mode = 'reset_head';
1593 $patch_mode_revision = 'HEAD';
1594 $arg = shift @ARGV or die "missing --";
1596 $patch_mode_revision = $arg;
1597 $patch_mode = ($arg eq 'HEAD' ?
1598 'reset_head' : 'reset_nothead');
1599 $arg = shift @ARGV or die "missing --";
1601 } elsif ($1 eq 'checkout') {
1602 $arg = shift @ARGV or die "missing --";
1604 $patch_mode = 'checkout_index';
1606 $patch_mode_revision = $arg;
1607 $patch_mode = ($arg eq 'HEAD' ?
1608 'checkout_head' : 'checkout_nothead');
1609 $arg = shift @ARGV or die "missing --";
1611 } elsif ($1 eq 'stage' or $1 eq 'stash') {
1613 $arg = shift @ARGV or die "missing --";
1615 die "unknown --patch mode: $1";
1618 $patch_mode = 'stage';
1619 $arg = shift @ARGV or die "missing --";
1621 die "invalid argument $arg, expecting --"
1622 unless $arg eq "--";
1623 %patch_mode_flavour = %{$patch_modes{$patch_mode}};
1625 elsif ($arg ne "--") {
1626 die "invalid argument $arg, expecting --";
1631 my @cmd = ([ 'status', \&status_cmd, ],
1632 [ 'update', \&update_cmd, ],
1633 [ 'revert', \&revert_cmd, ],
1634 [ 'add untracked', \&add_untracked_cmd, ],
1635 [ 'patch', \&patch_update_cmd, ],
1636 [ 'diff', \&diff_cmd, ],
1637 [ 'quit', \&quit_cmd, ],
1638 [ 'help', \&help_cmd, ],
1641 my ($it) = list_and_choose({ PROMPT => 'What now',
1644 HEADER => '*** Commands ***',
1645 ON_EOF => \&quit_cmd,
1646 IMMEDIATE => 1 }, @cmd);