Code

1813f9e8e388397fa314717c2170861c1dc5e6a0
[git.git] / git-add--interactive.perl
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 my $use_readkey = 0;
37 if ($repo->config_bool("interactive.singlekey")) {
38         eval {
39                 use Term::ReadKey;
40                 $use_readkey = 1;
41         };
42 }
44 sub colored {
45         my $color = shift;
46         my $string = join("", @_);
48         if (defined $color) {
49                 # Put a color code at the beginning of each line, a reset at the end
50                 # color after newlines that are not at the end of the string
51                 $string =~ s/(\n+)(.)/$1$color$2/g;
52                 # reset before newlines
53                 $string =~ s/(\n+)/$normal_color$1/g;
54                 # codes at beginning and end (if necessary):
55                 $string =~ s/^/$color/;
56                 $string =~ s/$/$normal_color/ unless $string =~ /\n$/;
57         }
58         return $string;
59 }
61 # command line options
62 my $patch_mode;
64 sub run_cmd_pipe {
65         if ($^O eq 'MSWin32' || $^O eq 'msys') {
66                 my @invalid = grep {m/[":*]/} @_;
67                 die "$^O does not support: @invalid\n" if @invalid;
68                 my @args = map { m/ /o ? "\"$_\"": $_ } @_;
69                 return qx{@args};
70         } else {
71                 my $fh = undef;
72                 open($fh, '-|', @_) or die;
73                 return <$fh>;
74         }
75 }
77 my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));
79 if (!defined $GIT_DIR) {
80         exit(1); # rev-parse would have already said "not a git repo"
81 }
82 chomp($GIT_DIR);
84 sub refresh {
85         my $fh;
86         open $fh, 'git update-index --refresh |'
87             or die;
88         while (<$fh>) {
89                 ;# ignore 'needs update'
90         }
91         close $fh;
92 }
94 sub list_untracked {
95         map {
96                 chomp $_;
97                 $_;
98         }
99         run_cmd_pipe(qw(git ls-files --others --exclude-standard --), @ARGV);
102 my $status_fmt = '%12s %12s %s';
103 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
106         my $initial;
107         sub is_initial_commit {
108                 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
109                         unless defined $initial;
110                 return $initial;
111         }
114 sub get_empty_tree {
115         return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
118 # Returns list of hashes, contents of each of which are:
119 # VALUE:        pathname
120 # BINARY:       is a binary path
121 # INDEX:        is index different from HEAD?
122 # FILE:         is file different from index?
123 # INDEX_ADDDEL: is it add/delete between HEAD and index?
124 # FILE_ADDDEL:  is it add/delete between index and file?
126 sub list_modified {
127         my ($only) = @_;
128         my (%data, @return);
129         my ($add, $del, $adddel, $file);
130         my @tracked = ();
132         if (@ARGV) {
133                 @tracked = map {
134                         chomp $_; $_;
135                 } run_cmd_pipe(qw(git ls-files --exclude-standard --), @ARGV);
136                 return if (!@tracked);
137         }
139         my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
140         for (run_cmd_pipe(qw(git diff-index --cached
141                              --numstat --summary), $reference,
142                              '--', @tracked)) {
143                 if (($add, $del, $file) =
144                     /^([-\d]+)  ([-\d]+)        (.*)/) {
145                         my ($change, $bin);
146                         if ($add eq '-' && $del eq '-') {
147                                 $change = 'binary';
148                                 $bin = 1;
149                         }
150                         else {
151                                 $change = "+$add/-$del";
152                         }
153                         $data{$file} = {
154                                 INDEX => $change,
155                                 BINARY => $bin,
156                                 FILE => 'nothing',
157                         }
158                 }
159                 elsif (($adddel, $file) =
160                        /^ (create|delete) mode [0-7]+ (.*)$/) {
161                         $data{$file}{INDEX_ADDDEL} = $adddel;
162                 }
163         }
165         for (run_cmd_pipe(qw(git diff-files --numstat --summary --), @tracked)) {
166                 if (($add, $del, $file) =
167                     /^([-\d]+)  ([-\d]+)        (.*)/) {
168                         if (!exists $data{$file}) {
169                                 $data{$file} = +{
170                                         INDEX => 'unchanged',
171                                         BINARY => 0,
172                                 };
173                         }
174                         my ($change, $bin);
175                         if ($add eq '-' && $del eq '-') {
176                                 $change = 'binary';
177                                 $bin = 1;
178                         }
179                         else {
180                                 $change = "+$add/-$del";
181                         }
182                         $data{$file}{FILE} = $change;
183                         if ($bin) {
184                                 $data{$file}{BINARY} = 1;
185                         }
186                 }
187                 elsif (($adddel, $file) =
188                        /^ (create|delete) mode [0-7]+ (.*)$/) {
189                         $data{$file}{FILE_ADDDEL} = $adddel;
190                 }
191         }
193         for (sort keys %data) {
194                 my $it = $data{$_};
196                 if ($only) {
197                         if ($only eq 'index-only') {
198                                 next if ($it->{INDEX} eq 'unchanged');
199                         }
200                         if ($only eq 'file-only') {
201                                 next if ($it->{FILE} eq 'nothing');
202                         }
203                 }
204                 push @return, +{
205                         VALUE => $_,
206                         %$it,
207                 };
208         }
209         return @return;
212 sub find_unique {
213         my ($string, @stuff) = @_;
214         my $found = undef;
215         for (my $i = 0; $i < @stuff; $i++) {
216                 my $it = $stuff[$i];
217                 my $hit = undef;
218                 if (ref $it) {
219                         if ((ref $it) eq 'ARRAY') {
220                                 $it = $it->[0];
221                         }
222                         else {
223                                 $it = $it->{VALUE};
224                         }
225                 }
226                 eval {
227                         if ($it =~ /^$string/) {
228                                 $hit = 1;
229                         };
230                 };
231                 if (defined $hit && defined $found) {
232                         return undef;
233                 }
234                 if ($hit) {
235                         $found = $i + 1;
236                 }
237         }
238         return $found;
241 # inserts string into trie and updates count for each character
242 sub update_trie {
243         my ($trie, $string) = @_;
244         foreach (split //, $string) {
245                 $trie = $trie->{$_} ||= {COUNT => 0};
246                 $trie->{COUNT}++;
247         }
250 # returns an array of tuples (prefix, remainder)
251 sub find_unique_prefixes {
252         my @stuff = @_;
253         my @return = ();
255         # any single prefix exceeding the soft limit is omitted
256         # if any prefix exceeds the hard limit all are omitted
257         # 0 indicates no limit
258         my $soft_limit = 0;
259         my $hard_limit = 3;
261         # build a trie modelling all possible options
262         my %trie;
263         foreach my $print (@stuff) {
264                 if ((ref $print) eq 'ARRAY') {
265                         $print = $print->[0];
266                 }
267                 elsif ((ref $print) eq 'HASH') {
268                         $print = $print->{VALUE};
269                 }
270                 update_trie(\%trie, $print);
271                 push @return, $print;
272         }
274         # use the trie to find the unique prefixes
275         for (my $i = 0; $i < @return; $i++) {
276                 my $ret = $return[$i];
277                 my @letters = split //, $ret;
278                 my %search = %trie;
279                 my ($prefix, $remainder);
280                 my $j;
281                 for ($j = 0; $j < @letters; $j++) {
282                         my $letter = $letters[$j];
283                         if ($search{$letter}{COUNT} == 1) {
284                                 $prefix = substr $ret, 0, $j + 1;
285                                 $remainder = substr $ret, $j + 1;
286                                 last;
287                         }
288                         else {
289                                 my $prefix = substr $ret, 0, $j;
290                                 return ()
291                                     if ($hard_limit && $j + 1 > $hard_limit);
292                         }
293                         %search = %{$search{$letter}};
294                 }
295                 if ($soft_limit && $j + 1 > $soft_limit) {
296                         $prefix = undef;
297                         $remainder = $ret;
298                 }
299                 $return[$i] = [$prefix, $remainder];
300         }
301         return @return;
304 # filters out prefixes which have special meaning to list_and_choose()
305 sub is_valid_prefix {
306         my $prefix = shift;
307         return (defined $prefix) &&
308             !($prefix =~ /[\s,]/) && # separators
309             !($prefix =~ /^-/) &&    # deselection
310             !($prefix =~ /^\d+/) &&  # selection
311             ($prefix ne '*') &&      # "all" wildcard
312             ($prefix ne '?');        # prompt help
315 # given a prefix/remainder tuple return a string with the prefix highlighted
316 # for now use square brackets; later might use ANSI colors (underline, bold)
317 sub highlight_prefix {
318         my $prefix = shift;
319         my $remainder = shift;
321         if (!defined $prefix) {
322                 return $remainder;
323         }
325         if (!is_valid_prefix($prefix)) {
326                 return "$prefix$remainder";
327         }
329         if (!$menu_use_color) {
330                 return "[$prefix]$remainder";
331         }
333         return "$prompt_color$prefix$normal_color$remainder";
336 sub list_and_choose {
337         my ($opts, @stuff) = @_;
338         my (@chosen, @return);
339         my $i;
340         my @prefixes = find_unique_prefixes(@stuff) unless $opts->{LIST_ONLY};
342       TOPLOOP:
343         while (1) {
344                 my $last_lf = 0;
346                 if ($opts->{HEADER}) {
347                         if (!$opts->{LIST_FLAT}) {
348                                 print "     ";
349                         }
350                         print colored $header_color, "$opts->{HEADER}\n";
351                 }
352                 for ($i = 0; $i < @stuff; $i++) {
353                         my $chosen = $chosen[$i] ? '*' : ' ';
354                         my $print = $stuff[$i];
355                         my $ref = ref $print;
356                         my $highlighted = highlight_prefix(@{$prefixes[$i]})
357                             if @prefixes;
358                         if ($ref eq 'ARRAY') {
359                                 $print = $highlighted || $print->[0];
360                         }
361                         elsif ($ref eq 'HASH') {
362                                 my $value = $highlighted || $print->{VALUE};
363                                 $print = sprintf($status_fmt,
364                                     $print->{INDEX},
365                                     $print->{FILE},
366                                     $value);
367                         }
368                         else {
369                                 $print = $highlighted || $print;
370                         }
371                         printf("%s%2d: %s", $chosen, $i+1, $print);
372                         if (($opts->{LIST_FLAT}) &&
373                             (($i + 1) % ($opts->{LIST_FLAT}))) {
374                                 print "\t";
375                                 $last_lf = 0;
376                         }
377                         else {
378                                 print "\n";
379                                 $last_lf = 1;
380                         }
381                 }
382                 if (!$last_lf) {
383                         print "\n";
384                 }
386                 return if ($opts->{LIST_ONLY});
388                 print colored $prompt_color, $opts->{PROMPT};
389                 if ($opts->{SINGLETON}) {
390                         print "> ";
391                 }
392                 else {
393                         print ">> ";
394                 }
395                 my $line = <STDIN>;
396                 if (!$line) {
397                         print "\n";
398                         $opts->{ON_EOF}->() if $opts->{ON_EOF};
399                         last;
400                 }
401                 chomp $line;
402                 last if $line eq '';
403                 if ($line eq '?') {
404                         $opts->{SINGLETON} ?
405                             singleton_prompt_help_cmd() :
406                             prompt_help_cmd();
407                         next TOPLOOP;
408                 }
409                 for my $choice (split(/[\s,]+/, $line)) {
410                         my $choose = 1;
411                         my ($bottom, $top);
413                         # Input that begins with '-'; unchoose
414                         if ($choice =~ s/^-//) {
415                                 $choose = 0;
416                         }
417                         # A range can be specified like 5-7 or 5-.
418                         if ($choice =~ /^(\d+)-(\d*)$/) {
419                                 ($bottom, $top) = ($1, length($2) ? $2 : 1 + @stuff);
420                         }
421                         elsif ($choice =~ /^\d+$/) {
422                                 $bottom = $top = $choice;
423                         }
424                         elsif ($choice eq '*') {
425                                 $bottom = 1;
426                                 $top = 1 + @stuff;
427                         }
428                         else {
429                                 $bottom = $top = find_unique($choice, @stuff);
430                                 if (!defined $bottom) {
431                                         print "Huh ($choice)?\n";
432                                         next TOPLOOP;
433                                 }
434                         }
435                         if ($opts->{SINGLETON} && $bottom != $top) {
436                                 print "Huh ($choice)?\n";
437                                 next TOPLOOP;
438                         }
439                         for ($i = $bottom-1; $i <= $top-1; $i++) {
440                                 next if (@stuff <= $i || $i < 0);
441                                 $chosen[$i] = $choose;
442                         }
443                 }
444                 last if ($opts->{IMMEDIATE} || $line eq '*');
445         }
446         for ($i = 0; $i < @stuff; $i++) {
447                 if ($chosen[$i]) {
448                         push @return, $stuff[$i];
449                 }
450         }
451         return @return;
454 sub singleton_prompt_help_cmd {
455         print colored $help_color, <<\EOF ;
456 Prompt help:
457 1          - select a numbered item
458 foo        - select item based on unique prefix
459            - (empty) select nothing
460 EOF
463 sub prompt_help_cmd {
464         print colored $help_color, <<\EOF ;
465 Prompt help:
466 1          - select a single item
467 3-5        - select a range of items
468 2-3,6-9    - select multiple ranges
469 foo        - select item based on unique prefix
470 -...       - unselect specified items
471 *          - choose all items
472            - (empty) finish selecting
473 EOF
476 sub status_cmd {
477         list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
478                         list_modified());
479         print "\n";
482 sub say_n_paths {
483         my $did = shift @_;
484         my $cnt = scalar @_;
485         print "$did ";
486         if (1 < $cnt) {
487                 print "$cnt paths\n";
488         }
489         else {
490                 print "one path\n";
491         }
494 sub update_cmd {
495         my @mods = list_modified('file-only');
496         return if (!@mods);
498         my @update = list_and_choose({ PROMPT => 'Update',
499                                        HEADER => $status_head, },
500                                      @mods);
501         if (@update) {
502                 system(qw(git update-index --add --remove --),
503                        map { $_->{VALUE} } @update);
504                 say_n_paths('updated', @update);
505         }
506         print "\n";
509 sub revert_cmd {
510         my @update = list_and_choose({ PROMPT => 'Revert',
511                                        HEADER => $status_head, },
512                                      list_modified());
513         if (@update) {
514                 if (is_initial_commit()) {
515                         system(qw(git rm --cached),
516                                 map { $_->{VALUE} } @update);
517                 }
518                 else {
519                         my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
520                                                  map { $_->{VALUE} } @update);
521                         my $fh;
522                         open $fh, '| git update-index --index-info'
523                             or die;
524                         for (@lines) {
525                                 print $fh $_;
526                         }
527                         close($fh);
528                         for (@update) {
529                                 if ($_->{INDEX_ADDDEL} &&
530                                     $_->{INDEX_ADDDEL} eq 'create') {
531                                         system(qw(git update-index --force-remove --),
532                                                $_->{VALUE});
533                                         print "note: $_->{VALUE} is untracked now.\n";
534                                 }
535                         }
536                 }
537                 refresh();
538                 say_n_paths('reverted', @update);
539         }
540         print "\n";
543 sub add_untracked_cmd {
544         my @add = list_and_choose({ PROMPT => 'Add untracked' },
545                                   list_untracked());
546         if (@add) {
547                 system(qw(git update-index --add --), @add);
548                 say_n_paths('added', @add);
549         }
550         print "\n";
553 sub parse_diff {
554         my ($path) = @_;
555         my @diff = run_cmd_pipe(qw(git diff-files -p --), $path);
556         my @colored = ();
557         if ($diff_use_color) {
558                 @colored = run_cmd_pipe(qw(git diff-files -p --color --), $path);
559         }
560         my (@hunk) = { TEXT => [], DISPLAY => [] };
562         for (my $i = 0; $i < @diff; $i++) {
563                 if ($diff[$i] =~ /^@@ /) {
564                         push @hunk, { TEXT => [], DISPLAY => [] };
565                 }
566                 push @{$hunk[-1]{TEXT}}, $diff[$i];
567                 push @{$hunk[-1]{DISPLAY}},
568                         ($diff_use_color ? $colored[$i] : $diff[$i]);
569         }
570         return @hunk;
573 sub parse_diff_header {
574         my $src = shift;
576         my $head = { TEXT => [], DISPLAY => [] };
577         my $mode = { TEXT => [], DISPLAY => [] };
579         for (my $i = 0; $i < @{$src->{TEXT}}; $i++) {
580                 my $dest = $src->{TEXT}->[$i] =~ /^(old|new) mode (\d+)$/ ?
581                         $mode : $head;
582                 push @{$dest->{TEXT}}, $src->{TEXT}->[$i];
583                 push @{$dest->{DISPLAY}}, $src->{DISPLAY}->[$i];
584         }
585         return ($head, $mode);
588 sub hunk_splittable {
589         my ($text) = @_;
591         my @s = split_hunk($text);
592         return (1 < @s);
595 sub parse_hunk_header {
596         my ($line) = @_;
597         my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
598             $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
599         $o_cnt = 1 unless defined $o_cnt;
600         $n_cnt = 1 unless defined $n_cnt;
601         return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
604 sub split_hunk {
605         my ($text, $display) = @_;
606         my @split = ();
607         if (!defined $display) {
608                 $display = $text;
609         }
610         # If there are context lines in the middle of a hunk,
611         # it can be split, but we would need to take care of
612         # overlaps later.
614         my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
615         my $hunk_start = 1;
617       OUTER:
618         while (1) {
619                 my $next_hunk_start = undef;
620                 my $i = $hunk_start - 1;
621                 my $this = +{
622                         TEXT => [],
623                         DISPLAY => [],
624                         OLD => $o_ofs,
625                         NEW => $n_ofs,
626                         OCNT => 0,
627                         NCNT => 0,
628                         ADDDEL => 0,
629                         POSTCTX => 0,
630                         USE => undef,
631                 };
633                 while (++$i < @$text) {
634                         my $line = $text->[$i];
635                         my $display = $display->[$i];
636                         if ($line =~ /^ /) {
637                                 if ($this->{ADDDEL} &&
638                                     !defined $next_hunk_start) {
639                                         # We have seen leading context and
640                                         # adds/dels and then here is another
641                                         # context, which is trailing for this
642                                         # split hunk and leading for the next
643                                         # one.
644                                         $next_hunk_start = $i;
645                                 }
646                                 push @{$this->{TEXT}}, $line;
647                                 push @{$this->{DISPLAY}}, $display;
648                                 $this->{OCNT}++;
649                                 $this->{NCNT}++;
650                                 if (defined $next_hunk_start) {
651                                         $this->{POSTCTX}++;
652                                 }
653                                 next;
654                         }
656                         # add/del
657                         if (defined $next_hunk_start) {
658                                 # We are done with the current hunk and
659                                 # this is the first real change for the
660                                 # next split one.
661                                 $hunk_start = $next_hunk_start;
662                                 $o_ofs = $this->{OLD} + $this->{OCNT};
663                                 $n_ofs = $this->{NEW} + $this->{NCNT};
664                                 $o_ofs -= $this->{POSTCTX};
665                                 $n_ofs -= $this->{POSTCTX};
666                                 push @split, $this;
667                                 redo OUTER;
668                         }
669                         push @{$this->{TEXT}}, $line;
670                         push @{$this->{DISPLAY}}, $display;
671                         $this->{ADDDEL}++;
672                         if ($line =~ /^-/) {
673                                 $this->{OCNT}++;
674                         }
675                         else {
676                                 $this->{NCNT}++;
677                         }
678                 }
680                 push @split, $this;
681                 last;
682         }
684         for my $hunk (@split) {
685                 $o_ofs = $hunk->{OLD};
686                 $n_ofs = $hunk->{NEW};
687                 my $o_cnt = $hunk->{OCNT};
688                 my $n_cnt = $hunk->{NCNT};
690                 my $head = ("@@ -$o_ofs" .
691                             (($o_cnt != 1) ? ",$o_cnt" : '') .
692                             " +$n_ofs" .
693                             (($n_cnt != 1) ? ",$n_cnt" : '') .
694                             " @@\n");
695                 my $display_head = $head;
696                 unshift @{$hunk->{TEXT}}, $head;
697                 if ($diff_use_color) {
698                         $display_head = colored($fraginfo_color, $head);
699                 }
700                 unshift @{$hunk->{DISPLAY}}, $display_head;
701         }
702         return @split;
706 sub color_diff {
707         return map {
708                 colored((/^@/  ? $fraginfo_color :
709                          /^\+/ ? $diff_new_color :
710                          /^-/  ? $diff_old_color :
711                          $diff_plain_color),
712                         $_);
713         } @_;
716 sub edit_hunk_manually {
717         my ($oldtext) = @_;
719         my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
720         my $fh;
721         open $fh, '>', $hunkfile
722                 or die "failed to open hunk edit file for writing: " . $!;
723         print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
724         print $fh @$oldtext;
725         print $fh <<EOF;
726 # ---
727 # To remove '-' lines, make them ' ' lines (context).
728 # To remove '+' lines, delete them.
729 # Lines starting with # will be removed.
731 # If the patch applies cleanly, the edited hunk will immediately be
732 # marked for staging. If it does not apply cleanly, you will be given
733 # an opportunity to edit again. If all lines of the hunk are removed,
734 # then the edit is aborted and the hunk is left unchanged.
735 EOF
736         close $fh;
738         my $editor = $ENV{GIT_EDITOR} || $repo->config("core.editor")
739                 || $ENV{VISUAL} || $ENV{EDITOR} || "vi";
740         system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
742         open $fh, '<', $hunkfile
743                 or die "failed to open hunk edit file for reading: " . $!;
744         my @newtext = grep { !/^#/ } <$fh>;
745         close $fh;
746         unlink $hunkfile;
748         # Abort if nothing remains
749         if (!grep { /\S/ } @newtext) {
750                 return undef;
751         }
753         # Reinsert the first hunk header if the user accidentally deleted it
754         if ($newtext[0] !~ /^@/) {
755                 unshift @newtext, $oldtext->[0];
756         }
757         return \@newtext;
760 sub diff_applies {
761         my $fh;
762         open $fh, '| git apply --recount --cached --check';
763         for my $h (@_) {
764                 print $fh @{$h->{TEXT}};
765         }
766         return close $fh;
769 sub _restore_terminal_and_die {
770         ReadMode 'restore';
771         print "\n";
772         exit 1;
775 sub prompt_single_character {
776         if ($use_readkey) {
777                 local $SIG{TERM} = \&_restore_terminal_and_die;
778                 local $SIG{INT} = \&_restore_terminal_and_die;
779                 ReadMode 'cbreak';
780                 my $key = ReadKey 0;
781                 ReadMode 'restore';
782                 print "$key" if defined $key;
783                 print "\n";
784                 return $key;
785         } else {
786                 return <STDIN>;
787         }
790 sub prompt_yesno {
791         my ($prompt) = @_;
792         while (1) {
793                 print colored $prompt_color, $prompt;
794                 my $line = prompt_single_character;
795                 return 0 if $line =~ /^n/i;
796                 return 1 if $line =~ /^y/i;
797         }
800 sub edit_hunk_loop {
801         my ($head, $hunk, $ix) = @_;
802         my $text = $hunk->[$ix]->{TEXT};
804         while (1) {
805                 $text = edit_hunk_manually($text);
806                 if (!defined $text) {
807                         return undef;
808                 }
809                 my $newhunk = { TEXT => $text, USE => 1 };
810                 if (diff_applies($head,
811                                  @{$hunk}[0..$ix-1],
812                                  $newhunk,
813                                  @{$hunk}[$ix+1..$#{$hunk}])) {
814                         $newhunk->{DISPLAY} = [color_diff(@{$text})];
815                         return $newhunk;
816                 }
817                 else {
818                         prompt_yesno(
819                                 'Your edited hunk does not apply. Edit again '
820                                 . '(saying "no" discards!) [y/n]? '
821                                 ) or return undef;
822                 }
823         }
826 sub help_patch_cmd {
827         print colored $help_color, <<\EOF ;
828 y - stage this hunk
829 n - do not stage this hunk
830 a - stage this and all the remaining hunks in the file
831 d - do not stage this hunk nor any of the remaining hunks in the file
832 g - select a hunk to go to
833 / - search for a hunk matching the given regex
834 j - leave this hunk undecided, see next undecided hunk
835 J - leave this hunk undecided, see next hunk
836 k - leave this hunk undecided, see previous undecided hunk
837 K - leave this hunk undecided, see previous hunk
838 s - split the current hunk into smaller hunks
839 e - manually edit the current hunk
840 ? - print help
841 EOF
844 sub patch_update_cmd {
845         my @all_mods = list_modified('file-only');
846         my @mods = grep { !($_->{BINARY}) } @all_mods;
847         my @them;
849         if (!@mods) {
850                 if (@all_mods) {
851                         print STDERR "Only binary files changed.\n";
852                 } else {
853                         print STDERR "No changes.\n";
854                 }
855                 return 0;
856         }
857         if ($patch_mode) {
858                 @them = @mods;
859         }
860         else {
861                 @them = list_and_choose({ PROMPT => 'Patch update',
862                                           HEADER => $status_head, },
863                                         @mods);
864         }
865         for (@them) {
866                 patch_update_file($_->{VALUE});
867         }
870 # Generate a one line summary of a hunk.
871 sub summarize_hunk {
872         my $rhunk = shift;
873         my $summary = $rhunk->{TEXT}[0];
875         # Keep the line numbers, discard extra context.
876         $summary =~ s/@@(.*?)@@.*/$1 /s;
877         $summary .= " " x (20 - length $summary);
879         # Add some user context.
880         for my $line (@{$rhunk->{TEXT}}) {
881                 if ($line =~ m/^[+-].*\w/) {
882                         $summary .= $line;
883                         last;
884                 }
885         }
887         chomp $summary;
888         return substr($summary, 0, 80) . "\n";
892 # Print a one-line summary of each hunk in the array ref in
893 # the first argument, starting wih the index in the 2nd.
894 sub display_hunks {
895         my ($hunks, $i) = @_;
896         my $ctr = 0;
897         $i ||= 0;
898         for (; $i < @$hunks && $ctr < 20; $i++, $ctr++) {
899                 my $status = " ";
900                 if (defined $hunks->[$i]{USE}) {
901                         $status = $hunks->[$i]{USE} ? "+" : "-";
902                 }
903                 printf "%s%2d: %s",
904                         $status,
905                         $i + 1,
906                         summarize_hunk($hunks->[$i]);
907         }
908         return $i;
911 sub patch_update_file {
912         my ($ix, $num);
913         my $path = shift;
914         my ($head, @hunk) = parse_diff($path);
915         ($head, my $mode) = parse_diff_header($head);
916         for (@{$head->{DISPLAY}}) {
917                 print;
918         }
920         if (@{$mode->{TEXT}}) {
921                 while (1) {
922                         print @{$mode->{DISPLAY}};
923                         print colored $prompt_color,
924                                 "Stage mode change [y/n/a/d/?]? ";
925                         my $line = prompt_single_character;
926                         if ($line =~ /^y/i) {
927                                 $mode->{USE} = 1;
928                                 last;
929                         }
930                         elsif ($line =~ /^n/i) {
931                                 $mode->{USE} = 0;
932                                 last;
933                         }
934                         elsif ($line =~ /^a/i) {
935                                 $_->{USE} = 1 foreach ($mode, @hunk);
936                                 last;
937                         }
938                         elsif ($line =~ /^d/i) {
939                                 $_->{USE} = 0 foreach ($mode, @hunk);
940                                 last;
941                         }
942                         else {
943                                 help_patch_cmd('');
944                                 next;
945                         }
946                 }
947         }
949         $num = scalar @hunk;
950         $ix = 0;
952         while (1) {
953                 my ($prev, $next, $other, $undecided, $i);
954                 $other = '';
956                 if ($num <= $ix) {
957                         $ix = 0;
958                 }
959                 for ($i = 0; $i < $ix; $i++) {
960                         if (!defined $hunk[$i]{USE}) {
961                                 $prev = 1;
962                                 $other .= ',k';
963                                 last;
964                         }
965                 }
966                 if ($ix) {
967                         $other .= ',K';
968                 }
969                 for ($i = $ix + 1; $i < $num; $i++) {
970                         if (!defined $hunk[$i]{USE}) {
971                                 $next = 1;
972                                 $other .= ',j';
973                                 last;
974                         }
975                 }
976                 if ($ix < $num - 1) {
977                         $other .= ',J';
978                 }
979                 if ($num > 1) {
980                         $other .= ',g';
981                 }
982                 for ($i = 0; $i < $num; $i++) {
983                         if (!defined $hunk[$i]{USE}) {
984                                 $undecided = 1;
985                                 last;
986                         }
987                 }
988                 last if (!$undecided);
990                 if (hunk_splittable($hunk[$ix]{TEXT})) {
991                         $other .= ',s';
992                 }
993                 $other .= ',e';
994                 for (@{$hunk[$ix]{DISPLAY}}) {
995                         print;
996                 }
997                 print colored $prompt_color, "Stage this hunk [y,n,a,d,/$other,?]? ";
998                 my $line = prompt_single_character;
999                 if ($line) {
1000                         if ($line =~ /^y/i) {
1001                                 $hunk[$ix]{USE} = 1;
1002                         }
1003                         elsif ($line =~ /^n/i) {
1004                                 $hunk[$ix]{USE} = 0;
1005                         }
1006                         elsif ($line =~ /^a/i) {
1007                                 while ($ix < $num) {
1008                                         if (!defined $hunk[$ix]{USE}) {
1009                                                 $hunk[$ix]{USE} = 1;
1010                                         }
1011                                         $ix++;
1012                                 }
1013                                 next;
1014                         }
1015                         elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1016                                 my $response = $1;
1017                                 my $no = $ix > 10 ? $ix - 10 : 0;
1018                                 while ($response eq '') {
1019                                         my $extra = "";
1020                                         $no = display_hunks(\@hunk, $no);
1021                                         if ($no < $num) {
1022                                                 $extra = " (<ret> to see more)";
1023                                         }
1024                                         print "go to which hunk$extra? ";
1025                                         $response = <STDIN>;
1026                                         if (!defined $response) {
1027                                                 $response = '';
1028                                         }
1029                                         chomp $response;
1030                                 }
1031                                 if ($response !~ /^\s*\d+\s*$/) {
1032                                         print STDERR "Invalid number: '$response'\n";
1033                                 } elsif (0 < $response && $response <= $num) {
1034                                         $ix = $response - 1;
1035                                 } else {
1036                                         print STDERR "Sorry, only $num hunks available.\n";
1037                                 }
1038                                 next;
1039                         }
1040                         elsif ($line =~ /^d/i) {
1041                                 while ($ix < $num) {
1042                                         if (!defined $hunk[$ix]{USE}) {
1043                                                 $hunk[$ix]{USE} = 0;
1044                                         }
1045                                         $ix++;
1046                                 }
1047                                 next;
1048                         }
1049                         elsif ($line =~ m|^/(.*)|) {
1050                                 my $regex = $1;
1051                                 if ($1 eq "") {
1052                                         print colored $prompt_color, "search for regex? ";
1053                                         $regex = <STDIN>;
1054                                         if (defined $regex) {
1055                                                 chomp $regex;
1056                                         }
1057                                 }
1058                                 my $search_string;
1059                                 eval {
1060                                         $search_string = qr{$regex}m;
1061                                 };
1062                                 if ($@) {
1063                                         my ($err,$exp) = ($@, $1);
1064                                         $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1065                                         print STDERR "Malformed search regexp $exp: $err\n";
1066                                         next;
1067                                 }
1068                                 my $iy = $ix;
1069                                 while (1) {
1070                                         my $text = join ("", @{$hunk[$iy]{TEXT}});
1071                                         last if ($text =~ $search_string);
1072                                         $iy++;
1073                                         $iy = 0 if ($iy >= $num);
1074                                         if ($ix == $iy) {
1075                                                 print STDERR "No hunk matches the given pattern\n";
1076                                                 last;
1077                                         }
1078                                 }
1079                                 $ix = $iy;
1080                                 next;
1081                         }
1082                         elsif ($line =~ /^K/) {
1083                                 if ($other =~ /K/) {
1084                                         $ix--;
1085                                 }
1086                                 else {
1087                                         print STDERR "No previous hunk\n";
1088                                 }
1089                                 next;
1090                         }
1091                         elsif ($line =~ /^J/) {
1092                                 if ($other =~ /J/) {
1093                                         $ix++;
1094                                 }
1095                                 else {
1096                                         print STDERR "No next hunk\n";
1097                                 }
1098                                 next;
1099                         }
1100                         elsif ($line =~ /^k/) {
1101                                 if ($other =~ /k/) {
1102                                         while (1) {
1103                                                 $ix--;
1104                                                 last if (!$ix ||
1105                                                          !defined $hunk[$ix]{USE});
1106                                         }
1107                                 }
1108                                 else {
1109                                         print STDERR "No previous hunk\n";
1110                                 }
1111                                 next;
1112                         }
1113                         elsif ($line =~ /^j/) {
1114                                 if ($other !~ /j/) {
1115                                         print STDERR "No next hunk\n";
1116                                         next;
1117                                 }
1118                         }
1119                         elsif ($other =~ /s/ && $line =~ /^s/) {
1120                                 my @split = split_hunk($hunk[$ix]{TEXT}, $hunk[$ix]{DISPLAY});
1121                                 if (1 < @split) {
1122                                         print colored $header_color, "Split into ",
1123                                         scalar(@split), " hunks.\n";
1124                                 }
1125                                 splice (@hunk, $ix, 1, @split);
1126                                 $num = scalar @hunk;
1127                                 next;
1128                         }
1129                         elsif ($line =~ /^e/) {
1130                                 my $newhunk = edit_hunk_loop($head, \@hunk, $ix);
1131                                 if (defined $newhunk) {
1132                                         splice @hunk, $ix, 1, $newhunk;
1133                                 }
1134                         }
1135                         else {
1136                                 help_patch_cmd($other);
1137                                 next;
1138                         }
1139                         # soft increment
1140                         while (1) {
1141                                 $ix++;
1142                                 last if ($ix >= $num ||
1143                                          !defined $hunk[$ix]{USE});
1144                         }
1145                 }
1146         }
1148         my $n_lofs = 0;
1149         my @result = ();
1150         if ($mode->{USE}) {
1151                 push @result, @{$mode->{TEXT}};
1152         }
1153         for (@hunk) {
1154                 if ($_->{USE}) {
1155                         push @result, @{$_->{TEXT}};
1156                 }
1157         }
1159         if (@result) {
1160                 my $fh;
1162                 open $fh, '| git apply --cached --recount';
1163                 for (@{$head->{TEXT}}, @result) {
1164                         print $fh $_;
1165                 }
1166                 if (!close $fh) {
1167                         for (@{$head->{TEXT}}, @result) {
1168                                 print STDERR $_;
1169                         }
1170                 }
1171                 refresh();
1172         }
1174         print "\n";
1177 sub diff_cmd {
1178         my @mods = list_modified('index-only');
1179         @mods = grep { !($_->{BINARY}) } @mods;
1180         return if (!@mods);
1181         my (@them) = list_and_choose({ PROMPT => 'Review diff',
1182                                      IMMEDIATE => 1,
1183                                      HEADER => $status_head, },
1184                                    @mods);
1185         return if (!@them);
1186         my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
1187         system(qw(git diff -p --cached), $reference, '--',
1188                 map { $_->{VALUE} } @them);
1191 sub quit_cmd {
1192         print "Bye.\n";
1193         exit(0);
1196 sub help_cmd {
1197         print colored $help_color, <<\EOF ;
1198 status        - show paths with changes
1199 update        - add working tree state to the staged set of changes
1200 revert        - revert staged set of changes back to the HEAD version
1201 patch         - pick hunks and update selectively
1202 diff          - view diff between HEAD and index
1203 add untracked - add contents of untracked files to the staged set of changes
1204 EOF
1207 sub process_args {
1208         return unless @ARGV;
1209         my $arg = shift @ARGV;
1210         if ($arg eq "--patch") {
1211                 $patch_mode = 1;
1212                 $arg = shift @ARGV or die "missing --";
1213                 die "invalid argument $arg, expecting --"
1214                     unless $arg eq "--";
1215         }
1216         elsif ($arg ne "--") {
1217                 die "invalid argument $arg, expecting --";
1218         }
1221 sub main_loop {
1222         my @cmd = ([ 'status', \&status_cmd, ],
1223                    [ 'update', \&update_cmd, ],
1224                    [ 'revert', \&revert_cmd, ],
1225                    [ 'add untracked', \&add_untracked_cmd, ],
1226                    [ 'patch', \&patch_update_cmd, ],
1227                    [ 'diff', \&diff_cmd, ],
1228                    [ 'quit', \&quit_cmd, ],
1229                    [ 'help', \&help_cmd, ],
1230         );
1231         while (1) {
1232                 my ($it) = list_and_choose({ PROMPT => 'What now',
1233                                              SINGLETON => 1,
1234                                              LIST_FLAT => 4,
1235                                              HEADER => '*** Commands ***',
1236                                              ON_EOF => \&quit_cmd,
1237                                              IMMEDIATE => 1 }, @cmd);
1238                 if ($it) {
1239                         eval {
1240                                 $it->[1]->();
1241                         };
1242                         if ($@) {
1243                                 print "$@";
1244                         }
1245                 }
1246         }
1249 process_args();
1250 refresh();
1251 if ($patch_mode) {
1252         patch_update_cmd();
1254 else {
1255         status_cmd();
1256         main_loop();