Code

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