Fix warnings in nedmalloc when compiling with GCC 4.4.0
[git/spearce.git] / git-add--interactive.perl
bloba06172c69f59391a04b75a3866a3fbcb98a21ba0
1 #!/usr/bin/perl -w
3 use strict;
4 use Git;
6 binmode(STDOUT, ":raw");
8 my $repo = Git->repository();
10 my $menu_use_color = $repo->get_colorbool('color.interactive');
11 my ($prompt_color, $header_color, $help_color) =
12 $menu_use_color ? (
13 $repo->get_color('color.interactive.prompt', 'bold blue'),
14 $repo->get_color('color.interactive.header', 'bold'),
15 $repo->get_color('color.interactive.help', 'red bold'),
16 ) : ();
17 my $error_color = ();
18 if ($menu_use_color) {
19 my $help_color_spec = ($repo->config('color.interactive.help') or
20 'red bold');
21 $error_color = $repo->get_color('color.interactive.error',
22 $help_color_spec);
25 my $diff_use_color = $repo->get_colorbool('color.diff');
26 my ($fraginfo_color) =
27 $diff_use_color ? (
28 $repo->get_color('color.diff.frag', 'cyan'),
29 ) : ();
30 my ($diff_plain_color) =
31 $diff_use_color ? (
32 $repo->get_color('color.diff.plain', ''),
33 ) : ();
34 my ($diff_old_color) =
35 $diff_use_color ? (
36 $repo->get_color('color.diff.old', 'red'),
37 ) : ();
38 my ($diff_new_color) =
39 $diff_use_color ? (
40 $repo->get_color('color.diff.new', 'green'),
41 ) : ();
43 my $normal_color = $repo->get_color("", "reset");
45 my $use_readkey = 0;
46 sub ReadMode;
47 sub ReadKey;
48 if ($repo->config_bool("interactive.singlekey")) {
49 eval {
50 require Term::ReadKey;
51 Term::ReadKey->import;
52 $use_readkey = 1;
56 sub colored {
57 my $color = shift;
58 my $string = join("", @_);
60 if (defined $color) {
61 # Put a color code at the beginning of each line, a reset at the end
62 # color after newlines that are not at the end of the string
63 $string =~ s/(\n+)(.)/$1$color$2/g;
64 # reset before newlines
65 $string =~ s/(\n+)/$normal_color$1/g;
66 # codes at beginning and end (if necessary):
67 $string =~ s/^/$color/;
68 $string =~ s/$/$normal_color/ unless $string =~ /\n$/;
70 return $string;
73 # command line options
74 my $patch_mode;
76 sub run_cmd_pipe {
77 if ($^O eq 'MSWin32' || $^O eq 'msys') {
78 my @invalid = grep {m/[":*]/} @_;
79 die "$^O does not support: @invalid\n" if @invalid;
80 my @args = map { m/ /o ? "\"$_\"": $_ } @_;
81 return qx{@args};
82 } else {
83 my $fh = undef;
84 open($fh, '-|', @_) or die;
85 return <$fh>;
89 my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));
91 if (!defined $GIT_DIR) {
92 exit(1); # rev-parse would have already said "not a git repo"
94 chomp($GIT_DIR);
96 my %cquote_map = (
97 "b" => chr(8),
98 "t" => chr(9),
99 "n" => chr(10),
100 "v" => chr(11),
101 "f" => chr(12),
102 "r" => chr(13),
103 "\\" => "\\",
104 "\042" => "\042",
107 sub unquote_path {
108 local ($_) = @_;
109 my ($retval, $remainder);
110 if (!/^\042(.*)\042$/) {
111 return $_;
113 ($_, $retval) = ($1, "");
114 while (/^([^\\]*)\\(.*)$/) {
115 $remainder = $2;
116 $retval .= $1;
117 for ($remainder) {
118 if (/^([0-3][0-7][0-7])(.*)$/) {
119 $retval .= chr(oct($1));
120 $_ = $2;
121 last;
123 if (/^([\\\042btnvfr])(.*)$/) {
124 $retval .= $cquote_map{$1};
125 $_ = $2;
126 last;
128 # This is malformed -- just return it as-is for now.
129 return $_[0];
131 $_ = $remainder;
133 $retval .= $_;
134 return $retval;
137 sub refresh {
138 my $fh;
139 open $fh, 'git update-index --refresh |'
140 or die;
141 while (<$fh>) {
142 ;# ignore 'needs update'
144 close $fh;
147 sub list_untracked {
148 map {
149 chomp $_;
150 unquote_path($_);
152 run_cmd_pipe(qw(git ls-files --others --exclude-standard --), @ARGV);
155 my $status_fmt = '%12s %12s %s';
156 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
159 my $initial;
160 sub is_initial_commit {
161 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
162 unless defined $initial;
163 return $initial;
167 sub get_empty_tree {
168 return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
171 # Returns list of hashes, contents of each of which are:
172 # VALUE: pathname
173 # BINARY: is a binary path
174 # INDEX: is index different from HEAD?
175 # FILE: is file different from index?
176 # INDEX_ADDDEL: is it add/delete between HEAD and index?
177 # FILE_ADDDEL: is it add/delete between index and file?
179 sub list_modified {
180 my ($only) = @_;
181 my (%data, @return);
182 my ($add, $del, $adddel, $file);
183 my @tracked = ();
185 if (@ARGV) {
186 @tracked = map {
187 chomp $_;
188 unquote_path($_);
189 } run_cmd_pipe(qw(git ls-files --exclude-standard --), @ARGV);
190 return if (!@tracked);
193 my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
194 for (run_cmd_pipe(qw(git diff-index --cached
195 --numstat --summary), $reference,
196 '--', @tracked)) {
197 if (($add, $del, $file) =
198 /^([-\d]+) ([-\d]+) (.*)/) {
199 my ($change, $bin);
200 $file = unquote_path($file);
201 if ($add eq '-' && $del eq '-') {
202 $change = 'binary';
203 $bin = 1;
205 else {
206 $change = "+$add/-$del";
208 $data{$file} = {
209 INDEX => $change,
210 BINARY => $bin,
211 FILE => 'nothing',
214 elsif (($adddel, $file) =
215 /^ (create|delete) mode [0-7]+ (.*)$/) {
216 $file = unquote_path($file);
217 $data{$file}{INDEX_ADDDEL} = $adddel;
221 for (run_cmd_pipe(qw(git diff-files --numstat --summary --), @tracked)) {
222 if (($add, $del, $file) =
223 /^([-\d]+) ([-\d]+) (.*)/) {
224 $file = unquote_path($file);
225 if (!exists $data{$file}) {
226 $data{$file} = +{
227 INDEX => 'unchanged',
228 BINARY => 0,
231 my ($change, $bin);
232 if ($add eq '-' && $del eq '-') {
233 $change = 'binary';
234 $bin = 1;
236 else {
237 $change = "+$add/-$del";
239 $data{$file}{FILE} = $change;
240 if ($bin) {
241 $data{$file}{BINARY} = 1;
244 elsif (($adddel, $file) =
245 /^ (create|delete) mode [0-7]+ (.*)$/) {
246 $file = unquote_path($file);
247 $data{$file}{FILE_ADDDEL} = $adddel;
251 for (sort keys %data) {
252 my $it = $data{$_};
254 if ($only) {
255 if ($only eq 'index-only') {
256 next if ($it->{INDEX} eq 'unchanged');
258 if ($only eq 'file-only') {
259 next if ($it->{FILE} eq 'nothing');
262 push @return, +{
263 VALUE => $_,
264 %$it,
267 return @return;
270 sub find_unique {
271 my ($string, @stuff) = @_;
272 my $found = undef;
273 for (my $i = 0; $i < @stuff; $i++) {
274 my $it = $stuff[$i];
275 my $hit = undef;
276 if (ref $it) {
277 if ((ref $it) eq 'ARRAY') {
278 $it = $it->[0];
280 else {
281 $it = $it->{VALUE};
284 eval {
285 if ($it =~ /^$string/) {
286 $hit = 1;
289 if (defined $hit && defined $found) {
290 return undef;
292 if ($hit) {
293 $found = $i + 1;
296 return $found;
299 # inserts string into trie and updates count for each character
300 sub update_trie {
301 my ($trie, $string) = @_;
302 foreach (split //, $string) {
303 $trie = $trie->{$_} ||= {COUNT => 0};
304 $trie->{COUNT}++;
308 # returns an array of tuples (prefix, remainder)
309 sub find_unique_prefixes {
310 my @stuff = @_;
311 my @return = ();
313 # any single prefix exceeding the soft limit is omitted
314 # if any prefix exceeds the hard limit all are omitted
315 # 0 indicates no limit
316 my $soft_limit = 0;
317 my $hard_limit = 3;
319 # build a trie modelling all possible options
320 my %trie;
321 foreach my $print (@stuff) {
322 if ((ref $print) eq 'ARRAY') {
323 $print = $print->[0];
325 elsif ((ref $print) eq 'HASH') {
326 $print = $print->{VALUE};
328 update_trie(\%trie, $print);
329 push @return, $print;
332 # use the trie to find the unique prefixes
333 for (my $i = 0; $i < @return; $i++) {
334 my $ret = $return[$i];
335 my @letters = split //, $ret;
336 my %search = %trie;
337 my ($prefix, $remainder);
338 my $j;
339 for ($j = 0; $j < @letters; $j++) {
340 my $letter = $letters[$j];
341 if ($search{$letter}{COUNT} == 1) {
342 $prefix = substr $ret, 0, $j + 1;
343 $remainder = substr $ret, $j + 1;
344 last;
346 else {
347 my $prefix = substr $ret, 0, $j;
348 return ()
349 if ($hard_limit && $j + 1 > $hard_limit);
351 %search = %{$search{$letter}};
353 if (ord($letters[0]) > 127 ||
354 ($soft_limit && $j + 1 > $soft_limit)) {
355 $prefix = undef;
356 $remainder = $ret;
358 $return[$i] = [$prefix, $remainder];
360 return @return;
363 # filters out prefixes which have special meaning to list_and_choose()
364 sub is_valid_prefix {
365 my $prefix = shift;
366 return (defined $prefix) &&
367 !($prefix =~ /[\s,]/) && # separators
368 !($prefix =~ /^-/) && # deselection
369 !($prefix =~ /^\d+/) && # selection
370 ($prefix ne '*') && # "all" wildcard
371 ($prefix ne '?'); # prompt help
374 # given a prefix/remainder tuple return a string with the prefix highlighted
375 # for now use square brackets; later might use ANSI colors (underline, bold)
376 sub highlight_prefix {
377 my $prefix = shift;
378 my $remainder = shift;
380 if (!defined $prefix) {
381 return $remainder;
384 if (!is_valid_prefix($prefix)) {
385 return "$prefix$remainder";
388 if (!$menu_use_color) {
389 return "[$prefix]$remainder";
392 return "$prompt_color$prefix$normal_color$remainder";
395 sub error_msg {
396 print STDERR colored $error_color, @_;
399 sub list_and_choose {
400 my ($opts, @stuff) = @_;
401 my (@chosen, @return);
402 my $i;
403 my @prefixes = find_unique_prefixes(@stuff) unless $opts->{LIST_ONLY};
405 TOPLOOP:
406 while (1) {
407 my $last_lf = 0;
409 if ($opts->{HEADER}) {
410 if (!$opts->{LIST_FLAT}) {
411 print " ";
413 print colored $header_color, "$opts->{HEADER}\n";
415 for ($i = 0; $i < @stuff; $i++) {
416 my $chosen = $chosen[$i] ? '*' : ' ';
417 my $print = $stuff[$i];
418 my $ref = ref $print;
419 my $highlighted = highlight_prefix(@{$prefixes[$i]})
420 if @prefixes;
421 if ($ref eq 'ARRAY') {
422 $print = $highlighted || $print->[0];
424 elsif ($ref eq 'HASH') {
425 my $value = $highlighted || $print->{VALUE};
426 $print = sprintf($status_fmt,
427 $print->{INDEX},
428 $print->{FILE},
429 $value);
431 else {
432 $print = $highlighted || $print;
434 printf("%s%2d: %s", $chosen, $i+1, $print);
435 if (($opts->{LIST_FLAT}) &&
436 (($i + 1) % ($opts->{LIST_FLAT}))) {
437 print "\t";
438 $last_lf = 0;
440 else {
441 print "\n";
442 $last_lf = 1;
445 if (!$last_lf) {
446 print "\n";
449 return if ($opts->{LIST_ONLY});
451 print colored $prompt_color, $opts->{PROMPT};
452 if ($opts->{SINGLETON}) {
453 print "> ";
455 else {
456 print ">> ";
458 my $line = <STDIN>;
459 if (!$line) {
460 print "\n";
461 $opts->{ON_EOF}->() if $opts->{ON_EOF};
462 last;
464 chomp $line;
465 last if $line eq '';
466 if ($line eq '?') {
467 $opts->{SINGLETON} ?
468 singleton_prompt_help_cmd() :
469 prompt_help_cmd();
470 next TOPLOOP;
472 for my $choice (split(/[\s,]+/, $line)) {
473 my $choose = 1;
474 my ($bottom, $top);
476 # Input that begins with '-'; unchoose
477 if ($choice =~ s/^-//) {
478 $choose = 0;
480 # A range can be specified like 5-7 or 5-.
481 if ($choice =~ /^(\d+)-(\d*)$/) {
482 ($bottom, $top) = ($1, length($2) ? $2 : 1 + @stuff);
484 elsif ($choice =~ /^\d+$/) {
485 $bottom = $top = $choice;
487 elsif ($choice eq '*') {
488 $bottom = 1;
489 $top = 1 + @stuff;
491 else {
492 $bottom = $top = find_unique($choice, @stuff);
493 if (!defined $bottom) {
494 error_msg "Huh ($choice)?\n";
495 next TOPLOOP;
498 if ($opts->{SINGLETON} && $bottom != $top) {
499 error_msg "Huh ($choice)?\n";
500 next TOPLOOP;
502 for ($i = $bottom-1; $i <= $top-1; $i++) {
503 next if (@stuff <= $i || $i < 0);
504 $chosen[$i] = $choose;
507 last if ($opts->{IMMEDIATE} || $line eq '*');
509 for ($i = 0; $i < @stuff; $i++) {
510 if ($chosen[$i]) {
511 push @return, $stuff[$i];
514 return @return;
517 sub singleton_prompt_help_cmd {
518 print colored $help_color, <<\EOF ;
519 Prompt help:
520 1 - select a numbered item
521 foo - select item based on unique prefix
522 - (empty) select nothing
526 sub prompt_help_cmd {
527 print colored $help_color, <<\EOF ;
528 Prompt help:
529 1 - select a single item
530 3-5 - select a range of items
531 2-3,6-9 - select multiple ranges
532 foo - select item based on unique prefix
533 -... - unselect specified items
534 * - choose all items
535 - (empty) finish selecting
539 sub status_cmd {
540 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
541 list_modified());
542 print "\n";
545 sub say_n_paths {
546 my $did = shift @_;
547 my $cnt = scalar @_;
548 print "$did ";
549 if (1 < $cnt) {
550 print "$cnt paths\n";
552 else {
553 print "one path\n";
557 sub update_cmd {
558 my @mods = list_modified('file-only');
559 return if (!@mods);
561 my @update = list_and_choose({ PROMPT => 'Update',
562 HEADER => $status_head, },
563 @mods);
564 if (@update) {
565 system(qw(git update-index --add --remove --),
566 map { $_->{VALUE} } @update);
567 say_n_paths('updated', @update);
569 print "\n";
572 sub revert_cmd {
573 my @update = list_and_choose({ PROMPT => 'Revert',
574 HEADER => $status_head, },
575 list_modified());
576 if (@update) {
577 if (is_initial_commit()) {
578 system(qw(git rm --cached),
579 map { $_->{VALUE} } @update);
581 else {
582 my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
583 map { $_->{VALUE} } @update);
584 my $fh;
585 open $fh, '| git update-index --index-info'
586 or die;
587 for (@lines) {
588 print $fh $_;
590 close($fh);
591 for (@update) {
592 if ($_->{INDEX_ADDDEL} &&
593 $_->{INDEX_ADDDEL} eq 'create') {
594 system(qw(git update-index --force-remove --),
595 $_->{VALUE});
596 print "note: $_->{VALUE} is untracked now.\n";
600 refresh();
601 say_n_paths('reverted', @update);
603 print "\n";
606 sub add_untracked_cmd {
607 my @add = list_and_choose({ PROMPT => 'Add untracked' },
608 list_untracked());
609 if (@add) {
610 system(qw(git update-index --add --), @add);
611 say_n_paths('added', @add);
613 print "\n";
616 sub parse_diff {
617 my ($path) = @_;
618 my @diff = run_cmd_pipe(qw(git diff-files -p --), $path);
619 my @colored = ();
620 if ($diff_use_color) {
621 @colored = run_cmd_pipe(qw(git diff-files -p --color --), $path);
623 my (@hunk) = { TEXT => [], DISPLAY => [], TYPE => 'header' };
625 for (my $i = 0; $i < @diff; $i++) {
626 if ($diff[$i] =~ /^@@ /) {
627 push @hunk, { TEXT => [], DISPLAY => [],
628 TYPE => 'hunk' };
630 push @{$hunk[-1]{TEXT}}, $diff[$i];
631 push @{$hunk[-1]{DISPLAY}},
632 ($diff_use_color ? $colored[$i] : $diff[$i]);
634 return @hunk;
637 sub parse_diff_header {
638 my $src = shift;
640 my $head = { TEXT => [], DISPLAY => [], TYPE => 'header' };
641 my $mode = { TEXT => [], DISPLAY => [], TYPE => 'mode' };
643 for (my $i = 0; $i < @{$src->{TEXT}}; $i++) {
644 my $dest = $src->{TEXT}->[$i] =~ /^(old|new) mode (\d+)$/ ?
645 $mode : $head;
646 push @{$dest->{TEXT}}, $src->{TEXT}->[$i];
647 push @{$dest->{DISPLAY}}, $src->{DISPLAY}->[$i];
649 return ($head, $mode);
652 sub hunk_splittable {
653 my ($text) = @_;
655 my @s = split_hunk($text);
656 return (1 < @s);
659 sub parse_hunk_header {
660 my ($line) = @_;
661 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
662 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
663 $o_cnt = 1 unless defined $o_cnt;
664 $n_cnt = 1 unless defined $n_cnt;
665 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
668 sub split_hunk {
669 my ($text, $display) = @_;
670 my @split = ();
671 if (!defined $display) {
672 $display = $text;
674 # If there are context lines in the middle of a hunk,
675 # it can be split, but we would need to take care of
676 # overlaps later.
678 my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
679 my $hunk_start = 1;
681 OUTER:
682 while (1) {
683 my $next_hunk_start = undef;
684 my $i = $hunk_start - 1;
685 my $this = +{
686 TEXT => [],
687 DISPLAY => [],
688 TYPE => 'hunk',
689 OLD => $o_ofs,
690 NEW => $n_ofs,
691 OCNT => 0,
692 NCNT => 0,
693 ADDDEL => 0,
694 POSTCTX => 0,
695 USE => undef,
698 while (++$i < @$text) {
699 my $line = $text->[$i];
700 my $display = $display->[$i];
701 if ($line =~ /^ /) {
702 if ($this->{ADDDEL} &&
703 !defined $next_hunk_start) {
704 # We have seen leading context and
705 # adds/dels and then here is another
706 # context, which is trailing for this
707 # split hunk and leading for the next
708 # one.
709 $next_hunk_start = $i;
711 push @{$this->{TEXT}}, $line;
712 push @{$this->{DISPLAY}}, $display;
713 $this->{OCNT}++;
714 $this->{NCNT}++;
715 if (defined $next_hunk_start) {
716 $this->{POSTCTX}++;
718 next;
721 # add/del
722 if (defined $next_hunk_start) {
723 # We are done with the current hunk and
724 # this is the first real change for the
725 # next split one.
726 $hunk_start = $next_hunk_start;
727 $o_ofs = $this->{OLD} + $this->{OCNT};
728 $n_ofs = $this->{NEW} + $this->{NCNT};
729 $o_ofs -= $this->{POSTCTX};
730 $n_ofs -= $this->{POSTCTX};
731 push @split, $this;
732 redo OUTER;
734 push @{$this->{TEXT}}, $line;
735 push @{$this->{DISPLAY}}, $display;
736 $this->{ADDDEL}++;
737 if ($line =~ /^-/) {
738 $this->{OCNT}++;
740 else {
741 $this->{NCNT}++;
745 push @split, $this;
746 last;
749 for my $hunk (@split) {
750 $o_ofs = $hunk->{OLD};
751 $n_ofs = $hunk->{NEW};
752 my $o_cnt = $hunk->{OCNT};
753 my $n_cnt = $hunk->{NCNT};
755 my $head = ("@@ -$o_ofs" .
756 (($o_cnt != 1) ? ",$o_cnt" : '') .
757 " +$n_ofs" .
758 (($n_cnt != 1) ? ",$n_cnt" : '') .
759 " @@\n");
760 my $display_head = $head;
761 unshift @{$hunk->{TEXT}}, $head;
762 if ($diff_use_color) {
763 $display_head = colored($fraginfo_color, $head);
765 unshift @{$hunk->{DISPLAY}}, $display_head;
767 return @split;
770 sub find_last_o_ctx {
771 my ($it) = @_;
772 my $text = $it->{TEXT};
773 my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
774 my $i = @{$text};
775 my $last_o_ctx = $o_ofs + $o_cnt;
776 while (0 < --$i) {
777 my $line = $text->[$i];
778 if ($line =~ /^ /) {
779 $last_o_ctx--;
780 next;
782 last;
784 return $last_o_ctx;
787 sub merge_hunk {
788 my ($prev, $this) = @_;
789 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
790 parse_hunk_header($prev->{TEXT}[0]);
791 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
792 parse_hunk_header($this->{TEXT}[0]);
794 my (@line, $i, $ofs, $o_cnt, $n_cnt);
795 $ofs = $o0_ofs;
796 $o_cnt = $n_cnt = 0;
797 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
798 my $line = $prev->{TEXT}[$i];
799 if ($line =~ /^\+/) {
800 $n_cnt++;
801 push @line, $line;
802 next;
805 last if ($o1_ofs <= $ofs);
807 $o_cnt++;
808 $ofs++;
809 if ($line =~ /^ /) {
810 $n_cnt++;
812 push @line, $line;
815 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
816 my $line = $this->{TEXT}[$i];
817 if ($line =~ /^\+/) {
818 $n_cnt++;
819 push @line, $line;
820 next;
822 $ofs++;
823 $o_cnt++;
824 if ($line =~ /^ /) {
825 $n_cnt++;
827 push @line, $line;
829 my $head = ("@@ -$o0_ofs" .
830 (($o_cnt != 1) ? ",$o_cnt" : '') .
831 " +$n0_ofs" .
832 (($n_cnt != 1) ? ",$n_cnt" : '') .
833 " @@\n");
834 @{$prev->{TEXT}} = ($head, @line);
837 sub coalesce_overlapping_hunks {
838 my (@in) = @_;
839 my @out = ();
841 my ($last_o_ctx, $last_was_dirty);
843 for (grep { $_->{USE} } @in) {
844 my $text = $_->{TEXT};
845 my ($o_ofs) = parse_hunk_header($text->[0]);
846 if (defined $last_o_ctx &&
847 $o_ofs <= $last_o_ctx &&
848 !$_->{DIRTY} &&
849 !$last_was_dirty) {
850 merge_hunk($out[-1], $_);
852 else {
853 push @out, $_;
855 $last_o_ctx = find_last_o_ctx($out[-1]);
856 $last_was_dirty = $_->{DIRTY};
858 return @out;
861 sub color_diff {
862 return map {
863 colored((/^@/ ? $fraginfo_color :
864 /^\+/ ? $diff_new_color :
865 /^-/ ? $diff_old_color :
866 $diff_plain_color),
867 $_);
868 } @_;
871 sub edit_hunk_manually {
872 my ($oldtext) = @_;
874 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
875 my $fh;
876 open $fh, '>', $hunkfile
877 or die "failed to open hunk edit file for writing: " . $!;
878 print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
879 print $fh @$oldtext;
880 print $fh <<EOF;
881 # ---
882 # To remove '-' lines, make them ' ' lines (context).
883 # To remove '+' lines, delete them.
884 # Lines starting with # will be removed.
886 # If the patch applies cleanly, the edited hunk will immediately be
887 # marked for staging. If it does not apply cleanly, you will be given
888 # an opportunity to edit again. If all lines of the hunk are removed,
889 # then the edit is aborted and the hunk is left unchanged.
891 close $fh;
893 my $editor = $ENV{GIT_EDITOR} || $repo->config("core.editor")
894 || $ENV{VISUAL} || $ENV{EDITOR} || "vi";
895 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
897 if ($? != 0) {
898 return undef;
901 open $fh, '<', $hunkfile
902 or die "failed to open hunk edit file for reading: " . $!;
903 my @newtext = grep { !/^#/ } <$fh>;
904 close $fh;
905 unlink $hunkfile;
907 # Abort if nothing remains
908 if (!grep { /\S/ } @newtext) {
909 return undef;
912 # Reinsert the first hunk header if the user accidentally deleted it
913 if ($newtext[0] !~ /^@/) {
914 unshift @newtext, $oldtext->[0];
916 return \@newtext;
919 sub diff_applies {
920 my $fh;
921 open $fh, '| git apply --recount --cached --check';
922 for my $h (@_) {
923 print $fh @{$h->{TEXT}};
925 return close $fh;
928 sub _restore_terminal_and_die {
929 ReadMode 'restore';
930 print "\n";
931 exit 1;
934 sub prompt_single_character {
935 if ($use_readkey) {
936 local $SIG{TERM} = \&_restore_terminal_and_die;
937 local $SIG{INT} = \&_restore_terminal_and_die;
938 ReadMode 'cbreak';
939 my $key = ReadKey 0;
940 ReadMode 'restore';
941 print "$key" if defined $key;
942 print "\n";
943 return $key;
944 } else {
945 return <STDIN>;
949 sub prompt_yesno {
950 my ($prompt) = @_;
951 while (1) {
952 print colored $prompt_color, $prompt;
953 my $line = prompt_single_character;
954 return 0 if $line =~ /^n/i;
955 return 1 if $line =~ /^y/i;
959 sub edit_hunk_loop {
960 my ($head, $hunk, $ix) = @_;
961 my $text = $hunk->[$ix]->{TEXT};
963 while (1) {
964 $text = edit_hunk_manually($text);
965 if (!defined $text) {
966 return undef;
968 my $newhunk = {
969 TEXT => $text,
970 TYPE => $hunk->[$ix]->{TYPE},
971 USE => 1,
972 DIRTY => 1,
974 if (diff_applies($head,
975 @{$hunk}[0..$ix-1],
976 $newhunk,
977 @{$hunk}[$ix+1..$#{$hunk}])) {
978 $newhunk->{DISPLAY} = [color_diff(@{$text})];
979 return $newhunk;
981 else {
982 prompt_yesno(
983 'Your edited hunk does not apply. Edit again '
984 . '(saying "no" discards!) [y/n]? '
985 ) or return undef;
990 sub help_patch_cmd {
991 print colored $help_color, <<\EOF ;
992 y - stage this hunk
993 n - do not stage this hunk
994 q - quit, do not stage this hunk nor any of the remaining ones
995 a - stage this and all the remaining hunks in the file
996 d - do not stage this hunk nor any of the remaining hunks in the file
997 g - select a hunk to go to
998 / - search for a hunk matching the given regex
999 j - leave this hunk undecided, see next undecided hunk
1000 J - leave this hunk undecided, see next hunk
1001 k - leave this hunk undecided, see previous undecided hunk
1002 K - leave this hunk undecided, see previous hunk
1003 s - split the current hunk into smaller hunks
1004 e - manually edit the current hunk
1005 ? - print help
1009 sub patch_update_cmd {
1010 my @all_mods = list_modified('file-only');
1011 my @mods = grep { !($_->{BINARY}) } @all_mods;
1012 my @them;
1014 if (!@mods) {
1015 if (@all_mods) {
1016 print STDERR "Only binary files changed.\n";
1017 } else {
1018 print STDERR "No changes.\n";
1020 return 0;
1022 if ($patch_mode) {
1023 @them = @mods;
1025 else {
1026 @them = list_and_choose({ PROMPT => 'Patch update',
1027 HEADER => $status_head, },
1028 @mods);
1030 for (@them) {
1031 return 0 if patch_update_file($_->{VALUE});
1035 # Generate a one line summary of a hunk.
1036 sub summarize_hunk {
1037 my $rhunk = shift;
1038 my $summary = $rhunk->{TEXT}[0];
1040 # Keep the line numbers, discard extra context.
1041 $summary =~ s/@@(.*?)@@.*/$1 /s;
1042 $summary .= " " x (20 - length $summary);
1044 # Add some user context.
1045 for my $line (@{$rhunk->{TEXT}}) {
1046 if ($line =~ m/^[+-].*\w/) {
1047 $summary .= $line;
1048 last;
1052 chomp $summary;
1053 return substr($summary, 0, 80) . "\n";
1057 # Print a one-line summary of each hunk in the array ref in
1058 # the first argument, starting wih the index in the 2nd.
1059 sub display_hunks {
1060 my ($hunks, $i) = @_;
1061 my $ctr = 0;
1062 $i ||= 0;
1063 for (; $i < @$hunks && $ctr < 20; $i++, $ctr++) {
1064 my $status = " ";
1065 if (defined $hunks->[$i]{USE}) {
1066 $status = $hunks->[$i]{USE} ? "+" : "-";
1068 printf "%s%2d: %s",
1069 $status,
1070 $i + 1,
1071 summarize_hunk($hunks->[$i]);
1073 return $i;
1076 sub patch_update_file {
1077 my $quit = 0;
1078 my ($ix, $num);
1079 my $path = shift;
1080 my ($head, @hunk) = parse_diff($path);
1081 ($head, my $mode) = parse_diff_header($head);
1082 for (@{$head->{DISPLAY}}) {
1083 print;
1086 if (@{$mode->{TEXT}}) {
1087 unshift @hunk, $mode;
1090 $num = scalar @hunk;
1091 $ix = 0;
1093 while (1) {
1094 my ($prev, $next, $other, $undecided, $i);
1095 $other = '';
1097 if ($num <= $ix) {
1098 $ix = 0;
1100 for ($i = 0; $i < $ix; $i++) {
1101 if (!defined $hunk[$i]{USE}) {
1102 $prev = 1;
1103 $other .= ',k';
1104 last;
1107 if ($ix) {
1108 $other .= ',K';
1110 for ($i = $ix + 1; $i < $num; $i++) {
1111 if (!defined $hunk[$i]{USE}) {
1112 $next = 1;
1113 $other .= ',j';
1114 last;
1117 if ($ix < $num - 1) {
1118 $other .= ',J';
1120 if ($num > 1) {
1121 $other .= ',g';
1123 for ($i = 0; $i < $num; $i++) {
1124 if (!defined $hunk[$i]{USE}) {
1125 $undecided = 1;
1126 last;
1129 last if (!$undecided);
1131 if ($hunk[$ix]{TYPE} eq 'hunk' &&
1132 hunk_splittable($hunk[$ix]{TEXT})) {
1133 $other .= ',s';
1135 if ($hunk[$ix]{TYPE} eq 'hunk') {
1136 $other .= ',e';
1138 for (@{$hunk[$ix]{DISPLAY}}) {
1139 print;
1141 print colored $prompt_color, 'Stage ',
1142 ($hunk[$ix]{TYPE} eq 'mode' ? 'mode change' : 'this hunk'),
1143 " [y,n,q,a,d,/$other,?]? ";
1144 my $line = prompt_single_character;
1145 if ($line) {
1146 if ($line =~ /^y/i) {
1147 $hunk[$ix]{USE} = 1;
1149 elsif ($line =~ /^n/i) {
1150 $hunk[$ix]{USE} = 0;
1152 elsif ($line =~ /^a/i) {
1153 while ($ix < $num) {
1154 if (!defined $hunk[$ix]{USE}) {
1155 $hunk[$ix]{USE} = 1;
1157 $ix++;
1159 next;
1161 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1162 my $response = $1;
1163 my $no = $ix > 10 ? $ix - 10 : 0;
1164 while ($response eq '') {
1165 my $extra = "";
1166 $no = display_hunks(\@hunk, $no);
1167 if ($no < $num) {
1168 $extra = " (<ret> to see more)";
1170 print "go to which hunk$extra? ";
1171 $response = <STDIN>;
1172 if (!defined $response) {
1173 $response = '';
1175 chomp $response;
1177 if ($response !~ /^\s*\d+\s*$/) {
1178 error_msg "Invalid number: '$response'\n";
1179 } elsif (0 < $response && $response <= $num) {
1180 $ix = $response - 1;
1181 } else {
1182 error_msg "Sorry, only $num hunks available.\n";
1184 next;
1186 elsif ($line =~ /^d/i) {
1187 while ($ix < $num) {
1188 if (!defined $hunk[$ix]{USE}) {
1189 $hunk[$ix]{USE} = 0;
1191 $ix++;
1193 next;
1195 elsif ($line =~ /^q/i) {
1196 while ($ix < $num) {
1197 if (!defined $hunk[$ix]{USE}) {
1198 $hunk[$ix]{USE} = 0;
1200 $ix++;
1202 $quit = 1;
1203 next;
1205 elsif ($line =~ m|^/(.*)|) {
1206 my $regex = $1;
1207 if ($1 eq "") {
1208 print colored $prompt_color, "search for regex? ";
1209 $regex = <STDIN>;
1210 if (defined $regex) {
1211 chomp $regex;
1214 my $search_string;
1215 eval {
1216 $search_string = qr{$regex}m;
1218 if ($@) {
1219 my ($err,$exp) = ($@, $1);
1220 $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1221 error_msg "Malformed search regexp $exp: $err\n";
1222 next;
1224 my $iy = $ix;
1225 while (1) {
1226 my $text = join ("", @{$hunk[$iy]{TEXT}});
1227 last if ($text =~ $search_string);
1228 $iy++;
1229 $iy = 0 if ($iy >= $num);
1230 if ($ix == $iy) {
1231 error_msg "No hunk matches the given pattern\n";
1232 last;
1235 $ix = $iy;
1236 next;
1238 elsif ($line =~ /^K/) {
1239 if ($other =~ /K/) {
1240 $ix--;
1242 else {
1243 error_msg "No previous hunk\n";
1245 next;
1247 elsif ($line =~ /^J/) {
1248 if ($other =~ /J/) {
1249 $ix++;
1251 else {
1252 error_msg "No next hunk\n";
1254 next;
1256 elsif ($line =~ /^k/) {
1257 if ($other =~ /k/) {
1258 while (1) {
1259 $ix--;
1260 last if (!$ix ||
1261 !defined $hunk[$ix]{USE});
1264 else {
1265 error_msg "No previous hunk\n";
1267 next;
1269 elsif ($line =~ /^j/) {
1270 if ($other !~ /j/) {
1271 error_msg "No next hunk\n";
1272 next;
1275 elsif ($other =~ /s/ && $line =~ /^s/) {
1276 my @split = split_hunk($hunk[$ix]{TEXT}, $hunk[$ix]{DISPLAY});
1277 if (1 < @split) {
1278 print colored $header_color, "Split into ",
1279 scalar(@split), " hunks.\n";
1281 splice (@hunk, $ix, 1, @split);
1282 $num = scalar @hunk;
1283 next;
1285 elsif ($other =~ /e/ && $line =~ /^e/) {
1286 my $newhunk = edit_hunk_loop($head, \@hunk, $ix);
1287 if (defined $newhunk) {
1288 splice @hunk, $ix, 1, $newhunk;
1291 else {
1292 help_patch_cmd($other);
1293 next;
1295 # soft increment
1296 while (1) {
1297 $ix++;
1298 last if ($ix >= $num ||
1299 !defined $hunk[$ix]{USE});
1304 @hunk = coalesce_overlapping_hunks(@hunk);
1306 my $n_lofs = 0;
1307 my @result = ();
1308 for (@hunk) {
1309 if ($_->{USE}) {
1310 push @result, @{$_->{TEXT}};
1314 if (@result) {
1315 my $fh;
1317 open $fh, '| git apply --cached --recount';
1318 for (@{$head->{TEXT}}, @result) {
1319 print $fh $_;
1320 print STDERR $_;
1322 if (!close $fh) {
1323 for (@{$head->{TEXT}}, @result) {
1324 print STDERR $_;
1327 refresh();
1330 print "\n";
1331 return $quit;
1334 sub diff_cmd {
1335 my @mods = list_modified('index-only');
1336 @mods = grep { !($_->{BINARY}) } @mods;
1337 return if (!@mods);
1338 my (@them) = list_and_choose({ PROMPT => 'Review diff',
1339 IMMEDIATE => 1,
1340 HEADER => $status_head, },
1341 @mods);
1342 return if (!@them);
1343 my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
1344 system(qw(git diff -p --cached), $reference, '--',
1345 map { $_->{VALUE} } @them);
1348 sub quit_cmd {
1349 print "Bye.\n";
1350 exit(0);
1353 sub help_cmd {
1354 print colored $help_color, <<\EOF ;
1355 status - show paths with changes
1356 update - add working tree state to the staged set of changes
1357 revert - revert staged set of changes back to the HEAD version
1358 patch - pick hunks and update selectively
1359 diff - view diff between HEAD and index
1360 add untracked - add contents of untracked files to the staged set of changes
1364 sub process_args {
1365 return unless @ARGV;
1366 my $arg = shift @ARGV;
1367 if ($arg eq "--patch") {
1368 $patch_mode = 1;
1369 $arg = shift @ARGV or die "missing --";
1370 die "invalid argument $arg, expecting --"
1371 unless $arg eq "--";
1373 elsif ($arg ne "--") {
1374 die "invalid argument $arg, expecting --";
1378 sub main_loop {
1379 my @cmd = ([ 'status', \&status_cmd, ],
1380 [ 'update', \&update_cmd, ],
1381 [ 'revert', \&revert_cmd, ],
1382 [ 'add untracked', \&add_untracked_cmd, ],
1383 [ 'patch', \&patch_update_cmd, ],
1384 [ 'diff', \&diff_cmd, ],
1385 [ 'quit', \&quit_cmd, ],
1386 [ 'help', \&help_cmd, ],
1388 while (1) {
1389 my ($it) = list_and_choose({ PROMPT => 'What now',
1390 SINGLETON => 1,
1391 LIST_FLAT => 4,
1392 HEADER => '*** Commands ***',
1393 ON_EOF => \&quit_cmd,
1394 IMMEDIATE => 1 }, @cmd);
1395 if ($it) {
1396 eval {
1397 $it->[1]->();
1399 if ($@) {
1400 print "$@";
1406 process_args();
1407 refresh();
1408 if ($patch_mode) {
1409 patch_update_cmd();
1411 else {
1412 status_cmd();
1413 main_loop();