archive: handle commits with an empty tree
[git/jnareb-git.git] / git-add--interactive.perl
blob710764abb132f16e393fd16178b845d8160e37cf
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?
271 # UNMERGED: is the path unmerged
273 sub list_modified {
274 my ($only) = @_;
275 my (%data, @return);
276 my ($add, $del, $adddel, $file);
277 my @tracked = ();
279 if (@ARGV) {
280 @tracked = map {
281 chomp $_;
282 unquote_path($_);
283 } run_cmd_pipe(qw(git ls-files --), @ARGV);
284 return if (!@tracked);
287 my $reference;
288 if (defined $patch_mode_revision and $patch_mode_revision ne 'HEAD') {
289 $reference = $patch_mode_revision;
290 } elsif (is_initial_commit()) {
291 $reference = get_empty_tree();
292 } else {
293 $reference = 'HEAD';
295 for (run_cmd_pipe(qw(git diff-index --cached
296 --numstat --summary), $reference,
297 '--', @tracked)) {
298 if (($add, $del, $file) =
299 /^([-\d]+) ([-\d]+) (.*)/) {
300 my ($change, $bin);
301 $file = unquote_path($file);
302 if ($add eq '-' && $del eq '-') {
303 $change = 'binary';
304 $bin = 1;
306 else {
307 $change = "+$add/-$del";
309 $data{$file} = {
310 INDEX => $change,
311 BINARY => $bin,
312 FILE => 'nothing',
315 elsif (($adddel, $file) =
316 /^ (create|delete) mode [0-7]+ (.*)$/) {
317 $file = unquote_path($file);
318 $data{$file}{INDEX_ADDDEL} = $adddel;
322 for (run_cmd_pipe(qw(git diff-files --numstat --summary --raw --), @tracked)) {
323 if (($add, $del, $file) =
324 /^([-\d]+) ([-\d]+) (.*)/) {
325 $file = unquote_path($file);
326 my ($change, $bin);
327 if ($add eq '-' && $del eq '-') {
328 $change = 'binary';
329 $bin = 1;
331 else {
332 $change = "+$add/-$del";
334 $data{$file}{FILE} = $change;
335 if ($bin) {
336 $data{$file}{BINARY} = 1;
339 elsif (($adddel, $file) =
340 /^ (create|delete) mode [0-7]+ (.*)$/) {
341 $file = unquote_path($file);
342 $data{$file}{FILE_ADDDEL} = $adddel;
344 elsif (/^:[0-7]+ [0-7]+ [0-9a-f]+ [0-9a-f]+ (.) (.*)$/) {
345 $file = unquote_path($2);
346 if (!exists $data{$file}) {
347 $data{$file} = +{
348 INDEX => 'unchanged',
349 BINARY => 0,
352 if ($1 eq 'U') {
353 $data{$file}{UNMERGED} = 1;
358 for (sort keys %data) {
359 my $it = $data{$_};
361 if ($only) {
362 if ($only eq 'index-only') {
363 next if ($it->{INDEX} eq 'unchanged');
365 if ($only eq 'file-only') {
366 next if ($it->{FILE} eq 'nothing');
369 push @return, +{
370 VALUE => $_,
371 %$it,
374 return @return;
377 sub find_unique {
378 my ($string, @stuff) = @_;
379 my $found = undef;
380 for (my $i = 0; $i < @stuff; $i++) {
381 my $it = $stuff[$i];
382 my $hit = undef;
383 if (ref $it) {
384 if ((ref $it) eq 'ARRAY') {
385 $it = $it->[0];
387 else {
388 $it = $it->{VALUE};
391 eval {
392 if ($it =~ /^$string/) {
393 $hit = 1;
396 if (defined $hit && defined $found) {
397 return undef;
399 if ($hit) {
400 $found = $i + 1;
403 return $found;
406 # inserts string into trie and updates count for each character
407 sub update_trie {
408 my ($trie, $string) = @_;
409 foreach (split //, $string) {
410 $trie = $trie->{$_} ||= {COUNT => 0};
411 $trie->{COUNT}++;
415 # returns an array of tuples (prefix, remainder)
416 sub find_unique_prefixes {
417 my @stuff = @_;
418 my @return = ();
420 # any single prefix exceeding the soft limit is omitted
421 # if any prefix exceeds the hard limit all are omitted
422 # 0 indicates no limit
423 my $soft_limit = 0;
424 my $hard_limit = 3;
426 # build a trie modelling all possible options
427 my %trie;
428 foreach my $print (@stuff) {
429 if ((ref $print) eq 'ARRAY') {
430 $print = $print->[0];
432 elsif ((ref $print) eq 'HASH') {
433 $print = $print->{VALUE};
435 update_trie(\%trie, $print);
436 push @return, $print;
439 # use the trie to find the unique prefixes
440 for (my $i = 0; $i < @return; $i++) {
441 my $ret = $return[$i];
442 my @letters = split //, $ret;
443 my %search = %trie;
444 my ($prefix, $remainder);
445 my $j;
446 for ($j = 0; $j < @letters; $j++) {
447 my $letter = $letters[$j];
448 if ($search{$letter}{COUNT} == 1) {
449 $prefix = substr $ret, 0, $j + 1;
450 $remainder = substr $ret, $j + 1;
451 last;
453 else {
454 my $prefix = substr $ret, 0, $j;
455 return ()
456 if ($hard_limit && $j + 1 > $hard_limit);
458 %search = %{$search{$letter}};
460 if (ord($letters[0]) > 127 ||
461 ($soft_limit && $j + 1 > $soft_limit)) {
462 $prefix = undef;
463 $remainder = $ret;
465 $return[$i] = [$prefix, $remainder];
467 return @return;
470 # filters out prefixes which have special meaning to list_and_choose()
471 sub is_valid_prefix {
472 my $prefix = shift;
473 return (defined $prefix) &&
474 !($prefix =~ /[\s,]/) && # separators
475 !($prefix =~ /^-/) && # deselection
476 !($prefix =~ /^\d+/) && # selection
477 ($prefix ne '*') && # "all" wildcard
478 ($prefix ne '?'); # prompt help
481 # given a prefix/remainder tuple return a string with the prefix highlighted
482 # for now use square brackets; later might use ANSI colors (underline, bold)
483 sub highlight_prefix {
484 my $prefix = shift;
485 my $remainder = shift;
487 if (!defined $prefix) {
488 return $remainder;
491 if (!is_valid_prefix($prefix)) {
492 return "$prefix$remainder";
495 if (!$menu_use_color) {
496 return "[$prefix]$remainder";
499 return "$prompt_color$prefix$normal_color$remainder";
502 sub error_msg {
503 print STDERR colored $error_color, @_;
506 sub list_and_choose {
507 my ($opts, @stuff) = @_;
508 my (@chosen, @return);
509 my $i;
510 my @prefixes = find_unique_prefixes(@stuff) unless $opts->{LIST_ONLY};
512 TOPLOOP:
513 while (1) {
514 my $last_lf = 0;
516 if ($opts->{HEADER}) {
517 if (!$opts->{LIST_FLAT}) {
518 print " ";
520 print colored $header_color, "$opts->{HEADER}\n";
522 for ($i = 0; $i < @stuff; $i++) {
523 my $chosen = $chosen[$i] ? '*' : ' ';
524 my $print = $stuff[$i];
525 my $ref = ref $print;
526 my $highlighted = highlight_prefix(@{$prefixes[$i]})
527 if @prefixes;
528 if ($ref eq 'ARRAY') {
529 $print = $highlighted || $print->[0];
531 elsif ($ref eq 'HASH') {
532 my $value = $highlighted || $print->{VALUE};
533 $print = sprintf($status_fmt,
534 $print->{INDEX},
535 $print->{FILE},
536 $value);
538 else {
539 $print = $highlighted || $print;
541 printf("%s%2d: %s", $chosen, $i+1, $print);
542 if (($opts->{LIST_FLAT}) &&
543 (($i + 1) % ($opts->{LIST_FLAT}))) {
544 print "\t";
545 $last_lf = 0;
547 else {
548 print "\n";
549 $last_lf = 1;
552 if (!$last_lf) {
553 print "\n";
556 return if ($opts->{LIST_ONLY});
558 print colored $prompt_color, $opts->{PROMPT};
559 if ($opts->{SINGLETON}) {
560 print "> ";
562 else {
563 print ">> ";
565 my $line = <STDIN>;
566 if (!$line) {
567 print "\n";
568 $opts->{ON_EOF}->() if $opts->{ON_EOF};
569 last;
571 chomp $line;
572 last if $line eq '';
573 if ($line eq '?') {
574 $opts->{SINGLETON} ?
575 singleton_prompt_help_cmd() :
576 prompt_help_cmd();
577 next TOPLOOP;
579 for my $choice (split(/[\s,]+/, $line)) {
580 my $choose = 1;
581 my ($bottom, $top);
583 # Input that begins with '-'; unchoose
584 if ($choice =~ s/^-//) {
585 $choose = 0;
587 # A range can be specified like 5-7 or 5-.
588 if ($choice =~ /^(\d+)-(\d*)$/) {
589 ($bottom, $top) = ($1, length($2) ? $2 : 1 + @stuff);
591 elsif ($choice =~ /^\d+$/) {
592 $bottom = $top = $choice;
594 elsif ($choice eq '*') {
595 $bottom = 1;
596 $top = 1 + @stuff;
598 else {
599 $bottom = $top = find_unique($choice, @stuff);
600 if (!defined $bottom) {
601 error_msg "Huh ($choice)?\n";
602 next TOPLOOP;
605 if ($opts->{SINGLETON} && $bottom != $top) {
606 error_msg "Huh ($choice)?\n";
607 next TOPLOOP;
609 for ($i = $bottom-1; $i <= $top-1; $i++) {
610 next if (@stuff <= $i || $i < 0);
611 $chosen[$i] = $choose;
614 last if ($opts->{IMMEDIATE} || $line eq '*');
616 for ($i = 0; $i < @stuff; $i++) {
617 if ($chosen[$i]) {
618 push @return, $stuff[$i];
621 return @return;
624 sub singleton_prompt_help_cmd {
625 print colored $help_color, <<\EOF ;
626 Prompt help:
627 1 - select a numbered item
628 foo - select item based on unique prefix
629 - (empty) select nothing
633 sub prompt_help_cmd {
634 print colored $help_color, <<\EOF ;
635 Prompt help:
636 1 - select a single item
637 3-5 - select a range of items
638 2-3,6-9 - select multiple ranges
639 foo - select item based on unique prefix
640 -... - unselect specified items
641 * - choose all items
642 - (empty) finish selecting
646 sub status_cmd {
647 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
648 list_modified());
649 print "\n";
652 sub say_n_paths {
653 my $did = shift @_;
654 my $cnt = scalar @_;
655 print "$did ";
656 if (1 < $cnt) {
657 print "$cnt paths\n";
659 else {
660 print "one path\n";
664 sub update_cmd {
665 my @mods = list_modified('file-only');
666 return if (!@mods);
668 my @update = list_and_choose({ PROMPT => 'Update',
669 HEADER => $status_head, },
670 @mods);
671 if (@update) {
672 system(qw(git update-index --add --remove --),
673 map { $_->{VALUE} } @update);
674 say_n_paths('updated', @update);
676 print "\n";
679 sub revert_cmd {
680 my @update = list_and_choose({ PROMPT => 'Revert',
681 HEADER => $status_head, },
682 list_modified());
683 if (@update) {
684 if (is_initial_commit()) {
685 system(qw(git rm --cached),
686 map { $_->{VALUE} } @update);
688 else {
689 my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
690 map { $_->{VALUE} } @update);
691 my $fh;
692 open $fh, '| git update-index --index-info'
693 or die;
694 for (@lines) {
695 print $fh $_;
697 close($fh);
698 for (@update) {
699 if ($_->{INDEX_ADDDEL} &&
700 $_->{INDEX_ADDDEL} eq 'create') {
701 system(qw(git update-index --force-remove --),
702 $_->{VALUE});
703 print "note: $_->{VALUE} is untracked now.\n";
707 refresh();
708 say_n_paths('reverted', @update);
710 print "\n";
713 sub add_untracked_cmd {
714 my @add = list_and_choose({ PROMPT => 'Add untracked' },
715 list_untracked());
716 if (@add) {
717 system(qw(git update-index --add --), @add);
718 say_n_paths('added', @add);
720 print "\n";
723 sub run_git_apply {
724 my $cmd = shift;
725 my $fh;
726 open $fh, '| git ' . $cmd . " --recount --allow-overlap";
727 print $fh @_;
728 return close $fh;
731 sub parse_diff {
732 my ($path) = @_;
733 my @diff_cmd = split(" ", $patch_mode_flavour{DIFF});
734 if (defined $patch_mode_revision) {
735 push @diff_cmd, $patch_mode_revision;
737 my @diff = run_cmd_pipe("git", @diff_cmd, "--", $path);
738 my @colored = ();
739 if ($diff_use_color) {
740 @colored = run_cmd_pipe("git", @diff_cmd, qw(--color --), $path);
742 my (@hunk) = { TEXT => [], DISPLAY => [], TYPE => 'header' };
744 for (my $i = 0; $i < @diff; $i++) {
745 if ($diff[$i] =~ /^@@ /) {
746 push @hunk, { TEXT => [], DISPLAY => [],
747 TYPE => 'hunk' };
749 push @{$hunk[-1]{TEXT}}, $diff[$i];
750 push @{$hunk[-1]{DISPLAY}},
751 ($diff_use_color ? $colored[$i] : $diff[$i]);
753 return @hunk;
756 sub parse_diff_header {
757 my $src = shift;
759 my $head = { TEXT => [], DISPLAY => [], TYPE => 'header' };
760 my $mode = { TEXT => [], DISPLAY => [], TYPE => 'mode' };
761 my $deletion = { TEXT => [], DISPLAY => [], TYPE => 'deletion' };
763 for (my $i = 0; $i < @{$src->{TEXT}}; $i++) {
764 my $dest =
765 $src->{TEXT}->[$i] =~ /^(old|new) mode (\d+)$/ ? $mode :
766 $src->{TEXT}->[$i] =~ /^deleted file/ ? $deletion :
767 $head;
768 push @{$dest->{TEXT}}, $src->{TEXT}->[$i];
769 push @{$dest->{DISPLAY}}, $src->{DISPLAY}->[$i];
771 return ($head, $mode, $deletion);
774 sub hunk_splittable {
775 my ($text) = @_;
777 my @s = split_hunk($text);
778 return (1 < @s);
781 sub parse_hunk_header {
782 my ($line) = @_;
783 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
784 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
785 $o_cnt = 1 unless defined $o_cnt;
786 $n_cnt = 1 unless defined $n_cnt;
787 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
790 sub split_hunk {
791 my ($text, $display) = @_;
792 my @split = ();
793 if (!defined $display) {
794 $display = $text;
796 # If there are context lines in the middle of a hunk,
797 # it can be split, but we would need to take care of
798 # overlaps later.
800 my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
801 my $hunk_start = 1;
803 OUTER:
804 while (1) {
805 my $next_hunk_start = undef;
806 my $i = $hunk_start - 1;
807 my $this = +{
808 TEXT => [],
809 DISPLAY => [],
810 TYPE => 'hunk',
811 OLD => $o_ofs,
812 NEW => $n_ofs,
813 OCNT => 0,
814 NCNT => 0,
815 ADDDEL => 0,
816 POSTCTX => 0,
817 USE => undef,
820 while (++$i < @$text) {
821 my $line = $text->[$i];
822 my $display = $display->[$i];
823 if ($line =~ /^ /) {
824 if ($this->{ADDDEL} &&
825 !defined $next_hunk_start) {
826 # We have seen leading context and
827 # adds/dels and then here is another
828 # context, which is trailing for this
829 # split hunk and leading for the next
830 # one.
831 $next_hunk_start = $i;
833 push @{$this->{TEXT}}, $line;
834 push @{$this->{DISPLAY}}, $display;
835 $this->{OCNT}++;
836 $this->{NCNT}++;
837 if (defined $next_hunk_start) {
838 $this->{POSTCTX}++;
840 next;
843 # add/del
844 if (defined $next_hunk_start) {
845 # We are done with the current hunk and
846 # this is the first real change for the
847 # next split one.
848 $hunk_start = $next_hunk_start;
849 $o_ofs = $this->{OLD} + $this->{OCNT};
850 $n_ofs = $this->{NEW} + $this->{NCNT};
851 $o_ofs -= $this->{POSTCTX};
852 $n_ofs -= $this->{POSTCTX};
853 push @split, $this;
854 redo OUTER;
856 push @{$this->{TEXT}}, $line;
857 push @{$this->{DISPLAY}}, $display;
858 $this->{ADDDEL}++;
859 if ($line =~ /^-/) {
860 $this->{OCNT}++;
862 else {
863 $this->{NCNT}++;
867 push @split, $this;
868 last;
871 for my $hunk (@split) {
872 $o_ofs = $hunk->{OLD};
873 $n_ofs = $hunk->{NEW};
874 my $o_cnt = $hunk->{OCNT};
875 my $n_cnt = $hunk->{NCNT};
877 my $head = ("@@ -$o_ofs" .
878 (($o_cnt != 1) ? ",$o_cnt" : '') .
879 " +$n_ofs" .
880 (($n_cnt != 1) ? ",$n_cnt" : '') .
881 " @@\n");
882 my $display_head = $head;
883 unshift @{$hunk->{TEXT}}, $head;
884 if ($diff_use_color) {
885 $display_head = colored($fraginfo_color, $head);
887 unshift @{$hunk->{DISPLAY}}, $display_head;
889 return @split;
892 sub find_last_o_ctx {
893 my ($it) = @_;
894 my $text = $it->{TEXT};
895 my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
896 my $i = @{$text};
897 my $last_o_ctx = $o_ofs + $o_cnt;
898 while (0 < --$i) {
899 my $line = $text->[$i];
900 if ($line =~ /^ /) {
901 $last_o_ctx--;
902 next;
904 last;
906 return $last_o_ctx;
909 sub merge_hunk {
910 my ($prev, $this) = @_;
911 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
912 parse_hunk_header($prev->{TEXT}[0]);
913 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
914 parse_hunk_header($this->{TEXT}[0]);
916 my (@line, $i, $ofs, $o_cnt, $n_cnt);
917 $ofs = $o0_ofs;
918 $o_cnt = $n_cnt = 0;
919 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
920 my $line = $prev->{TEXT}[$i];
921 if ($line =~ /^\+/) {
922 $n_cnt++;
923 push @line, $line;
924 next;
927 last if ($o1_ofs <= $ofs);
929 $o_cnt++;
930 $ofs++;
931 if ($line =~ /^ /) {
932 $n_cnt++;
934 push @line, $line;
937 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
938 my $line = $this->{TEXT}[$i];
939 if ($line =~ /^\+/) {
940 $n_cnt++;
941 push @line, $line;
942 next;
944 $ofs++;
945 $o_cnt++;
946 if ($line =~ /^ /) {
947 $n_cnt++;
949 push @line, $line;
951 my $head = ("@@ -$o0_ofs" .
952 (($o_cnt != 1) ? ",$o_cnt" : '') .
953 " +$n0_ofs" .
954 (($n_cnt != 1) ? ",$n_cnt" : '') .
955 " @@\n");
956 @{$prev->{TEXT}} = ($head, @line);
959 sub coalesce_overlapping_hunks {
960 my (@in) = @_;
961 my @out = ();
963 my ($last_o_ctx, $last_was_dirty);
965 for (grep { $_->{USE} } @in) {
966 if ($_->{TYPE} ne 'hunk') {
967 push @out, $_;
968 next;
970 my $text = $_->{TEXT};
971 my ($o_ofs) = parse_hunk_header($text->[0]);
972 if (defined $last_o_ctx &&
973 $o_ofs <= $last_o_ctx &&
974 !$_->{DIRTY} &&
975 !$last_was_dirty) {
976 merge_hunk($out[-1], $_);
978 else {
979 push @out, $_;
981 $last_o_ctx = find_last_o_ctx($out[-1]);
982 $last_was_dirty = $_->{DIRTY};
984 return @out;
987 sub reassemble_patch {
988 my $head = shift;
989 my @patch;
991 # Include everything in the header except the beginning of the diff.
992 push @patch, (grep { !/^[-+]{3}/ } @$head);
994 # Then include any headers from the hunk lines, which must
995 # come before any actual hunk.
996 while (@_ && $_[0] !~ /^@/) {
997 push @patch, shift;
1000 # Then begin the diff.
1001 push @patch, grep { /^[-+]{3}/ } @$head;
1003 # And then the actual hunks.
1004 push @patch, @_;
1006 return @patch;
1009 sub color_diff {
1010 return map {
1011 colored((/^@/ ? $fraginfo_color :
1012 /^\+/ ? $diff_new_color :
1013 /^-/ ? $diff_old_color :
1014 $diff_plain_color),
1015 $_);
1016 } @_;
1019 sub edit_hunk_manually {
1020 my ($oldtext) = @_;
1022 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
1023 my $fh;
1024 open $fh, '>', $hunkfile
1025 or die "failed to open hunk edit file for writing: " . $!;
1026 print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
1027 print $fh @$oldtext;
1028 my $participle = $patch_mode_flavour{PARTICIPLE};
1029 my $is_reverse = $patch_mode_flavour{IS_REVERSE};
1030 my ($remove_plus, $remove_minus) = $is_reverse ? ('-', '+') : ('+', '-');
1031 print $fh <<EOF;
1032 # ---
1033 # To remove '$remove_minus' lines, make them ' ' lines (context).
1034 # To remove '$remove_plus' lines, delete them.
1035 # Lines starting with # will be removed.
1037 # If the patch applies cleanly, the edited hunk will immediately be
1038 # marked for $participle. If it does not apply cleanly, you will be given
1039 # an opportunity to edit again. If all lines of the hunk are removed,
1040 # then the edit is aborted and the hunk is left unchanged.
1042 close $fh;
1044 chomp(my $editor = run_cmd_pipe(qw(git var GIT_EDITOR)));
1045 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
1047 if ($? != 0) {
1048 return undef;
1051 open $fh, '<', $hunkfile
1052 or die "failed to open hunk edit file for reading: " . $!;
1053 my @newtext = grep { !/^#/ } <$fh>;
1054 close $fh;
1055 unlink $hunkfile;
1057 # Abort if nothing remains
1058 if (!grep { /\S/ } @newtext) {
1059 return undef;
1062 # Reinsert the first hunk header if the user accidentally deleted it
1063 if ($newtext[0] !~ /^@/) {
1064 unshift @newtext, $oldtext->[0];
1066 return \@newtext;
1069 sub diff_applies {
1070 return run_git_apply($patch_mode_flavour{APPLY_CHECK} . ' --check',
1071 map { @{$_->{TEXT}} } @_);
1074 sub _restore_terminal_and_die {
1075 ReadMode 'restore';
1076 print "\n";
1077 exit 1;
1080 sub prompt_single_character {
1081 if ($use_readkey) {
1082 local $SIG{TERM} = \&_restore_terminal_and_die;
1083 local $SIG{INT} = \&_restore_terminal_and_die;
1084 ReadMode 'cbreak';
1085 my $key = ReadKey 0;
1086 ReadMode 'restore';
1087 if ($use_termcap and $key eq "\e") {
1088 while (!defined $term_escapes{$key}) {
1089 my $next = ReadKey 0.5;
1090 last if (!defined $next);
1091 $key .= $next;
1093 $key =~ s/\e/^[/;
1095 print "$key" if defined $key;
1096 print "\n";
1097 return $key;
1098 } else {
1099 return <STDIN>;
1103 sub prompt_yesno {
1104 my ($prompt) = @_;
1105 while (1) {
1106 print colored $prompt_color, $prompt;
1107 my $line = prompt_single_character;
1108 return 0 if $line =~ /^n/i;
1109 return 1 if $line =~ /^y/i;
1113 sub edit_hunk_loop {
1114 my ($head, $hunk, $ix) = @_;
1115 my $text = $hunk->[$ix]->{TEXT};
1117 while (1) {
1118 $text = edit_hunk_manually($text);
1119 if (!defined $text) {
1120 return undef;
1122 my $newhunk = {
1123 TEXT => $text,
1124 TYPE => $hunk->[$ix]->{TYPE},
1125 USE => 1,
1126 DIRTY => 1,
1128 if (diff_applies($head,
1129 @{$hunk}[0..$ix-1],
1130 $newhunk,
1131 @{$hunk}[$ix+1..$#{$hunk}])) {
1132 $newhunk->{DISPLAY} = [color_diff(@{$text})];
1133 return $newhunk;
1135 else {
1136 prompt_yesno(
1137 'Your edited hunk does not apply. Edit again '
1138 . '(saying "no" discards!) [y/n]? '
1139 ) or return undef;
1144 sub help_patch_cmd {
1145 my $verb = lc $patch_mode_flavour{VERB};
1146 my $target = $patch_mode_flavour{TARGET};
1147 print colored $help_color, <<EOF ;
1148 y - $verb this hunk$target
1149 n - do not $verb this hunk$target
1150 q - quit; do not $verb this hunk nor any of the remaining ones
1151 a - $verb this hunk and all later hunks in the file
1152 d - do not $verb this hunk nor any of the later hunks in the file
1153 g - select a hunk to go to
1154 / - search for a hunk matching the given regex
1155 j - leave this hunk undecided, see next undecided hunk
1156 J - leave this hunk undecided, see next hunk
1157 k - leave this hunk undecided, see previous undecided hunk
1158 K - leave this hunk undecided, see previous hunk
1159 s - split the current hunk into smaller hunks
1160 e - manually edit the current hunk
1161 ? - print help
1165 sub apply_patch {
1166 my $cmd = shift;
1167 my $ret = run_git_apply $cmd, @_;
1168 if (!$ret) {
1169 print STDERR @_;
1171 return $ret;
1174 sub apply_patch_for_checkout_commit {
1175 my $reverse = shift;
1176 my $applies_index = run_git_apply 'apply '.$reverse.' --cached --check', @_;
1177 my $applies_worktree = run_git_apply 'apply '.$reverse.' --check', @_;
1179 if ($applies_worktree && $applies_index) {
1180 run_git_apply 'apply '.$reverse.' --cached', @_;
1181 run_git_apply 'apply '.$reverse, @_;
1182 return 1;
1183 } elsif (!$applies_index) {
1184 print colored $error_color, "The selected hunks do not apply to the index!\n";
1185 if (prompt_yesno "Apply them to the worktree anyway? ") {
1186 return run_git_apply 'apply '.$reverse, @_;
1187 } else {
1188 print colored $error_color, "Nothing was applied.\n";
1189 return 0;
1191 } else {
1192 print STDERR @_;
1193 return 0;
1197 sub patch_update_cmd {
1198 my @all_mods = list_modified($patch_mode_flavour{FILTER});
1199 error_msg "ignoring unmerged: $_->{VALUE}\n"
1200 for grep { $_->{UNMERGED} } @all_mods;
1201 @all_mods = grep { !$_->{UNMERGED} } @all_mods;
1203 my @mods = grep { !($_->{BINARY}) } @all_mods;
1204 my @them;
1206 if (!@mods) {
1207 if (@all_mods) {
1208 print STDERR "Only binary files changed.\n";
1209 } else {
1210 print STDERR "No changes.\n";
1212 return 0;
1214 if ($patch_mode) {
1215 @them = @mods;
1217 else {
1218 @them = list_and_choose({ PROMPT => 'Patch update',
1219 HEADER => $status_head, },
1220 @mods);
1222 for (@them) {
1223 return 0 if patch_update_file($_->{VALUE});
1227 # Generate a one line summary of a hunk.
1228 sub summarize_hunk {
1229 my $rhunk = shift;
1230 my $summary = $rhunk->{TEXT}[0];
1232 # Keep the line numbers, discard extra context.
1233 $summary =~ s/@@(.*?)@@.*/$1 /s;
1234 $summary .= " " x (20 - length $summary);
1236 # Add some user context.
1237 for my $line (@{$rhunk->{TEXT}}) {
1238 if ($line =~ m/^[+-].*\w/) {
1239 $summary .= $line;
1240 last;
1244 chomp $summary;
1245 return substr($summary, 0, 80) . "\n";
1249 # Print a one-line summary of each hunk in the array ref in
1250 # the first argument, starting wih the index in the 2nd.
1251 sub display_hunks {
1252 my ($hunks, $i) = @_;
1253 my $ctr = 0;
1254 $i ||= 0;
1255 for (; $i < @$hunks && $ctr < 20; $i++, $ctr++) {
1256 my $status = " ";
1257 if (defined $hunks->[$i]{USE}) {
1258 $status = $hunks->[$i]{USE} ? "+" : "-";
1260 printf "%s%2d: %s",
1261 $status,
1262 $i + 1,
1263 summarize_hunk($hunks->[$i]);
1265 return $i;
1268 sub patch_update_file {
1269 my $quit = 0;
1270 my ($ix, $num);
1271 my $path = shift;
1272 my ($head, @hunk) = parse_diff($path);
1273 ($head, my $mode, my $deletion) = parse_diff_header($head);
1274 for (@{$head->{DISPLAY}}) {
1275 print;
1278 if (@{$mode->{TEXT}}) {
1279 unshift @hunk, $mode;
1281 if (@{$deletion->{TEXT}}) {
1282 foreach my $hunk (@hunk) {
1283 push @{$deletion->{TEXT}}, @{$hunk->{TEXT}};
1284 push @{$deletion->{DISPLAY}}, @{$hunk->{DISPLAY}};
1286 @hunk = ($deletion);
1289 $num = scalar @hunk;
1290 $ix = 0;
1292 while (1) {
1293 my ($prev, $next, $other, $undecided, $i);
1294 $other = '';
1296 if ($num <= $ix) {
1297 $ix = 0;
1299 for ($i = 0; $i < $ix; $i++) {
1300 if (!defined $hunk[$i]{USE}) {
1301 $prev = 1;
1302 $other .= ',k';
1303 last;
1306 if ($ix) {
1307 $other .= ',K';
1309 for ($i = $ix + 1; $i < $num; $i++) {
1310 if (!defined $hunk[$i]{USE}) {
1311 $next = 1;
1312 $other .= ',j';
1313 last;
1316 if ($ix < $num - 1) {
1317 $other .= ',J';
1319 if ($num > 1) {
1320 $other .= ',g';
1322 for ($i = 0; $i < $num; $i++) {
1323 if (!defined $hunk[$i]{USE}) {
1324 $undecided = 1;
1325 last;
1328 last if (!$undecided);
1330 if ($hunk[$ix]{TYPE} eq 'hunk' &&
1331 hunk_splittable($hunk[$ix]{TEXT})) {
1332 $other .= ',s';
1334 if ($hunk[$ix]{TYPE} eq 'hunk') {
1335 $other .= ',e';
1337 for (@{$hunk[$ix]{DISPLAY}}) {
1338 print;
1340 print colored $prompt_color, $patch_mode_flavour{VERB},
1341 ($hunk[$ix]{TYPE} eq 'mode' ? ' mode change' :
1342 $hunk[$ix]{TYPE} eq 'deletion' ? ' deletion' :
1343 ' this hunk'),
1344 $patch_mode_flavour{TARGET},
1345 " [y,n,q,a,d,/$other,?]? ";
1346 my $line = prompt_single_character;
1347 if ($line) {
1348 if ($line =~ /^y/i) {
1349 $hunk[$ix]{USE} = 1;
1351 elsif ($line =~ /^n/i) {
1352 $hunk[$ix]{USE} = 0;
1354 elsif ($line =~ /^a/i) {
1355 while ($ix < $num) {
1356 if (!defined $hunk[$ix]{USE}) {
1357 $hunk[$ix]{USE} = 1;
1359 $ix++;
1361 next;
1363 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1364 my $response = $1;
1365 my $no = $ix > 10 ? $ix - 10 : 0;
1366 while ($response eq '') {
1367 my $extra = "";
1368 $no = display_hunks(\@hunk, $no);
1369 if ($no < $num) {
1370 $extra = " (<ret> to see more)";
1372 print "go to which hunk$extra? ";
1373 $response = <STDIN>;
1374 if (!defined $response) {
1375 $response = '';
1377 chomp $response;
1379 if ($response !~ /^\s*\d+\s*$/) {
1380 error_msg "Invalid number: '$response'\n";
1381 } elsif (0 < $response && $response <= $num) {
1382 $ix = $response - 1;
1383 } else {
1384 error_msg "Sorry, only $num hunks available.\n";
1386 next;
1388 elsif ($line =~ /^d/i) {
1389 while ($ix < $num) {
1390 if (!defined $hunk[$ix]{USE}) {
1391 $hunk[$ix]{USE} = 0;
1393 $ix++;
1395 next;
1397 elsif ($line =~ /^q/i) {
1398 for ($i = 0; $i < $num; $i++) {
1399 if (!defined $hunk[$i]{USE}) {
1400 $hunk[$i]{USE} = 0;
1403 $quit = 1;
1404 last;
1406 elsif ($line =~ m|^/(.*)|) {
1407 my $regex = $1;
1408 if ($1 eq "") {
1409 print colored $prompt_color, "search for regex? ";
1410 $regex = <STDIN>;
1411 if (defined $regex) {
1412 chomp $regex;
1415 my $search_string;
1416 eval {
1417 $search_string = qr{$regex}m;
1419 if ($@) {
1420 my ($err,$exp) = ($@, $1);
1421 $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1422 error_msg "Malformed search regexp $exp: $err\n";
1423 next;
1425 my $iy = $ix;
1426 while (1) {
1427 my $text = join ("", @{$hunk[$iy]{TEXT}});
1428 last if ($text =~ $search_string);
1429 $iy++;
1430 $iy = 0 if ($iy >= $num);
1431 if ($ix == $iy) {
1432 error_msg "No hunk matches the given pattern\n";
1433 last;
1436 $ix = $iy;
1437 next;
1439 elsif ($line =~ /^K/) {
1440 if ($other =~ /K/) {
1441 $ix--;
1443 else {
1444 error_msg "No previous hunk\n";
1446 next;
1448 elsif ($line =~ /^J/) {
1449 if ($other =~ /J/) {
1450 $ix++;
1452 else {
1453 error_msg "No next hunk\n";
1455 next;
1457 elsif ($line =~ /^k/) {
1458 if ($other =~ /k/) {
1459 while (1) {
1460 $ix--;
1461 last if (!$ix ||
1462 !defined $hunk[$ix]{USE});
1465 else {
1466 error_msg "No previous hunk\n";
1468 next;
1470 elsif ($line =~ /^j/) {
1471 if ($other !~ /j/) {
1472 error_msg "No next hunk\n";
1473 next;
1476 elsif ($other =~ /s/ && $line =~ /^s/) {
1477 my @split = split_hunk($hunk[$ix]{TEXT}, $hunk[$ix]{DISPLAY});
1478 if (1 < @split) {
1479 print colored $header_color, "Split into ",
1480 scalar(@split), " hunks.\n";
1482 splice (@hunk, $ix, 1, @split);
1483 $num = scalar @hunk;
1484 next;
1486 elsif ($other =~ /e/ && $line =~ /^e/) {
1487 my $newhunk = edit_hunk_loop($head, \@hunk, $ix);
1488 if (defined $newhunk) {
1489 splice @hunk, $ix, 1, $newhunk;
1492 else {
1493 help_patch_cmd($other);
1494 next;
1496 # soft increment
1497 while (1) {
1498 $ix++;
1499 last if ($ix >= $num ||
1500 !defined $hunk[$ix]{USE});
1505 @hunk = coalesce_overlapping_hunks(@hunk);
1507 my $n_lofs = 0;
1508 my @result = ();
1509 for (@hunk) {
1510 if ($_->{USE}) {
1511 push @result, @{$_->{TEXT}};
1515 if (@result) {
1516 my @patch = reassemble_patch($head->{TEXT}, @result);
1517 my $apply_routine = $patch_mode_flavour{APPLY};
1518 &$apply_routine(@patch);
1519 refresh();
1522 print "\n";
1523 return $quit;
1526 sub diff_cmd {
1527 my @mods = list_modified('index-only');
1528 @mods = grep { !($_->{BINARY}) } @mods;
1529 return if (!@mods);
1530 my (@them) = list_and_choose({ PROMPT => 'Review diff',
1531 IMMEDIATE => 1,
1532 HEADER => $status_head, },
1533 @mods);
1534 return if (!@them);
1535 my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
1536 system(qw(git diff -p --cached), $reference, '--',
1537 map { $_->{VALUE} } @them);
1540 sub quit_cmd {
1541 print "Bye.\n";
1542 exit(0);
1545 sub help_cmd {
1546 print colored $help_color, <<\EOF ;
1547 status - show paths with changes
1548 update - add working tree state to the staged set of changes
1549 revert - revert staged set of changes back to the HEAD version
1550 patch - pick hunks and update selectively
1551 diff - view diff between HEAD and index
1552 add untracked - add contents of untracked files to the staged set of changes
1556 sub process_args {
1557 return unless @ARGV;
1558 my $arg = shift @ARGV;
1559 if ($arg =~ /--patch(?:=(.*))?/) {
1560 if (defined $1) {
1561 if ($1 eq 'reset') {
1562 $patch_mode = 'reset_head';
1563 $patch_mode_revision = 'HEAD';
1564 $arg = shift @ARGV or die "missing --";
1565 if ($arg ne '--') {
1566 $patch_mode_revision = $arg;
1567 $patch_mode = ($arg eq 'HEAD' ?
1568 'reset_head' : 'reset_nothead');
1569 $arg = shift @ARGV or die "missing --";
1571 } elsif ($1 eq 'checkout') {
1572 $arg = shift @ARGV or die "missing --";
1573 if ($arg eq '--') {
1574 $patch_mode = 'checkout_index';
1575 } else {
1576 $patch_mode_revision = $arg;
1577 $patch_mode = ($arg eq 'HEAD' ?
1578 'checkout_head' : 'checkout_nothead');
1579 $arg = shift @ARGV or die "missing --";
1581 } elsif ($1 eq 'stage' or $1 eq 'stash') {
1582 $patch_mode = $1;
1583 $arg = shift @ARGV or die "missing --";
1584 } else {
1585 die "unknown --patch mode: $1";
1587 } else {
1588 $patch_mode = 'stage';
1589 $arg = shift @ARGV or die "missing --";
1591 die "invalid argument $arg, expecting --"
1592 unless $arg eq "--";
1593 %patch_mode_flavour = %{$patch_modes{$patch_mode}};
1595 elsif ($arg ne "--") {
1596 die "invalid argument $arg, expecting --";
1600 sub main_loop {
1601 my @cmd = ([ 'status', \&status_cmd, ],
1602 [ 'update', \&update_cmd, ],
1603 [ 'revert', \&revert_cmd, ],
1604 [ 'add untracked', \&add_untracked_cmd, ],
1605 [ 'patch', \&patch_update_cmd, ],
1606 [ 'diff', \&diff_cmd, ],
1607 [ 'quit', \&quit_cmd, ],
1608 [ 'help', \&help_cmd, ],
1610 while (1) {
1611 my ($it) = list_and_choose({ PROMPT => 'What now',
1612 SINGLETON => 1,
1613 LIST_FLAT => 4,
1614 HEADER => '*** Commands ***',
1615 ON_EOF => \&quit_cmd,
1616 IMMEDIATE => 1 }, @cmd);
1617 if ($it) {
1618 eval {
1619 $it->[1]->();
1621 if ($@) {
1622 print "$@";
1628 process_args();
1629 refresh();
1630 if ($patch_mode) {
1631 patch_update_cmd();
1633 else {
1634 status_cmd();
1635 main_loop();