23fd2f741b8f2aec35f65239499b967aeb4499d2
   1#!/usr/bin/perl -w
   2
   3use strict;
   4
   5# command line options
   6my $patch_mode;
   7
   8sub run_cmd_pipe {
   9        if ($^O eq 'MSWin32') {
  10                my @invalid = grep {m/[":*]/} @_;
  11                die "$^O does not support: @invalid\n" if @invalid;
  12                my @args = map { m/ /o ? "\"$_\"": $_ } @_;
  13                return qx{@args};
  14        } else {
  15                my $fh = undef;
  16                open($fh, '-|', @_) or die;
  17                return <$fh>;
  18        }
  19}
  20
  21my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));
  22
  23if (!defined $GIT_DIR) {
  24        exit(1); # rev-parse would have already said "not a git repo"
  25}
  26chomp($GIT_DIR);
  27
  28sub refresh {
  29        my $fh;
  30        open $fh, 'git update-index --refresh |'
  31            or die;
  32        while (<$fh>) {
  33                ;# ignore 'needs update'
  34        }
  35        close $fh;
  36}
  37
  38sub list_untracked {
  39        map {
  40                chomp $_;
  41                $_;
  42        }
  43        run_cmd_pipe(qw(git ls-files --others --exclude-standard --), @ARGV);
  44}
  45
  46my $status_fmt = '%12s %12s %s';
  47my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
  48
  49# Returns list of hashes, contents of each of which are:
  50# VALUE:        pathname
  51# BINARY:       is a binary path
  52# INDEX:        is index different from HEAD?
  53# FILE:         is file different from index?
  54# INDEX_ADDDEL: is it add/delete between HEAD and index?
  55# FILE_ADDDEL:  is it add/delete between index and file?
  56
  57sub list_modified {
  58        my ($only) = @_;
  59        my (%data, @return);
  60        my ($add, $del, $adddel, $file);
  61        my @tracked = ();
  62
  63        if (@ARGV) {
  64                @tracked = map {
  65                        chomp $_; $_;
  66                } run_cmd_pipe(qw(git ls-files --exclude-standard --), @ARGV);
  67                return if (!@tracked);
  68        }
  69
  70        for (run_cmd_pipe(qw(git diff-index --cached
  71                             --numstat --summary HEAD --), @tracked)) {
  72                if (($add, $del, $file) =
  73                    /^([-\d]+)  ([-\d]+)        (.*)/) {
  74                        my ($change, $bin);
  75                        if ($add eq '-' && $del eq '-') {
  76                                $change = 'binary';
  77                                $bin = 1;
  78                        }
  79                        else {
  80                                $change = "+$add/-$del";
  81                        }
  82                        $data{$file} = {
  83                                INDEX => $change,
  84                                BINARY => $bin,
  85                                FILE => 'nothing',
  86                        }
  87                }
  88                elsif (($adddel, $file) =
  89                       /^ (create|delete) mode [0-7]+ (.*)$/) {
  90                        $data{$file}{INDEX_ADDDEL} = $adddel;
  91                }
  92        }
  93
  94        for (run_cmd_pipe(qw(git diff-files --numstat --summary --), @tracked)) {
  95                if (($add, $del, $file) =
  96                    /^([-\d]+)  ([-\d]+)        (.*)/) {
  97                        if (!exists $data{$file}) {
  98                                $data{$file} = +{
  99                                        INDEX => 'unchanged',
 100                                        BINARY => 0,
 101                                };
 102                        }
 103                        my ($change, $bin);
 104                        if ($add eq '-' && $del eq '-') {
 105                                $change = 'binary';
 106                                $bin = 1;
 107                        }
 108                        else {
 109                                $change = "+$add/-$del";
 110                        }
 111                        $data{$file}{FILE} = $change;
 112                        if ($bin) {
 113                                $data{$file}{BINARY} = 1;
 114                        }
 115                }
 116                elsif (($adddel, $file) =
 117                       /^ (create|delete) mode [0-7]+ (.*)$/) {
 118                        $data{$file}{FILE_ADDDEL} = $adddel;
 119                }
 120        }
 121
 122        for (sort keys %data) {
 123                my $it = $data{$_};
 124
 125                if ($only) {
 126                        if ($only eq 'index-only') {
 127                                next if ($it->{INDEX} eq 'unchanged');
 128                        }
 129                        if ($only eq 'file-only') {
 130                                next if ($it->{FILE} eq 'nothing');
 131                        }
 132                }
 133                push @return, +{
 134                        VALUE => $_,
 135                        %$it,
 136                };
 137        }
 138        return @return;
 139}
 140
 141sub find_unique {
 142        my ($string, @stuff) = @_;
 143        my $found = undef;
 144        for (my $i = 0; $i < @stuff; $i++) {
 145                my $it = $stuff[$i];
 146                my $hit = undef;
 147                if (ref $it) {
 148                        if ((ref $it) eq 'ARRAY') {
 149                                $it = $it->[0];
 150                        }
 151                        else {
 152                                $it = $it->{VALUE};
 153                        }
 154                }
 155                eval {
 156                        if ($it =~ /^$string/) {
 157                                $hit = 1;
 158                        };
 159                };
 160                if (defined $hit && defined $found) {
 161                        return undef;
 162                }
 163                if ($hit) {
 164                        $found = $i + 1;
 165                }
 166        }
 167        return $found;
 168}
 169
 170# inserts string into trie and updates count for each character
 171sub update_trie {
 172        my ($trie, $string) = @_;
 173        foreach (split //, $string) {
 174                $trie = $trie->{$_} ||= {COUNT => 0};
 175                $trie->{COUNT}++;
 176        }
 177}
 178
 179# returns an array of tuples (prefix, remainder)
 180sub find_unique_prefixes {
 181        my @stuff = @_;
 182        my @return = ();
 183
 184        # any single prefix exceeding the soft limit is omitted
 185        # if any prefix exceeds the hard limit all are omitted
 186        # 0 indicates no limit
 187        my $soft_limit = 0;
 188        my $hard_limit = 3;
 189
 190        # build a trie modelling all possible options
 191        my %trie;
 192        foreach my $print (@stuff) {
 193                if ((ref $print) eq 'ARRAY') {
 194                        $print = $print->[0];
 195                }
 196                else {
 197                        $print = $print->{VALUE};
 198                }
 199                update_trie(\%trie, $print);
 200                push @return, $print;
 201        }
 202
 203        # use the trie to find the unique prefixes
 204        for (my $i = 0; $i < @return; $i++) {
 205                my $ret = $return[$i];
 206                my @letters = split //, $ret;
 207                my %search = %trie;
 208                my ($prefix, $remainder);
 209                my $j;
 210                for ($j = 0; $j < @letters; $j++) {
 211                        my $letter = $letters[$j];
 212                        if ($search{$letter}{COUNT} == 1) {
 213                                $prefix = substr $ret, 0, $j + 1;
 214                                $remainder = substr $ret, $j + 1;
 215                                last;
 216                        }
 217                        else {
 218                                my $prefix = substr $ret, 0, $j;
 219                                return ()
 220                                    if ($hard_limit && $j + 1 > $hard_limit);
 221                        }
 222                        %search = %{$search{$letter}};
 223                }
 224                if ($soft_limit && $j + 1 > $soft_limit) {
 225                        $prefix = undef;
 226                        $remainder = $ret;
 227                }
 228                $return[$i] = [$prefix, $remainder];
 229        }
 230        return @return;
 231}
 232
 233# given a prefix/remainder tuple return a string with the prefix highlighted
 234# for now use square brackets; later might use ANSI colors (underline, bold)
 235sub highlight_prefix {
 236        my $prefix = shift;
 237        my $remainder = shift;
 238        return (defined $prefix) ? "[$prefix]$remainder" : $remainder;
 239}
 240
 241sub list_and_choose {
 242        my ($opts, @stuff) = @_;
 243        my (@chosen, @return);
 244        my $i;
 245        my @prefixes = find_unique_prefixes(@stuff) unless $opts->{LIST_ONLY};
 246
 247      TOPLOOP:
 248        while (1) {
 249                my $last_lf = 0;
 250
 251                if ($opts->{HEADER}) {
 252                        if (!$opts->{LIST_FLAT}) {
 253                                print "     ";
 254                        }
 255                        print "$opts->{HEADER}\n";
 256                }
 257                for ($i = 0; $i < @stuff; $i++) {
 258                        my $chosen = $chosen[$i] ? '*' : ' ';
 259                        my $print = $stuff[$i];
 260                        if (ref $print) {
 261                                if ((ref $print) eq 'ARRAY') {
 262                                        $print = @prefixes ?
 263                                            highlight_prefix(@{$prefixes[$i]}) :
 264                                            $print->[0];
 265                                }
 266                                else {
 267                                        my $value = @prefixes ?
 268                                            highlight_prefix(@{$prefixes[$i]}) :
 269                                            $print->{VALUE};
 270                                        $print = sprintf($status_fmt,
 271                                            $print->{INDEX},
 272                                            $print->{FILE},
 273                                            $value);
 274                                }
 275                        }
 276                        printf("%s%2d: %s", $chosen, $i+1, $print);
 277                        if (($opts->{LIST_FLAT}) &&
 278                            (($i + 1) % ($opts->{LIST_FLAT}))) {
 279                                print "\t";
 280                                $last_lf = 0;
 281                        }
 282                        else {
 283                                print "\n";
 284                                $last_lf = 1;
 285                        }
 286                }
 287                if (!$last_lf) {
 288                        print "\n";
 289                }
 290
 291                return if ($opts->{LIST_ONLY});
 292
 293                print $opts->{PROMPT};
 294                if ($opts->{SINGLETON}) {
 295                        print "> ";
 296                }
 297                else {
 298                        print ">> ";
 299                }
 300                my $line = <STDIN>;
 301                if (!$line) {
 302                        print "\n";
 303                        $opts->{ON_EOF}->() if $opts->{ON_EOF};
 304                        last;
 305                }
 306                chomp $line;
 307                last if $line eq '';
 308                for my $choice (split(/[\s,]+/, $line)) {
 309                        my $choose = 1;
 310                        my ($bottom, $top);
 311
 312                        # Input that begins with '-'; unchoose
 313                        if ($choice =~ s/^-//) {
 314                                $choose = 0;
 315                        }
 316                        # A range can be specified like 5-7
 317                        if ($choice =~ /^(\d+)-(\d+)$/) {
 318                                ($bottom, $top) = ($1, $2);
 319                        }
 320                        elsif ($choice =~ /^\d+$/) {
 321                                $bottom = $top = $choice;
 322                        }
 323                        elsif ($choice eq '*') {
 324                                $bottom = 1;
 325                                $top = 1 + @stuff;
 326                        }
 327                        else {
 328                                $bottom = $top = find_unique($choice, @stuff);
 329                                if (!defined $bottom) {
 330                                        print "Huh ($choice)?\n";
 331                                        next TOPLOOP;
 332                                }
 333                        }
 334                        if ($opts->{SINGLETON} && $bottom != $top) {
 335                                print "Huh ($choice)?\n";
 336                                next TOPLOOP;
 337                        }
 338                        for ($i = $bottom-1; $i <= $top-1; $i++) {
 339                                next if (@stuff <= $i || $i < 0);
 340                                $chosen[$i] = $choose;
 341                        }
 342                }
 343                last if ($opts->{IMMEDIATE} || $line eq '*');
 344        }
 345        for ($i = 0; $i < @stuff; $i++) {
 346                if ($chosen[$i]) {
 347                        push @return, $stuff[$i];
 348                }
 349        }
 350        return @return;
 351}
 352
 353sub status_cmd {
 354        list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
 355                        list_modified());
 356        print "\n";
 357}
 358
 359sub say_n_paths {
 360        my $did = shift @_;
 361        my $cnt = scalar @_;
 362        print "$did ";
 363        if (1 < $cnt) {
 364                print "$cnt paths\n";
 365        }
 366        else {
 367                print "one path\n";
 368        }
 369}
 370
 371sub update_cmd {
 372        my @mods = list_modified('file-only');
 373        return if (!@mods);
 374
 375        my @update = list_and_choose({ PROMPT => 'Update',
 376                                       HEADER => $status_head, },
 377                                     @mods);
 378        if (@update) {
 379                system(qw(git update-index --add --remove --),
 380                       map { $_->{VALUE} } @update);
 381                say_n_paths('updated', @update);
 382        }
 383        print "\n";
 384}
 385
 386sub revert_cmd {
 387        my @update = list_and_choose({ PROMPT => 'Revert',
 388                                       HEADER => $status_head, },
 389                                     list_modified());
 390        if (@update) {
 391                my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
 392                                         map { $_->{VALUE} } @update);
 393                my $fh;
 394                open $fh, '| git update-index --index-info'
 395                    or die;
 396                for (@lines) {
 397                        print $fh $_;
 398                }
 399                close($fh);
 400                for (@update) {
 401                        if ($_->{INDEX_ADDDEL} &&
 402                            $_->{INDEX_ADDDEL} eq 'create') {
 403                                system(qw(git update-index --force-remove --),
 404                                       $_->{VALUE});
 405                                print "note: $_->{VALUE} is untracked now.\n";
 406                        }
 407                }
 408                refresh();
 409                say_n_paths('reverted', @update);
 410        }
 411        print "\n";
 412}
 413
 414sub add_untracked_cmd {
 415        my @add = list_and_choose({ PROMPT => 'Add untracked' },
 416                                  list_untracked());
 417        if (@add) {
 418                system(qw(git update-index --add --), @add);
 419                say_n_paths('added', @add);
 420        }
 421        print "\n";
 422}
 423
 424sub parse_diff {
 425        my ($path) = @_;
 426        my @diff = run_cmd_pipe(qw(git diff-files -p --), $path);
 427        my (@hunk) = { TEXT => [] };
 428
 429        for (@diff) {
 430                if (/^@@ /) {
 431                        push @hunk, { TEXT => [] };
 432                }
 433                push @{$hunk[-1]{TEXT}}, $_;
 434        }
 435        return @hunk;
 436}
 437
 438sub hunk_splittable {
 439        my ($text) = @_;
 440
 441        my @s = split_hunk($text);
 442        return (1 < @s);
 443}
 444
 445sub parse_hunk_header {
 446        my ($line) = @_;
 447        my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
 448            $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
 449        $o_cnt = 1 unless defined $o_cnt;
 450        $n_cnt = 1 unless defined $n_cnt;
 451        return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
 452}
 453
 454sub split_hunk {
 455        my ($text) = @_;
 456        my @split = ();
 457
 458        # If there are context lines in the middle of a hunk,
 459        # it can be split, but we would need to take care of
 460        # overlaps later.
 461
 462        my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
 463        my $hunk_start = 1;
 464
 465      OUTER:
 466        while (1) {
 467                my $next_hunk_start = undef;
 468                my $i = $hunk_start - 1;
 469                my $this = +{
 470                        TEXT => [],
 471                        OLD => $o_ofs,
 472                        NEW => $n_ofs,
 473                        OCNT => 0,
 474                        NCNT => 0,
 475                        ADDDEL => 0,
 476                        POSTCTX => 0,
 477                };
 478
 479                while (++$i < @$text) {
 480                        my $line = $text->[$i];
 481                        if ($line =~ /^ /) {
 482                                if ($this->{ADDDEL} &&
 483                                    !defined $next_hunk_start) {
 484                                        # We have seen leading context and
 485                                        # adds/dels and then here is another
 486                                        # context, which is trailing for this
 487                                        # split hunk and leading for the next
 488                                        # one.
 489                                        $next_hunk_start = $i;
 490                                }
 491                                push @{$this->{TEXT}}, $line;
 492                                $this->{OCNT}++;
 493                                $this->{NCNT}++;
 494                                if (defined $next_hunk_start) {
 495                                        $this->{POSTCTX}++;
 496                                }
 497                                next;
 498                        }
 499
 500                        # add/del
 501                        if (defined $next_hunk_start) {
 502                                # We are done with the current hunk and
 503                                # this is the first real change for the
 504                                # next split one.
 505                                $hunk_start = $next_hunk_start;
 506                                $o_ofs = $this->{OLD} + $this->{OCNT};
 507                                $n_ofs = $this->{NEW} + $this->{NCNT};
 508                                $o_ofs -= $this->{POSTCTX};
 509                                $n_ofs -= $this->{POSTCTX};
 510                                push @split, $this;
 511                                redo OUTER;
 512                        }
 513                        push @{$this->{TEXT}}, $line;
 514                        $this->{ADDDEL}++;
 515                        if ($line =~ /^-/) {
 516                                $this->{OCNT}++;
 517                        }
 518                        else {
 519                                $this->{NCNT}++;
 520                        }
 521                }
 522
 523                push @split, $this;
 524                last;
 525        }
 526
 527        for my $hunk (@split) {
 528                $o_ofs = $hunk->{OLD};
 529                $n_ofs = $hunk->{NEW};
 530                my $o_cnt = $hunk->{OCNT};
 531                my $n_cnt = $hunk->{NCNT};
 532
 533                my $head = ("@@ -$o_ofs" .
 534                            (($o_cnt != 1) ? ",$o_cnt" : '') .
 535                            " +$n_ofs" .
 536                            (($n_cnt != 1) ? ",$n_cnt" : '') .
 537                            " @@\n");
 538                unshift @{$hunk->{TEXT}}, $head;
 539        }
 540        return map { $_->{TEXT} } @split;
 541}
 542
 543sub find_last_o_ctx {
 544        my ($it) = @_;
 545        my $text = $it->{TEXT};
 546        my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
 547        my $i = @{$text};
 548        my $last_o_ctx = $o_ofs + $o_cnt;
 549        while (0 < --$i) {
 550                my $line = $text->[$i];
 551                if ($line =~ /^ /) {
 552                        $last_o_ctx--;
 553                        next;
 554                }
 555                last;
 556        }
 557        return $last_o_ctx;
 558}
 559
 560sub merge_hunk {
 561        my ($prev, $this) = @_;
 562        my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
 563            parse_hunk_header($prev->{TEXT}[0]);
 564        my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
 565            parse_hunk_header($this->{TEXT}[0]);
 566
 567        my (@line, $i, $ofs, $o_cnt, $n_cnt);
 568        $ofs = $o0_ofs;
 569        $o_cnt = $n_cnt = 0;
 570        for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
 571                my $line = $prev->{TEXT}[$i];
 572                if ($line =~ /^\+/) {
 573                        $n_cnt++;
 574                        push @line, $line;
 575                        next;
 576                }
 577
 578                last if ($o1_ofs <= $ofs);
 579
 580                $o_cnt++;
 581                $ofs++;
 582                if ($line =~ /^ /) {
 583                        $n_cnt++;
 584                }
 585                push @line, $line;
 586        }
 587
 588        for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
 589                my $line = $this->{TEXT}[$i];
 590                if ($line =~ /^\+/) {
 591                        $n_cnt++;
 592                        push @line, $line;
 593                        next;
 594                }
 595                $ofs++;
 596                $o_cnt++;
 597                if ($line =~ /^ /) {
 598                        $n_cnt++;
 599                }
 600                push @line, $line;
 601        }
 602        my $head = ("@@ -$o0_ofs" .
 603                    (($o_cnt != 1) ? ",$o_cnt" : '') .
 604                    " +$n0_ofs" .
 605                    (($n_cnt != 1) ? ",$n_cnt" : '') .
 606                    " @@\n");
 607        @{$prev->{TEXT}} = ($head, @line);
 608}
 609
 610sub coalesce_overlapping_hunks {
 611        my (@in) = @_;
 612        my @out = ();
 613
 614        my ($last_o_ctx);
 615
 616        for (grep { $_->{USE} } @in) {
 617                my $text = $_->{TEXT};
 618                my ($o_ofs) = parse_hunk_header($text->[0]);
 619                if (defined $last_o_ctx &&
 620                    $o_ofs <= $last_o_ctx) {
 621                        merge_hunk($out[-1], $_);
 622                }
 623                else {
 624                        push @out, $_;
 625                }
 626                $last_o_ctx = find_last_o_ctx($out[-1]);
 627        }
 628        return @out;
 629}
 630
 631sub help_patch_cmd {
 632        print <<\EOF ;
 633y - stage this hunk
 634n - do not stage this hunk
 635a - stage this and all the remaining hunks in the file
 636d - do not stage this hunk nor any of the remaining hunks in the file
 637j - leave this hunk undecided, see next undecided hunk
 638J - leave this hunk undecided, see next hunk
 639k - leave this hunk undecided, see previous undecided hunk
 640K - leave this hunk undecided, see previous hunk
 641s - split the current hunk into smaller hunks
 642? - print help
 643EOF
 644}
 645
 646sub patch_update_cmd {
 647        my @mods = grep { !($_->{BINARY}) } list_modified('file-only');
 648        my @them;
 649
 650        if (!@mods) {
 651                print STDERR "No changes.\n";
 652                return 0;
 653        }
 654        if ($patch_mode) {
 655                @them = @mods;
 656        }
 657        else {
 658                @them = list_and_choose({ PROMPT => 'Patch update',
 659                                          HEADER => $status_head, },
 660                                        @mods);
 661        }
 662        for (@them) {
 663                patch_update_file($_->{VALUE});
 664        }
 665}
 666
 667sub patch_update_file {
 668        my ($ix, $num);
 669        my $path = shift;
 670        my ($head, @hunk) = parse_diff($path);
 671        for (@{$head->{TEXT}}) {
 672                print;
 673        }
 674        $num = scalar @hunk;
 675        $ix = 0;
 676
 677        while (1) {
 678                my ($prev, $next, $other, $undecided, $i);
 679                $other = '';
 680
 681                if ($num <= $ix) {
 682                        $ix = 0;
 683                }
 684                for ($i = 0; $i < $ix; $i++) {
 685                        if (!defined $hunk[$i]{USE}) {
 686                                $prev = 1;
 687                                $other .= '/k';
 688                                last;
 689                        }
 690                }
 691                if ($ix) {
 692                        $other .= '/K';
 693                }
 694                for ($i = $ix + 1; $i < $num; $i++) {
 695                        if (!defined $hunk[$i]{USE}) {
 696                                $next = 1;
 697                                $other .= '/j';
 698                                last;
 699                        }
 700                }
 701                if ($ix < $num - 1) {
 702                        $other .= '/J';
 703                }
 704                for ($i = 0; $i < $num; $i++) {
 705                        if (!defined $hunk[$i]{USE}) {
 706                                $undecided = 1;
 707                                last;
 708                        }
 709                }
 710                last if (!$undecided);
 711
 712                if (hunk_splittable($hunk[$ix]{TEXT})) {
 713                        $other .= '/s';
 714                }
 715                for (@{$hunk[$ix]{TEXT}}) {
 716                        print;
 717                }
 718                print "Stage this hunk [y/n/a/d$other/?]? ";
 719                my $line = <STDIN>;
 720                if ($line) {
 721                        if ($line =~ /^y/i) {
 722                                $hunk[$ix]{USE} = 1;
 723                        }
 724                        elsif ($line =~ /^n/i) {
 725                                $hunk[$ix]{USE} = 0;
 726                        }
 727                        elsif ($line =~ /^a/i) {
 728                                while ($ix < $num) {
 729                                        if (!defined $hunk[$ix]{USE}) {
 730                                                $hunk[$ix]{USE} = 1;
 731                                        }
 732                                        $ix++;
 733                                }
 734                                next;
 735                        }
 736                        elsif ($line =~ /^d/i) {
 737                                while ($ix < $num) {
 738                                        if (!defined $hunk[$ix]{USE}) {
 739                                                $hunk[$ix]{USE} = 0;
 740                                        }
 741                                        $ix++;
 742                                }
 743                                next;
 744                        }
 745                        elsif ($other =~ /K/ && $line =~ /^K/) {
 746                                $ix--;
 747                                next;
 748                        }
 749                        elsif ($other =~ /J/ && $line =~ /^J/) {
 750                                $ix++;
 751                                next;
 752                        }
 753                        elsif ($other =~ /k/ && $line =~ /^k/) {
 754                                while (1) {
 755                                        $ix--;
 756                                        last if (!$ix ||
 757                                                 !defined $hunk[$ix]{USE});
 758                                }
 759                                next;
 760                        }
 761                        elsif ($other =~ /j/ && $line =~ /^j/) {
 762                                while (1) {
 763                                        $ix++;
 764                                        last if ($ix >= $num ||
 765                                                 !defined $hunk[$ix]{USE});
 766                                }
 767                                next;
 768                        }
 769                        elsif ($other =~ /s/ && $line =~ /^s/) {
 770                                my @split = split_hunk($hunk[$ix]{TEXT});
 771                                if (1 < @split) {
 772                                        print "Split into ",
 773                                        scalar(@split), " hunks.\n";
 774                                }
 775                                splice(@hunk, $ix, 1,
 776                                       map { +{ TEXT => $_, USE => undef } }
 777                                       @split);
 778                                $num = scalar @hunk;
 779                                next;
 780                        }
 781                        else {
 782                                help_patch_cmd($other);
 783                                next;
 784                        }
 785                        # soft increment
 786                        while (1) {
 787                                $ix++;
 788                                last if ($ix >= $num ||
 789                                         !defined $hunk[$ix]{USE});
 790                        }
 791                }
 792        }
 793
 794        @hunk = coalesce_overlapping_hunks(@hunk);
 795
 796        my $n_lofs = 0;
 797        my @result = ();
 798        for (@hunk) {
 799                my $text = $_->{TEXT};
 800                my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
 801                    parse_hunk_header($text->[0]);
 802
 803                if (!$_->{USE}) {
 804                        # We would have added ($n_cnt - $o_cnt) lines
 805                        # to the postimage if we were to use this hunk,
 806                        # but we didn't.  So the line number that the next
 807                        # hunk starts at would be shifted by that much.
 808                        $n_lofs -= ($n_cnt - $o_cnt);
 809                        next;
 810                }
 811                else {
 812                        if ($n_lofs) {
 813                                $n_ofs += $n_lofs;
 814                                $text->[0] = ("@@ -$o_ofs" .
 815                                              (($o_cnt != 1)
 816                                               ? ",$o_cnt" : '') .
 817                                              " +$n_ofs" .
 818                                              (($n_cnt != 1)
 819                                               ? ",$n_cnt" : '') .
 820                                              " @@\n");
 821                        }
 822                        for (@$text) {
 823                                push @result, $_;
 824                        }
 825                }
 826        }
 827
 828        if (@result) {
 829                my $fh;
 830
 831                open $fh, '| git apply --cached';
 832                for (@{$head->{TEXT}}, @result) {
 833                        print $fh $_;
 834                }
 835                if (!close $fh) {
 836                        for (@{$head->{TEXT}}, @result) {
 837                                print STDERR $_;
 838                        }
 839                }
 840                refresh();
 841        }
 842
 843        print "\n";
 844}
 845
 846sub diff_cmd {
 847        my @mods = list_modified('index-only');
 848        @mods = grep { !($_->{BINARY}) } @mods;
 849        return if (!@mods);
 850        my (@them) = list_and_choose({ PROMPT => 'Review diff',
 851                                     IMMEDIATE => 1,
 852                                     HEADER => $status_head, },
 853                                   @mods);
 854        return if (!@them);
 855        system(qw(git diff-index -p --cached HEAD --),
 856               map { $_->{VALUE} } @them);
 857}
 858
 859sub quit_cmd {
 860        print "Bye.\n";
 861        exit(0);
 862}
 863
 864sub help_cmd {
 865        print <<\EOF ;
 866status        - show paths with changes
 867update        - add working tree state to the staged set of changes
 868revert        - revert staged set of changes back to the HEAD version
 869patch         - pick hunks and update selectively
 870diff          - view diff between HEAD and index
 871add untracked - add contents of untracked files to the staged set of changes
 872EOF
 873}
 874
 875sub process_args {
 876        return unless @ARGV;
 877        my $arg = shift @ARGV;
 878        if ($arg eq "--patch") {
 879                $patch_mode = 1;
 880                $arg = shift @ARGV or die "missing --";
 881                die "invalid argument $arg, expecting --"
 882                    unless $arg eq "--";
 883        }
 884        elsif ($arg ne "--") {
 885                die "invalid argument $arg, expecting --";
 886        }
 887}
 888
 889sub main_loop {
 890        my @cmd = ([ 'status', \&status_cmd, ],
 891                   [ 'update', \&update_cmd, ],
 892                   [ 'revert', \&revert_cmd, ],
 893                   [ 'add untracked', \&add_untracked_cmd, ],
 894                   [ 'patch', \&patch_update_cmd, ],
 895                   [ 'diff', \&diff_cmd, ],
 896                   [ 'quit', \&quit_cmd, ],
 897                   [ 'help', \&help_cmd, ],
 898        );
 899        while (1) {
 900                my ($it) = list_and_choose({ PROMPT => 'What now',
 901                                             SINGLETON => 1,
 902                                             LIST_FLAT => 4,
 903                                             HEADER => '*** Commands ***',
 904                                             ON_EOF => \&quit_cmd,
 905                                             IMMEDIATE => 1 }, @cmd);
 906                if ($it) {
 907                        eval {
 908                                $it->[1]->();
 909                        };
 910                        if ($@) {
 911                                print "$@";
 912                        }
 913                }
 914        }
 915}
 916
 917process_args();
 918refresh();
 919if ($patch_mode) {
 920        patch_update_cmd();
 921}
 922else {
 923        status_cmd();
 924        main_loop();
 925}