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