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