FIXME: hotpatch for compatibility with latest hg
[git] / git-add--interactive.perl
1 #!/usr/bin/perl
2
3 use 5.008;
4 use strict;
5 use warnings;
6 use Git;
7
8 binmode(STDOUT, ":raw");
9
10 my $repo = Git->repository();
11
12 my $menu_use_color = $repo->get_colorbool('color.interactive');
13 my ($prompt_color, $header_color, $help_color) =
14         $menu_use_color ? (
15                 $repo->get_color('color.interactive.prompt', 'bold blue'),
16                 $repo->get_color('color.interactive.header', 'bold'),
17                 $repo->get_color('color.interactive.help', 'red bold'),
18         ) : ();
19 my $error_color = ();
20 if ($menu_use_color) {
21         my $help_color_spec = ($repo->config('color.interactive.help') or
22                                 'red bold');
23         $error_color = $repo->get_color('color.interactive.error',
24                                         $help_color_spec);
25 }
26
27 my $diff_use_color = $repo->get_colorbool('color.diff');
28 my ($fraginfo_color) =
29         $diff_use_color ? (
30                 $repo->get_color('color.diff.frag', 'cyan'),
31         ) : ();
32 my ($diff_plain_color) =
33         $diff_use_color ? (
34                 $repo->get_color('color.diff.plain', ''),
35         ) : ();
36 my ($diff_old_color) =
37         $diff_use_color ? (
38                 $repo->get_color('color.diff.old', 'red'),
39         ) : ();
40 my ($diff_new_color) =
41         $diff_use_color ? (
42                 $repo->get_color('color.diff.new', 'green'),
43         ) : ();
44
45 my $normal_color = $repo->get_color("", "reset");
46
47 my $use_readkey = 0;
48 my $use_termcap = 0;
49 my %term_escapes;
50
51 sub ReadMode;
52 sub ReadKey;
53 if ($repo->config_bool("interactive.singlekey")) {
54         eval {
55                 require Term::ReadKey;
56                 Term::ReadKey->import;
57                 $use_readkey = 1;
58         };
59         eval {
60                 require Term::Cap;
61                 my $termcap = Term::Cap->Tgetent;
62                 foreach (values %$termcap) {
63                         $term_escapes{$_} = 1 if /^\e/;
64                 }
65                 $use_termcap = 1;
66         };
67 }
68
69 sub colored {
70         my $color = shift;
71         my $string = join("", @_);
72
73         if (defined $color) {
74                 # Put a color code at the beginning of each line, a reset at the end
75                 # color after newlines that are not at the end of the string
76                 $string =~ s/(\n+)(.)/$1$color$2/g;
77                 # reset before newlines
78                 $string =~ s/(\n+)/$normal_color$1/g;
79                 # codes at beginning and end (if necessary):
80                 $string =~ s/^/$color/;
81                 $string =~ s/$/$normal_color/ unless $string =~ /\n$/;
82         }
83         return $string;
84 }
85
86 # command line options
87 my $patch_mode;
88 my $patch_mode_revision;
89 my @patch_mode_hunk_filter;
90 my $patch_mode_negate_filter;
91 my $patch_mode_autosplit;
92
93 sub apply_patch;
94 sub apply_patch_for_checkout_commit;
95 sub apply_patch_for_stash;
96
97 my %patch_modes = (
98         'stage' => {
99                 default => 'index',
100                 index => {
101                         DIFF => 'diff-files -p',
102                         APPLY => sub { apply_patch 'apply --cached', @_; },
103                         APPLY_CHECK => 'apply --cached',
104                         VERB => 'Stage',
105                         TARGET => '',
106                         PARTICIPLE => 'staging',
107                         FILTER => 'file-only',
108                         IS_REVERSE => 0,
109                 },
110         },
111         'stash' => {
112                 default => 'head',
113                 head => {
114                         DIFF => 'diff-index -p',
115                         APPLY => sub { apply_patch 'apply --cached', @_; },
116                         APPLY_CHECK => 'apply --cached',
117                         VERB => 'Stash',
118                         TARGET => '',
119                         PARTICIPLE => 'stashing',
120                         FILTER => undef,
121                         IS_REVERSE => 0,
122                 },
123         },
124         'reset' => {
125                 default => 'head',
126                 head => {
127                         DIFF => 'diff-index -p --cached',
128                         APPLY => sub { apply_patch 'apply -R --cached', @_; },
129                         APPLY_CHECK => 'apply -R --cached',
130                         VERB => 'Unstage',
131                         TARGET => '',
132                         PARTICIPLE => 'unstaging',
133                         FILTER => 'index-only',
134                         IS_REVERSE => 1,
135                 },
136                 nothead => {
137                         DIFF => 'diff-index -R -p --cached',
138                         APPLY => sub { apply_patch 'apply --cached', @_; },
139                         APPLY_CHECK => 'apply --cached',
140                         VERB => 'Apply',
141                         TARGET => ' to index',
142                         PARTICIPLE => 'applying',
143                         FILTER => 'index-only',
144                         IS_REVERSE => 0,
145                 },
146         },
147         'checkout' => {
148                 default => 'index',
149                 index => {
150                         DIFF => 'diff-files -p',
151                         APPLY => sub { apply_patch 'apply -R', @_; },
152                         APPLY_CHECK => 'apply -R',
153                         VERB => 'Discard',
154                         TARGET => ' from worktree',
155                         PARTICIPLE => 'discarding',
156                         FILTER => 'file-only',
157                         IS_REVERSE => 1,
158                 },
159                 head => {
160                         DIFF => 'diff-index -p',
161                         APPLY => sub { apply_patch_for_checkout_commit '-R', @_ },
162                         APPLY_CHECK => 'apply -R',
163                         VERB => 'Discard',
164                         TARGET => ' from index and worktree',
165                         PARTICIPLE => 'discarding',
166                         FILTER => undef,
167                         IS_REVERSE => 1,
168                 },
169                 nothead => {
170                         DIFF => 'diff-index -R -p',
171                         APPLY => sub { apply_patch_for_checkout_commit '', @_ },
172                         APPLY_CHECK => 'apply',
173                         VERB => 'Apply',
174                         TARGET => ' to index and worktree',
175                         PARTICIPLE => 'applying',
176                         FILTER => undef,
177                         IS_REVERSE => 0,
178                 },
179         },
180 );
181
182 my %patch_mode_flavour = %{$patch_modes{stage}};
183
184 sub run_cmd_pipe {
185         if ($^O eq 'MSWin32' || $^O eq 'msys') {
186                 my @invalid = grep {m/[":*]/} @_;
187                 die "$^O does not support: @invalid\n" if @invalid;
188                 my @args = map { m/ /o ? "\"$_\"": $_ } @_;
189                 return qx{@args};
190         } else {
191                 my $fh = undef;
192                 open($fh, '-|', @_) or die;
193                 return <$fh>;
194         }
195 }
196
197 my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));
198
199 if (!defined $GIT_DIR) {
200         exit(1); # rev-parse would have already said "not a git repo"
201 }
202 chomp($GIT_DIR);
203
204 my %cquote_map = (
205  "b" => chr(8),
206  "t" => chr(9),
207  "n" => chr(10),
208  "v" => chr(11),
209  "f" => chr(12),
210  "r" => chr(13),
211  "\\" => "\\",
212  "\042" => "\042",
213 );
214
215 sub unquote_path {
216         local ($_) = @_;
217         my ($retval, $remainder);
218         if (!/^\042(.*)\042$/) {
219                 return $_;
220         }
221         ($_, $retval) = ($1, "");
222         while (/^([^\\]*)\\(.*)$/) {
223                 $remainder = $2;
224                 $retval .= $1;
225                 for ($remainder) {
226                         if (/^([0-3][0-7][0-7])(.*)$/) {
227                                 $retval .= chr(oct($1));
228                                 $_ = $2;
229                                 last;
230                         }
231                         if (/^([\\\042btnvfr])(.*)$/) {
232                                 $retval .= $cquote_map{$1};
233                                 $_ = $2;
234                                 last;
235                         }
236                         # This is malformed -- just return it as-is for now.
237                         return $_[0];
238                 }
239                 $_ = $remainder;
240         }
241         $retval .= $_;
242         return $retval;
243 }
244
245 sub refresh {
246         my $fh;
247         open $fh, 'git update-index --refresh |'
248             or die;
249         while (<$fh>) {
250                 ;# ignore 'needs update'
251         }
252         close $fh;
253 }
254
255 sub list_untracked {
256         map {
257                 chomp $_;
258                 unquote_path($_);
259         }
260         run_cmd_pipe(qw(git ls-files --others --exclude-standard --), @ARGV);
261 }
262
263 my $status_fmt = '%12s %12s %s';
264 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
265
266 {
267         my $initial;
268         sub is_initial_commit {
269                 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
270                         unless defined $initial;
271                 return $initial;
272         }
273 }
274
275 sub get_empty_tree {
276         return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
277 }
278
279 # Returns list of hashes, contents of each of which are:
280 # VALUE:        pathname
281 # BINARY:       is a binary path
282 # INDEX:        is index different from HEAD?
283 # FILE:         is file different from index?
284 # INDEX_ADDDEL: is it add/delete between HEAD and index?
285 # FILE_ADDDEL:  is it add/delete between index and file?
286
287 sub list_modified {
288         my ($only) = @_;
289         my (%data, @return);
290         my ($add, $del, $adddel, $file);
291         my @tracked = ();
292
293         if (@ARGV) {
294                 @tracked = map {
295                         chomp $_;
296                         unquote_path($_);
297                 } run_cmd_pipe(qw(git ls-files --), @ARGV);
298                 return if (!@tracked);
299         }
300
301         my $reference;
302         if (defined $patch_mode_revision and $patch_mode_revision ne 'HEAD') {
303                 $reference = $patch_mode_revision;
304         } elsif (is_initial_commit()) {
305                 $reference = get_empty_tree();
306         } else {
307                 $reference = 'HEAD';
308         }
309         for (run_cmd_pipe(qw(git diff-index --cached
310                              --numstat --summary), $reference,
311                              '--', @tracked)) {
312                 if (($add, $del, $file) =
313                     /^([-\d]+)  ([-\d]+)        (.*)/) {
314                         my ($change, $bin);
315                         $file = unquote_path($file);
316                         if ($add eq '-' && $del eq '-') {
317                                 $change = 'binary';
318                                 $bin = 1;
319                         }
320                         else {
321                                 $change = "+$add/-$del";
322                         }
323                         $data{$file} = {
324                                 INDEX => $change,
325                                 BINARY => $bin,
326                                 FILE => 'nothing',
327                         }
328                 }
329                 elsif (($adddel, $file) =
330                        /^ (create|delete) mode [0-7]+ (.*)$/) {
331                         $file = unquote_path($file);
332                         $data{$file}{INDEX_ADDDEL} = $adddel;
333                 }
334         }
335
336         for (run_cmd_pipe(qw(git diff-files --numstat --summary --), @tracked)) {
337                 if (($add, $del, $file) =
338                     /^([-\d]+)  ([-\d]+)        (.*)/) {
339                         $file = unquote_path($file);
340                         if (!exists $data{$file}) {
341                                 $data{$file} = +{
342                                         INDEX => 'unchanged',
343                                         BINARY => 0,
344                                 };
345                         }
346                         my ($change, $bin);
347                         if ($add eq '-' && $del eq '-') {
348                                 $change = 'binary';
349                                 $bin = 1;
350                         }
351                         else {
352                                 $change = "+$add/-$del";
353                         }
354                         $data{$file}{FILE} = $change;
355                         if ($bin) {
356                                 $data{$file}{BINARY} = 1;
357                         }
358                 }
359                 elsif (($adddel, $file) =
360                        /^ (create|delete) mode [0-7]+ (.*)$/) {
361                         $file = unquote_path($file);
362                         $data{$file}{FILE_ADDDEL} = $adddel;
363                 }
364         }
365
366         for (sort keys %data) {
367                 my $it = $data{$_};
368
369                 if ($only) {
370                         if ($only eq 'index-only') {
371                                 next if ($it->{INDEX} eq 'unchanged');
372                         }
373                         if ($only eq 'file-only') {
374                                 next if ($it->{FILE} eq 'nothing');
375                         }
376                 }
377                 push @return, +{
378                         VALUE => $_,
379                         %$it,
380                 };
381         }
382         return @return;
383 }
384
385 sub find_unique {
386         my ($string, @stuff) = @_;
387         my $found = undef;
388         for (my $i = 0; $i < @stuff; $i++) {
389                 my $it = $stuff[$i];
390                 my $hit = undef;
391                 if (ref $it) {
392                         if ((ref $it) eq 'ARRAY') {
393                                 $it = $it->[0];
394                         }
395                         else {
396                                 $it = $it->{VALUE};
397                         }
398                 }
399                 eval {
400                         if ($it =~ /^$string/) {
401                                 $hit = 1;
402                         };
403                 };
404                 if (defined $hit && defined $found) {
405                         return undef;
406                 }
407                 if ($hit) {
408                         $found = $i + 1;
409                 }
410         }
411         return $found;
412 }
413
414 # inserts string into trie and updates count for each character
415 sub update_trie {
416         my ($trie, $string) = @_;
417         foreach (split //, $string) {
418                 $trie = $trie->{$_} ||= {COUNT => 0};
419                 $trie->{COUNT}++;
420         }
421 }
422
423 # returns an array of tuples (prefix, remainder)
424 sub find_unique_prefixes {
425         my @stuff = @_;
426         my @return = ();
427
428         # any single prefix exceeding the soft limit is omitted
429         # if any prefix exceeds the hard limit all are omitted
430         # 0 indicates no limit
431         my $soft_limit = 0;
432         my $hard_limit = 3;
433
434         # build a trie modelling all possible options
435         my %trie;
436         foreach my $print (@stuff) {
437                 if ((ref $print) eq 'ARRAY') {
438                         $print = $print->[0];
439                 }
440                 elsif ((ref $print) eq 'HASH') {
441                         $print = $print->{VALUE};
442                 }
443                 update_trie(\%trie, $print);
444                 push @return, $print;
445         }
446
447         # use the trie to find the unique prefixes
448         for (my $i = 0; $i < @return; $i++) {
449                 my $ret = $return[$i];
450                 my @letters = split //, $ret;
451                 my %search = %trie;
452                 my ($prefix, $remainder);
453                 my $j;
454                 for ($j = 0; $j < @letters; $j++) {
455                         my $letter = $letters[$j];
456                         if ($search{$letter}{COUNT} == 1) {
457                                 $prefix = substr $ret, 0, $j + 1;
458                                 $remainder = substr $ret, $j + 1;
459                                 last;
460                         }
461                         else {
462                                 my $prefix = substr $ret, 0, $j;
463                                 return ()
464                                     if ($hard_limit && $j + 1 > $hard_limit);
465                         }
466                         %search = %{$search{$letter}};
467                 }
468                 if (ord($letters[0]) > 127 ||
469                     ($soft_limit && $j + 1 > $soft_limit)) {
470                         $prefix = undef;
471                         $remainder = $ret;
472                 }
473                 $return[$i] = [$prefix, $remainder];
474         }
475         return @return;
476 }
477
478 # filters out prefixes which have special meaning to list_and_choose()
479 sub is_valid_prefix {
480         my $prefix = shift;
481         return (defined $prefix) &&
482             !($prefix =~ /[\s,]/) && # separators
483             !($prefix =~ /^-/) &&    # deselection
484             !($prefix =~ /^\d+/) &&  # selection
485             ($prefix ne '*') &&      # "all" wildcard
486             ($prefix ne '?');        # prompt help
487 }
488
489 # given a prefix/remainder tuple return a string with the prefix highlighted
490 # for now use square brackets; later might use ANSI colors (underline, bold)
491 sub highlight_prefix {
492         my $prefix = shift;
493         my $remainder = shift;
494
495         if (!defined $prefix) {
496                 return $remainder;
497         }
498
499         if (!is_valid_prefix($prefix)) {
500                 return "$prefix$remainder";
501         }
502
503         if (!$menu_use_color) {
504                 return "[$prefix]$remainder";
505         }
506
507         return "$prompt_color$prefix$normal_color$remainder";
508 }
509
510 sub error_msg {
511         print STDERR colored $error_color, @_;
512 }
513
514 sub list_and_choose {
515         my ($opts, @stuff) = @_;
516         my (@chosen, @return);
517         my $i;
518         my @prefixes = find_unique_prefixes(@stuff) unless $opts->{LIST_ONLY};
519
520       TOPLOOP:
521         while (1) {
522                 my $last_lf = 0;
523
524                 if ($opts->{HEADER}) {
525                         if (!$opts->{LIST_FLAT}) {
526                                 print "     ";
527                         }
528                         print colored $header_color, "$opts->{HEADER}\n";
529                 }
530                 for ($i = 0; $i < @stuff; $i++) {
531                         my $chosen = $chosen[$i] ? '*' : ' ';
532                         my $print = $stuff[$i];
533                         my $ref = ref $print;
534                         my $highlighted = highlight_prefix(@{$prefixes[$i]})
535                             if @prefixes;
536                         if ($ref eq 'ARRAY') {
537                                 $print = $highlighted || $print->[0];
538                         }
539                         elsif ($ref eq 'HASH') {
540                                 my $value = $highlighted || $print->{VALUE};
541                                 $print = sprintf($status_fmt,
542                                     $print->{INDEX},
543                                     $print->{FILE},
544                                     $value);
545                         }
546                         else {
547                                 $print = $highlighted || $print;
548                         }
549                         printf("%s%2d: %s", $chosen, $i+1, $print);
550                         if (($opts->{LIST_FLAT}) &&
551                             (($i + 1) % ($opts->{LIST_FLAT}))) {
552                                 print "\t";
553                                 $last_lf = 0;
554                         }
555                         else {
556                                 print "\n";
557                                 $last_lf = 1;
558                         }
559                 }
560                 if (!$last_lf) {
561                         print "\n";
562                 }
563
564                 return if ($opts->{LIST_ONLY});
565
566                 print colored $prompt_color, $opts->{PROMPT};
567                 if ($opts->{SINGLETON}) {
568                         print "> ";
569                 }
570                 else {
571                         print ">> ";
572                 }
573                 my $line = <STDIN>;
574                 if (!$line) {
575                         print "\n";
576                         $opts->{ON_EOF}->() if $opts->{ON_EOF};
577                         last;
578                 }
579                 chomp $line;
580                 last if $line eq '';
581                 if ($line eq '?') {
582                         $opts->{SINGLETON} ?
583                             singleton_prompt_help_cmd() :
584                             prompt_help_cmd();
585                         next TOPLOOP;
586                 }
587                 for my $choice (split(/[\s,]+/, $line)) {
588                         my $choose = 1;
589                         my ($bottom, $top);
590
591                         # Input that begins with '-'; unchoose
592                         if ($choice =~ s/^-//) {
593                                 $choose = 0;
594                         }
595                         # A range can be specified like 5-7 or 5-.
596                         if ($choice =~ /^(\d+)-(\d*)$/) {
597                                 ($bottom, $top) = ($1, length($2) ? $2 : 1 + @stuff);
598                         }
599                         elsif ($choice =~ /^\d+$/) {
600                                 $bottom = $top = $choice;
601                         }
602                         elsif ($choice eq '*') {
603                                 $bottom = 1;
604                                 $top = 1 + @stuff;
605                         }
606                         else {
607                                 $bottom = $top = find_unique($choice, @stuff);
608                                 if (!defined $bottom) {
609                                         error_msg "Huh ($choice)?\n";
610                                         next TOPLOOP;
611                                 }
612                         }
613                         if ($opts->{SINGLETON} && $bottom != $top) {
614                                 error_msg "Huh ($choice)?\n";
615                                 next TOPLOOP;
616                         }
617                         for ($i = $bottom-1; $i <= $top-1; $i++) {
618                                 next if (@stuff <= $i || $i < 0);
619                                 $chosen[$i] = $choose;
620                         }
621                 }
622                 last if ($opts->{IMMEDIATE} || $line eq '*');
623         }
624         for ($i = 0; $i < @stuff; $i++) {
625                 if ($chosen[$i]) {
626                         push @return, $stuff[$i];
627                 }
628         }
629         return @return;
630 }
631
632 sub singleton_prompt_help_cmd {
633         print colored $help_color, <<\EOF ;
634 Prompt help:
635 1          - select a numbered item
636 foo        - select item based on unique prefix
637            - (empty) select nothing
638 EOF
639 }
640
641 sub prompt_help_cmd {
642         print colored $help_color, <<\EOF ;
643 Prompt help:
644 1          - select a single item
645 3-5        - select a range of items
646 2-3,6-9    - select multiple ranges
647 foo        - select item based on unique prefix
648 -...       - unselect specified items
649 *          - choose all items
650            - (empty) finish selecting
651 EOF
652 }
653
654 sub status_cmd {
655         list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
656                         list_modified());
657         print "\n";
658 }
659
660 sub say_n_paths {
661         my $did = shift @_;
662         my $cnt = scalar @_;
663         print "$did ";
664         if (1 < $cnt) {
665                 print "$cnt paths\n";
666         }
667         else {
668                 print "one path\n";
669         }
670 }
671
672 sub update_cmd {
673         my @mods = list_modified('file-only');
674         return if (!@mods);
675
676         my @update = list_and_choose({ PROMPT => 'Update',
677                                        HEADER => $status_head, },
678                                      @mods);
679         if (@update) {
680                 system(qw(git update-index --add --remove --),
681                        map { $_->{VALUE} } @update);
682                 say_n_paths('updated', @update);
683         }
684         print "\n";
685 }
686
687 sub revert_cmd {
688         my @update = list_and_choose({ PROMPT => 'Revert',
689                                        HEADER => $status_head, },
690                                      list_modified());
691         if (@update) {
692                 if (is_initial_commit()) {
693                         system(qw(git rm --cached),
694                                 map { $_->{VALUE} } @update);
695                 }
696                 else {
697                         my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
698                                                  map { $_->{VALUE} } @update);
699                         my $fh;
700                         open $fh, '| git update-index --index-info'
701                             or die;
702                         for (@lines) {
703                                 print $fh $_;
704                         }
705                         close($fh);
706                         for (@update) {
707                                 if ($_->{INDEX_ADDDEL} &&
708                                     $_->{INDEX_ADDDEL} eq 'create') {
709                                         system(qw(git update-index --force-remove --),
710                                                $_->{VALUE});
711                                         print "note: $_->{VALUE} is untracked now.\n";
712                                 }
713                         }
714                 }
715                 refresh();
716                 say_n_paths('reverted', @update);
717         }
718         print "\n";
719 }
720
721 sub add_untracked_cmd {
722         my @add = list_and_choose({ PROMPT => 'Add untracked' },
723                                   list_untracked());
724         if (@add) {
725                 system(qw(git update-index --add --), @add);
726                 say_n_paths('added', @add);
727         }
728         print "\n";
729 }
730
731 sub run_git_apply {
732         my $cmd = shift;
733         my $fh;
734         open $fh, '| git ' . $cmd . " --recount --allow-overlap";
735         print $fh @_;
736         return close $fh;
737 }
738
739 sub parse_diff {
740         my ($path) = @_;
741         my @diff_cmd = split(" ", $patch_mode_flavour{DIFF});
742         if (defined $patch_mode_revision) {
743                 push @diff_cmd, $patch_mode_revision;
744         }
745         my @diff = run_cmd_pipe("git", @diff_cmd, "--", $path);
746         my @colored = ();
747         if ($diff_use_color) {
748                 @colored = run_cmd_pipe("git", @diff_cmd, qw(--color --), $path);
749         }
750         my (@hunk) = { TEXT => [], DISPLAY => [], TYPE => 'header' };
751
752         for (my $i = 0; $i < @diff; $i++) {
753                 if ($diff[$i] =~ /^@@ /) {
754                         push @hunk, { TEXT => [], DISPLAY => [],
755                                 TYPE => 'hunk' };
756                 }
757                 push @{$hunk[-1]{TEXT}}, $diff[$i];
758                 push @{$hunk[-1]{DISPLAY}},
759                         ($diff_use_color ? $colored[$i] : $diff[$i]);
760         }
761         return @hunk;
762 }
763
764 sub parse_diff_header {
765         my $src = shift;
766
767         my $head = { TEXT => [], DISPLAY => [], TYPE => 'header' };
768         my $mode = { TEXT => [], DISPLAY => [], TYPE => 'mode' };
769         my $deletion = { TEXT => [], DISPLAY => [], TYPE => 'deletion' };
770
771         for (my $i = 0; $i < @{$src->{TEXT}}; $i++) {
772                 my $dest =
773                    $src->{TEXT}->[$i] =~ /^(old|new) mode (\d+)$/ ? $mode :
774                    $src->{TEXT}->[$i] =~ /^deleted file/ ? $deletion :
775                    $head;
776                 push @{$dest->{TEXT}}, $src->{TEXT}->[$i];
777                 push @{$dest->{DISPLAY}}, $src->{DISPLAY}->[$i];
778         }
779         return ($head, $mode, $deletion);
780 }
781
782 sub hunk_splittable {
783         my ($text) = @_;
784
785         my @s = split_hunk($text);
786         return (1 < @s);
787 }
788
789 sub parse_hunk_header {
790         my ($line) = @_;
791         my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
792             $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
793         $o_cnt = 1 unless defined $o_cnt;
794         $n_cnt = 1 unless defined $n_cnt;
795         return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
796 }
797
798 sub split_hunk {
799         my ($text, $display) = @_;
800         my @split = ();
801         if (!defined $display) {
802                 $display = $text;
803         }
804         # If there are context lines in the middle of a hunk,
805         # it can be split, but we would need to take care of
806         # overlaps later.
807
808         my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
809         my $hunk_start = 1;
810
811       OUTER:
812         while (1) {
813                 my $next_hunk_start = undef;
814                 my $i = $hunk_start - 1;
815                 my $this = +{
816                         TEXT => [],
817                         DISPLAY => [],
818                         TYPE => 'hunk',
819                         OLD => $o_ofs,
820                         NEW => $n_ofs,
821                         OCNT => 0,
822                         NCNT => 0,
823                         ADDDEL => 0,
824                         POSTCTX => 0,
825                         USE => undef,
826                 };
827
828                 while (++$i < @$text) {
829                         my $line = $text->[$i];
830                         my $display = $display->[$i];
831                         if ($line =~ /^ /) {
832                                 if ($this->{ADDDEL} &&
833                                     !defined $next_hunk_start) {
834                                         # We have seen leading context and
835                                         # adds/dels and then here is another
836                                         # context, which is trailing for this
837                                         # split hunk and leading for the next
838                                         # one.
839                                         $next_hunk_start = $i;
840                                 }
841                                 push @{$this->{TEXT}}, $line;
842                                 push @{$this->{DISPLAY}}, $display;
843                                 $this->{OCNT}++;
844                                 $this->{NCNT}++;
845                                 if (defined $next_hunk_start) {
846                                         $this->{POSTCTX}++;
847                                 }
848                                 next;
849                         }
850
851                         # add/del
852                         if (defined $next_hunk_start) {
853                                 # We are done with the current hunk and
854                                 # this is the first real change for the
855                                 # next split one.
856                                 $hunk_start = $next_hunk_start;
857                                 $o_ofs = $this->{OLD} + $this->{OCNT};
858                                 $n_ofs = $this->{NEW} + $this->{NCNT};
859                                 $o_ofs -= $this->{POSTCTX};
860                                 $n_ofs -= $this->{POSTCTX};
861                                 push @split, $this;
862                                 redo OUTER;
863                         }
864                         push @{$this->{TEXT}}, $line;
865                         push @{$this->{DISPLAY}}, $display;
866                         $this->{ADDDEL}++;
867                         if ($line =~ /^-/) {
868                                 $this->{OCNT}++;
869                         }
870                         else {
871                                 $this->{NCNT}++;
872                         }
873                 }
874
875                 push @split, $this;
876                 last;
877         }
878
879         for my $hunk (@split) {
880                 $o_ofs = $hunk->{OLD};
881                 $n_ofs = $hunk->{NEW};
882                 my $o_cnt = $hunk->{OCNT};
883                 my $n_cnt = $hunk->{NCNT};
884
885                 my $head = ("@@ -$o_ofs" .
886                             (($o_cnt != 1) ? ",$o_cnt" : '') .
887                             " +$n_ofs" .
888                             (($n_cnt != 1) ? ",$n_cnt" : '') .
889                             " @@\n");
890                 my $display_head = $head;
891                 unshift @{$hunk->{TEXT}}, $head;
892                 if ($diff_use_color) {
893                         $display_head = colored($fraginfo_color, $head);
894                 }
895                 unshift @{$hunk->{DISPLAY}}, $display_head;
896         }
897         return @split;
898 }
899
900 sub find_last_o_ctx {
901         my ($it) = @_;
902         my $text = $it->{TEXT};
903         my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
904         my $i = @{$text};
905         my $last_o_ctx = $o_ofs + $o_cnt;
906         while (0 < --$i) {
907                 my $line = $text->[$i];
908                 if ($line =~ /^ /) {
909                         $last_o_ctx--;
910                         next;
911                 }
912                 last;
913         }
914         return $last_o_ctx;
915 }
916
917 sub merge_hunk {
918         my ($prev, $this) = @_;
919         my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
920             parse_hunk_header($prev->{TEXT}[0]);
921         my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
922             parse_hunk_header($this->{TEXT}[0]);
923
924         my (@line, $i, $ofs, $o_cnt, $n_cnt);
925         $ofs = $o0_ofs;
926         $o_cnt = $n_cnt = 0;
927         for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
928                 my $line = $prev->{TEXT}[$i];
929                 if ($line =~ /^\+/) {
930                         $n_cnt++;
931                         push @line, $line;
932                         next;
933                 }
934
935                 last if ($o1_ofs <= $ofs);
936
937                 $o_cnt++;
938                 $ofs++;
939                 if ($line =~ /^ /) {
940                         $n_cnt++;
941                 }
942                 push @line, $line;
943         }
944
945         for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
946                 my $line = $this->{TEXT}[$i];
947                 if ($line =~ /^\+/) {
948                         $n_cnt++;
949                         push @line, $line;
950                         next;
951                 }
952                 $ofs++;
953                 $o_cnt++;
954                 if ($line =~ /^ /) {
955                         $n_cnt++;
956                 }
957                 push @line, $line;
958         }
959         my $head = ("@@ -$o0_ofs" .
960                     (($o_cnt != 1) ? ",$o_cnt" : '') .
961                     " +$n0_ofs" .
962                     (($n_cnt != 1) ? ",$n_cnt" : '') .
963                     " @@\n");
964         @{$prev->{TEXT}} = ($head, @line);
965 }
966
967 sub coalesce_overlapping_hunks {
968         my (@in) = @_;
969         my @out = ();
970
971         my ($last_o_ctx, $last_was_dirty);
972
973         for (grep { $_->{USE} } @in) {
974                 if ($_->{TYPE} ne 'hunk') {
975                         push @out, $_;
976                         next;
977                 }
978                 my $text = $_->{TEXT};
979                 my ($o_ofs) = parse_hunk_header($text->[0]);
980                 if (defined $last_o_ctx &&
981                     $o_ofs <= $last_o_ctx &&
982                     !$_->{DIRTY} &&
983                     !$last_was_dirty) {
984                         merge_hunk($out[-1], $_);
985                 }
986                 else {
987                         push @out, $_;
988                 }
989                 $last_o_ctx = find_last_o_ctx($out[-1]);
990                 $last_was_dirty = $_->{DIRTY};
991         }
992         return @out;
993 }
994
995 sub reassemble_patch {
996         my $head = shift;
997         my @patch;
998
999         # Include everything in the header except the beginning of the diff.
1000         push @patch, (grep { !/^[-+]{3}/ } @$head);
1001
1002         # Then include any headers from the hunk lines, which must
1003         # come before any actual hunk.
1004         while (@_ && $_[0] !~ /^@/) {
1005                 push @patch, shift;
1006         }
1007
1008         # Then begin the diff.
1009         push @patch, grep { /^[-+]{3}/ } @$head;
1010
1011         # And then the actual hunks.
1012         push @patch, @_;
1013
1014         return @patch;
1015 }
1016
1017 sub color_diff {
1018         return map {
1019                 colored((/^@/  ? $fraginfo_color :
1020                          /^\+/ ? $diff_new_color :
1021                          /^-/  ? $diff_old_color :
1022                          $diff_plain_color),
1023                         $_);
1024         } @_;
1025 }
1026
1027 sub edit_hunk_manually {
1028         my ($oldtext) = @_;
1029
1030         my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
1031         my $fh;
1032         open $fh, '>', $hunkfile
1033                 or die "failed to open hunk edit file for writing: " . $!;
1034         print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
1035         print $fh @$oldtext;
1036         my $participle = $patch_mode_flavour{PARTICIPLE};
1037         my $is_reverse = $patch_mode_flavour{IS_REVERSE};
1038         my ($remove_plus, $remove_minus) = $is_reverse ? ('-', '+') : ('+', '-');
1039         print $fh <<EOF;
1040 # ---
1041 # To remove '$remove_minus' lines, make them ' ' lines (context).
1042 # To remove '$remove_plus' lines, delete them.
1043 # Lines starting with # will be removed.
1044 #
1045 # If the patch applies cleanly, the edited hunk will immediately be
1046 # marked for $participle. If it does not apply cleanly, you will be given
1047 # an opportunity to edit again. If all lines of the hunk are removed,
1048 # then the edit is aborted and the hunk is left unchanged.
1049 EOF
1050         close $fh;
1051
1052         chomp(my $editor = run_cmd_pipe(qw(git var GIT_EDITOR)));
1053         system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
1054
1055         if ($? != 0) {
1056                 return undef;
1057         }
1058
1059         open $fh, '<', $hunkfile
1060                 or die "failed to open hunk edit file for reading: " . $!;
1061         my @newtext = grep { !/^#/ } <$fh>;
1062         close $fh;
1063         unlink $hunkfile;
1064
1065         # Abort if nothing remains
1066         if (!grep { /\S/ } @newtext) {
1067                 return undef;
1068         }
1069
1070         # Reinsert the first hunk header if the user accidentally deleted it
1071         if ($newtext[0] !~ /^@/) {
1072                 unshift @newtext, $oldtext->[0];
1073         }
1074         return \@newtext;
1075 }
1076
1077 sub diff_applies {
1078         my $fh;
1079         return run_git_apply($patch_mode_flavour{APPLY_CHECK} . ' --check',
1080                              map { @{$_->{TEXT}} } @_);
1081 }
1082
1083 sub _restore_terminal_and_die {
1084         ReadMode 'restore';
1085         print "\n";
1086         exit 1;
1087 }
1088
1089 sub prompt_single_character {
1090         if ($use_readkey) {
1091                 local $SIG{TERM} = \&_restore_terminal_and_die;
1092                 local $SIG{INT} = \&_restore_terminal_and_die;
1093                 ReadMode 'cbreak';
1094                 my $key = ReadKey 0;
1095                 ReadMode 'restore';
1096                 if ($use_termcap and $key eq "\e") {
1097                         while (!defined $term_escapes{$key}) {
1098                                 my $next = ReadKey 0.5;
1099                                 last if (!defined $next);
1100                                 $key .= $next;
1101                         }
1102                         $key =~ s/\e/^[/;
1103                 }
1104                 print "$key" if defined $key;
1105                 print "\n";
1106                 return $key;
1107         } else {
1108                 return <STDIN>;
1109         }
1110 }
1111
1112 sub prompt_yesno {
1113         my ($prompt) = @_;
1114         while (1) {
1115                 print colored $prompt_color, $prompt;
1116                 my $line = prompt_single_character;
1117                 return 0 if $line =~ /^n/i;
1118                 return 1 if $line =~ /^y/i;
1119         }
1120 }
1121
1122 sub edit_hunk_loop {
1123         my ($head, $hunk, $ix) = @_;
1124         my $text = $hunk->[$ix]->{TEXT};
1125
1126         while (1) {
1127                 $text = edit_hunk_manually($text);
1128                 if (!defined $text) {
1129                         return undef;
1130                 }
1131                 my $newhunk = {
1132                         TEXT => $text,
1133                         TYPE => $hunk->[$ix]->{TYPE},
1134                         USE => 1,
1135                         DIRTY => 1,
1136                 };
1137                 if (diff_applies($head,
1138                                  @{$hunk}[0..$ix-1],
1139                                  $newhunk,
1140                                  @{$hunk}[$ix+1..$#{$hunk}])) {
1141                         $newhunk->{DISPLAY} = [color_diff(@{$text})];
1142                         return $newhunk;
1143                 }
1144                 else {
1145                         prompt_yesno(
1146                                 'Your edited hunk does not apply. Edit again '
1147                                 . '(saying "no" discards!) [y/n]? '
1148                                 ) or return undef;
1149                 }
1150         }
1151 }
1152
1153 sub help_patch_cmd {
1154         my $verb = lc $patch_mode_flavour{VERB};
1155         my $target = $patch_mode_flavour{TARGET};
1156         print colored $help_color, <<EOF ;
1157 y - $verb this hunk$target
1158 n - do not $verb this hunk$target
1159 q - quit; do not $verb this hunk nor any of the remaining ones
1160 a - $verb this hunk and all later hunks in the file
1161 d - do not $verb this hunk nor any of the later hunks in the file
1162 g - select a hunk to go to
1163 / - search for a hunk matching the given regex
1164 j - leave this hunk undecided, see next undecided hunk
1165 J - leave this hunk undecided, see next hunk
1166 k - leave this hunk undecided, see previous undecided hunk
1167 K - leave this hunk undecided, see previous hunk
1168 s - split the current hunk into smaller hunks
1169 e - manually edit the current hunk
1170 ? - print help
1171 EOF
1172 }
1173
1174 sub apply_patch {
1175         my $cmd = shift;
1176         my $ret = run_git_apply $cmd, @_;
1177         if (!$ret) {
1178                 print STDERR @_;
1179         }
1180         return $ret;
1181 }
1182
1183 sub apply_patch_for_checkout_commit {
1184         my $reverse = shift;
1185         my $applies_index = run_git_apply 'apply '.$reverse.' --cached --check', @_;
1186         my $applies_worktree = run_git_apply 'apply '.$reverse.' --check', @_;
1187
1188         if ($applies_worktree && $applies_index) {
1189                 run_git_apply 'apply '.$reverse.' --cached', @_;
1190                 run_git_apply 'apply '.$reverse, @_;
1191                 return 1;
1192         } elsif (!$applies_index) {
1193                 print colored $error_color, "The selected hunks do not apply to the index!\n";
1194                 if (prompt_yesno "Apply them to the worktree anyway? ") {
1195                         return run_git_apply 'apply '.$reverse, @_;
1196                 } else {
1197                         print colored $error_color, "Nothing was applied.\n";
1198                         return 0;
1199                 }
1200         } else {
1201                 print STDERR @_;
1202                 return 0;
1203         }
1204 }
1205
1206 sub patch_update_cmd {
1207         my @all_mods = list_modified($patch_mode_flavour{FILTER});
1208         my @mods = grep { !($_->{BINARY}) } @all_mods;
1209         my @them;
1210
1211         if (!@mods) {
1212                 if (@all_mods) {
1213                         print STDERR "Only binary files changed.\n";
1214                 } else {
1215                         print STDERR "No changes.\n";
1216                 }
1217                 return 0;
1218         }
1219         if ($patch_mode) {
1220                 @them = @mods;
1221         }
1222         else {
1223                 @them = list_and_choose({ PROMPT => 'Patch update',
1224                                           HEADER => $status_head, },
1225                                         @mods);
1226         }
1227         for (@them) {
1228                 return 0 if patch_update_file($_->{VALUE});
1229         }
1230 }
1231
1232 # Generate a one line summary of a hunk.
1233 sub summarize_hunk {
1234         my $rhunk = shift;
1235         my $summary = $rhunk->{TEXT}[0];
1236
1237         # Keep the line numbers, discard extra context.
1238         $summary =~ s/@@(.*?)@@.*/$1 /s;
1239         $summary .= " " x (20 - length $summary);
1240
1241         # Add some user context.
1242         for my $line (@{$rhunk->{TEXT}}) {
1243                 if ($line =~ m/^[+-].*\w/) {
1244                         $summary .= $line;
1245                         last;
1246                 }
1247         }
1248
1249         chomp $summary;
1250         return substr($summary, 0, 80) . "\n";
1251 }
1252
1253
1254 # Print a one-line summary of each hunk in the array ref in
1255 # the first argument, starting wih the index in the 2nd.
1256 sub display_hunks {
1257         my ($hunks, $i) = @_;
1258         my $ctr = 0;
1259         $i ||= 0;
1260         for (; $i < @$hunks && $ctr < 20; $i++, $ctr++) {
1261                 my $status = " ";
1262                 if (defined $hunks->[$i]{USE}) {
1263                         $status = $hunks->[$i]{USE} ? "+" : "-";
1264                 }
1265                 printf "%s%2d: %s",
1266                         $status,
1267                         $i + 1,
1268                         summarize_hunk($hunks->[$i]);
1269         }
1270         return $i;
1271 }
1272
1273 sub trim_error {
1274         local $_ = shift;
1275         s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1276         return $_;
1277 }
1278
1279 sub want_hunk {
1280         my $hunk = shift;
1281         my $text = join('', @{$hunk->{TEXT}});
1282
1283         foreach my $re (@patch_mode_hunk_filter) {
1284                 return !$patch_mode_negate_filter if $text =~ $re;
1285         }
1286         return $patch_mode_negate_filter;
1287 }
1288
1289 sub patch_update_file {
1290         my $quit = 0;
1291         my ($ix, $num);
1292         my $path = shift;
1293         my ($head, @hunk) = parse_diff($path);
1294
1295         if ($patch_mode_autosplit) {
1296                 @hunk = map { split_hunk($_->{TEXT}, $_->{DISPLAY}) } @hunk;
1297         }
1298
1299         if (@patch_mode_hunk_filter) {
1300                 @hunk = grep { want_hunk($_) } @hunk;
1301                 return unless @hunk;
1302         }
1303
1304         ($head, my $mode, my $deletion) = parse_diff_header($head);
1305         for (@{$head->{DISPLAY}}) {
1306                 print;
1307         }
1308
1309         if (@{$mode->{TEXT}} && !@patch_mode_hunk_filter) {
1310                 unshift @hunk, $mode;
1311         }
1312         if (@{$deletion->{TEXT}}) {
1313                 foreach my $hunk (@hunk) {
1314                         push @{$deletion->{TEXT}}, @{$hunk->{TEXT}};
1315                         push @{$deletion->{DISPLAY}}, @{$hunk->{DISPLAY}};
1316                 }
1317                 @hunk = ($deletion);
1318         }
1319
1320         $num = scalar @hunk;
1321         $ix = 0;
1322
1323         while (1) {
1324                 my ($prev, $next, $other, $undecided, $i);
1325                 $other = '';
1326
1327                 if ($num <= $ix) {
1328                         $ix = 0;
1329                 }
1330                 for ($i = 0; $i < $ix; $i++) {
1331                         if (!defined $hunk[$i]{USE}) {
1332                                 $prev = 1;
1333                                 $other .= ',k';
1334                                 last;
1335                         }
1336                 }
1337                 if ($ix) {
1338                         $other .= ',K';
1339                 }
1340                 for ($i = $ix + 1; $i < $num; $i++) {
1341                         if (!defined $hunk[$i]{USE}) {
1342                                 $next = 1;
1343                                 $other .= ',j';
1344                                 last;
1345                         }
1346                 }
1347                 if ($ix < $num - 1) {
1348                         $other .= ',J';
1349                 }
1350                 if ($num > 1) {
1351                         $other .= ',g';
1352                 }
1353                 for ($i = 0; $i < $num; $i++) {
1354                         if (!defined $hunk[$i]{USE}) {
1355                                 $undecided = 1;
1356                                 last;
1357                         }
1358                 }
1359                 last if (!$undecided);
1360
1361                 if ($hunk[$ix]{TYPE} eq 'hunk' &&
1362                     hunk_splittable($hunk[$ix]{TEXT})) {
1363                         $other .= ',s';
1364                 }
1365                 if ($hunk[$ix]{TYPE} eq 'hunk') {
1366                         $other .= ',e';
1367                 }
1368                 for (@{$hunk[$ix]{DISPLAY}}) {
1369                         print;
1370                 }
1371                 print colored $prompt_color, $patch_mode_flavour{VERB},
1372                   ($hunk[$ix]{TYPE} eq 'mode' ? ' mode change' :
1373                    $hunk[$ix]{TYPE} eq 'deletion' ? ' deletion' :
1374                    ' this hunk'),
1375                   $patch_mode_flavour{TARGET},
1376                   " [y,n,q,a,d,/$other,?]? ";
1377                 my $line = prompt_single_character;
1378                 if ($line) {
1379                         if ($line =~ /^y/i) {
1380                                 $hunk[$ix]{USE} = 1;
1381                         }
1382                         elsif ($line =~ /^n/i) {
1383                                 $hunk[$ix]{USE} = 0;
1384                         }
1385                         elsif ($line =~ /^a/i) {
1386                                 while ($ix < $num) {
1387                                         if (!defined $hunk[$ix]{USE}) {
1388                                                 $hunk[$ix]{USE} = 1;
1389                                         }
1390                                         $ix++;
1391                                 }
1392                                 next;
1393                         }
1394                         elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1395                                 my $response = $1;
1396                                 my $no = $ix > 10 ? $ix - 10 : 0;
1397                                 while ($response eq '') {
1398                                         my $extra = "";
1399                                         $no = display_hunks(\@hunk, $no);
1400                                         if ($no < $num) {
1401                                                 $extra = " (<ret> to see more)";
1402                                         }
1403                                         print "go to which hunk$extra? ";
1404                                         $response = <STDIN>;
1405                                         if (!defined $response) {
1406                                                 $response = '';
1407                                         }
1408                                         chomp $response;
1409                                 }
1410                                 if ($response !~ /^\s*\d+\s*$/) {
1411                                         error_msg "Invalid number: '$response'\n";
1412                                 } elsif (0 < $response && $response <= $num) {
1413                                         $ix = $response - 1;
1414                                 } else {
1415                                         error_msg "Sorry, only $num hunks available.\n";
1416                                 }
1417                                 next;
1418                         }
1419                         elsif ($line =~ /^d/i) {
1420                                 while ($ix < $num) {
1421                                         if (!defined $hunk[$ix]{USE}) {
1422                                                 $hunk[$ix]{USE} = 0;
1423                                         }
1424                                         $ix++;
1425                                 }
1426                                 next;
1427                         }
1428                         elsif ($line =~ /^q/i) {
1429                                 for ($i = 0; $i < $num; $i++) {
1430                                         if (!defined $hunk[$i]{USE}) {
1431                                                 $hunk[$i]{USE} = 0;
1432                                         }
1433                                 }
1434                                 $quit = 1;
1435                                 last;
1436                         }
1437                         elsif ($line =~ m|^/(.*)|) {
1438                                 my $regex = $1;
1439                                 if ($1 eq "") {
1440                                         print colored $prompt_color, "search for regex? ";
1441                                         $regex = <STDIN>;
1442                                         if (defined $regex) {
1443                                                 chomp $regex;
1444                                         }
1445                                 }
1446                                 my $search_string;
1447                                 eval {
1448                                         $search_string = qr{$regex}m;
1449                                 };
1450                                 if ($@) {
1451                                         my $exp = $1;
1452                                         error_msg "Malformed search regexp $exp: " . trim_error($@) . "\n";
1453                                         next;
1454                                 }
1455                                 my $iy = $ix;
1456                                 while (1) {
1457                                         my $text = join ("", @{$hunk[$iy]{TEXT}});
1458                                         last if ($text =~ $search_string);
1459                                         $iy++;
1460                                         $iy = 0 if ($iy >= $num);
1461                                         if ($ix == $iy) {
1462                                                 error_msg "No hunk matches the given pattern\n";
1463                                                 last;
1464                                         }
1465                                 }
1466                                 $ix = $iy;
1467                                 next;
1468                         }
1469                         elsif ($line =~ /^K/) {
1470                                 if ($other =~ /K/) {
1471                                         $ix--;
1472                                 }
1473                                 else {
1474                                         error_msg "No previous hunk\n";
1475                                 }
1476                                 next;
1477                         }
1478                         elsif ($line =~ /^J/) {
1479                                 if ($other =~ /J/) {
1480                                         $ix++;
1481                                 }
1482                                 else {
1483                                         error_msg "No next hunk\n";
1484                                 }
1485                                 next;
1486                         }
1487                         elsif ($line =~ /^k/) {
1488                                 if ($other =~ /k/) {
1489                                         while (1) {
1490                                                 $ix--;
1491                                                 last if (!$ix ||
1492                                                          !defined $hunk[$ix]{USE});
1493                                         }
1494                                 }
1495                                 else {
1496                                         error_msg "No previous hunk\n";
1497                                 }
1498                                 next;
1499                         }
1500                         elsif ($line =~ /^j/) {
1501                                 if ($other !~ /j/) {
1502                                         error_msg "No next hunk\n";
1503                                         next;
1504                                 }
1505                         }
1506                         elsif ($other =~ /s/ && $line =~ /^s/) {
1507                                 my @split = split_hunk($hunk[$ix]{TEXT}, $hunk[$ix]{DISPLAY});
1508                                 if (1 < @split) {
1509                                         print colored $header_color, "Split into ",
1510                                         scalar(@split), " hunks.\n";
1511                                 }
1512                                 splice (@hunk, $ix, 1, @split);
1513                                 $num = scalar @hunk;
1514                                 next;
1515                         }
1516                         elsif ($other =~ /e/ && $line =~ /^e/) {
1517                                 my $newhunk = edit_hunk_loop($head, \@hunk, $ix);
1518                                 if (defined $newhunk) {
1519                                         splice @hunk, $ix, 1, $newhunk;
1520                                 }
1521                         }
1522                         else {
1523                                 help_patch_cmd($other);
1524                                 next;
1525                         }
1526                         # soft increment
1527                         while (1) {
1528                                 $ix++;
1529                                 last if ($ix >= $num ||
1530                                          !defined $hunk[$ix]{USE});
1531                         }
1532                 }
1533         }
1534
1535         @hunk = coalesce_overlapping_hunks(@hunk);
1536
1537         my $n_lofs = 0;
1538         my @result = ();
1539         for (@hunk) {
1540                 if ($_->{USE}) {
1541                         push @result, @{$_->{TEXT}};
1542                 }
1543         }
1544
1545         if (@result) {
1546                 my $fh;
1547                 my @patch = reassemble_patch($head->{TEXT}, @result);
1548                 my $apply_routine = $patch_mode_flavour{APPLY};
1549                 &$apply_routine(@patch);
1550                 refresh();
1551         }
1552
1553         print "\n";
1554         return $quit;
1555 }
1556
1557 sub diff_cmd {
1558         my @mods = list_modified('index-only');
1559         @mods = grep { !($_->{BINARY}) } @mods;
1560         return if (!@mods);
1561         my (@them) = list_and_choose({ PROMPT => 'Review diff',
1562                                      IMMEDIATE => 1,
1563                                      HEADER => $status_head, },
1564                                    @mods);
1565         return if (!@them);
1566         my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
1567         system(qw(git diff -p --cached), $reference, '--',
1568                 map { $_->{VALUE} } @them);
1569 }
1570
1571 sub quit_cmd {
1572         print "Bye.\n";
1573         exit(0);
1574 }
1575
1576 sub help_cmd {
1577         print colored $help_color, <<\EOF ;
1578 status        - show paths with changes
1579 update        - add working tree state to the staged set of changes
1580 revert        - revert staged set of changes back to the HEAD version
1581 patch         - pick hunks and update selectively
1582 diff          - view diff between HEAD and index
1583 add untracked - add contents of untracked files to the staged set of changes
1584 EOF
1585 }
1586
1587 sub process_args {
1588         return unless @ARGV;
1589
1590         while (@ARGV) {
1591                 if ($ARGV[0] =~ /--patch(?:=(.*))?/) {
1592                         $patch_mode = defined $1 ? $1 : 'stage';
1593                 }
1594                 elsif ($ARGV[0] =~ /--hunk-filter=(.*)/) {
1595                         my $re = eval { qr{$1}m }
1596                                 or die "malformed hunk filter $1: " . trim_error($@);
1597                         push @patch_mode_hunk_filter, $re;
1598                 }
1599                 elsif ($ARGV[0] eq '--negate-hunk-filter') {
1600                         $patch_mode_negate_filter = 1;
1601                 }
1602                 elsif ($ARGV[0] eq '--split-hunks') {
1603                         $patch_mode_autosplit = 1;
1604                 }
1605                 else {
1606                         last;
1607                 }
1608                 shift @ARGV;
1609         }
1610
1611         if (@ARGV && $ARGV[0] ne '--') {
1612                 $patch_mode_revision = shift @ARGV;
1613         }
1614         @ARGV or die "missing --";
1615         shift @ARGV;
1616
1617         if (defined $patch_mode) {
1618                 my $mode = $patch_modes{$patch_mode}
1619                         or die "unknown --patch mode: $patch_mode";
1620
1621                 my $submode;
1622                 if (!defined $patch_mode_revision) {
1623                         $submode = $mode->{default};
1624                         if ($submode eq 'head') {
1625                                 $patch_mode_revision = 'HEAD';
1626                         }
1627                 }
1628                 elsif ($patch_mode_revision eq 'HEAD') {
1629                         $submode = 'head';
1630                 }
1631                 else {
1632                         $submode = 'nothead';
1633                 }
1634
1635                 if (!exists $mode->{$submode}) {
1636                         die "mode '$patch_mode' cannot handle '$submode'";
1637                 }
1638                 %patch_mode_flavour = %{$mode->{$submode}};
1639         }
1640 }
1641
1642 sub main_loop {
1643         my @cmd = ([ 'status', \&status_cmd, ],
1644                    [ 'update', \&update_cmd, ],
1645                    [ 'revert', \&revert_cmd, ],
1646                    [ 'add untracked', \&add_untracked_cmd, ],
1647                    [ 'patch', \&patch_update_cmd, ],
1648                    [ 'diff', \&diff_cmd, ],
1649                    [ 'quit', \&quit_cmd, ],
1650                    [ 'help', \&help_cmd, ],
1651         );
1652         while (1) {
1653                 my ($it) = list_and_choose({ PROMPT => 'What now',
1654                                              SINGLETON => 1,
1655                                              LIST_FLAT => 4,
1656                                              HEADER => '*** Commands ***',
1657                                              ON_EOF => \&quit_cmd,
1658                                              IMMEDIATE => 1 }, @cmd);
1659                 if ($it) {
1660                         eval {
1661                                 $it->[1]->();
1662                         };
1663                         if ($@) {
1664                                 print "$@";
1665                         }
1666                 }
1667         }
1668 }
1669
1670 process_args();
1671 refresh();
1672 if ($patch_mode) {
1673         patch_update_cmd();
1674 }
1675 else {
1676         status_cmd();
1677         main_loop();
1678 }