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