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