t1510: setup case #8
[git/mjg.git] / git-add--interactive.perl
blob77f60fa3960323e412f8d09968e63865cc639298
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',
93 'stash' => {
94 DIFF => 'diff-index -p HEAD',
95 APPLY => sub { apply_patch 'apply --cached', @_; },
96 APPLY_CHECK => 'apply --cached',
97 VERB => 'Stash',
98 TARGET => '',
99 PARTICIPLE => 'stashing',
100 FILTER => undef,
102 'reset_head' => {
103 DIFF => 'diff-index -p --cached',
104 APPLY => sub { apply_patch 'apply -R --cached', @_; },
105 APPLY_CHECK => 'apply -R --cached',
106 VERB => 'Unstage',
107 TARGET => '',
108 PARTICIPLE => 'unstaging',
109 FILTER => 'index-only',
111 'reset_nothead' => {
112 DIFF => 'diff-index -R -p --cached',
113 APPLY => sub { apply_patch 'apply --cached', @_; },
114 APPLY_CHECK => 'apply --cached',
115 VERB => 'Apply',
116 TARGET => ' to index',
117 PARTICIPLE => 'applying',
118 FILTER => 'index-only',
120 'checkout_index' => {
121 DIFF => 'diff-files -p',
122 APPLY => sub { apply_patch 'apply -R', @_; },
123 APPLY_CHECK => 'apply -R',
124 VERB => 'Discard',
125 TARGET => ' from worktree',
126 PARTICIPLE => 'discarding',
127 FILTER => 'file-only',
129 'checkout_head' => {
130 DIFF => 'diff-index -p',
131 APPLY => sub { apply_patch_for_checkout_commit '-R', @_ },
132 APPLY_CHECK => 'apply -R',
133 VERB => 'Discard',
134 TARGET => ' from index and worktree',
135 PARTICIPLE => 'discarding',
136 FILTER => undef,
138 'checkout_nothead' => {
139 DIFF => 'diff-index -R -p',
140 APPLY => sub { apply_patch_for_checkout_commit '', @_ },
141 APPLY_CHECK => 'apply',
142 VERB => 'Apply',
143 TARGET => ' to index and worktree',
144 PARTICIPLE => 'applying',
145 FILTER => undef,
149 my %patch_mode_flavour = %{$patch_modes{stage}};
151 sub run_cmd_pipe {
152 if ($^O eq 'MSWin32' || $^O eq 'msys') {
153 my @invalid = grep {m/[":*]/} @_;
154 die "$^O does not support: @invalid\n" if @invalid;
155 my @args = map { m/ /o ? "\"$_\"": $_ } @_;
156 return qx{@args};
157 } else {
158 my $fh = undef;
159 open($fh, '-|', @_) or die;
160 return <$fh>;
164 my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));
166 if (!defined $GIT_DIR) {
167 exit(1); # rev-parse would have already said "not a git repo"
169 chomp($GIT_DIR);
171 my %cquote_map = (
172 "b" => chr(8),
173 "t" => chr(9),
174 "n" => chr(10),
175 "v" => chr(11),
176 "f" => chr(12),
177 "r" => chr(13),
178 "\\" => "\\",
179 "\042" => "\042",
182 sub unquote_path {
183 local ($_) = @_;
184 my ($retval, $remainder);
185 if (!/^\042(.*)\042$/) {
186 return $_;
188 ($_, $retval) = ($1, "");
189 while (/^([^\\]*)\\(.*)$/) {
190 $remainder = $2;
191 $retval .= $1;
192 for ($remainder) {
193 if (/^([0-3][0-7][0-7])(.*)$/) {
194 $retval .= chr(oct($1));
195 $_ = $2;
196 last;
198 if (/^([\\\042btnvfr])(.*)$/) {
199 $retval .= $cquote_map{$1};
200 $_ = $2;
201 last;
203 # This is malformed -- just return it as-is for now.
204 return $_[0];
206 $_ = $remainder;
208 $retval .= $_;
209 return $retval;
212 sub refresh {
213 my $fh;
214 open $fh, 'git update-index --refresh |'
215 or die;
216 while (<$fh>) {
217 ;# ignore 'needs update'
219 close $fh;
222 sub list_untracked {
223 map {
224 chomp $_;
225 unquote_path($_);
227 run_cmd_pipe(qw(git ls-files --others --exclude-standard --), @ARGV);
230 my $status_fmt = '%12s %12s %s';
231 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
234 my $initial;
235 sub is_initial_commit {
236 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
237 unless defined $initial;
238 return $initial;
242 sub get_empty_tree {
243 return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
246 # Returns list of hashes, contents of each of which are:
247 # VALUE: pathname
248 # BINARY: is a binary path
249 # INDEX: is index different from HEAD?
250 # FILE: is file different from index?
251 # INDEX_ADDDEL: is it add/delete between HEAD and index?
252 # FILE_ADDDEL: is it add/delete between index and file?
254 sub list_modified {
255 my ($only) = @_;
256 my (%data, @return);
257 my ($add, $del, $adddel, $file);
258 my @tracked = ();
260 if (@ARGV) {
261 @tracked = map {
262 chomp $_;
263 unquote_path($_);
264 } run_cmd_pipe(qw(git ls-files --), @ARGV);
265 return if (!@tracked);
268 my $reference;
269 if (defined $patch_mode_revision and $patch_mode_revision ne 'HEAD') {
270 $reference = $patch_mode_revision;
271 } elsif (is_initial_commit()) {
272 $reference = get_empty_tree();
273 } else {
274 $reference = 'HEAD';
276 for (run_cmd_pipe(qw(git diff-index --cached
277 --numstat --summary), $reference,
278 '--', @tracked)) {
279 if (($add, $del, $file) =
280 /^([-\d]+) ([-\d]+) (.*)/) {
281 my ($change, $bin);
282 $file = unquote_path($file);
283 if ($add eq '-' && $del eq '-') {
284 $change = 'binary';
285 $bin = 1;
287 else {
288 $change = "+$add/-$del";
290 $data{$file} = {
291 INDEX => $change,
292 BINARY => $bin,
293 FILE => 'nothing',
296 elsif (($adddel, $file) =
297 /^ (create|delete) mode [0-7]+ (.*)$/) {
298 $file = unquote_path($file);
299 $data{$file}{INDEX_ADDDEL} = $adddel;
303 for (run_cmd_pipe(qw(git diff-files --numstat --summary --), @tracked)) {
304 if (($add, $del, $file) =
305 /^([-\d]+) ([-\d]+) (.*)/) {
306 $file = unquote_path($file);
307 if (!exists $data{$file}) {
308 $data{$file} = +{
309 INDEX => 'unchanged',
310 BINARY => 0,
313 my ($change, $bin);
314 if ($add eq '-' && $del eq '-') {
315 $change = 'binary';
316 $bin = 1;
318 else {
319 $change = "+$add/-$del";
321 $data{$file}{FILE} = $change;
322 if ($bin) {
323 $data{$file}{BINARY} = 1;
326 elsif (($adddel, $file) =
327 /^ (create|delete) mode [0-7]+ (.*)$/) {
328 $file = unquote_path($file);
329 $data{$file}{FILE_ADDDEL} = $adddel;
333 for (sort keys %data) {
334 my $it = $data{$_};
336 if ($only) {
337 if ($only eq 'index-only') {
338 next if ($it->{INDEX} eq 'unchanged');
340 if ($only eq 'file-only') {
341 next if ($it->{FILE} eq 'nothing');
344 push @return, +{
345 VALUE => $_,
346 %$it,
349 return @return;
352 sub find_unique {
353 my ($string, @stuff) = @_;
354 my $found = undef;
355 for (my $i = 0; $i < @stuff; $i++) {
356 my $it = $stuff[$i];
357 my $hit = undef;
358 if (ref $it) {
359 if ((ref $it) eq 'ARRAY') {
360 $it = $it->[0];
362 else {
363 $it = $it->{VALUE};
366 eval {
367 if ($it =~ /^$string/) {
368 $hit = 1;
371 if (defined $hit && defined $found) {
372 return undef;
374 if ($hit) {
375 $found = $i + 1;
378 return $found;
381 # inserts string into trie and updates count for each character
382 sub update_trie {
383 my ($trie, $string) = @_;
384 foreach (split //, $string) {
385 $trie = $trie->{$_} ||= {COUNT => 0};
386 $trie->{COUNT}++;
390 # returns an array of tuples (prefix, remainder)
391 sub find_unique_prefixes {
392 my @stuff = @_;
393 my @return = ();
395 # any single prefix exceeding the soft limit is omitted
396 # if any prefix exceeds the hard limit all are omitted
397 # 0 indicates no limit
398 my $soft_limit = 0;
399 my $hard_limit = 3;
401 # build a trie modelling all possible options
402 my %trie;
403 foreach my $print (@stuff) {
404 if ((ref $print) eq 'ARRAY') {
405 $print = $print->[0];
407 elsif ((ref $print) eq 'HASH') {
408 $print = $print->{VALUE};
410 update_trie(\%trie, $print);
411 push @return, $print;
414 # use the trie to find the unique prefixes
415 for (my $i = 0; $i < @return; $i++) {
416 my $ret = $return[$i];
417 my @letters = split //, $ret;
418 my %search = %trie;
419 my ($prefix, $remainder);
420 my $j;
421 for ($j = 0; $j < @letters; $j++) {
422 my $letter = $letters[$j];
423 if ($search{$letter}{COUNT} == 1) {
424 $prefix = substr $ret, 0, $j + 1;
425 $remainder = substr $ret, $j + 1;
426 last;
428 else {
429 my $prefix = substr $ret, 0, $j;
430 return ()
431 if ($hard_limit && $j + 1 > $hard_limit);
433 %search = %{$search{$letter}};
435 if (ord($letters[0]) > 127 ||
436 ($soft_limit && $j + 1 > $soft_limit)) {
437 $prefix = undef;
438 $remainder = $ret;
440 $return[$i] = [$prefix, $remainder];
442 return @return;
445 # filters out prefixes which have special meaning to list_and_choose()
446 sub is_valid_prefix {
447 my $prefix = shift;
448 return (defined $prefix) &&
449 !($prefix =~ /[\s,]/) && # separators
450 !($prefix =~ /^-/) && # deselection
451 !($prefix =~ /^\d+/) && # selection
452 ($prefix ne '*') && # "all" wildcard
453 ($prefix ne '?'); # prompt help
456 # given a prefix/remainder tuple return a string with the prefix highlighted
457 # for now use square brackets; later might use ANSI colors (underline, bold)
458 sub highlight_prefix {
459 my $prefix = shift;
460 my $remainder = shift;
462 if (!defined $prefix) {
463 return $remainder;
466 if (!is_valid_prefix($prefix)) {
467 return "$prefix$remainder";
470 if (!$menu_use_color) {
471 return "[$prefix]$remainder";
474 return "$prompt_color$prefix$normal_color$remainder";
477 sub error_msg {
478 print STDERR colored $error_color, @_;
481 sub list_and_choose {
482 my ($opts, @stuff) = @_;
483 my (@chosen, @return);
484 my $i;
485 my @prefixes = find_unique_prefixes(@stuff) unless $opts->{LIST_ONLY};
487 TOPLOOP:
488 while (1) {
489 my $last_lf = 0;
491 if ($opts->{HEADER}) {
492 if (!$opts->{LIST_FLAT}) {
493 print " ";
495 print colored $header_color, "$opts->{HEADER}\n";
497 for ($i = 0; $i < @stuff; $i++) {
498 my $chosen = $chosen[$i] ? '*' : ' ';
499 my $print = $stuff[$i];
500 my $ref = ref $print;
501 my $highlighted = highlight_prefix(@{$prefixes[$i]})
502 if @prefixes;
503 if ($ref eq 'ARRAY') {
504 $print = $highlighted || $print->[0];
506 elsif ($ref eq 'HASH') {
507 my $value = $highlighted || $print->{VALUE};
508 $print = sprintf($status_fmt,
509 $print->{INDEX},
510 $print->{FILE},
511 $value);
513 else {
514 $print = $highlighted || $print;
516 printf("%s%2d: %s", $chosen, $i+1, $print);
517 if (($opts->{LIST_FLAT}) &&
518 (($i + 1) % ($opts->{LIST_FLAT}))) {
519 print "\t";
520 $last_lf = 0;
522 else {
523 print "\n";
524 $last_lf = 1;
527 if (!$last_lf) {
528 print "\n";
531 return if ($opts->{LIST_ONLY});
533 print colored $prompt_color, $opts->{PROMPT};
534 if ($opts->{SINGLETON}) {
535 print "> ";
537 else {
538 print ">> ";
540 my $line = <STDIN>;
541 if (!$line) {
542 print "\n";
543 $opts->{ON_EOF}->() if $opts->{ON_EOF};
544 last;
546 chomp $line;
547 last if $line eq '';
548 if ($line eq '?') {
549 $opts->{SINGLETON} ?
550 singleton_prompt_help_cmd() :
551 prompt_help_cmd();
552 next TOPLOOP;
554 for my $choice (split(/[\s,]+/, $line)) {
555 my $choose = 1;
556 my ($bottom, $top);
558 # Input that begins with '-'; unchoose
559 if ($choice =~ s/^-//) {
560 $choose = 0;
562 # A range can be specified like 5-7 or 5-.
563 if ($choice =~ /^(\d+)-(\d*)$/) {
564 ($bottom, $top) = ($1, length($2) ? $2 : 1 + @stuff);
566 elsif ($choice =~ /^\d+$/) {
567 $bottom = $top = $choice;
569 elsif ($choice eq '*') {
570 $bottom = 1;
571 $top = 1 + @stuff;
573 else {
574 $bottom = $top = find_unique($choice, @stuff);
575 if (!defined $bottom) {
576 error_msg "Huh ($choice)?\n";
577 next TOPLOOP;
580 if ($opts->{SINGLETON} && $bottom != $top) {
581 error_msg "Huh ($choice)?\n";
582 next TOPLOOP;
584 for ($i = $bottom-1; $i <= $top-1; $i++) {
585 next if (@stuff <= $i || $i < 0);
586 $chosen[$i] = $choose;
589 last if ($opts->{IMMEDIATE} || $line eq '*');
591 for ($i = 0; $i < @stuff; $i++) {
592 if ($chosen[$i]) {
593 push @return, $stuff[$i];
596 return @return;
599 sub singleton_prompt_help_cmd {
600 print colored $help_color, <<\EOF ;
601 Prompt help:
602 1 - select a numbered item
603 foo - select item based on unique prefix
604 - (empty) select nothing
608 sub prompt_help_cmd {
609 print colored $help_color, <<\EOF ;
610 Prompt help:
611 1 - select a single item
612 3-5 - select a range of items
613 2-3,6-9 - select multiple ranges
614 foo - select item based on unique prefix
615 -... - unselect specified items
616 * - choose all items
617 - (empty) finish selecting
621 sub status_cmd {
622 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
623 list_modified());
624 print "\n";
627 sub say_n_paths {
628 my $did = shift @_;
629 my $cnt = scalar @_;
630 print "$did ";
631 if (1 < $cnt) {
632 print "$cnt paths\n";
634 else {
635 print "one path\n";
639 sub update_cmd {
640 my @mods = list_modified('file-only');
641 return if (!@mods);
643 my @update = list_and_choose({ PROMPT => 'Update',
644 HEADER => $status_head, },
645 @mods);
646 if (@update) {
647 system(qw(git update-index --add --remove --),
648 map { $_->{VALUE} } @update);
649 say_n_paths('updated', @update);
651 print "\n";
654 sub revert_cmd {
655 my @update = list_and_choose({ PROMPT => 'Revert',
656 HEADER => $status_head, },
657 list_modified());
658 if (@update) {
659 if (is_initial_commit()) {
660 system(qw(git rm --cached),
661 map { $_->{VALUE} } @update);
663 else {
664 my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
665 map { $_->{VALUE} } @update);
666 my $fh;
667 open $fh, '| git update-index --index-info'
668 or die;
669 for (@lines) {
670 print $fh $_;
672 close($fh);
673 for (@update) {
674 if ($_->{INDEX_ADDDEL} &&
675 $_->{INDEX_ADDDEL} eq 'create') {
676 system(qw(git update-index --force-remove --),
677 $_->{VALUE});
678 print "note: $_->{VALUE} is untracked now.\n";
682 refresh();
683 say_n_paths('reverted', @update);
685 print "\n";
688 sub add_untracked_cmd {
689 my @add = list_and_choose({ PROMPT => 'Add untracked' },
690 list_untracked());
691 if (@add) {
692 system(qw(git update-index --add --), @add);
693 say_n_paths('added', @add);
695 print "\n";
698 sub run_git_apply {
699 my $cmd = shift;
700 my $fh;
701 open $fh, '| git ' . $cmd;
702 print $fh @_;
703 return close $fh;
706 sub parse_diff {
707 my ($path) = @_;
708 my @diff_cmd = split(" ", $patch_mode_flavour{DIFF});
709 if (defined $patch_mode_revision) {
710 push @diff_cmd, $patch_mode_revision;
712 my @diff = run_cmd_pipe("git", @diff_cmd, "--", $path);
713 my @colored = ();
714 if ($diff_use_color) {
715 @colored = run_cmd_pipe("git", @diff_cmd, qw(--color --), $path);
717 my (@hunk) = { TEXT => [], DISPLAY => [], TYPE => 'header' };
719 for (my $i = 0; $i < @diff; $i++) {
720 if ($diff[$i] =~ /^@@ /) {
721 push @hunk, { TEXT => [], DISPLAY => [],
722 TYPE => 'hunk' };
724 push @{$hunk[-1]{TEXT}}, $diff[$i];
725 push @{$hunk[-1]{DISPLAY}},
726 ($diff_use_color ? $colored[$i] : $diff[$i]);
728 return @hunk;
731 sub parse_diff_header {
732 my $src = shift;
734 my $head = { TEXT => [], DISPLAY => [], TYPE => 'header' };
735 my $mode = { TEXT => [], DISPLAY => [], TYPE => 'mode' };
736 my $deletion = { TEXT => [], DISPLAY => [], TYPE => 'deletion' };
738 for (my $i = 0; $i < @{$src->{TEXT}}; $i++) {
739 my $dest =
740 $src->{TEXT}->[$i] =~ /^(old|new) mode (\d+)$/ ? $mode :
741 $src->{TEXT}->[$i] =~ /^deleted file/ ? $deletion :
742 $head;
743 push @{$dest->{TEXT}}, $src->{TEXT}->[$i];
744 push @{$dest->{DISPLAY}}, $src->{DISPLAY}->[$i];
746 return ($head, $mode, $deletion);
749 sub hunk_splittable {
750 my ($text) = @_;
752 my @s = split_hunk($text);
753 return (1 < @s);
756 sub parse_hunk_header {
757 my ($line) = @_;
758 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
759 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
760 $o_cnt = 1 unless defined $o_cnt;
761 $n_cnt = 1 unless defined $n_cnt;
762 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
765 sub split_hunk {
766 my ($text, $display) = @_;
767 my @split = ();
768 if (!defined $display) {
769 $display = $text;
771 # If there are context lines in the middle of a hunk,
772 # it can be split, but we would need to take care of
773 # overlaps later.
775 my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
776 my $hunk_start = 1;
778 OUTER:
779 while (1) {
780 my $next_hunk_start = undef;
781 my $i = $hunk_start - 1;
782 my $this = +{
783 TEXT => [],
784 DISPLAY => [],
785 TYPE => 'hunk',
786 OLD => $o_ofs,
787 NEW => $n_ofs,
788 OCNT => 0,
789 NCNT => 0,
790 ADDDEL => 0,
791 POSTCTX => 0,
792 USE => undef,
795 while (++$i < @$text) {
796 my $line = $text->[$i];
797 my $display = $display->[$i];
798 if ($line =~ /^ /) {
799 if ($this->{ADDDEL} &&
800 !defined $next_hunk_start) {
801 # We have seen leading context and
802 # adds/dels and then here is another
803 # context, which is trailing for this
804 # split hunk and leading for the next
805 # one.
806 $next_hunk_start = $i;
808 push @{$this->{TEXT}}, $line;
809 push @{$this->{DISPLAY}}, $display;
810 $this->{OCNT}++;
811 $this->{NCNT}++;
812 if (defined $next_hunk_start) {
813 $this->{POSTCTX}++;
815 next;
818 # add/del
819 if (defined $next_hunk_start) {
820 # We are done with the current hunk and
821 # this is the first real change for the
822 # next split one.
823 $hunk_start = $next_hunk_start;
824 $o_ofs = $this->{OLD} + $this->{OCNT};
825 $n_ofs = $this->{NEW} + $this->{NCNT};
826 $o_ofs -= $this->{POSTCTX};
827 $n_ofs -= $this->{POSTCTX};
828 push @split, $this;
829 redo OUTER;
831 push @{$this->{TEXT}}, $line;
832 push @{$this->{DISPLAY}}, $display;
833 $this->{ADDDEL}++;
834 if ($line =~ /^-/) {
835 $this->{OCNT}++;
837 else {
838 $this->{NCNT}++;
842 push @split, $this;
843 last;
846 for my $hunk (@split) {
847 $o_ofs = $hunk->{OLD};
848 $n_ofs = $hunk->{NEW};
849 my $o_cnt = $hunk->{OCNT};
850 my $n_cnt = $hunk->{NCNT};
852 my $head = ("@@ -$o_ofs" .
853 (($o_cnt != 1) ? ",$o_cnt" : '') .
854 " +$n_ofs" .
855 (($n_cnt != 1) ? ",$n_cnt" : '') .
856 " @@\n");
857 my $display_head = $head;
858 unshift @{$hunk->{TEXT}}, $head;
859 if ($diff_use_color) {
860 $display_head = colored($fraginfo_color, $head);
862 unshift @{$hunk->{DISPLAY}}, $display_head;
864 return @split;
867 sub find_last_o_ctx {
868 my ($it) = @_;
869 my $text = $it->{TEXT};
870 my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
871 my $i = @{$text};
872 my $last_o_ctx = $o_ofs + $o_cnt;
873 while (0 < --$i) {
874 my $line = $text->[$i];
875 if ($line =~ /^ /) {
876 $last_o_ctx--;
877 next;
879 last;
881 return $last_o_ctx;
884 sub merge_hunk {
885 my ($prev, $this) = @_;
886 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
887 parse_hunk_header($prev->{TEXT}[0]);
888 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
889 parse_hunk_header($this->{TEXT}[0]);
891 my (@line, $i, $ofs, $o_cnt, $n_cnt);
892 $ofs = $o0_ofs;
893 $o_cnt = $n_cnt = 0;
894 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
895 my $line = $prev->{TEXT}[$i];
896 if ($line =~ /^\+/) {
897 $n_cnt++;
898 push @line, $line;
899 next;
902 last if ($o1_ofs <= $ofs);
904 $o_cnt++;
905 $ofs++;
906 if ($line =~ /^ /) {
907 $n_cnt++;
909 push @line, $line;
912 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
913 my $line = $this->{TEXT}[$i];
914 if ($line =~ /^\+/) {
915 $n_cnt++;
916 push @line, $line;
917 next;
919 $ofs++;
920 $o_cnt++;
921 if ($line =~ /^ /) {
922 $n_cnt++;
924 push @line, $line;
926 my $head = ("@@ -$o0_ofs" .
927 (($o_cnt != 1) ? ",$o_cnt" : '') .
928 " +$n0_ofs" .
929 (($n_cnt != 1) ? ",$n_cnt" : '') .
930 " @@\n");
931 @{$prev->{TEXT}} = ($head, @line);
934 sub coalesce_overlapping_hunks {
935 my (@in) = @_;
936 my @out = ();
938 my ($last_o_ctx, $last_was_dirty);
940 for (grep { $_->{USE} } @in) {
941 if ($_->{TYPE} ne 'hunk') {
942 push @out, $_;
943 next;
945 my $text = $_->{TEXT};
946 my ($o_ofs) = parse_hunk_header($text->[0]);
947 if (defined $last_o_ctx &&
948 $o_ofs <= $last_o_ctx &&
949 !$_->{DIRTY} &&
950 !$last_was_dirty) {
951 merge_hunk($out[-1], $_);
953 else {
954 push @out, $_;
956 $last_o_ctx = find_last_o_ctx($out[-1]);
957 $last_was_dirty = $_->{DIRTY};
959 return @out;
962 sub reassemble_patch {
963 my $head = shift;
964 my @patch;
966 # Include everything in the header except the beginning of the diff.
967 push @patch, (grep { !/^[-+]{3}/ } @$head);
969 # Then include any headers from the hunk lines, which must
970 # come before any actual hunk.
971 while (@_ && $_[0] !~ /^@/) {
972 push @patch, shift;
975 # Then begin the diff.
976 push @patch, grep { /^[-+]{3}/ } @$head;
978 # And then the actual hunks.
979 push @patch, @_;
981 return @patch;
984 sub color_diff {
985 return map {
986 colored((/^@/ ? $fraginfo_color :
987 /^\+/ ? $diff_new_color :
988 /^-/ ? $diff_old_color :
989 $diff_plain_color),
990 $_);
991 } @_;
994 sub edit_hunk_manually {
995 my ($oldtext) = @_;
997 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
998 my $fh;
999 open $fh, '>', $hunkfile
1000 or die "failed to open hunk edit file for writing: " . $!;
1001 print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
1002 print $fh @$oldtext;
1003 my $participle = $patch_mode_flavour{PARTICIPLE};
1004 print $fh <<EOF;
1005 # ---
1006 # To remove '-' lines, make them ' ' lines (context).
1007 # To remove '+' lines, delete them.
1008 # Lines starting with # will be removed.
1010 # If the patch applies cleanly, the edited hunk will immediately be
1011 # marked for $participle. If it does not apply cleanly, you will be given
1012 # an opportunity to edit again. If all lines of the hunk are removed,
1013 # then the edit is aborted and the hunk is left unchanged.
1015 close $fh;
1017 chomp(my $editor = run_cmd_pipe(qw(git var GIT_EDITOR)));
1018 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
1020 if ($? != 0) {
1021 return undef;
1024 open $fh, '<', $hunkfile
1025 or die "failed to open hunk edit file for reading: " . $!;
1026 my @newtext = grep { !/^#/ } <$fh>;
1027 close $fh;
1028 unlink $hunkfile;
1030 # Abort if nothing remains
1031 if (!grep { /\S/ } @newtext) {
1032 return undef;
1035 # Reinsert the first hunk header if the user accidentally deleted it
1036 if ($newtext[0] !~ /^@/) {
1037 unshift @newtext, $oldtext->[0];
1039 return \@newtext;
1042 sub diff_applies {
1043 my $fh;
1044 return run_git_apply($patch_mode_flavour{APPLY_CHECK} . ' --recount --check',
1045 map { @{$_->{TEXT}} } @_);
1048 sub _restore_terminal_and_die {
1049 ReadMode 'restore';
1050 print "\n";
1051 exit 1;
1054 sub prompt_single_character {
1055 if ($use_readkey) {
1056 local $SIG{TERM} = \&_restore_terminal_and_die;
1057 local $SIG{INT} = \&_restore_terminal_and_die;
1058 ReadMode 'cbreak';
1059 my $key = ReadKey 0;
1060 ReadMode 'restore';
1061 print "$key" if defined $key;
1062 print "\n";
1063 return $key;
1064 } else {
1065 return <STDIN>;
1069 sub prompt_yesno {
1070 my ($prompt) = @_;
1071 while (1) {
1072 print colored $prompt_color, $prompt;
1073 my $line = prompt_single_character;
1074 return 0 if $line =~ /^n/i;
1075 return 1 if $line =~ /^y/i;
1079 sub edit_hunk_loop {
1080 my ($head, $hunk, $ix) = @_;
1081 my $text = $hunk->[$ix]->{TEXT};
1083 while (1) {
1084 $text = edit_hunk_manually($text);
1085 if (!defined $text) {
1086 return undef;
1088 my $newhunk = {
1089 TEXT => $text,
1090 TYPE => $hunk->[$ix]->{TYPE},
1091 USE => 1,
1092 DIRTY => 1,
1094 if (diff_applies($head,
1095 @{$hunk}[0..$ix-1],
1096 $newhunk,
1097 @{$hunk}[$ix+1..$#{$hunk}])) {
1098 $newhunk->{DISPLAY} = [color_diff(@{$text})];
1099 return $newhunk;
1101 else {
1102 prompt_yesno(
1103 'Your edited hunk does not apply. Edit again '
1104 . '(saying "no" discards!) [y/n]? '
1105 ) or return undef;
1110 sub help_patch_cmd {
1111 my $verb = lc $patch_mode_flavour{VERB};
1112 my $target = $patch_mode_flavour{TARGET};
1113 print colored $help_color, <<EOF ;
1114 y - $verb this hunk$target
1115 n - do not $verb this hunk$target
1116 q - quit; do not $verb this hunk nor any of the remaining ones
1117 a - $verb this hunk and all later hunks in the file
1118 d - do not $verb this hunk nor any of the later hunks in the file
1119 g - select a hunk to go to
1120 / - search for a hunk matching the given regex
1121 j - leave this hunk undecided, see next undecided hunk
1122 J - leave this hunk undecided, see next hunk
1123 k - leave this hunk undecided, see previous undecided hunk
1124 K - leave this hunk undecided, see previous hunk
1125 s - split the current hunk into smaller hunks
1126 e - manually edit the current hunk
1127 ? - print help
1131 sub apply_patch {
1132 my $cmd = shift;
1133 my $ret = run_git_apply $cmd . ' --recount', @_;
1134 if (!$ret) {
1135 print STDERR @_;
1137 return $ret;
1140 sub apply_patch_for_checkout_commit {
1141 my $reverse = shift;
1142 my $applies_index = run_git_apply 'apply '.$reverse.' --cached --recount --check', @_;
1143 my $applies_worktree = run_git_apply 'apply '.$reverse.' --recount --check', @_;
1145 if ($applies_worktree && $applies_index) {
1146 run_git_apply 'apply '.$reverse.' --cached --recount', @_;
1147 run_git_apply 'apply '.$reverse.' --recount', @_;
1148 return 1;
1149 } elsif (!$applies_index) {
1150 print colored $error_color, "The selected hunks do not apply to the index!\n";
1151 if (prompt_yesno "Apply them to the worktree anyway? ") {
1152 return run_git_apply 'apply '.$reverse.' --recount', @_;
1153 } else {
1154 print colored $error_color, "Nothing was applied.\n";
1155 return 0;
1157 } else {
1158 print STDERR @_;
1159 return 0;
1163 sub patch_update_cmd {
1164 my @all_mods = list_modified($patch_mode_flavour{FILTER});
1165 my @mods = grep { !($_->{BINARY}) } @all_mods;
1166 my @them;
1168 if (!@mods) {
1169 if (@all_mods) {
1170 print STDERR "Only binary files changed.\n";
1171 } else {
1172 print STDERR "No changes.\n";
1174 return 0;
1176 if ($patch_mode) {
1177 @them = @mods;
1179 else {
1180 @them = list_and_choose({ PROMPT => 'Patch update',
1181 HEADER => $status_head, },
1182 @mods);
1184 for (@them) {
1185 return 0 if patch_update_file($_->{VALUE});
1189 # Generate a one line summary of a hunk.
1190 sub summarize_hunk {
1191 my $rhunk = shift;
1192 my $summary = $rhunk->{TEXT}[0];
1194 # Keep the line numbers, discard extra context.
1195 $summary =~ s/@@(.*?)@@.*/$1 /s;
1196 $summary .= " " x (20 - length $summary);
1198 # Add some user context.
1199 for my $line (@{$rhunk->{TEXT}}) {
1200 if ($line =~ m/^[+-].*\w/) {
1201 $summary .= $line;
1202 last;
1206 chomp $summary;
1207 return substr($summary, 0, 80) . "\n";
1211 # Print a one-line summary of each hunk in the array ref in
1212 # the first argument, starting wih the index in the 2nd.
1213 sub display_hunks {
1214 my ($hunks, $i) = @_;
1215 my $ctr = 0;
1216 $i ||= 0;
1217 for (; $i < @$hunks && $ctr < 20; $i++, $ctr++) {
1218 my $status = " ";
1219 if (defined $hunks->[$i]{USE}) {
1220 $status = $hunks->[$i]{USE} ? "+" : "-";
1222 printf "%s%2d: %s",
1223 $status,
1224 $i + 1,
1225 summarize_hunk($hunks->[$i]);
1227 return $i;
1230 sub patch_update_file {
1231 my $quit = 0;
1232 my ($ix, $num);
1233 my $path = shift;
1234 my ($head, @hunk) = parse_diff($path);
1235 ($head, my $mode, my $deletion) = parse_diff_header($head);
1236 for (@{$head->{DISPLAY}}) {
1237 print;
1240 if (@{$mode->{TEXT}}) {
1241 unshift @hunk, $mode;
1243 if (@{$deletion->{TEXT}}) {
1244 foreach my $hunk (@hunk) {
1245 push @{$deletion->{TEXT}}, @{$hunk->{TEXT}};
1246 push @{$deletion->{DISPLAY}}, @{$hunk->{DISPLAY}};
1248 @hunk = ($deletion);
1251 $num = scalar @hunk;
1252 $ix = 0;
1254 while (1) {
1255 my ($prev, $next, $other, $undecided, $i);
1256 $other = '';
1258 if ($num <= $ix) {
1259 $ix = 0;
1261 for ($i = 0; $i < $ix; $i++) {
1262 if (!defined $hunk[$i]{USE}) {
1263 $prev = 1;
1264 $other .= ',k';
1265 last;
1268 if ($ix) {
1269 $other .= ',K';
1271 for ($i = $ix + 1; $i < $num; $i++) {
1272 if (!defined $hunk[$i]{USE}) {
1273 $next = 1;
1274 $other .= ',j';
1275 last;
1278 if ($ix < $num - 1) {
1279 $other .= ',J';
1281 if ($num > 1) {
1282 $other .= ',g';
1284 for ($i = 0; $i < $num; $i++) {
1285 if (!defined $hunk[$i]{USE}) {
1286 $undecided = 1;
1287 last;
1290 last if (!$undecided);
1292 if ($hunk[$ix]{TYPE} eq 'hunk' &&
1293 hunk_splittable($hunk[$ix]{TEXT})) {
1294 $other .= ',s';
1296 if ($hunk[$ix]{TYPE} eq 'hunk') {
1297 $other .= ',e';
1299 for (@{$hunk[$ix]{DISPLAY}}) {
1300 print;
1302 print colored $prompt_color, $patch_mode_flavour{VERB},
1303 ($hunk[$ix]{TYPE} eq 'mode' ? ' mode change' :
1304 $hunk[$ix]{TYPE} eq 'deletion' ? ' deletion' :
1305 ' this hunk'),
1306 $patch_mode_flavour{TARGET},
1307 " [y,n,q,a,d,/$other,?]? ";
1308 my $line = prompt_single_character;
1309 if ($line) {
1310 if ($line =~ /^y/i) {
1311 $hunk[$ix]{USE} = 1;
1313 elsif ($line =~ /^n/i) {
1314 $hunk[$ix]{USE} = 0;
1316 elsif ($line =~ /^a/i) {
1317 while ($ix < $num) {
1318 if (!defined $hunk[$ix]{USE}) {
1319 $hunk[$ix]{USE} = 1;
1321 $ix++;
1323 next;
1325 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1326 my $response = $1;
1327 my $no = $ix > 10 ? $ix - 10 : 0;
1328 while ($response eq '') {
1329 my $extra = "";
1330 $no = display_hunks(\@hunk, $no);
1331 if ($no < $num) {
1332 $extra = " (<ret> to see more)";
1334 print "go to which hunk$extra? ";
1335 $response = <STDIN>;
1336 if (!defined $response) {
1337 $response = '';
1339 chomp $response;
1341 if ($response !~ /^\s*\d+\s*$/) {
1342 error_msg "Invalid number: '$response'\n";
1343 } elsif (0 < $response && $response <= $num) {
1344 $ix = $response - 1;
1345 } else {
1346 error_msg "Sorry, only $num hunks available.\n";
1348 next;
1350 elsif ($line =~ /^d/i) {
1351 while ($ix < $num) {
1352 if (!defined $hunk[$ix]{USE}) {
1353 $hunk[$ix]{USE} = 0;
1355 $ix++;
1357 next;
1359 elsif ($line =~ /^q/i) {
1360 while ($ix < $num) {
1361 if (!defined $hunk[$ix]{USE}) {
1362 $hunk[$ix]{USE} = 0;
1364 $ix++;
1366 $quit = 1;
1367 next;
1369 elsif ($line =~ m|^/(.*)|) {
1370 my $regex = $1;
1371 if ($1 eq "") {
1372 print colored $prompt_color, "search for regex? ";
1373 $regex = <STDIN>;
1374 if (defined $regex) {
1375 chomp $regex;
1378 my $search_string;
1379 eval {
1380 $search_string = qr{$regex}m;
1382 if ($@) {
1383 my ($err,$exp) = ($@, $1);
1384 $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1385 error_msg "Malformed search regexp $exp: $err\n";
1386 next;
1388 my $iy = $ix;
1389 while (1) {
1390 my $text = join ("", @{$hunk[$iy]{TEXT}});
1391 last if ($text =~ $search_string);
1392 $iy++;
1393 $iy = 0 if ($iy >= $num);
1394 if ($ix == $iy) {
1395 error_msg "No hunk matches the given pattern\n";
1396 last;
1399 $ix = $iy;
1400 next;
1402 elsif ($line =~ /^K/) {
1403 if ($other =~ /K/) {
1404 $ix--;
1406 else {
1407 error_msg "No previous hunk\n";
1409 next;
1411 elsif ($line =~ /^J/) {
1412 if ($other =~ /J/) {
1413 $ix++;
1415 else {
1416 error_msg "No next hunk\n";
1418 next;
1420 elsif ($line =~ /^k/) {
1421 if ($other =~ /k/) {
1422 while (1) {
1423 $ix--;
1424 last if (!$ix ||
1425 !defined $hunk[$ix]{USE});
1428 else {
1429 error_msg "No previous hunk\n";
1431 next;
1433 elsif ($line =~ /^j/) {
1434 if ($other !~ /j/) {
1435 error_msg "No next hunk\n";
1436 next;
1439 elsif ($other =~ /s/ && $line =~ /^s/) {
1440 my @split = split_hunk($hunk[$ix]{TEXT}, $hunk[$ix]{DISPLAY});
1441 if (1 < @split) {
1442 print colored $header_color, "Split into ",
1443 scalar(@split), " hunks.\n";
1445 splice (@hunk, $ix, 1, @split);
1446 $num = scalar @hunk;
1447 next;
1449 elsif ($other =~ /e/ && $line =~ /^e/) {
1450 my $newhunk = edit_hunk_loop($head, \@hunk, $ix);
1451 if (defined $newhunk) {
1452 splice @hunk, $ix, 1, $newhunk;
1455 else {
1456 help_patch_cmd($other);
1457 next;
1459 # soft increment
1460 while (1) {
1461 $ix++;
1462 last if ($ix >= $num ||
1463 !defined $hunk[$ix]{USE});
1468 @hunk = coalesce_overlapping_hunks(@hunk);
1470 my $n_lofs = 0;
1471 my @result = ();
1472 for (@hunk) {
1473 if ($_->{USE}) {
1474 push @result, @{$_->{TEXT}};
1478 if (@result) {
1479 my $fh;
1480 my @patch = reassemble_patch($head->{TEXT}, @result);
1481 my $apply_routine = $patch_mode_flavour{APPLY};
1482 &$apply_routine(@patch);
1483 refresh();
1486 print "\n";
1487 return $quit;
1490 sub diff_cmd {
1491 my @mods = list_modified('index-only');
1492 @mods = grep { !($_->{BINARY}) } @mods;
1493 return if (!@mods);
1494 my (@them) = list_and_choose({ PROMPT => 'Review diff',
1495 IMMEDIATE => 1,
1496 HEADER => $status_head, },
1497 @mods);
1498 return if (!@them);
1499 my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
1500 system(qw(git diff -p --cached), $reference, '--',
1501 map { $_->{VALUE} } @them);
1504 sub quit_cmd {
1505 print "Bye.\n";
1506 exit(0);
1509 sub help_cmd {
1510 print colored $help_color, <<\EOF ;
1511 status - show paths with changes
1512 update - add working tree state to the staged set of changes
1513 revert - revert staged set of changes back to the HEAD version
1514 patch - pick hunks and update selectively
1515 diff - view diff between HEAD and index
1516 add untracked - add contents of untracked files to the staged set of changes
1520 sub process_args {
1521 return unless @ARGV;
1522 my $arg = shift @ARGV;
1523 if ($arg =~ /--patch(?:=(.*))?/) {
1524 if (defined $1) {
1525 if ($1 eq 'reset') {
1526 $patch_mode = 'reset_head';
1527 $patch_mode_revision = 'HEAD';
1528 $arg = shift @ARGV or die "missing --";
1529 if ($arg ne '--') {
1530 $patch_mode_revision = $arg;
1531 $patch_mode = ($arg eq 'HEAD' ?
1532 'reset_head' : 'reset_nothead');
1533 $arg = shift @ARGV or die "missing --";
1535 } elsif ($1 eq 'checkout') {
1536 $arg = shift @ARGV or die "missing --";
1537 if ($arg eq '--') {
1538 $patch_mode = 'checkout_index';
1539 } else {
1540 $patch_mode_revision = $arg;
1541 $patch_mode = ($arg eq 'HEAD' ?
1542 'checkout_head' : 'checkout_nothead');
1543 $arg = shift @ARGV or die "missing --";
1545 } elsif ($1 eq 'stage' or $1 eq 'stash') {
1546 $patch_mode = $1;
1547 $arg = shift @ARGV or die "missing --";
1548 } else {
1549 die "unknown --patch mode: $1";
1551 } else {
1552 $patch_mode = 'stage';
1553 $arg = shift @ARGV or die "missing --";
1555 die "invalid argument $arg, expecting --"
1556 unless $arg eq "--";
1557 %patch_mode_flavour = %{$patch_modes{$patch_mode}};
1559 elsif ($arg ne "--") {
1560 die "invalid argument $arg, expecting --";
1564 sub main_loop {
1565 my @cmd = ([ 'status', \&status_cmd, ],
1566 [ 'update', \&update_cmd, ],
1567 [ 'revert', \&revert_cmd, ],
1568 [ 'add untracked', \&add_untracked_cmd, ],
1569 [ 'patch', \&patch_update_cmd, ],
1570 [ 'diff', \&diff_cmd, ],
1571 [ 'quit', \&quit_cmd, ],
1572 [ 'help', \&help_cmd, ],
1574 while (1) {
1575 my ($it) = list_and_choose({ PROMPT => 'What now',
1576 SINGLETON => 1,
1577 LIST_FLAT => 4,
1578 HEADER => '*** Commands ***',
1579 ON_EOF => \&quit_cmd,
1580 IMMEDIATE => 1 }, @cmd);
1581 if ($it) {
1582 eval {
1583 $it->[1]->();
1585 if ($@) {
1586 print "$@";
1592 process_args();
1593 refresh();
1594 if ($patch_mode) {
1595 patch_update_cmd();
1597 else {
1598 status_cmd();
1599 main_loop();