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