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