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