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