refactor signal handling for cleanup functions
[git/mingw/j6t.git] / git-add--interactive.perl
blobca60356d0082123cd1e9572572528d8265be43a3
1 #!/usr/bin/perl -w
3 use strict;
4 use Git;
6 my $repo = Git->repository();
8 my $menu_use_color = $repo->get_colorbool('color.interactive');
9 my ($prompt_color, $header_color, $help_color) =
10 $menu_use_color ? (
11 $repo->get_color('color.interactive.prompt', 'bold blue'),
12 $repo->get_color('color.interactive.header', 'bold'),
13 $repo->get_color('color.interactive.help', 'red bold'),
14 ) : ();
16 my $diff_use_color = $repo->get_colorbool('color.diff');
17 my ($fraginfo_color) =
18 $diff_use_color ? (
19 $repo->get_color('color.diff.frag', 'cyan'),
20 ) : ();
21 my ($diff_plain_color) =
22 $diff_use_color ? (
23 $repo->get_color('color.diff.plain', ''),
24 ) : ();
25 my ($diff_old_color) =
26 $diff_use_color ? (
27 $repo->get_color('color.diff.old', 'red'),
28 ) : ();
29 my ($diff_new_color) =
30 $diff_use_color ? (
31 $repo->get_color('color.diff.new', 'green'),
32 ) : ();
34 my $normal_color = $repo->get_color("", "reset");
36 sub colored {
37 my $color = shift;
38 my $string = join("", @_);
40 if (defined $color) {
41 # Put a color code at the beginning of each line, a reset at the end
42 # color after newlines that are not at the end of the string
43 $string =~ s/(\n+)(.)/$1$color$2/g;
44 # reset before newlines
45 $string =~ s/(\n+)/$normal_color$1/g;
46 # codes at beginning and end (if necessary):
47 $string =~ s/^/$color/;
48 $string =~ s/$/$normal_color/ unless $string =~ /\n$/;
50 return $string;
53 # command line options
54 my $patch_mode;
56 sub run_cmd_pipe {
57 if ($^O eq 'MSWin32' || $^O eq 'msys') {
58 my @invalid = grep {m/[":*]/} @_;
59 die "$^O does not support: @invalid\n" if @invalid;
60 my @args = map { m/ /o ? "\"$_\"": $_ } @_;
61 return qx{@args};
62 } else {
63 my $fh = undef;
64 open($fh, '-|', @_) or die;
65 return <$fh>;
69 my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));
71 if (!defined $GIT_DIR) {
72 exit(1); # rev-parse would have already said "not a git repo"
74 chomp($GIT_DIR);
76 sub refresh {
77 my $fh;
78 open $fh, 'git update-index --refresh |'
79 or die;
80 while (<$fh>) {
81 ;# ignore 'needs update'
83 close $fh;
86 sub list_untracked {
87 map {
88 chomp $_;
89 $_;
91 run_cmd_pipe(qw(git ls-files --others --exclude-standard --), @ARGV);
94 my $status_fmt = '%12s %12s %s';
95 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
98 my $initial;
99 sub is_initial_commit {
100 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
101 unless defined $initial;
102 return $initial;
106 sub get_empty_tree {
107 return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
110 # Returns list of hashes, contents of each of which are:
111 # VALUE: pathname
112 # BINARY: is a binary path
113 # INDEX: is index different from HEAD?
114 # FILE: is file different from index?
115 # INDEX_ADDDEL: is it add/delete between HEAD and index?
116 # FILE_ADDDEL: is it add/delete between index and file?
118 sub list_modified {
119 my ($only) = @_;
120 my (%data, @return);
121 my ($add, $del, $adddel, $file);
122 my @tracked = ();
124 if (@ARGV) {
125 @tracked = map {
126 chomp $_; $_;
127 } run_cmd_pipe(qw(git ls-files --exclude-standard --), @ARGV);
128 return if (!@tracked);
131 my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
132 for (run_cmd_pipe(qw(git diff-index --cached
133 --numstat --summary), $reference,
134 '--', @tracked)) {
135 if (($add, $del, $file) =
136 /^([-\d]+) ([-\d]+) (.*)/) {
137 my ($change, $bin);
138 if ($add eq '-' && $del eq '-') {
139 $change = 'binary';
140 $bin = 1;
142 else {
143 $change = "+$add/-$del";
145 $data{$file} = {
146 INDEX => $change,
147 BINARY => $bin,
148 FILE => 'nothing',
151 elsif (($adddel, $file) =
152 /^ (create|delete) mode [0-7]+ (.*)$/) {
153 $data{$file}{INDEX_ADDDEL} = $adddel;
157 for (run_cmd_pipe(qw(git diff-files --numstat --summary --), @tracked)) {
158 if (($add, $del, $file) =
159 /^([-\d]+) ([-\d]+) (.*)/) {
160 if (!exists $data{$file}) {
161 $data{$file} = +{
162 INDEX => 'unchanged',
163 BINARY => 0,
166 my ($change, $bin);
167 if ($add eq '-' && $del eq '-') {
168 $change = 'binary';
169 $bin = 1;
171 else {
172 $change = "+$add/-$del";
174 $data{$file}{FILE} = $change;
175 if ($bin) {
176 $data{$file}{BINARY} = 1;
179 elsif (($adddel, $file) =
180 /^ (create|delete) mode [0-7]+ (.*)$/) {
181 $data{$file}{FILE_ADDDEL} = $adddel;
185 for (sort keys %data) {
186 my $it = $data{$_};
188 if ($only) {
189 if ($only eq 'index-only') {
190 next if ($it->{INDEX} eq 'unchanged');
192 if ($only eq 'file-only') {
193 next if ($it->{FILE} eq 'nothing');
196 push @return, +{
197 VALUE => $_,
198 %$it,
201 return @return;
204 sub find_unique {
205 my ($string, @stuff) = @_;
206 my $found = undef;
207 for (my $i = 0; $i < @stuff; $i++) {
208 my $it = $stuff[$i];
209 my $hit = undef;
210 if (ref $it) {
211 if ((ref $it) eq 'ARRAY') {
212 $it = $it->[0];
214 else {
215 $it = $it->{VALUE};
218 eval {
219 if ($it =~ /^$string/) {
220 $hit = 1;
223 if (defined $hit && defined $found) {
224 return undef;
226 if ($hit) {
227 $found = $i + 1;
230 return $found;
233 # inserts string into trie and updates count for each character
234 sub update_trie {
235 my ($trie, $string) = @_;
236 foreach (split //, $string) {
237 $trie = $trie->{$_} ||= {COUNT => 0};
238 $trie->{COUNT}++;
242 # returns an array of tuples (prefix, remainder)
243 sub find_unique_prefixes {
244 my @stuff = @_;
245 my @return = ();
247 # any single prefix exceeding the soft limit is omitted
248 # if any prefix exceeds the hard limit all are omitted
249 # 0 indicates no limit
250 my $soft_limit = 0;
251 my $hard_limit = 3;
253 # build a trie modelling all possible options
254 my %trie;
255 foreach my $print (@stuff) {
256 if ((ref $print) eq 'ARRAY') {
257 $print = $print->[0];
259 elsif ((ref $print) eq 'HASH') {
260 $print = $print->{VALUE};
262 update_trie(\%trie, $print);
263 push @return, $print;
266 # use the trie to find the unique prefixes
267 for (my $i = 0; $i < @return; $i++) {
268 my $ret = $return[$i];
269 my @letters = split //, $ret;
270 my %search = %trie;
271 my ($prefix, $remainder);
272 my $j;
273 for ($j = 0; $j < @letters; $j++) {
274 my $letter = $letters[$j];
275 if ($search{$letter}{COUNT} == 1) {
276 $prefix = substr $ret, 0, $j + 1;
277 $remainder = substr $ret, $j + 1;
278 last;
280 else {
281 my $prefix = substr $ret, 0, $j;
282 return ()
283 if ($hard_limit && $j + 1 > $hard_limit);
285 %search = %{$search{$letter}};
287 if ($soft_limit && $j + 1 > $soft_limit) {
288 $prefix = undef;
289 $remainder = $ret;
291 $return[$i] = [$prefix, $remainder];
293 return @return;
296 # filters out prefixes which have special meaning to list_and_choose()
297 sub is_valid_prefix {
298 my $prefix = shift;
299 return (defined $prefix) &&
300 !($prefix =~ /[\s,]/) && # separators
301 !($prefix =~ /^-/) && # deselection
302 !($prefix =~ /^\d+/) && # selection
303 ($prefix ne '*') && # "all" wildcard
304 ($prefix ne '?'); # prompt help
307 # given a prefix/remainder tuple return a string with the prefix highlighted
308 # for now use square brackets; later might use ANSI colors (underline, bold)
309 sub highlight_prefix {
310 my $prefix = shift;
311 my $remainder = shift;
313 if (!defined $prefix) {
314 return $remainder;
317 if (!is_valid_prefix($prefix)) {
318 return "$prefix$remainder";
321 if (!$menu_use_color) {
322 return "[$prefix]$remainder";
325 return "$prompt_color$prefix$normal_color$remainder";
328 sub list_and_choose {
329 my ($opts, @stuff) = @_;
330 my (@chosen, @return);
331 my $i;
332 my @prefixes = find_unique_prefixes(@stuff) unless $opts->{LIST_ONLY};
334 TOPLOOP:
335 while (1) {
336 my $last_lf = 0;
338 if ($opts->{HEADER}) {
339 if (!$opts->{LIST_FLAT}) {
340 print " ";
342 print colored $header_color, "$opts->{HEADER}\n";
344 for ($i = 0; $i < @stuff; $i++) {
345 my $chosen = $chosen[$i] ? '*' : ' ';
346 my $print = $stuff[$i];
347 my $ref = ref $print;
348 my $highlighted = highlight_prefix(@{$prefixes[$i]})
349 if @prefixes;
350 if ($ref eq 'ARRAY') {
351 $print = $highlighted || $print->[0];
353 elsif ($ref eq 'HASH') {
354 my $value = $highlighted || $print->{VALUE};
355 $print = sprintf($status_fmt,
356 $print->{INDEX},
357 $print->{FILE},
358 $value);
360 else {
361 $print = $highlighted || $print;
363 printf("%s%2d: %s", $chosen, $i+1, $print);
364 if (($opts->{LIST_FLAT}) &&
365 (($i + 1) % ($opts->{LIST_FLAT}))) {
366 print "\t";
367 $last_lf = 0;
369 else {
370 print "\n";
371 $last_lf = 1;
374 if (!$last_lf) {
375 print "\n";
378 return if ($opts->{LIST_ONLY});
380 print colored $prompt_color, $opts->{PROMPT};
381 if ($opts->{SINGLETON}) {
382 print "> ";
384 else {
385 print ">> ";
387 my $line = <STDIN>;
388 if (!$line) {
389 print "\n";
390 $opts->{ON_EOF}->() if $opts->{ON_EOF};
391 last;
393 chomp $line;
394 last if $line eq '';
395 if ($line eq '?') {
396 $opts->{SINGLETON} ?
397 singleton_prompt_help_cmd() :
398 prompt_help_cmd();
399 next TOPLOOP;
401 for my $choice (split(/[\s,]+/, $line)) {
402 my $choose = 1;
403 my ($bottom, $top);
405 # Input that begins with '-'; unchoose
406 if ($choice =~ s/^-//) {
407 $choose = 0;
409 # A range can be specified like 5-7 or 5-.
410 if ($choice =~ /^(\d+)-(\d*)$/) {
411 ($bottom, $top) = ($1, length($2) ? $2 : 1 + @stuff);
413 elsif ($choice =~ /^\d+$/) {
414 $bottom = $top = $choice;
416 elsif ($choice eq '*') {
417 $bottom = 1;
418 $top = 1 + @stuff;
420 else {
421 $bottom = $top = find_unique($choice, @stuff);
422 if (!defined $bottom) {
423 print "Huh ($choice)?\n";
424 next TOPLOOP;
427 if ($opts->{SINGLETON} && $bottom != $top) {
428 print "Huh ($choice)?\n";
429 next TOPLOOP;
431 for ($i = $bottom-1; $i <= $top-1; $i++) {
432 next if (@stuff <= $i || $i < 0);
433 $chosen[$i] = $choose;
436 last if ($opts->{IMMEDIATE} || $line eq '*');
438 for ($i = 0; $i < @stuff; $i++) {
439 if ($chosen[$i]) {
440 push @return, $stuff[$i];
443 return @return;
446 sub singleton_prompt_help_cmd {
447 print colored $help_color, <<\EOF ;
448 Prompt help:
449 1 - select a numbered item
450 foo - select item based on unique prefix
451 - (empty) select nothing
455 sub prompt_help_cmd {
456 print colored $help_color, <<\EOF ;
457 Prompt help:
458 1 - select a single item
459 3-5 - select a range of items
460 2-3,6-9 - select multiple ranges
461 foo - select item based on unique prefix
462 -... - unselect specified items
463 * - choose all items
464 - (empty) finish selecting
468 sub status_cmd {
469 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
470 list_modified());
471 print "\n";
474 sub say_n_paths {
475 my $did = shift @_;
476 my $cnt = scalar @_;
477 print "$did ";
478 if (1 < $cnt) {
479 print "$cnt paths\n";
481 else {
482 print "one path\n";
486 sub update_cmd {
487 my @mods = list_modified('file-only');
488 return if (!@mods);
490 my @update = list_and_choose({ PROMPT => 'Update',
491 HEADER => $status_head, },
492 @mods);
493 if (@update) {
494 system(qw(git update-index --add --remove --),
495 map { $_->{VALUE} } @update);
496 say_n_paths('updated', @update);
498 print "\n";
501 sub revert_cmd {
502 my @update = list_and_choose({ PROMPT => 'Revert',
503 HEADER => $status_head, },
504 list_modified());
505 if (@update) {
506 if (is_initial_commit()) {
507 system(qw(git rm --cached),
508 map { $_->{VALUE} } @update);
510 else {
511 my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
512 map { $_->{VALUE} } @update);
513 my $fh;
514 open $fh, '| git update-index --index-info'
515 or die;
516 for (@lines) {
517 print $fh $_;
519 close($fh);
520 for (@update) {
521 if ($_->{INDEX_ADDDEL} &&
522 $_->{INDEX_ADDDEL} eq 'create') {
523 system(qw(git update-index --force-remove --),
524 $_->{VALUE});
525 print "note: $_->{VALUE} is untracked now.\n";
529 refresh();
530 say_n_paths('reverted', @update);
532 print "\n";
535 sub add_untracked_cmd {
536 my @add = list_and_choose({ PROMPT => 'Add untracked' },
537 list_untracked());
538 if (@add) {
539 system(qw(git update-index --add --), @add);
540 say_n_paths('added', @add);
542 print "\n";
545 sub parse_diff {
546 my ($path) = @_;
547 my @diff = run_cmd_pipe(qw(git diff-files -p --), $path);
548 my @colored = ();
549 if ($diff_use_color) {
550 @colored = run_cmd_pipe(qw(git diff-files -p --color --), $path);
552 my (@hunk) = { TEXT => [], DISPLAY => [] };
554 for (my $i = 0; $i < @diff; $i++) {
555 if ($diff[$i] =~ /^@@ /) {
556 push @hunk, { TEXT => [], DISPLAY => [] };
558 push @{$hunk[-1]{TEXT}}, $diff[$i];
559 push @{$hunk[-1]{DISPLAY}},
560 ($diff_use_color ? $colored[$i] : $diff[$i]);
562 return @hunk;
565 sub parse_diff_header {
566 my $src = shift;
568 my $head = { TEXT => [], DISPLAY => [] };
569 my $mode = { TEXT => [], DISPLAY => [] };
571 for (my $i = 0; $i < @{$src->{TEXT}}; $i++) {
572 my $dest = $src->{TEXT}->[$i] =~ /^(old|new) mode (\d+)$/ ?
573 $mode : $head;
574 push @{$dest->{TEXT}}, $src->{TEXT}->[$i];
575 push @{$dest->{DISPLAY}}, $src->{DISPLAY}->[$i];
577 return ($head, $mode);
580 sub hunk_splittable {
581 my ($text) = @_;
583 my @s = split_hunk($text);
584 return (1 < @s);
587 sub parse_hunk_header {
588 my ($line) = @_;
589 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
590 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
591 $o_cnt = 1 unless defined $o_cnt;
592 $n_cnt = 1 unless defined $n_cnt;
593 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
596 sub split_hunk {
597 my ($text, $display) = @_;
598 my @split = ();
599 if (!defined $display) {
600 $display = $text;
602 # If there are context lines in the middle of a hunk,
603 # it can be split, but we would need to take care of
604 # overlaps later.
606 my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
607 my $hunk_start = 1;
609 OUTER:
610 while (1) {
611 my $next_hunk_start = undef;
612 my $i = $hunk_start - 1;
613 my $this = +{
614 TEXT => [],
615 DISPLAY => [],
616 OLD => $o_ofs,
617 NEW => $n_ofs,
618 OCNT => 0,
619 NCNT => 0,
620 ADDDEL => 0,
621 POSTCTX => 0,
622 USE => undef,
625 while (++$i < @$text) {
626 my $line = $text->[$i];
627 my $display = $display->[$i];
628 if ($line =~ /^ /) {
629 if ($this->{ADDDEL} &&
630 !defined $next_hunk_start) {
631 # We have seen leading context and
632 # adds/dels and then here is another
633 # context, which is trailing for this
634 # split hunk and leading for the next
635 # one.
636 $next_hunk_start = $i;
638 push @{$this->{TEXT}}, $line;
639 push @{$this->{DISPLAY}}, $display;
640 $this->{OCNT}++;
641 $this->{NCNT}++;
642 if (defined $next_hunk_start) {
643 $this->{POSTCTX}++;
645 next;
648 # add/del
649 if (defined $next_hunk_start) {
650 # We are done with the current hunk and
651 # this is the first real change for the
652 # next split one.
653 $hunk_start = $next_hunk_start;
654 $o_ofs = $this->{OLD} + $this->{OCNT};
655 $n_ofs = $this->{NEW} + $this->{NCNT};
656 $o_ofs -= $this->{POSTCTX};
657 $n_ofs -= $this->{POSTCTX};
658 push @split, $this;
659 redo OUTER;
661 push @{$this->{TEXT}}, $line;
662 push @{$this->{DISPLAY}}, $display;
663 $this->{ADDDEL}++;
664 if ($line =~ /^-/) {
665 $this->{OCNT}++;
667 else {
668 $this->{NCNT}++;
672 push @split, $this;
673 last;
676 for my $hunk (@split) {
677 $o_ofs = $hunk->{OLD};
678 $n_ofs = $hunk->{NEW};
679 my $o_cnt = $hunk->{OCNT};
680 my $n_cnt = $hunk->{NCNT};
682 my $head = ("@@ -$o_ofs" .
683 (($o_cnt != 1) ? ",$o_cnt" : '') .
684 " +$n_ofs" .
685 (($n_cnt != 1) ? ",$n_cnt" : '') .
686 " @@\n");
687 my $display_head = $head;
688 unshift @{$hunk->{TEXT}}, $head;
689 if ($diff_use_color) {
690 $display_head = colored($fraginfo_color, $head);
692 unshift @{$hunk->{DISPLAY}}, $display_head;
694 return @split;
698 sub color_diff {
699 return map {
700 colored((/^@/ ? $fraginfo_color :
701 /^\+/ ? $diff_new_color :
702 /^-/ ? $diff_old_color :
703 $diff_plain_color),
704 $_);
705 } @_;
708 sub edit_hunk_manually {
709 my ($oldtext) = @_;
711 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
712 my $fh;
713 open $fh, '>', $hunkfile
714 or die "failed to open hunk edit file for writing: " . $!;
715 print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
716 print $fh @$oldtext;
717 print $fh <<EOF;
718 # ---
719 # To remove '-' lines, make them ' ' lines (context).
720 # To remove '+' lines, delete them.
721 # Lines starting with # will be removed.
723 # If the patch applies cleanly, the edited hunk will immediately be
724 # marked for staging. If it does not apply cleanly, you will be given
725 # an opportunity to edit again. If all lines of the hunk are removed,
726 # then the edit is aborted and the hunk is left unchanged.
728 close $fh;
730 my $editor = $ENV{GIT_EDITOR} || $repo->config("core.editor")
731 || $ENV{VISUAL} || $ENV{EDITOR} || "vi";
732 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
734 open $fh, '<', $hunkfile
735 or die "failed to open hunk edit file for reading: " . $!;
736 my @newtext = grep { !/^#/ } <$fh>;
737 close $fh;
738 unlink $hunkfile;
740 # Abort if nothing remains
741 if (!grep { /\S/ } @newtext) {
742 return undef;
745 # Reinsert the first hunk header if the user accidentally deleted it
746 if ($newtext[0] !~ /^@/) {
747 unshift @newtext, $oldtext->[0];
749 return \@newtext;
752 sub diff_applies {
753 my $fh;
754 open $fh, '| git apply --recount --cached --check';
755 for my $h (@_) {
756 print $fh @{$h->{TEXT}};
758 return close $fh;
761 sub prompt_yesno {
762 my ($prompt) = @_;
763 while (1) {
764 print colored $prompt_color, $prompt;
765 my $line = <STDIN>;
766 return 0 if $line =~ /^n/i;
767 return 1 if $line =~ /^y/i;
771 sub edit_hunk_loop {
772 my ($head, $hunk, $ix) = @_;
773 my $text = $hunk->[$ix]->{TEXT};
775 while (1) {
776 $text = edit_hunk_manually($text);
777 if (!defined $text) {
778 return undef;
780 my $newhunk = { TEXT => $text, USE => 1 };
781 if (diff_applies($head,
782 @{$hunk}[0..$ix-1],
783 $newhunk,
784 @{$hunk}[$ix+1..$#{$hunk}])) {
785 $newhunk->{DISPLAY} = [color_diff(@{$text})];
786 return $newhunk;
788 else {
789 prompt_yesno(
790 'Your edited hunk does not apply. Edit again '
791 . '(saying "no" discards!) [y/n]? '
792 ) or return undef;
797 sub help_patch_cmd {
798 print colored $help_color, <<\EOF ;
799 y - stage this hunk
800 n - do not stage this hunk
801 a - stage this and all the remaining hunks in the file
802 d - do not stage this hunk nor any of the remaining hunks in the file
803 g - select a hunk to go to
804 j - leave this hunk undecided, see next undecided hunk
805 J - leave this hunk undecided, see next hunk
806 k - leave this hunk undecided, see previous undecided hunk
807 K - leave this hunk undecided, see previous hunk
808 s - split the current hunk into smaller hunks
809 e - manually edit the current hunk
810 ? - print help
814 sub patch_update_cmd {
815 my @all_mods = list_modified('file-only');
816 my @mods = grep { !($_->{BINARY}) } @all_mods;
817 my @them;
819 if (!@mods) {
820 if (@all_mods) {
821 print STDERR "Only binary files changed.\n";
822 } else {
823 print STDERR "No changes.\n";
825 return 0;
827 if ($patch_mode) {
828 @them = @mods;
830 else {
831 @them = list_and_choose({ PROMPT => 'Patch update',
832 HEADER => $status_head, },
833 @mods);
835 for (@them) {
836 patch_update_file($_->{VALUE});
840 # Generate a one line summary of a hunk.
841 sub summarize_hunk {
842 my $rhunk = shift;
843 my $summary = $rhunk->{TEXT}[0];
845 # Keep the line numbers, discard extra context.
846 $summary =~ s/@@(.*?)@@.*/$1 /s;
847 $summary .= " " x (20 - length $summary);
849 # Add some user context.
850 for my $line (@{$rhunk->{TEXT}}) {
851 if ($line =~ m/^[+-].*\w/) {
852 $summary .= $line;
853 last;
857 chomp $summary;
858 return substr($summary, 0, 80) . "\n";
862 # Print a one-line summary of each hunk in the array ref in
863 # the first argument, starting wih the index in the 2nd.
864 sub display_hunks {
865 my ($hunks, $i) = @_;
866 my $ctr = 0;
867 $i ||= 0;
868 for (; $i < @$hunks && $ctr < 20; $i++, $ctr++) {
869 my $status = " ";
870 if (defined $hunks->[$i]{USE}) {
871 $status = $hunks->[$i]{USE} ? "+" : "-";
873 printf "%s%2d: %s",
874 $status,
875 $i + 1,
876 summarize_hunk($hunks->[$i]);
878 return $i;
881 sub patch_update_file {
882 my ($ix, $num);
883 my $path = shift;
884 my ($head, @hunk) = parse_diff($path);
885 ($head, my $mode) = parse_diff_header($head);
886 for (@{$head->{DISPLAY}}) {
887 print;
890 if (@{$mode->{TEXT}}) {
891 while (1) {
892 print @{$mode->{DISPLAY}};
893 print colored $prompt_color,
894 "Stage mode change [y/n/a/d/?]? ";
895 my $line = <STDIN>;
896 if ($line =~ /^y/i) {
897 $mode->{USE} = 1;
898 last;
900 elsif ($line =~ /^n/i) {
901 $mode->{USE} = 0;
902 last;
904 elsif ($line =~ /^a/i) {
905 $_->{USE} = 1 foreach ($mode, @hunk);
906 last;
908 elsif ($line =~ /^d/i) {
909 $_->{USE} = 0 foreach ($mode, @hunk);
910 last;
912 else {
913 help_patch_cmd('');
914 next;
919 $num = scalar @hunk;
920 $ix = 0;
922 while (1) {
923 my ($prev, $next, $other, $undecided, $i);
924 $other = '';
926 if ($num <= $ix) {
927 $ix = 0;
929 for ($i = 0; $i < $ix; $i++) {
930 if (!defined $hunk[$i]{USE}) {
931 $prev = 1;
932 $other .= '/k';
933 last;
936 if ($ix) {
937 $other .= '/K';
939 for ($i = $ix + 1; $i < $num; $i++) {
940 if (!defined $hunk[$i]{USE}) {
941 $next = 1;
942 $other .= '/j';
943 last;
946 if ($ix < $num - 1) {
947 $other .= '/J';
949 if ($num > 1) {
950 $other .= '/g';
952 for ($i = 0; $i < $num; $i++) {
953 if (!defined $hunk[$i]{USE}) {
954 $undecided = 1;
955 last;
958 last if (!$undecided);
960 if (hunk_splittable($hunk[$ix]{TEXT})) {
961 $other .= '/s';
963 $other .= '/e';
964 for (@{$hunk[$ix]{DISPLAY}}) {
965 print;
967 print colored $prompt_color, "Stage this hunk [y/n/a/d$other/?]? ";
968 my $line = <STDIN>;
969 if ($line) {
970 if ($line =~ /^y/i) {
971 $hunk[$ix]{USE} = 1;
973 elsif ($line =~ /^n/i) {
974 $hunk[$ix]{USE} = 0;
976 elsif ($line =~ /^a/i) {
977 while ($ix < $num) {
978 if (!defined $hunk[$ix]{USE}) {
979 $hunk[$ix]{USE} = 1;
981 $ix++;
983 next;
985 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
986 my $response = $1;
987 my $no = $ix > 10 ? $ix - 10 : 0;
988 while ($response eq '') {
989 my $extra = "";
990 $no = display_hunks(\@hunk, $no);
991 if ($no < $num) {
992 $extra = " (<ret> to see more)";
994 print "go to which hunk$extra? ";
995 $response = <STDIN>;
996 chomp $response;
998 if ($response !~ /^\s*\d+\s*$/) {
999 print STDERR "Invalid number: '$response'\n";
1000 } elsif (0 < $response && $response <= $num) {
1001 $ix = $response - 1;
1002 } else {
1003 print STDERR "Sorry, only $num hunks available.\n";
1005 next;
1007 elsif ($line =~ /^d/i) {
1008 while ($ix < $num) {
1009 if (!defined $hunk[$ix]{USE}) {
1010 $hunk[$ix]{USE} = 0;
1012 $ix++;
1014 next;
1016 elsif ($other =~ /K/ && $line =~ /^K/) {
1017 $ix--;
1018 next;
1020 elsif ($other =~ /J/ && $line =~ /^J/) {
1021 $ix++;
1022 next;
1024 elsif ($other =~ /k/ && $line =~ /^k/) {
1025 while (1) {
1026 $ix--;
1027 last if (!$ix ||
1028 !defined $hunk[$ix]{USE});
1030 next;
1032 elsif ($other =~ /j/ && $line =~ /^j/) {
1033 while (1) {
1034 $ix++;
1035 last if ($ix >= $num ||
1036 !defined $hunk[$ix]{USE});
1038 next;
1040 elsif ($other =~ /s/ && $line =~ /^s/) {
1041 my @split = split_hunk($hunk[$ix]{TEXT}, $hunk[$ix]{DISPLAY});
1042 if (1 < @split) {
1043 print colored $header_color, "Split into ",
1044 scalar(@split), " hunks.\n";
1046 splice (@hunk, $ix, 1, @split);
1047 $num = scalar @hunk;
1048 next;
1050 elsif ($line =~ /^e/) {
1051 my $newhunk = edit_hunk_loop($head, \@hunk, $ix);
1052 if (defined $newhunk) {
1053 splice @hunk, $ix, 1, $newhunk;
1056 else {
1057 help_patch_cmd($other);
1058 next;
1060 # soft increment
1061 while (1) {
1062 $ix++;
1063 last if ($ix >= $num ||
1064 !defined $hunk[$ix]{USE});
1069 my $n_lofs = 0;
1070 my @result = ();
1071 if ($mode->{USE}) {
1072 push @result, @{$mode->{TEXT}};
1074 for (@hunk) {
1075 if ($_->{USE}) {
1076 push @result, @{$_->{TEXT}};
1080 if (@result) {
1081 my $fh;
1083 open $fh, '| git apply --cached --recount';
1084 for (@{$head->{TEXT}}, @result) {
1085 print $fh $_;
1087 if (!close $fh) {
1088 for (@{$head->{TEXT}}, @result) {
1089 print STDERR $_;
1092 refresh();
1095 print "\n";
1098 sub diff_cmd {
1099 my @mods = list_modified('index-only');
1100 @mods = grep { !($_->{BINARY}) } @mods;
1101 return if (!@mods);
1102 my (@them) = list_and_choose({ PROMPT => 'Review diff',
1103 IMMEDIATE => 1,
1104 HEADER => $status_head, },
1105 @mods);
1106 return if (!@them);
1107 my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
1108 system(qw(git diff -p --cached), $reference, '--',
1109 map { $_->{VALUE} } @them);
1112 sub quit_cmd {
1113 print "Bye.\n";
1114 exit(0);
1117 sub help_cmd {
1118 print colored $help_color, <<\EOF ;
1119 status - show paths with changes
1120 update - add working tree state to the staged set of changes
1121 revert - revert staged set of changes back to the HEAD version
1122 patch - pick hunks and update selectively
1123 diff - view diff between HEAD and index
1124 add untracked - add contents of untracked files to the staged set of changes
1128 sub process_args {
1129 return unless @ARGV;
1130 my $arg = shift @ARGV;
1131 if ($arg eq "--patch") {
1132 $patch_mode = 1;
1133 $arg = shift @ARGV or die "missing --";
1134 die "invalid argument $arg, expecting --"
1135 unless $arg eq "--";
1137 elsif ($arg ne "--") {
1138 die "invalid argument $arg, expecting --";
1142 sub main_loop {
1143 my @cmd = ([ 'status', \&status_cmd, ],
1144 [ 'update', \&update_cmd, ],
1145 [ 'revert', \&revert_cmd, ],
1146 [ 'add untracked', \&add_untracked_cmd, ],
1147 [ 'patch', \&patch_update_cmd, ],
1148 [ 'diff', \&diff_cmd, ],
1149 [ 'quit', \&quit_cmd, ],
1150 [ 'help', \&help_cmd, ],
1152 while (1) {
1153 my ($it) = list_and_choose({ PROMPT => 'What now',
1154 SINGLETON => 1,
1155 LIST_FLAT => 4,
1156 HEADER => '*** Commands ***',
1157 ON_EOF => \&quit_cmd,
1158 IMMEDIATE => 1 }, @cmd);
1159 if ($it) {
1160 eval {
1161 $it->[1]->();
1163 if ($@) {
1164 print "$@";
1170 process_args();
1171 refresh();
1172 if ($patch_mode) {
1173 patch_update_cmd();
1175 else {
1176 status_cmd();
1177 main_loop();