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