git add -i: Fix parsing of abbreviated hunk headers
[git/git.git] / git-add--interactive.perl
1 #!/usr/bin/perl -w
2
3 use strict;
4
5 sub run_cmd_pipe {
6 if ($^O eq 'MSWin32') {
7 my @invalid = grep {m/[":*]/} @_;
8 die "$^O does not support: @invalid\n" if @invalid;
9 my @args = map { m/ /o ? "\"$_\"": $_ } @_;
10 return qx{@args};
11 } else {
12 my $fh = undef;
13 open($fh, '-|', @_) or die;
14 return <$fh>;
15 }
16 }
17
18 my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));
19
20 if (!defined $GIT_DIR) {
21 exit(1); # rev-parse would have already said "not a git repo"
22 }
23 chomp($GIT_DIR);
24
25 sub refresh {
26 my $fh;
27 open $fh, 'git update-index --refresh |'
28 or die;
29 while (<$fh>) {
30 ;# ignore 'needs update'
31 }
32 close $fh;
33 }
34
35 sub list_untracked {
36 map {
37 chomp $_;
38 $_;
39 }
40 run_cmd_pipe(qw(git ls-files --others
41 --exclude-per-directory=.gitignore),
42 "--exclude-from=$GIT_DIR/info/exclude",
43 '--', @_);
44 }
45
46 my $status_fmt = '%12s %12s %s';
47 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
48
49 # Returns list of hashes, contents of each of which are:
50 # PRINT: print message
51 # VALUE: pathname
52 # BINARY: is a binary path
53 # INDEX: is index different from HEAD?
54 # FILE: is file different from index?
55 # INDEX_ADDDEL: is it add/delete between HEAD and index?
56 # FILE_ADDDEL: is it add/delete between index and file?
57
58 sub list_modified {
59 my ($only) = @_;
60 my (%data, @return);
61 my ($add, $del, $adddel, $file);
62
63 for (run_cmd_pipe(qw(git diff-index --cached
64 --numstat --summary HEAD))) {
65 if (($add, $del, $file) =
66 /^([-\d]+) ([-\d]+) (.*)/) {
67 my ($change, $bin);
68 if ($add eq '-' && $del eq '-') {
69 $change = 'binary';
70 $bin = 1;
71 }
72 else {
73 $change = "+$add/-$del";
74 }
75 $data{$file} = {
76 INDEX => $change,
77 BINARY => $bin,
78 FILE => 'nothing',
79 }
80 }
81 elsif (($adddel, $file) =
82 /^ (create|delete) mode [0-7]+ (.*)$/) {
83 $data{$file}{INDEX_ADDDEL} = $adddel;
84 }
85 }
86
87 for (run_cmd_pipe(qw(git diff-files --numstat --summary))) {
88 if (($add, $del, $file) =
89 /^([-\d]+) ([-\d]+) (.*)/) {
90 if (!exists $data{$file}) {
91 $data{$file} = +{
92 INDEX => 'unchanged',
93 BINARY => 0,
94 };
95 }
96 my ($change, $bin);
97 if ($add eq '-' && $del eq '-') {
98 $change = 'binary';
99 $bin = 1;
100 }
101 else {
102 $change = "+$add/-$del";
103 }
104 $data{$file}{FILE} = $change;
105 if ($bin) {
106 $data{$file}{BINARY} = 1;
107 }
108 }
109 elsif (($adddel, $file) =
110 /^ (create|delete) mode [0-7]+ (.*)$/) {
111 $data{$file}{FILE_ADDDEL} = $adddel;
112 }
113 }
114
115 for (sort keys %data) {
116 my $it = $data{$_};
117
118 if ($only) {
119 if ($only eq 'index-only') {
120 next if ($it->{INDEX} eq 'unchanged');
121 }
122 if ($only eq 'file-only') {
123 next if ($it->{FILE} eq 'nothing');
124 }
125 }
126 push @return, +{
127 VALUE => $_,
128 PRINT => (sprintf $status_fmt,
129 $it->{INDEX}, $it->{FILE}, $_),
130 %$it,
131 };
132 }
133 return @return;
134 }
135
136 sub find_unique {
137 my ($string, @stuff) = @_;
138 my $found = undef;
139 for (my $i = 0; $i < @stuff; $i++) {
140 my $it = $stuff[$i];
141 my $hit = undef;
142 if (ref $it) {
143 if ((ref $it) eq 'ARRAY') {
144 $it = $it->[0];
145 }
146 else {
147 $it = $it->{VALUE};
148 }
149 }
150 eval {
151 if ($it =~ /^$string/) {
152 $hit = 1;
153 };
154 };
155 if (defined $hit && defined $found) {
156 return undef;
157 }
158 if ($hit) {
159 $found = $i + 1;
160 }
161 }
162 return $found;
163 }
164
165 sub list_and_choose {
166 my ($opts, @stuff) = @_;
167 my (@chosen, @return);
168 my $i;
169
170 TOPLOOP:
171 while (1) {
172 my $last_lf = 0;
173
174 if ($opts->{HEADER}) {
175 if (!$opts->{LIST_FLAT}) {
176 print " ";
177 }
178 print "$opts->{HEADER}\n";
179 }
180 for ($i = 0; $i < @stuff; $i++) {
181 my $chosen = $chosen[$i] ? '*' : ' ';
182 my $print = $stuff[$i];
183 if (ref $print) {
184 if ((ref $print) eq 'ARRAY') {
185 $print = $print->[0];
186 }
187 else {
188 $print = $print->{PRINT};
189 }
190 }
191 printf("%s%2d: %s", $chosen, $i+1, $print);
192 if (($opts->{LIST_FLAT}) &&
193 (($i + 1) % ($opts->{LIST_FLAT}))) {
194 print "\t";
195 $last_lf = 0;
196 }
197 else {
198 print "\n";
199 $last_lf = 1;
200 }
201 }
202 if (!$last_lf) {
203 print "\n";
204 }
205
206 return if ($opts->{LIST_ONLY});
207
208 print $opts->{PROMPT};
209 if ($opts->{SINGLETON}) {
210 print "> ";
211 }
212 else {
213 print ">> ";
214 }
215 my $line = <STDIN>;
216 if (!$line) {
217 print "\n";
218 $opts->{ON_EOF}->() if $opts->{ON_EOF};
219 last;
220 }
221 chomp $line;
222 last if $line eq '';
223 for my $choice (split(/[\s,]+/, $line)) {
224 my $choose = 1;
225 my ($bottom, $top);
226
227 # Input that begins with '-'; unchoose
228 if ($choice =~ s/^-//) {
229 $choose = 0;
230 }
231 # A range can be specified like 5-7
232 if ($choice =~ /^(\d+)-(\d+)$/) {
233 ($bottom, $top) = ($1, $2);
234 }
235 elsif ($choice =~ /^\d+$/) {
236 $bottom = $top = $choice;
237 }
238 elsif ($choice eq '*') {
239 $bottom = 1;
240 $top = 1 + @stuff;
241 }
242 else {
243 $bottom = $top = find_unique($choice, @stuff);
244 if (!defined $bottom) {
245 print "Huh ($choice)?\n";
246 next TOPLOOP;
247 }
248 }
249 if ($opts->{SINGLETON} && $bottom != $top) {
250 print "Huh ($choice)?\n";
251 next TOPLOOP;
252 }
253 for ($i = $bottom-1; $i <= $top-1; $i++) {
254 next if (@stuff <= $i || $i < 0);
255 $chosen[$i] = $choose;
256 }
257 }
258 last if ($opts->{IMMEDIATE});
259 }
260 for ($i = 0; $i < @stuff; $i++) {
261 if ($chosen[$i]) {
262 push @return, $stuff[$i];
263 }
264 }
265 return @return;
266 }
267
268 sub status_cmd {
269 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
270 list_modified());
271 print "\n";
272 }
273
274 sub say_n_paths {
275 my $did = shift @_;
276 my $cnt = scalar @_;
277 print "$did ";
278 if (1 < $cnt) {
279 print "$cnt paths\n";
280 }
281 else {
282 print "one path\n";
283 }
284 }
285
286 sub update_cmd {
287 my @mods = list_modified('file-only');
288 return if (!@mods);
289
290 my @update = list_and_choose({ PROMPT => 'Update',
291 HEADER => $status_head, },
292 @mods);
293 if (@update) {
294 system(qw(git update-index --add --remove --),
295 map { $_->{VALUE} } @update);
296 say_n_paths('updated', @update);
297 }
298 print "\n";
299 }
300
301 sub revert_cmd {
302 my @update = list_and_choose({ PROMPT => 'Revert',
303 HEADER => $status_head, },
304 list_modified());
305 if (@update) {
306 my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
307 map { $_->{VALUE} } @update);
308 my $fh;
309 open $fh, '| git update-index --index-info'
310 or die;
311 for (@lines) {
312 print $fh $_;
313 }
314 close($fh);
315 for (@update) {
316 if ($_->{INDEX_ADDDEL} &&
317 $_->{INDEX_ADDDEL} eq 'create') {
318 system(qw(git update-index --force-remove --),
319 $_->{VALUE});
320 print "note: $_->{VALUE} is untracked now.\n";
321 }
322 }
323 refresh();
324 say_n_paths('reverted', @update);
325 }
326 print "\n";
327 }
328
329 sub add_untracked_cmd {
330 my @add = list_and_choose({ PROMPT => 'Add untracked' },
331 list_untracked());
332 if (@add) {
333 system(qw(git update-index --add --), @add);
334 say_n_paths('added', @add);
335 }
336 print "\n";
337 }
338
339 sub parse_diff {
340 my ($path) = @_;
341 my @diff = run_cmd_pipe(qw(git diff-files -p --), $path);
342 my (@hunk) = { TEXT => [] };
343
344 for (@diff) {
345 if (/^@@ /) {
346 push @hunk, { TEXT => [] };
347 }
348 push @{$hunk[-1]{TEXT}}, $_;
349 }
350 return @hunk;
351 }
352
353 sub hunk_splittable {
354 my ($text) = @_;
355
356 my @s = split_hunk($text);
357 return (1 < @s);
358 }
359
360 sub parse_hunk_header {
361 my ($line) = @_;
362 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
363 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
364 $o_cnt = 1 unless defined $o_cnt;
365 $n_cnt = 1 unless defined $n_cnt;
366 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
367 }
368
369 sub split_hunk {
370 my ($text) = @_;
371 my @split = ();
372
373 # If there are context lines in the middle of a hunk,
374 # it can be split, but we would need to take care of
375 # overlaps later.
376
377 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) = parse_hunk_header($text->[0]);
378 my $hunk_start = 1;
379 my $next_hunk_start;
380
381 OUTER:
382 while (1) {
383 my $next_hunk_start = undef;
384 my $i = $hunk_start - 1;
385 my $this = +{
386 TEXT => [],
387 OLD => $o_ofs,
388 NEW => $n_ofs,
389 OCNT => 0,
390 NCNT => 0,
391 ADDDEL => 0,
392 POSTCTX => 0,
393 };
394
395 while (++$i < @$text) {
396 my $line = $text->[$i];
397 if ($line =~ /^ /) {
398 if ($this->{ADDDEL} &&
399 !defined $next_hunk_start) {
400 # We have seen leading context and
401 # adds/dels and then here is another
402 # context, which is trailing for this
403 # split hunk and leading for the next
404 # one.
405 $next_hunk_start = $i;
406 }
407 push @{$this->{TEXT}}, $line;
408 $this->{OCNT}++;
409 $this->{NCNT}++;
410 if (defined $next_hunk_start) {
411 $this->{POSTCTX}++;
412 }
413 next;
414 }
415
416 # add/del
417 if (defined $next_hunk_start) {
418 # We are done with the current hunk and
419 # this is the first real change for the
420 # next split one.
421 $hunk_start = $next_hunk_start;
422 $o_ofs = $this->{OLD} + $this->{OCNT};
423 $n_ofs = $this->{NEW} + $this->{NCNT};
424 $o_ofs -= $this->{POSTCTX};
425 $n_ofs -= $this->{POSTCTX};
426 push @split, $this;
427 redo OUTER;
428 }
429 push @{$this->{TEXT}}, $line;
430 $this->{ADDDEL}++;
431 if ($line =~ /^-/) {
432 $this->{OCNT}++;
433 }
434 else {
435 $this->{NCNT}++;
436 }
437 }
438
439 push @split, $this;
440 last;
441 }
442
443 for my $hunk (@split) {
444 $o_ofs = $hunk->{OLD};
445 $n_ofs = $hunk->{NEW};
446 $o_cnt = $hunk->{OCNT};
447 $n_cnt = $hunk->{NCNT};
448
449 my $head = ("@@ -$o_ofs" .
450 (($o_cnt != 1) ? ",$o_cnt" : '') .
451 " +$n_ofs" .
452 (($n_cnt != 1) ? ",$n_cnt" : '') .
453 " @@\n");
454 unshift @{$hunk->{TEXT}}, $head;
455 }
456 return map { $_->{TEXT} } @split;
457 }
458
459 sub find_last_o_ctx {
460 my ($it) = @_;
461 my $text = $it->{TEXT};
462 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) = parse_hunk_header($text->[0]);
463 my $i = @{$text};
464 my $last_o_ctx = $o_ofs + $o_cnt;
465 while (0 < --$i) {
466 my $line = $text->[$i];
467 if ($line =~ /^ /) {
468 $last_o_ctx--;
469 next;
470 }
471 last;
472 }
473 return $last_o_ctx;
474 }
475
476 sub merge_hunk {
477 my ($prev, $this) = @_;
478 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
479 parse_hunk_header($prev->{TEXT}[0]);
480 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
481 parse_hunk_header($this->{TEXT}[0]);
482
483 my (@line, $i, $ofs, $o_cnt, $n_cnt);
484 $ofs = $o0_ofs;
485 $o_cnt = $n_cnt = 0;
486 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
487 my $line = $prev->{TEXT}[$i];
488 if ($line =~ /^\+/) {
489 $n_cnt++;
490 push @line, $line;
491 next;
492 }
493
494 last if ($o1_ofs <= $ofs);
495
496 $o_cnt++;
497 $ofs++;
498 if ($line =~ /^ /) {
499 $n_cnt++;
500 }
501 push @line, $line;
502 }
503
504 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
505 my $line = $this->{TEXT}[$i];
506 if ($line =~ /^\+/) {
507 $n_cnt++;
508 push @line, $line;
509 next;
510 }
511 $ofs++;
512 $o_cnt++;
513 if ($line =~ /^ /) {
514 $n_cnt++;
515 }
516 push @line, $line;
517 }
518 my $head = ("@@ -$o0_ofs" .
519 (($o_cnt != 1) ? ",$o_cnt" : '') .
520 " +$n0_ofs" .
521 (($n_cnt != 1) ? ",$n_cnt" : '') .
522 " @@\n");
523 @{$prev->{TEXT}} = ($head, @line);
524 }
525
526 sub coalesce_overlapping_hunks {
527 my (@in) = @_;
528 my @out = ();
529
530 my ($last_o_ctx);
531
532 for (grep { $_->{USE} } @in) {
533 my $text = $_->{TEXT};
534 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
535 parse_hunk_header($text->[0]);
536 if (defined $last_o_ctx &&
537 $o_ofs <= $last_o_ctx) {
538 merge_hunk($out[-1], $_);
539 }
540 else {
541 push @out, $_;
542 }
543 $last_o_ctx = find_last_o_ctx($out[-1]);
544 }
545 return @out;
546 }
547
548 sub help_patch_cmd {
549 print <<\EOF ;
550 y - stage this hunk
551 n - do not stage this hunk
552 a - stage this and all the remaining hunks
553 d - do not stage this hunk nor any of the remaining hunks
554 j - leave this hunk undecided, see next undecided hunk
555 J - leave this hunk undecided, see next hunk
556 k - leave this hunk undecided, see previous undecided hunk
557 K - leave this hunk undecided, see previous hunk
558 s - split the current hunk into smaller hunks
559 EOF
560 }
561
562 sub patch_update_cmd {
563 my @mods = list_modified('file-only');
564 @mods = grep { !($_->{BINARY}) } @mods;
565 return if (!@mods);
566
567 my ($it) = list_and_choose({ PROMPT => 'Patch update',
568 SINGLETON => 1,
569 IMMEDIATE => 1,
570 HEADER => $status_head, },
571 @mods);
572 return if (!$it);
573
574 my ($ix, $num);
575 my $path = $it->{VALUE};
576 my ($head, @hunk) = parse_diff($path);
577 for (@{$head->{TEXT}}) {
578 print;
579 }
580 $num = scalar @hunk;
581 $ix = 0;
582
583 while (1) {
584 my ($prev, $next, $other, $undecided, $i);
585 $other = '';
586
587 if ($num <= $ix) {
588 $ix = 0;
589 }
590 for ($i = 0; $i < $ix; $i++) {
591 if (!defined $hunk[$i]{USE}) {
592 $prev = 1;
593 $other .= '/k';
594 last;
595 }
596 }
597 if ($ix) {
598 $other .= '/K';
599 }
600 for ($i = $ix + 1; $i < $num; $i++) {
601 if (!defined $hunk[$i]{USE}) {
602 $next = 1;
603 $other .= '/j';
604 last;
605 }
606 }
607 if ($ix < $num - 1) {
608 $other .= '/J';
609 }
610 for ($i = 0; $i < $num; $i++) {
611 if (!defined $hunk[$i]{USE}) {
612 $undecided = 1;
613 last;
614 }
615 }
616 last if (!$undecided);
617
618 if (hunk_splittable($hunk[$ix]{TEXT})) {
619 $other .= '/s';
620 }
621 for (@{$hunk[$ix]{TEXT}}) {
622 print;
623 }
624 print "Stage this hunk [y/n/a/d$other/?]? ";
625 my $line = <STDIN>;
626 if ($line) {
627 if ($line =~ /^y/i) {
628 $hunk[$ix]{USE} = 1;
629 }
630 elsif ($line =~ /^n/i) {
631 $hunk[$ix]{USE} = 0;
632 }
633 elsif ($line =~ /^a/i) {
634 while ($ix < $num) {
635 if (!defined $hunk[$ix]{USE}) {
636 $hunk[$ix]{USE} = 1;
637 }
638 $ix++;
639 }
640 next;
641 }
642 elsif ($line =~ /^d/i) {
643 while ($ix < $num) {
644 if (!defined $hunk[$ix]{USE}) {
645 $hunk[$ix]{USE} = 0;
646 }
647 $ix++;
648 }
649 next;
650 }
651 elsif ($other =~ /K/ && $line =~ /^K/) {
652 $ix--;
653 next;
654 }
655 elsif ($other =~ /J/ && $line =~ /^J/) {
656 $ix++;
657 next;
658 }
659 elsif ($other =~ /k/ && $line =~ /^k/) {
660 while (1) {
661 $ix--;
662 last if (!$ix ||
663 !defined $hunk[$ix]{USE});
664 }
665 next;
666 }
667 elsif ($other =~ /j/ && $line =~ /^j/) {
668 while (1) {
669 $ix++;
670 last if ($ix >= $num ||
671 !defined $hunk[$ix]{USE});
672 }
673 next;
674 }
675 elsif ($other =~ /s/ && $line =~ /^s/) {
676 my @split = split_hunk($hunk[$ix]{TEXT});
677 if (1 < @split) {
678 print "Split into ",
679 scalar(@split), " hunks.\n";
680 }
681 splice(@hunk, $ix, 1,
682 map { +{ TEXT => $_, USE => undef } }
683 @split);
684 $num = scalar @hunk;
685 next;
686 }
687 else {
688 help_patch_cmd($other);
689 next;
690 }
691 # soft increment
692 while (1) {
693 $ix++;
694 last if ($ix >= $num ||
695 !defined $hunk[$ix]{USE});
696 }
697 }
698 }
699
700 @hunk = coalesce_overlapping_hunks(@hunk);
701
702 my ($o_lofs, $n_lofs) = (0, 0);
703 my @result = ();
704 for (@hunk) {
705 my $text = $_->{TEXT};
706 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
707 parse_hunk_header($text->[0]);
708
709 if (!$_->{USE}) {
710 # We would have added ($n_cnt - $o_cnt) lines
711 # to the postimage if we were to use this hunk,
712 # but we didn't. So the line number that the next
713 # hunk starts at would be shifted by that much.
714 $n_lofs -= ($n_cnt - $o_cnt);
715 next;
716 }
717 else {
718 if ($n_lofs) {
719 $n_ofs += $n_lofs;
720 $text->[0] = ("@@ -$o_ofs" .
721 (($o_cnt != 1)
722 ? ",$o_cnt" : '') .
723 " +$n_ofs" .
724 (($n_cnt != 1)
725 ? ",$n_cnt" : '') .
726 " @@\n");
727 }
728 for (@$text) {
729 push @result, $_;
730 }
731 }
732 }
733
734 if (@result) {
735 my $fh;
736
737 open $fh, '| git apply --cached';
738 for (@{$head->{TEXT}}, @result) {
739 print $fh $_;
740 }
741 if (!close $fh) {
742 for (@{$head->{TEXT}}, @result) {
743 print STDERR $_;
744 }
745 }
746 refresh();
747 }
748
749 print "\n";
750 }
751
752 sub diff_cmd {
753 my @mods = list_modified('index-only');
754 @mods = grep { !($_->{BINARY}) } @mods;
755 return if (!@mods);
756 my (@them) = list_and_choose({ PROMPT => 'Review diff',
757 IMMEDIATE => 1,
758 HEADER => $status_head, },
759 @mods);
760 return if (!@them);
761 system(qw(git diff-index -p --cached HEAD --),
762 map { $_->{VALUE} } @them);
763 }
764
765 sub quit_cmd {
766 print "Bye.\n";
767 exit(0);
768 }
769
770 sub help_cmd {
771 print <<\EOF ;
772 status - show paths with changes
773 update - add working tree state to the staged set of changes
774 revert - revert staged set of changes back to the HEAD version
775 patch - pick hunks and update selectively
776 diff - view diff between HEAD and index
777 add untracked - add contents of untracked files to the staged set of changes
778 EOF
779 }
780
781 sub main_loop {
782 my @cmd = ([ 'status', \&status_cmd, ],
783 [ 'update', \&update_cmd, ],
784 [ 'revert', \&revert_cmd, ],
785 [ 'add untracked', \&add_untracked_cmd, ],
786 [ 'patch', \&patch_update_cmd, ],
787 [ 'diff', \&diff_cmd, ],
788 [ 'quit', \&quit_cmd, ],
789 [ 'help', \&help_cmd, ],
790 );
791 while (1) {
792 my ($it) = list_and_choose({ PROMPT => 'What now',
793 SINGLETON => 1,
794 LIST_FLAT => 4,
795 HEADER => '*** Commands ***',
796 ON_EOF => \&quit_cmd,
797 IMMEDIATE => 1 }, @cmd);
798 if ($it) {
799 eval {
800 $it->[1]->();
801 };
802 if ($@) {
803 print "$@";
804 }
805 }
806 }
807 }
808
809 my @z;
810
811 refresh();
812 status_cmd();
813 main_loop();