make add -i easier to use with large numbers of files
[git/bebarino.git] / git-add--interactive.perl
blob4c3dcc9e237c8129c9fecea802cd05d7cb98b282
1 #!/usr/bin/perl
3 use 5.008;
4 use strict;
5 use warnings;
6 use Git;
8 binmode(STDOUT, ":raw");
10 my $repo = Git->repository();
12 my $menu_use_color = $repo->get_colorbool('color.interactive');
13 my ($prompt_color, $header_color, $help_color) =
14 $menu_use_color ? (
15 $repo->get_color('color.interactive.prompt', 'bold blue'),
16 $repo->get_color('color.interactive.header', 'bold'),
17 $repo->get_color('color.interactive.help', 'red bold'),
18 ) : ();
19 my $error_color = ();
20 if ($menu_use_color) {
21 my $help_color_spec = ($repo->config('color.interactive.help') or
22 'red bold');
23 $error_color = $repo->get_color('color.interactive.error',
24 $help_color_spec);
27 my $diff_use_color = $repo->get_colorbool('color.diff');
28 my ($fraginfo_color) =
29 $diff_use_color ? (
30 $repo->get_color('color.diff.frag', 'cyan'),
31 ) : ();
32 my ($diff_plain_color) =
33 $diff_use_color ? (
34 $repo->get_color('color.diff.plain', ''),
35 ) : ();
36 my ($diff_old_color) =
37 $diff_use_color ? (
38 $repo->get_color('color.diff.old', 'red'),
39 ) : ();
40 my ($diff_new_color) =
41 $diff_use_color ? (
42 $repo->get_color('color.diff.new', 'green'),
43 ) : ();
45 my $normal_color = $repo->get_color("", "reset");
47 my $use_readkey = 0;
48 sub ReadMode;
49 sub ReadKey;
50 if ($repo->config_bool("interactive.singlekey")) {
51 eval {
52 require Term::ReadKey;
53 Term::ReadKey->import;
54 $use_readkey = 1;
58 sub colored {
59 my $color = shift;
60 my $string = join("", @_);
62 if (defined $color) {
63 # Put a color code at the beginning of each line, a reset at the end
64 # color after newlines that are not at the end of the string
65 $string =~ s/(\n+)(.)/$1$color$2/g;
66 # reset before newlines
67 $string =~ s/(\n+)/$normal_color$1/g;
68 # codes at beginning and end (if necessary):
69 $string =~ s/^/$color/;
70 $string =~ s/$/$normal_color/ unless $string =~ /\n$/;
72 return $string;
75 # command line options
76 my $patch_mode;
77 my $patch_mode_revision;
79 sub apply_patch;
80 sub apply_patch_for_checkout_commit;
81 sub apply_patch_for_stash;
83 my %patch_modes = (
84 'stage' => {
85 DIFF => 'diff-files -p',
86 APPLY => sub { apply_patch 'apply --cached', @_; },
87 APPLY_CHECK => 'apply --cached',
88 VERB => 'Stage',
89 TARGET => '',
90 PARTICIPLE => 'staging',
91 FILTER => 'file-only',
92 IS_REVERSE => 0,
94 'stash' => {
95 DIFF => 'diff-index -p HEAD',
96 APPLY => sub { apply_patch 'apply --cached', @_; },
97 APPLY_CHECK => 'apply --cached',
98 VERB => 'Stash',
99 TARGET => '',
100 PARTICIPLE => 'stashing',
101 FILTER => undef,
102 IS_REVERSE => 0,
104 'reset_head' => {
105 DIFF => 'diff-index -p --cached',
106 APPLY => sub { apply_patch 'apply -R --cached', @_; },
107 APPLY_CHECK => 'apply -R --cached',
108 VERB => 'Unstage',
109 TARGET => '',
110 PARTICIPLE => 'unstaging',
111 FILTER => 'index-only',
112 IS_REVERSE => 1,
114 'reset_nothead' => {
115 DIFF => 'diff-index -R -p --cached',
116 APPLY => sub { apply_patch 'apply --cached', @_; },
117 APPLY_CHECK => 'apply --cached',
118 VERB => 'Apply',
119 TARGET => ' to index',
120 PARTICIPLE => 'applying',
121 FILTER => 'index-only',
122 IS_REVERSE => 0,
124 'checkout_index' => {
125 DIFF => 'diff-files -p',
126 APPLY => sub { apply_patch 'apply -R', @_; },
127 APPLY_CHECK => 'apply -R',
128 VERB => 'Discard',
129 TARGET => ' from worktree',
130 PARTICIPLE => 'discarding',
131 FILTER => 'file-only',
132 IS_REVERSE => 1,
134 'checkout_head' => {
135 DIFF => 'diff-index -p',
136 APPLY => sub { apply_patch_for_checkout_commit '-R', @_ },
137 APPLY_CHECK => 'apply -R',
138 VERB => 'Discard',
139 TARGET => ' from index and worktree',
140 PARTICIPLE => 'discarding',
141 FILTER => undef,
142 IS_REVERSE => 1,
144 'checkout_nothead' => {
145 DIFF => 'diff-index -R -p',
146 APPLY => sub { apply_patch_for_checkout_commit '', @_ },
147 APPLY_CHECK => 'apply',
148 VERB => 'Apply',
149 TARGET => ' to index and worktree',
150 PARTICIPLE => 'applying',
151 FILTER => undef,
152 IS_REVERSE => 0,
156 my %patch_mode_flavour = %{$patch_modes{stage}};
158 sub run_cmd_pipe {
159 if ($^O eq 'MSWin32' || $^O eq 'msys') {
160 my @invalid = grep {m/[":*]/} @_;
161 die "$^O does not support: @invalid\n" if @invalid;
162 my @args = map { m/ /o ? "\"$_\"": $_ } @_;
163 return qx{@args};
164 } else {
165 my $fh = undef;
166 open($fh, '-|', @_) or die;
167 return <$fh>;
171 my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));
173 if (!defined $GIT_DIR) {
174 exit(1); # rev-parse would have already said "not a git repo"
176 chomp($GIT_DIR);
178 my %cquote_map = (
179 "b" => chr(8),
180 "t" => chr(9),
181 "n" => chr(10),
182 "v" => chr(11),
183 "f" => chr(12),
184 "r" => chr(13),
185 "\\" => "\\",
186 "\042" => "\042",
189 sub unquote_path {
190 local ($_) = @_;
191 my ($retval, $remainder);
192 if (!/^\042(.*)\042$/) {
193 return $_;
195 ($_, $retval) = ($1, "");
196 while (/^([^\\]*)\\(.*)$/) {
197 $remainder = $2;
198 $retval .= $1;
199 for ($remainder) {
200 if (/^([0-3][0-7][0-7])(.*)$/) {
201 $retval .= chr(oct($1));
202 $_ = $2;
203 last;
205 if (/^([\\\042btnvfr])(.*)$/) {
206 $retval .= $cquote_map{$1};
207 $_ = $2;
208 last;
210 # This is malformed -- just return it as-is for now.
211 return $_[0];
213 $_ = $remainder;
215 $retval .= $_;
216 return $retval;
219 sub refresh {
220 my $fh;
221 open $fh, 'git update-index --refresh |'
222 or die;
223 while (<$fh>) {
224 ;# ignore 'needs update'
226 close $fh;
229 sub list_untracked {
230 map {
231 chomp $_;
232 unquote_path($_);
234 run_cmd_pipe(qw(git ls-files --others --exclude-standard --), @ARGV);
237 my $status_fmt = '%12s %12s %4s%s %s';
238 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', '#', ' ', 'path');
241 my $initial;
242 sub is_initial_commit {
243 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
244 unless defined $initial;
245 return $initial;
249 sub get_empty_tree {
250 return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
253 # Returns list of hashes, contents of each of which are:
254 # VALUE: pathname
255 # BINARY: is a binary path
256 # INDEX: is index different from HEAD?
257 # FILE: is file different from index?
258 # INDEX_ADDDEL: is it add/delete between HEAD and index?
259 # FILE_ADDDEL: is it add/delete between index and file?
261 sub list_modified {
262 my ($only) = @_;
263 my (%data, @return);
264 my ($add, $del, $adddel, $file);
265 my @tracked = ();
267 if (@ARGV) {
268 @tracked = map {
269 chomp $_;
270 unquote_path($_);
271 } run_cmd_pipe(qw(git ls-files --), @ARGV);
272 return if (!@tracked);
275 my $reference;
276 if (defined $patch_mode_revision and $patch_mode_revision ne 'HEAD') {
277 $reference = $patch_mode_revision;
278 } elsif (is_initial_commit()) {
279 $reference = get_empty_tree();
280 } else {
281 $reference = 'HEAD';
283 for (run_cmd_pipe(qw(git diff-index --cached
284 --numstat --summary), $reference,
285 '--', @tracked)) {
286 if (($add, $del, $file) =
287 /^([-\d]+) ([-\d]+) (.*)/) {
288 my ($change, $bin);
289 $file = unquote_path($file);
290 if ($add eq '-' && $del eq '-') {
291 $change = 'binary';
292 $bin = 1;
294 else {
295 $change = "+$add/-$del";
297 $data{$file} = {
298 INDEX => $change,
299 BINARY => $bin,
300 FILE => 'nothing',
303 elsif (($adddel, $file) =
304 /^ (create|delete) mode [0-7]+ (.*)$/) {
305 $file = unquote_path($file);
306 $data{$file}{INDEX_ADDDEL} = $adddel;
310 for (run_cmd_pipe(qw(git diff-files --numstat --summary --), @tracked)) {
311 if (($add, $del, $file) =
312 /^([-\d]+) ([-\d]+) (.*)/) {
313 $file = unquote_path($file);
314 if (!exists $data{$file}) {
315 $data{$file} = +{
316 INDEX => 'unchanged',
317 BINARY => 0,
320 my ($change, $bin);
321 if ($add eq '-' && $del eq '-') {
322 $change = 'binary';
323 $bin = 1;
325 else {
326 $change = "+$add/-$del";
328 $data{$file}{FILE} = $change;
329 if ($bin) {
330 $data{$file}{BINARY} = 1;
333 elsif (($adddel, $file) =
334 /^ (create|delete) mode [0-7]+ (.*)$/) {
335 $file = unquote_path($file);
336 $data{$file}{FILE_ADDDEL} = $adddel;
340 for (sort keys %data) {
341 my $it = $data{$_};
343 if ($only) {
344 if ($only eq 'index-only') {
345 next if ($it->{INDEX} eq 'unchanged');
347 if ($only eq 'file-only') {
348 next if ($it->{FILE} eq 'nothing');
351 push @return, +{
352 VALUE => $_,
353 %$it,
356 return @return;
359 sub find_unique {
360 my ($string, @stuff) = @_;
361 my $found = undef;
362 for (my $i = 0; $i < @stuff; $i++) {
363 my $it = $stuff[$i];
364 my $hit = undef;
365 if (ref $it) {
366 if ((ref $it) eq 'ARRAY') {
367 $it = $it->[0];
369 else {
370 $it = $it->{VALUE};
373 eval {
374 if ($it =~ /^$string/) {
375 $hit = 1;
378 if (defined $hit && defined $found) {
379 return undef;
381 if ($hit) {
382 $found = $i + 1;
385 return $found;
388 # inserts string into trie and updates count for each character
389 sub update_trie {
390 my ($trie, $string) = @_;
391 foreach (split //, $string) {
392 $trie = $trie->{$_} ||= {COUNT => 0};
393 $trie->{COUNT}++;
397 # returns an array of tuples (prefix, remainder)
398 sub find_unique_prefixes {
399 my @stuff = @_;
400 my @return = ();
402 # any single prefix exceeding the soft limit is omitted
403 # if any prefix exceeds the hard limit all are omitted
404 # 0 indicates no limit
405 my $soft_limit = 0;
406 my $hard_limit = 3;
408 # build a trie modelling all possible options
409 my %trie;
410 foreach my $print (@stuff) {
411 if ((ref $print) eq 'ARRAY') {
412 $print = $print->[0];
414 elsif ((ref $print) eq 'HASH') {
415 $print = $print->{VALUE};
417 update_trie(\%trie, $print);
418 push @return, $print;
421 # use the trie to find the unique prefixes
422 for (my $i = 0; $i < @return; $i++) {
423 my $ret = $return[$i];
424 my @letters = split //, $ret;
425 my %search = %trie;
426 my ($prefix, $remainder);
427 my $j;
428 for ($j = 0; $j < @letters; $j++) {
429 my $letter = $letters[$j];
430 if ($search{$letter}{COUNT} == 1) {
431 $prefix = substr $ret, 0, $j + 1;
432 $remainder = substr $ret, $j + 1;
433 last;
435 else {
436 my $prefix = substr $ret, 0, $j;
437 return ()
438 if ($hard_limit && $j + 1 > $hard_limit);
440 %search = %{$search{$letter}};
442 if (ord($letters[0]) > 127 ||
443 ($soft_limit && $j + 1 > $soft_limit)) {
444 $prefix = undef;
445 $remainder = $ret;
447 $return[$i] = [$prefix, $remainder];
449 return @return;
452 # filters out prefixes which have special meaning to list_and_choose()
453 sub is_valid_prefix {
454 my $prefix = shift;
455 return (defined $prefix) &&
456 !($prefix =~ /[\s,]/) && # separators
457 !($prefix =~ /^-/) && # deselection
458 !($prefix =~ /^\d+/) && # selection
459 ($prefix ne '*') && # "all" wildcard
460 ($prefix ne '?'); # prompt help
463 # given a prefix/remainder tuple return a string with the prefix highlighted
464 # for now use square brackets; later might use ANSI colors (underline, bold)
465 sub highlight_prefix {
466 my $prefix = shift;
467 my $remainder = shift;
469 if (!defined $prefix) {
470 return $remainder;
473 if (!is_valid_prefix($prefix)) {
474 return "$prefix$remainder";
477 if (!$menu_use_color) {
478 return "[$prefix]$remainder";
481 return "$prompt_color$prefix$normal_color$remainder";
484 sub error_msg {
485 print STDERR colored $error_color, @_;
488 sub list_and_choose {
489 my ($opts, @stuff) = @_;
490 my (@chosen, @return);
491 my $i;
492 my @prefixes = find_unique_prefixes(@stuff) unless $opts->{LIST_ONLY};
494 TOPLOOP:
495 while (1) {
496 my $last_lf = 0;
498 if ($opts->{HEADER}) {
499 if (!$opts->{LIST_FLAT}) {
500 print " ";
502 print colored $header_color, "$opts->{HEADER}\n";
504 for ($i = 0; $i < @stuff; $i++) {
505 my $chosen = $chosen[$i] ? '*' : ' ';
506 my $print = $stuff[$i];
507 my $ref = ref $print;
508 my $highlighted = highlight_prefix(@{$prefixes[$i]})
509 if @prefixes;
510 if ($ref eq 'ARRAY') {
511 $print = $highlighted || $print->[0];
513 elsif ($ref eq 'HASH') {
514 my $value = $highlighted || $print->{VALUE};
515 $print = sprintf($status_fmt,
516 $print->{INDEX},
517 $print->{FILE},
518 $i + 1,
519 ":",
520 $value);
522 else {
523 $print = $highlighted || $print;
525 printf("%s%s", $chosen, $print);
526 if (($opts->{LIST_FLAT}) &&
527 (($i + 1) % ($opts->{LIST_FLAT}))) {
528 print "\t";
529 $last_lf = 0;
531 else {
532 print "\n";
533 $last_lf = 1;
536 if (!$last_lf) {
537 print "\n";
540 return if ($opts->{LIST_ONLY});
542 print colored $prompt_color, $opts->{PROMPT};
543 if ($opts->{SINGLETON}) {
544 print "> ";
546 else {
547 print ">> ";
549 my $line = <STDIN>;
550 if (!$line) {
551 print "\n";
552 $opts->{ON_EOF}->() if $opts->{ON_EOF};
553 last;
555 chomp $line;
556 last if $line eq '';
557 if ($line eq '?') {
558 $opts->{SINGLETON} ?
559 singleton_prompt_help_cmd() :
560 prompt_help_cmd();
561 next TOPLOOP;
563 for my $choice (split(/[\s,]+/, $line)) {
564 my $choose = 1;
565 my ($bottom, $top);
567 # Input that begins with '-'; unchoose
568 if ($choice =~ s/^-//) {
569 $choose = 0;
571 # A range can be specified like 5-7 or 5-.
572 if ($choice =~ /^(\d+)-(\d*)$/) {
573 ($bottom, $top) = ($1, length($2) ? $2 : 1 + @stuff);
575 elsif ($choice =~ /^\d+$/) {
576 $bottom = $top = $choice;
578 elsif ($choice eq '*') {
579 $bottom = 1;
580 $top = 1 + @stuff;
582 else {
583 $bottom = $top = find_unique($choice, @stuff);
584 if (!defined $bottom) {
585 error_msg "Huh ($choice)?\n";
586 next TOPLOOP;
589 if ($opts->{SINGLETON} && $bottom != $top) {
590 error_msg "Huh ($choice)?\n";
591 next TOPLOOP;
593 for ($i = $bottom-1; $i <= $top-1; $i++) {
594 next if (@stuff <= $i || $i < 0);
595 $chosen[$i] = $choose;
598 last if ($opts->{IMMEDIATE} || $line eq '*');
600 for ($i = 0; $i < @stuff; $i++) {
601 if ($chosen[$i]) {
602 push @return, $stuff[$i];
605 return @return;
608 sub singleton_prompt_help_cmd {
609 print colored $help_color, <<\EOF ;
610 Prompt help:
611 1 - select a numbered item
612 foo - select item based on unique prefix
613 - (empty) select nothing
617 sub prompt_help_cmd {
618 print colored $help_color, <<\EOF ;
619 Prompt help:
620 1 - select a single item
621 3-5 - select a range of items
622 2-3,6-9 - select multiple ranges
623 foo - select item based on unique prefix
624 -... - unselect specified items
625 * - choose all items
626 - (empty) finish selecting
630 sub status_cmd {
631 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
632 list_modified());
633 print "\n";
636 sub say_n_paths {
637 my $did = shift @_;
638 my $cnt = scalar @_;
639 print "$did ";
640 if (1 < $cnt) {
641 print "$cnt paths\n";
643 else {
644 print "one path\n";
648 sub update_cmd {
649 my @mods = list_modified('file-only');
650 return if (!@mods);
652 my @update = list_and_choose({ PROMPT => 'Update',
653 HEADER => $status_head, },
654 @mods);
655 if (@update) {
656 system(qw(git update-index --add --remove --),
657 map { $_->{VALUE} } @update);
658 say_n_paths('updated', @update);
660 print "\n";
663 sub revert_cmd {
664 my @update = list_and_choose({ PROMPT => 'Revert',
665 HEADER => $status_head, },
666 list_modified());
667 if (@update) {
668 if (is_initial_commit()) {
669 system(qw(git rm --cached),
670 map { $_->{VALUE} } @update);
672 else {
673 my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
674 map { $_->{VALUE} } @update);
675 my $fh;
676 open $fh, '| git update-index --index-info'
677 or die;
678 for (@lines) {
679 print $fh $_;
681 close($fh);
682 for (@update) {
683 if ($_->{INDEX_ADDDEL} &&
684 $_->{INDEX_ADDDEL} eq 'create') {
685 system(qw(git update-index --force-remove --),
686 $_->{VALUE});
687 print "note: $_->{VALUE} is untracked now.\n";
691 refresh();
692 say_n_paths('reverted', @update);
694 print "\n";
697 sub add_untracked_cmd {
698 my @add = list_and_choose({ PROMPT => 'Add untracked' },
699 list_untracked());
700 if (@add) {
701 system(qw(git update-index --add --), @add);
702 say_n_paths('added', @add);
704 print "\n";
707 sub run_git_apply {
708 my $cmd = shift;
709 my $fh;
710 open $fh, '| git ' . $cmd;
711 print $fh @_;
712 return close $fh;
715 sub parse_diff {
716 my ($path) = @_;
717 my @diff_cmd = split(" ", $patch_mode_flavour{DIFF});
718 if (defined $patch_mode_revision) {
719 push @diff_cmd, $patch_mode_revision;
721 my @diff = run_cmd_pipe("git", @diff_cmd, "--", $path);
722 my @colored = ();
723 if ($diff_use_color) {
724 @colored = run_cmd_pipe("git", @diff_cmd, qw(--color --), $path);
726 my (@hunk) = { TEXT => [], DISPLAY => [], TYPE => 'header' };
728 for (my $i = 0; $i < @diff; $i++) {
729 if ($diff[$i] =~ /^@@ /) {
730 push @hunk, { TEXT => [], DISPLAY => [],
731 TYPE => 'hunk' };
733 push @{$hunk[-1]{TEXT}}, $diff[$i];
734 push @{$hunk[-1]{DISPLAY}},
735 ($diff_use_color ? $colored[$i] : $diff[$i]);
737 return @hunk;
740 sub parse_diff_header {
741 my $src = shift;
743 my $head = { TEXT => [], DISPLAY => [], TYPE => 'header' };
744 my $mode = { TEXT => [], DISPLAY => [], TYPE => 'mode' };
745 my $deletion = { TEXT => [], DISPLAY => [], TYPE => 'deletion' };
747 for (my $i = 0; $i < @{$src->{TEXT}}; $i++) {
748 my $dest =
749 $src->{TEXT}->[$i] =~ /^(old|new) mode (\d+)$/ ? $mode :
750 $src->{TEXT}->[$i] =~ /^deleted file/ ? $deletion :
751 $head;
752 push @{$dest->{TEXT}}, $src->{TEXT}->[$i];
753 push @{$dest->{DISPLAY}}, $src->{DISPLAY}->[$i];
755 return ($head, $mode, $deletion);
758 sub hunk_splittable {
759 my ($text) = @_;
761 my @s = split_hunk($text);
762 return (1 < @s);
765 sub parse_hunk_header {
766 my ($line) = @_;
767 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
768 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
769 $o_cnt = 1 unless defined $o_cnt;
770 $n_cnt = 1 unless defined $n_cnt;
771 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
774 sub split_hunk {
775 my ($text, $display) = @_;
776 my @split = ();
777 if (!defined $display) {
778 $display = $text;
780 # If there are context lines in the middle of a hunk,
781 # it can be split, but we would need to take care of
782 # overlaps later.
784 my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
785 my $hunk_start = 1;
787 OUTER:
788 while (1) {
789 my $next_hunk_start = undef;
790 my $i = $hunk_start - 1;
791 my $this = +{
792 TEXT => [],
793 DISPLAY => [],
794 TYPE => 'hunk',
795 OLD => $o_ofs,
796 NEW => $n_ofs,
797 OCNT => 0,
798 NCNT => 0,
799 ADDDEL => 0,
800 POSTCTX => 0,
801 USE => undef,
804 while (++$i < @$text) {
805 my $line = $text->[$i];
806 my $display = $display->[$i];
807 if ($line =~ /^ /) {
808 if ($this->{ADDDEL} &&
809 !defined $next_hunk_start) {
810 # We have seen leading context and
811 # adds/dels and then here is another
812 # context, which is trailing for this
813 # split hunk and leading for the next
814 # one.
815 $next_hunk_start = $i;
817 push @{$this->{TEXT}}, $line;
818 push @{$this->{DISPLAY}}, $display;
819 $this->{OCNT}++;
820 $this->{NCNT}++;
821 if (defined $next_hunk_start) {
822 $this->{POSTCTX}++;
824 next;
827 # add/del
828 if (defined $next_hunk_start) {
829 # We are done with the current hunk and
830 # this is the first real change for the
831 # next split one.
832 $hunk_start = $next_hunk_start;
833 $o_ofs = $this->{OLD} + $this->{OCNT};
834 $n_ofs = $this->{NEW} + $this->{NCNT};
835 $o_ofs -= $this->{POSTCTX};
836 $n_ofs -= $this->{POSTCTX};
837 push @split, $this;
838 redo OUTER;
840 push @{$this->{TEXT}}, $line;
841 push @{$this->{DISPLAY}}, $display;
842 $this->{ADDDEL}++;
843 if ($line =~ /^-/) {
844 $this->{OCNT}++;
846 else {
847 $this->{NCNT}++;
851 push @split, $this;
852 last;
855 for my $hunk (@split) {
856 $o_ofs = $hunk->{OLD};
857 $n_ofs = $hunk->{NEW};
858 my $o_cnt = $hunk->{OCNT};
859 my $n_cnt = $hunk->{NCNT};
861 my $head = ("@@ -$o_ofs" .
862 (($o_cnt != 1) ? ",$o_cnt" : '') .
863 " +$n_ofs" .
864 (($n_cnt != 1) ? ",$n_cnt" : '') .
865 " @@\n");
866 my $display_head = $head;
867 unshift @{$hunk->{TEXT}}, $head;
868 if ($diff_use_color) {
869 $display_head = colored($fraginfo_color, $head);
871 unshift @{$hunk->{DISPLAY}}, $display_head;
873 return @split;
876 sub find_last_o_ctx {
877 my ($it) = @_;
878 my $text = $it->{TEXT};
879 my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
880 my $i = @{$text};
881 my $last_o_ctx = $o_ofs + $o_cnt;
882 while (0 < --$i) {
883 my $line = $text->[$i];
884 if ($line =~ /^ /) {
885 $last_o_ctx--;
886 next;
888 last;
890 return $last_o_ctx;
893 sub merge_hunk {
894 my ($prev, $this) = @_;
895 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
896 parse_hunk_header($prev->{TEXT}[0]);
897 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
898 parse_hunk_header($this->{TEXT}[0]);
900 my (@line, $i, $ofs, $o_cnt, $n_cnt);
901 $ofs = $o0_ofs;
902 $o_cnt = $n_cnt = 0;
903 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
904 my $line = $prev->{TEXT}[$i];
905 if ($line =~ /^\+/) {
906 $n_cnt++;
907 push @line, $line;
908 next;
911 last if ($o1_ofs <= $ofs);
913 $o_cnt++;
914 $ofs++;
915 if ($line =~ /^ /) {
916 $n_cnt++;
918 push @line, $line;
921 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
922 my $line = $this->{TEXT}[$i];
923 if ($line =~ /^\+/) {
924 $n_cnt++;
925 push @line, $line;
926 next;
928 $ofs++;
929 $o_cnt++;
930 if ($line =~ /^ /) {
931 $n_cnt++;
933 push @line, $line;
935 my $head = ("@@ -$o0_ofs" .
936 (($o_cnt != 1) ? ",$o_cnt" : '') .
937 " +$n0_ofs" .
938 (($n_cnt != 1) ? ",$n_cnt" : '') .
939 " @@\n");
940 @{$prev->{TEXT}} = ($head, @line);
943 sub coalesce_overlapping_hunks {
944 my (@in) = @_;
945 my @out = ();
947 my ($last_o_ctx, $last_was_dirty);
949 for (grep { $_->{USE} } @in) {
950 if ($_->{TYPE} ne 'hunk') {
951 push @out, $_;
952 next;
954 my $text = $_->{TEXT};
955 my ($o_ofs) = parse_hunk_header($text->[0]);
956 if (defined $last_o_ctx &&
957 $o_ofs <= $last_o_ctx &&
958 !$_->{DIRTY} &&
959 !$last_was_dirty) {
960 merge_hunk($out[-1], $_);
962 else {
963 push @out, $_;
965 $last_o_ctx = find_last_o_ctx($out[-1]);
966 $last_was_dirty = $_->{DIRTY};
968 return @out;
971 sub reassemble_patch {
972 my $head = shift;
973 my @patch;
975 # Include everything in the header except the beginning of the diff.
976 push @patch, (grep { !/^[-+]{3}/ } @$head);
978 # Then include any headers from the hunk lines, which must
979 # come before any actual hunk.
980 while (@_ && $_[0] !~ /^@/) {
981 push @patch, shift;
984 # Then begin the diff.
985 push @patch, grep { /^[-+]{3}/ } @$head;
987 # And then the actual hunks.
988 push @patch, @_;
990 return @patch;
993 sub color_diff {
994 return map {
995 colored((/^@/ ? $fraginfo_color :
996 /^\+/ ? $diff_new_color :
997 /^-/ ? $diff_old_color :
998 $diff_plain_color),
999 $_);
1000 } @_;
1003 sub edit_hunk_manually {
1004 my ($oldtext) = @_;
1006 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
1007 my $fh;
1008 open $fh, '>', $hunkfile
1009 or die "failed to open hunk edit file for writing: " . $!;
1010 print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
1011 print $fh @$oldtext;
1012 my $participle = $patch_mode_flavour{PARTICIPLE};
1013 my $is_reverse = $patch_mode_flavour{IS_REVERSE};
1014 my ($remove_plus, $remove_minus) = $is_reverse ? ('-', '+') : ('+', '-');
1015 print $fh <<EOF;
1016 # ---
1017 # To remove '$remove_minus' lines, make them ' ' lines (context).
1018 # To remove '$remove_plus' lines, delete them.
1019 # Lines starting with # will be removed.
1021 # If the patch applies cleanly, the edited hunk will immediately be
1022 # marked for $participle. If it does not apply cleanly, you will be given
1023 # an opportunity to edit again. If all lines of the hunk are removed,
1024 # then the edit is aborted and the hunk is left unchanged.
1026 close $fh;
1028 chomp(my $editor = run_cmd_pipe(qw(git var GIT_EDITOR)));
1029 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
1031 if ($? != 0) {
1032 return undef;
1035 open $fh, '<', $hunkfile
1036 or die "failed to open hunk edit file for reading: " . $!;
1037 my @newtext = grep { !/^#/ } <$fh>;
1038 close $fh;
1039 unlink $hunkfile;
1041 # Abort if nothing remains
1042 if (!grep { /\S/ } @newtext) {
1043 return undef;
1046 # Reinsert the first hunk header if the user accidentally deleted it
1047 if ($newtext[0] !~ /^@/) {
1048 unshift @newtext, $oldtext->[0];
1050 return \@newtext;
1053 sub diff_applies {
1054 my $fh;
1055 return run_git_apply($patch_mode_flavour{APPLY_CHECK} . ' --recount --check',
1056 map { @{$_->{TEXT}} } @_);
1059 sub _restore_terminal_and_die {
1060 ReadMode 'restore';
1061 print "\n";
1062 exit 1;
1065 sub prompt_single_character {
1066 if ($use_readkey) {
1067 local $SIG{TERM} = \&_restore_terminal_and_die;
1068 local $SIG{INT} = \&_restore_terminal_and_die;
1069 ReadMode 'cbreak';
1070 my $key = ReadKey 0;
1071 ReadMode 'restore';
1072 print "$key" if defined $key;
1073 print "\n";
1074 return $key;
1075 } else {
1076 return <STDIN>;
1080 sub prompt_yesno {
1081 my ($prompt) = @_;
1082 while (1) {
1083 print colored $prompt_color, $prompt;
1084 my $line = prompt_single_character;
1085 return 0 if $line =~ /^n/i;
1086 return 1 if $line =~ /^y/i;
1090 sub edit_hunk_loop {
1091 my ($head, $hunk, $ix) = @_;
1092 my $text = $hunk->[$ix]->{TEXT};
1094 while (1) {
1095 $text = edit_hunk_manually($text);
1096 if (!defined $text) {
1097 return undef;
1099 my $newhunk = {
1100 TEXT => $text,
1101 TYPE => $hunk->[$ix]->{TYPE},
1102 USE => 1,
1103 DIRTY => 1,
1105 if (diff_applies($head,
1106 @{$hunk}[0..$ix-1],
1107 $newhunk,
1108 @{$hunk}[$ix+1..$#{$hunk}])) {
1109 $newhunk->{DISPLAY} = [color_diff(@{$text})];
1110 return $newhunk;
1112 else {
1113 prompt_yesno(
1114 'Your edited hunk does not apply. Edit again '
1115 . '(saying "no" discards!) [y/n]? '
1116 ) or return undef;
1121 sub help_patch_cmd {
1122 my $verb = lc $patch_mode_flavour{VERB};
1123 my $target = $patch_mode_flavour{TARGET};
1124 print colored $help_color, <<EOF ;
1125 y - $verb this hunk$target
1126 n - do not $verb this hunk$target
1127 q - quit; do not $verb this hunk nor any of the remaining ones
1128 a - $verb this hunk and all later hunks in the file
1129 d - do not $verb this hunk nor any of the later hunks in the file
1130 g - select a hunk to go to
1131 / - search for a hunk matching the given regex
1132 j - leave this hunk undecided, see next undecided hunk
1133 J - leave this hunk undecided, see next hunk
1134 k - leave this hunk undecided, see previous undecided hunk
1135 K - leave this hunk undecided, see previous hunk
1136 s - split the current hunk into smaller hunks
1137 e - manually edit the current hunk
1138 ? - print help
1142 sub apply_patch {
1143 my $cmd = shift;
1144 my $ret = run_git_apply $cmd . ' --recount', @_;
1145 if (!$ret) {
1146 print STDERR @_;
1148 return $ret;
1151 sub apply_patch_for_checkout_commit {
1152 my $reverse = shift;
1153 my $applies_index = run_git_apply 'apply '.$reverse.' --cached --recount --check', @_;
1154 my $applies_worktree = run_git_apply 'apply '.$reverse.' --recount --check', @_;
1156 if ($applies_worktree && $applies_index) {
1157 run_git_apply 'apply '.$reverse.' --cached --recount', @_;
1158 run_git_apply 'apply '.$reverse.' --recount', @_;
1159 return 1;
1160 } elsif (!$applies_index) {
1161 print colored $error_color, "The selected hunks do not apply to the index!\n";
1162 if (prompt_yesno "Apply them to the worktree anyway? ") {
1163 return run_git_apply 'apply '.$reverse.' --recount', @_;
1164 } else {
1165 print colored $error_color, "Nothing was applied.\n";
1166 return 0;
1168 } else {
1169 print STDERR @_;
1170 return 0;
1174 sub patch_update_cmd {
1175 my @all_mods = list_modified($patch_mode_flavour{FILTER});
1176 my @mods = grep { !($_->{BINARY}) } @all_mods;
1177 my @them;
1179 if (!@mods) {
1180 if (@all_mods) {
1181 print STDERR "Only binary files changed.\n";
1182 } else {
1183 print STDERR "No changes.\n";
1185 return 0;
1187 if ($patch_mode) {
1188 @them = @mods;
1190 else {
1191 @them = list_and_choose({ PROMPT => 'Patch update',
1192 HEADER => $status_head, },
1193 @mods);
1195 for (@them) {
1196 return 0 if patch_update_file($_->{VALUE});
1200 # Generate a one line summary of a hunk.
1201 sub summarize_hunk {
1202 my $rhunk = shift;
1203 my $summary = $rhunk->{TEXT}[0];
1205 # Keep the line numbers, discard extra context.
1206 $summary =~ s/@@(.*?)@@.*/$1 /s;
1207 $summary .= " " x (20 - length $summary);
1209 # Add some user context.
1210 for my $line (@{$rhunk->{TEXT}}) {
1211 if ($line =~ m/^[+-].*\w/) {
1212 $summary .= $line;
1213 last;
1217 chomp $summary;
1218 return substr($summary, 0, 80) . "\n";
1222 # Print a one-line summary of each hunk in the array ref in
1223 # the first argument, starting wih the index in the 2nd.
1224 sub display_hunks {
1225 my ($hunks, $i) = @_;
1226 my $ctr = 0;
1227 $i ||= 0;
1228 for (; $i < @$hunks && $ctr < 20; $i++, $ctr++) {
1229 my $status = " ";
1230 if (defined $hunks->[$i]{USE}) {
1231 $status = $hunks->[$i]{USE} ? "+" : "-";
1233 printf "%s%2d: %s",
1234 $status,
1235 $i + 1,
1236 summarize_hunk($hunks->[$i]);
1238 return $i;
1241 sub patch_update_file {
1242 my $quit = 0;
1243 my ($ix, $num);
1244 my $path = shift;
1245 my ($head, @hunk) = parse_diff($path);
1246 ($head, my $mode, my $deletion) = parse_diff_header($head);
1247 for (@{$head->{DISPLAY}}) {
1248 print;
1251 if (@{$mode->{TEXT}}) {
1252 unshift @hunk, $mode;
1254 if (@{$deletion->{TEXT}}) {
1255 foreach my $hunk (@hunk) {
1256 push @{$deletion->{TEXT}}, @{$hunk->{TEXT}};
1257 push @{$deletion->{DISPLAY}}, @{$hunk->{DISPLAY}};
1259 @hunk = ($deletion);
1262 $num = scalar @hunk;
1263 $ix = 0;
1265 while (1) {
1266 my ($prev, $next, $other, $undecided, $i);
1267 $other = '';
1269 if ($num <= $ix) {
1270 $ix = 0;
1272 for ($i = 0; $i < $ix; $i++) {
1273 if (!defined $hunk[$i]{USE}) {
1274 $prev = 1;
1275 $other .= ',k';
1276 last;
1279 if ($ix) {
1280 $other .= ',K';
1282 for ($i = $ix + 1; $i < $num; $i++) {
1283 if (!defined $hunk[$i]{USE}) {
1284 $next = 1;
1285 $other .= ',j';
1286 last;
1289 if ($ix < $num - 1) {
1290 $other .= ',J';
1292 if ($num > 1) {
1293 $other .= ',g';
1295 for ($i = 0; $i < $num; $i++) {
1296 if (!defined $hunk[$i]{USE}) {
1297 $undecided = 1;
1298 last;
1301 last if (!$undecided);
1303 if ($hunk[$ix]{TYPE} eq 'hunk' &&
1304 hunk_splittable($hunk[$ix]{TEXT})) {
1305 $other .= ',s';
1307 if ($hunk[$ix]{TYPE} eq 'hunk') {
1308 $other .= ',e';
1310 for (@{$hunk[$ix]{DISPLAY}}) {
1311 print;
1313 print colored $prompt_color, $patch_mode_flavour{VERB},
1314 ($hunk[$ix]{TYPE} eq 'mode' ? ' mode change' :
1315 $hunk[$ix]{TYPE} eq 'deletion' ? ' deletion' :
1316 ' this hunk'),
1317 $patch_mode_flavour{TARGET},
1318 " [y,n,q,a,d,/$other,?]? ";
1319 my $line = prompt_single_character;
1320 if ($line) {
1321 if ($line =~ /^y/i) {
1322 $hunk[$ix]{USE} = 1;
1324 elsif ($line =~ /^n/i) {
1325 $hunk[$ix]{USE} = 0;
1327 elsif ($line =~ /^a/i) {
1328 while ($ix < $num) {
1329 if (!defined $hunk[$ix]{USE}) {
1330 $hunk[$ix]{USE} = 1;
1332 $ix++;
1334 next;
1336 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1337 my $response = $1;
1338 my $no = $ix > 10 ? $ix - 10 : 0;
1339 while ($response eq '') {
1340 my $extra = "";
1341 $no = display_hunks(\@hunk, $no);
1342 if ($no < $num) {
1343 $extra = " (<ret> to see more)";
1345 print "go to which hunk$extra? ";
1346 $response = <STDIN>;
1347 if (!defined $response) {
1348 $response = '';
1350 chomp $response;
1352 if ($response !~ /^\s*\d+\s*$/) {
1353 error_msg "Invalid number: '$response'\n";
1354 } elsif (0 < $response && $response <= $num) {
1355 $ix = $response - 1;
1356 } else {
1357 error_msg "Sorry, only $num hunks available.\n";
1359 next;
1361 elsif ($line =~ /^d/i) {
1362 while ($ix < $num) {
1363 if (!defined $hunk[$ix]{USE}) {
1364 $hunk[$ix]{USE} = 0;
1366 $ix++;
1368 next;
1370 elsif ($line =~ /^q/i) {
1371 while ($ix < $num) {
1372 if (!defined $hunk[$ix]{USE}) {
1373 $hunk[$ix]{USE} = 0;
1375 $ix++;
1377 $quit = 1;
1378 next;
1380 elsif ($line =~ m|^/(.*)|) {
1381 my $regex = $1;
1382 if ($1 eq "") {
1383 print colored $prompt_color, "search for regex? ";
1384 $regex = <STDIN>;
1385 if (defined $regex) {
1386 chomp $regex;
1389 my $search_string;
1390 eval {
1391 $search_string = qr{$regex}m;
1393 if ($@) {
1394 my ($err,$exp) = ($@, $1);
1395 $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1396 error_msg "Malformed search regexp $exp: $err\n";
1397 next;
1399 my $iy = $ix;
1400 while (1) {
1401 my $text = join ("", @{$hunk[$iy]{TEXT}});
1402 last if ($text =~ $search_string);
1403 $iy++;
1404 $iy = 0 if ($iy >= $num);
1405 if ($ix == $iy) {
1406 error_msg "No hunk matches the given pattern\n";
1407 last;
1410 $ix = $iy;
1411 next;
1413 elsif ($line =~ /^K/) {
1414 if ($other =~ /K/) {
1415 $ix--;
1417 else {
1418 error_msg "No previous hunk\n";
1420 next;
1422 elsif ($line =~ /^J/) {
1423 if ($other =~ /J/) {
1424 $ix++;
1426 else {
1427 error_msg "No next hunk\n";
1429 next;
1431 elsif ($line =~ /^k/) {
1432 if ($other =~ /k/) {
1433 while (1) {
1434 $ix--;
1435 last if (!$ix ||
1436 !defined $hunk[$ix]{USE});
1439 else {
1440 error_msg "No previous hunk\n";
1442 next;
1444 elsif ($line =~ /^j/) {
1445 if ($other !~ /j/) {
1446 error_msg "No next hunk\n";
1447 next;
1450 elsif ($other =~ /s/ && $line =~ /^s/) {
1451 my @split = split_hunk($hunk[$ix]{TEXT}, $hunk[$ix]{DISPLAY});
1452 if (1 < @split) {
1453 print colored $header_color, "Split into ",
1454 scalar(@split), " hunks.\n";
1456 splice (@hunk, $ix, 1, @split);
1457 $num = scalar @hunk;
1458 next;
1460 elsif ($other =~ /e/ && $line =~ /^e/) {
1461 my $newhunk = edit_hunk_loop($head, \@hunk, $ix);
1462 if (defined $newhunk) {
1463 splice @hunk, $ix, 1, $newhunk;
1466 else {
1467 help_patch_cmd($other);
1468 next;
1470 # soft increment
1471 while (1) {
1472 $ix++;
1473 last if ($ix >= $num ||
1474 !defined $hunk[$ix]{USE});
1479 @hunk = coalesce_overlapping_hunks(@hunk);
1481 my $n_lofs = 0;
1482 my @result = ();
1483 for (@hunk) {
1484 if ($_->{USE}) {
1485 push @result, @{$_->{TEXT}};
1489 if (@result) {
1490 my $fh;
1491 my @patch = reassemble_patch($head->{TEXT}, @result);
1492 my $apply_routine = $patch_mode_flavour{APPLY};
1493 &$apply_routine(@patch);
1494 refresh();
1497 print "\n";
1498 return $quit;
1501 sub diff_cmd {
1502 my @mods = list_modified('index-only');
1503 @mods = grep { !($_->{BINARY}) } @mods;
1504 return if (!@mods);
1505 my (@them) = list_and_choose({ PROMPT => 'Review diff',
1506 IMMEDIATE => 1,
1507 HEADER => $status_head, },
1508 @mods);
1509 return if (!@them);
1510 my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
1511 system(qw(git diff -p --cached), $reference, '--',
1512 map { $_->{VALUE} } @them);
1515 sub quit_cmd {
1516 print "Bye.\n";
1517 exit(0);
1520 sub help_cmd {
1521 print colored $help_color, <<\EOF ;
1522 status - show paths with changes
1523 update - add working tree state to the staged set of changes
1524 revert - revert staged set of changes back to the HEAD version
1525 patch - pick hunks and update selectively
1526 diff - view diff between HEAD and index
1527 add untracked - add contents of untracked files to the staged set of changes
1531 sub process_args {
1532 return unless @ARGV;
1533 my $arg = shift @ARGV;
1534 if ($arg =~ /--patch(?:=(.*))?/) {
1535 if (defined $1) {
1536 if ($1 eq 'reset') {
1537 $patch_mode = 'reset_head';
1538 $patch_mode_revision = 'HEAD';
1539 $arg = shift @ARGV or die "missing --";
1540 if ($arg ne '--') {
1541 $patch_mode_revision = $arg;
1542 $patch_mode = ($arg eq 'HEAD' ?
1543 'reset_head' : 'reset_nothead');
1544 $arg = shift @ARGV or die "missing --";
1546 } elsif ($1 eq 'checkout') {
1547 $arg = shift @ARGV or die "missing --";
1548 if ($arg eq '--') {
1549 $patch_mode = 'checkout_index';
1550 } else {
1551 $patch_mode_revision = $arg;
1552 $patch_mode = ($arg eq 'HEAD' ?
1553 'checkout_head' : 'checkout_nothead');
1554 $arg = shift @ARGV or die "missing --";
1556 } elsif ($1 eq 'stage' or $1 eq 'stash') {
1557 $patch_mode = $1;
1558 $arg = shift @ARGV or die "missing --";
1559 } else {
1560 die "unknown --patch mode: $1";
1562 } else {
1563 $patch_mode = 'stage';
1564 $arg = shift @ARGV or die "missing --";
1566 die "invalid argument $arg, expecting --"
1567 unless $arg eq "--";
1568 %patch_mode_flavour = %{$patch_modes{$patch_mode}};
1570 elsif ($arg ne "--") {
1571 die "invalid argument $arg, expecting --";
1575 sub main_loop {
1576 my @cmd = ([ 'status', \&status_cmd, ],
1577 [ 'update', \&update_cmd, ],
1578 [ 'revert', \&revert_cmd, ],
1579 [ 'add untracked', \&add_untracked_cmd, ],
1580 [ 'patch', \&patch_update_cmd, ],
1581 [ 'diff', \&diff_cmd, ],
1582 [ 'quit', \&quit_cmd, ],
1583 [ 'help', \&help_cmd, ],
1585 while (1) {
1586 my ($it) = list_and_choose({ PROMPT => 'What now',
1587 SINGLETON => 1,
1588 LIST_FLAT => 4,
1589 HEADER => '*** Commands ***',
1590 ON_EOF => \&quit_cmd,
1591 IMMEDIATE => 1 }, @cmd);
1592 if ($it) {
1593 eval {
1594 $it->[1]->();
1596 if ($@) {
1597 print "$@";
1603 process_args();
1604 refresh();
1605 if ($patch_mode) {
1606 patch_update_cmd();
1608 else {
1609 status_cmd();
1610 main_loop();