git-add -i: allow multiple selection in patch subcommand
[git/haiku.git] / git-add--interactive.perl
blobe3472165503a98572769ac8b28caef39d2f3d6b4
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 --exclude-standard --), @ARGV);
43 my $status_fmt = '%12s %12s %s';
44 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
46 # Returns list of hashes, contents of each of which are:
47 # PRINT: print message
48 # VALUE: pathname
49 # BINARY: is a binary path
50 # INDEX: is index different from HEAD?
51 # FILE: is file different from index?
52 # INDEX_ADDDEL: is it add/delete between HEAD and index?
53 # FILE_ADDDEL: is it add/delete between index and file?
55 sub list_modified {
56 my ($only) = @_;
57 my (%data, @return);
58 my ($add, $del, $adddel, $file);
59 my @tracked = ();
61 if (@ARGV) {
62 @tracked = map {
63 chomp $_; $_;
64 } run_cmd_pipe(qw(git ls-files --exclude-standard --), @ARGV);
65 return if (!@tracked);
68 for (run_cmd_pipe(qw(git diff-index --cached
69 --numstat --summary HEAD --), @tracked)) {
70 if (($add, $del, $file) =
71 /^([-\d]+) ([-\d]+) (.*)/) {
72 my ($change, $bin);
73 if ($add eq '-' && $del eq '-') {
74 $change = 'binary';
75 $bin = 1;
77 else {
78 $change = "+$add/-$del";
80 $data{$file} = {
81 INDEX => $change,
82 BINARY => $bin,
83 FILE => 'nothing',
86 elsif (($adddel, $file) =
87 /^ (create|delete) mode [0-7]+ (.*)$/) {
88 $data{$file}{INDEX_ADDDEL} = $adddel;
92 for (run_cmd_pipe(qw(git diff-files --numstat --summary --), @tracked)) {
93 if (($add, $del, $file) =
94 /^([-\d]+) ([-\d]+) (.*)/) {
95 if (!exists $data{$file}) {
96 $data{$file} = +{
97 INDEX => 'unchanged',
98 BINARY => 0,
101 my ($change, $bin);
102 if ($add eq '-' && $del eq '-') {
103 $change = 'binary';
104 $bin = 1;
106 else {
107 $change = "+$add/-$del";
109 $data{$file}{FILE} = $change;
110 if ($bin) {
111 $data{$file}{BINARY} = 1;
114 elsif (($adddel, $file) =
115 /^ (create|delete) mode [0-7]+ (.*)$/) {
116 $data{$file}{FILE_ADDDEL} = $adddel;
120 for (sort keys %data) {
121 my $it = $data{$_};
123 if ($only) {
124 if ($only eq 'index-only') {
125 next if ($it->{INDEX} eq 'unchanged');
127 if ($only eq 'file-only') {
128 next if ($it->{FILE} eq 'nothing');
131 push @return, +{
132 VALUE => $_,
133 PRINT => (sprintf $status_fmt,
134 $it->{INDEX}, $it->{FILE}, $_),
135 %$it,
138 return @return;
141 sub find_unique {
142 my ($string, @stuff) = @_;
143 my $found = undef;
144 for (my $i = 0; $i < @stuff; $i++) {
145 my $it = $stuff[$i];
146 my $hit = undef;
147 if (ref $it) {
148 if ((ref $it) eq 'ARRAY') {
149 $it = $it->[0];
151 else {
152 $it = $it->{VALUE};
155 eval {
156 if ($it =~ /^$string/) {
157 $hit = 1;
160 if (defined $hit && defined $found) {
161 return undef;
163 if ($hit) {
164 $found = $i + 1;
167 return $found;
170 sub list_and_choose {
171 my ($opts, @stuff) = @_;
172 my (@chosen, @return);
173 my $i;
175 TOPLOOP:
176 while (1) {
177 my $last_lf = 0;
179 if ($opts->{HEADER}) {
180 if (!$opts->{LIST_FLAT}) {
181 print " ";
183 print "$opts->{HEADER}\n";
185 for ($i = 0; $i < @stuff; $i++) {
186 my $chosen = $chosen[$i] ? '*' : ' ';
187 my $print = $stuff[$i];
188 if (ref $print) {
189 if ((ref $print) eq 'ARRAY') {
190 $print = $print->[0];
192 else {
193 $print = $print->{PRINT};
196 printf("%s%2d: %s", $chosen, $i+1, $print);
197 if (($opts->{LIST_FLAT}) &&
198 (($i + 1) % ($opts->{LIST_FLAT}))) {
199 print "\t";
200 $last_lf = 0;
202 else {
203 print "\n";
204 $last_lf = 1;
207 if (!$last_lf) {
208 print "\n";
211 return if ($opts->{LIST_ONLY});
213 print $opts->{PROMPT};
214 if ($opts->{SINGLETON}) {
215 print "> ";
217 else {
218 print ">> ";
220 my $line = <STDIN>;
221 if (!$line) {
222 print "\n";
223 $opts->{ON_EOF}->() if $opts->{ON_EOF};
224 last;
226 chomp $line;
227 last if $line eq '';
228 for my $choice (split(/[\s,]+/, $line)) {
229 my $choose = 1;
230 my ($bottom, $top);
232 # Input that begins with '-'; unchoose
233 if ($choice =~ s/^-//) {
234 $choose = 0;
236 # A range can be specified like 5-7
237 if ($choice =~ /^(\d+)-(\d+)$/) {
238 ($bottom, $top) = ($1, $2);
240 elsif ($choice =~ /^\d+$/) {
241 $bottom = $top = $choice;
243 elsif ($choice eq '*') {
244 $bottom = 1;
245 $top = 1 + @stuff;
247 else {
248 $bottom = $top = find_unique($choice, @stuff);
249 if (!defined $bottom) {
250 print "Huh ($choice)?\n";
251 next TOPLOOP;
254 if ($opts->{SINGLETON} && $bottom != $top) {
255 print "Huh ($choice)?\n";
256 next TOPLOOP;
258 for ($i = $bottom-1; $i <= $top-1; $i++) {
259 next if (@stuff <= $i || $i < 0);
260 $chosen[$i] = $choose;
263 last if ($opts->{IMMEDIATE} || $line eq '*');
265 for ($i = 0; $i < @stuff; $i++) {
266 if ($chosen[$i]) {
267 push @return, $stuff[$i];
270 return @return;
273 sub status_cmd {
274 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
275 list_modified());
276 print "\n";
279 sub say_n_paths {
280 my $did = shift @_;
281 my $cnt = scalar @_;
282 print "$did ";
283 if (1 < $cnt) {
284 print "$cnt paths\n";
286 else {
287 print "one path\n";
291 sub update_cmd {
292 my @mods = list_modified('file-only');
293 return if (!@mods);
295 my @update = list_and_choose({ PROMPT => 'Update',
296 HEADER => $status_head, },
297 @mods);
298 if (@update) {
299 system(qw(git update-index --add --remove --),
300 map { $_->{VALUE} } @update);
301 say_n_paths('updated', @update);
303 print "\n";
306 sub revert_cmd {
307 my @update = list_and_choose({ PROMPT => 'Revert',
308 HEADER => $status_head, },
309 list_modified());
310 if (@update) {
311 my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
312 map { $_->{VALUE} } @update);
313 my $fh;
314 open $fh, '| git update-index --index-info'
315 or die;
316 for (@lines) {
317 print $fh $_;
319 close($fh);
320 for (@update) {
321 if ($_->{INDEX_ADDDEL} &&
322 $_->{INDEX_ADDDEL} eq 'create') {
323 system(qw(git update-index --force-remove --),
324 $_->{VALUE});
325 print "note: $_->{VALUE} is untracked now.\n";
328 refresh();
329 say_n_paths('reverted', @update);
331 print "\n";
334 sub add_untracked_cmd {
335 my @add = list_and_choose({ PROMPT => 'Add untracked' },
336 list_untracked());
337 if (@add) {
338 system(qw(git update-index --add --), @add);
339 say_n_paths('added', @add);
341 print "\n";
344 sub parse_diff {
345 my ($path) = @_;
346 my @diff = run_cmd_pipe(qw(git diff-files -p --), $path);
347 my (@hunk) = { TEXT => [] };
349 for (@diff) {
350 if (/^@@ /) {
351 push @hunk, { TEXT => [] };
353 push @{$hunk[-1]{TEXT}}, $_;
355 return @hunk;
358 sub hunk_splittable {
359 my ($text) = @_;
361 my @s = split_hunk($text);
362 return (1 < @s);
365 sub parse_hunk_header {
366 my ($line) = @_;
367 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
368 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
369 $o_cnt = 1 unless defined $o_cnt;
370 $n_cnt = 1 unless defined $n_cnt;
371 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
374 sub split_hunk {
375 my ($text) = @_;
376 my @split = ();
378 # If there are context lines in the middle of a hunk,
379 # it can be split, but we would need to take care of
380 # overlaps later.
382 my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
383 my $hunk_start = 1;
385 OUTER:
386 while (1) {
387 my $next_hunk_start = undef;
388 my $i = $hunk_start - 1;
389 my $this = +{
390 TEXT => [],
391 OLD => $o_ofs,
392 NEW => $n_ofs,
393 OCNT => 0,
394 NCNT => 0,
395 ADDDEL => 0,
396 POSTCTX => 0,
399 while (++$i < @$text) {
400 my $line = $text->[$i];
401 if ($line =~ /^ /) {
402 if ($this->{ADDDEL} &&
403 !defined $next_hunk_start) {
404 # We have seen leading context and
405 # adds/dels and then here is another
406 # context, which is trailing for this
407 # split hunk and leading for the next
408 # one.
409 $next_hunk_start = $i;
411 push @{$this->{TEXT}}, $line;
412 $this->{OCNT}++;
413 $this->{NCNT}++;
414 if (defined $next_hunk_start) {
415 $this->{POSTCTX}++;
417 next;
420 # add/del
421 if (defined $next_hunk_start) {
422 # We are done with the current hunk and
423 # this is the first real change for the
424 # next split one.
425 $hunk_start = $next_hunk_start;
426 $o_ofs = $this->{OLD} + $this->{OCNT};
427 $n_ofs = $this->{NEW} + $this->{NCNT};
428 $o_ofs -= $this->{POSTCTX};
429 $n_ofs -= $this->{POSTCTX};
430 push @split, $this;
431 redo OUTER;
433 push @{$this->{TEXT}}, $line;
434 $this->{ADDDEL}++;
435 if ($line =~ /^-/) {
436 $this->{OCNT}++;
438 else {
439 $this->{NCNT}++;
443 push @split, $this;
444 last;
447 for my $hunk (@split) {
448 $o_ofs = $hunk->{OLD};
449 $n_ofs = $hunk->{NEW};
450 my $o_cnt = $hunk->{OCNT};
451 my $n_cnt = $hunk->{NCNT};
453 my $head = ("@@ -$o_ofs" .
454 (($o_cnt != 1) ? ",$o_cnt" : '') .
455 " +$n_ofs" .
456 (($n_cnt != 1) ? ",$n_cnt" : '') .
457 " @@\n");
458 unshift @{$hunk->{TEXT}}, $head;
460 return map { $_->{TEXT} } @split;
463 sub find_last_o_ctx {
464 my ($it) = @_;
465 my $text = $it->{TEXT};
466 my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
467 my $i = @{$text};
468 my $last_o_ctx = $o_ofs + $o_cnt;
469 while (0 < --$i) {
470 my $line = $text->[$i];
471 if ($line =~ /^ /) {
472 $last_o_ctx--;
473 next;
475 last;
477 return $last_o_ctx;
480 sub merge_hunk {
481 my ($prev, $this) = @_;
482 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
483 parse_hunk_header($prev->{TEXT}[0]);
484 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
485 parse_hunk_header($this->{TEXT}[0]);
487 my (@line, $i, $ofs, $o_cnt, $n_cnt);
488 $ofs = $o0_ofs;
489 $o_cnt = $n_cnt = 0;
490 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
491 my $line = $prev->{TEXT}[$i];
492 if ($line =~ /^\+/) {
493 $n_cnt++;
494 push @line, $line;
495 next;
498 last if ($o1_ofs <= $ofs);
500 $o_cnt++;
501 $ofs++;
502 if ($line =~ /^ /) {
503 $n_cnt++;
505 push @line, $line;
508 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
509 my $line = $this->{TEXT}[$i];
510 if ($line =~ /^\+/) {
511 $n_cnt++;
512 push @line, $line;
513 next;
515 $ofs++;
516 $o_cnt++;
517 if ($line =~ /^ /) {
518 $n_cnt++;
520 push @line, $line;
522 my $head = ("@@ -$o0_ofs" .
523 (($o_cnt != 1) ? ",$o_cnt" : '') .
524 " +$n0_ofs" .
525 (($n_cnt != 1) ? ",$n_cnt" : '') .
526 " @@\n");
527 @{$prev->{TEXT}} = ($head, @line);
530 sub coalesce_overlapping_hunks {
531 my (@in) = @_;
532 my @out = ();
534 my ($last_o_ctx);
536 for (grep { $_->{USE} } @in) {
537 my $text = $_->{TEXT};
538 my ($o_ofs) = parse_hunk_header($text->[0]);
539 if (defined $last_o_ctx &&
540 $o_ofs <= $last_o_ctx) {
541 merge_hunk($out[-1], $_);
543 else {
544 push @out, $_;
546 $last_o_ctx = find_last_o_ctx($out[-1]);
548 return @out;
551 sub help_patch_cmd {
552 print <<\EOF ;
553 y - stage this hunk
554 n - do not stage this hunk
555 a - stage this and all the remaining hunks
556 d - do not stage this hunk nor any of the remaining hunks
557 j - leave this hunk undecided, see next undecided hunk
558 J - leave this hunk undecided, see next hunk
559 k - leave this hunk undecided, see previous undecided hunk
560 K - leave this hunk undecided, see previous hunk
561 s - split the current hunk into smaller hunks
565 sub patch_update_cmd {
566 my @mods = list_modified('file-only');
567 @mods = grep { !($_->{BINARY}) } @mods;
568 return if (!@mods);
570 my (@them) = list_and_choose({ PROMPT => 'Patch update',
571 HEADER => $status_head, },
572 @mods);
573 for (@them) {
574 patch_update_file($_->{VALUE});
578 sub patch_update_file {
579 my ($ix, $num);
580 my $path = shift;
581 my ($head, @hunk) = parse_diff($path);
582 for (@{$head->{TEXT}}) {
583 print;
585 $num = scalar @hunk;
586 $ix = 0;
588 while (1) {
589 my ($prev, $next, $other, $undecided, $i);
590 $other = '';
592 if ($num <= $ix) {
593 $ix = 0;
595 for ($i = 0; $i < $ix; $i++) {
596 if (!defined $hunk[$i]{USE}) {
597 $prev = 1;
598 $other .= '/k';
599 last;
602 if ($ix) {
603 $other .= '/K';
605 for ($i = $ix + 1; $i < $num; $i++) {
606 if (!defined $hunk[$i]{USE}) {
607 $next = 1;
608 $other .= '/j';
609 last;
612 if ($ix < $num - 1) {
613 $other .= '/J';
615 for ($i = 0; $i < $num; $i++) {
616 if (!defined $hunk[$i]{USE}) {
617 $undecided = 1;
618 last;
621 last if (!$undecided);
623 if (hunk_splittable($hunk[$ix]{TEXT})) {
624 $other .= '/s';
626 for (@{$hunk[$ix]{TEXT}}) {
627 print;
629 print "Stage this hunk [y/n/a/d$other/?]? ";
630 my $line = <STDIN>;
631 if ($line) {
632 if ($line =~ /^y/i) {
633 $hunk[$ix]{USE} = 1;
635 elsif ($line =~ /^n/i) {
636 $hunk[$ix]{USE} = 0;
638 elsif ($line =~ /^a/i) {
639 while ($ix < $num) {
640 if (!defined $hunk[$ix]{USE}) {
641 $hunk[$ix]{USE} = 1;
643 $ix++;
645 next;
647 elsif ($line =~ /^d/i) {
648 while ($ix < $num) {
649 if (!defined $hunk[$ix]{USE}) {
650 $hunk[$ix]{USE} = 0;
652 $ix++;
654 next;
656 elsif ($other =~ /K/ && $line =~ /^K/) {
657 $ix--;
658 next;
660 elsif ($other =~ /J/ && $line =~ /^J/) {
661 $ix++;
662 next;
664 elsif ($other =~ /k/ && $line =~ /^k/) {
665 while (1) {
666 $ix--;
667 last if (!$ix ||
668 !defined $hunk[$ix]{USE});
670 next;
672 elsif ($other =~ /j/ && $line =~ /^j/) {
673 while (1) {
674 $ix++;
675 last if ($ix >= $num ||
676 !defined $hunk[$ix]{USE});
678 next;
680 elsif ($other =~ /s/ && $line =~ /^s/) {
681 my @split = split_hunk($hunk[$ix]{TEXT});
682 if (1 < @split) {
683 print "Split into ",
684 scalar(@split), " hunks.\n";
686 splice(@hunk, $ix, 1,
687 map { +{ TEXT => $_, USE => undef } }
688 @split);
689 $num = scalar @hunk;
690 next;
692 else {
693 help_patch_cmd($other);
694 next;
696 # soft increment
697 while (1) {
698 $ix++;
699 last if ($ix >= $num ||
700 !defined $hunk[$ix]{USE});
705 @hunk = coalesce_overlapping_hunks(@hunk);
707 my $n_lofs = 0;
708 my @result = ();
709 for (@hunk) {
710 my $text = $_->{TEXT};
711 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
712 parse_hunk_header($text->[0]);
714 if (!$_->{USE}) {
715 # We would have added ($n_cnt - $o_cnt) lines
716 # to the postimage if we were to use this hunk,
717 # but we didn't. So the line number that the next
718 # hunk starts at would be shifted by that much.
719 $n_lofs -= ($n_cnt - $o_cnt);
720 next;
722 else {
723 if ($n_lofs) {
724 $n_ofs += $n_lofs;
725 $text->[0] = ("@@ -$o_ofs" .
726 (($o_cnt != 1)
727 ? ",$o_cnt" : '') .
728 " +$n_ofs" .
729 (($n_cnt != 1)
730 ? ",$n_cnt" : '') .
731 " @@\n");
733 for (@$text) {
734 push @result, $_;
739 if (@result) {
740 my $fh;
742 open $fh, '| git apply --cached';
743 for (@{$head->{TEXT}}, @result) {
744 print $fh $_;
746 if (!close $fh) {
747 for (@{$head->{TEXT}}, @result) {
748 print STDERR $_;
751 refresh();
754 print "\n";
757 sub diff_cmd {
758 my @mods = list_modified('index-only');
759 @mods = grep { !($_->{BINARY}) } @mods;
760 return if (!@mods);
761 my (@them) = list_and_choose({ PROMPT => 'Review diff',
762 IMMEDIATE => 1,
763 HEADER => $status_head, },
764 @mods);
765 return if (!@them);
766 system(qw(git diff-index -p --cached HEAD --),
767 map { $_->{VALUE} } @them);
770 sub quit_cmd {
771 print "Bye.\n";
772 exit(0);
775 sub help_cmd {
776 print <<\EOF ;
777 status - show paths with changes
778 update - add working tree state to the staged set of changes
779 revert - revert staged set of changes back to the HEAD version
780 patch - pick hunks and update selectively
781 diff - view diff between HEAD and index
782 add untracked - add contents of untracked files to the staged set of changes
786 sub main_loop {
787 my @cmd = ([ 'status', \&status_cmd, ],
788 [ 'update', \&update_cmd, ],
789 [ 'revert', \&revert_cmd, ],
790 [ 'add untracked', \&add_untracked_cmd, ],
791 [ 'patch', \&patch_update_cmd, ],
792 [ 'diff', \&diff_cmd, ],
793 [ 'quit', \&quit_cmd, ],
794 [ 'help', \&help_cmd, ],
796 while (1) {
797 my ($it) = list_and_choose({ PROMPT => 'What now',
798 SINGLETON => 1,
799 LIST_FLAT => 4,
800 HEADER => '*** Commands ***',
801 ON_EOF => \&quit_cmd,
802 IMMEDIATE => 1 }, @cmd);
803 if ($it) {
804 eval {
805 $it->[1]->();
807 if ($@) {
808 print "$@";
814 refresh();
815 status_cmd();
816 main_loop();