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