Merge branch 'maint'
[git.git] / git-add--interactive.perl
bloba329c5a1f8c3b63ee6976a8e0e3903a11783324b
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 %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 $value);
520 else {
521 $print = $highlighted || $print;
523 printf("%s%2d: %s", $chosen, $i+1, $print);
524 if (($opts->{LIST_FLAT}) &&
525 (($i + 1) % ($opts->{LIST_FLAT}))) {
526 print "\t";
527 $last_lf = 0;
529 else {
530 print "\n";
531 $last_lf = 1;
534 if (!$last_lf) {
535 print "\n";
538 return if ($opts->{LIST_ONLY});
540 print colored $prompt_color, $opts->{PROMPT};
541 if ($opts->{SINGLETON}) {
542 print "> ";
544 else {
545 print ">> ";
547 my $line = <STDIN>;
548 if (!$line) {
549 print "\n";
550 $opts->{ON_EOF}->() if $opts->{ON_EOF};
551 last;
553 chomp $line;
554 last if $line eq '';
555 if ($line eq '?') {
556 $opts->{SINGLETON} ?
557 singleton_prompt_help_cmd() :
558 prompt_help_cmd();
559 next TOPLOOP;
561 for my $choice (split(/[\s,]+/, $line)) {
562 my $choose = 1;
563 my ($bottom, $top);
565 # Input that begins with '-'; unchoose
566 if ($choice =~ s/^-//) {
567 $choose = 0;
569 # A range can be specified like 5-7 or 5-.
570 if ($choice =~ /^(\d+)-(\d*)$/) {
571 ($bottom, $top) = ($1, length($2) ? $2 : 1 + @stuff);
573 elsif ($choice =~ /^\d+$/) {
574 $bottom = $top = $choice;
576 elsif ($choice eq '*') {
577 $bottom = 1;
578 $top = 1 + @stuff;
580 else {
581 $bottom = $top = find_unique($choice, @stuff);
582 if (!defined $bottom) {
583 error_msg "Huh ($choice)?\n";
584 next TOPLOOP;
587 if ($opts->{SINGLETON} && $bottom != $top) {
588 error_msg "Huh ($choice)?\n";
589 next TOPLOOP;
591 for ($i = $bottom-1; $i <= $top-1; $i++) {
592 next if (@stuff <= $i || $i < 0);
593 $chosen[$i] = $choose;
596 last if ($opts->{IMMEDIATE} || $line eq '*');
598 for ($i = 0; $i < @stuff; $i++) {
599 if ($chosen[$i]) {
600 push @return, $stuff[$i];
603 return @return;
606 sub singleton_prompt_help_cmd {
607 print colored $help_color, <<\EOF ;
608 Prompt help:
609 1 - select a numbered item
610 foo - select item based on unique prefix
611 - (empty) select nothing
615 sub prompt_help_cmd {
616 print colored $help_color, <<\EOF ;
617 Prompt help:
618 1 - select a single item
619 3-5 - select a range of items
620 2-3,6-9 - select multiple ranges
621 foo - select item based on unique prefix
622 -... - unselect specified items
623 * - choose all items
624 - (empty) finish selecting
628 sub status_cmd {
629 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
630 list_modified());
631 print "\n";
634 sub say_n_paths {
635 my $did = shift @_;
636 my $cnt = scalar @_;
637 print "$did ";
638 if (1 < $cnt) {
639 print "$cnt paths\n";
641 else {
642 print "one path\n";
646 sub update_cmd {
647 my @mods = list_modified('file-only');
648 return if (!@mods);
650 my @update = list_and_choose({ PROMPT => 'Update',
651 HEADER => $status_head, },
652 @mods);
653 if (@update) {
654 system(qw(git update-index --add --remove --),
655 map { $_->{VALUE} } @update);
656 say_n_paths('updated', @update);
658 print "\n";
661 sub revert_cmd {
662 my @update = list_and_choose({ PROMPT => 'Revert',
663 HEADER => $status_head, },
664 list_modified());
665 if (@update) {
666 if (is_initial_commit()) {
667 system(qw(git rm --cached),
668 map { $_->{VALUE} } @update);
670 else {
671 my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
672 map { $_->{VALUE} } @update);
673 my $fh;
674 open $fh, '| git update-index --index-info'
675 or die;
676 for (@lines) {
677 print $fh $_;
679 close($fh);
680 for (@update) {
681 if ($_->{INDEX_ADDDEL} &&
682 $_->{INDEX_ADDDEL} eq 'create') {
683 system(qw(git update-index --force-remove --),
684 $_->{VALUE});
685 print "note: $_->{VALUE} is untracked now.\n";
689 refresh();
690 say_n_paths('reverted', @update);
692 print "\n";
695 sub add_untracked_cmd {
696 my @add = list_and_choose({ PROMPT => 'Add untracked' },
697 list_untracked());
698 if (@add) {
699 system(qw(git update-index --add --), @add);
700 say_n_paths('added', @add);
702 print "\n";
705 sub run_git_apply {
706 my $cmd = shift;
707 my $fh;
708 open $fh, '| git ' . $cmd;
709 print $fh @_;
710 return close $fh;
713 sub parse_diff {
714 my ($path) = @_;
715 my @diff_cmd = split(" ", $patch_mode_flavour{DIFF});
716 if (defined $patch_mode_revision) {
717 push @diff_cmd, $patch_mode_revision;
719 my @diff = run_cmd_pipe("git", @diff_cmd, "--", $path);
720 my @colored = ();
721 if ($diff_use_color) {
722 @colored = run_cmd_pipe("git", @diff_cmd, qw(--color --), $path);
724 my (@hunk) = { TEXT => [], DISPLAY => [], TYPE => 'header' };
726 for (my $i = 0; $i < @diff; $i++) {
727 if ($diff[$i] =~ /^@@ /) {
728 push @hunk, { TEXT => [], DISPLAY => [],
729 TYPE => 'hunk' };
731 push @{$hunk[-1]{TEXT}}, $diff[$i];
732 push @{$hunk[-1]{DISPLAY}},
733 ($diff_use_color ? $colored[$i] : $diff[$i]);
735 return @hunk;
738 sub parse_diff_header {
739 my $src = shift;
741 my $head = { TEXT => [], DISPLAY => [], TYPE => 'header' };
742 my $mode = { TEXT => [], DISPLAY => [], TYPE => 'mode' };
743 my $deletion = { TEXT => [], DISPLAY => [], TYPE => 'deletion' };
745 for (my $i = 0; $i < @{$src->{TEXT}}; $i++) {
746 my $dest =
747 $src->{TEXT}->[$i] =~ /^(old|new) mode (\d+)$/ ? $mode :
748 $src->{TEXT}->[$i] =~ /^deleted file/ ? $deletion :
749 $head;
750 push @{$dest->{TEXT}}, $src->{TEXT}->[$i];
751 push @{$dest->{DISPLAY}}, $src->{DISPLAY}->[$i];
753 return ($head, $mode, $deletion);
756 sub hunk_splittable {
757 my ($text) = @_;
759 my @s = split_hunk($text);
760 return (1 < @s);
763 sub parse_hunk_header {
764 my ($line) = @_;
765 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
766 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
767 $o_cnt = 1 unless defined $o_cnt;
768 $n_cnt = 1 unless defined $n_cnt;
769 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
772 sub split_hunk {
773 my ($text, $display) = @_;
774 my @split = ();
775 if (!defined $display) {
776 $display = $text;
778 # If there are context lines in the middle of a hunk,
779 # it can be split, but we would need to take care of
780 # overlaps later.
782 my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
783 my $hunk_start = 1;
785 OUTER:
786 while (1) {
787 my $next_hunk_start = undef;
788 my $i = $hunk_start - 1;
789 my $this = +{
790 TEXT => [],
791 DISPLAY => [],
792 TYPE => 'hunk',
793 OLD => $o_ofs,
794 NEW => $n_ofs,
795 OCNT => 0,
796 NCNT => 0,
797 ADDDEL => 0,
798 POSTCTX => 0,
799 USE => undef,
802 while (++$i < @$text) {
803 my $line = $text->[$i];
804 my $display = $display->[$i];
805 if ($line =~ /^ /) {
806 if ($this->{ADDDEL} &&
807 !defined $next_hunk_start) {
808 # We have seen leading context and
809 # adds/dels and then here is another
810 # context, which is trailing for this
811 # split hunk and leading for the next
812 # one.
813 $next_hunk_start = $i;
815 push @{$this->{TEXT}}, $line;
816 push @{$this->{DISPLAY}}, $display;
817 $this->{OCNT}++;
818 $this->{NCNT}++;
819 if (defined $next_hunk_start) {
820 $this->{POSTCTX}++;
822 next;
825 # add/del
826 if (defined $next_hunk_start) {
827 # We are done with the current hunk and
828 # this is the first real change for the
829 # next split one.
830 $hunk_start = $next_hunk_start;
831 $o_ofs = $this->{OLD} + $this->{OCNT};
832 $n_ofs = $this->{NEW} + $this->{NCNT};
833 $o_ofs -= $this->{POSTCTX};
834 $n_ofs -= $this->{POSTCTX};
835 push @split, $this;
836 redo OUTER;
838 push @{$this->{TEXT}}, $line;
839 push @{$this->{DISPLAY}}, $display;
840 $this->{ADDDEL}++;
841 if ($line =~ /^-/) {
842 $this->{OCNT}++;
844 else {
845 $this->{NCNT}++;
849 push @split, $this;
850 last;
853 for my $hunk (@split) {
854 $o_ofs = $hunk->{OLD};
855 $n_ofs = $hunk->{NEW};
856 my $o_cnt = $hunk->{OCNT};
857 my $n_cnt = $hunk->{NCNT};
859 my $head = ("@@ -$o_ofs" .
860 (($o_cnt != 1) ? ",$o_cnt" : '') .
861 " +$n_ofs" .
862 (($n_cnt != 1) ? ",$n_cnt" : '') .
863 " @@\n");
864 my $display_head = $head;
865 unshift @{$hunk->{TEXT}}, $head;
866 if ($diff_use_color) {
867 $display_head = colored($fraginfo_color, $head);
869 unshift @{$hunk->{DISPLAY}}, $display_head;
871 return @split;
874 sub find_last_o_ctx {
875 my ($it) = @_;
876 my $text = $it->{TEXT};
877 my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
878 my $i = @{$text};
879 my $last_o_ctx = $o_ofs + $o_cnt;
880 while (0 < --$i) {
881 my $line = $text->[$i];
882 if ($line =~ /^ /) {
883 $last_o_ctx--;
884 next;
886 last;
888 return $last_o_ctx;
891 sub merge_hunk {
892 my ($prev, $this) = @_;
893 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
894 parse_hunk_header($prev->{TEXT}[0]);
895 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
896 parse_hunk_header($this->{TEXT}[0]);
898 my (@line, $i, $ofs, $o_cnt, $n_cnt);
899 $ofs = $o0_ofs;
900 $o_cnt = $n_cnt = 0;
901 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
902 my $line = $prev->{TEXT}[$i];
903 if ($line =~ /^\+/) {
904 $n_cnt++;
905 push @line, $line;
906 next;
909 last if ($o1_ofs <= $ofs);
911 $o_cnt++;
912 $ofs++;
913 if ($line =~ /^ /) {
914 $n_cnt++;
916 push @line, $line;
919 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
920 my $line = $this->{TEXT}[$i];
921 if ($line =~ /^\+/) {
922 $n_cnt++;
923 push @line, $line;
924 next;
926 $ofs++;
927 $o_cnt++;
928 if ($line =~ /^ /) {
929 $n_cnt++;
931 push @line, $line;
933 my $head = ("@@ -$o0_ofs" .
934 (($o_cnt != 1) ? ",$o_cnt" : '') .
935 " +$n0_ofs" .
936 (($n_cnt != 1) ? ",$n_cnt" : '') .
937 " @@\n");
938 @{$prev->{TEXT}} = ($head, @line);
941 sub coalesce_overlapping_hunks {
942 my (@in) = @_;
943 my @out = ();
945 my ($last_o_ctx, $last_was_dirty);
947 for (grep { $_->{USE} } @in) {
948 if ($_->{TYPE} ne 'hunk') {
949 push @out, $_;
950 next;
952 my $text = $_->{TEXT};
953 my ($o_ofs) = parse_hunk_header($text->[0]);
954 if (defined $last_o_ctx &&
955 $o_ofs <= $last_o_ctx &&
956 !$_->{DIRTY} &&
957 !$last_was_dirty) {
958 merge_hunk($out[-1], $_);
960 else {
961 push @out, $_;
963 $last_o_ctx = find_last_o_ctx($out[-1]);
964 $last_was_dirty = $_->{DIRTY};
966 return @out;
969 sub reassemble_patch {
970 my $head = shift;
971 my @patch;
973 # Include everything in the header except the beginning of the diff.
974 push @patch, (grep { !/^[-+]{3}/ } @$head);
976 # Then include any headers from the hunk lines, which must
977 # come before any actual hunk.
978 while (@_ && $_[0] !~ /^@/) {
979 push @patch, shift;
982 # Then begin the diff.
983 push @patch, grep { /^[-+]{3}/ } @$head;
985 # And then the actual hunks.
986 push @patch, @_;
988 return @patch;
991 sub color_diff {
992 return map {
993 colored((/^@/ ? $fraginfo_color :
994 /^\+/ ? $diff_new_color :
995 /^-/ ? $diff_old_color :
996 $diff_plain_color),
997 $_);
998 } @_;
1001 sub edit_hunk_manually {
1002 my ($oldtext) = @_;
1004 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
1005 my $fh;
1006 open $fh, '>', $hunkfile
1007 or die "failed to open hunk edit file for writing: " . $!;
1008 print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
1009 print $fh @$oldtext;
1010 my $participle = $patch_mode_flavour{PARTICIPLE};
1011 my $is_reverse = $patch_mode_flavour{IS_REVERSE};
1012 my ($remove_plus, $remove_minus) = $is_reverse ? ('-', '+') : ('+', '-');
1013 print $fh <<EOF;
1014 # ---
1015 # To remove '$remove_minus' lines, make them ' ' lines (context).
1016 # To remove '$remove_plus' lines, delete them.
1017 # Lines starting with # will be removed.
1019 # If the patch applies cleanly, the edited hunk will immediately be
1020 # marked for $participle. If it does not apply cleanly, you will be given
1021 # an opportunity to edit again. If all lines of the hunk are removed,
1022 # then the edit is aborted and the hunk is left unchanged.
1024 close $fh;
1026 chomp(my $editor = run_cmd_pipe(qw(git var GIT_EDITOR)));
1027 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
1029 if ($? != 0) {
1030 return undef;
1033 open $fh, '<', $hunkfile
1034 or die "failed to open hunk edit file for reading: " . $!;
1035 my @newtext = grep { !/^#/ } <$fh>;
1036 close $fh;
1037 unlink $hunkfile;
1039 # Abort if nothing remains
1040 if (!grep { /\S/ } @newtext) {
1041 return undef;
1044 # Reinsert the first hunk header if the user accidentally deleted it
1045 if ($newtext[0] !~ /^@/) {
1046 unshift @newtext, $oldtext->[0];
1048 return \@newtext;
1051 sub diff_applies {
1052 my $fh;
1053 return run_git_apply($patch_mode_flavour{APPLY_CHECK} . ' --recount --check',
1054 map { @{$_->{TEXT}} } @_);
1057 sub _restore_terminal_and_die {
1058 ReadMode 'restore';
1059 print "\n";
1060 exit 1;
1063 sub prompt_single_character {
1064 if ($use_readkey) {
1065 local $SIG{TERM} = \&_restore_terminal_and_die;
1066 local $SIG{INT} = \&_restore_terminal_and_die;
1067 ReadMode 'cbreak';
1068 my $key = ReadKey 0;
1069 ReadMode 'restore';
1070 print "$key" if defined $key;
1071 print "\n";
1072 return $key;
1073 } else {
1074 return <STDIN>;
1078 sub prompt_yesno {
1079 my ($prompt) = @_;
1080 while (1) {
1081 print colored $prompt_color, $prompt;
1082 my $line = prompt_single_character;
1083 return 0 if $line =~ /^n/i;
1084 return 1 if $line =~ /^y/i;
1088 sub edit_hunk_loop {
1089 my ($head, $hunk, $ix) = @_;
1090 my $text = $hunk->[$ix]->{TEXT};
1092 while (1) {
1093 $text = edit_hunk_manually($text);
1094 if (!defined $text) {
1095 return undef;
1097 my $newhunk = {
1098 TEXT => $text,
1099 TYPE => $hunk->[$ix]->{TYPE},
1100 USE => 1,
1101 DIRTY => 1,
1103 if (diff_applies($head,
1104 @{$hunk}[0..$ix-1],
1105 $newhunk,
1106 @{$hunk}[$ix+1..$#{$hunk}])) {
1107 $newhunk->{DISPLAY} = [color_diff(@{$text})];
1108 return $newhunk;
1110 else {
1111 prompt_yesno(
1112 'Your edited hunk does not apply. Edit again '
1113 . '(saying "no" discards!) [y/n]? '
1114 ) or return undef;
1119 sub help_patch_cmd {
1120 my $verb = lc $patch_mode_flavour{VERB};
1121 my $target = $patch_mode_flavour{TARGET};
1122 print colored $help_color, <<EOF ;
1123 y - $verb this hunk$target
1124 n - do not $verb this hunk$target
1125 q - quit; do not $verb this hunk nor any of the remaining ones
1126 a - $verb this hunk and all later hunks in the file
1127 d - do not $verb this hunk nor any of the later hunks in the file
1128 g - select a hunk to go to
1129 / - search for a hunk matching the given regex
1130 j - leave this hunk undecided, see next undecided hunk
1131 J - leave this hunk undecided, see next hunk
1132 k - leave this hunk undecided, see previous undecided hunk
1133 K - leave this hunk undecided, see previous hunk
1134 s - split the current hunk into smaller hunks
1135 e - manually edit the current hunk
1136 ? - print help
1140 sub apply_patch {
1141 my $cmd = shift;
1142 my $ret = run_git_apply $cmd . ' --recount', @_;
1143 if (!$ret) {
1144 print STDERR @_;
1146 return $ret;
1149 sub apply_patch_for_checkout_commit {
1150 my $reverse = shift;
1151 my $applies_index = run_git_apply 'apply '.$reverse.' --cached --recount --check', @_;
1152 my $applies_worktree = run_git_apply 'apply '.$reverse.' --recount --check', @_;
1154 if ($applies_worktree && $applies_index) {
1155 run_git_apply 'apply '.$reverse.' --cached --recount', @_;
1156 run_git_apply 'apply '.$reverse.' --recount', @_;
1157 return 1;
1158 } elsif (!$applies_index) {
1159 print colored $error_color, "The selected hunks do not apply to the index!\n";
1160 if (prompt_yesno "Apply them to the worktree anyway? ") {
1161 return run_git_apply 'apply '.$reverse.' --recount', @_;
1162 } else {
1163 print colored $error_color, "Nothing was applied.\n";
1164 return 0;
1166 } else {
1167 print STDERR @_;
1168 return 0;
1172 sub patch_update_cmd {
1173 my @all_mods = list_modified($patch_mode_flavour{FILTER});
1174 my @mods = grep { !($_->{BINARY}) } @all_mods;
1175 my @them;
1177 if (!@mods) {
1178 if (@all_mods) {
1179 print STDERR "Only binary files changed.\n";
1180 } else {
1181 print STDERR "No changes.\n";
1183 return 0;
1185 if ($patch_mode) {
1186 @them = @mods;
1188 else {
1189 @them = list_and_choose({ PROMPT => 'Patch update',
1190 HEADER => $status_head, },
1191 @mods);
1193 for (@them) {
1194 return 0 if patch_update_file($_->{VALUE});
1198 # Generate a one line summary of a hunk.
1199 sub summarize_hunk {
1200 my $rhunk = shift;
1201 my $summary = $rhunk->{TEXT}[0];
1203 # Keep the line numbers, discard extra context.
1204 $summary =~ s/@@(.*?)@@.*/$1 /s;
1205 $summary .= " " x (20 - length $summary);
1207 # Add some user context.
1208 for my $line (@{$rhunk->{TEXT}}) {
1209 if ($line =~ m/^[+-].*\w/) {
1210 $summary .= $line;
1211 last;
1215 chomp $summary;
1216 return substr($summary, 0, 80) . "\n";
1220 # Print a one-line summary of each hunk in the array ref in
1221 # the first argument, starting wih the index in the 2nd.
1222 sub display_hunks {
1223 my ($hunks, $i) = @_;
1224 my $ctr = 0;
1225 $i ||= 0;
1226 for (; $i < @$hunks && $ctr < 20; $i++, $ctr++) {
1227 my $status = " ";
1228 if (defined $hunks->[$i]{USE}) {
1229 $status = $hunks->[$i]{USE} ? "+" : "-";
1231 printf "%s%2d: %s",
1232 $status,
1233 $i + 1,
1234 summarize_hunk($hunks->[$i]);
1236 return $i;
1239 sub patch_update_file {
1240 my $quit = 0;
1241 my ($ix, $num);
1242 my $path = shift;
1243 my ($head, @hunk) = parse_diff($path);
1244 ($head, my $mode, my $deletion) = parse_diff_header($head);
1245 for (@{$head->{DISPLAY}}) {
1246 print;
1249 if (@{$mode->{TEXT}}) {
1250 unshift @hunk, $mode;
1252 if (@{$deletion->{TEXT}}) {
1253 foreach my $hunk (@hunk) {
1254 push @{$deletion->{TEXT}}, @{$hunk->{TEXT}};
1255 push @{$deletion->{DISPLAY}}, @{$hunk->{DISPLAY}};
1257 @hunk = ($deletion);
1260 $num = scalar @hunk;
1261 $ix = 0;
1263 while (1) {
1264 my ($prev, $next, $other, $undecided, $i);
1265 $other = '';
1267 if ($num <= $ix) {
1268 $ix = 0;
1270 for ($i = 0; $i < $ix; $i++) {
1271 if (!defined $hunk[$i]{USE}) {
1272 $prev = 1;
1273 $other .= ',k';
1274 last;
1277 if ($ix) {
1278 $other .= ',K';
1280 for ($i = $ix + 1; $i < $num; $i++) {
1281 if (!defined $hunk[$i]{USE}) {
1282 $next = 1;
1283 $other .= ',j';
1284 last;
1287 if ($ix < $num - 1) {
1288 $other .= ',J';
1290 if ($num > 1) {
1291 $other .= ',g';
1293 for ($i = 0; $i < $num; $i++) {
1294 if (!defined $hunk[$i]{USE}) {
1295 $undecided = 1;
1296 last;
1299 last if (!$undecided);
1301 if ($hunk[$ix]{TYPE} eq 'hunk' &&
1302 hunk_splittable($hunk[$ix]{TEXT})) {
1303 $other .= ',s';
1305 if ($hunk[$ix]{TYPE} eq 'hunk') {
1306 $other .= ',e';
1308 for (@{$hunk[$ix]{DISPLAY}}) {
1309 print;
1311 print colored $prompt_color, $patch_mode_flavour{VERB},
1312 ($hunk[$ix]{TYPE} eq 'mode' ? ' mode change' :
1313 $hunk[$ix]{TYPE} eq 'deletion' ? ' deletion' :
1314 ' this hunk'),
1315 $patch_mode_flavour{TARGET},
1316 " [y,n,q,a,d,/$other,?]? ";
1317 my $line = prompt_single_character;
1318 if ($line) {
1319 if ($line =~ /^y/i) {
1320 $hunk[$ix]{USE} = 1;
1322 elsif ($line =~ /^n/i) {
1323 $hunk[$ix]{USE} = 0;
1325 elsif ($line =~ /^a/i) {
1326 while ($ix < $num) {
1327 if (!defined $hunk[$ix]{USE}) {
1328 $hunk[$ix]{USE} = 1;
1330 $ix++;
1332 next;
1334 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1335 my $response = $1;
1336 my $no = $ix > 10 ? $ix - 10 : 0;
1337 while ($response eq '') {
1338 my $extra = "";
1339 $no = display_hunks(\@hunk, $no);
1340 if ($no < $num) {
1341 $extra = " (<ret> to see more)";
1343 print "go to which hunk$extra? ";
1344 $response = <STDIN>;
1345 if (!defined $response) {
1346 $response = '';
1348 chomp $response;
1350 if ($response !~ /^\s*\d+\s*$/) {
1351 error_msg "Invalid number: '$response'\n";
1352 } elsif (0 < $response && $response <= $num) {
1353 $ix = $response - 1;
1354 } else {
1355 error_msg "Sorry, only $num hunks available.\n";
1357 next;
1359 elsif ($line =~ /^d/i) {
1360 while ($ix < $num) {
1361 if (!defined $hunk[$ix]{USE}) {
1362 $hunk[$ix]{USE} = 0;
1364 $ix++;
1366 next;
1368 elsif ($line =~ /^q/i) {
1369 while ($ix < $num) {
1370 if (!defined $hunk[$ix]{USE}) {
1371 $hunk[$ix]{USE} = 0;
1373 $ix++;
1375 $quit = 1;
1376 next;
1378 elsif ($line =~ m|^/(.*)|) {
1379 my $regex = $1;
1380 if ($1 eq "") {
1381 print colored $prompt_color, "search for regex? ";
1382 $regex = <STDIN>;
1383 if (defined $regex) {
1384 chomp $regex;
1387 my $search_string;
1388 eval {
1389 $search_string = qr{$regex}m;
1391 if ($@) {
1392 my ($err,$exp) = ($@, $1);
1393 $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1394 error_msg "Malformed search regexp $exp: $err\n";
1395 next;
1397 my $iy = $ix;
1398 while (1) {
1399 my $text = join ("", @{$hunk[$iy]{TEXT}});
1400 last if ($text =~ $search_string);
1401 $iy++;
1402 $iy = 0 if ($iy >= $num);
1403 if ($ix == $iy) {
1404 error_msg "No hunk matches the given pattern\n";
1405 last;
1408 $ix = $iy;
1409 next;
1411 elsif ($line =~ /^K/) {
1412 if ($other =~ /K/) {
1413 $ix--;
1415 else {
1416 error_msg "No previous hunk\n";
1418 next;
1420 elsif ($line =~ /^J/) {
1421 if ($other =~ /J/) {
1422 $ix++;
1424 else {
1425 error_msg "No next hunk\n";
1427 next;
1429 elsif ($line =~ /^k/) {
1430 if ($other =~ /k/) {
1431 while (1) {
1432 $ix--;
1433 last if (!$ix ||
1434 !defined $hunk[$ix]{USE});
1437 else {
1438 error_msg "No previous hunk\n";
1440 next;
1442 elsif ($line =~ /^j/) {
1443 if ($other !~ /j/) {
1444 error_msg "No next hunk\n";
1445 next;
1448 elsif ($other =~ /s/ && $line =~ /^s/) {
1449 my @split = split_hunk($hunk[$ix]{TEXT}, $hunk[$ix]{DISPLAY});
1450 if (1 < @split) {
1451 print colored $header_color, "Split into ",
1452 scalar(@split), " hunks.\n";
1454 splice (@hunk, $ix, 1, @split);
1455 $num = scalar @hunk;
1456 next;
1458 elsif ($other =~ /e/ && $line =~ /^e/) {
1459 my $newhunk = edit_hunk_loop($head, \@hunk, $ix);
1460 if (defined $newhunk) {
1461 splice @hunk, $ix, 1, $newhunk;
1464 else {
1465 help_patch_cmd($other);
1466 next;
1468 # soft increment
1469 while (1) {
1470 $ix++;
1471 last if ($ix >= $num ||
1472 !defined $hunk[$ix]{USE});
1477 @hunk = coalesce_overlapping_hunks(@hunk);
1479 my $n_lofs = 0;
1480 my @result = ();
1481 for (@hunk) {
1482 if ($_->{USE}) {
1483 push @result, @{$_->{TEXT}};
1487 if (@result) {
1488 my $fh;
1489 my @patch = reassemble_patch($head->{TEXT}, @result);
1490 my $apply_routine = $patch_mode_flavour{APPLY};
1491 &$apply_routine(@patch);
1492 refresh();
1495 print "\n";
1496 return $quit;
1499 sub diff_cmd {
1500 my @mods = list_modified('index-only');
1501 @mods = grep { !($_->{BINARY}) } @mods;
1502 return if (!@mods);
1503 my (@them) = list_and_choose({ PROMPT => 'Review diff',
1504 IMMEDIATE => 1,
1505 HEADER => $status_head, },
1506 @mods);
1507 return if (!@them);
1508 my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
1509 system(qw(git diff -p --cached), $reference, '--',
1510 map { $_->{VALUE} } @them);
1513 sub quit_cmd {
1514 print "Bye.\n";
1515 exit(0);
1518 sub help_cmd {
1519 print colored $help_color, <<\EOF ;
1520 status - show paths with changes
1521 update - add working tree state to the staged set of changes
1522 revert - revert staged set of changes back to the HEAD version
1523 patch - pick hunks and update selectively
1524 diff - view diff between HEAD and index
1525 add untracked - add contents of untracked files to the staged set of changes
1529 sub process_args {
1530 return unless @ARGV;
1531 my $arg = shift @ARGV;
1532 if ($arg =~ /--patch(?:=(.*))?/) {
1533 if (defined $1) {
1534 if ($1 eq 'reset') {
1535 $patch_mode = 'reset_head';
1536 $patch_mode_revision = 'HEAD';
1537 $arg = shift @ARGV or die "missing --";
1538 if ($arg ne '--') {
1539 $patch_mode_revision = $arg;
1540 $patch_mode = ($arg eq 'HEAD' ?
1541 'reset_head' : 'reset_nothead');
1542 $arg = shift @ARGV or die "missing --";
1544 } elsif ($1 eq 'checkout') {
1545 $arg = shift @ARGV or die "missing --";
1546 if ($arg eq '--') {
1547 $patch_mode = 'checkout_index';
1548 } else {
1549 $patch_mode_revision = $arg;
1550 $patch_mode = ($arg eq 'HEAD' ?
1551 'checkout_head' : 'checkout_nothead');
1552 $arg = shift @ARGV or die "missing --";
1554 } elsif ($1 eq 'stage' or $1 eq 'stash') {
1555 $patch_mode = $1;
1556 $arg = shift @ARGV or die "missing --";
1557 } else {
1558 die "unknown --patch mode: $1";
1560 } else {
1561 $patch_mode = 'stage';
1562 $arg = shift @ARGV or die "missing --";
1564 die "invalid argument $arg, expecting --"
1565 unless $arg eq "--";
1566 %patch_mode_flavour = %{$patch_modes{$patch_mode}};
1568 elsif ($arg ne "--") {
1569 die "invalid argument $arg, expecting --";
1573 sub main_loop {
1574 my @cmd = ([ 'status', \&status_cmd, ],
1575 [ 'update', \&update_cmd, ],
1576 [ 'revert', \&revert_cmd, ],
1577 [ 'add untracked', \&add_untracked_cmd, ],
1578 [ 'patch', \&patch_update_cmd, ],
1579 [ 'diff', \&diff_cmd, ],
1580 [ 'quit', \&quit_cmd, ],
1581 [ 'help', \&help_cmd, ],
1583 while (1) {
1584 my ($it) = list_and_choose({ PROMPT => 'What now',
1585 SINGLETON => 1,
1586 LIST_FLAT => 4,
1587 HEADER => '*** Commands ***',
1588 ON_EOF => \&quit_cmd,
1589 IMMEDIATE => 1 }, @cmd);
1590 if ($it) {
1591 eval {
1592 $it->[1]->();
1594 if ($@) {
1595 print "$@";
1601 process_args();
1602 refresh();
1603 if ($patch_mode) {
1604 patch_update_cmd();
1606 else {
1607 status_cmd();
1608 main_loop();