]> git.ipfire.org Git - thirdparty/git.git/blame - git-add--interactive.perl
verify-commit: add test for exit status on untrusted signature
[thirdparty/git.git] / git-add--interactive.perl
CommitLineData
3328aced 1#!/usr/bin/perl
5cde71d6 2
d48b2841 3use 5.008;
5cde71d6 4use strict;
3328aced 5use warnings;
b4c61ed6
JH
6use Git;
7
8851f480
JH
8binmode(STDOUT, ":raw");
9
b4c61ed6
JH
10my $repo = Git->repository();
11
f87e310d
JK
12my $menu_use_color = $repo->get_colorbool('color.interactive');
13my ($prompt_color, $header_color, $help_color) =
14 $menu_use_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'),
18 ) : ();
a3019736
TR
19my $error_color = ();
20if ($menu_use_color) {
9aad6cba
SB
21 my $help_color_spec = ($repo->config('color.interactive.help') or
22 'red bold');
a3019736
TR
23 $error_color = $repo->get_color('color.interactive.error',
24 $help_color_spec);
25}
b4c61ed6 26
f87e310d
JK
27my $diff_use_color = $repo->get_colorbool('color.diff');
28my ($fraginfo_color) =
29 $diff_use_color ? (
30 $repo->get_color('color.diff.frag', 'cyan'),
31 ) : ();
ac083c47
TR
32my ($diff_plain_color) =
33 $diff_use_color ? (
34 $repo->get_color('color.diff.plain', ''),
35 ) : ();
36my ($diff_old_color) =
37 $diff_use_color ? (
38 $repo->get_color('color.diff.old', 'red'),
39 ) : ();
40my ($diff_new_color) =
41 $diff_use_color ? (
42 $repo->get_color('color.diff.new', 'green'),
43 ) : ();
b4c61ed6 44
f87e310d 45my $normal_color = $repo->get_color("", "reset");
b4c61ed6 46
2cc0f53b
JK
47my $diff_algorithm = $repo->config('diff.algorithm');
48
ca6ac7f1 49my $use_readkey = 0;
b5cc0032
TR
50my $use_termcap = 0;
51my %term_escapes;
52
748aa689
TR
53sub ReadMode;
54sub ReadKey;
ca6ac7f1
TR
55if ($repo->config_bool("interactive.singlekey")) {
56 eval {
748aa689
TR
57 require Term::ReadKey;
58 Term::ReadKey->import;
ca6ac7f1
TR
59 $use_readkey = 1;
60 };
b294097b
SR
61 if (!$use_readkey) {
62 print STDERR "missing Term::ReadKey, disabling interactive.singlekey\n";
63 }
b5cc0032
TR
64 eval {
65 require Term::Cap;
66 my $termcap = Term::Cap->Tgetent;
67 foreach (values %$termcap) {
68 $term_escapes{$_} = 1 if /^\e/;
69 }
70 $use_termcap = 1;
71 };
ca6ac7f1
TR
72}
73
b4c61ed6
JH
74sub colored {
75 my $color = shift;
76 my $string = join("", @_);
77
f87e310d 78 if (defined $color) {
b4c61ed6
JH
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$/;
87 }
88 return $string;
89}
5cde71d6 90
b63e9950
WC
91# command line options
92my $patch_mode;
d002ef4d 93my $patch_mode_revision;
b63e9950 94
8f0bef6d 95sub apply_patch;
4f353658 96sub apply_patch_for_checkout_commit;
dda1f2a5 97sub apply_patch_for_stash;
8f0bef6d
TR
98
99my %patch_modes = (
100 'stage' => {
101 DIFF => 'diff-files -p',
102 APPLY => sub { apply_patch 'apply --cached', @_; },
103 APPLY_CHECK => 'apply --cached',
104 VERB => 'Stage',
105 TARGET => '',
106 PARTICIPLE => 'staging',
107 FILTER => 'file-only',
7b8c7051 108 IS_REVERSE => 0,
8f0bef6d 109 },
dda1f2a5
TR
110 'stash' => {
111 DIFF => 'diff-index -p HEAD',
112 APPLY => sub { apply_patch 'apply --cached', @_; },
113 APPLY_CHECK => 'apply --cached',
114 VERB => 'Stash',
115 TARGET => '',
116 PARTICIPLE => 'stashing',
117 FILTER => undef,
7b8c7051 118 IS_REVERSE => 0,
dda1f2a5 119 },
d002ef4d
TR
120 'reset_head' => {
121 DIFF => 'diff-index -p --cached',
122 APPLY => sub { apply_patch 'apply -R --cached', @_; },
123 APPLY_CHECK => 'apply -R --cached',
124 VERB => 'Unstage',
125 TARGET => '',
126 PARTICIPLE => 'unstaging',
127 FILTER => 'index-only',
7b8c7051 128 IS_REVERSE => 1,
d002ef4d
TR
129 },
130 'reset_nothead' => {
131 DIFF => 'diff-index -R -p --cached',
132 APPLY => sub { apply_patch 'apply --cached', @_; },
133 APPLY_CHECK => 'apply --cached',
134 VERB => 'Apply',
135 TARGET => ' to index',
136 PARTICIPLE => 'applying',
137 FILTER => 'index-only',
7b8c7051 138 IS_REVERSE => 0,
d002ef4d 139 },
4f353658
TR
140 'checkout_index' => {
141 DIFF => 'diff-files -p',
142 APPLY => sub { apply_patch 'apply -R', @_; },
143 APPLY_CHECK => 'apply -R',
144 VERB => 'Discard',
145 TARGET => ' from worktree',
146 PARTICIPLE => 'discarding',
147 FILTER => 'file-only',
7b8c7051 148 IS_REVERSE => 1,
4f353658
TR
149 },
150 'checkout_head' => {
151 DIFF => 'diff-index -p',
152 APPLY => sub { apply_patch_for_checkout_commit '-R', @_ },
153 APPLY_CHECK => 'apply -R',
154 VERB => 'Discard',
155 TARGET => ' from index and worktree',
156 PARTICIPLE => 'discarding',
157 FILTER => undef,
7b8c7051 158 IS_REVERSE => 1,
4f353658
TR
159 },
160 'checkout_nothead' => {
161 DIFF => 'diff-index -R -p',
162 APPLY => sub { apply_patch_for_checkout_commit '', @_ },
163 APPLY_CHECK => 'apply',
164 VERB => 'Apply',
165 TARGET => ' to index and worktree',
166 PARTICIPLE => 'applying',
167 FILTER => undef,
7b8c7051 168 IS_REVERSE => 0,
4f353658 169 },
8f0bef6d
TR
170);
171
172my %patch_mode_flavour = %{$patch_modes{stage}};
b63e9950 173
5cde71d6 174sub run_cmd_pipe {
df17e77c 175 if ($^O eq 'MSWin32') {
21e9757e
AR
176 my @invalid = grep {m/[":*]/} @_;
177 die "$^O does not support: @invalid\n" if @invalid;
178 my @args = map { m/ /o ? "\"$_\"": $_ } @_;
179 return qx{@args};
180 } else {
181 my $fh = undef;
182 open($fh, '-|', @_) or die;
183 return <$fh>;
184 }
5cde71d6
JH
185}
186
187my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));
188
189if (!defined $GIT_DIR) {
190 exit(1); # rev-parse would have already said "not a git repo"
191}
192chomp($GIT_DIR);
193
8851f480
JH
194my %cquote_map = (
195 "b" => chr(8),
196 "t" => chr(9),
197 "n" => chr(10),
198 "v" => chr(11),
199 "f" => chr(12),
200 "r" => chr(13),
201 "\\" => "\\",
202 "\042" => "\042",
203);
204
205sub unquote_path {
206 local ($_) = @_;
207 my ($retval, $remainder);
208 if (!/^\042(.*)\042$/) {
209 return $_;
210 }
211 ($_, $retval) = ($1, "");
212 while (/^([^\\]*)\\(.*)$/) {
213 $remainder = $2;
214 $retval .= $1;
215 for ($remainder) {
216 if (/^([0-3][0-7][0-7])(.*)$/) {
217 $retval .= chr(oct($1));
218 $_ = $2;
219 last;
220 }
221 if (/^([\\\042btnvfr])(.*)$/) {
222 $retval .= $cquote_map{$1};
223 $_ = $2;
224 last;
225 }
226 # This is malformed -- just return it as-is for now.
227 return $_[0];
228 }
229 $_ = $remainder;
230 }
231 $retval .= $_;
232 return $retval;
233}
234
5cde71d6
JH
235sub refresh {
236 my $fh;
21e9757e 237 open $fh, 'git update-index --refresh |'
5cde71d6
JH
238 or die;
239 while (<$fh>) {
240 ;# ignore 'needs update'
241 }
242 close $fh;
243}
244
245sub list_untracked {
246 map {
247 chomp $_;
8851f480 248 unquote_path($_);
5cde71d6 249 }
4c841684 250 run_cmd_pipe(qw(git ls-files --others --exclude-standard --), @ARGV);
5cde71d6
JH
251}
252
253my $status_fmt = '%12s %12s %s';
254my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
255
18bc7616
JK
256{
257 my $initial;
258 sub is_initial_commit {
259 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
260 unless defined $initial;
261 return $initial;
262 }
263}
264
265sub get_empty_tree {
266 return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
267}
268
954312a3
JK
269sub get_diff_reference {
270 my $ref = shift;
271 if (defined $ref and $ref ne 'HEAD') {
272 return $ref;
273 } elsif (is_initial_commit()) {
274 return get_empty_tree();
275 } else {
276 return 'HEAD';
277 }
278}
279
5cde71d6 280# Returns list of hashes, contents of each of which are:
5cde71d6
JH
281# VALUE: pathname
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?
4066bd67 287# UNMERGED: is the path unmerged
5cde71d6
JH
288
289sub list_modified {
290 my ($only) = @_;
291 my (%data, @return);
292 my ($add, $del, $adddel, $file);
4c841684
WC
293 my @tracked = ();
294
295 if (@ARGV) {
296 @tracked = map {
8851f480
JH
297 chomp $_;
298 unquote_path($_);
b145b211 299 } run_cmd_pipe(qw(git ls-files --), @ARGV);
4c841684
WC
300 return if (!@tracked);
301 }
5cde71d6 302
954312a3 303 my $reference = get_diff_reference($patch_mode_revision);
5cde71d6 304 for (run_cmd_pipe(qw(git diff-index --cached
18bc7616
JK
305 --numstat --summary), $reference,
306 '--', @tracked)) {
5cde71d6
JH
307 if (($add, $del, $file) =
308 /^([-\d]+) ([-\d]+) (.*)/) {
309 my ($change, $bin);
8851f480 310 $file = unquote_path($file);
5cde71d6
JH
311 if ($add eq '-' && $del eq '-') {
312 $change = 'binary';
313 $bin = 1;
314 }
315 else {
316 $change = "+$add/-$del";
317 }
318 $data{$file} = {
319 INDEX => $change,
320 BINARY => $bin,
321 FILE => 'nothing',
322 }
323 }
324 elsif (($adddel, $file) =
325 /^ (create|delete) mode [0-7]+ (.*)$/) {
8851f480 326 $file = unquote_path($file);
5cde71d6
JH
327 $data{$file}{INDEX_ADDDEL} = $adddel;
328 }
329 }
330
4066bd67 331 for (run_cmd_pipe(qw(git diff-files --numstat --summary --raw --), @tracked)) {
5cde71d6
JH
332 if (($add, $del, $file) =
333 /^([-\d]+) ([-\d]+) (.*)/) {
8851f480 334 $file = unquote_path($file);
5cde71d6
JH
335 my ($change, $bin);
336 if ($add eq '-' && $del eq '-') {
337 $change = 'binary';
338 $bin = 1;
339 }
340 else {
341 $change = "+$add/-$del";
342 }
343 $data{$file}{FILE} = $change;
344 if ($bin) {
345 $data{$file}{BINARY} = 1;
346 }
347 }
348 elsif (($adddel, $file) =
349 /^ (create|delete) mode [0-7]+ (.*)$/) {
8851f480 350 $file = unquote_path($file);
5cde71d6
JH
351 $data{$file}{FILE_ADDDEL} = $adddel;
352 }
4066bd67
JK
353 elsif (/^:[0-7]+ [0-7]+ [0-9a-f]+ [0-9a-f]+ (.) (.*)$/) {
354 $file = unquote_path($2);
355 if (!exists $data{$file}) {
356 $data{$file} = +{
357 INDEX => 'unchanged',
358 BINARY => 0,
359 };
360 }
361 if ($1 eq 'U') {
362 $data{$file}{UNMERGED} = 1;
363 }
364 }
5cde71d6
JH
365 }
366
367 for (sort keys %data) {
368 my $it = $data{$_};
369
370 if ($only) {
371 if ($only eq 'index-only') {
372 next if ($it->{INDEX} eq 'unchanged');
373 }
374 if ($only eq 'file-only') {
375 next if ($it->{FILE} eq 'nothing');
376 }
377 }
378 push @return, +{
379 VALUE => $_,
5cde71d6
JH
380 %$it,
381 };
382 }
383 return @return;
384}
385
386sub find_unique {
387 my ($string, @stuff) = @_;
388 my $found = undef;
389 for (my $i = 0; $i < @stuff; $i++) {
390 my $it = $stuff[$i];
391 my $hit = undef;
392 if (ref $it) {
393 if ((ref $it) eq 'ARRAY') {
394 $it = $it->[0];
395 }
396 else {
397 $it = $it->{VALUE};
398 }
399 }
400 eval {
401 if ($it =~ /^$string/) {
402 $hit = 1;
403 };
404 };
405 if (defined $hit && defined $found) {
406 return undef;
407 }
408 if ($hit) {
409 $found = $i + 1;
410 }
411 }
412 return $found;
413}
414
14cb5038
WC
415# inserts string into trie and updates count for each character
416sub update_trie {
417 my ($trie, $string) = @_;
418 foreach (split //, $string) {
419 $trie = $trie->{$_} ||= {COUNT => 0};
420 $trie->{COUNT}++;
421 }
422}
423
424# returns an array of tuples (prefix, remainder)
425sub find_unique_prefixes {
426 my @stuff = @_;
427 my @return = ();
428
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
432 my $soft_limit = 0;
433 my $hard_limit = 3;
434
435 # build a trie modelling all possible options
436 my %trie;
437 foreach my $print (@stuff) {
438 if ((ref $print) eq 'ARRAY') {
439 $print = $print->[0];
440 }
63320989 441 elsif ((ref $print) eq 'HASH') {
14cb5038
WC
442 $print = $print->{VALUE};
443 }
444 update_trie(\%trie, $print);
445 push @return, $print;
446 }
447
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;
452 my %search = %trie;
453 my ($prefix, $remainder);
454 my $j;
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;
460 last;
461 }
462 else {
463 my $prefix = substr $ret, 0, $j;
464 return ()
465 if ($hard_limit && $j + 1 > $hard_limit);
466 }
467 %search = %{$search{$letter}};
468 }
8851f480
JH
469 if (ord($letters[0]) > 127 ||
470 ($soft_limit && $j + 1 > $soft_limit)) {
14cb5038
WC
471 $prefix = undef;
472 $remainder = $ret;
473 }
474 $return[$i] = [$prefix, $remainder];
475 }
476 return @return;
477}
478
63320989
WC
479# filters out prefixes which have special meaning to list_and_choose()
480sub is_valid_prefix {
481 my $prefix = shift;
482 return (defined $prefix) &&
483 !($prefix =~ /[\s,]/) && # separators
484 !($prefix =~ /^-/) && # deselection
485 !($prefix =~ /^\d+/) && # selection
7e018be2
WC
486 ($prefix ne '*') && # "all" wildcard
487 ($prefix ne '?'); # prompt help
63320989
WC
488}
489
14cb5038
WC
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)
492sub highlight_prefix {
493 my $prefix = shift;
494 my $remainder = shift;
b4c61ed6
JH
495
496 if (!defined $prefix) {
497 return $remainder;
498 }
499
500 if (!is_valid_prefix($prefix)) {
501 return "$prefix$remainder";
502 }
503
f87e310d 504 if (!$menu_use_color) {
b4c61ed6
JH
505 return "[$prefix]$remainder";
506 }
507
508 return "$prompt_color$prefix$normal_color$remainder";
14cb5038
WC
509}
510
a3019736
TR
511sub error_msg {
512 print STDERR colored $error_color, @_;
513}
514
5cde71d6
JH
515sub list_and_choose {
516 my ($opts, @stuff) = @_;
517 my (@chosen, @return);
a9c4641d
AK
518 if (!@stuff) {
519 return @return;
520 }
5cde71d6 521 my $i;
14cb5038 522 my @prefixes = find_unique_prefixes(@stuff) unless $opts->{LIST_ONLY};
5cde71d6
JH
523
524 TOPLOOP:
525 while (1) {
526 my $last_lf = 0;
527
528 if ($opts->{HEADER}) {
529 if (!$opts->{LIST_FLAT}) {
530 print " ";
531 }
b4c61ed6 532 print colored $header_color, "$opts->{HEADER}\n";
5cde71d6
JH
533 }
534 for ($i = 0; $i < @stuff; $i++) {
535 my $chosen = $chosen[$i] ? '*' : ' ';
536 my $print = $stuff[$i];
63320989
WC
537 my $ref = ref $print;
538 my $highlighted = highlight_prefix(@{$prefixes[$i]})
539 if @prefixes;
540 if ($ref eq 'ARRAY') {
541 $print = $highlighted || $print->[0];
542 }
543 elsif ($ref eq 'HASH') {
544 my $value = $highlighted || $print->{VALUE};
545 $print = sprintf($status_fmt,
546 $print->{INDEX},
547 $print->{FILE},
548 $value);
549 }
550 else {
551 $print = $highlighted || $print;
5cde71d6
JH
552 }
553 printf("%s%2d: %s", $chosen, $i+1, $print);
554 if (($opts->{LIST_FLAT}) &&
555 (($i + 1) % ($opts->{LIST_FLAT}))) {
556 print "\t";
557 $last_lf = 0;
558 }
559 else {
560 print "\n";
561 $last_lf = 1;
562 }
563 }
564 if (!$last_lf) {
565 print "\n";
566 }
567
568 return if ($opts->{LIST_ONLY});
569
b4c61ed6 570 print colored $prompt_color, $opts->{PROMPT};
5cde71d6
JH
571 if ($opts->{SINGLETON}) {
572 print "> ";
573 }
574 else {
575 print ">> ";
576 }
577 my $line = <STDIN>;
c95c0248
JLH
578 if (!$line) {
579 print "\n";
580 $opts->{ON_EOF}->() if $opts->{ON_EOF};
581 last;
582 }
5cde71d6 583 chomp $line;
6a6eb3d0 584 last if $line eq '';
7e018be2
WC
585 if ($line eq '?') {
586 $opts->{SINGLETON} ?
587 singleton_prompt_help_cmd() :
588 prompt_help_cmd();
589 next TOPLOOP;
590 }
5cde71d6
JH
591 for my $choice (split(/[\s,]+/, $line)) {
592 my $choose = 1;
593 my ($bottom, $top);
594
595 # Input that begins with '-'; unchoose
596 if ($choice =~ s/^-//) {
597 $choose = 0;
598 }
1e5aaa6d
CM
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);
5cde71d6
JH
602 }
603 elsif ($choice =~ /^\d+$/) {
604 $bottom = $top = $choice;
605 }
606 elsif ($choice eq '*') {
607 $bottom = 1;
608 $top = 1 + @stuff;
609 }
610 else {
611 $bottom = $top = find_unique($choice, @stuff);
612 if (!defined $bottom) {
a3019736 613 error_msg "Huh ($choice)?\n";
5cde71d6
JH
614 next TOPLOOP;
615 }
616 }
617 if ($opts->{SINGLETON} && $bottom != $top) {
a3019736 618 error_msg "Huh ($choice)?\n";
5cde71d6
JH
619 next TOPLOOP;
620 }
621 for ($i = $bottom-1; $i <= $top-1; $i++) {
6a6eb3d0 622 next if (@stuff <= $i || $i < 0);
5cde71d6 623 $chosen[$i] = $choose;
5cde71d6
JH
624 }
625 }
12db334e 626 last if ($opts->{IMMEDIATE} || $line eq '*');
5cde71d6
JH
627 }
628 for ($i = 0; $i < @stuff; $i++) {
629 if ($chosen[$i]) {
630 push @return, $stuff[$i];
631 }
632 }
633 return @return;
634}
635
7e018be2 636sub singleton_prompt_help_cmd {
b4c61ed6 637 print colored $help_color, <<\EOF ;
7e018be2
WC
638Prompt help:
6391 - select a numbered item
640foo - select item based on unique prefix
641 - (empty) select nothing
642EOF
643}
644
645sub prompt_help_cmd {
b4c61ed6 646 print colored $help_color, <<\EOF ;
7e018be2
WC
647Prompt help:
6481 - select a single item
6493-5 - select a range of items
6502-3,6-9 - select multiple ranges
651foo - select item based on unique prefix
652-... - unselect specified items
653* - choose all items
654 - (empty) finish selecting
655EOF
656}
657
5cde71d6
JH
658sub status_cmd {
659 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
660 list_modified());
661 print "\n";
662}
663
664sub say_n_paths {
665 my $did = shift @_;
666 my $cnt = scalar @_;
667 print "$did ";
668 if (1 < $cnt) {
669 print "$cnt paths\n";
670 }
671 else {
672 print "one path\n";
673 }
674}
675
676sub update_cmd {
677 my @mods = list_modified('file-only');
678 return if (!@mods);
679
680 my @update = list_and_choose({ PROMPT => 'Update',
681 HEADER => $status_head, },
682 @mods);
683 if (@update) {
a4f7112f 684 system(qw(git update-index --add --remove --),
5cde71d6
JH
685 map { $_->{VALUE} } @update);
686 say_n_paths('updated', @update);
687 }
688 print "\n";
689}
690
691sub revert_cmd {
692 my @update = list_and_choose({ PROMPT => 'Revert',
693 HEADER => $status_head, },
694 list_modified());
695 if (@update) {
18bc7616
JK
696 if (is_initial_commit()) {
697 system(qw(git rm --cached),
698 map { $_->{VALUE} } @update);
5cde71d6 699 }
18bc7616
JK
700 else {
701 my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
702 map { $_->{VALUE} } @update);
703 my $fh;
704 open $fh, '| git update-index --index-info'
705 or die;
706 for (@lines) {
707 print $fh $_;
708 }
709 close($fh);
710 for (@update) {
711 if ($_->{INDEX_ADDDEL} &&
712 $_->{INDEX_ADDDEL} eq 'create') {
713 system(qw(git update-index --force-remove --),
714 $_->{VALUE});
715 print "note: $_->{VALUE} is untracked now.\n";
716 }
5cde71d6
JH
717 }
718 }
719 refresh();
720 say_n_paths('reverted', @update);
721 }
722 print "\n";
723}
724
725sub add_untracked_cmd {
726 my @add = list_and_choose({ PROMPT => 'Add untracked' },
727 list_untracked());
728 if (@add) {
729 system(qw(git update-index --add --), @add);
730 say_n_paths('added', @add);
a9c4641d
AK
731 } else {
732 print "No untracked files.\n";
5cde71d6
JH
733 }
734 print "\n";
735}
736
8f0bef6d
TR
737sub run_git_apply {
738 my $cmd = shift;
739 my $fh;
933e44d3 740 open $fh, '| git ' . $cmd . " --recount --allow-overlap";
8f0bef6d
TR
741 print $fh @_;
742 return close $fh;
743}
744
5cde71d6
JH
745sub parse_diff {
746 my ($path) = @_;
8f0bef6d 747 my @diff_cmd = split(" ", $patch_mode_flavour{DIFF});
2cc0f53b 748 if (defined $diff_algorithm) {
e5c29097 749 splice @diff_cmd, 1, 0, "--diff-algorithm=${diff_algorithm}";
2cc0f53b 750 }
d002ef4d 751 if (defined $patch_mode_revision) {
954312a3 752 push @diff_cmd, get_diff_reference($patch_mode_revision);
d002ef4d 753 }
8f0bef6d 754 my @diff = run_cmd_pipe("git", @diff_cmd, "--", $path);
4af756f3
WC
755 my @colored = ();
756 if ($diff_use_color) {
8f0bef6d 757 @colored = run_cmd_pipe("git", @diff_cmd, qw(--color --), $path);
5cde71d6 758 }
0392513f 759 my (@hunk) = { TEXT => [], DISPLAY => [], TYPE => 'header' };
b4c61ed6 760
4af756f3
WC
761 for (my $i = 0; $i < @diff; $i++) {
762 if ($diff[$i] =~ /^@@ /) {
0392513f
JK
763 push @hunk, { TEXT => [], DISPLAY => [],
764 TYPE => 'hunk' };
b4c61ed6 765 }
4af756f3
WC
766 push @{$hunk[-1]{TEXT}}, $diff[$i];
767 push @{$hunk[-1]{DISPLAY}},
768 ($diff_use_color ? $colored[$i] : $diff[$i]);
b4c61ed6 769 }
4af756f3 770 return @hunk;
b4c61ed6
JH
771}
772
b717a627
JK
773sub parse_diff_header {
774 my $src = shift;
775
0392513f
JK
776 my $head = { TEXT => [], DISPLAY => [], TYPE => 'header' };
777 my $mode = { TEXT => [], DISPLAY => [], TYPE => 'mode' };
24ab81ae 778 my $deletion = { TEXT => [], DISPLAY => [], TYPE => 'deletion' };
b717a627
JK
779
780 for (my $i = 0; $i < @{$src->{TEXT}}; $i++) {
24ab81ae
JK
781 my $dest =
782 $src->{TEXT}->[$i] =~ /^(old|new) mode (\d+)$/ ? $mode :
783 $src->{TEXT}->[$i] =~ /^deleted file/ ? $deletion :
784 $head;
b717a627
JK
785 push @{$dest->{TEXT}}, $src->{TEXT}->[$i];
786 push @{$dest->{DISPLAY}}, $src->{DISPLAY}->[$i];
787 }
24ab81ae 788 return ($head, $mode, $deletion);
b717a627
JK
789}
790
835b2aeb
JH
791sub hunk_splittable {
792 my ($text) = @_;
793
794 my @s = split_hunk($text);
795 return (1 < @s);
796}
797
798sub parse_hunk_header {
799 my ($line) = @_;
800 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
7288ed8e
JLH
801 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
802 $o_cnt = 1 unless defined $o_cnt;
803 $n_cnt = 1 unless defined $n_cnt;
835b2aeb
JH
804 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
805}
806
807sub split_hunk {
4af756f3 808 my ($text, $display) = @_;
835b2aeb 809 my @split = ();
4af756f3
WC
810 if (!defined $display) {
811 $display = $text;
812 }
835b2aeb
JH
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
815 # overlaps later.
816
7b40a455 817 my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
835b2aeb 818 my $hunk_start = 1;
835b2aeb
JH
819
820 OUTER:
821 while (1) {
822 my $next_hunk_start = undef;
823 my $i = $hunk_start - 1;
824 my $this = +{
825 TEXT => [],
4af756f3 826 DISPLAY => [],
0392513f 827 TYPE => 'hunk',
835b2aeb
JH
828 OLD => $o_ofs,
829 NEW => $n_ofs,
830 OCNT => 0,
831 NCNT => 0,
832 ADDDEL => 0,
833 POSTCTX => 0,
4af756f3 834 USE => undef,
835b2aeb
JH
835 };
836
837 while (++$i < @$text) {
838 my $line = $text->[$i];
4af756f3 839 my $display = $display->[$i];
835b2aeb
JH
840 if ($line =~ /^ /) {
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
847 # one.
848 $next_hunk_start = $i;
849 }
850 push @{$this->{TEXT}}, $line;
4af756f3 851 push @{$this->{DISPLAY}}, $display;
835b2aeb
JH
852 $this->{OCNT}++;
853 $this->{NCNT}++;
854 if (defined $next_hunk_start) {
855 $this->{POSTCTX}++;
856 }
857 next;
858 }
859
860 # add/del
861 if (defined $next_hunk_start) {
862 # We are done with the current hunk and
863 # this is the first real change for the
864 # next split one.
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};
870 push @split, $this;
871 redo OUTER;
872 }
873 push @{$this->{TEXT}}, $line;
4af756f3 874 push @{$this->{DISPLAY}}, $display;
835b2aeb
JH
875 $this->{ADDDEL}++;
876 if ($line =~ /^-/) {
877 $this->{OCNT}++;
878 }
879 else {
880 $this->{NCNT}++;
881 }
882 }
883
884 push @split, $this;
885 last;
886 }
887
888 for my $hunk (@split) {
889 $o_ofs = $hunk->{OLD};
890 $n_ofs = $hunk->{NEW};
7b40a455
JLH
891 my $o_cnt = $hunk->{OCNT};
892 my $n_cnt = $hunk->{NCNT};
835b2aeb
JH
893
894 my $head = ("@@ -$o_ofs" .
895 (($o_cnt != 1) ? ",$o_cnt" : '') .
896 " +$n_ofs" .
897 (($n_cnt != 1) ? ",$n_cnt" : '') .
898 " @@\n");
4af756f3 899 my $display_head = $head;
835b2aeb 900 unshift @{$hunk->{TEXT}}, $head;
4af756f3
WC
901 if ($diff_use_color) {
902 $display_head = colored($fraginfo_color, $head);
903 }
904 unshift @{$hunk->{DISPLAY}}, $display_head;
835b2aeb 905 }
4af756f3 906 return @split;
835b2aeb
JH
907}
908
7a26e653
JH
909sub find_last_o_ctx {
910 my ($it) = @_;
911 my $text = $it->{TEXT};
912 my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
913 my $i = @{$text};
914 my $last_o_ctx = $o_ofs + $o_cnt;
915 while (0 < --$i) {
916 my $line = $text->[$i];
917 if ($line =~ /^ /) {
918 $last_o_ctx--;
919 next;
920 }
921 last;
922 }
923 return $last_o_ctx;
924}
925
926sub merge_hunk {
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]);
932
933 my (@line, $i, $ofs, $o_cnt, $n_cnt);
934 $ofs = $o0_ofs;
935 $o_cnt = $n_cnt = 0;
936 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
937 my $line = $prev->{TEXT}[$i];
938 if ($line =~ /^\+/) {
939 $n_cnt++;
940 push @line, $line;
941 next;
942 }
943
944 last if ($o1_ofs <= $ofs);
945
946 $o_cnt++;
947 $ofs++;
948 if ($line =~ /^ /) {
949 $n_cnt++;
950 }
951 push @line, $line;
952 }
953
954 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
955 my $line = $this->{TEXT}[$i];
956 if ($line =~ /^\+/) {
957 $n_cnt++;
958 push @line, $line;
959 next;
960 }
961 $ofs++;
962 $o_cnt++;
963 if ($line =~ /^ /) {
964 $n_cnt++;
965 }
966 push @line, $line;
967 }
968 my $head = ("@@ -$o0_ofs" .
969 (($o_cnt != 1) ? ",$o_cnt" : '') .
970 " +$n0_ofs" .
971 (($n_cnt != 1) ? ",$n_cnt" : '') .
972 " @@\n");
973 @{$prev->{TEXT}} = ($head, @line);
974}
975
976sub coalesce_overlapping_hunks {
977 my (@in) = @_;
978 my @out = ();
979
980 my ($last_o_ctx, $last_was_dirty);
981
982 for (grep { $_->{USE} } @in) {
3d792161
TR
983 if ($_->{TYPE} ne 'hunk') {
984 push @out, $_;
985 next;
986 }
7a26e653
JH
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 &&
991 !$_->{DIRTY} &&
992 !$last_was_dirty) {
993 merge_hunk($out[-1], $_);
994 }
995 else {
996 push @out, $_;
997 }
998 $last_o_ctx = find_last_o_ctx($out[-1]);
999 $last_was_dirty = $_->{DIRTY};
1000 }
1001 return @out;
1002}
835b2aeb 1003
e1327ed5
JK
1004sub reassemble_patch {
1005 my $head = shift;
1006 my @patch;
1007
1008 # Include everything in the header except the beginning of the diff.
1009 push @patch, (grep { !/^[-+]{3}/ } @$head);
1010
1011 # Then include any headers from the hunk lines, which must
1012 # come before any actual hunk.
1013 while (@_ && $_[0] !~ /^@/) {
1014 push @patch, shift;
1015 }
1016
1017 # Then begin the diff.
1018 push @patch, grep { /^[-+]{3}/ } @$head;
1019
1020 # And then the actual hunks.
1021 push @patch, @_;
1022
1023 return @patch;
1024}
1025
ac083c47
TR
1026sub color_diff {
1027 return map {
1028 colored((/^@/ ? $fraginfo_color :
1029 /^\+/ ? $diff_new_color :
1030 /^-/ ? $diff_old_color :
1031 $diff_plain_color),
1032 $_);
1033 } @_;
1034}
1035
1036sub edit_hunk_manually {
1037 my ($oldtext) = @_;
1038
1039 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
1040 my $fh;
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;
8f0bef6d 1045 my $participle = $patch_mode_flavour{PARTICIPLE};
7b8c7051
JDL
1046 my $is_reverse = $patch_mode_flavour{IS_REVERSE};
1047 my ($remove_plus, $remove_minus) = $is_reverse ? ('-', '+') : ('+', '-');
ac083c47
TR
1048 print $fh <<EOF;
1049# ---
7b8c7051
JDL
1050# To remove '$remove_minus' lines, make them ' ' lines (context).
1051# To remove '$remove_plus' lines, delete them.
ac083c47
TR
1052# Lines starting with # will be removed.
1053#
1054# If the patch applies cleanly, the edited hunk will immediately be
8f0bef6d 1055# marked for $participle. If it does not apply cleanly, you will be given
ac083c47
TR
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.
1058EOF
1059 close $fh;
1060
b4479f07 1061 chomp(my $editor = run_cmd_pipe(qw(git var GIT_EDITOR)));
ac083c47
TR
1062 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
1063
1d398a03
DM
1064 if ($? != 0) {
1065 return undef;
1066 }
1067
ac083c47
TR
1068 open $fh, '<', $hunkfile
1069 or die "failed to open hunk edit file for reading: " . $!;
1070 my @newtext = grep { !/^#/ } <$fh>;
1071 close $fh;
1072 unlink $hunkfile;
1073
1074 # Abort if nothing remains
1075 if (!grep { /\S/ } @newtext) {
1076 return undef;
1077 }
1078
1079 # Reinsert the first hunk header if the user accidentally deleted it
1080 if ($newtext[0] !~ /^@/) {
1081 unshift @newtext, $oldtext->[0];
1082 }
1083 return \@newtext;
1084}
1085
1086sub diff_applies {
9dce8323 1087 return run_git_apply($patch_mode_flavour{APPLY_CHECK} . ' --check',
8f0bef6d 1088 map { @{$_->{TEXT}} } @_);
ac083c47
TR
1089}
1090
ca6ac7f1
TR
1091sub _restore_terminal_and_die {
1092 ReadMode 'restore';
1093 print "\n";
1094 exit 1;
1095}
1096
1097sub prompt_single_character {
1098 if ($use_readkey) {
1099 local $SIG{TERM} = \&_restore_terminal_and_die;
1100 local $SIG{INT} = \&_restore_terminal_and_die;
1101 ReadMode 'cbreak';
1102 my $key = ReadKey 0;
1103 ReadMode 'restore';
b5cc0032
TR
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);
1108 $key .= $next;
1109 }
1110 $key =~ s/\e/^[/;
1111 }
ca6ac7f1
TR
1112 print "$key" if defined $key;
1113 print "\n";
1114 return $key;
1115 } else {
1116 return <STDIN>;
1117 }
1118}
1119
ac083c47
TR
1120sub prompt_yesno {
1121 my ($prompt) = @_;
1122 while (1) {
1123 print colored $prompt_color, $prompt;
ca6ac7f1 1124 my $line = prompt_single_character;
ac083c47
TR
1125 return 0 if $line =~ /^n/i;
1126 return 1 if $line =~ /^y/i;
1127 }
1128}
1129
1130sub edit_hunk_loop {
1131 my ($head, $hunk, $ix) = @_;
1132 my $text = $hunk->[$ix]->{TEXT};
1133
1134 while (1) {
1135 $text = edit_hunk_manually($text);
1136 if (!defined $text) {
1137 return undef;
1138 }
0392513f
JK
1139 my $newhunk = {
1140 TEXT => $text,
1141 TYPE => $hunk->[$ix]->{TYPE},
7a26e653
JH
1142 USE => 1,
1143 DIRTY => 1,
0392513f 1144 };
ac083c47
TR
1145 if (diff_applies($head,
1146 @{$hunk}[0..$ix-1],
1147 $newhunk,
1148 @{$hunk}[$ix+1..$#{$hunk}])) {
1149 $newhunk->{DISPLAY} = [color_diff(@{$text})];
1150 return $newhunk;
1151 }
1152 else {
1153 prompt_yesno(
1154 'Your edited hunk does not apply. Edit again '
1155 . '(saying "no" discards!) [y/n]? '
1156 ) or return undef;
1157 }
1158 }
1159}
1160
5cde71d6 1161sub help_patch_cmd {
8f0bef6d
TR
1162 my $verb = lc $patch_mode_flavour{VERB};
1163 my $target = $patch_mode_flavour{TARGET};
1164 print colored $help_color, <<EOF ;
1165y - $verb this hunk$target
1166n - do not $verb this hunk$target
235e8d59 1167q - quit; do not $verb this hunk or any of the remaining ones
74e42ce1 1168a - $verb this hunk and all later hunks in the file
235e8d59 1169d - do not $verb this hunk or any of the later hunks in the file
070434d0 1170g - select a hunk to go to
dd971cc9 1171/ - search for a hunk matching the given regex
5cde71d6
JH
1172j - leave this hunk undecided, see next undecided hunk
1173J - leave this hunk undecided, see next hunk
1174k - leave this hunk undecided, see previous undecided hunk
1175K - leave this hunk undecided, see previous hunk
835b2aeb 1176s - split the current hunk into smaller hunks
ac083c47 1177e - manually edit the current hunk
280e50c7 1178? - print help
5cde71d6
JH
1179EOF
1180}
1181
8f0bef6d
TR
1182sub apply_patch {
1183 my $cmd = shift;
9dce8323 1184 my $ret = run_git_apply $cmd, @_;
8f0bef6d
TR
1185 if (!$ret) {
1186 print STDERR @_;
1187 }
1188 return $ret;
1189}
1190
4f353658
TR
1191sub apply_patch_for_checkout_commit {
1192 my $reverse = shift;
9dce8323
JH
1193 my $applies_index = run_git_apply 'apply '.$reverse.' --cached --check', @_;
1194 my $applies_worktree = run_git_apply 'apply '.$reverse.' --check', @_;
4f353658
TR
1195
1196 if ($applies_worktree && $applies_index) {
9dce8323
JH
1197 run_git_apply 'apply '.$reverse.' --cached', @_;
1198 run_git_apply 'apply '.$reverse, @_;
4f353658
TR
1199 return 1;
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? ") {
9dce8323 1203 return run_git_apply 'apply '.$reverse, @_;
4f353658
TR
1204 } else {
1205 print colored $error_color, "Nothing was applied.\n";
1206 return 0;
1207 }
1208 } else {
1209 print STDERR @_;
1210 return 0;
1211 }
1212}
1213
5cde71d6 1214sub patch_update_cmd {
8f0bef6d 1215 my @all_mods = list_modified($patch_mode_flavour{FILTER});
4066bd67
JK
1216 error_msg "ignoring unmerged: $_->{VALUE}\n"
1217 for grep { $_->{UNMERGED} } @all_mods;
1218 @all_mods = grep { !$_->{UNMERGED} } @all_mods;
1219
9fe7a643 1220 my @mods = grep { !($_->{BINARY}) } @all_mods;
b63e9950 1221 my @them;
5cde71d6 1222
b63e9950 1223 if (!@mods) {
9fe7a643
TR
1224 if (@all_mods) {
1225 print STDERR "Only binary files changed.\n";
1226 } else {
1227 print STDERR "No changes.\n";
1228 }
b63e9950
WC
1229 return 0;
1230 }
1231 if ($patch_mode) {
1232 @them = @mods;
1233 }
1234 else {
1235 @them = list_and_choose({ PROMPT => 'Patch update',
1236 HEADER => $status_head, },
1237 @mods);
1238 }
12db334e 1239 for (@them) {
9a7a1e03 1240 return 0 if patch_update_file($_->{VALUE});
12db334e 1241 }
a7d9da6c 1242}
5cde71d6 1243
3f6aff68
WP
1244# Generate a one line summary of a hunk.
1245sub summarize_hunk {
1246 my $rhunk = shift;
1247 my $summary = $rhunk->{TEXT}[0];
1248
1249 # Keep the line numbers, discard extra context.
1250 $summary =~ s/@@(.*?)@@.*/$1 /s;
1251 $summary .= " " x (20 - length $summary);
1252
1253 # Add some user context.
1254 for my $line (@{$rhunk->{TEXT}}) {
1255 if ($line =~ m/^[+-].*\w/) {
1256 $summary .= $line;
1257 last;
1258 }
1259 }
1260
1261 chomp $summary;
1262 return substr($summary, 0, 80) . "\n";
1263}
1264
1265
1266# Print a one-line summary of each hunk in the array ref in
41ccfdd9 1267# the first argument, starting with the index in the 2nd.
3f6aff68
WP
1268sub display_hunks {
1269 my ($hunks, $i) = @_;
1270 my $ctr = 0;
1271 $i ||= 0;
1272 for (; $i < @$hunks && $ctr < 20; $i++, $ctr++) {
1273 my $status = " ";
1274 if (defined $hunks->[$i]{USE}) {
1275 $status = $hunks->[$i]{USE} ? "+" : "-";
1276 }
1277 printf "%s%2d: %s",
1278 $status,
1279 $i + 1,
1280 summarize_hunk($hunks->[$i]);
1281 }
1282 return $i;
1283}
1284
a7d9da6c 1285sub patch_update_file {
9a7a1e03 1286 my $quit = 0;
5cde71d6 1287 my ($ix, $num);
a7d9da6c 1288 my $path = shift;
5cde71d6 1289 my ($head, @hunk) = parse_diff($path);
24ab81ae 1290 ($head, my $mode, my $deletion) = parse_diff_header($head);
4af756f3
WC
1291 for (@{$head->{DISPLAY}}) {
1292 print;
1293 }
ca724686
JK
1294
1295 if (@{$mode->{TEXT}}) {
0392513f 1296 unshift @hunk, $mode;
ca724686 1297 }
8947fdd5
JK
1298 if (@{$deletion->{TEXT}}) {
1299 foreach my $hunk (@hunk) {
1300 push @{$deletion->{TEXT}}, @{$hunk->{TEXT}};
1301 push @{$deletion->{DISPLAY}}, @{$hunk->{DISPLAY}};
1302 }
24ab81ae
JK
1303 @hunk = ($deletion);
1304 }
ca724686 1305
5cde71d6
JH
1306 $num = scalar @hunk;
1307 $ix = 0;
1308
1309 while (1) {
835b2aeb 1310 my ($prev, $next, $other, $undecided, $i);
5cde71d6
JH
1311 $other = '';
1312
1313 if ($num <= $ix) {
1314 $ix = 0;
1315 }
835b2aeb 1316 for ($i = 0; $i < $ix; $i++) {
5cde71d6
JH
1317 if (!defined $hunk[$i]{USE}) {
1318 $prev = 1;
57886bc7 1319 $other .= ',k';
5cde71d6
JH
1320 last;
1321 }
1322 }
1323 if ($ix) {
57886bc7 1324 $other .= ',K';
5cde71d6 1325 }
835b2aeb 1326 for ($i = $ix + 1; $i < $num; $i++) {
5cde71d6
JH
1327 if (!defined $hunk[$i]{USE}) {
1328 $next = 1;
57886bc7 1329 $other .= ',j';
5cde71d6
JH
1330 last;
1331 }
1332 }
1333 if ($ix < $num - 1) {
57886bc7 1334 $other .= ',J';
5cde71d6 1335 }
070434d0 1336 if ($num > 1) {
4404b2e3 1337 $other .= ',g';
070434d0 1338 }
835b2aeb 1339 for ($i = 0; $i < $num; $i++) {
5cde71d6
JH
1340 if (!defined $hunk[$i]{USE}) {
1341 $undecided = 1;
1342 last;
1343 }
1344 }
1345 last if (!$undecided);
1346
0392513f
JK
1347 if ($hunk[$ix]{TYPE} eq 'hunk' &&
1348 hunk_splittable($hunk[$ix]{TEXT})) {
57886bc7 1349 $other .= ',s';
835b2aeb 1350 }
0392513f
JK
1351 if ($hunk[$ix]{TYPE} eq 'hunk') {
1352 $other .= ',e';
1353 }
4af756f3
WC
1354 for (@{$hunk[$ix]{DISPLAY}}) {
1355 print;
1356 }
8f0bef6d 1357 print colored $prompt_color, $patch_mode_flavour{VERB},
24ab81ae
JK
1358 ($hunk[$ix]{TYPE} eq 'mode' ? ' mode change' :
1359 $hunk[$ix]{TYPE} eq 'deletion' ? ' deletion' :
1360 ' this hunk'),
8f0bef6d 1361 $patch_mode_flavour{TARGET},
a2fc8d65 1362 " [y,n,q,a,d,/$other,?]? ";
ca6ac7f1 1363 my $line = prompt_single_character;
a8bec7ab 1364 last unless defined $line;
5cde71d6
JH
1365 if ($line) {
1366 if ($line =~ /^y/i) {
1367 $hunk[$ix]{USE} = 1;
1368 }
1369 elsif ($line =~ /^n/i) {
1370 $hunk[$ix]{USE} = 0;
1371 }
1372 elsif ($line =~ /^a/i) {
1373 while ($ix < $num) {
1374 if (!defined $hunk[$ix]{USE}) {
1375 $hunk[$ix]{USE} = 1;
1376 }
1377 $ix++;
1378 }
1379 next;
1380 }
070434d0
WP
1381 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1382 my $response = $1;
1383 my $no = $ix > 10 ? $ix - 10 : 0;
1384 while ($response eq '') {
1385 my $extra = "";
1386 $no = display_hunks(\@hunk, $no);
1387 if ($no < $num) {
1388 $extra = " (<ret> to see more)";
1389 }
1390 print "go to which hunk$extra? ";
1391 $response = <STDIN>;
68c02d7c
TR
1392 if (!defined $response) {
1393 $response = '';
1394 }
070434d0
WP
1395 chomp $response;
1396 }
1397 if ($response !~ /^\s*\d+\s*$/) {
a3019736 1398 error_msg "Invalid number: '$response'\n";
070434d0
WP
1399 } elsif (0 < $response && $response <= $num) {
1400 $ix = $response - 1;
1401 } else {
a3019736 1402 error_msg "Sorry, only $num hunks available.\n";
070434d0
WP
1403 }
1404 next;
1405 }
5cde71d6
JH
1406 elsif ($line =~ /^d/i) {
1407 while ($ix < $num) {
1408 if (!defined $hunk[$ix]{USE}) {
1409 $hunk[$ix]{USE} = 0;
1410 }
1411 $ix++;
1412 }
1413 next;
1414 }
9a7a1e03 1415 elsif ($line =~ /^q/i) {
f5ea3f2b
JH
1416 for ($i = 0; $i < $num; $i++) {
1417 if (!defined $hunk[$i]{USE}) {
1418 $hunk[$i]{USE} = 0;
9a7a1e03 1419 }
9a7a1e03
MM
1420 }
1421 $quit = 1;
f5ea3f2b 1422 last;
9a7a1e03 1423 }
dd971cc9 1424 elsif ($line =~ m|^/(.*)|) {
ca6ac7f1
TR
1425 my $regex = $1;
1426 if ($1 eq "") {
1427 print colored $prompt_color, "search for regex? ";
1428 $regex = <STDIN>;
1429 if (defined $regex) {
1430 chomp $regex;
1431 }
1432 }
dd971cc9
WP
1433 my $search_string;
1434 eval {
ca6ac7f1 1435 $search_string = qr{$regex}m;
dd971cc9
WP
1436 };
1437 if ($@) {
1438 my ($err,$exp) = ($@, $1);
1439 $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
a3019736 1440 error_msg "Malformed search regexp $exp: $err\n";
dd971cc9
WP
1441 next;
1442 }
1443 my $iy = $ix;
1444 while (1) {
1445 my $text = join ("", @{$hunk[$iy]{TEXT}});
1446 last if ($text =~ $search_string);
1447 $iy++;
1448 $iy = 0 if ($iy >= $num);
1449 if ($ix == $iy) {
a3019736 1450 error_msg "No hunk matches the given pattern\n";
dd971cc9
WP
1451 last;
1452 }
1453 }
1454 $ix = $iy;
1455 next;
1456 }
ace30ba8
WP
1457 elsif ($line =~ /^K/) {
1458 if ($other =~ /K/) {
1459 $ix--;
1460 }
1461 else {
a3019736 1462 error_msg "No previous hunk\n";
ace30ba8 1463 }
5cde71d6
JH
1464 next;
1465 }
ace30ba8
WP
1466 elsif ($line =~ /^J/) {
1467 if ($other =~ /J/) {
1468 $ix++;
1469 }
1470 else {
a3019736 1471 error_msg "No next hunk\n";
ace30ba8 1472 }
5cde71d6
JH
1473 next;
1474 }
ace30ba8
WP
1475 elsif ($line =~ /^k/) {
1476 if ($other =~ /k/) {
1477 while (1) {
1478 $ix--;
1479 last if (!$ix ||
1480 !defined $hunk[$ix]{USE});
1481 }
1482 }
1483 else {
a3019736 1484 error_msg "No previous hunk\n";
5cde71d6
JH
1485 }
1486 next;
1487 }
ace30ba8
WP
1488 elsif ($line =~ /^j/) {
1489 if ($other !~ /j/) {
a3019736 1490 error_msg "No next hunk\n";
ace30ba8 1491 next;
5cde71d6 1492 }
5cde71d6 1493 }
835b2aeb 1494 elsif ($other =~ /s/ && $line =~ /^s/) {
4af756f3 1495 my @split = split_hunk($hunk[$ix]{TEXT}, $hunk[$ix]{DISPLAY});
835b2aeb 1496 if (1 < @split) {
b4c61ed6 1497 print colored $header_color, "Split into ",
835b2aeb
JH
1498 scalar(@split), " hunks.\n";
1499 }
4af756f3 1500 splice (@hunk, $ix, 1, @split);
835b2aeb
JH
1501 $num = scalar @hunk;
1502 next;
1503 }
0392513f 1504 elsif ($other =~ /e/ && $line =~ /^e/) {
ac083c47
TR
1505 my $newhunk = edit_hunk_loop($head, \@hunk, $ix);
1506 if (defined $newhunk) {
1507 splice @hunk, $ix, 1, $newhunk;
1508 }
1509 }
5cde71d6
JH
1510 else {
1511 help_patch_cmd($other);
1512 next;
1513 }
1514 # soft increment
1515 while (1) {
1516 $ix++;
1517 last if ($ix >= $num ||
1518 !defined $hunk[$ix]{USE});
1519 }
1520 }
1521 }
1522
7a26e653
JH
1523 @hunk = coalesce_overlapping_hunks(@hunk);
1524
7b40a455 1525 my $n_lofs = 0;
5cde71d6
JH
1526 my @result = ();
1527 for (@hunk) {
8cbd4310
TR
1528 if ($_->{USE}) {
1529 push @result, @{$_->{TEXT}};
5cde71d6
JH
1530 }
1531 }
1532
1533 if (@result) {
e1327ed5 1534 my @patch = reassemble_patch($head->{TEXT}, @result);
8f0bef6d
TR
1535 my $apply_routine = $patch_mode_flavour{APPLY};
1536 &$apply_routine(@patch);
5cde71d6
JH
1537 refresh();
1538 }
1539
1540 print "\n";
9a7a1e03 1541 return $quit;
5cde71d6
JH
1542}
1543
1544sub diff_cmd {
1545 my @mods = list_modified('index-only');
1546 @mods = grep { !($_->{BINARY}) } @mods;
1547 return if (!@mods);
1548 my (@them) = list_and_choose({ PROMPT => 'Review diff',
1549 IMMEDIATE => 1,
1550 HEADER => $status_head, },
1551 @mods);
1552 return if (!@them);
18bc7616
JK
1553 my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
1554 system(qw(git diff -p --cached), $reference, '--',
1555 map { $_->{VALUE} } @them);
5cde71d6
JH
1556}
1557
1558sub quit_cmd {
1559 print "Bye.\n";
1560 exit(0);
1561}
1562
1563sub help_cmd {
b4c61ed6 1564 print colored $help_color, <<\EOF ;
5cde71d6
JH
1565status - show paths with changes
1566update - add working tree state to the staged set of changes
1567revert - revert staged set of changes back to the HEAD version
1568patch - pick hunks and update selectively
1569diff - view diff between HEAD and index
1570add untracked - add contents of untracked files to the staged set of changes
1571EOF
1572}
1573
b63e9950
WC
1574sub process_args {
1575 return unless @ARGV;
1576 my $arg = shift @ARGV;
d002ef4d
TR
1577 if ($arg =~ /--patch(?:=(.*))?/) {
1578 if (defined $1) {
1579 if ($1 eq 'reset') {
1580 $patch_mode = 'reset_head';
1581 $patch_mode_revision = 'HEAD';
1582 $arg = shift @ARGV or die "missing --";
1583 if ($arg ne '--') {
1584 $patch_mode_revision = $arg;
1585 $patch_mode = ($arg eq 'HEAD' ?
1586 'reset_head' : 'reset_nothead');
1587 $arg = shift @ARGV or die "missing --";
1588 }
4f353658
TR
1589 } elsif ($1 eq 'checkout') {
1590 $arg = shift @ARGV or die "missing --";
1591 if ($arg eq '--') {
1592 $patch_mode = 'checkout_index';
1593 } else {
1594 $patch_mode_revision = $arg;
1595 $patch_mode = ($arg eq 'HEAD' ?
1596 'checkout_head' : 'checkout_nothead');
1597 $arg = shift @ARGV or die "missing --";
1598 }
dda1f2a5
TR
1599 } elsif ($1 eq 'stage' or $1 eq 'stash') {
1600 $patch_mode = $1;
d002ef4d
TR
1601 $arg = shift @ARGV or die "missing --";
1602 } else {
1603 die "unknown --patch mode: $1";
1604 }
1605 } else {
1606 $patch_mode = 'stage';
1607 $arg = shift @ARGV or die "missing --";
1608 }
b63e9950
WC
1609 die "invalid argument $arg, expecting --"
1610 unless $arg eq "--";
d002ef4d 1611 %patch_mode_flavour = %{$patch_modes{$patch_mode}};
b63e9950
WC
1612 }
1613 elsif ($arg ne "--") {
1614 die "invalid argument $arg, expecting --";
1615 }
1616}
1617
5cde71d6
JH
1618sub main_loop {
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, ],
1627 );
1628 while (1) {
1629 my ($it) = list_and_choose({ PROMPT => 'What now',
1630 SINGLETON => 1,
1631 LIST_FLAT => 4,
1632 HEADER => '*** Commands ***',
c95c0248 1633 ON_EOF => \&quit_cmd,
5cde71d6
JH
1634 IMMEDIATE => 1 }, @cmd);
1635 if ($it) {
1636 eval {
1637 $it->[1]->();
1638 };
1639 if ($@) {
1640 print "$@";
1641 }
1642 }
1643 }
1644}
1645
b63e9950 1646process_args();
5cde71d6 1647refresh();
b63e9950
WC
1648if ($patch_mode) {
1649 patch_update_cmd();
1650}
1651else {
1652 status_cmd();
1653 main_loop();
1654}