Add "--patch" option to git-add--interactive
[git/jnareb-git.git] / git-add--interactive.perl
blobdf5df3ec905e23da61e83906aa6a5651cf06149d
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
568 sub patch_update_cmd {
569 my @mods = grep { !($_->{BINARY}) } list_modified('file-only');
570 my @them;
572 if (!@mods) {
573 print STDERR "No changes.\n";
574 return 0;
576 if ($patch_mode) {
577 @them = @mods;
579 else {
580 @them = list_and_choose({ PROMPT => 'Patch update',
581 HEADER => $status_head, },
582 @mods);
584 for (@them) {
585 patch_update_file($_->{VALUE});
589 sub patch_update_file {
590 my ($ix, $num);
591 my $path = shift;
592 my ($head, @hunk) = parse_diff($path);
593 for (@{$head->{TEXT}}) {
594 print;
596 $num = scalar @hunk;
597 $ix = 0;
599 while (1) {
600 my ($prev, $next, $other, $undecided, $i);
601 $other = '';
603 if ($num <= $ix) {
604 $ix = 0;
606 for ($i = 0; $i < $ix; $i++) {
607 if (!defined $hunk[$i]{USE}) {
608 $prev = 1;
609 $other .= '/k';
610 last;
613 if ($ix) {
614 $other .= '/K';
616 for ($i = $ix + 1; $i < $num; $i++) {
617 if (!defined $hunk[$i]{USE}) {
618 $next = 1;
619 $other .= '/j';
620 last;
623 if ($ix < $num - 1) {
624 $other .= '/J';
626 for ($i = 0; $i < $num; $i++) {
627 if (!defined $hunk[$i]{USE}) {
628 $undecided = 1;
629 last;
632 last if (!$undecided);
634 if (hunk_splittable($hunk[$ix]{TEXT})) {
635 $other .= '/s';
637 for (@{$hunk[$ix]{TEXT}}) {
638 print;
640 print "Stage this hunk [y/n/a/d$other/?]? ";
641 my $line = <STDIN>;
642 if ($line) {
643 if ($line =~ /^y/i) {
644 $hunk[$ix]{USE} = 1;
646 elsif ($line =~ /^n/i) {
647 $hunk[$ix]{USE} = 0;
649 elsif ($line =~ /^a/i) {
650 while ($ix < $num) {
651 if (!defined $hunk[$ix]{USE}) {
652 $hunk[$ix]{USE} = 1;
654 $ix++;
656 next;
658 elsif ($line =~ /^d/i) {
659 while ($ix < $num) {
660 if (!defined $hunk[$ix]{USE}) {
661 $hunk[$ix]{USE} = 0;
663 $ix++;
665 next;
667 elsif ($other =~ /K/ && $line =~ /^K/) {
668 $ix--;
669 next;
671 elsif ($other =~ /J/ && $line =~ /^J/) {
672 $ix++;
673 next;
675 elsif ($other =~ /k/ && $line =~ /^k/) {
676 while (1) {
677 $ix--;
678 last if (!$ix ||
679 !defined $hunk[$ix]{USE});
681 next;
683 elsif ($other =~ /j/ && $line =~ /^j/) {
684 while (1) {
685 $ix++;
686 last if ($ix >= $num ||
687 !defined $hunk[$ix]{USE});
689 next;
691 elsif ($other =~ /s/ && $line =~ /^s/) {
692 my @split = split_hunk($hunk[$ix]{TEXT});
693 if (1 < @split) {
694 print "Split into ",
695 scalar(@split), " hunks.\n";
697 splice(@hunk, $ix, 1,
698 map { +{ TEXT => $_, USE => undef } }
699 @split);
700 $num = scalar @hunk;
701 next;
703 else {
704 help_patch_cmd($other);
705 next;
707 # soft increment
708 while (1) {
709 $ix++;
710 last if ($ix >= $num ||
711 !defined $hunk[$ix]{USE});
716 @hunk = coalesce_overlapping_hunks(@hunk);
718 my $n_lofs = 0;
719 my @result = ();
720 for (@hunk) {
721 my $text = $_->{TEXT};
722 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
723 parse_hunk_header($text->[0]);
725 if (!$_->{USE}) {
726 # We would have added ($n_cnt - $o_cnt) lines
727 # to the postimage if we were to use this hunk,
728 # but we didn't. So the line number that the next
729 # hunk starts at would be shifted by that much.
730 $n_lofs -= ($n_cnt - $o_cnt);
731 next;
733 else {
734 if ($n_lofs) {
735 $n_ofs += $n_lofs;
736 $text->[0] = ("@@ -$o_ofs" .
737 (($o_cnt != 1)
738 ? ",$o_cnt" : '') .
739 " +$n_ofs" .
740 (($n_cnt != 1)
741 ? ",$n_cnt" : '') .
742 " @@\n");
744 for (@$text) {
745 push @result, $_;
750 if (@result) {
751 my $fh;
753 open $fh, '| git apply --cached';
754 for (@{$head->{TEXT}}, @result) {
755 print $fh $_;
757 if (!close $fh) {
758 for (@{$head->{TEXT}}, @result) {
759 print STDERR $_;
762 refresh();
765 print "\n";
768 sub diff_cmd {
769 my @mods = list_modified('index-only');
770 @mods = grep { !($_->{BINARY}) } @mods;
771 return if (!@mods);
772 my (@them) = list_and_choose({ PROMPT => 'Review diff',
773 IMMEDIATE => 1,
774 HEADER => $status_head, },
775 @mods);
776 return if (!@them);
777 system(qw(git diff-index -p --cached HEAD --),
778 map { $_->{VALUE} } @them);
781 sub quit_cmd {
782 print "Bye.\n";
783 exit(0);
786 sub help_cmd {
787 print <<\EOF ;
788 status - show paths with changes
789 update - add working tree state to the staged set of changes
790 revert - revert staged set of changes back to the HEAD version
791 patch - pick hunks and update selectively
792 diff - view diff between HEAD and index
793 add untracked - add contents of untracked files to the staged set of changes
797 sub process_args {
798 return unless @ARGV;
799 my $arg = shift @ARGV;
800 if ($arg eq "--patch") {
801 $patch_mode = 1;
802 $arg = shift @ARGV or die "missing --";
803 die "invalid argument $arg, expecting --"
804 unless $arg eq "--";
806 elsif ($arg ne "--") {
807 die "invalid argument $arg, expecting --";
811 sub main_loop {
812 my @cmd = ([ 'status', \&status_cmd, ],
813 [ 'update', \&update_cmd, ],
814 [ 'revert', \&revert_cmd, ],
815 [ 'add untracked', \&add_untracked_cmd, ],
816 [ 'patch', \&patch_update_cmd, ],
817 [ 'diff', \&diff_cmd, ],
818 [ 'quit', \&quit_cmd, ],
819 [ 'help', \&help_cmd, ],
821 while (1) {
822 my ($it) = list_and_choose({ PROMPT => 'What now',
823 SINGLETON => 1,
824 LIST_FLAT => 4,
825 HEADER => '*** Commands ***',
826 ON_EOF => \&quit_cmd,
827 IMMEDIATE => 1 }, @cmd);
828 if ($it) {
829 eval {
830 $it->[1]->();
832 if ($@) {
833 print "$@";
839 process_args();
840 refresh();
841 if ($patch_mode) {
842 patch_update_cmd();
844 else {
845 status_cmd();
846 main_loop();