6 my $repo = Git
->repository();
8 my $menu_use_color = $repo->get_colorbool('color.interactive');
9 my ($prompt_color, $header_color, $help_color) =
11 $repo->get_color('color.interactive.prompt', 'bold blue'),
12 $repo->get_color('color.interactive.header', 'bold'),
13 $repo->get_color('color.interactive.help', 'red bold'),
16 my $diff_use_color = $repo->get_colorbool('color.diff');
17 my ($fraginfo_color) =
19 $repo->get_color('color.diff.frag', 'cyan'),
22 my $normal_color = $repo->get_color("", "reset");
26 my $string = join("", @_);
29 # Put a color code at the beginning of each line, a reset at the end
30 # color after newlines that are not at the end of the string
31 $string =~ s/(\n+)(.)/$1$color$2/g;
32 # reset before newlines
33 $string =~ s/(\n+)/$normal_color$1/g;
34 # codes at beginning and end (if necessary):
35 $string =~ s/^/$color/;
36 $string =~ s/$/$normal_color/ unless $string =~ /\n$/;
41 # command line options
45 if ($^O
eq 'MSWin32') {
46 my @invalid = grep {m/[":*]/} @_;
47 die "$^O does not support: @invalid\n" if @invalid;
48 my @args = map { m/ /o ?
"\"$_\"": $_ } @_;
52 open($fh, '-|', @_) or die;
57 my ($GIT_DIR) = run_cmd_pipe
(qw(git rev-parse --git-dir));
59 if (!defined $GIT_DIR) {
60 exit(1); # rev-parse would have already said "not a git repo"
66 open $fh, 'git update-index --refresh |'
69 ;# ignore 'needs update'
79 run_cmd_pipe
(qw(git ls-files --others --exclude-standard --), @ARGV);
82 my $status_fmt = '%12s %12s %s';
83 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
87 sub is_initial_commit
{
88 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
89 unless defined $initial;
95 return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
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 my $reference = is_initial_commit
() ? get_empty_tree
() : 'HEAD';
120 for (run_cmd_pipe
(qw(git diff-index --cached
121 --numstat --summary), $reference,
123 if (($add, $del, $file) =
124 /^([-\d]+) ([-\d]+) (.*)/) {
126 if ($add eq '-' && $del eq '-') {
131 $change = "+$add/-$del";
139 elsif (($adddel, $file) =
140 /^ (create|delete) mode [0-7]+ (.*)$/) {
141 $data{$file}{INDEX_ADDDEL
} = $adddel;
145 for (run_cmd_pipe
(qw(git diff-files --numstat --summary --), @tracked)) {
146 if (($add, $del, $file) =
147 /^([-\d]+) ([-\d]+) (.*)/) {
148 if (!exists $data{$file}) {
150 INDEX
=> 'unchanged',
155 if ($add eq '-' && $del eq '-') {
160 $change = "+$add/-$del";
162 $data{$file}{FILE
} = $change;
164 $data{$file}{BINARY
} = 1;
167 elsif (($adddel, $file) =
168 /^ (create|delete) mode [0-7]+ (.*)$/) {
169 $data{$file}{FILE_ADDDEL
} = $adddel;
173 for (sort keys %data) {
177 if ($only eq 'index-only') {
178 next if ($it->{INDEX
} eq 'unchanged');
180 if ($only eq 'file-only') {
181 next if ($it->{FILE
} eq 'nothing');
193 my ($string, @stuff) = @_;
195 for (my $i = 0; $i < @stuff; $i++) {
199 if ((ref $it) eq 'ARRAY') {
207 if ($it =~ /^$string/) {
211 if (defined $hit && defined $found) {
221 # inserts string into trie and updates count for each character
223 my ($trie, $string) = @_;
224 foreach (split //, $string) {
225 $trie = $trie->{$_} ||= {COUNT
=> 0};
230 # returns an array of tuples (prefix, remainder)
231 sub find_unique_prefixes
{
235 # any single prefix exceeding the soft limit is omitted
236 # if any prefix exceeds the hard limit all are omitted
237 # 0 indicates no limit
241 # build a trie modelling all possible options
243 foreach my $print (@stuff) {
244 if ((ref $print) eq 'ARRAY') {
245 $print = $print->[0];
247 elsif ((ref $print) eq 'HASH') {
248 $print = $print->{VALUE
};
250 update_trie
(\
%trie, $print);
251 push @return, $print;
254 # use the trie to find the unique prefixes
255 for (my $i = 0; $i < @return; $i++) {
256 my $ret = $return[$i];
257 my @letters = split //, $ret;
259 my ($prefix, $remainder);
261 for ($j = 0; $j < @letters; $j++) {
262 my $letter = $letters[$j];
263 if ($search{$letter}{COUNT
} == 1) {
264 $prefix = substr $ret, 0, $j + 1;
265 $remainder = substr $ret, $j + 1;
269 my $prefix = substr $ret, 0, $j;
271 if ($hard_limit && $j + 1 > $hard_limit);
273 %search = %{$search{$letter}};
275 if ($soft_limit && $j + 1 > $soft_limit) {
279 $return[$i] = [$prefix, $remainder];
284 # filters out prefixes which have special meaning to list_and_choose()
285 sub is_valid_prefix
{
287 return (defined $prefix) &&
288 !($prefix =~ /[\s,]/) && # separators
289 !($prefix =~ /^-/) && # deselection
290 !($prefix =~ /^\d+/) && # selection
291 ($prefix ne '*') && # "all" wildcard
292 ($prefix ne '?'); # prompt help
295 # given a prefix/remainder tuple return a string with the prefix highlighted
296 # for now use square brackets; later might use ANSI colors (underline, bold)
297 sub highlight_prefix
{
299 my $remainder = shift;
301 if (!defined $prefix) {
305 if (!is_valid_prefix
($prefix)) {
306 return "$prefix$remainder";
309 if (!$menu_use_color) {
310 return "[$prefix]$remainder";
313 return "$prompt_color$prefix$normal_color$remainder";
316 sub list_and_choose
{
317 my ($opts, @stuff) = @_;
318 my (@chosen, @return);
320 my @prefixes = find_unique_prefixes
(@stuff) unless $opts->{LIST_ONLY
};
326 if ($opts->{HEADER
}) {
327 if (!$opts->{LIST_FLAT
}) {
330 print colored
$header_color, "$opts->{HEADER}\n";
332 for ($i = 0; $i < @stuff; $i++) {
333 my $chosen = $chosen[$i] ?
'*' : ' ';
334 my $print = $stuff[$i];
335 my $ref = ref $print;
336 my $highlighted = highlight_prefix
(@
{$prefixes[$i]})
338 if ($ref eq 'ARRAY') {
339 $print = $highlighted || $print->[0];
341 elsif ($ref eq 'HASH') {
342 my $value = $highlighted || $print->{VALUE
};
343 $print = sprintf($status_fmt,
349 $print = $highlighted || $print;
351 printf("%s%2d: %s", $chosen, $i+1, $print);
352 if (($opts->{LIST_FLAT
}) &&
353 (($i + 1) % ($opts->{LIST_FLAT
}))) {
366 return if ($opts->{LIST_ONLY
});
368 print colored
$prompt_color, $opts->{PROMPT
};
369 if ($opts->{SINGLETON
}) {
378 $opts->{ON_EOF
}->() if $opts->{ON_EOF
};
385 singleton_prompt_help_cmd
() :
389 for my $choice (split(/[\s,]+/, $line)) {
393 # Input that begins with '-'; unchoose
394 if ($choice =~ s/^-//) {
397 # A range can be specified like 5-7
398 if ($choice =~ /^(\d+)-(\d+)$/) {
399 ($bottom, $top) = ($1, $2);
401 elsif ($choice =~ /^\d+$/) {
402 $bottom = $top = $choice;
404 elsif ($choice eq '*') {
409 $bottom = $top = find_unique
($choice, @stuff);
410 if (!defined $bottom) {
411 print "Huh ($choice)?\n";
415 if ($opts->{SINGLETON
} && $bottom != $top) {
416 print "Huh ($choice)?\n";
419 for ($i = $bottom-1; $i <= $top-1; $i++) {
420 next if (@stuff <= $i || $i < 0);
421 $chosen[$i] = $choose;
424 last if ($opts->{IMMEDIATE
} || $line eq '*');
426 for ($i = 0; $i < @stuff; $i++) {
428 push @return, $stuff[$i];
434 sub singleton_prompt_help_cmd
{
435 print colored
$help_color, <<\EOF
;
437 1 - select a numbered item
438 foo
- select item based on unique prefix
439 - (empty
) select nothing
443 sub prompt_help_cmd
{
444 print colored
$help_color, <<\EOF
;
446 1 - select a single item
447 3-5 - select a range of items
448 2-3,6-9 - select multiple ranges
449 foo
- select item based on unique prefix
450 -... - unselect specified items
452 - (empty
) finish selecting
457 list_and_choose
({ LIST_ONLY
=> 1, HEADER
=> $status_head },
467 print "$cnt paths\n";
475 my @mods = list_modified
('file-only');
478 my @update = list_and_choose
({ PROMPT
=> 'Update',
479 HEADER
=> $status_head, },
482 system(qw(git update-index --add --remove --),
483 map { $_->{VALUE
} } @update);
484 say_n_paths
('updated', @update);
490 my @update = list_and_choose
({ PROMPT
=> 'Revert',
491 HEADER
=> $status_head, },
494 if (is_initial_commit
()) {
495 system(qw(git rm --cached),
496 map { $_->{VALUE
} } @update);
499 my @lines = run_cmd_pipe
(qw(git ls-tree HEAD --),
500 map { $_->{VALUE
} } @update);
502 open $fh, '| git update-index --index-info'
509 if ($_->{INDEX_ADDDEL
} &&
510 $_->{INDEX_ADDDEL
} eq 'create') {
511 system(qw(git update-index --force-remove --),
513 print "note: $_->{VALUE} is untracked now.\n";
518 say_n_paths
('reverted', @update);
523 sub add_untracked_cmd
{
524 my @add = list_and_choose
({ PROMPT
=> 'Add untracked' },
527 system(qw(git update-index --add --), @add);
528 say_n_paths
('added', @add);
535 my @diff = run_cmd_pipe
(qw(git diff-files -p --), $path);
537 if ($diff_use_color) {
538 @colored = run_cmd_pipe
(qw(git diff-files -p --color --), $path);
540 my (@hunk) = { TEXT
=> [], DISPLAY
=> [] };
542 for (my $i = 0; $i < @diff; $i++) {
543 if ($diff[$i] =~ /^@@ /) {
544 push @hunk, { TEXT
=> [], DISPLAY
=> [] };
546 push @
{$hunk[-1]{TEXT
}}, $diff[$i];
547 push @
{$hunk[-1]{DISPLAY
}},
548 ($diff_use_color ?
$colored[$i] : $diff[$i]);
553 sub parse_diff_header
{
556 my $head = { TEXT
=> [], DISPLAY
=> [] };
557 my $mode = { TEXT
=> [], DISPLAY
=> [] };
559 for (my $i = 0; $i < @
{$src->{TEXT
}}; $i++) {
560 my $dest = $src->{TEXT
}->[$i] =~ /^(old|new) mode (\d+)$/ ?
562 push @
{$dest->{TEXT
}}, $src->{TEXT
}->[$i];
563 push @
{$dest->{DISPLAY
}}, $src->{DISPLAY
}->[$i];
565 return ($head, $mode);
568 sub hunk_splittable
{
571 my @s = split_hunk
($text);
575 sub parse_hunk_header
{
577 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
578 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
579 $o_cnt = 1 unless defined $o_cnt;
580 $n_cnt = 1 unless defined $n_cnt;
581 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
585 my ($text, $display) = @_;
587 if (!defined $display) {
590 # If there are context lines in the middle of a hunk,
591 # it can be split, but we would need to take care of
594 my ($o_ofs, undef, $n_ofs) = parse_hunk_header
($text->[0]);
599 my $next_hunk_start = undef;
600 my $i = $hunk_start - 1;
613 while (++$i < @
$text) {
614 my $line = $text->[$i];
615 my $display = $display->[$i];
617 if ($this->{ADDDEL
} &&
618 !defined $next_hunk_start) {
619 # We have seen leading context and
620 # adds/dels and then here is another
621 # context, which is trailing for this
622 # split hunk and leading for the next
624 $next_hunk_start = $i;
626 push @
{$this->{TEXT
}}, $line;
627 push @
{$this->{DISPLAY
}}, $display;
630 if (defined $next_hunk_start) {
637 if (defined $next_hunk_start) {
638 # We are done with the current hunk and
639 # this is the first real change for the
641 $hunk_start = $next_hunk_start;
642 $o_ofs = $this->{OLD
} + $this->{OCNT
};
643 $n_ofs = $this->{NEW
} + $this->{NCNT
};
644 $o_ofs -= $this->{POSTCTX
};
645 $n_ofs -= $this->{POSTCTX
};
649 push @
{$this->{TEXT
}}, $line;
650 push @
{$this->{DISPLAY
}}, $display;
664 for my $hunk (@split) {
665 $o_ofs = $hunk->{OLD
};
666 $n_ofs = $hunk->{NEW
};
667 my $o_cnt = $hunk->{OCNT
};
668 my $n_cnt = $hunk->{NCNT
};
670 my $head = ("@@ -$o_ofs" .
671 (($o_cnt != 1) ?
",$o_cnt" : '') .
673 (($n_cnt != 1) ?
",$n_cnt" : '') .
675 my $display_head = $head;
676 unshift @
{$hunk->{TEXT
}}, $head;
677 if ($diff_use_color) {
678 $display_head = colored
($fraginfo_color, $head);
680 unshift @
{$hunk->{DISPLAY
}}, $display_head;
685 sub find_last_o_ctx
{
687 my $text = $it->{TEXT
};
688 my ($o_ofs, $o_cnt) = parse_hunk_header
($text->[0]);
690 my $last_o_ctx = $o_ofs + $o_cnt;
692 my $line = $text->[$i];
703 my ($prev, $this) = @_;
704 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
705 parse_hunk_header
($prev->{TEXT
}[0]);
706 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
707 parse_hunk_header
($this->{TEXT
}[0]);
709 my (@line, $i, $ofs, $o_cnt, $n_cnt);
712 for ($i = 1; $i < @
{$prev->{TEXT
}}; $i++) {
713 my $line = $prev->{TEXT
}[$i];
714 if ($line =~ /^\+/) {
720 last if ($o1_ofs <= $ofs);
730 for ($i = 1; $i < @
{$this->{TEXT
}}; $i++) {
731 my $line = $this->{TEXT
}[$i];
732 if ($line =~ /^\+/) {
744 my $head = ("@@ -$o0_ofs" .
745 (($o_cnt != 1) ?
",$o_cnt" : '') .
747 (($n_cnt != 1) ?
",$n_cnt" : '') .
749 @
{$prev->{TEXT
}} = ($head, @line);
752 sub coalesce_overlapping_hunks
{
758 for (grep { $_->{USE
} } @in) {
759 my $text = $_->{TEXT
};
760 my ($o_ofs) = parse_hunk_header
($text->[0]);
761 if (defined $last_o_ctx &&
762 $o_ofs <= $last_o_ctx) {
763 merge_hunk
($out[-1], $_);
768 $last_o_ctx = find_last_o_ctx
($out[-1]);
774 print colored
$help_color, <<\EOF
;
776 n
- do not stage this hunk
777 a
- stage this
and all the remaining hunks
in the file
778 d
- do not stage this hunk nor any of the remaining hunks
in the file
779 j
- leave this hunk undecided
, see
next undecided hunk
780 J
- leave this hunk undecided
, see
next hunk
781 k
- leave this hunk undecided
, see previous undecided hunk
782 K
- leave this hunk undecided
, see previous hunk
783 s
- split the current hunk into smaller hunks
788 sub patch_update_cmd
{
789 my @mods = grep { !($_->{BINARY
}) } list_modified
('file-only');
793 print STDERR
"No changes.\n";
800 @them = list_and_choose
({ PROMPT
=> 'Patch update',
801 HEADER
=> $status_head, },
805 patch_update_file
($_->{VALUE
});
809 sub patch_update_file
{
812 my ($head, @hunk) = parse_diff
($path);
813 ($head, my $mode) = parse_diff_header
($head);
814 for (@
{$head->{DISPLAY
}}) {
821 my ($prev, $next, $other, $undecided, $i);
827 for ($i = 0; $i < $ix; $i++) {
828 if (!defined $hunk[$i]{USE
}) {
837 for ($i = $ix + 1; $i < $num; $i++) {
838 if (!defined $hunk[$i]{USE
}) {
844 if ($ix < $num - 1) {
847 for ($i = 0; $i < $num; $i++) {
848 if (!defined $hunk[$i]{USE
}) {
853 last if (!$undecided);
855 if (hunk_splittable
($hunk[$ix]{TEXT
})) {
858 for (@
{$hunk[$ix]{DISPLAY
}}) {
861 print colored
$prompt_color, "Stage this hunk [y/n/a/d$other/?]? ";
864 if ($line =~ /^y/i) {
867 elsif ($line =~ /^n/i) {
870 elsif ($line =~ /^a/i) {
872 if (!defined $hunk[$ix]{USE
}) {
879 elsif ($line =~ /^d/i) {
881 if (!defined $hunk[$ix]{USE
}) {
888 elsif ($other =~ /K/ && $line =~ /^K/) {
892 elsif ($other =~ /J/ && $line =~ /^J/) {
896 elsif ($other =~ /k/ && $line =~ /^k/) {
900 !defined $hunk[$ix]{USE
});
904 elsif ($other =~ /j/ && $line =~ /^j/) {
907 last if ($ix >= $num ||
908 !defined $hunk[$ix]{USE
});
912 elsif ($other =~ /s/ && $line =~ /^s/) {
913 my @split = split_hunk
($hunk[$ix]{TEXT
}, $hunk[$ix]{DISPLAY
});
915 print colored
$header_color, "Split into ",
916 scalar(@split), " hunks.\n";
918 splice (@hunk, $ix, 1, @split);
923 help_patch_cmd
($other);
929 last if ($ix >= $num ||
930 !defined $hunk[$ix]{USE
});
935 @hunk = coalesce_overlapping_hunks
(@hunk);
940 my $text = $_->{TEXT
};
941 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
942 parse_hunk_header
($text->[0]);
945 # We would have added ($n_cnt - $o_cnt) lines
946 # to the postimage if we were to use this hunk,
947 # but we didn't. So the line number that the next
948 # hunk starts at would be shifted by that much.
949 $n_lofs -= ($n_cnt - $o_cnt);
955 $text->[0] = ("@@ -$o_ofs" .
972 open $fh, '| git apply --cached';
973 for (@
{$head->{TEXT
}}, @result) {
977 for (@
{$head->{TEXT
}}, @result) {
988 my @mods = list_modified
('index-only');
989 @mods = grep { !($_->{BINARY
}) } @mods;
991 my (@them) = list_and_choose
({ PROMPT
=> 'Review diff',
993 HEADER
=> $status_head, },
996 my $reference = is_initial_commit
() ? get_empty_tree
() : 'HEAD';
997 system(qw(git diff -p --cached), $reference, '--',
998 map { $_->{VALUE
} } @them);
1007 print colored
$help_color, <<\EOF
;
1008 status
- show paths with changes
1009 update
- add working tree
state to the staged set of changes
1010 revert
- revert staged set of changes back to the HEAD version
1011 patch
- pick hunks
and update selectively
1012 diff
- view diff between HEAD
and index
1013 add untracked
- add contents of untracked files to the staged set of changes
1018 return unless @ARGV;
1019 my $arg = shift @ARGV;
1020 if ($arg eq "--patch") {
1022 $arg = shift @ARGV or die "missing --";
1023 die "invalid argument $arg, expecting --"
1024 unless $arg eq "--";
1026 elsif ($arg ne "--") {
1027 die "invalid argument $arg, expecting --";
1032 my @cmd = ([ 'status', \
&status_cmd
, ],
1033 [ 'update', \
&update_cmd
, ],
1034 [ 'revert', \
&revert_cmd
, ],
1035 [ 'add untracked', \
&add_untracked_cmd
, ],
1036 [ 'patch', \
&patch_update_cmd
, ],
1037 [ 'diff', \
&diff_cmd
, ],
1038 [ 'quit', \
&quit_cmd
, ],
1039 [ 'help', \
&help_cmd
, ],
1042 my ($it) = list_and_choose
({ PROMPT
=> 'What now',
1045 HEADER
=> '*** Commands ***',
1046 ON_EOF
=> \
&quit_cmd
,
1047 IMMEDIATE
=> 1 }, @cmd);