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