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