Document all help keys in "git add -i" patch mode.
[git/dscho.git] / git-add--interactive.perl
blob879cc5eadf6d13d531e862293a41a8d1db7e174a
1 #!/usr/bin/perl -w
3 use strict;
5 # command line options
6 my $patch_mode;
8 sub run_cmd_pipe {
9 if ($^O eq 'MSWin32') {
10 my @invalid = grep {m/[":*]/} @_;
11 die "$^O does not support: @invalid\n" if @invalid;
12 my @args = map { m/ /o ? "\"$_\"": $_ } @_;
13 return qx{@args};
14 } else {
15 my $fh = undef;
16 open($fh, '-|', @_) or die;
17 return <$fh>;
21 my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));
23 if (!defined $GIT_DIR) {
24 exit(1); # rev-parse would have already said "not a git repo"
26 chomp($GIT_DIR);
28 sub refresh {
29 my $fh;
30 open $fh, 'git update-index --refresh |'
31 or die;
32 while (<$fh>) {
33 ;# ignore 'needs update'
35 close $fh;
38 sub list_untracked {
39 map {
40 chomp $_;
41 $_;
43 run_cmd_pipe(qw(git ls-files --others --exclude-standard --), @ARGV);
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);
62 my @tracked = ();
64 if (@ARGV) {
65 @tracked = map {
66 chomp $_; $_;
67 } run_cmd_pipe(qw(git ls-files --exclude-standard --), @ARGV);
68 return if (!@tracked);
71 for (run_cmd_pipe(qw(git diff-index --cached
72 --numstat --summary HEAD --), @tracked)) {
73 if (($add, $del, $file) =
74 /^([-\d]+) ([-\d]+) (.*)/) {
75 my ($change, $bin);
76 if ($add eq '-' && $del eq '-') {
77 $change = 'binary';
78 $bin = 1;
80 else {
81 $change = "+$add/-$del";
83 $data{$file} = {
84 INDEX => $change,
85 BINARY => $bin,
86 FILE => 'nothing',
89 elsif (($adddel, $file) =
90 /^ (create|delete) mode [0-7]+ (.*)$/) {
91 $data{$file}{INDEX_ADDDEL} = $adddel;
95 for (run_cmd_pipe(qw(git diff-files --numstat --summary --), @tracked)) {
96 if (($add, $del, $file) =
97 /^([-\d]+) ([-\d]+) (.*)/) {
98 if (!exists $data{$file}) {
99 $data{$file} = +{
100 INDEX => 'unchanged',
101 BINARY => 0,
104 my ($change, $bin);
105 if ($add eq '-' && $del eq '-') {
106 $change = 'binary';
107 $bin = 1;
109 else {
110 $change = "+$add/-$del";
112 $data{$file}{FILE} = $change;
113 if ($bin) {
114 $data{$file}{BINARY} = 1;
117 elsif (($adddel, $file) =
118 /^ (create|delete) mode [0-7]+ (.*)$/) {
119 $data{$file}{FILE_ADDDEL} = $adddel;
123 for (sort keys %data) {
124 my $it = $data{$_};
126 if ($only) {
127 if ($only eq 'index-only') {
128 next if ($it->{INDEX} eq 'unchanged');
130 if ($only eq 'file-only') {
131 next if ($it->{FILE} eq 'nothing');
134 push @return, +{
135 VALUE => $_,
136 PRINT => (sprintf $status_fmt,
137 $it->{INDEX}, $it->{FILE}, $_),
138 %$it,
141 return @return;
144 sub find_unique {
145 my ($string, @stuff) = @_;
146 my $found = undef;
147 for (my $i = 0; $i < @stuff; $i++) {
148 my $it = $stuff[$i];
149 my $hit = undef;
150 if (ref $it) {
151 if ((ref $it) eq 'ARRAY') {
152 $it = $it->[0];
154 else {
155 $it = $it->{VALUE};
158 eval {
159 if ($it =~ /^$string/) {
160 $hit = 1;
163 if (defined $hit && defined $found) {
164 return undef;
166 if ($hit) {
167 $found = $i + 1;
170 return $found;
173 sub list_and_choose {
174 my ($opts, @stuff) = @_;
175 my (@chosen, @return);
176 my $i;
178 TOPLOOP:
179 while (1) {
180 my $last_lf = 0;
182 if ($opts->{HEADER}) {
183 if (!$opts->{LIST_FLAT}) {
184 print " ";
186 print "$opts->{HEADER}\n";
188 for ($i = 0; $i < @stuff; $i++) {
189 my $chosen = $chosen[$i] ? '*' : ' ';
190 my $print = $stuff[$i];
191 if (ref $print) {
192 if ((ref $print) eq 'ARRAY') {
193 $print = $print->[0];
195 else {
196 $print = $print->{PRINT};
199 printf("%s%2d: %s", $chosen, $i+1, $print);
200 if (($opts->{LIST_FLAT}) &&
201 (($i + 1) % ($opts->{LIST_FLAT}))) {
202 print "\t";
203 $last_lf = 0;
205 else {
206 print "\n";
207 $last_lf = 1;
210 if (!$last_lf) {
211 print "\n";
214 return if ($opts->{LIST_ONLY});
216 print $opts->{PROMPT};
217 if ($opts->{SINGLETON}) {
218 print "> ";
220 else {
221 print ">> ";
223 my $line = <STDIN>;
224 if (!$line) {
225 print "\n";
226 $opts->{ON_EOF}->() if $opts->{ON_EOF};
227 last;
229 chomp $line;
230 last if $line eq '';
231 for my $choice (split(/[\s,]+/, $line)) {
232 my $choose = 1;
233 my ($bottom, $top);
235 # Input that begins with '-'; unchoose
236 if ($choice =~ s/^-//) {
237 $choose = 0;
239 # A range can be specified like 5-7
240 if ($choice =~ /^(\d+)-(\d+)$/) {
241 ($bottom, $top) = ($1, $2);
243 elsif ($choice =~ /^\d+$/) {
244 $bottom = $top = $choice;
246 elsif ($choice eq '*') {
247 $bottom = 1;
248 $top = 1 + @stuff;
250 else {
251 $bottom = $top = find_unique($choice, @stuff);
252 if (!defined $bottom) {
253 print "Huh ($choice)?\n";
254 next TOPLOOP;
257 if ($opts->{SINGLETON} && $bottom != $top) {
258 print "Huh ($choice)?\n";
259 next TOPLOOP;
261 for ($i = $bottom-1; $i <= $top-1; $i++) {
262 next if (@stuff <= $i || $i < 0);
263 $chosen[$i] = $choose;
266 last if ($opts->{IMMEDIATE} || $line eq '*');
268 for ($i = 0; $i < @stuff; $i++) {
269 if ($chosen[$i]) {
270 push @return, $stuff[$i];
273 return @return;
276 sub status_cmd {
277 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
278 list_modified());
279 print "\n";
282 sub say_n_paths {
283 my $did = shift @_;
284 my $cnt = scalar @_;
285 print "$did ";
286 if (1 < $cnt) {
287 print "$cnt paths\n";
289 else {
290 print "one path\n";
294 sub update_cmd {
295 my @mods = list_modified('file-only');
296 return if (!@mods);
298 my @update = list_and_choose({ PROMPT => 'Update',
299 HEADER => $status_head, },
300 @mods);
301 if (@update) {
302 system(qw(git update-index --add --remove --),
303 map { $_->{VALUE} } @update);
304 say_n_paths('updated', @update);
306 print "\n";
309 sub revert_cmd {
310 my @update = list_and_choose({ PROMPT => 'Revert',
311 HEADER => $status_head, },
312 list_modified());
313 if (@update) {
314 my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
315 map { $_->{VALUE} } @update);
316 my $fh;
317 open $fh, '| git update-index --index-info'
318 or die;
319 for (@lines) {
320 print $fh $_;
322 close($fh);
323 for (@update) {
324 if ($_->{INDEX_ADDDEL} &&
325 $_->{INDEX_ADDDEL} eq 'create') {
326 system(qw(git update-index --force-remove --),
327 $_->{VALUE});
328 print "note: $_->{VALUE} is untracked now.\n";
331 refresh();
332 say_n_paths('reverted', @update);
334 print "\n";
337 sub add_untracked_cmd {
338 my @add = list_and_choose({ PROMPT => 'Add untracked' },
339 list_untracked());
340 if (@add) {
341 system(qw(git update-index --add --), @add);
342 say_n_paths('added', @add);
344 print "\n";
347 sub parse_diff {
348 my ($path) = @_;
349 my @diff = run_cmd_pipe(qw(git diff-files -p --), $path);
350 my (@hunk) = { TEXT => [] };
352 for (@diff) {
353 if (/^@@ /) {
354 push @hunk, { TEXT => [] };
356 push @{$hunk[-1]{TEXT}}, $_;
358 return @hunk;
361 sub hunk_splittable {
362 my ($text) = @_;
364 my @s = split_hunk($text);
365 return (1 < @s);
368 sub parse_hunk_header {
369 my ($line) = @_;
370 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
371 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
372 $o_cnt = 1 unless defined $o_cnt;
373 $n_cnt = 1 unless defined $n_cnt;
374 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
377 sub split_hunk {
378 my ($text) = @_;
379 my @split = ();
381 # If there are context lines in the middle of a hunk,
382 # it can be split, but we would need to take care of
383 # overlaps later.
385 my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
386 my $hunk_start = 1;
388 OUTER:
389 while (1) {
390 my $next_hunk_start = undef;
391 my $i = $hunk_start - 1;
392 my $this = +{
393 TEXT => [],
394 OLD => $o_ofs,
395 NEW => $n_ofs,
396 OCNT => 0,
397 NCNT => 0,
398 ADDDEL => 0,
399 POSTCTX => 0,
402 while (++$i < @$text) {
403 my $line = $text->[$i];
404 if ($line =~ /^ /) {
405 if ($this->{ADDDEL} &&
406 !defined $next_hunk_start) {
407 # We have seen leading context and
408 # adds/dels and then here is another
409 # context, which is trailing for this
410 # split hunk and leading for the next
411 # one.
412 $next_hunk_start = $i;
414 push @{$this->{TEXT}}, $line;
415 $this->{OCNT}++;
416 $this->{NCNT}++;
417 if (defined $next_hunk_start) {
418 $this->{POSTCTX}++;
420 next;
423 # add/del
424 if (defined $next_hunk_start) {
425 # We are done with the current hunk and
426 # this is the first real change for the
427 # next split one.
428 $hunk_start = $next_hunk_start;
429 $o_ofs = $this->{OLD} + $this->{OCNT};
430 $n_ofs = $this->{NEW} + $this->{NCNT};
431 $o_ofs -= $this->{POSTCTX};
432 $n_ofs -= $this->{POSTCTX};
433 push @split, $this;
434 redo OUTER;
436 push @{$this->{TEXT}}, $line;
437 $this->{ADDDEL}++;
438 if ($line =~ /^-/) {
439 $this->{OCNT}++;
441 else {
442 $this->{NCNT}++;
446 push @split, $this;
447 last;
450 for my $hunk (@split) {
451 $o_ofs = $hunk->{OLD};
452 $n_ofs = $hunk->{NEW};
453 my $o_cnt = $hunk->{OCNT};
454 my $n_cnt = $hunk->{NCNT};
456 my $head = ("@@ -$o_ofs" .
457 (($o_cnt != 1) ? ",$o_cnt" : '') .
458 " +$n_ofs" .
459 (($n_cnt != 1) ? ",$n_cnt" : '') .
460 " @@\n");
461 unshift @{$hunk->{TEXT}}, $head;
463 return map { $_->{TEXT} } @split;
466 sub find_last_o_ctx {
467 my ($it) = @_;
468 my $text = $it->{TEXT};
469 my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
470 my $i = @{$text};
471 my $last_o_ctx = $o_ofs + $o_cnt;
472 while (0 < --$i) {
473 my $line = $text->[$i];
474 if ($line =~ /^ /) {
475 $last_o_ctx--;
476 next;
478 last;
480 return $last_o_ctx;
483 sub merge_hunk {
484 my ($prev, $this) = @_;
485 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
486 parse_hunk_header($prev->{TEXT}[0]);
487 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
488 parse_hunk_header($this->{TEXT}[0]);
490 my (@line, $i, $ofs, $o_cnt, $n_cnt);
491 $ofs = $o0_ofs;
492 $o_cnt = $n_cnt = 0;
493 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
494 my $line = $prev->{TEXT}[$i];
495 if ($line =~ /^\+/) {
496 $n_cnt++;
497 push @line, $line;
498 next;
501 last if ($o1_ofs <= $ofs);
503 $o_cnt++;
504 $ofs++;
505 if ($line =~ /^ /) {
506 $n_cnt++;
508 push @line, $line;
511 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
512 my $line = $this->{TEXT}[$i];
513 if ($line =~ /^\+/) {
514 $n_cnt++;
515 push @line, $line;
516 next;
518 $ofs++;
519 $o_cnt++;
520 if ($line =~ /^ /) {
521 $n_cnt++;
523 push @line, $line;
525 my $head = ("@@ -$o0_ofs" .
526 (($o_cnt != 1) ? ",$o_cnt" : '') .
527 " +$n0_ofs" .
528 (($n_cnt != 1) ? ",$n_cnt" : '') .
529 " @@\n");
530 @{$prev->{TEXT}} = ($head, @line);
533 sub coalesce_overlapping_hunks {
534 my (@in) = @_;
535 my @out = ();
537 my ($last_o_ctx);
539 for (grep { $_->{USE} } @in) {
540 my $text = $_->{TEXT};
541 my ($o_ofs) = parse_hunk_header($text->[0]);
542 if (defined $last_o_ctx &&
543 $o_ofs <= $last_o_ctx) {
544 merge_hunk($out[-1], $_);
546 else {
547 push @out, $_;
549 $last_o_ctx = find_last_o_ctx($out[-1]);
551 return @out;
554 sub help_patch_cmd {
555 print <<\EOF ;
556 y - stage this hunk
557 n - do not stage this hunk
558 a - stage this and all the remaining hunks in the file
559 d - do not stage this hunk nor any of the remaining hunks in the file
560 j - leave this hunk undecided, see next undecided hunk
561 J - leave this hunk undecided, see next hunk
562 k - leave this hunk undecided, see previous undecided hunk
563 K - leave this hunk undecided, see previous hunk
564 s - split the current hunk into smaller hunks
565 ? - print help
569 sub patch_update_cmd {
570 my @mods = grep { !($_->{BINARY}) } list_modified('file-only');
571 my @them;
573 if (!@mods) {
574 print STDERR "No changes.\n";
575 return 0;
577 if ($patch_mode) {
578 @them = @mods;
580 else {
581 @them = list_and_choose({ PROMPT => 'Patch update',
582 HEADER => $status_head, },
583 @mods);
585 for (@them) {
586 patch_update_file($_->{VALUE});
590 sub patch_update_file {
591 my ($ix, $num);
592 my $path = shift;
593 my ($head, @hunk) = parse_diff($path);
594 for (@{$head->{TEXT}}) {
595 print;
597 $num = scalar @hunk;
598 $ix = 0;
600 while (1) {
601 my ($prev, $next, $other, $undecided, $i);
602 $other = '';
604 if ($num <= $ix) {
605 $ix = 0;
607 for ($i = 0; $i < $ix; $i++) {
608 if (!defined $hunk[$i]{USE}) {
609 $prev = 1;
610 $other .= '/k';
611 last;
614 if ($ix) {
615 $other .= '/K';
617 for ($i = $ix + 1; $i < $num; $i++) {
618 if (!defined $hunk[$i]{USE}) {
619 $next = 1;
620 $other .= '/j';
621 last;
624 if ($ix < $num - 1) {
625 $other .= '/J';
627 for ($i = 0; $i < $num; $i++) {
628 if (!defined $hunk[$i]{USE}) {
629 $undecided = 1;
630 last;
633 last if (!$undecided);
635 if (hunk_splittable($hunk[$ix]{TEXT})) {
636 $other .= '/s';
638 for (@{$hunk[$ix]{TEXT}}) {
639 print;
641 print "Stage this hunk [y/n/a/d$other/?]? ";
642 my $line = <STDIN>;
643 if ($line) {
644 if ($line =~ /^y/i) {
645 $hunk[$ix]{USE} = 1;
647 elsif ($line =~ /^n/i) {
648 $hunk[$ix]{USE} = 0;
650 elsif ($line =~ /^a/i) {
651 while ($ix < $num) {
652 if (!defined $hunk[$ix]{USE}) {
653 $hunk[$ix]{USE} = 1;
655 $ix++;
657 next;
659 elsif ($line =~ /^d/i) {
660 while ($ix < $num) {
661 if (!defined $hunk[$ix]{USE}) {
662 $hunk[$ix]{USE} = 0;
664 $ix++;
666 next;
668 elsif ($other =~ /K/ && $line =~ /^K/) {
669 $ix--;
670 next;
672 elsif ($other =~ /J/ && $line =~ /^J/) {
673 $ix++;
674 next;
676 elsif ($other =~ /k/ && $line =~ /^k/) {
677 while (1) {
678 $ix--;
679 last if (!$ix ||
680 !defined $hunk[$ix]{USE});
682 next;
684 elsif ($other =~ /j/ && $line =~ /^j/) {
685 while (1) {
686 $ix++;
687 last if ($ix >= $num ||
688 !defined $hunk[$ix]{USE});
690 next;
692 elsif ($other =~ /s/ && $line =~ /^s/) {
693 my @split = split_hunk($hunk[$ix]{TEXT});
694 if (1 < @split) {
695 print "Split into ",
696 scalar(@split), " hunks.\n";
698 splice(@hunk, $ix, 1,
699 map { +{ TEXT => $_, USE => undef } }
700 @split);
701 $num = scalar @hunk;
702 next;
704 else {
705 help_patch_cmd($other);
706 next;
708 # soft increment
709 while (1) {
710 $ix++;
711 last if ($ix >= $num ||
712 !defined $hunk[$ix]{USE});
717 @hunk = coalesce_overlapping_hunks(@hunk);
719 my $n_lofs = 0;
720 my @result = ();
721 for (@hunk) {
722 my $text = $_->{TEXT};
723 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
724 parse_hunk_header($text->[0]);
726 if (!$_->{USE}) {
727 # We would have added ($n_cnt - $o_cnt) lines
728 # to the postimage if we were to use this hunk,
729 # but we didn't. So the line number that the next
730 # hunk starts at would be shifted by that much.
731 $n_lofs -= ($n_cnt - $o_cnt);
732 next;
734 else {
735 if ($n_lofs) {
736 $n_ofs += $n_lofs;
737 $text->[0] = ("@@ -$o_ofs" .
738 (($o_cnt != 1)
739 ? ",$o_cnt" : '') .
740 " +$n_ofs" .
741 (($n_cnt != 1)
742 ? ",$n_cnt" : '') .
743 " @@\n");
745 for (@$text) {
746 push @result, $_;
751 if (@result) {
752 my $fh;
754 open $fh, '| git apply --cached';
755 for (@{$head->{TEXT}}, @result) {
756 print $fh $_;
758 if (!close $fh) {
759 for (@{$head->{TEXT}}, @result) {
760 print STDERR $_;
763 refresh();
766 print "\n";
769 sub diff_cmd {
770 my @mods = list_modified('index-only');
771 @mods = grep { !($_->{BINARY}) } @mods;
772 return if (!@mods);
773 my (@them) = list_and_choose({ PROMPT => 'Review diff',
774 IMMEDIATE => 1,
775 HEADER => $status_head, },
776 @mods);
777 return if (!@them);
778 system(qw(git diff-index -p --cached HEAD --),
779 map { $_->{VALUE} } @them);
782 sub quit_cmd {
783 print "Bye.\n";
784 exit(0);
787 sub help_cmd {
788 print <<\EOF ;
789 status - show paths with changes
790 update - add working tree state to the staged set of changes
791 revert - revert staged set of changes back to the HEAD version
792 patch - pick hunks and update selectively
793 diff - view diff between HEAD and index
794 add untracked - add contents of untracked files to the staged set of changes
798 sub process_args {
799 return unless @ARGV;
800 my $arg = shift @ARGV;
801 if ($arg eq "--patch") {
802 $patch_mode = 1;
803 $arg = shift @ARGV or die "missing --";
804 die "invalid argument $arg, expecting --"
805 unless $arg eq "--";
807 elsif ($arg ne "--") {
808 die "invalid argument $arg, expecting --";
812 sub main_loop {
813 my @cmd = ([ 'status', \&status_cmd, ],
814 [ 'update', \&update_cmd, ],
815 [ 'revert', \&revert_cmd, ],
816 [ 'add untracked', \&add_untracked_cmd, ],
817 [ 'patch', \&patch_update_cmd, ],
818 [ 'diff', \&diff_cmd, ],
819 [ 'quit', \&quit_cmd, ],
820 [ 'help', \&help_cmd, ],
822 while (1) {
823 my ($it) = list_and_choose({ PROMPT => 'What now',
824 SINGLETON => 1,
825 LIST_FLAT => 4,
826 HEADER => '*** Commands ***',
827 ON_EOF => \&quit_cmd,
828 IMMEDIATE => 1 }, @cmd);
829 if ($it) {
830 eval {
831 $it->[1]->();
833 if ($@) {
834 print "$@";
840 process_args();
841 refresh();
842 if ($patch_mode) {
843 patch_update_cmd();
845 else {
846 status_cmd();
847 main_loop();