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