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