rebase -i: work on a detached HEAD
[git/spearce.git] / git-add--interactive.perl
blob7921cde8cbd3b58f1d7222e9828bf85e10f363e3
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 last if (!$line);
217 chomp $line;
218 my $donesomething = 0;
219 for my $choice (split(/[\s,]+/, $line)) {
220 my $choose = 1;
221 my ($bottom, $top);
223 # Input that begins with '-'; unchoose
224 if ($choice =~ s/^-//) {
225 $choose = 0;
227 # A range can be specified like 5-7
228 if ($choice =~ /^(\d+)-(\d+)$/) {
229 ($bottom, $top) = ($1, $2);
231 elsif ($choice =~ /^\d+$/) {
232 $bottom = $top = $choice;
234 elsif ($choice eq '*') {
235 $bottom = 1;
236 $top = 1 + @stuff;
238 else {
239 $bottom = $top = find_unique($choice, @stuff);
240 if (!defined $bottom) {
241 print "Huh ($choice)?\n";
242 next TOPLOOP;
245 if ($opts->{SINGLETON} && $bottom != $top) {
246 print "Huh ($choice)?\n";
247 next TOPLOOP;
249 for ($i = $bottom-1; $i <= $top-1; $i++) {
250 next if (@stuff <= $i);
251 $chosen[$i] = $choose;
252 $donesomething++;
255 last if (!$donesomething || $opts->{IMMEDIATE});
257 for ($i = 0; $i < @stuff; $i++) {
258 if ($chosen[$i]) {
259 push @return, $stuff[$i];
262 return @return;
265 sub status_cmd {
266 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
267 list_modified());
268 print "\n";
271 sub say_n_paths {
272 my $did = shift @_;
273 my $cnt = scalar @_;
274 print "$did ";
275 if (1 < $cnt) {
276 print "$cnt paths\n";
278 else {
279 print "one path\n";
283 sub update_cmd {
284 my @mods = list_modified('file-only');
285 return if (!@mods);
287 my @update = list_and_choose({ PROMPT => 'Update',
288 HEADER => $status_head, },
289 @mods);
290 if (@update) {
291 system(qw(git update-index --add --remove --),
292 map { $_->{VALUE} } @update);
293 say_n_paths('updated', @update);
295 print "\n";
298 sub revert_cmd {
299 my @update = list_and_choose({ PROMPT => 'Revert',
300 HEADER => $status_head, },
301 list_modified());
302 if (@update) {
303 my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
304 map { $_->{VALUE} } @update);
305 my $fh;
306 open $fh, '| git update-index --index-info'
307 or die;
308 for (@lines) {
309 print $fh $_;
311 close($fh);
312 for (@update) {
313 if ($_->{INDEX_ADDDEL} &&
314 $_->{INDEX_ADDDEL} eq 'create') {
315 system(qw(git update-index --force-remove --),
316 $_->{VALUE});
317 print "note: $_->{VALUE} is untracked now.\n";
320 refresh();
321 say_n_paths('reverted', @update);
323 print "\n";
326 sub add_untracked_cmd {
327 my @add = list_and_choose({ PROMPT => 'Add untracked' },
328 list_untracked());
329 if (@add) {
330 system(qw(git update-index --add --), @add);
331 say_n_paths('added', @add);
333 print "\n";
336 sub parse_diff {
337 my ($path) = @_;
338 my @diff = run_cmd_pipe(qw(git diff-files -p --), $path);
339 my (@hunk) = { TEXT => [] };
341 for (@diff) {
342 if (/^@@ /) {
343 push @hunk, { TEXT => [] };
345 push @{$hunk[-1]{TEXT}}, $_;
347 return @hunk;
350 sub hunk_splittable {
351 my ($text) = @_;
353 my @s = split_hunk($text);
354 return (1 < @s);
357 sub parse_hunk_header {
358 my ($line) = @_;
359 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
360 $line =~ /^@@ -(\d+)(?:,(\d+)) \+(\d+)(?:,(\d+)) @@/;
361 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
364 sub split_hunk {
365 my ($text) = @_;
366 my @split = ();
368 # If there are context lines in the middle of a hunk,
369 # it can be split, but we would need to take care of
370 # overlaps later.
372 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) = parse_hunk_header($text->[0]);
373 my $hunk_start = 1;
374 my $next_hunk_start;
376 OUTER:
377 while (1) {
378 my $next_hunk_start = undef;
379 my $i = $hunk_start - 1;
380 my $this = +{
381 TEXT => [],
382 OLD => $o_ofs,
383 NEW => $n_ofs,
384 OCNT => 0,
385 NCNT => 0,
386 ADDDEL => 0,
387 POSTCTX => 0,
390 while (++$i < @$text) {
391 my $line = $text->[$i];
392 if ($line =~ /^ /) {
393 if ($this->{ADDDEL} &&
394 !defined $next_hunk_start) {
395 # We have seen leading context and
396 # adds/dels and then here is another
397 # context, which is trailing for this
398 # split hunk and leading for the next
399 # one.
400 $next_hunk_start = $i;
402 push @{$this->{TEXT}}, $line;
403 $this->{OCNT}++;
404 $this->{NCNT}++;
405 if (defined $next_hunk_start) {
406 $this->{POSTCTX}++;
408 next;
411 # add/del
412 if (defined $next_hunk_start) {
413 # We are done with the current hunk and
414 # this is the first real change for the
415 # next split one.
416 $hunk_start = $next_hunk_start;
417 $o_ofs = $this->{OLD} + $this->{OCNT};
418 $n_ofs = $this->{NEW} + $this->{NCNT};
419 $o_ofs -= $this->{POSTCTX};
420 $n_ofs -= $this->{POSTCTX};
421 push @split, $this;
422 redo OUTER;
424 push @{$this->{TEXT}}, $line;
425 $this->{ADDDEL}++;
426 if ($line =~ /^-/) {
427 $this->{OCNT}++;
429 else {
430 $this->{NCNT}++;
434 push @split, $this;
435 last;
438 for my $hunk (@split) {
439 $o_ofs = $hunk->{OLD};
440 $n_ofs = $hunk->{NEW};
441 $o_cnt = $hunk->{OCNT};
442 $n_cnt = $hunk->{NCNT};
444 my $head = ("@@ -$o_ofs" .
445 (($o_cnt != 1) ? ",$o_cnt" : '') .
446 " +$n_ofs" .
447 (($n_cnt != 1) ? ",$n_cnt" : '') .
448 " @@\n");
449 unshift @{$hunk->{TEXT}}, $head;
451 return map { $_->{TEXT} } @split;
454 sub find_last_o_ctx {
455 my ($it) = @_;
456 my $text = $it->{TEXT};
457 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) = parse_hunk_header($text->[0]);
458 my $i = @{$text};
459 my $last_o_ctx = $o_ofs + $o_cnt;
460 while (0 < --$i) {
461 my $line = $text->[$i];
462 if ($line =~ /^ /) {
463 $last_o_ctx--;
464 next;
466 last;
468 return $last_o_ctx;
471 sub merge_hunk {
472 my ($prev, $this) = @_;
473 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
474 parse_hunk_header($prev->{TEXT}[0]);
475 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
476 parse_hunk_header($this->{TEXT}[0]);
478 my (@line, $i, $ofs, $o_cnt, $n_cnt);
479 $ofs = $o0_ofs;
480 $o_cnt = $n_cnt = 0;
481 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
482 my $line = $prev->{TEXT}[$i];
483 if ($line =~ /^\+/) {
484 $n_cnt++;
485 push @line, $line;
486 next;
489 last if ($o1_ofs <= $ofs);
491 $o_cnt++;
492 $ofs++;
493 if ($line =~ /^ /) {
494 $n_cnt++;
496 push @line, $line;
499 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
500 my $line = $this->{TEXT}[$i];
501 if ($line =~ /^\+/) {
502 $n_cnt++;
503 push @line, $line;
504 next;
506 $ofs++;
507 $o_cnt++;
508 if ($line =~ /^ /) {
509 $n_cnt++;
511 push @line, $line;
513 my $head = ("@@ -$o0_ofs" .
514 (($o_cnt != 1) ? ",$o_cnt" : '') .
515 " +$n0_ofs" .
516 (($n_cnt != 1) ? ",$n_cnt" : '') .
517 " @@\n");
518 @{$prev->{TEXT}} = ($head, @line);
521 sub coalesce_overlapping_hunks {
522 my (@in) = @_;
523 my @out = ();
525 my ($last_o_ctx);
527 for (grep { $_->{USE} } @in) {
528 my $text = $_->{TEXT};
529 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
530 parse_hunk_header($text->[0]);
531 if (defined $last_o_ctx &&
532 $o_ofs <= $last_o_ctx) {
533 merge_hunk($out[-1], $_);
535 else {
536 push @out, $_;
538 $last_o_ctx = find_last_o_ctx($out[-1]);
540 return @out;
543 sub help_patch_cmd {
544 print <<\EOF ;
545 y - stage this hunk
546 n - do not stage this hunk
547 a - stage this and all the remaining hunks
548 d - do not stage this hunk nor any of the remaining hunks
549 j - leave this hunk undecided, see next undecided hunk
550 J - leave this hunk undecided, see next hunk
551 k - leave this hunk undecided, see previous undecided hunk
552 K - leave this hunk undecided, see previous hunk
553 s - split the current hunk into smaller hunks
557 sub patch_update_cmd {
558 my @mods = list_modified('file-only');
559 @mods = grep { !($_->{BINARY}) } @mods;
560 return if (!@mods);
562 my ($it) = list_and_choose({ PROMPT => 'Patch update',
563 SINGLETON => 1,
564 IMMEDIATE => 1,
565 HEADER => $status_head, },
566 @mods);
567 return if (!$it);
569 my ($ix, $num);
570 my $path = $it->{VALUE};
571 my ($head, @hunk) = parse_diff($path);
572 for (@{$head->{TEXT}}) {
573 print;
575 $num = scalar @hunk;
576 $ix = 0;
578 while (1) {
579 my ($prev, $next, $other, $undecided, $i);
580 $other = '';
582 if ($num <= $ix) {
583 $ix = 0;
585 for ($i = 0; $i < $ix; $i++) {
586 if (!defined $hunk[$i]{USE}) {
587 $prev = 1;
588 $other .= '/k';
589 last;
592 if ($ix) {
593 $other .= '/K';
595 for ($i = $ix + 1; $i < $num; $i++) {
596 if (!defined $hunk[$i]{USE}) {
597 $next = 1;
598 $other .= '/j';
599 last;
602 if ($ix < $num - 1) {
603 $other .= '/J';
605 for ($i = 0; $i < $num; $i++) {
606 if (!defined $hunk[$i]{USE}) {
607 $undecided = 1;
608 last;
611 last if (!$undecided);
613 if (hunk_splittable($hunk[$ix]{TEXT})) {
614 $other .= '/s';
616 for (@{$hunk[$ix]{TEXT}}) {
617 print;
619 print "Stage this hunk [y/n/a/d$other/?]? ";
620 my $line = <STDIN>;
621 if ($line) {
622 if ($line =~ /^y/i) {
623 $hunk[$ix]{USE} = 1;
625 elsif ($line =~ /^n/i) {
626 $hunk[$ix]{USE} = 0;
628 elsif ($line =~ /^a/i) {
629 while ($ix < $num) {
630 if (!defined $hunk[$ix]{USE}) {
631 $hunk[$ix]{USE} = 1;
633 $ix++;
635 next;
637 elsif ($line =~ /^d/i) {
638 while ($ix < $num) {
639 if (!defined $hunk[$ix]{USE}) {
640 $hunk[$ix]{USE} = 0;
642 $ix++;
644 next;
646 elsif ($other =~ /K/ && $line =~ /^K/) {
647 $ix--;
648 next;
650 elsif ($other =~ /J/ && $line =~ /^J/) {
651 $ix++;
652 next;
654 elsif ($other =~ /k/ && $line =~ /^k/) {
655 while (1) {
656 $ix--;
657 last if (!$ix ||
658 !defined $hunk[$ix]{USE});
660 next;
662 elsif ($other =~ /j/ && $line =~ /^j/) {
663 while (1) {
664 $ix++;
665 last if ($ix >= $num ||
666 !defined $hunk[$ix]{USE});
668 next;
670 elsif ($other =~ /s/ && $line =~ /^s/) {
671 my @split = split_hunk($hunk[$ix]{TEXT});
672 if (1 < @split) {
673 print "Split into ",
674 scalar(@split), " hunks.\n";
676 splice(@hunk, $ix, 1,
677 map { +{ TEXT => $_, USE => undef } }
678 @split);
679 $num = scalar @hunk;
680 next;
682 else {
683 help_patch_cmd($other);
684 next;
686 # soft increment
687 while (1) {
688 $ix++;
689 last if ($ix >= $num ||
690 !defined $hunk[$ix]{USE});
695 @hunk = coalesce_overlapping_hunks(@hunk);
697 my ($o_lofs, $n_lofs) = (0, 0);
698 my @result = ();
699 for (@hunk) {
700 my $text = $_->{TEXT};
701 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
702 parse_hunk_header($text->[0]);
704 if (!$_->{USE}) {
705 if (!defined $o_cnt) { $o_cnt = 1; }
706 if (!defined $n_cnt) { $n_cnt = 1; }
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 ((defined $o_cnt)
720 ? ",$o_cnt" : '') .
721 " +$n_ofs" .
722 ((defined $n_cnt)
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 IMMEDIATE => 1 }, @cmd);
795 if ($it) {
796 eval {
797 $it->[1]->();
799 if ($@) {
800 print "$@";
806 my @z;
808 refresh();
809 status_cmd();
810 main_loop();