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");
53 if ($repo->config_bool("interactive.singlekey")) {
55 require Term::ReadKey;
56 Term::ReadKey->import;
61 my $termcap = Term::Cap->Tgetent;
62 foreach (values %$termcap) {
63 $term_escapes{$_} = 1 if /^\e/;
71 my $string = join("", @_);
74 # Put a color code at the beginning of each line, a reset at the end
75 # color after newlines that are not at the end of the string
76 $string =~ s/(\n+)(.)/$1$color$2/g;
77 # reset before newlines
78 $string =~ s/(\n+)/$normal_color$1/g;
79 # codes at beginning and end (if necessary):
80 $string =~ s/^/$color/;
81 $string =~ s/$/$normal_color/ unless $string =~ /\n$/;
86 # command line options
88 my $patch_mode_revision;
89 my @patch_mode_hunk_filter;
90 my $patch_mode_negate_filter;
91 my $patch_mode_autosplit;
94 sub apply_patch_for_checkout_commit;
95 sub apply_patch_for_stash;
101 DIFF => 'diff-files -p',
102 APPLY => sub { apply_patch 'apply --cached', @_; },
103 APPLY_CHECK => 'apply --cached',
106 PARTICIPLE => 'staging',
107 FILTER => 'file-only',
114 DIFF => 'diff-index -p',
115 APPLY => sub { apply_patch 'apply --cached', @_; },
116 APPLY_CHECK => 'apply --cached',
119 PARTICIPLE => 'stashing',
127 DIFF => 'diff-index -p --cached',
128 APPLY => sub { apply_patch 'apply -R --cached', @_; },
129 APPLY_CHECK => 'apply -R --cached',
132 PARTICIPLE => 'unstaging',
133 FILTER => 'index-only',
137 DIFF => 'diff-index -R -p --cached',
138 APPLY => sub { apply_patch 'apply --cached', @_; },
139 APPLY_CHECK => 'apply --cached',
141 TARGET => ' to index',
142 PARTICIPLE => 'applying',
143 FILTER => 'index-only',
150 DIFF => 'diff-files -p',
151 APPLY => sub { apply_patch 'apply -R', @_; },
152 APPLY_CHECK => 'apply -R',
154 TARGET => ' from worktree',
155 PARTICIPLE => 'discarding',
156 FILTER => 'file-only',
160 DIFF => 'diff-index -p',
161 APPLY => sub { apply_patch_for_checkout_commit '-R', @_ },
162 APPLY_CHECK => 'apply -R',
164 TARGET => ' from index and worktree',
165 PARTICIPLE => 'discarding',
170 DIFF => 'diff-index -R -p',
171 APPLY => sub { apply_patch_for_checkout_commit '', @_ },
172 APPLY_CHECK => 'apply',
174 TARGET => ' to index and worktree',
175 PARTICIPLE => 'applying',
182 my %patch_mode_flavour = %{$patch_modes{stage}};
185 if ($^O eq 'MSWin32' || $^O eq 'msys') {
186 my @invalid = grep {m/[":*]/} @_;
187 die "$^O does not support: @invalid\n" if @invalid;
188 my @args = map { m/ /o ? "\"$_\"": $_ } @_;
192 open($fh, '-|', @_) or die;
197 my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));
199 if (!defined $GIT_DIR) {
200 exit(1); # rev-parse would have already said "not a git repo"
217 my ($retval, $remainder);
218 if (!/^\042(.*)\042$/) {
221 ($_, $retval) = ($1, "");
222 while (/^([^\\]*)\\(.*)$/) {
226 if (/^([0-3][0-7][0-7])(.*)$/) {
227 $retval .= chr(oct($1));
231 if (/^([\\\042btnvfr])(.*)$/) {
232 $retval .= $cquote_map{$1};
236 # This is malformed -- just return it as-is for now.
247 open $fh, 'git update-index --refresh |'
250 ;# ignore 'needs update'
260 run_cmd_pipe(qw(git ls-files --others --exclude-standard --), @ARGV);
263 my $status_fmt = '%12s %12s %s';
264 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
268 sub is_initial_commit {
269 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
270 unless defined $initial;
276 return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
279 # Returns list of hashes, contents of each of which are:
281 # BINARY: is a binary path
282 # INDEX: is index different from HEAD?
283 # FILE: is file different from index?
284 # INDEX_ADDDEL: is it add/delete between HEAD and index?
285 # FILE_ADDDEL: is it add/delete between index and file?
290 my ($add, $del, $adddel, $file);
297 } run_cmd_pipe(qw(git ls-files --), @ARGV);
298 return if (!@tracked);
302 if (defined $patch_mode_revision and $patch_mode_revision ne 'HEAD') {
303 $reference = $patch_mode_revision;
304 } elsif (is_initial_commit()) {
305 $reference = get_empty_tree();
309 for (run_cmd_pipe(qw(git diff-index --cached
310 --numstat --summary), $reference,
312 if (($add, $del, $file) =
313 /^([-\d]+) ([-\d]+) (.*)/) {
315 $file = unquote_path($file);
316 if ($add eq '-' && $del eq '-') {
321 $change = "+$add/-$del";
329 elsif (($adddel, $file) =
330 /^ (create|delete) mode [0-7]+ (.*)$/) {
331 $file = unquote_path($file);
332 $data{$file}{INDEX_ADDDEL} = $adddel;
336 for (run_cmd_pipe(qw(git diff-files --numstat --summary --), @tracked)) {
337 if (($add, $del, $file) =
338 /^([-\d]+) ([-\d]+) (.*)/) {
339 $file = unquote_path($file);
340 if (!exists $data{$file}) {
342 INDEX => 'unchanged',
347 if ($add eq '-' && $del eq '-') {
352 $change = "+$add/-$del";
354 $data{$file}{FILE} = $change;
356 $data{$file}{BINARY} = 1;
359 elsif (($adddel, $file) =
360 /^ (create|delete) mode [0-7]+ (.*)$/) {
361 $file = unquote_path($file);
362 $data{$file}{FILE_ADDDEL} = $adddel;
366 for (sort keys %data) {
370 if ($only eq 'index-only') {
371 next if ($it->{INDEX} eq 'unchanged');
373 if ($only eq 'file-only') {
374 next if ($it->{FILE} eq 'nothing');
386 my ($string, @stuff) = @_;
388 for (my $i = 0; $i < @stuff; $i++) {
392 if ((ref $it) eq 'ARRAY') {
400 if ($it =~ /^$string/) {
404 if (defined $hit && defined $found) {
414 # inserts string into trie and updates count for each character
416 my ($trie, $string) = @_;
417 foreach (split //, $string) {
418 $trie = $trie->{$_} ||= {COUNT => 0};
423 # returns an array of tuples (prefix, remainder)
424 sub find_unique_prefixes {
428 # any single prefix exceeding the soft limit is omitted
429 # if any prefix exceeds the hard limit all are omitted
430 # 0 indicates no limit
434 # build a trie modelling all possible options
436 foreach my $print (@stuff) {
437 if ((ref $print) eq 'ARRAY') {
438 $print = $print->[0];
440 elsif ((ref $print) eq 'HASH') {
441 $print = $print->{VALUE};
443 update_trie(\%trie, $print);
444 push @return, $print;
447 # use the trie to find the unique prefixes
448 for (my $i = 0; $i < @return; $i++) {
449 my $ret = $return[$i];
450 my @letters = split //, $ret;
452 my ($prefix, $remainder);
454 for ($j = 0; $j < @letters; $j++) {
455 my $letter = $letters[$j];
456 if ($search{$letter}{COUNT} == 1) {
457 $prefix = substr $ret, 0, $j + 1;
458 $remainder = substr $ret, $j + 1;
462 my $prefix = substr $ret, 0, $j;
464 if ($hard_limit && $j + 1 > $hard_limit);
466 %search = %{$search{$letter}};
468 if (ord($letters[0]) > 127 ||
469 ($soft_limit && $j + 1 > $soft_limit)) {
473 $return[$i] = [$prefix, $remainder];
478 # filters out prefixes which have special meaning to list_and_choose()
479 sub is_valid_prefix {
481 return (defined $prefix) &&
482 !($prefix =~ /[\s,]/) && # separators
483 !($prefix =~ /^-/) && # deselection
484 !($prefix =~ /^\d+/) && # selection
485 ($prefix ne '*') && # "all" wildcard
486 ($prefix ne '?'); # prompt help
489 # given a prefix/remainder tuple return a string with the prefix highlighted
490 # for now use square brackets; later might use ANSI colors (underline, bold)
491 sub highlight_prefix {
493 my $remainder = shift;
495 if (!defined $prefix) {
499 if (!is_valid_prefix($prefix)) {
500 return "$prefix$remainder";
503 if (!$menu_use_color) {
504 return "[$prefix]$remainder";
507 return "$prompt_color$prefix$normal_color$remainder";
511 print STDERR colored $error_color, @_;
514 sub list_and_choose {
515 my ($opts, @stuff) = @_;
516 my (@chosen, @return);
518 my @prefixes = find_unique_prefixes(@stuff) unless $opts->{LIST_ONLY};
524 if ($opts->{HEADER}) {
525 if (!$opts->{LIST_FLAT}) {
528 print colored $header_color, "$opts->{HEADER}\n";
530 for ($i = 0; $i < @stuff; $i++) {
531 my $chosen = $chosen[$i] ? '*' : ' ';
532 my $print = $stuff[$i];
533 my $ref = ref $print;
534 my $highlighted = highlight_prefix(@{$prefixes[$i]})
536 if ($ref eq 'ARRAY') {
537 $print = $highlighted || $print->[0];
539 elsif ($ref eq 'HASH') {
540 my $value = $highlighted || $print->{VALUE};
541 $print = sprintf($status_fmt,
547 $print = $highlighted || $print;
549 printf("%s%2d: %s", $chosen, $i+1, $print);
550 if (($opts->{LIST_FLAT}) &&
551 (($i + 1) % ($opts->{LIST_FLAT}))) {
564 return if ($opts->{LIST_ONLY});
566 print colored $prompt_color, $opts->{PROMPT};
567 if ($opts->{SINGLETON}) {
576 $opts->{ON_EOF}->() if $opts->{ON_EOF};
583 singleton_prompt_help_cmd() :
587 for my $choice (split(/[\s,]+/, $line)) {
591 # Input that begins with '-'; unchoose
592 if ($choice =~ s/^-//) {
595 # A range can be specified like 5-7 or 5-.
596 if ($choice =~ /^(\d+)-(\d*)$/) {
597 ($bottom, $top) = ($1, length($2) ? $2 : 1 + @stuff);
599 elsif ($choice =~ /^\d+$/) {
600 $bottom = $top = $choice;
602 elsif ($choice eq '*') {
607 $bottom = $top = find_unique($choice, @stuff);
608 if (!defined $bottom) {
609 error_msg "Huh ($choice)?\n";
613 if ($opts->{SINGLETON} && $bottom != $top) {
614 error_msg "Huh ($choice)?\n";
617 for ($i = $bottom-1; $i <= $top-1; $i++) {
618 next if (@stuff <= $i || $i < 0);
619 $chosen[$i] = $choose;
622 last if ($opts->{IMMEDIATE} || $line eq '*');
624 for ($i = 0; $i < @stuff; $i++) {
626 push @return, $stuff[$i];
632 sub singleton_prompt_help_cmd {
633 print colored $help_color, <<\EOF ;
635 1 - select a numbered item
636 foo - select item based on unique prefix
637 - (empty) select nothing
641 sub prompt_help_cmd {
642 print colored $help_color, <<\EOF ;
644 1 - select a single item
645 3-5 - select a range of items
646 2-3,6-9 - select multiple ranges
647 foo - select item based on unique prefix
648 -... - unselect specified items
650 - (empty) finish selecting
655 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
665 print "$cnt paths\n";
673 my @mods = list_modified('file-only');
676 my @update = list_and_choose({ PROMPT => 'Update',
677 HEADER => $status_head, },
680 system(qw(git update-index --add --remove --),
681 map { $_->{VALUE} } @update);
682 say_n_paths('updated', @update);
688 my @update = list_and_choose({ PROMPT => 'Revert',
689 HEADER => $status_head, },
692 if (is_initial_commit()) {
693 system(qw(git rm --cached),
694 map { $_->{VALUE} } @update);
697 my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
698 map { $_->{VALUE} } @update);
700 open $fh, '| git update-index --index-info'
707 if ($_->{INDEX_ADDDEL} &&
708 $_->{INDEX_ADDDEL} eq 'create') {
709 system(qw(git update-index --force-remove --),
711 print "note: $_->{VALUE} is untracked now.\n";
716 say_n_paths('reverted', @update);
721 sub add_untracked_cmd {
722 my @add = list_and_choose({ PROMPT => 'Add untracked' },
725 system(qw(git update-index --add --), @add);
726 say_n_paths('added', @add);
734 open $fh, '| git ' . $cmd . " --recount --allow-overlap";
741 my @diff_cmd = split(" ", $patch_mode_flavour{DIFF});
742 if (defined $patch_mode_revision) {
743 push @diff_cmd, $patch_mode_revision;
745 my @diff = run_cmd_pipe("git", @diff_cmd, "--", $path);
747 if ($diff_use_color) {
748 @colored = run_cmd_pipe("git", @diff_cmd, qw(--color --), $path);
750 my (@hunk) = { TEXT => [], DISPLAY => [], TYPE => 'header' };
752 for (my $i = 0; $i < @diff; $i++) {
753 if ($diff[$i] =~ /^@@ /) {
754 push @hunk, { TEXT => [], DISPLAY => [],
757 push @{$hunk[-1]{TEXT}}, $diff[$i];
758 push @{$hunk[-1]{DISPLAY}},
759 ($diff_use_color ? $colored[$i] : $diff[$i]);
764 sub parse_diff_header {
767 my $head = { TEXT => [], DISPLAY => [], TYPE => 'header' };
768 my $mode = { TEXT => [], DISPLAY => [], TYPE => 'mode' };
769 my $deletion = { TEXT => [], DISPLAY => [], TYPE => 'deletion' };
771 for (my $i = 0; $i < @{$src->{TEXT}}; $i++) {
773 $src->{TEXT}->[$i] =~ /^(old|new) mode (\d+)$/ ? $mode :
774 $src->{TEXT}->[$i] =~ /^deleted file/ ? $deletion :
776 push @{$dest->{TEXT}}, $src->{TEXT}->[$i];
777 push @{$dest->{DISPLAY}}, $src->{DISPLAY}->[$i];
779 return ($head, $mode, $deletion);
782 sub hunk_splittable {
785 my @s = split_hunk($text);
789 sub parse_hunk_header {
791 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
792 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
793 $o_cnt = 1 unless defined $o_cnt;
794 $n_cnt = 1 unless defined $n_cnt;
795 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
799 my ($text, $display) = @_;
801 if (!defined $display) {
804 # If there are context lines in the middle of a hunk,
805 # it can be split, but we would need to take care of
808 my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
813 my $next_hunk_start = undef;
814 my $i = $hunk_start - 1;
828 while (++$i < @$text) {
829 my $line = $text->[$i];
830 my $display = $display->[$i];
832 if ($this->{ADDDEL} &&
833 !defined $next_hunk_start) {
834 # We have seen leading context and
835 # adds/dels and then here is another
836 # context, which is trailing for this
837 # split hunk and leading for the next
839 $next_hunk_start = $i;
841 push @{$this->{TEXT}}, $line;
842 push @{$this->{DISPLAY}}, $display;
845 if (defined $next_hunk_start) {
852 if (defined $next_hunk_start) {
853 # We are done with the current hunk and
854 # this is the first real change for the
856 $hunk_start = $next_hunk_start;
857 $o_ofs = $this->{OLD} + $this->{OCNT};
858 $n_ofs = $this->{NEW} + $this->{NCNT};
859 $o_ofs -= $this->{POSTCTX};
860 $n_ofs -= $this->{POSTCTX};
864 push @{$this->{TEXT}}, $line;
865 push @{$this->{DISPLAY}}, $display;
879 for my $hunk (@split) {
880 $o_ofs = $hunk->{OLD};
881 $n_ofs = $hunk->{NEW};
882 my $o_cnt = $hunk->{OCNT};
883 my $n_cnt = $hunk->{NCNT};
885 my $head = ("@@ -$o_ofs" .
886 (($o_cnt != 1) ? ",$o_cnt" : '') .
888 (($n_cnt != 1) ? ",$n_cnt" : '') .
890 my $display_head = $head;
891 unshift @{$hunk->{TEXT}}, $head;
892 if ($diff_use_color) {
893 $display_head = colored($fraginfo_color, $head);
895 unshift @{$hunk->{DISPLAY}}, $display_head;
900 sub find_last_o_ctx {
902 my $text = $it->{TEXT};
903 my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
905 my $last_o_ctx = $o_ofs + $o_cnt;
907 my $line = $text->[$i];
918 my ($prev, $this) = @_;
919 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
920 parse_hunk_header($prev->{TEXT}[0]);
921 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
922 parse_hunk_header($this->{TEXT}[0]);
924 my (@line, $i, $ofs, $o_cnt, $n_cnt);
927 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
928 my $line = $prev->{TEXT}[$i];
929 if ($line =~ /^\+/) {
935 last if ($o1_ofs <= $ofs);
945 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
946 my $line = $this->{TEXT}[$i];
947 if ($line =~ /^\+/) {
959 my $head = ("@@ -$o0_ofs" .
960 (($o_cnt != 1) ? ",$o_cnt" : '') .
962 (($n_cnt != 1) ? ",$n_cnt" : '') .
964 @{$prev->{TEXT}} = ($head, @line);
967 sub coalesce_overlapping_hunks {
971 my ($last_o_ctx, $last_was_dirty);
973 for (grep { $_->{USE} } @in) {
974 if ($_->{TYPE} ne 'hunk') {
978 my $text = $_->{TEXT};
979 my ($o_ofs) = parse_hunk_header($text->[0]);
980 if (defined $last_o_ctx &&
981 $o_ofs <= $last_o_ctx &&
984 merge_hunk($out[-1], $_);
989 $last_o_ctx = find_last_o_ctx($out[-1]);
990 $last_was_dirty = $_->{DIRTY};
995 sub reassemble_patch {
999 # Include everything in the header except the beginning of the diff.
1000 push @patch, (grep { !/^[-+]{3}/ } @$head);
1002 # Then include any headers from the hunk lines, which must
1003 # come before any actual hunk.
1004 while (@_ && $_[0] !~ /^@/) {
1008 # Then begin the diff.
1009 push @patch, grep { /^[-+]{3}/ } @$head;
1011 # And then the actual hunks.
1019 colored((/^@/ ? $fraginfo_color :
1020 /^\+/ ? $diff_new_color :
1021 /^-/ ? $diff_old_color :
1027 sub edit_hunk_manually {
1030 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
1032 open $fh, '>', $hunkfile
1033 or die "failed to open hunk edit file for writing: " . $!;
1034 print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
1035 print $fh @$oldtext;
1036 my $participle = $patch_mode_flavour{PARTICIPLE};
1037 my $is_reverse = $patch_mode_flavour{IS_REVERSE};
1038 my ($remove_plus, $remove_minus) = $is_reverse ? ('-', '+') : ('+', '-');
1041 # To remove '$remove_minus' lines, make them ' ' lines (context).
1042 # To remove '$remove_plus' lines, delete them.
1043 # Lines starting with # will be removed.
1045 # If the patch applies cleanly, the edited hunk will immediately be
1046 # marked for $participle. If it does not apply cleanly, you will be given
1047 # an opportunity to edit again. If all lines of the hunk are removed,
1048 # then the edit is aborted and the hunk is left unchanged.
1052 chomp(my $editor = run_cmd_pipe(qw(git var GIT_EDITOR)));
1053 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
1059 open $fh, '<', $hunkfile
1060 or die "failed to open hunk edit file for reading: " . $!;
1061 my @newtext = grep { !/^#/ } <$fh>;
1065 # Abort if nothing remains
1066 if (!grep { /\S/ } @newtext) {
1070 # Reinsert the first hunk header if the user accidentally deleted it
1071 if ($newtext[0] !~ /^@/) {
1072 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 nor any of the remaining ones
1160 a - $verb this hunk and all later hunks in the file
1161 d - do not $verb this hunk nor 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 my @mods = grep { !($_->{BINARY}) } @all_mods;
1213 print STDERR "Only binary files changed.\n";
1215 print STDERR "No changes.\n";
1223 @them = list_and_choose({ PROMPT => 'Patch update',
1224 HEADER => $status_head, },
1228 return 0 if patch_update_file($_->{VALUE});
1232 # Generate a one line summary of a hunk.
1233 sub summarize_hunk {
1235 my $summary = $rhunk->{TEXT}[0];
1237 # Keep the line numbers, discard extra context.
1238 $summary =~ s/@@(.*?)@@.*/$1 /s;
1239 $summary .= " " x (20 - length $summary);
1241 # Add some user context.
1242 for my $line (@{$rhunk->{TEXT}}) {
1243 if ($line =~ m/^[+-].*\w/) {
1250 return substr($summary, 0, 80) . "\n";
1254 # Print a one-line summary of each hunk in the array ref in
1255 # the first argument, starting wih the index in the 2nd.
1257 my ($hunks, $i) = @_;
1260 for (; $i < @$hunks && $ctr < 20; $i++, $ctr++) {
1262 if (defined $hunks->[$i]{USE}) {
1263 $status = $hunks->[$i]{USE} ? "+" : "-";
1268 summarize_hunk($hunks->[$i]);
1275 s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1281 my $text = join('', @{$hunk->{TEXT}});
1283 foreach my $re (@patch_mode_hunk_filter) {
1284 return !$patch_mode_negate_filter if $text =~ $re;
1286 return $patch_mode_negate_filter;
1289 sub patch_update_file {
1293 my ($head, @hunk) = parse_diff($path);
1295 if ($patch_mode_autosplit) {
1296 @hunk = map { split_hunk($_->{TEXT}, $_->{DISPLAY}) } @hunk;
1299 if (@patch_mode_hunk_filter) {
1300 @hunk = grep { want_hunk($_) } @hunk;
1301 return unless @hunk;
1304 ($head, my $mode, my $deletion) = parse_diff_header($head);
1305 for (@{$head->{DISPLAY}}) {
1309 if (@{$mode->{TEXT}} && !@patch_mode_hunk_filter) {
1310 unshift @hunk, $mode;
1312 if (@{$deletion->{TEXT}}) {
1313 foreach my $hunk (@hunk) {
1314 push @{$deletion->{TEXT}}, @{$hunk->{TEXT}};
1315 push @{$deletion->{DISPLAY}}, @{$hunk->{DISPLAY}};
1317 @hunk = ($deletion);
1320 $num = scalar @hunk;
1324 my ($prev, $next, $other, $undecided, $i);
1330 for ($i = 0; $i < $ix; $i++) {
1331 if (!defined $hunk[$i]{USE}) {
1340 for ($i = $ix + 1; $i < $num; $i++) {
1341 if (!defined $hunk[$i]{USE}) {
1347 if ($ix < $num - 1) {
1353 for ($i = 0; $i < $num; $i++) {
1354 if (!defined $hunk[$i]{USE}) {
1359 last if (!$undecided);
1361 if ($hunk[$ix]{TYPE} eq 'hunk' &&
1362 hunk_splittable($hunk[$ix]{TEXT})) {
1365 if ($hunk[$ix]{TYPE} eq 'hunk') {
1368 for (@{$hunk[$ix]{DISPLAY}}) {
1371 print colored $prompt_color, $patch_mode_flavour{VERB},
1372 ($hunk[$ix]{TYPE} eq 'mode' ? ' mode change' :
1373 $hunk[$ix]{TYPE} eq 'deletion' ? ' deletion' :
1375 $patch_mode_flavour{TARGET},
1376 " [y,n,q,a,d,/$other,?]? ";
1377 my $line = prompt_single_character;
1379 if ($line =~ /^y/i) {
1380 $hunk[$ix]{USE} = 1;
1382 elsif ($line =~ /^n/i) {
1383 $hunk[$ix]{USE} = 0;
1385 elsif ($line =~ /^a/i) {
1386 while ($ix < $num) {
1387 if (!defined $hunk[$ix]{USE}) {
1388 $hunk[$ix]{USE} = 1;
1394 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1396 my $no = $ix > 10 ? $ix - 10 : 0;
1397 while ($response eq '') {
1399 $no = display_hunks(\@hunk, $no);
1401 $extra = " (<ret> to see more)";
1403 print "go to which hunk$extra? ";
1404 $response = <STDIN>;
1405 if (!defined $response) {
1410 if ($response !~ /^\s*\d+\s*$/) {
1411 error_msg "Invalid number: '$response'\n";
1412 } elsif (0 < $response && $response <= $num) {
1413 $ix = $response - 1;
1415 error_msg "Sorry, only $num hunks available.\n";
1419 elsif ($line =~ /^d/i) {
1420 while ($ix < $num) {
1421 if (!defined $hunk[$ix]{USE}) {
1422 $hunk[$ix]{USE} = 0;
1428 elsif ($line =~ /^q/i) {
1429 for ($i = 0; $i < $num; $i++) {
1430 if (!defined $hunk[$i]{USE}) {
1437 elsif ($line =~ m|^/(.*)|) {
1440 print colored $prompt_color, "search for regex? ";
1442 if (defined $regex) {
1448 $search_string = qr{$regex}m;
1452 error_msg "Malformed search regexp $exp: " . trim_error($@) . "\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}};
1547 my @patch = reassemble_patch($head->{TEXT}, @result);
1548 my $apply_routine = $patch_mode_flavour{APPLY};
1549 &$apply_routine(@patch);
1558 my @mods = list_modified('index-only');
1559 @mods = grep { !($_->{BINARY}) } @mods;
1561 my (@them) = list_and_choose({ PROMPT => 'Review diff',
1563 HEADER => $status_head, },
1566 my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
1567 system(qw(git diff -p --cached), $reference, '--',
1568 map { $_->{VALUE} } @them);
1577 print colored $help_color, <<\EOF ;
1578 status - show paths with changes
1579 update - add working tree state to the staged set of changes
1580 revert - revert staged set of changes back to the HEAD version
1581 patch - pick hunks and update selectively
1582 diff - view diff between HEAD and index
1583 add untracked - add contents of untracked files to the staged set of changes
1588 return unless @ARGV;
1591 if ($ARGV[0] =~ /--patch(?:=(.*))?/) {
1592 $patch_mode = defined $1 ? $1 : 'stage';
1594 elsif ($ARGV[0] =~ /--hunk-filter=(.*)/) {
1595 my $re = eval { qr{$1}m }
1596 or die "malformed hunk filter $1: " . trim_error($@);
1597 push @patch_mode_hunk_filter, $re;
1599 elsif ($ARGV[0] eq '--negate-hunk-filter') {
1600 $patch_mode_negate_filter = 1;
1602 elsif ($ARGV[0] eq '--split-hunks') {
1603 $patch_mode_autosplit = 1;
1611 if (@ARGV && $ARGV[0] ne '--') {
1612 $patch_mode_revision = shift @ARGV;
1614 @ARGV or die "missing --";
1617 if (defined $patch_mode) {
1618 my $mode = $patch_modes{$patch_mode}
1619 or die "unknown --patch mode: $patch_mode";
1622 if (!defined $patch_mode_revision) {
1623 $submode = $mode->{default};
1624 if ($submode eq 'head') {
1625 $patch_mode_revision = 'HEAD';
1628 elsif ($patch_mode_revision eq 'HEAD') {
1632 $submode = 'nothead';
1635 if (!exists $mode->{$submode}) {
1636 die "mode '$patch_mode' cannot handle '$submode'";
1638 %patch_mode_flavour = %{$mode->{$submode}};
1643 my @cmd = ([ 'status', \&status_cmd, ],
1644 [ 'update', \&update_cmd, ],
1645 [ 'revert', \&revert_cmd, ],
1646 [ 'add untracked', \&add_untracked_cmd, ],
1647 [ 'patch', \&patch_update_cmd, ],
1648 [ 'diff', \&diff_cmd, ],
1649 [ 'quit', \&quit_cmd, ],
1650 [ 'help', \&help_cmd, ],
1653 my ($it) = list_and_choose({ PROMPT => 'What now',
1656 HEADER => '*** Commands ***',
1657 ON_EOF => \&quit_cmd,
1658 IMMEDIATE => 1 }, @cmd);