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