Refactor patch_update_cmd
[git.git] / git-add--interactive.perl
blobfb1e92a7664f77aa5ca4ca30b4711bafaf155466
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 --), @_);
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);
60 for (run_cmd_pipe(qw(git diff-index --cached
61 --numstat --summary HEAD))) {
62 if (($add, $del, $file) =
63 /^([-\d]+) ([-\d]+) (.*)/) {
64 my ($change, $bin);
65 if ($add eq '-' && $del eq '-') {
66 $change = 'binary';
67 $bin = 1;
69 else {
70 $change = "+$add/-$del";
72 $data{$file} = {
73 INDEX => $change,
74 BINARY => $bin,
75 FILE => 'nothing',
78 elsif (($adddel, $file) =
79 /^ (create|delete) mode [0-7]+ (.*)$/) {
80 $data{$file}{INDEX_ADDDEL} = $adddel;
84 for (run_cmd_pipe(qw(git diff-files --numstat --summary))) {
85 if (($add, $del, $file) =
86 /^([-\d]+) ([-\d]+) (.*)/) {
87 if (!exists $data{$file}) {
88 $data{$file} = +{
89 INDEX => 'unchanged',
90 BINARY => 0,
93 my ($change, $bin);
94 if ($add eq '-' && $del eq '-') {
95 $change = 'binary';
96 $bin = 1;
98 else {
99 $change = "+$add/-$del";
101 $data{$file}{FILE} = $change;
102 if ($bin) {
103 $data{$file}{BINARY} = 1;
106 elsif (($adddel, $file) =
107 /^ (create|delete) mode [0-7]+ (.*)$/) {
108 $data{$file}{FILE_ADDDEL} = $adddel;
112 for (sort keys %data) {
113 my $it = $data{$_};
115 if ($only) {
116 if ($only eq 'index-only') {
117 next if ($it->{INDEX} eq 'unchanged');
119 if ($only eq 'file-only') {
120 next if ($it->{FILE} eq 'nothing');
123 push @return, +{
124 VALUE => $_,
125 PRINT => (sprintf $status_fmt,
126 $it->{INDEX}, $it->{FILE}, $_),
127 %$it,
130 return @return;
133 sub find_unique {
134 my ($string, @stuff) = @_;
135 my $found = undef;
136 for (my $i = 0; $i < @stuff; $i++) {
137 my $it = $stuff[$i];
138 my $hit = undef;
139 if (ref $it) {
140 if ((ref $it) eq 'ARRAY') {
141 $it = $it->[0];
143 else {
144 $it = $it->{VALUE};
147 eval {
148 if ($it =~ /^$string/) {
149 $hit = 1;
152 if (defined $hit && defined $found) {
153 return undef;
155 if ($hit) {
156 $found = $i + 1;
159 return $found;
162 sub list_and_choose {
163 my ($opts, @stuff) = @_;
164 my (@chosen, @return);
165 my $i;
167 TOPLOOP:
168 while (1) {
169 my $last_lf = 0;
171 if ($opts->{HEADER}) {
172 if (!$opts->{LIST_FLAT}) {
173 print " ";
175 print "$opts->{HEADER}\n";
177 for ($i = 0; $i < @stuff; $i++) {
178 my $chosen = $chosen[$i] ? '*' : ' ';
179 my $print = $stuff[$i];
180 if (ref $print) {
181 if ((ref $print) eq 'ARRAY') {
182 $print = $print->[0];
184 else {
185 $print = $print->{PRINT};
188 printf("%s%2d: %s", $chosen, $i+1, $print);
189 if (($opts->{LIST_FLAT}) &&
190 (($i + 1) % ($opts->{LIST_FLAT}))) {
191 print "\t";
192 $last_lf = 0;
194 else {
195 print "\n";
196 $last_lf = 1;
199 if (!$last_lf) {
200 print "\n";
203 return if ($opts->{LIST_ONLY});
205 print $opts->{PROMPT};
206 if ($opts->{SINGLETON}) {
207 print "> ";
209 else {
210 print ">> ";
212 my $line = <STDIN>;
213 if (!$line) {
214 print "\n";
215 $opts->{ON_EOF}->() if $opts->{ON_EOF};
216 last;
218 chomp $line;
219 last if $line eq '';
220 for my $choice (split(/[\s,]+/, $line)) {
221 my $choose = 1;
222 my ($bottom, $top);
224 # Input that begins with '-'; unchoose
225 if ($choice =~ s/^-//) {
226 $choose = 0;
228 # A range can be specified like 5-7
229 if ($choice =~ /^(\d+)-(\d+)$/) {
230 ($bottom, $top) = ($1, $2);
232 elsif ($choice =~ /^\d+$/) {
233 $bottom = $top = $choice;
235 elsif ($choice eq '*') {
236 $bottom = 1;
237 $top = 1 + @stuff;
239 else {
240 $bottom = $top = find_unique($choice, @stuff);
241 if (!defined $bottom) {
242 print "Huh ($choice)?\n";
243 next TOPLOOP;
246 if ($opts->{SINGLETON} && $bottom != $top) {
247 print "Huh ($choice)?\n";
248 next TOPLOOP;
250 for ($i = $bottom-1; $i <= $top-1; $i++) {
251 next if (@stuff <= $i || $i < 0);
252 $chosen[$i] = $choose;
255 last if ($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 $o_cnt = 1 unless defined $o_cnt;
362 $n_cnt = 1 unless defined $n_cnt;
363 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
366 sub split_hunk {
367 my ($text) = @_;
368 my @split = ();
370 # If there are context lines in the middle of a hunk,
371 # it can be split, but we would need to take care of
372 # overlaps later.
374 my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
375 my $hunk_start = 1;
377 OUTER:
378 while (1) {
379 my $next_hunk_start = undef;
380 my $i = $hunk_start - 1;
381 my $this = +{
382 TEXT => [],
383 OLD => $o_ofs,
384 NEW => $n_ofs,
385 OCNT => 0,
386 NCNT => 0,
387 ADDDEL => 0,
388 POSTCTX => 0,
391 while (++$i < @$text) {
392 my $line = $text->[$i];
393 if ($line =~ /^ /) {
394 if ($this->{ADDDEL} &&
395 !defined $next_hunk_start) {
396 # We have seen leading context and
397 # adds/dels and then here is another
398 # context, which is trailing for this
399 # split hunk and leading for the next
400 # one.
401 $next_hunk_start = $i;
403 push @{$this->{TEXT}}, $line;
404 $this->{OCNT}++;
405 $this->{NCNT}++;
406 if (defined $next_hunk_start) {
407 $this->{POSTCTX}++;
409 next;
412 # add/del
413 if (defined $next_hunk_start) {
414 # We are done with the current hunk and
415 # this is the first real change for the
416 # next split one.
417 $hunk_start = $next_hunk_start;
418 $o_ofs = $this->{OLD} + $this->{OCNT};
419 $n_ofs = $this->{NEW} + $this->{NCNT};
420 $o_ofs -= $this->{POSTCTX};
421 $n_ofs -= $this->{POSTCTX};
422 push @split, $this;
423 redo OUTER;
425 push @{$this->{TEXT}}, $line;
426 $this->{ADDDEL}++;
427 if ($line =~ /^-/) {
428 $this->{OCNT}++;
430 else {
431 $this->{NCNT}++;
435 push @split, $this;
436 last;
439 for my $hunk (@split) {
440 $o_ofs = $hunk->{OLD};
441 $n_ofs = $hunk->{NEW};
442 my $o_cnt = $hunk->{OCNT};
443 my $n_cnt = $hunk->{NCNT};
445 my $head = ("@@ -$o_ofs" .
446 (($o_cnt != 1) ? ",$o_cnt" : '') .
447 " +$n_ofs" .
448 (($n_cnt != 1) ? ",$n_cnt" : '') .
449 " @@\n");
450 unshift @{$hunk->{TEXT}}, $head;
452 return map { $_->{TEXT} } @split;
455 sub find_last_o_ctx {
456 my ($it) = @_;
457 my $text = $it->{TEXT};
458 my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
459 my $i = @{$text};
460 my $last_o_ctx = $o_ofs + $o_cnt;
461 while (0 < --$i) {
462 my $line = $text->[$i];
463 if ($line =~ /^ /) {
464 $last_o_ctx--;
465 next;
467 last;
469 return $last_o_ctx;
472 sub merge_hunk {
473 my ($prev, $this) = @_;
474 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
475 parse_hunk_header($prev->{TEXT}[0]);
476 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
477 parse_hunk_header($this->{TEXT}[0]);
479 my (@line, $i, $ofs, $o_cnt, $n_cnt);
480 $ofs = $o0_ofs;
481 $o_cnt = $n_cnt = 0;
482 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
483 my $line = $prev->{TEXT}[$i];
484 if ($line =~ /^\+/) {
485 $n_cnt++;
486 push @line, $line;
487 next;
490 last if ($o1_ofs <= $ofs);
492 $o_cnt++;
493 $ofs++;
494 if ($line =~ /^ /) {
495 $n_cnt++;
497 push @line, $line;
500 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
501 my $line = $this->{TEXT}[$i];
502 if ($line =~ /^\+/) {
503 $n_cnt++;
504 push @line, $line;
505 next;
507 $ofs++;
508 $o_cnt++;
509 if ($line =~ /^ /) {
510 $n_cnt++;
512 push @line, $line;
514 my $head = ("@@ -$o0_ofs" .
515 (($o_cnt != 1) ? ",$o_cnt" : '') .
516 " +$n0_ofs" .
517 (($n_cnt != 1) ? ",$n_cnt" : '') .
518 " @@\n");
519 @{$prev->{TEXT}} = ($head, @line);
522 sub coalesce_overlapping_hunks {
523 my (@in) = @_;
524 my @out = ();
526 my ($last_o_ctx);
528 for (grep { $_->{USE} } @in) {
529 my $text = $_->{TEXT};
530 my ($o_ofs) = 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 patch_update_file($it->{VALUE}) if ($it);
570 sub patch_update_file {
571 my ($ix, $num);
572 my $path = shift;
573 my ($head, @hunk) = parse_diff($path);
574 for (@{$head->{TEXT}}) {
575 print;
577 $num = scalar @hunk;
578 $ix = 0;
580 while (1) {
581 my ($prev, $next, $other, $undecided, $i);
582 $other = '';
584 if ($num <= $ix) {
585 $ix = 0;
587 for ($i = 0; $i < $ix; $i++) {
588 if (!defined $hunk[$i]{USE}) {
589 $prev = 1;
590 $other .= '/k';
591 last;
594 if ($ix) {
595 $other .= '/K';
597 for ($i = $ix + 1; $i < $num; $i++) {
598 if (!defined $hunk[$i]{USE}) {
599 $next = 1;
600 $other .= '/j';
601 last;
604 if ($ix < $num - 1) {
605 $other .= '/J';
607 for ($i = 0; $i < $num; $i++) {
608 if (!defined $hunk[$i]{USE}) {
609 $undecided = 1;
610 last;
613 last if (!$undecided);
615 if (hunk_splittable($hunk[$ix]{TEXT})) {
616 $other .= '/s';
618 for (@{$hunk[$ix]{TEXT}}) {
619 print;
621 print "Stage this hunk [y/n/a/d$other/?]? ";
622 my $line = <STDIN>;
623 if ($line) {
624 if ($line =~ /^y/i) {
625 $hunk[$ix]{USE} = 1;
627 elsif ($line =~ /^n/i) {
628 $hunk[$ix]{USE} = 0;
630 elsif ($line =~ /^a/i) {
631 while ($ix < $num) {
632 if (!defined $hunk[$ix]{USE}) {
633 $hunk[$ix]{USE} = 1;
635 $ix++;
637 next;
639 elsif ($line =~ /^d/i) {
640 while ($ix < $num) {
641 if (!defined $hunk[$ix]{USE}) {
642 $hunk[$ix]{USE} = 0;
644 $ix++;
646 next;
648 elsif ($other =~ /K/ && $line =~ /^K/) {
649 $ix--;
650 next;
652 elsif ($other =~ /J/ && $line =~ /^J/) {
653 $ix++;
654 next;
656 elsif ($other =~ /k/ && $line =~ /^k/) {
657 while (1) {
658 $ix--;
659 last if (!$ix ||
660 !defined $hunk[$ix]{USE});
662 next;
664 elsif ($other =~ /j/ && $line =~ /^j/) {
665 while (1) {
666 $ix++;
667 last if ($ix >= $num ||
668 !defined $hunk[$ix]{USE});
670 next;
672 elsif ($other =~ /s/ && $line =~ /^s/) {
673 my @split = split_hunk($hunk[$ix]{TEXT});
674 if (1 < @split) {
675 print "Split into ",
676 scalar(@split), " hunks.\n";
678 splice(@hunk, $ix, 1,
679 map { +{ TEXT => $_, USE => undef } }
680 @split);
681 $num = scalar @hunk;
682 next;
684 else {
685 help_patch_cmd($other);
686 next;
688 # soft increment
689 while (1) {
690 $ix++;
691 last if ($ix >= $num ||
692 !defined $hunk[$ix]{USE});
697 @hunk = coalesce_overlapping_hunks(@hunk);
699 my $n_lofs = 0;
700 my @result = ();
701 for (@hunk) {
702 my $text = $_->{TEXT};
703 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
704 parse_hunk_header($text->[0]);
706 if (!$_->{USE}) {
707 # We would have added ($n_cnt - $o_cnt) lines
708 # to the postimage if we were to use this hunk,
709 # but we didn't. So the line number that the next
710 # hunk starts at would be shifted by that much.
711 $n_lofs -= ($n_cnt - $o_cnt);
712 next;
714 else {
715 if ($n_lofs) {
716 $n_ofs += $n_lofs;
717 $text->[0] = ("@@ -$o_ofs" .
718 (($o_cnt != 1)
719 ? ",$o_cnt" : '') .
720 " +$n_ofs" .
721 (($n_cnt != 1)
722 ? ",$n_cnt" : '') .
723 " @@\n");
725 for (@$text) {
726 push @result, $_;
731 if (@result) {
732 my $fh;
734 open $fh, '| git apply --cached';
735 for (@{$head->{TEXT}}, @result) {
736 print $fh $_;
738 if (!close $fh) {
739 for (@{$head->{TEXT}}, @result) {
740 print STDERR $_;
743 refresh();
746 print "\n";
749 sub diff_cmd {
750 my @mods = list_modified('index-only');
751 @mods = grep { !($_->{BINARY}) } @mods;
752 return if (!@mods);
753 my (@them) = list_and_choose({ PROMPT => 'Review diff',
754 IMMEDIATE => 1,
755 HEADER => $status_head, },
756 @mods);
757 return if (!@them);
758 system(qw(git diff-index -p --cached HEAD --),
759 map { $_->{VALUE} } @them);
762 sub quit_cmd {
763 print "Bye.\n";
764 exit(0);
767 sub help_cmd {
768 print <<\EOF ;
769 status - show paths with changes
770 update - add working tree state to the staged set of changes
771 revert - revert staged set of changes back to the HEAD version
772 patch - pick hunks and update selectively
773 diff - view diff between HEAD and index
774 add untracked - add contents of untracked files to the staged set of changes
778 sub main_loop {
779 my @cmd = ([ 'status', \&status_cmd, ],
780 [ 'update', \&update_cmd, ],
781 [ 'revert', \&revert_cmd, ],
782 [ 'add untracked', \&add_untracked_cmd, ],
783 [ 'patch', \&patch_update_cmd, ],
784 [ 'diff', \&diff_cmd, ],
785 [ 'quit', \&quit_cmd, ],
786 [ 'help', \&help_cmd, ],
788 while (1) {
789 my ($it) = list_and_choose({ PROMPT => 'What now',
790 SINGLETON => 1,
791 LIST_FLAT => 4,
792 HEADER => '*** Commands ***',
793 ON_EOF => \&quit_cmd,
794 IMMEDIATE => 1 }, @cmd);
795 if ($it) {
796 eval {
797 $it->[1]->();
799 if ($@) {
800 print "$@";
806 refresh();
807 status_cmd();
808 main_loop();