8 binmode(STDOUT
, ":raw");
10 my $repo = Git
->repository();
12 my $menu_use_color = $repo->get_colorbool('color.interactive');
13 my ($prompt_color, $header_color, $help_color) =
15 $repo->get_color('color.interactive.prompt', 'bold blue'),
16 $repo->get_color('color.interactive.header', 'bold'),
17 $repo->get_color('color.interactive.help', 'red bold'),
20 if ($menu_use_color) {
21 my $help_color_spec = ($repo->config('color.interactive.help') or
23 $error_color = $repo->get_color('color.interactive.error',
27 my $diff_use_color = $repo->get_colorbool('color.diff');
28 my ($fraginfo_color) =
30 $repo->get_color('color.diff.frag', 'cyan'),
32 my ($diff_plain_color) =
34 $repo->get_color('color.diff.plain', ''),
36 my ($diff_old_color) =
38 $repo->get_color('color.diff.old', 'red'),
40 my ($diff_new_color) =
42 $repo->get_color('color.diff.new', 'green'),
45 my $normal_color = $repo->get_color("", "reset");
47 my $diff_algorithm = $repo->config('diff.algorithm');
48 my $diff_filter = $repo->config('interactive.difffilter');
56 if ($repo->config_bool("interactive.singlekey")) {
58 require Term
::ReadKey
;
59 Term
::ReadKey
->import;
63 print STDERR
"missing Term::ReadKey, disabling interactive.singlekey\n";
67 my $termcap = Term
::Cap
->Tgetent;
68 foreach (values %$termcap) {
69 $term_escapes{$_} = 1 if /^\e/;
77 my $string = join("", @_);
80 # Put a color code at the beginning of each line, a reset at the end
81 # color after newlines that are not at the end of the string
82 $string =~ s/(\n+)(.)/$1$color$2/g;
83 # reset before newlines
84 $string =~ s/(\n+)/$normal_color$1/g;
85 # codes at beginning and end (if necessary):
86 $string =~ s/^/$color/;
87 $string =~ s/$/$normal_color/ unless $string =~ /\n$/;
92 # command line options
94 my $patch_mode_revision;
97 sub apply_patch_for_checkout_commit
;
98 sub apply_patch_for_stash
;
102 DIFF
=> 'diff-files -p',
103 APPLY
=> sub { apply_patch
'apply --cached', @_; },
104 APPLY_CHECK
=> 'apply --cached',
107 PARTICIPLE
=> 'staging',
108 FILTER
=> 'file-only',
112 DIFF
=> 'diff-index -p HEAD',
113 APPLY
=> sub { apply_patch
'apply --cached', @_; },
114 APPLY_CHECK
=> 'apply --cached',
117 PARTICIPLE
=> 'stashing',
122 DIFF
=> 'diff-index -p --cached',
123 APPLY
=> sub { apply_patch
'apply -R --cached', @_; },
124 APPLY_CHECK
=> 'apply -R --cached',
127 PARTICIPLE
=> 'unstaging',
128 FILTER
=> 'index-only',
132 DIFF
=> 'diff-index -R -p --cached',
133 APPLY
=> sub { apply_patch
'apply --cached', @_; },
134 APPLY_CHECK
=> 'apply --cached',
136 TARGET
=> ' to index',
137 PARTICIPLE
=> 'applying',
138 FILTER
=> 'index-only',
141 'checkout_index' => {
142 DIFF
=> 'diff-files -p',
143 APPLY
=> sub { apply_patch
'apply -R', @_; },
144 APPLY_CHECK
=> 'apply -R',
146 TARGET
=> ' from worktree',
147 PARTICIPLE
=> 'discarding',
148 FILTER
=> 'file-only',
152 DIFF
=> 'diff-index -p',
153 APPLY
=> sub { apply_patch_for_checkout_commit
'-R', @_ },
154 APPLY_CHECK
=> 'apply -R',
156 TARGET
=> ' from index and worktree',
157 PARTICIPLE
=> 'discarding',
161 'checkout_nothead' => {
162 DIFF
=> 'diff-index -R -p',
163 APPLY
=> sub { apply_patch_for_checkout_commit
'', @_ },
164 APPLY_CHECK
=> 'apply',
166 TARGET
=> ' to index and worktree',
167 PARTICIPLE
=> 'applying',
173 my %patch_mode_flavour = %{$patch_modes{stage
}};
176 if ($^O
eq 'MSWin32') {
177 my @invalid = grep {m/[":*]/} @_;
178 die "$^O does not support: @invalid\n" if @invalid;
179 my @args = map { m/ /o ?
"\"$_\"": $_ } @_;
183 open($fh, '-|', @_) or die;
188 my ($GIT_DIR) = run_cmd_pipe
(qw(git rev-parse --git-dir));
190 if (!defined $GIT_DIR) {
191 exit(1); # rev-parse would have already said "not a git repo"
208 my ($retval, $remainder);
209 if (!/^\042(.*)\042$/) {
212 ($_, $retval) = ($1, "");
213 while (/^([^\\]*)\\(.*)$/) {
217 if (/^([0-3][0-7][0-7])(.*)$/) {
218 $retval .= chr(oct($1));
222 if (/^([\\\042btnvfr])(.*)$/) {
223 $retval .= $cquote_map{$1};
227 # This is malformed -- just return it as-is for now.
238 open $fh, 'git update-index --refresh |'
241 ;# ignore 'needs update'
251 run_cmd_pipe
(qw(git ls-files --others --exclude-standard --), @ARGV);
254 my $status_fmt = '%12s %12s %s';
255 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
259 sub is_initial_commit
{
260 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
261 unless defined $initial;
267 return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
270 sub get_diff_reference
{
272 if (defined $ref and $ref ne 'HEAD') {
274 } elsif (is_initial_commit
()) {
275 return get_empty_tree
();
281 # Returns list of hashes, contents of each of which are:
283 # BINARY: is a binary path
284 # INDEX: is index different from HEAD?
285 # FILE: is file different from index?
286 # INDEX_ADDDEL: is it add/delete between HEAD and index?
287 # FILE_ADDDEL: is it add/delete between index and file?
288 # UNMERGED: is the path unmerged
293 my ($add, $del, $adddel, $file);
300 } run_cmd_pipe
(qw(git ls-files --), @ARGV);
301 return if (!@tracked);
304 my $reference = get_diff_reference
($patch_mode_revision);
305 for (run_cmd_pipe
(qw(git diff-index --cached
306 --numstat --summary), $reference,
308 if (($add, $del, $file) =
309 /^([-\d]+) ([-\d]+) (.*)/) {
311 $file = unquote_path
($file);
312 if ($add eq '-' && $del eq '-') {
317 $change = "+$add/-$del";
325 elsif (($adddel, $file) =
326 /^ (create|delete) mode [0-7]+ (.*)$/) {
327 $file = unquote_path
($file);
328 $data{$file}{INDEX_ADDDEL
} = $adddel;
332 for (run_cmd_pipe
(qw(git diff-files --numstat --summary --raw --), @tracked)) {
333 if (($add, $del, $file) =
334 /^([-\d]+) ([-\d]+) (.*)/) {
335 $file = unquote_path
($file);
337 if ($add eq '-' && $del eq '-') {
342 $change = "+$add/-$del";
344 $data{$file}{FILE
} = $change;
346 $data{$file}{BINARY
} = 1;
349 elsif (($adddel, $file) =
350 /^ (create|delete) mode [0-7]+ (.*)$/) {
351 $file = unquote_path
($file);
352 $data{$file}{FILE_ADDDEL
} = $adddel;
354 elsif (/^:[0-7]+ [0-7]+ [0-9a-f]+ [0-9a-f]+ (.) (.*)$/) {
355 $file = unquote_path
($2);
356 if (!exists $data{$file}) {
358 INDEX
=> 'unchanged',
363 $data{$file}{UNMERGED
} = 1;
368 for (sort keys %data) {
372 if ($only eq 'index-only') {
373 next if ($it->{INDEX
} eq 'unchanged');
375 if ($only eq 'file-only') {
376 next if ($it->{FILE
} eq 'nothing');
388 my ($string, @stuff) = @_;
390 for (my $i = 0; $i < @stuff; $i++) {
394 if ((ref $it) eq 'ARRAY') {
402 if ($it =~ /^$string/) {
406 if (defined $hit && defined $found) {
416 # inserts string into trie and updates count for each character
418 my ($trie, $string) = @_;
419 foreach (split //, $string) {
420 $trie = $trie->{$_} ||= {COUNT
=> 0};
425 # returns an array of tuples (prefix, remainder)
426 sub find_unique_prefixes
{
430 # any single prefix exceeding the soft limit is omitted
431 # if any prefix exceeds the hard limit all are omitted
432 # 0 indicates no limit
436 # build a trie modelling all possible options
438 foreach my $print (@stuff) {
439 if ((ref $print) eq 'ARRAY') {
440 $print = $print->[0];
442 elsif ((ref $print) eq 'HASH') {
443 $print = $print->{VALUE
};
445 update_trie
(\
%trie, $print);
446 push @return, $print;
449 # use the trie to find the unique prefixes
450 for (my $i = 0; $i < @return; $i++) {
451 my $ret = $return[$i];
452 my @letters = split //, $ret;
454 my ($prefix, $remainder);
456 for ($j = 0; $j < @letters; $j++) {
457 my $letter = $letters[$j];
458 if ($search{$letter}{COUNT
} == 1) {
459 $prefix = substr $ret, 0, $j + 1;
460 $remainder = substr $ret, $j + 1;
464 my $prefix = substr $ret, 0, $j;
466 if ($hard_limit && $j + 1 > $hard_limit);
468 %search = %{$search{$letter}};
470 if (ord($letters[0]) > 127 ||
471 ($soft_limit && $j + 1 > $soft_limit)) {
475 $return[$i] = [$prefix, $remainder];
480 # filters out prefixes which have special meaning to list_and_choose()
481 sub is_valid_prefix
{
483 return (defined $prefix) &&
484 !($prefix =~ /[\s,]/) && # separators
485 !($prefix =~ /^-/) && # deselection
486 !($prefix =~ /^\d+/) && # selection
487 ($prefix ne '*') && # "all" wildcard
488 ($prefix ne '?'); # prompt help
491 # given a prefix/remainder tuple return a string with the prefix highlighted
492 # for now use square brackets; later might use ANSI colors (underline, bold)
493 sub highlight_prefix
{
495 my $remainder = shift;
497 if (!defined $prefix) {
501 if (!is_valid_prefix
($prefix)) {
502 return "$prefix$remainder";
505 if (!$menu_use_color) {
506 return "[$prefix]$remainder";
509 return "$prompt_color$prefix$normal_color$remainder";
513 print STDERR colored
$error_color, @_;
516 sub list_and_choose
{
517 my ($opts, @stuff) = @_;
518 my (@chosen, @return);
523 my @prefixes = find_unique_prefixes
(@stuff) unless $opts->{LIST_ONLY
};
529 if ($opts->{HEADER
}) {
530 if (!$opts->{LIST_FLAT
}) {
533 print colored
$header_color, "$opts->{HEADER}\n";
535 for ($i = 0; $i < @stuff; $i++) {
536 my $chosen = $chosen[$i] ?
'*' : ' ';
537 my $print = $stuff[$i];
538 my $ref = ref $print;
539 my $highlighted = highlight_prefix
(@
{$prefixes[$i]})
541 if ($ref eq 'ARRAY') {
542 $print = $highlighted || $print->[0];
544 elsif ($ref eq 'HASH') {
545 my $value = $highlighted || $print->{VALUE
};
546 $print = sprintf($status_fmt,
552 $print = $highlighted || $print;
554 printf("%s%2d: %s", $chosen, $i+1, $print);
555 if (($opts->{LIST_FLAT
}) &&
556 (($i + 1) % ($opts->{LIST_FLAT
}))) {
569 return if ($opts->{LIST_ONLY
});
571 print colored
$prompt_color, $opts->{PROMPT
};
572 if ($opts->{SINGLETON
}) {
581 $opts->{ON_EOF
}->() if $opts->{ON_EOF
};
588 singleton_prompt_help_cmd
() :
592 for my $choice (split(/[\s,]+/, $line)) {
596 # Input that begins with '-'; unchoose
597 if ($choice =~ s/^-//) {
600 # A range can be specified like 5-7 or 5-.
601 if ($choice =~ /^(\d+)-(\d*)$/) {
602 ($bottom, $top) = ($1, length($2) ?
$2 : 1 + @stuff);
604 elsif ($choice =~ /^\d+$/) {
605 $bottom = $top = $choice;
607 elsif ($choice eq '*') {
612 $bottom = $top = find_unique
($choice, @stuff);
613 if (!defined $bottom) {
614 error_msg
"Huh ($choice)?\n";
618 if ($opts->{SINGLETON
} && $bottom != $top) {
619 error_msg
"Huh ($choice)?\n";
622 for ($i = $bottom-1; $i <= $top-1; $i++) {
623 next if (@stuff <= $i || $i < 0);
624 $chosen[$i] = $choose;
627 last if ($opts->{IMMEDIATE
} || $line eq '*');
629 for ($i = 0; $i < @stuff; $i++) {
631 push @return, $stuff[$i];
637 sub singleton_prompt_help_cmd
{
638 print colored
$help_color, <<\EOF
;
640 1 - select a numbered item
641 foo
- select item based on unique prefix
642 - (empty
) select nothing
646 sub prompt_help_cmd
{
647 print colored
$help_color, <<\EOF
;
649 1 - select a single item
650 3-5 - select a range of items
651 2-3,6-9 - select multiple ranges
652 foo
- select item based on unique prefix
653 -... - unselect specified items
655 - (empty
) finish selecting
660 list_and_choose
({ LIST_ONLY
=> 1, HEADER
=> $status_head },
670 print "$cnt paths\n";
678 my @mods = list_modified
('file-only');
681 my @update = list_and_choose
({ PROMPT
=> 'Update',
682 HEADER
=> $status_head, },
685 system(qw(git update-index --add --remove --),
686 map { $_->{VALUE
} } @update);
687 say_n_paths
('updated', @update);
693 my @update = list_and_choose
({ PROMPT
=> 'Revert',
694 HEADER
=> $status_head, },
697 if (is_initial_commit
()) {
698 system(qw(git rm --cached),
699 map { $_->{VALUE
} } @update);
702 my @lines = run_cmd_pipe
(qw(git ls-tree HEAD --),
703 map { $_->{VALUE
} } @update);
705 open $fh, '| git update-index --index-info'
712 if ($_->{INDEX_ADDDEL
} &&
713 $_->{INDEX_ADDDEL
} eq 'create') {
714 system(qw(git update-index --force-remove --),
716 print "note: $_->{VALUE} is untracked now.\n";
721 say_n_paths
('reverted', @update);
726 sub add_untracked_cmd
{
727 my @add = list_and_choose
({ PROMPT
=> 'Add untracked' },
730 system(qw(git update-index --add --), @add);
731 say_n_paths
('added', @add);
733 print "No untracked files.\n";
741 open $fh, '| git ' . $cmd . " --recount --allow-overlap";
748 my @diff_cmd = split(" ", $patch_mode_flavour{DIFF
});
749 if (defined $diff_algorithm) {
750 splice @diff_cmd, 1, 0, "--diff-algorithm=${diff_algorithm}";
752 if (defined $patch_mode_revision) {
753 push @diff_cmd, get_diff_reference
($patch_mode_revision);
755 my @diff = run_cmd_pipe
("git", @diff_cmd, "--", $path);
757 if ($diff_use_color) {
758 my @display_cmd = ("git", @diff_cmd, qw(--color --), $path);
759 if (defined $diff_filter) {
760 # quotemeta is overkill, but sufficient for shell-quoting
761 my $diff = join(' ', map { quotemeta } @display_cmd);
762 @display_cmd = ("$diff | $diff_filter");
765 @colored = run_cmd_pipe
(@display_cmd);
767 my (@hunk) = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'header' };
769 for (my $i = 0; $i < @diff; $i++) {
770 if ($diff[$i] =~ /^@@ /) {
771 push @hunk, { TEXT
=> [], DISPLAY
=> [],
774 push @
{$hunk[-1]{TEXT
}}, $diff[$i];
775 push @
{$hunk[-1]{DISPLAY
}},
776 (@colored ?
$colored[$i] : $diff[$i]);
781 sub parse_diff_header
{
784 my $head = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'header' };
785 my $mode = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'mode' };
786 my $deletion = { TEXT
=> [], DISPLAY
=> [], TYPE
=> 'deletion' };
788 for (my $i = 0; $i < @
{$src->{TEXT
}}; $i++) {
790 $src->{TEXT
}->[$i] =~ /^(old|new) mode (\d+)$/ ?
$mode :
791 $src->{TEXT
}->[$i] =~ /^deleted file/ ?
$deletion :
793 push @
{$dest->{TEXT
}}, $src->{TEXT
}->[$i];
794 push @
{$dest->{DISPLAY
}}, $src->{DISPLAY
}->[$i];
796 return ($head, $mode, $deletion);
799 sub hunk_splittable
{
802 my @s = split_hunk
($text);
806 sub parse_hunk_header
{
808 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
809 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
810 $o_cnt = 1 unless defined $o_cnt;
811 $n_cnt = 1 unless defined $n_cnt;
812 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
816 my ($text, $display) = @_;
818 if (!defined $display) {
821 # If there are context lines in the middle of a hunk,
822 # it can be split, but we would need to take care of
825 my ($o_ofs, undef, $n_ofs) = parse_hunk_header
($text->[0]);
830 my $next_hunk_start = undef;
831 my $i = $hunk_start - 1;
845 while (++$i < @
$text) {
846 my $line = $text->[$i];
847 my $display = $display->[$i];
849 if ($this->{ADDDEL
} &&
850 !defined $next_hunk_start) {
851 # We have seen leading context and
852 # adds/dels and then here is another
853 # context, which is trailing for this
854 # split hunk and leading for the next
856 $next_hunk_start = $i;
858 push @
{$this->{TEXT
}}, $line;
859 push @
{$this->{DISPLAY
}}, $display;
862 if (defined $next_hunk_start) {
869 if (defined $next_hunk_start) {
870 # We are done with the current hunk and
871 # this is the first real change for the
873 $hunk_start = $next_hunk_start;
874 $o_ofs = $this->{OLD
} + $this->{OCNT
};
875 $n_ofs = $this->{NEW
} + $this->{NCNT
};
876 $o_ofs -= $this->{POSTCTX
};
877 $n_ofs -= $this->{POSTCTX
};
881 push @
{$this->{TEXT
}}, $line;
882 push @
{$this->{DISPLAY
}}, $display;
896 for my $hunk (@split) {
897 $o_ofs = $hunk->{OLD
};
898 $n_ofs = $hunk->{NEW
};
899 my $o_cnt = $hunk->{OCNT
};
900 my $n_cnt = $hunk->{NCNT
};
902 my $head = ("@@ -$o_ofs" .
903 (($o_cnt != 1) ?
",$o_cnt" : '') .
905 (($n_cnt != 1) ?
",$n_cnt" : '') .
907 my $display_head = $head;
908 unshift @
{$hunk->{TEXT
}}, $head;
909 if ($diff_use_color) {
910 $display_head = colored
($fraginfo_color, $head);
912 unshift @
{$hunk->{DISPLAY
}}, $display_head;
917 sub find_last_o_ctx
{
919 my $text = $it->{TEXT
};
920 my ($o_ofs, $o_cnt) = parse_hunk_header
($text->[0]);
922 my $last_o_ctx = $o_ofs + $o_cnt;
924 my $line = $text->[$i];
935 my ($prev, $this) = @_;
936 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
937 parse_hunk_header
($prev->{TEXT
}[0]);
938 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
939 parse_hunk_header
($this->{TEXT
}[0]);
941 my (@line, $i, $ofs, $o_cnt, $n_cnt);
944 for ($i = 1; $i < @
{$prev->{TEXT
}}; $i++) {
945 my $line = $prev->{TEXT
}[$i];
946 if ($line =~ /^\+/) {
952 last if ($o1_ofs <= $ofs);
962 for ($i = 1; $i < @
{$this->{TEXT
}}; $i++) {
963 my $line = $this->{TEXT
}[$i];
964 if ($line =~ /^\+/) {
976 my $head = ("@@ -$o0_ofs" .
977 (($o_cnt != 1) ?
",$o_cnt" : '') .
979 (($n_cnt != 1) ?
",$n_cnt" : '') .
981 @
{$prev->{TEXT
}} = ($head, @line);
984 sub coalesce_overlapping_hunks
{
988 my ($last_o_ctx, $last_was_dirty);
990 for (grep { $_->{USE
} } @in) {
991 if ($_->{TYPE
} ne 'hunk') {
995 my $text = $_->{TEXT
};
996 my ($o_ofs) = parse_hunk_header
($text->[0]);
997 if (defined $last_o_ctx &&
998 $o_ofs <= $last_o_ctx &&
1001 merge_hunk
($out[-1], $_);
1006 $last_o_ctx = find_last_o_ctx
($out[-1]);
1007 $last_was_dirty = $_->{DIRTY
};
1012 sub reassemble_patch
{
1016 # Include everything in the header except the beginning of the diff.
1017 push @patch, (grep { !/^[-+]{3}/ } @
$head);
1019 # Then include any headers from the hunk lines, which must
1020 # come before any actual hunk.
1021 while (@_ && $_[0] !~ /^@/) {
1025 # Then begin the diff.
1026 push @patch, grep { /^[-+]{3}/ } @
$head;
1028 # And then the actual hunks.
1036 colored
((/^@/ ?
$fraginfo_color :
1037 /^\+/ ?
$diff_new_color :
1038 /^-/ ?
$diff_old_color :
1044 sub edit_hunk_manually
{
1047 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
1049 open $fh, '>', $hunkfile
1050 or die "failed to open hunk edit file for writing: " . $!;
1051 print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
1052 print $fh @
$oldtext;
1053 my $participle = $patch_mode_flavour{PARTICIPLE
};
1054 my $is_reverse = $patch_mode_flavour{IS_REVERSE
};
1055 my ($remove_plus, $remove_minus) = $is_reverse ?
('-', '+') : ('+', '-');
1058 # To remove '$remove_minus' lines, make them ' ' lines (context).
1059 # To remove '$remove_plus' lines, delete them.
1060 # Lines starting with # will be removed.
1062 # If the patch applies cleanly, the edited hunk will immediately be
1063 # marked for $participle. If it does not apply cleanly, you will be given
1064 # an opportunity to edit again. If all lines of the hunk are removed,
1065 # then the edit is aborted and the hunk is left unchanged.
1069 chomp(my $editor = run_cmd_pipe
(qw(git var GIT_EDITOR)));
1070 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
1076 open $fh, '<', $hunkfile
1077 or die "failed to open hunk edit file for reading: " . $!;
1078 my @newtext = grep { !/^#/ } <$fh>;
1082 # Abort if nothing remains
1083 if (!grep { /\S/ } @newtext) {
1087 # Reinsert the first hunk header if the user accidentally deleted it
1088 if ($newtext[0] !~ /^@/) {
1089 unshift @newtext, $oldtext->[0];
1095 return run_git_apply
($patch_mode_flavour{APPLY_CHECK
} . ' --check',
1096 map { @
{$_->{TEXT
}} } @_);
1099 sub _restore_terminal_and_die
{
1105 sub prompt_single_character
{
1107 local $SIG{TERM
} = \
&_restore_terminal_and_die
;
1108 local $SIG{INT
} = \
&_restore_terminal_and_die
;
1110 my $key = ReadKey
0;
1112 if ($use_termcap and $key eq "\e") {
1113 while (!defined $term_escapes{$key}) {
1114 my $next = ReadKey
0.5;
1115 last if (!defined $next);
1120 print "$key" if defined $key;
1131 print colored
$prompt_color, $prompt;
1132 my $line = prompt_single_character
;
1133 return 0 if $line =~ /^n/i;
1134 return 1 if $line =~ /^y/i;
1138 sub edit_hunk_loop
{
1139 my ($head, $hunk, $ix) = @_;
1140 my $text = $hunk->[$ix]->{TEXT
};
1143 $text = edit_hunk_manually
($text);
1144 if (!defined $text) {
1149 TYPE
=> $hunk->[$ix]->{TYPE
},
1153 if (diff_applies
($head,
1156 @
{$hunk}[$ix+1..$#{$hunk}])) {
1157 $newhunk->{DISPLAY
} = [color_diff
(@
{$text})];
1162 'Your edited hunk does not apply. Edit again '
1163 . '(saying "no" discards!) [y/n]? '
1169 sub help_patch_cmd
{
1170 my $verb = lc $patch_mode_flavour{VERB
};
1171 my $target = $patch_mode_flavour{TARGET
};
1172 print colored
$help_color, <<EOF ;
1173 y - $verb this hunk$target
1174 n - do not $verb this hunk$target
1175 q - quit; do not $verb this hunk or any of the remaining ones
1176 a - $verb this hunk and all later hunks in the file
1177 d - do not $verb this hunk or any of the later hunks in the file
1178 g - select a hunk to go to
1179 / - search for a hunk matching the given regex
1180 j - leave this hunk undecided, see next undecided hunk
1181 J - leave this hunk undecided, see next hunk
1182 k - leave this hunk undecided, see previous undecided hunk
1183 K - leave this hunk undecided, see previous hunk
1184 s - split the current hunk into smaller hunks
1185 e - manually edit the current hunk
1192 my $ret = run_git_apply
$cmd, @_;
1199 sub apply_patch_for_checkout_commit
{
1200 my $reverse = shift;
1201 my $applies_index = run_git_apply
'apply '.$reverse.' --cached --check', @_;
1202 my $applies_worktree = run_git_apply
'apply '.$reverse.' --check', @_;
1204 if ($applies_worktree && $applies_index) {
1205 run_git_apply
'apply '.$reverse.' --cached', @_;
1206 run_git_apply
'apply '.$reverse, @_;
1208 } elsif (!$applies_index) {
1209 print colored
$error_color, "The selected hunks do not apply to the index!\n";
1210 if (prompt_yesno
"Apply them to the worktree anyway? ") {
1211 return run_git_apply
'apply '.$reverse, @_;
1213 print colored
$error_color, "Nothing was applied.\n";
1222 sub patch_update_cmd
{
1223 my @all_mods = list_modified
($patch_mode_flavour{FILTER
});
1224 error_msg
"ignoring unmerged: $_->{VALUE}\n"
1225 for grep { $_->{UNMERGED
} } @all_mods;
1226 @all_mods = grep { !$_->{UNMERGED
} } @all_mods;
1228 my @mods = grep { !($_->{BINARY
}) } @all_mods;
1233 print STDERR
"Only binary files changed.\n";
1235 print STDERR
"No changes.\n";
1243 @them = list_and_choose
({ PROMPT
=> 'Patch update',
1244 HEADER
=> $status_head, },
1248 return 0 if patch_update_file
($_->{VALUE
});
1252 # Generate a one line summary of a hunk.
1253 sub summarize_hunk
{
1255 my $summary = $rhunk->{TEXT
}[0];
1257 # Keep the line numbers, discard extra context.
1258 $summary =~ s/@@(.*?)@@.*/$1 /s;
1259 $summary .= " " x
(20 - length $summary);
1261 # Add some user context.
1262 for my $line (@
{$rhunk->{TEXT
}}) {
1263 if ($line =~ m/^[+-].*\w/) {
1270 return substr($summary, 0, 80) . "\n";
1274 # Print a one-line summary of each hunk in the array ref in
1275 # the first argument, starting with the index in the 2nd.
1277 my ($hunks, $i) = @_;
1280 for (; $i < @
$hunks && $ctr < 20; $i++, $ctr++) {
1282 if (defined $hunks->[$i]{USE
}) {
1283 $status = $hunks->[$i]{USE
} ?
"+" : "-";
1288 summarize_hunk
($hunks->[$i]);
1293 sub patch_update_file
{
1297 my ($head, @hunk) = parse_diff
($path);
1298 ($head, my $mode, my $deletion) = parse_diff_header
($head);
1299 for (@
{$head->{DISPLAY
}}) {
1303 if (@
{$mode->{TEXT
}}) {
1304 unshift @hunk, $mode;
1306 if (@
{$deletion->{TEXT
}}) {
1307 foreach my $hunk (@hunk) {
1308 push @
{$deletion->{TEXT
}}, @
{$hunk->{TEXT
}};
1309 push @
{$deletion->{DISPLAY
}}, @
{$hunk->{DISPLAY
}};
1311 @hunk = ($deletion);
1314 $num = scalar @hunk;
1318 my ($prev, $next, $other, $undecided, $i);
1324 for ($i = 0; $i < $ix; $i++) {
1325 if (!defined $hunk[$i]{USE
}) {
1334 for ($i = $ix + 1; $i < $num; $i++) {
1335 if (!defined $hunk[$i]{USE
}) {
1341 if ($ix < $num - 1) {
1347 for ($i = 0; $i < $num; $i++) {
1348 if (!defined $hunk[$i]{USE
}) {
1353 last if (!$undecided);
1355 if ($hunk[$ix]{TYPE
} eq 'hunk' &&
1356 hunk_splittable
($hunk[$ix]{TEXT
})) {
1359 if ($hunk[$ix]{TYPE
} eq 'hunk') {
1362 for (@
{$hunk[$ix]{DISPLAY
}}) {
1365 print colored
$prompt_color, $patch_mode_flavour{VERB
},
1366 ($hunk[$ix]{TYPE
} eq 'mode' ?
' mode change' :
1367 $hunk[$ix]{TYPE
} eq 'deletion' ?
' deletion' :
1369 $patch_mode_flavour{TARGET
},
1370 " [y,n,q,a,d,/$other,?]? ";
1371 my $line = prompt_single_character
;
1372 last unless defined $line;
1374 if ($line =~ /^y/i) {
1375 $hunk[$ix]{USE
} = 1;
1377 elsif ($line =~ /^n/i) {
1378 $hunk[$ix]{USE
} = 0;
1380 elsif ($line =~ /^a/i) {
1381 while ($ix < $num) {
1382 if (!defined $hunk[$ix]{USE
}) {
1383 $hunk[$ix]{USE
} = 1;
1389 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1391 my $no = $ix > 10 ?
$ix - 10 : 0;
1392 while ($response eq '') {
1394 $no = display_hunks
(\
@hunk, $no);
1396 $extra = " (<ret> to see more)";
1398 print "go to which hunk$extra? ";
1399 $response = <STDIN
>;
1400 if (!defined $response) {
1405 if ($response !~ /^\s*\d+\s*$/) {
1406 error_msg
"Invalid number: '$response'\n";
1407 } elsif (0 < $response && $response <= $num) {
1408 $ix = $response - 1;
1410 error_msg
"Sorry, only $num hunks available.\n";
1414 elsif ($line =~ /^d/i) {
1415 while ($ix < $num) {
1416 if (!defined $hunk[$ix]{USE
}) {
1417 $hunk[$ix]{USE
} = 0;
1423 elsif ($line =~ /^q/i) {
1424 for ($i = 0; $i < $num; $i++) {
1425 if (!defined $hunk[$i]{USE
}) {
1432 elsif ($line =~ m
|^/(.*)|) {
1435 print colored
$prompt_color, "search for regex? ";
1437 if (defined $regex) {
1443 $search_string = qr{$regex}m;
1446 my ($err,$exp) = ($@
, $1);
1447 $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1448 error_msg
"Malformed search regexp $exp: $err\n";
1453 my $text = join ("", @
{$hunk[$iy]{TEXT
}});
1454 last if ($text =~ $search_string);
1456 $iy = 0 if ($iy >= $num);
1458 error_msg
"No hunk matches the given pattern\n";
1465 elsif ($line =~ /^K/) {
1466 if ($other =~ /K/) {
1470 error_msg
"No previous hunk\n";
1474 elsif ($line =~ /^J/) {
1475 if ($other =~ /J/) {
1479 error_msg
"No next hunk\n";
1483 elsif ($line =~ /^k/) {
1484 if ($other =~ /k/) {
1488 !defined $hunk[$ix]{USE
});
1492 error_msg
"No previous hunk\n";
1496 elsif ($line =~ /^j/) {
1497 if ($other !~ /j/) {
1498 error_msg
"No next hunk\n";
1502 elsif ($other =~ /s/ && $line =~ /^s/) {
1503 my @split = split_hunk
($hunk[$ix]{TEXT
}, $hunk[$ix]{DISPLAY
});
1505 print colored
$header_color, "Split into ",
1506 scalar(@split), " hunks.\n";
1508 splice (@hunk, $ix, 1, @split);
1509 $num = scalar @hunk;
1512 elsif ($other =~ /e/ && $line =~ /^e/) {
1513 my $newhunk = edit_hunk_loop
($head, \
@hunk, $ix);
1514 if (defined $newhunk) {
1515 splice @hunk, $ix, 1, $newhunk;
1519 help_patch_cmd
($other);
1525 last if ($ix >= $num ||
1526 !defined $hunk[$ix]{USE
});
1531 @hunk = coalesce_overlapping_hunks
(@hunk);
1537 push @result, @
{$_->{TEXT
}};
1542 my @patch = reassemble_patch
($head->{TEXT
}, @result);
1543 my $apply_routine = $patch_mode_flavour{APPLY
};
1544 &$apply_routine(@patch);
1553 my @mods = list_modified
('index-only');
1554 @mods = grep { !($_->{BINARY
}) } @mods;
1556 my (@them) = list_and_choose
({ PROMPT
=> 'Review diff',
1558 HEADER
=> $status_head, },
1561 my $reference = is_initial_commit
() ? get_empty_tree
() : 'HEAD';
1562 system(qw(git diff -p --cached), $reference, '--',
1563 map { $_->{VALUE
} } @them);
1572 print colored
$help_color, <<\EOF
;
1573 status
- show paths with changes
1574 update
- add working tree
state to the staged set of changes
1575 revert
- revert staged set of changes back to the HEAD version
1576 patch
- pick hunks
and update selectively
1577 diff
- view diff between HEAD
and index
1578 add untracked
- add contents of untracked files to the staged set of changes
1583 return unless @ARGV;
1584 my $arg = shift @ARGV;
1585 if ($arg =~ /--patch(?:=(.*))?/) {
1587 if ($1 eq 'reset') {
1588 $patch_mode = 'reset_head';
1589 $patch_mode_revision = 'HEAD';
1590 $arg = shift @ARGV or die "missing --";
1592 $patch_mode_revision = $arg;
1593 $patch_mode = ($arg eq 'HEAD' ?
1594 'reset_head' : 'reset_nothead');
1595 $arg = shift @ARGV or die "missing --";
1597 } elsif ($1 eq 'checkout') {
1598 $arg = shift @ARGV or die "missing --";
1600 $patch_mode = 'checkout_index';
1602 $patch_mode_revision = $arg;
1603 $patch_mode = ($arg eq 'HEAD' ?
1604 'checkout_head' : 'checkout_nothead');
1605 $arg = shift @ARGV or die "missing --";
1607 } elsif ($1 eq 'stage' or $1 eq 'stash') {
1609 $arg = shift @ARGV or die "missing --";
1611 die "unknown --patch mode: $1";
1614 $patch_mode = 'stage';
1615 $arg = shift @ARGV or die "missing --";
1617 die "invalid argument $arg, expecting --"
1618 unless $arg eq "--";
1619 %patch_mode_flavour = %{$patch_modes{$patch_mode}};
1621 elsif ($arg ne "--") {
1622 die "invalid argument $arg, expecting --";
1627 my @cmd = ([ 'status', \
&status_cmd
, ],
1628 [ 'update', \
&update_cmd
, ],
1629 [ 'revert', \
&revert_cmd
, ],
1630 [ 'add untracked', \
&add_untracked_cmd
, ],
1631 [ 'patch', \
&patch_update_cmd
, ],
1632 [ 'diff', \
&diff_cmd
, ],
1633 [ 'quit', \
&quit_cmd
, ],
1634 [ 'help', \
&help_cmd
, ],
1637 my ($it) = list_and_choose
({ PROMPT
=> 'What now',
1640 HEADER
=> '*** Commands ***',
1641 ON_EOF
=> \
&quit_cmd
,
1642 IMMEDIATE
=> 1 }, @cmd);