Teach core.autocrlf to 'git blame'
[git/spearce.git] / git-add--interactive.perl
blobac598f88e62fc8f48aaaac8376ccde63cb3e2643
1 #!/usr/bin/perl -w
3 use strict;
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>;
18 my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));
20 if (!defined $GIT_DIR) {
21 exit(1); # rev-parse would have already said "not a git repo"
23 chomp($GIT_DIR);
25 sub refresh {
26 my $fh;
27 open $fh, 'git update-index --refresh |'
28 or die;
29 while (<$fh>) {
30 ;# ignore 'needs update'
32 close $fh;
35 sub list_untracked {
36 map {
37 chomp $_;
38 $_;
40 run_cmd_pipe(qw(git ls-files --others
41 --exclude-per-directory=.gitignore),
42 "--exclude-from=$GIT_DIR/info/exclude",
43 '--', @_);
46 my $status_fmt = '%12s %12s %s';
47 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
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?
58 sub list_modified {
59 my ($only) = @_;
60 my (%data, @return);
61 my ($add, $del, $adddel, $file);
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;
72 else {
73 $change = "+$add/-$del";
75 $data{$file} = {
76 INDEX => $change,
77 BINARY => $bin,
78 FILE => 'nothing',
81 elsif (($adddel, $file) =
82 /^ (create|delete) mode [0-7]+ (.*)$/) {
83 $data{$file}{INDEX_ADDDEL} = $adddel;
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,
96 my ($change, $bin);
97 if ($add eq '-' && $del eq '-') {
98 $change = 'binary';
99 $bin = 1;
101 else {
102 $change = "+$add/-$del";
104 $data{$file}{FILE} = $change;
105 if ($bin) {
106 $data{$file}{BINARY} = 1;
109 elsif (($adddel, $file) =
110 /^ (create|delete) mode [0-7]+ (.*)$/) {
111 $data{$file}{FILE_ADDDEL} = $adddel;
115 for (sort keys %data) {
116 my $it = $data{$_};
118 if ($only) {
119 if ($only eq 'index-only') {
120 next if ($it->{INDEX} eq 'unchanged');
122 if ($only eq 'file-only') {
123 next if ($it->{FILE} eq 'nothing');
126 push @return, +{
127 VALUE => $_,
128 PRINT => (sprintf $status_fmt,
129 $it->{INDEX}, $it->{FILE}, $_),
130 %$it,
133 return @return;
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];
146 else {
147 $it = $it->{VALUE};
150 eval {
151 if ($it =~ /^$string/) {
152 $hit = 1;
155 if (defined $hit && defined $found) {
156 return undef;
158 if ($hit) {
159 $found = $i + 1;
162 return $found;
165 sub list_and_choose {
166 my ($opts, @stuff) = @_;
167 my (@chosen, @return);
168 my $i;
170 TOPLOOP:
171 while (1) {
172 my $last_lf = 0;
174 if ($opts->{HEADER}) {
175 if (!$opts->{LIST_FLAT}) {
176 print " ";
178 print "$opts->{HEADER}\n";
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];
187 else {
188 $print = $print->{PRINT};
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;
197 else {
198 print "\n";
199 $last_lf = 1;
202 if (!$last_lf) {
203 print "\n";
206 return if ($opts->{LIST_ONLY});
208 print $opts->{PROMPT};
209 if ($opts->{SINGLETON}) {
210 print "> ";
212 else {
213 print ">> ";
215 my $line = <STDIN>;
216 if (!$line) {
217 print "\n";
218 $opts->{ON_EOF}->() if $opts->{ON_EOF};
219 last;
221 chomp $line;
222 last if $line eq '';
223 for my $choice (split(/[\s,]+/, $line)) {
224 my $choose = 1;
225 my ($bottom, $top);
227 # Input that begins with '-'; unchoose
228 if ($choice =~ s/^-//) {
229 $choose = 0;
231 # A range can be specified like 5-7
232 if ($choice =~ /^(\d+)-(\d+)$/) {
233 ($bottom, $top) = ($1, $2);
235 elsif ($choice =~ /^\d+$/) {
236 $bottom = $top = $choice;
238 elsif ($choice eq '*') {
239 $bottom = 1;
240 $top = 1 + @stuff;
242 else {
243 $bottom = $top = find_unique($choice, @stuff);
244 if (!defined $bottom) {
245 print "Huh ($choice)?\n";
246 next TOPLOOP;
249 if ($opts->{SINGLETON} && $bottom != $top) {
250 print "Huh ($choice)?\n";
251 next TOPLOOP;
253 for ($i = $bottom-1; $i <= $top-1; $i++) {
254 next if (@stuff <= $i || $i < 0);
255 $chosen[$i] = $choose;
258 last if ($opts->{IMMEDIATE});
260 for ($i = 0; $i < @stuff; $i++) {
261 if ($chosen[$i]) {
262 push @return, $stuff[$i];
265 return @return;
268 sub status_cmd {
269 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
270 list_modified());
271 print "\n";
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";
281 else {
282 print "one path\n";
286 sub update_cmd {
287 my @mods = list_modified('file-only');
288 return if (!@mods);
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);
298 print "\n";
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 $_;
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";
323 refresh();
324 say_n_paths('reverted', @update);
326 print "\n";
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);
336 print "\n";
339 sub parse_diff {
340 my ($path) = @_;
341 my @diff = run_cmd_pipe(qw(git diff-files -p --), $path);
342 my (@hunk) = { TEXT => [] };
344 for (@diff) {
345 if (/^@@ /) {
346 push @hunk, { TEXT => [] };
348 push @{$hunk[-1]{TEXT}}, $_;
350 return @hunk;
353 sub hunk_splittable {
354 my ($text) = @_;
356 my @s = split_hunk($text);
357 return (1 < @s);
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);
369 sub split_hunk {
370 my ($text) = @_;
371 my @split = ();
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.
377 my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
378 my $hunk_start = 1;
380 OUTER:
381 while (1) {
382 my $next_hunk_start = undef;
383 my $i = $hunk_start - 1;
384 my $this = +{
385 TEXT => [],
386 OLD => $o_ofs,
387 NEW => $n_ofs,
388 OCNT => 0,
389 NCNT => 0,
390 ADDDEL => 0,
391 POSTCTX => 0,
394 while (++$i < @$text) {
395 my $line = $text->[$i];
396 if ($line =~ /^ /) {
397 if ($this->{ADDDEL} &&
398 !defined $next_hunk_start) {
399 # We have seen leading context and
400 # adds/dels and then here is another
401 # context, which is trailing for this
402 # split hunk and leading for the next
403 # one.
404 $next_hunk_start = $i;
406 push @{$this->{TEXT}}, $line;
407 $this->{OCNT}++;
408 $this->{NCNT}++;
409 if (defined $next_hunk_start) {
410 $this->{POSTCTX}++;
412 next;
415 # add/del
416 if (defined $next_hunk_start) {
417 # We are done with the current hunk and
418 # this is the first real change for the
419 # next split one.
420 $hunk_start = $next_hunk_start;
421 $o_ofs = $this->{OLD} + $this->{OCNT};
422 $n_ofs = $this->{NEW} + $this->{NCNT};
423 $o_ofs -= $this->{POSTCTX};
424 $n_ofs -= $this->{POSTCTX};
425 push @split, $this;
426 redo OUTER;
428 push @{$this->{TEXT}}, $line;
429 $this->{ADDDEL}++;
430 if ($line =~ /^-/) {
431 $this->{OCNT}++;
433 else {
434 $this->{NCNT}++;
438 push @split, $this;
439 last;
442 for my $hunk (@split) {
443 $o_ofs = $hunk->{OLD};
444 $n_ofs = $hunk->{NEW};
445 my $o_cnt = $hunk->{OCNT};
446 my $n_cnt = $hunk->{NCNT};
448 my $head = ("@@ -$o_ofs" .
449 (($o_cnt != 1) ? ",$o_cnt" : '') .
450 " +$n_ofs" .
451 (($n_cnt != 1) ? ",$n_cnt" : '') .
452 " @@\n");
453 unshift @{$hunk->{TEXT}}, $head;
455 return map { $_->{TEXT} } @split;
458 sub find_last_o_ctx {
459 my ($it) = @_;
460 my $text = $it->{TEXT};
461 my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
462 my $i = @{$text};
463 my $last_o_ctx = $o_ofs + $o_cnt;
464 while (0 < --$i) {
465 my $line = $text->[$i];
466 if ($line =~ /^ /) {
467 $last_o_ctx--;
468 next;
470 last;
472 return $last_o_ctx;
475 sub merge_hunk {
476 my ($prev, $this) = @_;
477 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
478 parse_hunk_header($prev->{TEXT}[0]);
479 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
480 parse_hunk_header($this->{TEXT}[0]);
482 my (@line, $i, $ofs, $o_cnt, $n_cnt);
483 $ofs = $o0_ofs;
484 $o_cnt = $n_cnt = 0;
485 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
486 my $line = $prev->{TEXT}[$i];
487 if ($line =~ /^\+/) {
488 $n_cnt++;
489 push @line, $line;
490 next;
493 last if ($o1_ofs <= $ofs);
495 $o_cnt++;
496 $ofs++;
497 if ($line =~ /^ /) {
498 $n_cnt++;
500 push @line, $line;
503 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
504 my $line = $this->{TEXT}[$i];
505 if ($line =~ /^\+/) {
506 $n_cnt++;
507 push @line, $line;
508 next;
510 $ofs++;
511 $o_cnt++;
512 if ($line =~ /^ /) {
513 $n_cnt++;
515 push @line, $line;
517 my $head = ("@@ -$o0_ofs" .
518 (($o_cnt != 1) ? ",$o_cnt" : '') .
519 " +$n0_ofs" .
520 (($n_cnt != 1) ? ",$n_cnt" : '') .
521 " @@\n");
522 @{$prev->{TEXT}} = ($head, @line);
525 sub coalesce_overlapping_hunks {
526 my (@in) = @_;
527 my @out = ();
529 my ($last_o_ctx);
531 for (grep { $_->{USE} } @in) {
532 my $text = $_->{TEXT};
533 my ($o_ofs) = parse_hunk_header($text->[0]);
534 if (defined $last_o_ctx &&
535 $o_ofs <= $last_o_ctx) {
536 merge_hunk($out[-1], $_);
538 else {
539 push @out, $_;
541 $last_o_ctx = find_last_o_ctx($out[-1]);
543 return @out;
546 sub help_patch_cmd {
547 print <<\EOF ;
548 y - stage this hunk
549 n - do not stage this hunk
550 a - stage this and all the remaining hunks
551 d - do not stage this hunk nor any of the remaining hunks
552 j - leave this hunk undecided, see next undecided hunk
553 J - leave this hunk undecided, see next hunk
554 k - leave this hunk undecided, see previous undecided hunk
555 K - leave this hunk undecided, see previous hunk
556 s - split the current hunk into smaller hunks
560 sub patch_update_cmd {
561 my @mods = list_modified('file-only');
562 @mods = grep { !($_->{BINARY}) } @mods;
563 return if (!@mods);
565 my ($it) = list_and_choose({ PROMPT => 'Patch update',
566 SINGLETON => 1,
567 IMMEDIATE => 1,
568 HEADER => $status_head, },
569 @mods);
570 return if (!$it);
572 my ($ix, $num);
573 my $path = $it->{VALUE};
574 my ($head, @hunk) = parse_diff($path);
575 for (@{$head->{TEXT}}) {
576 print;
578 $num = scalar @hunk;
579 $ix = 0;
581 while (1) {
582 my ($prev, $next, $other, $undecided, $i);
583 $other = '';
585 if ($num <= $ix) {
586 $ix = 0;
588 for ($i = 0; $i < $ix; $i++) {
589 if (!defined $hunk[$i]{USE}) {
590 $prev = 1;
591 $other .= '/k';
592 last;
595 if ($ix) {
596 $other .= '/K';
598 for ($i = $ix + 1; $i < $num; $i++) {
599 if (!defined $hunk[$i]{USE}) {
600 $next = 1;
601 $other .= '/j';
602 last;
605 if ($ix < $num - 1) {
606 $other .= '/J';
608 for ($i = 0; $i < $num; $i++) {
609 if (!defined $hunk[$i]{USE}) {
610 $undecided = 1;
611 last;
614 last if (!$undecided);
616 if (hunk_splittable($hunk[$ix]{TEXT})) {
617 $other .= '/s';
619 for (@{$hunk[$ix]{TEXT}}) {
620 print;
622 print "Stage this hunk [y/n/a/d$other/?]? ";
623 my $line = <STDIN>;
624 if ($line) {
625 if ($line =~ /^y/i) {
626 $hunk[$ix]{USE} = 1;
628 elsif ($line =~ /^n/i) {
629 $hunk[$ix]{USE} = 0;
631 elsif ($line =~ /^a/i) {
632 while ($ix < $num) {
633 if (!defined $hunk[$ix]{USE}) {
634 $hunk[$ix]{USE} = 1;
636 $ix++;
638 next;
640 elsif ($line =~ /^d/i) {
641 while ($ix < $num) {
642 if (!defined $hunk[$ix]{USE}) {
643 $hunk[$ix]{USE} = 0;
645 $ix++;
647 next;
649 elsif ($other =~ /K/ && $line =~ /^K/) {
650 $ix--;
651 next;
653 elsif ($other =~ /J/ && $line =~ /^J/) {
654 $ix++;
655 next;
657 elsif ($other =~ /k/ && $line =~ /^k/) {
658 while (1) {
659 $ix--;
660 last if (!$ix ||
661 !defined $hunk[$ix]{USE});
663 next;
665 elsif ($other =~ /j/ && $line =~ /^j/) {
666 while (1) {
667 $ix++;
668 last if ($ix >= $num ||
669 !defined $hunk[$ix]{USE});
671 next;
673 elsif ($other =~ /s/ && $line =~ /^s/) {
674 my @split = split_hunk($hunk[$ix]{TEXT});
675 if (1 < @split) {
676 print "Split into ",
677 scalar(@split), " hunks.\n";
679 splice(@hunk, $ix, 1,
680 map { +{ TEXT => $_, USE => undef } }
681 @split);
682 $num = scalar @hunk;
683 next;
685 else {
686 help_patch_cmd($other);
687 next;
689 # soft increment
690 while (1) {
691 $ix++;
692 last if ($ix >= $num ||
693 !defined $hunk[$ix]{USE});
698 @hunk = coalesce_overlapping_hunks(@hunk);
700 my $n_lofs = 0;
701 my @result = ();
702 for (@hunk) {
703 my $text = $_->{TEXT};
704 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
705 parse_hunk_header($text->[0]);
707 if (!$_->{USE}) {
708 # We would have added ($n_cnt - $o_cnt) lines
709 # to the postimage if we were to use this hunk,
710 # but we didn't. So the line number that the next
711 # hunk starts at would be shifted by that much.
712 $n_lofs -= ($n_cnt - $o_cnt);
713 next;
715 else {
716 if ($n_lofs) {
717 $n_ofs += $n_lofs;
718 $text->[0] = ("@@ -$o_ofs" .
719 (($o_cnt != 1)
720 ? ",$o_cnt" : '') .
721 " +$n_ofs" .
722 (($n_cnt != 1)
723 ? ",$n_cnt" : '') .
724 " @@\n");
726 for (@$text) {
727 push @result, $_;
732 if (@result) {
733 my $fh;
735 open $fh, '| git apply --cached';
736 for (@{$head->{TEXT}}, @result) {
737 print $fh $_;
739 if (!close $fh) {
740 for (@{$head->{TEXT}}, @result) {
741 print STDERR $_;
744 refresh();
747 print "\n";
750 sub diff_cmd {
751 my @mods = list_modified('index-only');
752 @mods = grep { !($_->{BINARY}) } @mods;
753 return if (!@mods);
754 my (@them) = list_and_choose({ PROMPT => 'Review diff',
755 IMMEDIATE => 1,
756 HEADER => $status_head, },
757 @mods);
758 return if (!@them);
759 system(qw(git diff-index -p --cached HEAD --),
760 map { $_->{VALUE} } @them);
763 sub quit_cmd {
764 print "Bye.\n";
765 exit(0);
768 sub help_cmd {
769 print <<\EOF ;
770 status - show paths with changes
771 update - add working tree state to the staged set of changes
772 revert - revert staged set of changes back to the HEAD version
773 patch - pick hunks and update selectively
774 diff - view diff between HEAD and index
775 add untracked - add contents of untracked files to the staged set of changes
779 sub main_loop {
780 my @cmd = ([ 'status', \&status_cmd, ],
781 [ 'update', \&update_cmd, ],
782 [ 'revert', \&revert_cmd, ],
783 [ 'add untracked', \&add_untracked_cmd, ],
784 [ 'patch', \&patch_update_cmd, ],
785 [ 'diff', \&diff_cmd, ],
786 [ 'quit', \&quit_cmd, ],
787 [ 'help', \&help_cmd, ],
789 while (1) {
790 my ($it) = list_and_choose({ PROMPT => 'What now',
791 SINGLETON => 1,
792 LIST_FLAT => 4,
793 HEADER => '*** Commands ***',
794 ON_EOF => \&quit_cmd,
795 IMMEDIATE => 1 }, @cmd);
796 if ($it) {
797 eval {
798 $it->[1]->();
800 if ($@) {
801 print "$@";
807 refresh();
808 status_cmd();
809 main_loop();