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