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;
91 sub apply_patch_for_checkout_commit
;
92 sub apply_patch_for_stash
;
96 DIFF
=> 'diff-files -p',
97 APPLY
=> sub { apply_patch
'apply --cached', @_; },
98 APPLY_CHECK
=> 'apply --cached',
101 PARTICIPLE
=> 'staging',
102 FILTER
=> 'file-only',
106 DIFF
=> 'diff-index -p HEAD',
107 APPLY
=> sub { apply_patch
'apply --cached', @_; },
108 APPLY_CHECK
=> 'apply --cached',
111 PARTICIPLE
=> 'stashing',
116 DIFF
=> 'diff-index -p --cached',
117 APPLY
=> sub { apply_patch
'apply -R --cached', @_; },
118 APPLY_CHECK
=> 'apply -R --cached',
121 PARTICIPLE
=> 'unstaging',
122 FILTER
=> 'index-only',
126 DIFF
=> 'diff-index -R -p --cached',
127 APPLY
=> sub { apply_patch
'apply --cached', @_; },
128 APPLY_CHECK
=> 'apply --cached',
130 TARGET
=> ' to index',
131 PARTICIPLE
=> 'applying',
132 FILTER
=> 'index-only',
135 'checkout_index' => {
136 DIFF
=> 'diff-files -p',
137 APPLY
=> sub { apply_patch
'apply -R', @_; },
138 APPLY_CHECK
=> 'apply -R',
140 TARGET
=> ' from worktree',
141 PARTICIPLE
=> 'discarding',
142 FILTER
=> 'file-only',
146 DIFF
=> 'diff-index -p',
147 APPLY
=> sub { apply_patch_for_checkout_commit
'-R', @_ },
148 APPLY_CHECK
=> 'apply -R',
150 TARGET
=> ' from index and worktree',
151 PARTICIPLE
=> 'discarding',
155 'checkout_nothead' => {
156 DIFF
=> 'diff-index -R -p',
157 APPLY
=> sub { apply_patch_for_checkout_commit
'', @_ },
158 APPLY_CHECK
=> 'apply',
160 TARGET
=> ' to index and worktree',
161 PARTICIPLE
=> 'applying',
167 my %patch_mode_flavour = %{$patch_modes{stage
}};
170 if ($^O
eq 'MSWin32' || $^O
eq 'msys') {
171 my @invalid = grep {m/[":*]/} @_;
172 die "$^O does not support: @invalid\n" if @invalid;
173 my @args = map { m/ /o ?
"\"$_\"": $_ } @_;
177 open($fh, '-|', @_) or die;
182 my ($GIT_DIR) = run_cmd_pipe
(qw(git rev-parse --git-dir));
184 if (!defined $GIT_DIR) {
185 exit(1); # rev-parse would have already said "not a git repo"
202 my ($retval, $remainder);
203 if (!/^\042(.*)\042$/) {
206 ($_, $retval) = ($1, "");
207 while (/^([^\\]*)\\(.*)$/) {
211 if (/^([0-3][0-7][0-7])(.*)$/) {
212 $retval .= chr(oct($1));
216 if (/^([\\\042btnvfr])(.*)$/) {
217 $retval .= $cquote_map{$1};
221 # This is malformed -- just return it as-is for now.
232 open $fh, 'git update-index --refresh |'
235 ;# ignore 'needs update'
245 run_cmd_pipe
(qw(git ls-files --others --exclude-standard --), @ARGV);
248 my $status_fmt = '%12s %12s %s';
249 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
253 sub is_initial_commit
{
254 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
255 unless defined $initial;
261 return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
264 # Returns list of hashes, contents of each of which are:
266 # BINARY: is a binary path
267 # INDEX: is index different from HEAD?
268 # FILE: is file different from index?
269 # INDEX_ADDDEL: is it add/delete between HEAD and index?
270 # FILE_ADDDEL: is it add/delete between index and file?
271 # UNMERGED: is the path unmerged
276 my ($add, $del, $adddel, $file);
283 } run_cmd_pipe
(qw(git ls-files --), @ARGV);
284 return if (!@tracked);
288 if (defined $patch_mode_revision and $patch_mode_revision ne 'HEAD') {
289 $reference = $patch_mode_revision;
290 } elsif (is_initial_commit
()) {
291 $reference = get_empty_tree
();
295 for (run_cmd_pipe
(qw(git diff-index --cached
296 --numstat --summary), $reference,
298 if (($add, $del, $file) =
299 /^([-\d]+) ([-\d]+) (.*)/) {
301 $file = unquote_path
($file);
302 if ($add eq '-' && $del eq '-') {
307 $change = "+$add/-$del";
315 elsif (($adddel, $file) =
316 /^ (create|delete) mode [0-7]+ (.*)$/) {
317 $file = unquote_path
($file);
318 $data{$file}{INDEX_ADDDEL
} = $adddel;
322 for (run_cmd_pipe
(qw(git diff-files --numstat --summary --raw --), @tracked)) {
323 if (($add, $del, $file) =
324 /^([-\d]+) ([-\d]+) (.*)/) {
325 $file = unquote_path
($file);
327 if ($add eq '-' && $del eq '-') {
332 $change = "+$add/-$del";
334 $data{$file}{FILE
} = $change;
336 $data{$file}{BINARY
} = 1;
339 elsif (($adddel, $file) =
340 /^ (create|delete) mode [0-7]+ (.*)$/) {
341 $file = unquote_path
($file);
342 $data{$file}{FILE_ADDDEL
} = $adddel;
344 elsif (/^:[0-7]+ [0-7]+ [0-9a-f]+ [0-9a-f]+ (.) (.*)$/) {
345 $file = unquote_path
($2);
346 if (!exists $data{$file}) {
348 INDEX
=> 'unchanged',
353 $data{$file}{UNMERGED
} = 1;
358 for (sort keys %data) {
362 if ($only eq 'index-only') {
363 next if ($it->{INDEX
} eq 'unchanged');
365 if ($only eq 'file-only') {
366 next if ($it->{FILE
} eq 'nothing');
378 my ($string, @stuff) = @_;
380 for (my $i = 0; $i < @stuff; $i++) {
384 if ((ref $it) eq 'ARRAY') {
392 if ($it =~ /^$string/) {
396 if (defined $hit && defined $found) {
406 # inserts string into trie and updates count for each character
408 my ($trie, $string) = @_;
409 foreach (split //, $string) {
410 $trie = $trie->{$_} ||= {COUNT
=> 0};
415 # returns an array of tuples (prefix, remainder)
416 sub find_unique_prefixes
{
420 # any single prefix exceeding the soft limit is omitted
421 # if any prefix exceeds the hard limit all are omitted
422 # 0 indicates no limit
426 # build a trie modelling all possible options
428 foreach my $print (@stuff) {
429 if ((ref $print) eq 'ARRAY') {
430 $print = $print->[0];
432 elsif ((ref $print) eq 'HASH') {
433 $print = $print->{VALUE
};
435 update_trie
(\
%trie, $print);
436 push @return, $print;
439 # use the trie to find the unique prefixes
440 for (my $i = 0; $i < @return; $i++) {
441 my $ret = $return[$i];
442 my @letters = split //, $ret;
444 my ($prefix, $remainder);
446 for ($j = 0; $j < @letters; $j++) {
447 my $letter = $letters[$j];
448 if ($search{$letter}{COUNT
} == 1) {
449 $prefix = substr $ret, 0, $j + 1;
450 $remainder = substr $ret, $j + 1;
454 my $prefix = substr $ret, 0, $j;
456 if ($hard_limit && $j + 1 > $hard_limit);
458 %search = %{$search{$letter}};
460 if (ord($letters[0]) > 127 ||
461 ($soft_limit && $j + 1 > $soft_limit)) {
465 $return[$i] = [$prefix, $remainder];
470 # filters out prefixes which have special meaning to list_and_choose()
471 sub is_valid_prefix
{
473 return (defined $prefix) &&
474 !($prefix =~ /[\s,]/) && # separators
475 !($prefix =~ /^-/) && # deselection
476 !($prefix =~ /^\d+/) && # selection
477 ($prefix ne '*') && # "all" wildcard
478 ($prefix ne '?'); # prompt help
481 # given a prefix/remainder tuple return a string with the prefix highlighted
482 # for now use square brackets; later might use ANSI colors (underline, bold)
483 sub highlight_prefix
{
485 my $remainder = shift;
487 if (!defined $prefix) {
491 if (!is_valid_prefix
($prefix)) {
492 return "$prefix$remainder";
495 if (!$menu_use_color) {
496 return "[$prefix]$remainder";
499 return "$prompt_color$prefix$normal_color$remainder";
503 print STDERR colored
$error_color, @_;
506 sub list_and_choose
{
507 my ($opts, @stuff) = @_;
508 my (@chosen, @return);
510 my @prefixes = find_unique_prefixes
(@stuff) unless $opts->{LIST_ONLY
};
516 if ($opts->{HEADER
}) {
517 if (!$opts->{LIST_FLAT
}) {
520 print colored
$header_color, "$opts->{HEADER}\n";
522 for ($i = 0; $i < @stuff; $i++) {
523 my $chosen = $chosen[$i] ?
'*' : ' ';
524 my $print = $stuff[$i];
525 my $ref = ref $print;
526 my $highlighted = highlight_prefix
(@
{$prefixes[$i]})
528 if ($ref eq 'ARRAY') {
529 $print = $highlighted || $print->[0];
531 elsif ($ref eq 'HASH') {
532 my $value = $highlighted || $print->{VALUE
};
533 $print = sprintf($status_fmt,
539 $print = $highlighted || $print;
541 printf("%s%2d: %s", $chosen, $i+1, $print);
542 if (($opts->{LIST_FLAT
}) &&
543 (($i + 1) % ($opts->{LIST_FLAT
}))) {
556 return if ($opts->{LIST_ONLY
});
558 print colored
$prompt_color, $opts->{PROMPT
};
559 if ($opts->{SINGLETON
}) {
568 $opts->{ON_EOF
}->() if $opts->{ON_EOF
};
575 singleton_prompt_help_cmd
() :
579 for my $choice (split(/[\s,]+/, $line)) {
583 # Input that begins with '-'; unchoose
584 if ($choice =~ s/^-//) {
587 # A range can be specified like 5-7 or 5-.
588 if ($choice =~ /^(\d+)-(\d*)$/) {
589 ($bottom, $top) = ($1, length($2) ?
$2 : 1 + @stuff);
591 elsif ($choice =~ /^\d+$/) {
592 $bottom = $top = $choice;
594 elsif ($choice eq '*') {
599 $bottom = $top = find_unique
($choice, @stuff);
600 if (!defined $bottom) {
601 error_msg
"Huh ($choice)?\n";
605 if ($opts->{SINGLETON
} && $bottom != $top) {
606 error_msg
"Huh ($choice)?\n";
609 for ($i = $bottom-1; $i <= $top-1; $i++) {
610 next if (@stuff <= $i || $i < 0);
611 $chosen[$i] = $choose;
614 last if ($opts->{IMMEDIATE
} || $line eq '*');
616 for ($i = 0; $i < @stuff; $i++) {
618 push @return, $stuff[$i];
624 sub singleton_prompt_help_cmd
{
625 print colored
$help_color, <<\EOF
;
627 1 - select a numbered item
628 foo
- select item based on unique prefix
629 - (empty
) select nothing
633 sub prompt_help_cmd
{
634 print colored
$help_color, <<\EOF
;
636 1 - select a single item
637 3-5 - select a range of items
638 2-3,6-9 - select multiple ranges
639 foo
- select item based on unique prefix
640 -... - unselect specified items
642 - (empty
) finish selecting
647 list_and_choose
({ LIST_ONLY
=> 1, HEADER
=> $status_head },
657 print "$cnt paths\n";
665 my @mods = list_modified
('file-only');
668 my @update = list_and_choose
({ PROMPT
=> 'Update',
669 HEADER
=> $status_head, },
672 system(qw(git update-index --add --remove --),
673 map { $_->{VALUE
} } @update);
674 say_n_paths
('updated', @update);
680 my @update = list_and_choose
({ PROMPT
=> 'Revert',
681 HEADER
=> $status_head, },
684 if (is_initial_commit
()) {
685 system(qw(git rm --cached),
686 map { $_->{VALUE
} } @update);
689 my @lines = run_cmd_pipe
(qw(git ls-tree HEAD --),
690 map { $_->{VALUE
} } @update);
692 open $fh, '| git update-index --index-info'
699 if ($_->{INDEX_ADDDEL
} &&
700 $_->{INDEX_ADDDEL
} eq 'create') {
701 system(qw(git update-index --force-remove --),
703 print "note: $_->{VALUE} is untracked now.\n";
708 say_n_paths
('reverted', @update);
713 sub add_untracked_cmd
{
714 my @add = list_and_choose
({ PROMPT
=> 'Add untracked' },
717 system(qw(git update-index --add --), @add);
718 say_n_paths
('added', @add);
726 open $fh, '| git ' . $cmd . " --recount --allow-overlap";
733 my @diff_cmd = split(" ", $patch_mode_flavour{DIFF
});
734 if (defined $patch_mode_revision) {
735 push @diff_cmd, $patch_mode_revision;
737 my @diff = run_cmd_pipe
("git", @diff_cmd, "--", $path);
739 if ($diff_use_color) {
740 @colored = run_cmd_pipe
("git", @diff_cmd, qw(--color --), $path);
742 my (@hunk) = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'header' };
744 for (my $i = 0; $i < @diff; $i++) {
745 if ($diff[$i] =~ /^@@ /) {
746 push @hunk, { TEXT
=> [], DISPLAY
=> [],
749 push @
{$hunk[-1]{TEXT
}}, $diff[$i];
750 push @
{$hunk[-1]{DISPLAY
}},
751 ($diff_use_color ?
$colored[$i] : $diff[$i]);
756 sub parse_diff_header
{
759 my $head = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'header' };
760 my $mode = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'mode' };
761 my $deletion = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'deletion' };
763 for (my $i = 0; $i < @
{$src->{TEXT
}}; $i++) {
765 $src->{TEXT
}->[$i] =~ /^(old|new) mode (\d+)$/ ?
$mode :
766 $src->{TEXT
}->[$i] =~ /^deleted file/ ?
$deletion :
768 push @
{$dest->{TEXT
}}, $src->{TEXT
}->[$i];
769 push @
{$dest->{DISPLAY
}}, $src->{DISPLAY
}->[$i];
771 return ($head, $mode, $deletion);
774 sub hunk_splittable
{
777 my @s = split_hunk
($text);
781 sub parse_hunk_header
{
783 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
784 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
785 $o_cnt = 1 unless defined $o_cnt;
786 $n_cnt = 1 unless defined $n_cnt;
787 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
791 my ($text, $display) = @_;
793 if (!defined $display) {
796 # If there are context lines in the middle of a hunk,
797 # it can be split, but we would need to take care of
800 my ($o_ofs, undef, $n_ofs) = parse_hunk_header
($text->[0]);
805 my $next_hunk_start = undef;
806 my $i = $hunk_start - 1;
820 while (++$i < @
$text) {
821 my $line = $text->[$i];
822 my $display = $display->[$i];
824 if ($this->{ADDDEL
} &&
825 !defined $next_hunk_start) {
826 # We have seen leading context and
827 # adds/dels and then here is another
828 # context, which is trailing for this
829 # split hunk and leading for the next
831 $next_hunk_start = $i;
833 push @
{$this->{TEXT
}}, $line;
834 push @
{$this->{DISPLAY
}}, $display;
837 if (defined $next_hunk_start) {
844 if (defined $next_hunk_start) {
845 # We are done with the current hunk and
846 # this is the first real change for the
848 $hunk_start = $next_hunk_start;
849 $o_ofs = $this->{OLD
} + $this->{OCNT
};
850 $n_ofs = $this->{NEW
} + $this->{NCNT
};
851 $o_ofs -= $this->{POSTCTX
};
852 $n_ofs -= $this->{POSTCTX
};
856 push @
{$this->{TEXT
}}, $line;
857 push @
{$this->{DISPLAY
}}, $display;
871 for my $hunk (@split) {
872 $o_ofs = $hunk->{OLD
};
873 $n_ofs = $hunk->{NEW
};
874 my $o_cnt = $hunk->{OCNT
};
875 my $n_cnt = $hunk->{NCNT
};
877 my $head = ("@@ -$o_ofs" .
878 (($o_cnt != 1) ?
",$o_cnt" : '') .
880 (($n_cnt != 1) ?
",$n_cnt" : '') .
882 my $display_head = $head;
883 unshift @
{$hunk->{TEXT
}}, $head;
884 if ($diff_use_color) {
885 $display_head = colored
($fraginfo_color, $head);
887 unshift @
{$hunk->{DISPLAY
}}, $display_head;
892 sub find_last_o_ctx
{
894 my $text = $it->{TEXT
};
895 my ($o_ofs, $o_cnt) = parse_hunk_header
($text->[0]);
897 my $last_o_ctx = $o_ofs + $o_cnt;
899 my $line = $text->[$i];
910 my ($prev, $this) = @_;
911 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
912 parse_hunk_header
($prev->{TEXT
}[0]);
913 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
914 parse_hunk_header
($this->{TEXT
}[0]);
916 my (@line, $i, $ofs, $o_cnt, $n_cnt);
919 for ($i = 1; $i < @
{$prev->{TEXT
}}; $i++) {
920 my $line = $prev->{TEXT
}[$i];
921 if ($line =~ /^\+/) {
927 last if ($o1_ofs <= $ofs);
937 for ($i = 1; $i < @
{$this->{TEXT
}}; $i++) {
938 my $line = $this->{TEXT
}[$i];
939 if ($line =~ /^\+/) {
951 my $head = ("@@ -$o0_ofs" .
952 (($o_cnt != 1) ?
",$o_cnt" : '') .
954 (($n_cnt != 1) ?
",$n_cnt" : '') .
956 @
{$prev->{TEXT
}} = ($head, @line);
959 sub coalesce_overlapping_hunks
{
963 my ($last_o_ctx, $last_was_dirty);
965 for (grep { $_->{USE
} } @in) {
966 if ($_->{TYPE
} ne 'hunk') {
970 my $text = $_->{TEXT
};
971 my ($o_ofs) = parse_hunk_header
($text->[0]);
972 if (defined $last_o_ctx &&
973 $o_ofs <= $last_o_ctx &&
976 merge_hunk
($out[-1], $_);
981 $last_o_ctx = find_last_o_ctx
($out[-1]);
982 $last_was_dirty = $_->{DIRTY
};
987 sub reassemble_patch
{
991 # Include everything in the header except the beginning of the diff.
992 push @patch, (grep { !/^[-+]{3}/ } @
$head);
994 # Then include any headers from the hunk lines, which must
995 # come before any actual hunk.
996 while (@_ && $_[0] !~ /^@/) {
1000 # Then begin the diff.
1001 push @patch, grep { /^[-+]{3}/ } @
$head;
1003 # And then the actual hunks.
1011 colored
((/^@/ ?
$fraginfo_color :
1012 /^\+/ ?
$diff_new_color :
1013 /^-/ ?
$diff_old_color :
1019 sub edit_hunk_manually
{
1022 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
1024 open $fh, '>', $hunkfile
1025 or die "failed to open hunk edit file for writing: " . $!;
1026 print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
1027 print $fh @
$oldtext;
1028 my $participle = $patch_mode_flavour{PARTICIPLE
};
1029 my $is_reverse = $patch_mode_flavour{IS_REVERSE
};
1030 my ($remove_plus, $remove_minus) = $is_reverse ?
('-', '+') : ('+', '-');
1033 # To remove '$remove_minus' lines, make them ' ' lines (context).
1034 # To remove '$remove_plus' lines, delete them.
1035 # Lines starting with # will be removed.
1037 # If the patch applies cleanly, the edited hunk will immediately be
1038 # marked for $participle. If it does not apply cleanly, you will be given
1039 # an opportunity to edit again. If all lines of the hunk are removed,
1040 # then the edit is aborted and the hunk is left unchanged.
1044 chomp(my $editor = run_cmd_pipe
(qw(git var GIT_EDITOR)));
1045 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
1051 open $fh, '<', $hunkfile
1052 or die "failed to open hunk edit file for reading: " . $!;
1053 my @newtext = grep { !/^#/ } <$fh>;
1057 # Abort if nothing remains
1058 if (!grep { /\S/ } @newtext) {
1062 # Reinsert the first hunk header if the user accidentally deleted it
1063 if ($newtext[0] !~ /^@/) {
1064 unshift @newtext, $oldtext->[0];
1070 return run_git_apply
($patch_mode_flavour{APPLY_CHECK
} . ' --check',
1071 map { @
{$_->{TEXT
}} } @_);
1074 sub _restore_terminal_and_die
{
1080 sub prompt_single_character
{
1082 local $SIG{TERM
} = \
&_restore_terminal_and_die
;
1083 local $SIG{INT
} = \
&_restore_terminal_and_die
;
1085 my $key = ReadKey
0;
1087 if ($use_termcap and $key eq "\e") {
1088 while (!defined $term_escapes{$key}) {
1089 my $next = ReadKey
0.5;
1090 last if (!defined $next);
1095 print "$key" if defined $key;
1106 print colored
$prompt_color, $prompt;
1107 my $line = prompt_single_character
;
1108 return 0 if $line =~ /^n/i;
1109 return 1 if $line =~ /^y/i;
1113 sub edit_hunk_loop
{
1114 my ($head, $hunk, $ix) = @_;
1115 my $text = $hunk->[$ix]->{TEXT
};
1118 $text = edit_hunk_manually
($text);
1119 if (!defined $text) {
1124 TYPE
=> $hunk->[$ix]->{TYPE
},
1128 if (diff_applies
($head,
1131 @
{$hunk}[$ix+1..$#{$hunk}])) {
1132 $newhunk->{DISPLAY
} = [color_diff
(@
{$text})];
1137 'Your edited hunk does not apply. Edit again '
1138 . '(saying "no" discards!) [y/n]? '
1144 sub help_patch_cmd
{
1145 my $verb = lc $patch_mode_flavour{VERB
};
1146 my $target = $patch_mode_flavour{TARGET
};
1147 print colored
$help_color, <<EOF ;
1148 y - $verb this hunk$target
1149 n - do not $verb this hunk$target
1150 q - quit; do not $verb this hunk nor any of the remaining ones
1151 a - $verb this hunk and all later hunks in the file
1152 d - do not $verb this hunk nor any of the later hunks in the file
1153 g - select a hunk to go to
1154 / - search for a hunk matching the given regex
1155 j - leave this hunk undecided, see next undecided hunk
1156 J - leave this hunk undecided, see next hunk
1157 k - leave this hunk undecided, see previous undecided hunk
1158 K - leave this hunk undecided, see previous hunk
1159 s - split the current hunk into smaller hunks
1160 e - manually edit the current hunk
1167 my $ret = run_git_apply
$cmd, @_;
1174 sub apply_patch_for_checkout_commit
{
1175 my $reverse = shift;
1176 my $applies_index = run_git_apply
'apply '.$reverse.' --cached --check', @_;
1177 my $applies_worktree = run_git_apply
'apply '.$reverse.' --check', @_;
1179 if ($applies_worktree && $applies_index) {
1180 run_git_apply
'apply '.$reverse.' --cached', @_;
1181 run_git_apply
'apply '.$reverse, @_;
1183 } elsif (!$applies_index) {
1184 print colored
$error_color, "The selected hunks do not apply to the index!\n";
1185 if (prompt_yesno
"Apply them to the worktree anyway? ") {
1186 return run_git_apply
'apply '.$reverse, @_;
1188 print colored
$error_color, "Nothing was applied.\n";
1197 sub patch_update_cmd
{
1198 my @all_mods = list_modified
($patch_mode_flavour{FILTER
});
1199 error_msg
"ignoring unmerged: $_->{VALUE}\n"
1200 for grep { $_->{UNMERGED
} } @all_mods;
1201 @all_mods = grep { !$_->{UNMERGED
} } @all_mods;
1203 my @mods = grep { !($_->{BINARY
}) } @all_mods;
1208 print STDERR
"Only binary files changed.\n";
1210 print STDERR
"No changes.\n";
1218 @them = list_and_choose
({ PROMPT
=> 'Patch update',
1219 HEADER
=> $status_head, },
1223 return 0 if patch_update_file
($_->{VALUE
});
1227 # Generate a one line summary of a hunk.
1228 sub summarize_hunk
{
1230 my $summary = $rhunk->{TEXT
}[0];
1232 # Keep the line numbers, discard extra context.
1233 $summary =~ s/@@(.*?)@@.*/$1 /s;
1234 $summary .= " " x
(20 - length $summary);
1236 # Add some user context.
1237 for my $line (@
{$rhunk->{TEXT
}}) {
1238 if ($line =~ m/^[+-].*\w/) {
1245 return substr($summary, 0, 80) . "\n";
1249 # Print a one-line summary of each hunk in the array ref in
1250 # the first argument, starting wih the index in the 2nd.
1252 my ($hunks, $i) = @_;
1255 for (; $i < @
$hunks && $ctr < 20; $i++, $ctr++) {
1257 if (defined $hunks->[$i]{USE
}) {
1258 $status = $hunks->[$i]{USE
} ?
"+" : "-";
1263 summarize_hunk
($hunks->[$i]);
1268 sub patch_update_file
{
1272 my ($head, @hunk) = parse_diff
($path);
1273 ($head, my $mode, my $deletion) = parse_diff_header
($head);
1274 for (@
{$head->{DISPLAY
}}) {
1278 if (@
{$mode->{TEXT
}}) {
1279 unshift @hunk, $mode;
1281 if (@
{$deletion->{TEXT
}}) {
1282 foreach my $hunk (@hunk) {
1283 push @
{$deletion->{TEXT
}}, @
{$hunk->{TEXT
}};
1284 push @
{$deletion->{DISPLAY
}}, @
{$hunk->{DISPLAY
}};
1286 @hunk = ($deletion);
1289 $num = scalar @hunk;
1293 my ($prev, $next, $other, $undecided, $i);
1299 for ($i = 0; $i < $ix; $i++) {
1300 if (!defined $hunk[$i]{USE
}) {
1309 for ($i = $ix + 1; $i < $num; $i++) {
1310 if (!defined $hunk[$i]{USE
}) {
1316 if ($ix < $num - 1) {
1322 for ($i = 0; $i < $num; $i++) {
1323 if (!defined $hunk[$i]{USE
}) {
1328 last if (!$undecided);
1330 if ($hunk[$ix]{TYPE
} eq 'hunk' &&
1331 hunk_splittable
($hunk[$ix]{TEXT
})) {
1334 if ($hunk[$ix]{TYPE
} eq 'hunk') {
1337 for (@
{$hunk[$ix]{DISPLAY
}}) {
1340 print colored
$prompt_color, $patch_mode_flavour{VERB
},
1341 ($hunk[$ix]{TYPE
} eq 'mode' ?
' mode change' :
1342 $hunk[$ix]{TYPE
} eq 'deletion' ?
' deletion' :
1344 $patch_mode_flavour{TARGET
},
1345 " [y,n,q,a,d,/$other,?]? ";
1346 my $line = prompt_single_character
;
1348 if ($line =~ /^y/i) {
1349 $hunk[$ix]{USE
} = 1;
1351 elsif ($line =~ /^n/i) {
1352 $hunk[$ix]{USE
} = 0;
1354 elsif ($line =~ /^a/i) {
1355 while ($ix < $num) {
1356 if (!defined $hunk[$ix]{USE
}) {
1357 $hunk[$ix]{USE
} = 1;
1363 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1365 my $no = $ix > 10 ?
$ix - 10 : 0;
1366 while ($response eq '') {
1368 $no = display_hunks
(\
@hunk, $no);
1370 $extra = " (<ret> to see more)";
1372 print "go to which hunk$extra? ";
1373 $response = <STDIN
>;
1374 if (!defined $response) {
1379 if ($response !~ /^\s*\d+\s*$/) {
1380 error_msg
"Invalid number: '$response'\n";
1381 } elsif (0 < $response && $response <= $num) {
1382 $ix = $response - 1;
1384 error_msg
"Sorry, only $num hunks available.\n";
1388 elsif ($line =~ /^d/i) {
1389 while ($ix < $num) {
1390 if (!defined $hunk[$ix]{USE
}) {
1391 $hunk[$ix]{USE
} = 0;
1397 elsif ($line =~ /^q/i) {
1398 for ($i = 0; $i < $num; $i++) {
1399 if (!defined $hunk[$i]{USE
}) {
1406 elsif ($line =~ m
|^/(.*)|) {
1409 print colored
$prompt_color, "search for regex? ";
1411 if (defined $regex) {
1417 $search_string = qr{$regex}m;
1420 my ($err,$exp) = ($@
, $1);
1421 $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1422 error_msg
"Malformed search regexp $exp: $err\n";
1427 my $text = join ("", @
{$hunk[$iy]{TEXT
}});
1428 last if ($text =~ $search_string);
1430 $iy = 0 if ($iy >= $num);
1432 error_msg
"No hunk matches the given pattern\n";
1439 elsif ($line =~ /^K/) {
1440 if ($other =~ /K/) {
1444 error_msg
"No previous hunk\n";
1448 elsif ($line =~ /^J/) {
1449 if ($other =~ /J/) {
1453 error_msg
"No next hunk\n";
1457 elsif ($line =~ /^k/) {
1458 if ($other =~ /k/) {
1462 !defined $hunk[$ix]{USE
});
1466 error_msg
"No previous hunk\n";
1470 elsif ($line =~ /^j/) {
1471 if ($other !~ /j/) {
1472 error_msg
"No next hunk\n";
1476 elsif ($other =~ /s/ && $line =~ /^s/) {
1477 my @split = split_hunk
($hunk[$ix]{TEXT
}, $hunk[$ix]{DISPLAY
});
1479 print colored
$header_color, "Split into ",
1480 scalar(@split), " hunks.\n";
1482 splice (@hunk, $ix, 1, @split);
1483 $num = scalar @hunk;
1486 elsif ($other =~ /e/ && $line =~ /^e/) {
1487 my $newhunk = edit_hunk_loop
($head, \
@hunk, $ix);
1488 if (defined $newhunk) {
1489 splice @hunk, $ix, 1, $newhunk;
1493 help_patch_cmd
($other);
1499 last if ($ix >= $num ||
1500 !defined $hunk[$ix]{USE
});
1505 @hunk = coalesce_overlapping_hunks
(@hunk);
1511 push @result, @
{$_->{TEXT
}};
1516 my @patch = reassemble_patch
($head->{TEXT
}, @result);
1517 my $apply_routine = $patch_mode_flavour{APPLY
};
1518 &$apply_routine(@patch);
1527 my @mods = list_modified
('index-only');
1528 @mods = grep { !($_->{BINARY
}) } @mods;
1530 my (@them) = list_and_choose
({ PROMPT
=> 'Review diff',
1532 HEADER
=> $status_head, },
1535 my $reference = is_initial_commit
() ? get_empty_tree
() : 'HEAD';
1536 system(qw(git diff -p --cached), $reference, '--',
1537 map { $_->{VALUE
} } @them);
1546 print colored
$help_color, <<\EOF
;
1547 status
- show paths with changes
1548 update
- add working tree
state to the staged set of changes
1549 revert
- revert staged set of changes back to the HEAD version
1550 patch
- pick hunks
and update selectively
1551 diff
- view diff between HEAD
and index
1552 add untracked
- add contents of untracked files to the staged set of changes
1557 return unless @ARGV;
1558 my $arg = shift @ARGV;
1559 if ($arg =~ /--patch(?:=(.*))?/) {
1561 if ($1 eq 'reset') {
1562 $patch_mode = 'reset_head';
1563 $patch_mode_revision = 'HEAD';
1564 $arg = shift @ARGV or die "missing --";
1566 $patch_mode_revision = $arg;
1567 $patch_mode = ($arg eq 'HEAD' ?
1568 'reset_head' : 'reset_nothead');
1569 $arg = shift @ARGV or die "missing --";
1571 } elsif ($1 eq 'checkout') {
1572 $arg = shift @ARGV or die "missing --";
1574 $patch_mode = 'checkout_index';
1576 $patch_mode_revision = $arg;
1577 $patch_mode = ($arg eq 'HEAD' ?
1578 'checkout_head' : 'checkout_nothead');
1579 $arg = shift @ARGV or die "missing --";
1581 } elsif ($1 eq 'stage' or $1 eq 'stash') {
1583 $arg = shift @ARGV or die "missing --";
1585 die "unknown --patch mode: $1";
1588 $patch_mode = 'stage';
1589 $arg = shift @ARGV or die "missing --";
1591 die "invalid argument $arg, expecting --"
1592 unless $arg eq "--";
1593 %patch_mode_flavour = %{$patch_modes{$patch_mode}};
1595 elsif ($arg ne "--") {
1596 die "invalid argument $arg, expecting --";
1601 my @cmd = ([ 'status', \
&status_cmd
, ],
1602 [ 'update', \
&update_cmd
, ],
1603 [ 'revert', \
&revert_cmd
, ],
1604 [ 'add untracked', \
&add_untracked_cmd
, ],
1605 [ 'patch', \
&patch_update_cmd
, ],
1606 [ 'diff', \
&diff_cmd
, ],
1607 [ 'quit', \
&quit_cmd
, ],
1608 [ 'help', \
&help_cmd
, ],
1611 my ($it) = list_and_choose
({ PROMPT
=> 'What now',
1614 HEADER
=> '*** Commands ***',
1615 ON_EOF
=> \
&quit_cmd
,
1616 IMMEDIATE
=> 1 }, @cmd);