8 binmode(STDOUT
, ":raw");
10 my $repo = Git
->repository();
12 my $menu_use_color = $repo->get_colorbool('color.interactive');
13 my ($prompt_color, $header_color, $help_color) =
15 $repo->get_color('color.interactive.prompt', 'bold blue'),
16 $repo->get_color('color.interactive.header', 'bold'),
17 $repo->get_color('color.interactive.help', 'red bold'),
20 if ($menu_use_color) {
21 my $help_color_spec = ($repo->config('color.interactive.help') or
23 $error_color = $repo->get_color('color.interactive.error',
27 my $diff_use_color = $repo->get_colorbool('color.diff');
28 my ($fraginfo_color) =
30 $repo->get_color('color.diff.frag', 'cyan'),
32 my ($diff_plain_color) =
34 $repo->get_color('color.diff.plain', ''),
36 my ($diff_old_color) =
38 $repo->get_color('color.diff.old', 'red'),
40 my ($diff_new_color) =
42 $repo->get_color('color.diff.new', 'green'),
45 my $normal_color = $repo->get_color("", "reset");
47 my $diff_algorithm = $repo->config('diff.algorithm');
55 if ($repo->config_bool("interactive.singlekey")) {
57 require Term
::ReadKey
;
58 Term
::ReadKey
->import;
63 my $termcap = Term
::Cap
->Tgetent;
64 foreach (values %$termcap) {
65 $term_escapes{$_} = 1 if /^\e/;
73 my $string = join("", @_);
76 # Put a color code at the beginning of each line, a reset at the end
77 # color after newlines that are not at the end of the string
78 $string =~ s/(\n+)(.)/$1$color$2/g;
79 # reset before newlines
80 $string =~ s/(\n+)/$normal_color$1/g;
81 # codes at beginning and end (if necessary):
82 $string =~ s/^/$color/;
83 $string =~ s/$/$normal_color/ unless $string =~ /\n$/;
88 # command line options
90 my $patch_mode_revision;
93 sub apply_patch_for_checkout_commit
;
94 sub apply_patch_for_stash
;
98 DIFF
=> 'diff-files -p',
99 APPLY
=> sub { apply_patch
'apply --cached', @_; },
100 APPLY_CHECK
=> 'apply --cached',
103 PARTICIPLE
=> 'staging',
104 FILTER
=> 'file-only',
108 DIFF
=> 'diff-index -p HEAD',
109 APPLY
=> sub { apply_patch
'apply --cached', @_; },
110 APPLY_CHECK
=> 'apply --cached',
113 PARTICIPLE
=> 'stashing',
118 DIFF
=> 'diff-index -p --cached',
119 APPLY
=> sub { apply_patch
'apply -R --cached', @_; },
120 APPLY_CHECK
=> 'apply -R --cached',
123 PARTICIPLE
=> 'unstaging',
124 FILTER
=> 'index-only',
128 DIFF
=> 'diff-index -R -p --cached',
129 APPLY
=> sub { apply_patch
'apply --cached', @_; },
130 APPLY_CHECK
=> 'apply --cached',
132 TARGET
=> ' to index',
133 PARTICIPLE
=> 'applying',
134 FILTER
=> 'index-only',
137 'checkout_index' => {
138 DIFF
=> 'diff-files -p',
139 APPLY
=> sub { apply_patch
'apply -R', @_; },
140 APPLY_CHECK
=> 'apply -R',
142 TARGET
=> ' from worktree',
143 PARTICIPLE
=> 'discarding',
144 FILTER
=> 'file-only',
148 DIFF
=> 'diff-index -p',
149 APPLY
=> sub { apply_patch_for_checkout_commit
'-R', @_ },
150 APPLY_CHECK
=> 'apply -R',
152 TARGET
=> ' from index and worktree',
153 PARTICIPLE
=> 'discarding',
157 'checkout_nothead' => {
158 DIFF
=> 'diff-index -R -p',
159 APPLY
=> sub { apply_patch_for_checkout_commit
'', @_ },
160 APPLY_CHECK
=> 'apply',
162 TARGET
=> ' to index and worktree',
163 PARTICIPLE
=> 'applying',
169 my %patch_mode_flavour = %{$patch_modes{stage
}};
172 if ($^O
eq 'MSWin32') {
173 my @invalid = grep {m/[":*]/} @_;
174 die "$^O does not support: @invalid\n" if @invalid;
175 my @args = map { m/ /o ?
"\"$_\"": $_ } @_;
179 open($fh, '-|', @_) or die;
184 my ($GIT_DIR) = run_cmd_pipe
(qw(git rev-parse --git-dir));
186 if (!defined $GIT_DIR) {
187 exit(1); # rev-parse would have already said "not a git repo"
204 my ($retval, $remainder);
205 if (!/^\042(.*)\042$/) {
208 ($_, $retval) = ($1, "");
209 while (/^([^\\]*)\\(.*)$/) {
213 if (/^([0-3][0-7][0-7])(.*)$/) {
214 $retval .= chr(oct($1));
218 if (/^([\\\042btnvfr])(.*)$/) {
219 $retval .= $cquote_map{$1};
223 # This is malformed -- just return it as-is for now.
234 open $fh, 'git update-index --refresh |'
237 ;# ignore 'needs update'
247 run_cmd_pipe
(qw(git ls-files --others --exclude-standard --), @ARGV);
250 my $status_fmt = '%12s %12s %s';
251 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
255 sub is_initial_commit
{
256 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
257 unless defined $initial;
263 return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
266 # Returns list of hashes, contents of each of which are:
268 # BINARY: is a binary path
269 # INDEX: is index different from HEAD?
270 # FILE: is file different from index?
271 # INDEX_ADDDEL: is it add/delete between HEAD and index?
272 # FILE_ADDDEL: is it add/delete between index and file?
273 # UNMERGED: is the path unmerged
278 my ($add, $del, $adddel, $file);
285 } run_cmd_pipe
(qw(git ls-files --), @ARGV);
286 return if (!@tracked);
290 if (defined $patch_mode_revision and $patch_mode_revision ne 'HEAD') {
291 $reference = $patch_mode_revision;
292 } elsif (is_initial_commit
()) {
293 $reference = get_empty_tree
();
297 for (run_cmd_pipe
(qw(git diff-index --cached
298 --numstat --summary), $reference,
300 if (($add, $del, $file) =
301 /^([-\d]+) ([-\d]+) (.*)/) {
303 $file = unquote_path
($file);
304 if ($add eq '-' && $del eq '-') {
309 $change = "+$add/-$del";
317 elsif (($adddel, $file) =
318 /^ (create|delete) mode [0-7]+ (.*)$/) {
319 $file = unquote_path
($file);
320 $data{$file}{INDEX_ADDDEL
} = $adddel;
324 for (run_cmd_pipe
(qw(git diff-files --numstat --summary --raw --), @tracked)) {
325 if (($add, $del, $file) =
326 /^([-\d]+) ([-\d]+) (.*)/) {
327 $file = unquote_path
($file);
329 if ($add eq '-' && $del eq '-') {
334 $change = "+$add/-$del";
336 $data{$file}{FILE
} = $change;
338 $data{$file}{BINARY
} = 1;
341 elsif (($adddel, $file) =
342 /^ (create|delete) mode [0-7]+ (.*)$/) {
343 $file = unquote_path
($file);
344 $data{$file}{FILE_ADDDEL
} = $adddel;
346 elsif (/^:[0-7]+ [0-7]+ [0-9a-f]+ [0-9a-f]+ (.) (.*)$/) {
347 $file = unquote_path
($2);
348 if (!exists $data{$file}) {
350 INDEX
=> 'unchanged',
355 $data{$file}{UNMERGED
} = 1;
360 for (sort keys %data) {
364 if ($only eq 'index-only') {
365 next if ($it->{INDEX
} eq 'unchanged');
367 if ($only eq 'file-only') {
368 next if ($it->{FILE
} eq 'nothing');
380 my ($string, @stuff) = @_;
382 for (my $i = 0; $i < @stuff; $i++) {
386 if ((ref $it) eq 'ARRAY') {
394 if ($it =~ /^$string/) {
398 if (defined $hit && defined $found) {
408 # inserts string into trie and updates count for each character
410 my ($trie, $string) = @_;
411 foreach (split //, $string) {
412 $trie = $trie->{$_} ||= {COUNT
=> 0};
417 # returns an array of tuples (prefix, remainder)
418 sub find_unique_prefixes
{
422 # any single prefix exceeding the soft limit is omitted
423 # if any prefix exceeds the hard limit all are omitted
424 # 0 indicates no limit
428 # build a trie modelling all possible options
430 foreach my $print (@stuff) {
431 if ((ref $print) eq 'ARRAY') {
432 $print = $print->[0];
434 elsif ((ref $print) eq 'HASH') {
435 $print = $print->{VALUE
};
437 update_trie
(\
%trie, $print);
438 push @return, $print;
441 # use the trie to find the unique prefixes
442 for (my $i = 0; $i < @return; $i++) {
443 my $ret = $return[$i];
444 my @letters = split //, $ret;
446 my ($prefix, $remainder);
448 for ($j = 0; $j < @letters; $j++) {
449 my $letter = $letters[$j];
450 if ($search{$letter}{COUNT
} == 1) {
451 $prefix = substr $ret, 0, $j + 1;
452 $remainder = substr $ret, $j + 1;
456 my $prefix = substr $ret, 0, $j;
458 if ($hard_limit && $j + 1 > $hard_limit);
460 %search = %{$search{$letter}};
462 if (ord($letters[0]) > 127 ||
463 ($soft_limit && $j + 1 > $soft_limit)) {
467 $return[$i] = [$prefix, $remainder];
472 # filters out prefixes which have special meaning to list_and_choose()
473 sub is_valid_prefix
{
475 return (defined $prefix) &&
476 !($prefix =~ /[\s,]/) && # separators
477 !($prefix =~ /^-/) && # deselection
478 !($prefix =~ /^\d+/) && # selection
479 ($prefix ne '*') && # "all" wildcard
480 ($prefix ne '?'); # prompt help
483 # given a prefix/remainder tuple return a string with the prefix highlighted
484 # for now use square brackets; later might use ANSI colors (underline, bold)
485 sub highlight_prefix
{
487 my $remainder = shift;
489 if (!defined $prefix) {
493 if (!is_valid_prefix
($prefix)) {
494 return "$prefix$remainder";
497 if (!$menu_use_color) {
498 return "[$prefix]$remainder";
501 return "$prompt_color$prefix$normal_color$remainder";
505 print STDERR colored
$error_color, @_;
508 sub list_and_choose
{
509 my ($opts, @stuff) = @_;
510 my (@chosen, @return);
512 my @prefixes = find_unique_prefixes
(@stuff) unless $opts->{LIST_ONLY
};
518 if ($opts->{HEADER
}) {
519 if (!$opts->{LIST_FLAT
}) {
522 print colored
$header_color, "$opts->{HEADER}\n";
524 for ($i = 0; $i < @stuff; $i++) {
525 my $chosen = $chosen[$i] ?
'*' : ' ';
526 my $print = $stuff[$i];
527 my $ref = ref $print;
528 my $highlighted = highlight_prefix
(@
{$prefixes[$i]})
530 if ($ref eq 'ARRAY') {
531 $print = $highlighted || $print->[0];
533 elsif ($ref eq 'HASH') {
534 my $value = $highlighted || $print->{VALUE
};
535 $print = sprintf($status_fmt,
541 $print = $highlighted || $print;
543 printf("%s%2d: %s", $chosen, $i+1, $print);
544 if (($opts->{LIST_FLAT
}) &&
545 (($i + 1) % ($opts->{LIST_FLAT
}))) {
558 return if ($opts->{LIST_ONLY
});
560 print colored
$prompt_color, $opts->{PROMPT
};
561 if ($opts->{SINGLETON
}) {
570 $opts->{ON_EOF
}->() if $opts->{ON_EOF
};
577 singleton_prompt_help_cmd
() :
581 for my $choice (split(/[\s,]+/, $line)) {
585 # Input that begins with '-'; unchoose
586 if ($choice =~ s/^-//) {
589 # A range can be specified like 5-7 or 5-.
590 if ($choice =~ /^(\d+)-(\d*)$/) {
591 ($bottom, $top) = ($1, length($2) ?
$2 : 1 + @stuff);
593 elsif ($choice =~ /^\d+$/) {
594 $bottom = $top = $choice;
596 elsif ($choice eq '*') {
601 $bottom = $top = find_unique
($choice, @stuff);
602 if (!defined $bottom) {
603 error_msg
"Huh ($choice)?\n";
607 if ($opts->{SINGLETON
} && $bottom != $top) {
608 error_msg
"Huh ($choice)?\n";
611 for ($i = $bottom-1; $i <= $top-1; $i++) {
612 next if (@stuff <= $i || $i < 0);
613 $chosen[$i] = $choose;
616 last if ($opts->{IMMEDIATE
} || $line eq '*');
618 for ($i = 0; $i < @stuff; $i++) {
620 push @return, $stuff[$i];
626 sub singleton_prompt_help_cmd
{
627 print colored
$help_color, <<\EOF
;
629 1 - select a numbered item
630 foo
- select item based on unique prefix
631 - (empty
) select nothing
635 sub prompt_help_cmd
{
636 print colored
$help_color, <<\EOF
;
638 1 - select a single item
639 3-5 - select a range of items
640 2-3,6-9 - select multiple ranges
641 foo
- select item based on unique prefix
642 -... - unselect specified items
644 - (empty
) finish selecting
649 list_and_choose
({ LIST_ONLY
=> 1, HEADER
=> $status_head },
659 print "$cnt paths\n";
667 my @mods = list_modified
('file-only');
670 my @update = list_and_choose
({ PROMPT
=> 'Update',
671 HEADER
=> $status_head, },
674 system(qw(git update-index --add --remove --),
675 map { $_->{VALUE
} } @update);
676 say_n_paths
('updated', @update);
682 my @update = list_and_choose
({ PROMPT
=> 'Revert',
683 HEADER
=> $status_head, },
686 if (is_initial_commit
()) {
687 system(qw(git rm --cached),
688 map { $_->{VALUE
} } @update);
691 my @lines = run_cmd_pipe
(qw(git ls-tree HEAD --),
692 map { $_->{VALUE
} } @update);
694 open $fh, '| git update-index --index-info'
701 if ($_->{INDEX_ADDDEL
} &&
702 $_->{INDEX_ADDDEL
} eq 'create') {
703 system(qw(git update-index --force-remove --),
705 print "note: $_->{VALUE} is untracked now.\n";
710 say_n_paths
('reverted', @update);
715 sub add_untracked_cmd
{
716 my @add = list_and_choose
({ PROMPT
=> 'Add untracked' },
719 system(qw(git update-index --add --), @add);
720 say_n_paths
('added', @add);
728 open $fh, '| git ' . $cmd . " --recount --allow-overlap";
735 my @diff_cmd = split(" ", $patch_mode_flavour{DIFF
});
736 if (defined $diff_algorithm) {
737 splice @diff_cmd, 1, 0, "--diff-algorithm=${diff_algorithm}";
739 if (defined $patch_mode_revision) {
740 push @diff_cmd, $patch_mode_revision;
742 my @diff = run_cmd_pipe
("git", @diff_cmd, "--", $path);
744 if ($diff_use_color) {
745 @colored = run_cmd_pipe
("git", @diff_cmd, qw(--color --), $path);
747 my (@hunk) = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'header' };
749 for (my $i = 0; $i < @diff; $i++) {
750 if ($diff[$i] =~ /^@@ /) {
751 push @hunk, { TEXT
=> [], DISPLAY
=> [],
754 push @
{$hunk[-1]{TEXT
}}, $diff[$i];
755 push @
{$hunk[-1]{DISPLAY
}},
756 ($diff_use_color ?
$colored[$i] : $diff[$i]);
761 sub parse_diff_header
{
764 my $head = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'header' };
765 my $mode = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'mode' };
766 my $deletion = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'deletion' };
768 for (my $i = 0; $i < @
{$src->{TEXT
}}; $i++) {
770 $src->{TEXT
}->[$i] =~ /^(old|new) mode (\d+)$/ ?
$mode :
771 $src->{TEXT
}->[$i] =~ /^deleted file/ ?
$deletion :
773 push @
{$dest->{TEXT
}}, $src->{TEXT
}->[$i];
774 push @
{$dest->{DISPLAY
}}, $src->{DISPLAY
}->[$i];
776 return ($head, $mode, $deletion);
779 sub hunk_splittable
{
782 my @s = split_hunk
($text);
786 sub parse_hunk_header
{
788 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
789 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
790 $o_cnt = 1 unless defined $o_cnt;
791 $n_cnt = 1 unless defined $n_cnt;
792 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
796 my ($text, $display) = @_;
798 if (!defined $display) {
801 # If there are context lines in the middle of a hunk,
802 # it can be split, but we would need to take care of
805 my ($o_ofs, undef, $n_ofs) = parse_hunk_header
($text->[0]);
810 my $next_hunk_start = undef;
811 my $i = $hunk_start - 1;
825 while (++$i < @
$text) {
826 my $line = $text->[$i];
827 my $display = $display->[$i];
829 if ($this->{ADDDEL
} &&
830 !defined $next_hunk_start) {
831 # We have seen leading context and
832 # adds/dels and then here is another
833 # context, which is trailing for this
834 # split hunk and leading for the next
836 $next_hunk_start = $i;
838 push @
{$this->{TEXT
}}, $line;
839 push @
{$this->{DISPLAY
}}, $display;
842 if (defined $next_hunk_start) {
849 if (defined $next_hunk_start) {
850 # We are done with the current hunk and
851 # this is the first real change for the
853 $hunk_start = $next_hunk_start;
854 $o_ofs = $this->{OLD
} + $this->{OCNT
};
855 $n_ofs = $this->{NEW
} + $this->{NCNT
};
856 $o_ofs -= $this->{POSTCTX
};
857 $n_ofs -= $this->{POSTCTX
};
861 push @
{$this->{TEXT
}}, $line;
862 push @
{$this->{DISPLAY
}}, $display;
876 for my $hunk (@split) {
877 $o_ofs = $hunk->{OLD
};
878 $n_ofs = $hunk->{NEW
};
879 my $o_cnt = $hunk->{OCNT
};
880 my $n_cnt = $hunk->{NCNT
};
882 my $head = ("@@ -$o_ofs" .
883 (($o_cnt != 1) ?
",$o_cnt" : '') .
885 (($n_cnt != 1) ?
",$n_cnt" : '') .
887 my $display_head = $head;
888 unshift @
{$hunk->{TEXT
}}, $head;
889 if ($diff_use_color) {
890 $display_head = colored
($fraginfo_color, $head);
892 unshift @
{$hunk->{DISPLAY
}}, $display_head;
897 sub find_last_o_ctx
{
899 my $text = $it->{TEXT
};
900 my ($o_ofs, $o_cnt) = parse_hunk_header
($text->[0]);
902 my $last_o_ctx = $o_ofs + $o_cnt;
904 my $line = $text->[$i];
915 my ($prev, $this) = @_;
916 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
917 parse_hunk_header
($prev->{TEXT
}[0]);
918 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
919 parse_hunk_header
($this->{TEXT
}[0]);
921 my (@line, $i, $ofs, $o_cnt, $n_cnt);
924 for ($i = 1; $i < @
{$prev->{TEXT
}}; $i++) {
925 my $line = $prev->{TEXT
}[$i];
926 if ($line =~ /^\+/) {
932 last if ($o1_ofs <= $ofs);
942 for ($i = 1; $i < @
{$this->{TEXT
}}; $i++) {
943 my $line = $this->{TEXT
}[$i];
944 if ($line =~ /^\+/) {
956 my $head = ("@@ -$o0_ofs" .
957 (($o_cnt != 1) ?
",$o_cnt" : '') .
959 (($n_cnt != 1) ?
",$n_cnt" : '') .
961 @
{$prev->{TEXT
}} = ($head, @line);
964 sub coalesce_overlapping_hunks
{
968 my ($last_o_ctx, $last_was_dirty);
970 for (grep { $_->{USE
} } @in) {
971 if ($_->{TYPE
} ne 'hunk') {
975 my $text = $_->{TEXT
};
976 my ($o_ofs) = parse_hunk_header
($text->[0]);
977 if (defined $last_o_ctx &&
978 $o_ofs <= $last_o_ctx &&
981 merge_hunk
($out[-1], $_);
986 $last_o_ctx = find_last_o_ctx
($out[-1]);
987 $last_was_dirty = $_->{DIRTY
};
992 sub reassemble_patch
{
996 # Include everything in the header except the beginning of the diff.
997 push @patch, (grep { !/^[-+]{3}/ } @
$head);
999 # Then include any headers from the hunk lines, which must
1000 # come before any actual hunk.
1001 while (@_ && $_[0] !~ /^@/) {
1005 # Then begin the diff.
1006 push @patch, grep { /^[-+]{3}/ } @
$head;
1008 # And then the actual hunks.
1016 colored
((/^@/ ?
$fraginfo_color :
1017 /^\+/ ?
$diff_new_color :
1018 /^-/ ?
$diff_old_color :
1024 sub edit_hunk_manually
{
1027 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
1029 open $fh, '>', $hunkfile
1030 or die "failed to open hunk edit file for writing: " . $!;
1031 print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
1032 print $fh @
$oldtext;
1033 my $participle = $patch_mode_flavour{PARTICIPLE
};
1034 my $is_reverse = $patch_mode_flavour{IS_REVERSE
};
1035 my ($remove_plus, $remove_minus) = $is_reverse ?
('-', '+') : ('+', '-');
1038 # To remove '$remove_minus' lines, make them ' ' lines (context).
1039 # To remove '$remove_plus' lines, delete them.
1040 # Lines starting with # will be removed.
1042 # If the patch applies cleanly, the edited hunk will immediately be
1043 # marked for $participle. If it does not apply cleanly, you will be given
1044 # an opportunity to edit again. If all lines of the hunk are removed,
1045 # then the edit is aborted and the hunk is left unchanged.
1049 chomp(my $editor = run_cmd_pipe
(qw(git var GIT_EDITOR)));
1050 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
1056 open $fh, '<', $hunkfile
1057 or die "failed to open hunk edit file for reading: " . $!;
1058 my @newtext = grep { !/^#/ } <$fh>;
1062 # Abort if nothing remains
1063 if (!grep { /\S/ } @newtext) {
1067 # Reinsert the first hunk header if the user accidentally deleted it
1068 if ($newtext[0] !~ /^@/) {
1069 unshift @newtext, $oldtext->[0];
1075 return run_git_apply
($patch_mode_flavour{APPLY_CHECK
} . ' --check',
1076 map { @
{$_->{TEXT
}} } @_);
1079 sub _restore_terminal_and_die
{
1085 sub prompt_single_character
{
1087 local $SIG{TERM
} = \
&_restore_terminal_and_die
;
1088 local $SIG{INT
} = \
&_restore_terminal_and_die
;
1090 my $key = ReadKey
0;
1092 if ($use_termcap and $key eq "\e") {
1093 while (!defined $term_escapes{$key}) {
1094 my $next = ReadKey
0.5;
1095 last if (!defined $next);
1100 print "$key" if defined $key;
1111 print colored
$prompt_color, $prompt;
1112 my $line = prompt_single_character
;
1113 return 0 if $line =~ /^n/i;
1114 return 1 if $line =~ /^y/i;
1118 sub edit_hunk_loop
{
1119 my ($head, $hunk, $ix) = @_;
1120 my $text = $hunk->[$ix]->{TEXT
};
1123 $text = edit_hunk_manually
($text);
1124 if (!defined $text) {
1129 TYPE
=> $hunk->[$ix]->{TYPE
},
1133 if (diff_applies
($head,
1136 @
{$hunk}[$ix+1..$#{$hunk}])) {
1137 $newhunk->{DISPLAY
} = [color_diff
(@
{$text})];
1142 'Your edited hunk does not apply. Edit again '
1143 . '(saying "no" discards!) [y/n]? '
1149 sub help_patch_cmd
{
1150 my $verb = lc $patch_mode_flavour{VERB
};
1151 my $target = $patch_mode_flavour{TARGET
};
1152 print colored
$help_color, <<EOF ;
1153 y - $verb this hunk$target
1154 n - do not $verb this hunk$target
1155 q - quit; do not $verb this hunk nor any of the remaining ones
1156 a - $verb this hunk and all later hunks in the file
1157 d - do not $verb this hunk nor any of the later hunks in the file
1158 g - select a hunk to go to
1159 / - search for a hunk matching the given regex
1160 j - leave this hunk undecided, see next undecided hunk
1161 J - leave this hunk undecided, see next hunk
1162 k - leave this hunk undecided, see previous undecided hunk
1163 K - leave this hunk undecided, see previous hunk
1164 s - split the current hunk into smaller hunks
1165 e - manually edit the current hunk
1172 my $ret = run_git_apply
$cmd, @_;
1179 sub apply_patch_for_checkout_commit
{
1180 my $reverse = shift;
1181 my $applies_index = run_git_apply
'apply '.$reverse.' --cached --check', @_;
1182 my $applies_worktree = run_git_apply
'apply '.$reverse.' --check', @_;
1184 if ($applies_worktree && $applies_index) {
1185 run_git_apply
'apply '.$reverse.' --cached', @_;
1186 run_git_apply
'apply '.$reverse, @_;
1188 } elsif (!$applies_index) {
1189 print colored
$error_color, "The selected hunks do not apply to the index!\n";
1190 if (prompt_yesno
"Apply them to the worktree anyway? ") {
1191 return run_git_apply
'apply '.$reverse, @_;
1193 print colored
$error_color, "Nothing was applied.\n";
1202 sub patch_update_cmd
{
1203 my @all_mods = list_modified
($patch_mode_flavour{FILTER
});
1204 error_msg
"ignoring unmerged: $_->{VALUE}\n"
1205 for grep { $_->{UNMERGED
} } @all_mods;
1206 @all_mods = grep { !$_->{UNMERGED
} } @all_mods;
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 with 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]);
1273 sub patch_update_file
{
1277 my ($head, @hunk) = parse_diff
($path);
1278 ($head, my $mode, my $deletion) = parse_diff_header
($head);
1279 for (@
{$head->{DISPLAY
}}) {
1283 if (@
{$mode->{TEXT
}}) {
1284 unshift @hunk, $mode;
1286 if (@
{$deletion->{TEXT
}}) {
1287 foreach my $hunk (@hunk) {
1288 push @
{$deletion->{TEXT
}}, @
{$hunk->{TEXT
}};
1289 push @
{$deletion->{DISPLAY
}}, @
{$hunk->{DISPLAY
}};
1291 @hunk = ($deletion);
1294 $num = scalar @hunk;
1298 my ($prev, $next, $other, $undecided, $i);
1304 for ($i = 0; $i < $ix; $i++) {
1305 if (!defined $hunk[$i]{USE
}) {
1314 for ($i = $ix + 1; $i < $num; $i++) {
1315 if (!defined $hunk[$i]{USE
}) {
1321 if ($ix < $num - 1) {
1327 for ($i = 0; $i < $num; $i++) {
1328 if (!defined $hunk[$i]{USE
}) {
1333 last if (!$undecided);
1335 if ($hunk[$ix]{TYPE
} eq 'hunk' &&
1336 hunk_splittable
($hunk[$ix]{TEXT
})) {
1339 if ($hunk[$ix]{TYPE
} eq 'hunk') {
1342 for (@
{$hunk[$ix]{DISPLAY
}}) {
1345 print colored
$prompt_color, $patch_mode_flavour{VERB
},
1346 ($hunk[$ix]{TYPE
} eq 'mode' ?
' mode change' :
1347 $hunk[$ix]{TYPE
} eq 'deletion' ?
' deletion' :
1349 $patch_mode_flavour{TARGET
},
1350 " [y,n,q,a,d,/$other,?]? ";
1351 my $line = prompt_single_character
;
1353 if ($line =~ /^y/i) {
1354 $hunk[$ix]{USE
} = 1;
1356 elsif ($line =~ /^n/i) {
1357 $hunk[$ix]{USE
} = 0;
1359 elsif ($line =~ /^a/i) {
1360 while ($ix < $num) {
1361 if (!defined $hunk[$ix]{USE
}) {
1362 $hunk[$ix]{USE
} = 1;
1368 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1370 my $no = $ix > 10 ?
$ix - 10 : 0;
1371 while ($response eq '') {
1373 $no = display_hunks
(\
@hunk, $no);
1375 $extra = " (<ret> to see more)";
1377 print "go to which hunk$extra? ";
1378 $response = <STDIN
>;
1379 if (!defined $response) {
1384 if ($response !~ /^\s*\d+\s*$/) {
1385 error_msg
"Invalid number: '$response'\n";
1386 } elsif (0 < $response && $response <= $num) {
1387 $ix = $response - 1;
1389 error_msg
"Sorry, only $num hunks available.\n";
1393 elsif ($line =~ /^d/i) {
1394 while ($ix < $num) {
1395 if (!defined $hunk[$ix]{USE
}) {
1396 $hunk[$ix]{USE
} = 0;
1402 elsif ($line =~ /^q/i) {
1403 for ($i = 0; $i < $num; $i++) {
1404 if (!defined $hunk[$i]{USE
}) {
1411 elsif ($line =~ m
|^/(.*)|) {
1414 print colored
$prompt_color, "search for regex? ";
1416 if (defined $regex) {
1422 $search_string = qr{$regex}m;
1425 my ($err,$exp) = ($@
, $1);
1426 $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1427 error_msg
"Malformed search regexp $exp: $err\n";
1432 my $text = join ("", @
{$hunk[$iy]{TEXT
}});
1433 last if ($text =~ $search_string);
1435 $iy = 0 if ($iy >= $num);
1437 error_msg
"No hunk matches the given pattern\n";
1444 elsif ($line =~ /^K/) {
1445 if ($other =~ /K/) {
1449 error_msg
"No previous hunk\n";
1453 elsif ($line =~ /^J/) {
1454 if ($other =~ /J/) {
1458 error_msg
"No next hunk\n";
1462 elsif ($line =~ /^k/) {
1463 if ($other =~ /k/) {
1467 !defined $hunk[$ix]{USE
});
1471 error_msg
"No previous hunk\n";
1475 elsif ($line =~ /^j/) {
1476 if ($other !~ /j/) {
1477 error_msg
"No next hunk\n";
1481 elsif ($other =~ /s/ && $line =~ /^s/) {
1482 my @split = split_hunk
($hunk[$ix]{TEXT
}, $hunk[$ix]{DISPLAY
});
1484 print colored
$header_color, "Split into ",
1485 scalar(@split), " hunks.\n";
1487 splice (@hunk, $ix, 1, @split);
1488 $num = scalar @hunk;
1491 elsif ($other =~ /e/ && $line =~ /^e/) {
1492 my $newhunk = edit_hunk_loop
($head, \
@hunk, $ix);
1493 if (defined $newhunk) {
1494 splice @hunk, $ix, 1, $newhunk;
1498 help_patch_cmd
($other);
1504 last if ($ix >= $num ||
1505 !defined $hunk[$ix]{USE
});
1510 @hunk = coalesce_overlapping_hunks
(@hunk);
1516 push @result, @
{$_->{TEXT
}};
1521 my @patch = reassemble_patch
($head->{TEXT
}, @result);
1522 my $apply_routine = $patch_mode_flavour{APPLY
};
1523 &$apply_routine(@patch);
1532 my @mods = list_modified
('index-only');
1533 @mods = grep { !($_->{BINARY
}) } @mods;
1535 my (@them) = list_and_choose
({ PROMPT
=> 'Review diff',
1537 HEADER
=> $status_head, },
1540 my $reference = is_initial_commit
() ? get_empty_tree
() : 'HEAD';
1541 system(qw(git diff -p --cached), $reference, '--',
1542 map { $_->{VALUE
} } @them);
1551 print colored
$help_color, <<\EOF
;
1552 status
- show paths with changes
1553 update
- add working tree
state to the staged set of changes
1554 revert
- revert staged set of changes back to the HEAD version
1555 patch
- pick hunks
and update selectively
1556 diff
- view diff between HEAD
and index
1557 add untracked
- add contents of untracked files to the staged set of changes
1562 return unless @ARGV;
1563 my $arg = shift @ARGV;
1564 if ($arg =~ /--patch(?:=(.*))?/) {
1566 if ($1 eq 'reset') {
1567 $patch_mode = 'reset_head';
1568 $patch_mode_revision = 'HEAD';
1569 $arg = shift @ARGV or die "missing --";
1571 $patch_mode_revision = $arg;
1572 $patch_mode = ($arg eq 'HEAD' ?
1573 'reset_head' : 'reset_nothead');
1574 $arg = shift @ARGV or die "missing --";
1576 } elsif ($1 eq 'checkout') {
1577 $arg = shift @ARGV or die "missing --";
1579 $patch_mode = 'checkout_index';
1581 $patch_mode_revision = $arg;
1582 $patch_mode = ($arg eq 'HEAD' ?
1583 'checkout_head' : 'checkout_nothead');
1584 $arg = shift @ARGV or die "missing --";
1586 } elsif ($1 eq 'stage' or $1 eq 'stash') {
1588 $arg = shift @ARGV or die "missing --";
1590 die "unknown --patch mode: $1";
1593 $patch_mode = 'stage';
1594 $arg = shift @ARGV or die "missing --";
1596 die "invalid argument $arg, expecting --"
1597 unless $arg eq "--";
1598 %patch_mode_flavour = %{$patch_modes{$patch_mode}};
1600 elsif ($arg ne "--") {
1601 die "invalid argument $arg, expecting --";
1606 my @cmd = ([ 'status', \
&status_cmd
, ],
1607 [ 'update', \
&update_cmd
, ],
1608 [ 'revert', \
&revert_cmd
, ],
1609 [ 'add untracked', \
&add_untracked_cmd
, ],
1610 [ 'patch', \
&patch_update_cmd
, ],
1611 [ 'diff', \
&diff_cmd
, ],
1612 [ 'quit', \
&quit_cmd
, ],
1613 [ 'help', \
&help_cmd
, ],
1616 my ($it) = list_and_choose
({ PROMPT
=> 'What now',
1619 HEADER
=> '*** Commands ***',
1620 ON_EOF
=> \
&quit_cmd
,
1621 IMMEDIATE
=> 1 }, @cmd);