7 my ($prompt_color, $header_color, $help_color, $normal_color);
9 my ($new_color, $old_color, $fraginfo_color, $metainfo_color, $whitespace_color);
11 my ($use_color, $diff_use_color);
12 my $repo = Git->repository();
14 $use_color = $repo->get_colorbool('color.interactive');
17 # Set interactive colors:
19 # Grab the 3 main colors in git color string format, with sane
21 $prompt_color = $repo->get_color("color.interactive.prompt", "bold blue");
22 $header_color = $repo->get_color("color.interactive.header", "bold");
23 $help_color = $repo->get_color("color.interactive.help", "red bold");
24 $normal_color = $repo->get_color("", "reset");
26 # Do we also set diff colors?
27 $diff_use_color = $repo->get_colorbool('color.diff');
28 if ($diff_use_color) {
29 $new_color = $repo->get_color("color.diff.new", "green");
30 $old_color = $repo->get_color("color.diff.old", "red");
31 $fraginfo_color = $repo->get_color("color.diff.frag", "cyan");
32 $metainfo_color = $repo->get_color("color.diff.meta", "bold");
33 $whitespace_color = $repo->get_color("color.diff.whitespace", "normal red");
39 my $string = join("", @_);
42 # Put a color code at the beginning of each line, a reset at the end
43 # color after newlines that are not at the end of the string
44 $string =~ s/(\n+)(.)/$1$color$2/g;
45 # reset before newlines
46 $string =~ s/(\n+)/$normal_color$1/g;
47 # codes at beginning and end (if necessary):
48 $string =~ s/^/$color/;
49 $string =~ s/$/$normal_color/ unless $string =~ /\n$/;
54 # command line options
58 if ($^O eq 'MSWin32') {
59 my @invalid = grep {m/[":*]/} @_;
60 die "$^O does not support: @invalid\n" if @invalid;
61 my @args = map { m/ /o ? "\"$_\"": $_ } @_;
65 open($fh, '-|', @_) or die;
70 my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));
72 if (!defined $GIT_DIR) {
73 exit(1); # rev-parse would have already said "not a git repo"
79 open $fh, 'git update-index --refresh |'
82 ;# ignore 'needs update'
92 run_cmd_pipe(qw(git ls-files --others --exclude-standard --), @ARGV);
95 my $status_fmt = '%12s %12s %s';
96 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
98 # Returns list of hashes, contents of each of which are:
100 # BINARY: is a binary path
101 # INDEX: is index different from HEAD?
102 # FILE: is file different from index?
103 # INDEX_ADDDEL: is it add/delete between HEAD and index?
104 # FILE_ADDDEL: is it add/delete between index and file?
109 my ($add, $del, $adddel, $file);
115 } run_cmd_pipe(qw(git ls-files --exclude-standard --), @ARGV);
116 return if (!@tracked);
119 for (run_cmd_pipe(qw(git diff-index --cached
120 --numstat --summary HEAD --), @tracked)) {
121 if (($add, $del, $file) =
122 /^([-\d]+) ([-\d]+) (.*)/) {
124 if ($add eq '-' && $del eq '-') {
129 $change = "+$add/-$del";
137 elsif (($adddel, $file) =
138 /^ (create|delete) mode [0-7]+ (.*)$/) {
139 $data{$file}{INDEX_ADDDEL} = $adddel;
143 for (run_cmd_pipe(qw(git diff-files --numstat --summary --), @tracked)) {
144 if (($add, $del, $file) =
145 /^([-\d]+) ([-\d]+) (.*)/) {
146 if (!exists $data{$file}) {
148 INDEX => 'unchanged',
153 if ($add eq '-' && $del eq '-') {
158 $change = "+$add/-$del";
160 $data{$file}{FILE} = $change;
162 $data{$file}{BINARY} = 1;
165 elsif (($adddel, $file) =
166 /^ (create|delete) mode [0-7]+ (.*)$/) {
167 $data{$file}{FILE_ADDDEL} = $adddel;
171 for (sort keys %data) {
175 if ($only eq 'index-only') {
176 next if ($it->{INDEX} eq 'unchanged');
178 if ($only eq 'file-only') {
179 next if ($it->{FILE} eq 'nothing');
191 my ($string, @stuff) = @_;
193 for (my $i = 0; $i < @stuff; $i++) {
197 if ((ref $it) eq 'ARRAY') {
205 if ($it =~ /^$string/) {
209 if (defined $hit && defined $found) {
219 # inserts string into trie and updates count for each character
221 my ($trie, $string) = @_;
222 foreach (split //, $string) {
223 $trie = $trie->{$_} ||= {COUNT => 0};
228 # returns an array of tuples (prefix, remainder)
229 sub find_unique_prefixes {
233 # any single prefix exceeding the soft limit is omitted
234 # if any prefix exceeds the hard limit all are omitted
235 # 0 indicates no limit
239 # build a trie modelling all possible options
241 foreach my $print (@stuff) {
242 if ((ref $print) eq 'ARRAY') {
243 $print = $print->[0];
245 elsif ((ref $print) eq 'HASH') {
246 $print = $print->{VALUE};
248 update_trie(\%trie, $print);
249 push @return, $print;
252 # use the trie to find the unique prefixes
253 for (my $i = 0; $i < @return; $i++) {
254 my $ret = $return[$i];
255 my @letters = split //, $ret;
257 my ($prefix, $remainder);
259 for ($j = 0; $j < @letters; $j++) {
260 my $letter = $letters[$j];
261 if ($search{$letter}{COUNT} == 1) {
262 $prefix = substr $ret, 0, $j + 1;
263 $remainder = substr $ret, $j + 1;
267 my $prefix = substr $ret, 0, $j;
269 if ($hard_limit && $j + 1 > $hard_limit);
271 %search = %{$search{$letter}};
273 if ($soft_limit && $j + 1 > $soft_limit) {
277 $return[$i] = [$prefix, $remainder];
282 # filters out prefixes which have special meaning to list_and_choose()
283 sub is_valid_prefix {
285 return (defined $prefix) &&
286 !($prefix =~ /[\s,]/) && # separators
287 !($prefix =~ /^-/) && # deselection
288 !($prefix =~ /^\d+/) && # selection
289 ($prefix ne '*') && # "all" wildcard
290 ($prefix ne '?'); # prompt help
293 # given a prefix/remainder tuple return a string with the prefix highlighted
294 # for now use square brackets; later might use ANSI colors (underline, bold)
295 sub highlight_prefix {
297 my $remainder = shift;
299 if (!defined $prefix) {
303 if (!is_valid_prefix($prefix)) {
304 return "$prefix$remainder";
308 return "[$prefix]$remainder";
311 return "$prompt_color$prefix$normal_color$remainder";
314 sub list_and_choose {
315 my ($opts, @stuff) = @_;
316 my (@chosen, @return);
318 my @prefixes = find_unique_prefixes(@stuff) unless $opts->{LIST_ONLY};
324 if ($opts->{HEADER}) {
325 if (!$opts->{LIST_FLAT}) {
328 print colored $header_color, "$opts->{HEADER}\n";
330 for ($i = 0; $i < @stuff; $i++) {
331 my $chosen = $chosen[$i] ? '*' : ' ';
332 my $print = $stuff[$i];
333 my $ref = ref $print;
334 my $highlighted = highlight_prefix(@{$prefixes[$i]})
336 if ($ref eq 'ARRAY') {
337 $print = $highlighted || $print->[0];
339 elsif ($ref eq 'HASH') {
340 my $value = $highlighted || $print->{VALUE};
341 $print = sprintf($status_fmt,
347 $print = $highlighted || $print;
349 printf("%s%2d: %s", $chosen, $i+1, $print);
350 if (($opts->{LIST_FLAT}) &&
351 (($i + 1) % ($opts->{LIST_FLAT}))) {
364 return if ($opts->{LIST_ONLY});
366 print colored $prompt_color, $opts->{PROMPT};
367 if ($opts->{SINGLETON}) {
376 $opts->{ON_EOF}->() if $opts->{ON_EOF};
383 singleton_prompt_help_cmd() :
387 for my $choice (split(/[\s,]+/, $line)) {
391 # Input that begins with '-'; unchoose
392 if ($choice =~ s/^-//) {
395 # A range can be specified like 5-7
396 if ($choice =~ /^(\d+)-(\d+)$/) {
397 ($bottom, $top) = ($1, $2);
399 elsif ($choice =~ /^\d+$/) {
400 $bottom = $top = $choice;
402 elsif ($choice eq '*') {
407 $bottom = $top = find_unique($choice, @stuff);
408 if (!defined $bottom) {
409 print "Huh ($choice)?\n";
413 if ($opts->{SINGLETON} && $bottom != $top) {
414 print "Huh ($choice)?\n";
417 for ($i = $bottom-1; $i <= $top-1; $i++) {
418 next if (@stuff <= $i || $i < 0);
419 $chosen[$i] = $choose;
422 last if ($opts->{IMMEDIATE} || $line eq '*');
424 for ($i = 0; $i < @stuff; $i++) {
426 push @return, $stuff[$i];
432 sub singleton_prompt_help_cmd {
433 print colored $help_color, <<\EOF ;
435 1 - select a numbered item
436 foo - select item based on unique prefix
437 - (empty) select nothing
441 sub prompt_help_cmd {
442 print colored $help_color, <<\EOF ;
444 1 - select a single item
445 3-5 - select a range of items
446 2-3,6-9 - select multiple ranges
447 foo - select item based on unique prefix
448 -... - unselect specified items
450 - (empty) finish selecting
455 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
465 print "$cnt paths\n";
473 my @mods = list_modified('file-only');
476 my @update = list_and_choose({ PROMPT => 'Update',
477 HEADER => $status_head, },
480 system(qw(git update-index --add --remove --),
481 map { $_->{VALUE} } @update);
482 say_n_paths('updated', @update);
488 my @update = list_and_choose({ PROMPT => 'Revert',
489 HEADER => $status_head, },
492 my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
493 map { $_->{VALUE} } @update);
495 open $fh, '| git update-index --index-info'
502 if ($_->{INDEX_ADDDEL} &&
503 $_->{INDEX_ADDDEL} eq 'create') {
504 system(qw(git update-index --force-remove --),
506 print "note: $_->{VALUE} is untracked now.\n";
510 say_n_paths('reverted', @update);
515 sub add_untracked_cmd {
516 my @add = list_and_choose({ PROMPT => 'Add untracked' },
519 system(qw(git update-index --add --), @add);
520 say_n_paths('added', @add);
527 my @diff = run_cmd_pipe(qw(git diff-files -p --), $path);
529 if ($diff_use_color) {
530 @colored = run_cmd_pipe(qw(git diff-files -p --color --), $path);
532 my (@hunk) = { TEXT => [], DISPLAY => [] };
534 for (my $i = 0; $i < @diff; $i++) {
535 if ($diff[$i] =~ /^@@ /) {
536 push @hunk, { TEXT => [], DISPLAY => [] };
538 push @{$hunk[-1]{TEXT}}, $diff[$i];
539 push @{$hunk[-1]{DISPLAY}},
540 ($diff_use_color ? $colored[$i] : $diff[$i]);
545 sub hunk_splittable {
548 my @s = split_hunk($text);
552 sub parse_hunk_header {
554 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
555 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
556 $o_cnt = 1 unless defined $o_cnt;
557 $n_cnt = 1 unless defined $n_cnt;
558 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
562 my ($text, $display) = @_;
564 if (!defined $display) {
567 # If there are context lines in the middle of a hunk,
568 # it can be split, but we would need to take care of
571 my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
576 my $next_hunk_start = undef;
577 my $i = $hunk_start - 1;
590 while (++$i < @$text) {
591 my $line = $text->[$i];
592 my $display = $display->[$i];
594 if ($this->{ADDDEL} &&
595 !defined $next_hunk_start) {
596 # We have seen leading context and
597 # adds/dels and then here is another
598 # context, which is trailing for this
599 # split hunk and leading for the next
601 $next_hunk_start = $i;
603 push @{$this->{TEXT}}, $line;
604 push @{$this->{DISPLAY}}, $display;
607 if (defined $next_hunk_start) {
614 if (defined $next_hunk_start) {
615 # We are done with the current hunk and
616 # this is the first real change for the
618 $hunk_start = $next_hunk_start;
619 $o_ofs = $this->{OLD} + $this->{OCNT};
620 $n_ofs = $this->{NEW} + $this->{NCNT};
621 $o_ofs -= $this->{POSTCTX};
622 $n_ofs -= $this->{POSTCTX};
626 push @{$this->{TEXT}}, $line;
627 push @{$this->{DISPLAY}}, $display;
641 for my $hunk (@split) {
642 $o_ofs = $hunk->{OLD};
643 $n_ofs = $hunk->{NEW};
644 my $o_cnt = $hunk->{OCNT};
645 my $n_cnt = $hunk->{NCNT};
647 my $head = ("@@ -$o_ofs" .
648 (($o_cnt != 1) ? ",$o_cnt" : '') .
650 (($n_cnt != 1) ? ",$n_cnt" : '') .
652 my $display_head = $head;
653 unshift @{$hunk->{TEXT}}, $head;
654 if ($diff_use_color) {
655 $display_head = colored($fraginfo_color, $head);
657 unshift @{$hunk->{DISPLAY}}, $display_head;
662 sub find_last_o_ctx {
664 my $text = $it->{TEXT};
665 my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
667 my $last_o_ctx = $o_ofs + $o_cnt;
669 my $line = $text->[$i];
680 my ($prev, $this) = @_;
681 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
682 parse_hunk_header($prev->{TEXT}[0]);
683 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
684 parse_hunk_header($this->{TEXT}[0]);
686 my (@line, $i, $ofs, $o_cnt, $n_cnt);
689 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
690 my $line = $prev->{TEXT}[$i];
691 if ($line =~ /^\+/) {
697 last if ($o1_ofs <= $ofs);
707 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
708 my $line = $this->{TEXT}[$i];
709 if ($line =~ /^\+/) {
721 my $head = ("@@ -$o0_ofs" .
722 (($o_cnt != 1) ? ",$o_cnt" : '') .
724 (($n_cnt != 1) ? ",$n_cnt" : '') .
726 @{$prev->{TEXT}} = ($head, @line);
729 sub coalesce_overlapping_hunks {
735 for (grep { $_->{USE} } @in) {
736 my $text = $_->{TEXT};
737 my ($o_ofs) = parse_hunk_header($text->[0]);
738 if (defined $last_o_ctx &&
739 $o_ofs <= $last_o_ctx) {
740 merge_hunk($out[-1], $_);
745 $last_o_ctx = find_last_o_ctx($out[-1]);
751 print colored $help_color, <<\EOF ;
753 n - do not stage this hunk
754 a - stage this and all the remaining hunks in the file
755 d - do not stage this hunk nor any of the remaining hunks in the file
756 j - leave this hunk undecided, see next undecided hunk
757 J - leave this hunk undecided, see next hunk
758 k - leave this hunk undecided, see previous undecided hunk
759 K - leave this hunk undecided, see previous hunk
760 s - split the current hunk into smaller hunks
765 sub patch_update_cmd {
766 my @mods = grep { !($_->{BINARY}) } list_modified('file-only');
770 print STDERR "No changes.\n";
777 @them = list_and_choose({ PROMPT => 'Patch update',
778 HEADER => $status_head, },
782 patch_update_file($_->{VALUE});
786 sub patch_update_file {
789 my ($head, @hunk) = parse_diff($path);
790 for (@{$head->{DISPLAY}}) {
797 my ($prev, $next, $other, $undecided, $i);
803 for ($i = 0; $i < $ix; $i++) {
804 if (!defined $hunk[$i]{USE}) {
813 for ($i = $ix + 1; $i < $num; $i++) {
814 if (!defined $hunk[$i]{USE}) {
820 if ($ix < $num - 1) {
823 for ($i = 0; $i < $num; $i++) {
824 if (!defined $hunk[$i]{USE}) {
829 last if (!$undecided);
831 if (hunk_splittable($hunk[$ix]{TEXT})) {
834 for (@{$hunk[$ix]{DISPLAY}}) {
837 print colored $prompt_color, "Stage this hunk [y/n/a/d$other/?]? ";
840 if ($line =~ /^y/i) {
843 elsif ($line =~ /^n/i) {
846 elsif ($line =~ /^a/i) {
848 if (!defined $hunk[$ix]{USE}) {
855 elsif ($line =~ /^d/i) {
857 if (!defined $hunk[$ix]{USE}) {
864 elsif ($other =~ /K/ && $line =~ /^K/) {
868 elsif ($other =~ /J/ && $line =~ /^J/) {
872 elsif ($other =~ /k/ && $line =~ /^k/) {
876 !defined $hunk[$ix]{USE});
880 elsif ($other =~ /j/ && $line =~ /^j/) {
883 last if ($ix >= $num ||
884 !defined $hunk[$ix]{USE});
888 elsif ($other =~ /s/ && $line =~ /^s/) {
889 my @split = split_hunk($hunk[$ix]{TEXT}, $hunk[$ix]{DISPLAY});
891 print colored $header_color, "Split into ",
892 scalar(@split), " hunks.\n";
894 splice (@hunk, $ix, 1, @split);
899 help_patch_cmd($other);
905 last if ($ix >= $num ||
906 !defined $hunk[$ix]{USE});
911 @hunk = coalesce_overlapping_hunks(@hunk);
916 my $text = $_->{TEXT};
917 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
918 parse_hunk_header($text->[0]);
921 # We would have added ($n_cnt - $o_cnt) lines
922 # to the postimage if we were to use this hunk,
923 # but we didn't. So the line number that the next
924 # hunk starts at would be shifted by that much.
925 $n_lofs -= ($n_cnt - $o_cnt);
931 $text->[0] = ("@@ -$o_ofs" .
948 open $fh, '| git apply --cached';
949 for (@{$head->{TEXT}}, @result) {
953 for (@{$head->{TEXT}}, @result) {
964 my @mods = list_modified('index-only');
965 @mods = grep { !($_->{BINARY}) } @mods;
967 my (@them) = list_and_choose({ PROMPT => 'Review diff',
969 HEADER => $status_head, },
972 system(qw(git diff -p --cached HEAD --), map { $_->{VALUE} } @them);
981 print colored $help_color, <<\EOF ;
982 status - show paths with changes
983 update - add working tree state to the staged set of changes
984 revert - revert staged set of changes back to the HEAD version
985 patch - pick hunks and update selectively
986 diff - view diff between HEAD and index
987 add untracked - add contents of untracked files to the staged set of changes
993 my $arg = shift @ARGV;
994 if ($arg eq "--patch") {
996 $arg = shift @ARGV or die "missing --";
997 die "invalid argument $arg, expecting --"
1000 elsif ($arg ne "--") {
1001 die "invalid argument $arg, expecting --";
1006 my @cmd = ([ 'status', \&status_cmd, ],
1007 [ 'update', \&update_cmd, ],
1008 [ 'revert', \&revert_cmd, ],
1009 [ 'add untracked', \&add_untracked_cmd, ],
1010 [ 'patch', \&patch_update_cmd, ],
1011 [ 'diff', \&diff_cmd, ],
1012 [ 'quit', \&quit_cmd, ],
1013 [ 'help', \&help_cmd, ],
1016 my ($it) = list_and_choose({ PROMPT => 'What now',
1019 HEADER => '*** Commands ***',
1020 ON_EOF => \&quit_cmd,
1021 IMMEDIATE => 1 }, @cmd);