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;
62 print STDERR "missing Term::ReadKey, disabling interactive.singlekey\n";
66 my $termcap = Term::Cap->Tgetent;
67 foreach (values %$termcap) {
68 $term_escapes{$_} = 1 if /^\e/;
76 my $string = join("", @_);
79 # Put a color code at the beginning of each line, a reset at the end
80 # color after newlines that are not at the end of the string
81 $string =~ s/(\n+)(.)/$1$color$2/g;
82 # reset before newlines
83 $string =~ s/(\n+)/$normal_color$1/g;
84 # codes at beginning and end (if necessary):
85 $string =~ s/^/$color/;
86 $string =~ s/$/$normal_color/ unless $string =~ /\n$/;
91 # command line options
93 my $patch_mode_revision;
96 sub apply_patch_for_checkout_commit;
97 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',
111 DIFF => 'diff-index -p HEAD',
112 APPLY => sub { apply_patch 'apply --cached', @_; },
113 APPLY_CHECK => 'apply --cached',
116 PARTICIPLE => 'stashing',
121 DIFF => 'diff-index -p --cached',
122 APPLY => sub { apply_patch 'apply -R --cached', @_; },
123 APPLY_CHECK => 'apply -R --cached',
126 PARTICIPLE => 'unstaging',
127 FILTER => 'index-only',
131 DIFF => 'diff-index -R -p --cached',
132 APPLY => sub { apply_patch 'apply --cached', @_; },
133 APPLY_CHECK => 'apply --cached',
135 TARGET => ' to index',
136 PARTICIPLE => 'applying',
137 FILTER => 'index-only',
140 'checkout_index' => {
141 DIFF => 'diff-files -p',
142 APPLY => sub { apply_patch 'apply -R', @_; },
143 APPLY_CHECK => 'apply -R',
145 TARGET => ' from worktree',
146 PARTICIPLE => 'discarding',
147 FILTER => 'file-only',
151 DIFF => 'diff-index -p',
152 APPLY => sub { apply_patch_for_checkout_commit '-R', @_ },
153 APPLY_CHECK => 'apply -R',
155 TARGET => ' from index and worktree',
156 PARTICIPLE => 'discarding',
160 'checkout_nothead' => {
161 DIFF => 'diff-index -R -p',
162 APPLY => sub { apply_patch_for_checkout_commit '', @_ },
163 APPLY_CHECK => 'apply',
165 TARGET => ' to index and worktree',
166 PARTICIPLE => 'applying',
172 my %patch_mode_flavour = %{$patch_modes{stage}};
175 if ($^O eq 'MSWin32') {
176 my @invalid = grep {m/[":*]/} @_;
177 die "$^O does not support: @invalid\n" if @invalid;
178 my @args = map { m/ /o ? "\"$_\"": $_ } @_;
182 open($fh, '-|', @_) or die;
187 my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));
189 if (!defined $GIT_DIR) {
190 exit(1); # rev-parse would have already said "not a git repo"
207 my ($retval, $remainder);
208 if (!/^\042(.*)\042$/) {
211 ($_, $retval) = ($1, "");
212 while (/^([^\\]*)\\(.*)$/) {
216 if (/^([0-3][0-7][0-7])(.*)$/) {
217 $retval .= chr(oct($1));
221 if (/^([\\\042btnvfr])(.*)$/) {
222 $retval .= $cquote_map{$1};
226 # This is malformed -- just return it as-is for now.
237 open $fh, 'git update-index --refresh |'
240 ;# ignore 'needs update'
250 run_cmd_pipe(qw(git ls-files --others --exclude-standard --), @ARGV);
253 my $status_fmt = '%12s %12s %s';
254 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
258 sub is_initial_commit {
259 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
260 unless defined $initial;
266 return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
269 sub get_diff_reference {
271 if (defined $ref and $ref ne 'HEAD') {
273 } elsif (is_initial_commit()) {
274 return get_empty_tree();
280 # Returns list of hashes, contents of each of which are:
282 # BINARY: is a binary path
283 # INDEX: is index different from HEAD?
284 # FILE: is file different from index?
285 # INDEX_ADDDEL: is it add/delete between HEAD and index?
286 # FILE_ADDDEL: is it add/delete between index and file?
287 # UNMERGED: is the path unmerged
292 my ($add, $del, $adddel, $file);
299 } run_cmd_pipe(qw(git ls-files --), @ARGV);
300 return if (!@tracked);
303 my $reference = get_diff_reference($patch_mode_revision);
304 for (run_cmd_pipe(qw(git diff-index --cached
305 --numstat --summary), $reference,
307 if (($add, $del, $file) =
308 /^([-\d]+) ([-\d]+) (.*)/) {
310 $file = unquote_path($file);
311 if ($add eq '-' && $del eq '-') {
316 $change = "+$add/-$del";
324 elsif (($adddel, $file) =
325 /^ (create|delete) mode [0-7]+ (.*)$/) {
326 $file = unquote_path($file);
327 $data{$file}{INDEX_ADDDEL} = $adddel;
331 for (run_cmd_pipe(qw(git diff-files --numstat --summary --raw --), @tracked)) {
332 if (($add, $del, $file) =
333 /^([-\d]+) ([-\d]+) (.*)/) {
334 $file = unquote_path($file);
336 if ($add eq '-' && $del eq '-') {
341 $change = "+$add/-$del";
343 $data{$file}{FILE} = $change;
345 $data{$file}{BINARY} = 1;
348 elsif (($adddel, $file) =
349 /^ (create|delete) mode [0-7]+ (.*)$/) {
350 $file = unquote_path($file);
351 $data{$file}{FILE_ADDDEL} = $adddel;
353 elsif (/^:[0-7]+ [0-7]+ [0-9a-f]+ [0-9a-f]+ (.) (.*)$/) {
354 $file = unquote_path($2);
355 if (!exists $data{$file}) {
357 INDEX => 'unchanged',
362 $data{$file}{UNMERGED} = 1;
367 for (sort keys %data) {
371 if ($only eq 'index-only') {
372 next if ($it->{INDEX} eq 'unchanged');
374 if ($only eq 'file-only') {
375 next if ($it->{FILE} eq 'nothing');
387 my ($string, @stuff) = @_;
389 for (my $i = 0; $i < @stuff; $i++) {
393 if ((ref $it) eq 'ARRAY') {
401 if ($it =~ /^$string/) {
405 if (defined $hit && defined $found) {
415 # inserts string into trie and updates count for each character
417 my ($trie, $string) = @_;
418 foreach (split //, $string) {
419 $trie = $trie->{$_} ||= {COUNT => 0};
424 # returns an array of tuples (prefix, remainder)
425 sub find_unique_prefixes {
429 # any single prefix exceeding the soft limit is omitted
430 # if any prefix exceeds the hard limit all are omitted
431 # 0 indicates no limit
435 # build a trie modelling all possible options
437 foreach my $print (@stuff) {
438 if ((ref $print) eq 'ARRAY') {
439 $print = $print->[0];
441 elsif ((ref $print) eq 'HASH') {
442 $print = $print->{VALUE};
444 update_trie(\%trie, $print);
445 push @return, $print;
448 # use the trie to find the unique prefixes
449 for (my $i = 0; $i < @return; $i++) {
450 my $ret = $return[$i];
451 my @letters = split //, $ret;
453 my ($prefix, $remainder);
455 for ($j = 0; $j < @letters; $j++) {
456 my $letter = $letters[$j];
457 if ($search{$letter}{COUNT} == 1) {
458 $prefix = substr $ret, 0, $j + 1;
459 $remainder = substr $ret, $j + 1;
463 my $prefix = substr $ret, 0, $j;
465 if ($hard_limit && $j + 1 > $hard_limit);
467 %search = %{$search{$letter}};
469 if (ord($letters[0]) > 127 ||
470 ($soft_limit && $j + 1 > $soft_limit)) {
474 $return[$i] = [$prefix, $remainder];
479 # filters out prefixes which have special meaning to list_and_choose()
480 sub is_valid_prefix {
482 return (defined $prefix) &&
483 !($prefix =~ /[\s,]/) && # separators
484 !($prefix =~ /^-/) && # deselection
485 !($prefix =~ /^\d+/) && # selection
486 ($prefix ne '*') && # "all" wildcard
487 ($prefix ne '?'); # prompt help
490 # given a prefix/remainder tuple return a string with the prefix highlighted
491 # for now use square brackets; later might use ANSI colors (underline, bold)
492 sub highlight_prefix {
494 my $remainder = shift;
496 if (!defined $prefix) {
500 if (!is_valid_prefix($prefix)) {
501 return "$prefix$remainder";
504 if (!$menu_use_color) {
505 return "[$prefix]$remainder";
508 return "$prompt_color$prefix$normal_color$remainder";
512 print STDERR colored $error_color, @_;
515 sub list_and_choose {
516 my ($opts, @stuff) = @_;
517 my (@chosen, @return);
522 my @prefixes = find_unique_prefixes(@stuff) unless $opts->{LIST_ONLY};
528 if ($opts->{HEADER}) {
529 if (!$opts->{LIST_FLAT}) {
532 print colored $header_color, "$opts->{HEADER}\n";
534 for ($i = 0; $i < @stuff; $i++) {
535 my $chosen = $chosen[$i] ? '*' : ' ';
536 my $print = $stuff[$i];
537 my $ref = ref $print;
538 my $highlighted = highlight_prefix(@{$prefixes[$i]})
540 if ($ref eq 'ARRAY') {
541 $print = $highlighted || $print->[0];
543 elsif ($ref eq 'HASH') {
544 my $value = $highlighted || $print->{VALUE};
545 $print = sprintf($status_fmt,
551 $print = $highlighted || $print;
553 printf("%s%2d: %s", $chosen, $i+1, $print);
554 if (($opts->{LIST_FLAT}) &&
555 (($i + 1) % ($opts->{LIST_FLAT}))) {
568 return if ($opts->{LIST_ONLY});
570 print colored $prompt_color, $opts->{PROMPT};
571 if ($opts->{SINGLETON}) {
580 $opts->{ON_EOF}->() if $opts->{ON_EOF};
587 singleton_prompt_help_cmd() :
591 for my $choice (split(/[\s,]+/, $line)) {
595 # Input that begins with '-'; unchoose
596 if ($choice =~ s/^-//) {
599 # A range can be specified like 5-7 or 5-.
600 if ($choice =~ /^(\d+)-(\d*)$/) {
601 ($bottom, $top) = ($1, length($2) ? $2 : 1 + @stuff);
603 elsif ($choice =~ /^\d+$/) {
604 $bottom = $top = $choice;
606 elsif ($choice eq '*') {
611 $bottom = $top = find_unique($choice, @stuff);
612 if (!defined $bottom) {
613 error_msg "Huh ($choice)?\n";
617 if ($opts->{SINGLETON} && $bottom != $top) {
618 error_msg "Huh ($choice)?\n";
621 for ($i = $bottom-1; $i <= $top-1; $i++) {
622 next if (@stuff <= $i || $i < 0);
623 $chosen[$i] = $choose;
626 last if ($opts->{IMMEDIATE} || $line eq '*');
628 for ($i = 0; $i < @stuff; $i++) {
630 push @return, $stuff[$i];
636 sub singleton_prompt_help_cmd {
637 print colored $help_color, <<\EOF ;
639 1 - select a numbered item
640 foo - select item based on unique prefix
641 - (empty) select nothing
645 sub prompt_help_cmd {
646 print colored $help_color, <<\EOF ;
648 1 - select a single item
649 3-5 - select a range of items
650 2-3,6-9 - select multiple ranges
651 foo - select item based on unique prefix
652 -... - unselect specified items
654 - (empty) finish selecting
659 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
669 print "$cnt paths\n";
677 my @mods = list_modified('file-only');
680 my @update = list_and_choose({ PROMPT => 'Update',
681 HEADER => $status_head, },
684 system(qw(git update-index --add --remove --),
685 map { $_->{VALUE} } @update);
686 say_n_paths('updated', @update);
692 my @update = list_and_choose({ PROMPT => 'Revert',
693 HEADER => $status_head, },
696 if (is_initial_commit()) {
697 system(qw(git rm --cached),
698 map { $_->{VALUE} } @update);
701 my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
702 map { $_->{VALUE} } @update);
704 open $fh, '| git update-index --index-info'
711 if ($_->{INDEX_ADDDEL} &&
712 $_->{INDEX_ADDDEL} eq 'create') {
713 system(qw(git update-index --force-remove --),
715 print "note: $_->{VALUE} is untracked now.\n";
720 say_n_paths('reverted', @update);
725 sub add_untracked_cmd {
726 my @add = list_and_choose({ PROMPT => 'Add untracked' },
729 system(qw(git update-index --add --), @add);
730 say_n_paths('added', @add);
732 print "No untracked files.\n";
740 open $fh, '| git ' . $cmd . " --recount --allow-overlap";
747 my @diff_cmd = split(" ", $patch_mode_flavour{DIFF});
748 if (defined $diff_algorithm) {
749 splice @diff_cmd, 1, 0, "--diff-algorithm=${diff_algorithm}";
751 if (defined $patch_mode_revision) {
752 push @diff_cmd, get_diff_reference($patch_mode_revision);
754 my @diff = run_cmd_pipe("git", @diff_cmd, "--", $path);
756 if ($diff_use_color) {
757 @colored = run_cmd_pipe("git", @diff_cmd, qw(--color --), $path);
759 my (@hunk) = { TEXT => [], DISPLAY => [], TYPE => 'header' };
761 for (my $i = 0; $i < @diff; $i++) {
762 if ($diff[$i] =~ /^@@ /) {
763 push @hunk, { TEXT => [], DISPLAY => [],
766 push @{$hunk[-1]{TEXT}}, $diff[$i];
767 push @{$hunk[-1]{DISPLAY}},
768 ($diff_use_color ? $colored[$i] : $diff[$i]);
773 sub parse_diff_header {
776 my $head = { TEXT => [], DISPLAY => [], TYPE => 'header' };
777 my $mode = { TEXT => [], DISPLAY => [], TYPE => 'mode' };
778 my $deletion = { TEXT => [], DISPLAY => [], TYPE => 'deletion' };
780 for (my $i = 0; $i < @{$src->{TEXT}}; $i++) {
782 $src->{TEXT}->[$i] =~ /^(old|new) mode (\d+)$/ ? $mode :
783 $src->{TEXT}->[$i] =~ /^deleted file/ ? $deletion :
785 push @{$dest->{TEXT}}, $src->{TEXT}->[$i];
786 push @{$dest->{DISPLAY}}, $src->{DISPLAY}->[$i];
788 return ($head, $mode, $deletion);
791 sub hunk_splittable {
794 my @s = split_hunk($text);
798 sub parse_hunk_header {
800 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
801 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
802 $o_cnt = 1 unless defined $o_cnt;
803 $n_cnt = 1 unless defined $n_cnt;
804 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
808 my ($text, $display) = @_;
810 if (!defined $display) {
813 # If there are context lines in the middle of a hunk,
814 # it can be split, but we would need to take care of
817 my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
822 my $next_hunk_start = undef;
823 my $i = $hunk_start - 1;
837 while (++$i < @$text) {
838 my $line = $text->[$i];
839 my $display = $display->[$i];
841 if ($this->{ADDDEL} &&
842 !defined $next_hunk_start) {
843 # We have seen leading context and
844 # adds/dels and then here is another
845 # context, which is trailing for this
846 # split hunk and leading for the next
848 $next_hunk_start = $i;
850 push @{$this->{TEXT}}, $line;
851 push @{$this->{DISPLAY}}, $display;
854 if (defined $next_hunk_start) {
861 if (defined $next_hunk_start) {
862 # We are done with the current hunk and
863 # this is the first real change for the
865 $hunk_start = $next_hunk_start;
866 $o_ofs = $this->{OLD} + $this->{OCNT};
867 $n_ofs = $this->{NEW} + $this->{NCNT};
868 $o_ofs -= $this->{POSTCTX};
869 $n_ofs -= $this->{POSTCTX};
873 push @{$this->{TEXT}}, $line;
874 push @{$this->{DISPLAY}}, $display;
888 for my $hunk (@split) {
889 $o_ofs = $hunk->{OLD};
890 $n_ofs = $hunk->{NEW};
891 my $o_cnt = $hunk->{OCNT};
892 my $n_cnt = $hunk->{NCNT};
894 my $head = ("@@ -$o_ofs" .
895 (($o_cnt != 1) ? ",$o_cnt" : '') .
897 (($n_cnt != 1) ? ",$n_cnt" : '') .
899 my $display_head = $head;
900 unshift @{$hunk->{TEXT}}, $head;
901 if ($diff_use_color) {
902 $display_head = colored($fraginfo_color, $head);
904 unshift @{$hunk->{DISPLAY}}, $display_head;
909 sub find_last_o_ctx {
911 my $text = $it->{TEXT};
912 my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
914 my $last_o_ctx = $o_ofs + $o_cnt;
916 my $line = $text->[$i];
927 my ($prev, $this) = @_;
928 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
929 parse_hunk_header($prev->{TEXT}[0]);
930 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
931 parse_hunk_header($this->{TEXT}[0]);
933 my (@line, $i, $ofs, $o_cnt, $n_cnt);
936 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
937 my $line = $prev->{TEXT}[$i];
938 if ($line =~ /^\+/) {
944 last if ($o1_ofs <= $ofs);
954 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
955 my $line = $this->{TEXT}[$i];
956 if ($line =~ /^\+/) {
968 my $head = ("@@ -$o0_ofs" .
969 (($o_cnt != 1) ? ",$o_cnt" : '') .
971 (($n_cnt != 1) ? ",$n_cnt" : '') .
973 @{$prev->{TEXT}} = ($head, @line);
976 sub coalesce_overlapping_hunks {
980 my ($last_o_ctx, $last_was_dirty);
982 for (grep { $_->{USE} } @in) {
983 if ($_->{TYPE} ne 'hunk') {
987 my $text = $_->{TEXT};
988 my ($o_ofs) = parse_hunk_header($text->[0]);
989 if (defined $last_o_ctx &&
990 $o_ofs <= $last_o_ctx &&
993 merge_hunk($out[-1], $_);
998 $last_o_ctx = find_last_o_ctx($out[-1]);
999 $last_was_dirty = $_->{DIRTY};
1004 sub reassemble_patch {
1008 # Include everything in the header except the beginning of the diff.
1009 push @patch, (grep { !/^[-+]{3}/ } @$head);
1011 # Then include any headers from the hunk lines, which must
1012 # come before any actual hunk.
1013 while (@_ && $_[0] !~ /^@/) {
1017 # Then begin the diff.
1018 push @patch, grep { /^[-+]{3}/ } @$head;
1020 # And then the actual hunks.
1028 colored((/^@/ ? $fraginfo_color :
1029 /^\+/ ? $diff_new_color :
1030 /^-/ ? $diff_old_color :
1036 sub edit_hunk_manually {
1039 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
1041 open $fh, '>', $hunkfile
1042 or die "failed to open hunk edit file for writing: " . $!;
1043 print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
1044 print $fh @$oldtext;
1045 my $participle = $patch_mode_flavour{PARTICIPLE};
1046 my $is_reverse = $patch_mode_flavour{IS_REVERSE};
1047 my ($remove_plus, $remove_minus) = $is_reverse ? ('-', '+') : ('+', '-');
1050 # To remove '$remove_minus' lines, make them ' ' lines (context).
1051 # To remove '$remove_plus' lines, delete them.
1052 # Lines starting with # will be removed.
1054 # If the patch applies cleanly, the edited hunk will immediately be
1055 # marked for $participle. If it does not apply cleanly, you will be given
1056 # an opportunity to edit again. If all lines of the hunk are removed,
1057 # then the edit is aborted and the hunk is left unchanged.
1061 chomp(my $editor = run_cmd_pipe(qw(git var GIT_EDITOR)));
1062 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
1068 open $fh, '<', $hunkfile
1069 or die "failed to open hunk edit file for reading: " . $!;
1070 my @newtext = grep { !/^#/ } <$fh>;
1074 # Abort if nothing remains
1075 if (!grep { /\S/ } @newtext) {
1079 # Reinsert the first hunk header if the user accidentally deleted it
1080 if ($newtext[0] !~ /^@/) {
1081 unshift @newtext, $oldtext->[0];
1087 return run_git_apply($patch_mode_flavour{APPLY_CHECK} . ' --check',
1088 map { @{$_->{TEXT}} } @_);
1091 sub _restore_terminal_and_die {
1097 sub prompt_single_character {
1099 local $SIG{TERM} = \&_restore_terminal_and_die;
1100 local $SIG{INT} = \&_restore_terminal_and_die;
1102 my $key = ReadKey 0;
1104 if ($use_termcap and $key eq "\e") {
1105 while (!defined $term_escapes{$key}) {
1106 my $next = ReadKey 0.5;
1107 last if (!defined $next);
1112 print "$key" if defined $key;
1123 print colored $prompt_color, $prompt;
1124 my $line = prompt_single_character;
1125 return 0 if $line =~ /^n/i;
1126 return 1 if $line =~ /^y/i;
1130 sub edit_hunk_loop {
1131 my ($head, $hunk, $ix) = @_;
1132 my $text = $hunk->[$ix]->{TEXT};
1135 $text = edit_hunk_manually($text);
1136 if (!defined $text) {
1141 TYPE => $hunk->[$ix]->{TYPE},
1145 if (diff_applies($head,
1148 @{$hunk}[$ix+1..$#{$hunk}])) {
1149 $newhunk->{DISPLAY} = [color_diff(@{$text})];
1154 'Your edited hunk does not apply. Edit again '
1155 . '(saying "no" discards!) [y/n]? '
1161 sub help_patch_cmd {
1162 my $verb = lc $patch_mode_flavour{VERB};
1163 my $target = $patch_mode_flavour{TARGET};
1164 print colored $help_color, <<EOF ;
1165 y - $verb this hunk$target
1166 n - do not $verb this hunk$target
1167 q - quit; do not $verb this hunk or any of the remaining ones
1168 a - $verb this hunk and all later hunks in the file
1169 d - do not $verb this hunk or any of the later hunks in the file
1170 g - select a hunk to go to
1171 / - search for a hunk matching the given regex
1172 j - leave this hunk undecided, see next undecided hunk
1173 J - leave this hunk undecided, see next hunk
1174 k - leave this hunk undecided, see previous undecided hunk
1175 K - leave this hunk undecided, see previous hunk
1176 s - split the current hunk into smaller hunks
1177 e - manually edit the current hunk
1184 my $ret = run_git_apply $cmd, @_;
1191 sub apply_patch_for_checkout_commit {
1192 my $reverse = shift;
1193 my $applies_index = run_git_apply 'apply '.$reverse.' --cached --check', @_;
1194 my $applies_worktree = run_git_apply 'apply '.$reverse.' --check', @_;
1196 if ($applies_worktree && $applies_index) {
1197 run_git_apply 'apply '.$reverse.' --cached', @_;
1198 run_git_apply 'apply '.$reverse, @_;
1200 } elsif (!$applies_index) {
1201 print colored $error_color, "The selected hunks do not apply to the index!\n";
1202 if (prompt_yesno "Apply them to the worktree anyway? ") {
1203 return run_git_apply 'apply '.$reverse, @_;
1205 print colored $error_color, "Nothing was applied.\n";
1214 sub patch_update_cmd {
1215 my @all_mods = list_modified($patch_mode_flavour{FILTER});
1216 error_msg "ignoring unmerged: $_->{VALUE}\n"
1217 for grep { $_->{UNMERGED} } @all_mods;
1218 @all_mods = grep { !$_->{UNMERGED} } @all_mods;
1220 my @mods = grep { !($_->{BINARY}) } @all_mods;
1225 print STDERR "Only binary files changed.\n";
1227 print STDERR "No changes.\n";
1235 @them = list_and_choose({ PROMPT => 'Patch update',
1236 HEADER => $status_head, },
1240 return 0 if patch_update_file($_->{VALUE});
1244 # Generate a one line summary of a hunk.
1245 sub summarize_hunk {
1247 my $summary = $rhunk->{TEXT}[0];
1249 # Keep the line numbers, discard extra context.
1250 $summary =~ s/@@(.*?)@@.*/$1 /s;
1251 $summary .= " " x (20 - length $summary);
1253 # Add some user context.
1254 for my $line (@{$rhunk->{TEXT}}) {
1255 if ($line =~ m/^[+-].*\w/) {
1262 return substr($summary, 0, 80) . "\n";
1266 # Print a one-line summary of each hunk in the array ref in
1267 # the first argument, starting with the index in the 2nd.
1269 my ($hunks, $i) = @_;
1272 for (; $i < @$hunks && $ctr < 20; $i++, $ctr++) {
1274 if (defined $hunks->[$i]{USE}) {
1275 $status = $hunks->[$i]{USE} ? "+" : "-";
1280 summarize_hunk($hunks->[$i]);
1285 sub patch_update_file {
1289 my ($head, @hunk) = parse_diff($path);
1290 ($head, my $mode, my $deletion) = parse_diff_header($head);
1291 for (@{$head->{DISPLAY}}) {
1295 if (@{$mode->{TEXT}}) {
1296 unshift @hunk, $mode;
1298 if (@{$deletion->{TEXT}}) {
1299 foreach my $hunk (@hunk) {
1300 push @{$deletion->{TEXT}}, @{$hunk->{TEXT}};
1301 push @{$deletion->{DISPLAY}}, @{$hunk->{DISPLAY}};
1303 @hunk = ($deletion);
1306 $num = scalar @hunk;
1310 my ($prev, $next, $other, $undecided, $i);
1316 for ($i = 0; $i < $ix; $i++) {
1317 if (!defined $hunk[$i]{USE}) {
1326 for ($i = $ix + 1; $i < $num; $i++) {
1327 if (!defined $hunk[$i]{USE}) {
1333 if ($ix < $num - 1) {
1339 for ($i = 0; $i < $num; $i++) {
1340 if (!defined $hunk[$i]{USE}) {
1345 last if (!$undecided);
1347 if ($hunk[$ix]{TYPE} eq 'hunk' &&
1348 hunk_splittable($hunk[$ix]{TEXT})) {
1351 if ($hunk[$ix]{TYPE} eq 'hunk') {
1354 for (@{$hunk[$ix]{DISPLAY}}) {
1357 print colored $prompt_color, $patch_mode_flavour{VERB},
1358 ($hunk[$ix]{TYPE} eq 'mode' ? ' mode change' :
1359 $hunk[$ix]{TYPE} eq 'deletion' ? ' deletion' :
1361 $patch_mode_flavour{TARGET},
1362 " [y,n,q,a,d,/$other,?]? ";
1363 my $line = prompt_single_character;
1364 last unless defined $line;
1366 if ($line =~ /^y/i) {
1367 $hunk[$ix]{USE} = 1;
1369 elsif ($line =~ /^n/i) {
1370 $hunk[$ix]{USE} = 0;
1372 elsif ($line =~ /^a/i) {
1373 while ($ix < $num) {
1374 if (!defined $hunk[$ix]{USE}) {
1375 $hunk[$ix]{USE} = 1;
1381 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1383 my $no = $ix > 10 ? $ix - 10 : 0;
1384 while ($response eq '') {
1386 $no = display_hunks(\@hunk, $no);
1388 $extra = " (<ret> to see more)";
1390 print "go to which hunk$extra? ";
1391 $response = <STDIN>;
1392 if (!defined $response) {
1397 if ($response !~ /^\s*\d+\s*$/) {
1398 error_msg "Invalid number: '$response'\n";
1399 } elsif (0 < $response && $response <= $num) {
1400 $ix = $response - 1;
1402 error_msg "Sorry, only $num hunks available.\n";
1406 elsif ($line =~ /^d/i) {
1407 while ($ix < $num) {
1408 if (!defined $hunk[$ix]{USE}) {
1409 $hunk[$ix]{USE} = 0;
1415 elsif ($line =~ /^q/i) {
1416 for ($i = 0; $i < $num; $i++) {
1417 if (!defined $hunk[$i]{USE}) {
1424 elsif ($line =~ m|^/(.*)|) {
1427 print colored $prompt_color, "search for regex? ";
1429 if (defined $regex) {
1435 $search_string = qr{$regex}m;
1438 my ($err,$exp) = ($@, $1);
1439 $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1440 error_msg "Malformed search regexp $exp: $err\n";
1445 my $text = join ("", @{$hunk[$iy]{TEXT}});
1446 last if ($text =~ $search_string);
1448 $iy = 0 if ($iy >= $num);
1450 error_msg "No hunk matches the given pattern\n";
1457 elsif ($line =~ /^K/) {
1458 if ($other =~ /K/) {
1462 error_msg "No previous hunk\n";
1466 elsif ($line =~ /^J/) {
1467 if ($other =~ /J/) {
1471 error_msg "No next hunk\n";
1475 elsif ($line =~ /^k/) {
1476 if ($other =~ /k/) {
1480 !defined $hunk[$ix]{USE});
1484 error_msg "No previous hunk\n";
1488 elsif ($line =~ /^j/) {
1489 if ($other !~ /j/) {
1490 error_msg "No next hunk\n";
1494 elsif ($other =~ /s/ && $line =~ /^s/) {
1495 my @split = split_hunk($hunk[$ix]{TEXT}, $hunk[$ix]{DISPLAY});
1497 print colored $header_color, "Split into ",
1498 scalar(@split), " hunks.\n";
1500 splice (@hunk, $ix, 1, @split);
1501 $num = scalar @hunk;
1504 elsif ($other =~ /e/ && $line =~ /^e/) {
1505 my $newhunk = edit_hunk_loop($head, \@hunk, $ix);
1506 if (defined $newhunk) {
1507 splice @hunk, $ix, 1, $newhunk;
1511 help_patch_cmd($other);
1517 last if ($ix >= $num ||
1518 !defined $hunk[$ix]{USE});
1523 @hunk = coalesce_overlapping_hunks(@hunk);
1529 push @result, @{$_->{TEXT}};
1534 my @patch = reassemble_patch($head->{TEXT}, @result);
1535 my $apply_routine = $patch_mode_flavour{APPLY};
1536 &$apply_routine(@patch);
1545 my @mods = list_modified('index-only');
1546 @mods = grep { !($_->{BINARY}) } @mods;
1548 my (@them) = list_and_choose({ PROMPT => 'Review diff',
1550 HEADER => $status_head, },
1553 my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
1554 system(qw(git diff -p --cached), $reference, '--',
1555 map { $_->{VALUE} } @them);
1564 print colored $help_color, <<\EOF ;
1565 status - show paths with changes
1566 update - add working tree state to the staged set of changes
1567 revert - revert staged set of changes back to the HEAD version
1568 patch - pick hunks and update selectively
1569 diff - view diff between HEAD and index
1570 add untracked - add contents of untracked files to the staged set of changes
1575 return unless @ARGV;
1576 my $arg = shift @ARGV;
1577 if ($arg =~ /--patch(?:=(.*))?/) {
1579 if ($1 eq 'reset') {
1580 $patch_mode = 'reset_head';
1581 $patch_mode_revision = 'HEAD';
1582 $arg = shift @ARGV or die "missing --";
1584 $patch_mode_revision = $arg;
1585 $patch_mode = ($arg eq 'HEAD' ?
1586 'reset_head' : 'reset_nothead');
1587 $arg = shift @ARGV or die "missing --";
1589 } elsif ($1 eq 'checkout') {
1590 $arg = shift @ARGV or die "missing --";
1592 $patch_mode = 'checkout_index';
1594 $patch_mode_revision = $arg;
1595 $patch_mode = ($arg eq 'HEAD' ?
1596 'checkout_head' : 'checkout_nothead');
1597 $arg = shift @ARGV or die "missing --";
1599 } elsif ($1 eq 'stage' or $1 eq 'stash') {
1601 $arg = shift @ARGV or die "missing --";
1603 die "unknown --patch mode: $1";
1606 $patch_mode = 'stage';
1607 $arg = shift @ARGV or die "missing --";
1609 die "invalid argument $arg, expecting --"
1610 unless $arg eq "--";
1611 %patch_mode_flavour = %{$patch_modes{$patch_mode}};
1613 elsif ($arg ne "--") {
1614 die "invalid argument $arg, expecting --";
1619 my @cmd = ([ 'status', \&status_cmd, ],
1620 [ 'update', \&update_cmd, ],
1621 [ 'revert', \&revert_cmd, ],
1622 [ 'add untracked', \&add_untracked_cmd, ],
1623 [ 'patch', \&patch_update_cmd, ],
1624 [ 'diff', \&diff_cmd, ],
1625 [ 'quit', \&quit_cmd, ],
1626 [ 'help', \&help_cmd, ],
1629 my ($it) = list_and_choose({ PROMPT => 'What now',
1632 HEADER => '*** Commands ***',
1633 ON_EOF => \&quit_cmd,
1634 IMMEDIATE => 1 }, @cmd);