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