Code

Merge branch 'jw/imap-preformatted-html'
[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         if ($? != 0) {
757                 return undef;
758         }
760         open $fh, '<', $hunkfile
761                 or die "failed to open hunk edit file for reading: " . $!;
762         my @newtext = grep { !/^#/ } <$fh>;
763         close $fh;
764         unlink $hunkfile;
766         # Abort if nothing remains
767         if (!grep { /\S/ } @newtext) {
768                 return undef;
769         }
771         # Reinsert the first hunk header if the user accidentally deleted it
772         if ($newtext[0] !~ /^@/) {
773                 unshift @newtext, $oldtext->[0];
774         }
775         return \@newtext;
778 sub diff_applies {
779         my $fh;
780         open $fh, '| git apply --recount --cached --check';
781         for my $h (@_) {
782                 print $fh @{$h->{TEXT}};
783         }
784         return close $fh;
787 sub _restore_terminal_and_die {
788         ReadMode 'restore';
789         print "\n";
790         exit 1;
793 sub prompt_single_character {
794         if ($use_readkey) {
795                 local $SIG{TERM} = \&_restore_terminal_and_die;
796                 local $SIG{INT} = \&_restore_terminal_and_die;
797                 ReadMode 'cbreak';
798                 my $key = ReadKey 0;
799                 ReadMode 'restore';
800                 print "$key" if defined $key;
801                 print "\n";
802                 return $key;
803         } else {
804                 return <STDIN>;
805         }
808 sub prompt_yesno {
809         my ($prompt) = @_;
810         while (1) {
811                 print colored $prompt_color, $prompt;
812                 my $line = prompt_single_character;
813                 return 0 if $line =~ /^n/i;
814                 return 1 if $line =~ /^y/i;
815         }
818 sub edit_hunk_loop {
819         my ($head, $hunk, $ix) = @_;
820         my $text = $hunk->[$ix]->{TEXT};
822         while (1) {
823                 $text = edit_hunk_manually($text);
824                 if (!defined $text) {
825                         return undef;
826                 }
827                 my $newhunk = { TEXT => $text, USE => 1 };
828                 if (diff_applies($head,
829                                  @{$hunk}[0..$ix-1],
830                                  $newhunk,
831                                  @{$hunk}[$ix+1..$#{$hunk}])) {
832                         $newhunk->{DISPLAY} = [color_diff(@{$text})];
833                         return $newhunk;
834                 }
835                 else {
836                         prompt_yesno(
837                                 'Your edited hunk does not apply. Edit again '
838                                 . '(saying "no" discards!) [y/n]? '
839                                 ) or return undef;
840                 }
841         }
844 sub help_patch_cmd {
845         print colored $help_color, <<\EOF ;
846 y - stage this hunk
847 n - do not stage this hunk
848 a - stage this and all the remaining hunks in the file
849 d - do not stage this hunk nor any of the remaining hunks in the file
850 g - select a hunk to go to
851 / - search for a hunk matching the given regex
852 j - leave this hunk undecided, see next undecided hunk
853 J - leave this hunk undecided, see next hunk
854 k - leave this hunk undecided, see previous undecided hunk
855 K - leave this hunk undecided, see previous hunk
856 s - split the current hunk into smaller hunks
857 e - manually edit the current hunk
858 ? - print help
859 EOF
862 sub patch_update_cmd {
863         my @all_mods = list_modified('file-only');
864         my @mods = grep { !($_->{BINARY}) } @all_mods;
865         my @them;
867         if (!@mods) {
868                 if (@all_mods) {
869                         print STDERR "Only binary files changed.\n";
870                 } else {
871                         print STDERR "No changes.\n";
872                 }
873                 return 0;
874         }
875         if ($patch_mode) {
876                 @them = @mods;
877         }
878         else {
879                 @them = list_and_choose({ PROMPT => 'Patch update',
880                                           HEADER => $status_head, },
881                                         @mods);
882         }
883         for (@them) {
884                 patch_update_file($_->{VALUE});
885         }
888 # Generate a one line summary of a hunk.
889 sub summarize_hunk {
890         my $rhunk = shift;
891         my $summary = $rhunk->{TEXT}[0];
893         # Keep the line numbers, discard extra context.
894         $summary =~ s/@@(.*?)@@.*/$1 /s;
895         $summary .= " " x (20 - length $summary);
897         # Add some user context.
898         for my $line (@{$rhunk->{TEXT}}) {
899                 if ($line =~ m/^[+-].*\w/) {
900                         $summary .= $line;
901                         last;
902                 }
903         }
905         chomp $summary;
906         return substr($summary, 0, 80) . "\n";
910 # Print a one-line summary of each hunk in the array ref in
911 # the first argument, starting wih the index in the 2nd.
912 sub display_hunks {
913         my ($hunks, $i) = @_;
914         my $ctr = 0;
915         $i ||= 0;
916         for (; $i < @$hunks && $ctr < 20; $i++, $ctr++) {
917                 my $status = " ";
918                 if (defined $hunks->[$i]{USE}) {
919                         $status = $hunks->[$i]{USE} ? "+" : "-";
920                 }
921                 printf "%s%2d: %s",
922                         $status,
923                         $i + 1,
924                         summarize_hunk($hunks->[$i]);
925         }
926         return $i;
929 sub patch_update_file {
930         my ($ix, $num);
931         my $path = shift;
932         my ($head, @hunk) = parse_diff($path);
933         ($head, my $mode) = parse_diff_header($head);
934         for (@{$head->{DISPLAY}}) {
935                 print;
936         }
938         if (@{$mode->{TEXT}}) {
939                 while (1) {
940                         print @{$mode->{DISPLAY}};
941                         print colored $prompt_color,
942                                 "Stage mode change [y/n/a/d/?]? ";
943                         my $line = prompt_single_character;
944                         if ($line =~ /^y/i) {
945                                 $mode->{USE} = 1;
946                                 last;
947                         }
948                         elsif ($line =~ /^n/i) {
949                                 $mode->{USE} = 0;
950                                 last;
951                         }
952                         elsif ($line =~ /^a/i) {
953                                 $_->{USE} = 1 foreach ($mode, @hunk);
954                                 last;
955                         }
956                         elsif ($line =~ /^d/i) {
957                                 $_->{USE} = 0 foreach ($mode, @hunk);
958                                 last;
959                         }
960                         else {
961                                 help_patch_cmd('');
962                                 next;
963                         }
964                 }
965         }
967         $num = scalar @hunk;
968         $ix = 0;
970         while (1) {
971                 my ($prev, $next, $other, $undecided, $i);
972                 $other = '';
974                 if ($num <= $ix) {
975                         $ix = 0;
976                 }
977                 for ($i = 0; $i < $ix; $i++) {
978                         if (!defined $hunk[$i]{USE}) {
979                                 $prev = 1;
980                                 $other .= ',k';
981                                 last;
982                         }
983                 }
984                 if ($ix) {
985                         $other .= ',K';
986                 }
987                 for ($i = $ix + 1; $i < $num; $i++) {
988                         if (!defined $hunk[$i]{USE}) {
989                                 $next = 1;
990                                 $other .= ',j';
991                                 last;
992                         }
993                 }
994                 if ($ix < $num - 1) {
995                         $other .= ',J';
996                 }
997                 if ($num > 1) {
998                         $other .= ',g';
999                 }
1000                 for ($i = 0; $i < $num; $i++) {
1001                         if (!defined $hunk[$i]{USE}) {
1002                                 $undecided = 1;
1003                                 last;
1004                         }
1005                 }
1006                 last if (!$undecided);
1008                 if (hunk_splittable($hunk[$ix]{TEXT})) {
1009                         $other .= ',s';
1010                 }
1011                 $other .= ',e';
1012                 for (@{$hunk[$ix]{DISPLAY}}) {
1013                         print;
1014                 }
1015                 print colored $prompt_color, "Stage this hunk [y,n,a,d,/$other,?]? ";
1016                 my $line = prompt_single_character;
1017                 if ($line) {
1018                         if ($line =~ /^y/i) {
1019                                 $hunk[$ix]{USE} = 1;
1020                         }
1021                         elsif ($line =~ /^n/i) {
1022                                 $hunk[$ix]{USE} = 0;
1023                         }
1024                         elsif ($line =~ /^a/i) {
1025                                 while ($ix < $num) {
1026                                         if (!defined $hunk[$ix]{USE}) {
1027                                                 $hunk[$ix]{USE} = 1;
1028                                         }
1029                                         $ix++;
1030                                 }
1031                                 next;
1032                         }
1033                         elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1034                                 my $response = $1;
1035                                 my $no = $ix > 10 ? $ix - 10 : 0;
1036                                 while ($response eq '') {
1037                                         my $extra = "";
1038                                         $no = display_hunks(\@hunk, $no);
1039                                         if ($no < $num) {
1040                                                 $extra = " (<ret> to see more)";
1041                                         }
1042                                         print "go to which hunk$extra? ";
1043                                         $response = <STDIN>;
1044                                         if (!defined $response) {
1045                                                 $response = '';
1046                                         }
1047                                         chomp $response;
1048                                 }
1049                                 if ($response !~ /^\s*\d+\s*$/) {
1050                                         error_msg "Invalid number: '$response'\n";
1051                                 } elsif (0 < $response && $response <= $num) {
1052                                         $ix = $response - 1;
1053                                 } else {
1054                                         error_msg "Sorry, only $num hunks available.\n";
1055                                 }
1056                                 next;
1057                         }
1058                         elsif ($line =~ /^d/i) {
1059                                 while ($ix < $num) {
1060                                         if (!defined $hunk[$ix]{USE}) {
1061                                                 $hunk[$ix]{USE} = 0;
1062                                         }
1063                                         $ix++;
1064                                 }
1065                                 next;
1066                         }
1067                         elsif ($line =~ m|^/(.*)|) {
1068                                 my $regex = $1;
1069                                 if ($1 eq "") {
1070                                         print colored $prompt_color, "search for regex? ";
1071                                         $regex = <STDIN>;
1072                                         if (defined $regex) {
1073                                                 chomp $regex;
1074                                         }
1075                                 }
1076                                 my $search_string;
1077                                 eval {
1078                                         $search_string = qr{$regex}m;
1079                                 };
1080                                 if ($@) {
1081                                         my ($err,$exp) = ($@, $1);
1082                                         $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1083                                         error_msg "Malformed search regexp $exp: $err\n";
1084                                         next;
1085                                 }
1086                                 my $iy = $ix;
1087                                 while (1) {
1088                                         my $text = join ("", @{$hunk[$iy]{TEXT}});
1089                                         last if ($text =~ $search_string);
1090                                         $iy++;
1091                                         $iy = 0 if ($iy >= $num);
1092                                         if ($ix == $iy) {
1093                                                 error_msg "No hunk matches the given pattern\n";
1094                                                 last;
1095                                         }
1096                                 }
1097                                 $ix = $iy;
1098                                 next;
1099                         }
1100                         elsif ($line =~ /^K/) {
1101                                 if ($other =~ /K/) {
1102                                         $ix--;
1103                                 }
1104                                 else {
1105                                         error_msg "No previous hunk\n";
1106                                 }
1107                                 next;
1108                         }
1109                         elsif ($line =~ /^J/) {
1110                                 if ($other =~ /J/) {
1111                                         $ix++;
1112                                 }
1113                                 else {
1114                                         error_msg "No next hunk\n";
1115                                 }
1116                                 next;
1117                         }
1118                         elsif ($line =~ /^k/) {
1119                                 if ($other =~ /k/) {
1120                                         while (1) {
1121                                                 $ix--;
1122                                                 last if (!$ix ||
1123                                                          !defined $hunk[$ix]{USE});
1124                                         }
1125                                 }
1126                                 else {
1127                                         error_msg "No previous hunk\n";
1128                                 }
1129                                 next;
1130                         }
1131                         elsif ($line =~ /^j/) {
1132                                 if ($other !~ /j/) {
1133                                         error_msg "No next hunk\n";
1134                                         next;
1135                                 }
1136                         }
1137                         elsif ($other =~ /s/ && $line =~ /^s/) {
1138                                 my @split = split_hunk($hunk[$ix]{TEXT}, $hunk[$ix]{DISPLAY});
1139                                 if (1 < @split) {
1140                                         print colored $header_color, "Split into ",
1141                                         scalar(@split), " hunks.\n";
1142                                 }
1143                                 splice (@hunk, $ix, 1, @split);
1144                                 $num = scalar @hunk;
1145                                 next;
1146                         }
1147                         elsif ($line =~ /^e/) {
1148                                 my $newhunk = edit_hunk_loop($head, \@hunk, $ix);
1149                                 if (defined $newhunk) {
1150                                         splice @hunk, $ix, 1, $newhunk;
1151                                 }
1152                         }
1153                         else {
1154                                 help_patch_cmd($other);
1155                                 next;
1156                         }
1157                         # soft increment
1158                         while (1) {
1159                                 $ix++;
1160                                 last if ($ix >= $num ||
1161                                          !defined $hunk[$ix]{USE});
1162                         }
1163                 }
1164         }
1166         my $n_lofs = 0;
1167         my @result = ();
1168         if ($mode->{USE}) {
1169                 push @result, @{$mode->{TEXT}};
1170         }
1171         for (@hunk) {
1172                 if ($_->{USE}) {
1173                         push @result, @{$_->{TEXT}};
1174                 }
1175         }
1177         if (@result) {
1178                 my $fh;
1180                 open $fh, '| git apply --cached --recount';
1181                 for (@{$head->{TEXT}}, @result) {
1182                         print $fh $_;
1183                 }
1184                 if (!close $fh) {
1185                         for (@{$head->{TEXT}}, @result) {
1186                                 print STDERR $_;
1187                         }
1188                 }
1189                 refresh();
1190         }
1192         print "\n";
1195 sub diff_cmd {
1196         my @mods = list_modified('index-only');
1197         @mods = grep { !($_->{BINARY}) } @mods;
1198         return if (!@mods);
1199         my (@them) = list_and_choose({ PROMPT => 'Review diff',
1200                                      IMMEDIATE => 1,
1201                                      HEADER => $status_head, },
1202                                    @mods);
1203         return if (!@them);
1204         my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
1205         system(qw(git diff -p --cached), $reference, '--',
1206                 map { $_->{VALUE} } @them);
1209 sub quit_cmd {
1210         print "Bye.\n";
1211         exit(0);
1214 sub help_cmd {
1215         print colored $help_color, <<\EOF ;
1216 status        - show paths with changes
1217 update        - add working tree state to the staged set of changes
1218 revert        - revert staged set of changes back to the HEAD version
1219 patch         - pick hunks and update selectively
1220 diff          - view diff between HEAD and index
1221 add untracked - add contents of untracked files to the staged set of changes
1222 EOF
1225 sub process_args {
1226         return unless @ARGV;
1227         my $arg = shift @ARGV;
1228         if ($arg eq "--patch") {
1229                 $patch_mode = 1;
1230                 $arg = shift @ARGV or die "missing --";
1231                 die "invalid argument $arg, expecting --"
1232                     unless $arg eq "--";
1233         }
1234         elsif ($arg ne "--") {
1235                 die "invalid argument $arg, expecting --";
1236         }
1239 sub main_loop {
1240         my @cmd = ([ 'status', \&status_cmd, ],
1241                    [ 'update', \&update_cmd, ],
1242                    [ 'revert', \&revert_cmd, ],
1243                    [ 'add untracked', \&add_untracked_cmd, ],
1244                    [ 'patch', \&patch_update_cmd, ],
1245                    [ 'diff', \&diff_cmd, ],
1246                    [ 'quit', \&quit_cmd, ],
1247                    [ 'help', \&help_cmd, ],
1248         );
1249         while (1) {
1250                 my ($it) = list_and_choose({ PROMPT => 'What now',
1251                                              SINGLETON => 1,
1252                                              LIST_FLAT => 4,
1253                                              HEADER => '*** Commands ***',
1254                                              ON_EOF => \&quit_cmd,
1255                                              IMMEDIATE => 1 }, @cmd);
1256                 if ($it) {
1257                         eval {
1258                                 $it->[1]->();
1259                         };
1260                         if ($@) {
1261                                 print "$@";
1262                         }
1263                 }
1264         }
1267 process_args();
1268 refresh();
1269 if ($patch_mode) {
1270         patch_update_cmd();
1272 else {
1273         status_cmd();
1274         main_loop();