Avoid declaration after statement
[git/jnareb-git/bp-gitweb.git] / git-add--interactive.perl
blob392efb913f7c2ff13bbbb46e4414325b71e07676
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;
75 my $patch_mode_revision;
77 sub apply_patch;
78 sub apply_patch_for_checkout_commit;
79 sub apply_patch_for_stash;
81 my %patch_modes = (
82 'stage' => {
83 DIFF => 'diff-files -p',
84 APPLY => sub { apply_patch 'apply --cached', @_; },
85 APPLY_CHECK => 'apply --cached',
86 VERB => 'Stage',
87 TARGET => '',
88 PARTICIPLE => 'staging',
89 FILTER => 'file-only',
91 'stash' => {
92 DIFF => 'diff-index -p HEAD',
93 APPLY => sub { apply_patch 'apply --cached', @_; },
94 APPLY_CHECK => 'apply --cached',
95 VERB => 'Stash',
96 TARGET => '',
97 PARTICIPLE => 'stashing',
98 FILTER => undef,
100 'reset_head' => {
101 DIFF => 'diff-index -p --cached',
102 APPLY => sub { apply_patch 'apply -R --cached', @_; },
103 APPLY_CHECK => 'apply -R --cached',
104 VERB => 'Unstage',
105 TARGET => '',
106 PARTICIPLE => 'unstaging',
107 FILTER => 'index-only',
109 'reset_nothead' => {
110 DIFF => 'diff-index -R -p --cached',
111 APPLY => sub { apply_patch 'apply --cached', @_; },
112 APPLY_CHECK => 'apply --cached',
113 VERB => 'Apply',
114 TARGET => ' to index',
115 PARTICIPLE => 'applying',
116 FILTER => 'index-only',
118 'checkout_index' => {
119 DIFF => 'diff-files -p',
120 APPLY => sub { apply_patch 'apply -R', @_; },
121 APPLY_CHECK => 'apply -R',
122 VERB => 'Discard',
123 TARGET => ' from worktree',
124 PARTICIPLE => 'discarding',
125 FILTER => 'file-only',
127 'checkout_head' => {
128 DIFF => 'diff-index -p',
129 APPLY => sub { apply_patch_for_checkout_commit '-R', @_ },
130 APPLY_CHECK => 'apply -R',
131 VERB => 'Discard',
132 TARGET => ' from index and worktree',
133 PARTICIPLE => 'discarding',
134 FILTER => undef,
136 'checkout_nothead' => {
137 DIFF => 'diff-index -R -p',
138 APPLY => sub { apply_patch_for_checkout_commit '', @_ },
139 APPLY_CHECK => 'apply',
140 VERB => 'Apply',
141 TARGET => ' to index and worktree',
142 PARTICIPLE => 'applying',
143 FILTER => undef,
147 my %patch_mode_flavour = %{$patch_modes{stage}};
149 sub run_cmd_pipe {
150 if ($^O eq 'MSWin32' || $^O eq 'msys') {
151 my @invalid = grep {m/[":*]/} @_;
152 die "$^O does not support: @invalid\n" if @invalid;
153 my @args = map { m/ /o ? "\"$_\"": $_ } @_;
154 return qx{@args};
155 } else {
156 my $fh = undef;
157 open($fh, '-|', @_) or die;
158 return <$fh>;
162 my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));
164 if (!defined $GIT_DIR) {
165 exit(1); # rev-parse would have already said "not a git repo"
167 chomp($GIT_DIR);
169 my %cquote_map = (
170 "b" => chr(8),
171 "t" => chr(9),
172 "n" => chr(10),
173 "v" => chr(11),
174 "f" => chr(12),
175 "r" => chr(13),
176 "\\" => "\\",
177 "\042" => "\042",
180 sub unquote_path {
181 local ($_) = @_;
182 my ($retval, $remainder);
183 if (!/^\042(.*)\042$/) {
184 return $_;
186 ($_, $retval) = ($1, "");
187 while (/^([^\\]*)\\(.*)$/) {
188 $remainder = $2;
189 $retval .= $1;
190 for ($remainder) {
191 if (/^([0-3][0-7][0-7])(.*)$/) {
192 $retval .= chr(oct($1));
193 $_ = $2;
194 last;
196 if (/^([\\\042btnvfr])(.*)$/) {
197 $retval .= $cquote_map{$1};
198 $_ = $2;
199 last;
201 # This is malformed -- just return it as-is for now.
202 return $_[0];
204 $_ = $remainder;
206 $retval .= $_;
207 return $retval;
210 sub refresh {
211 my $fh;
212 open $fh, 'git update-index --refresh |'
213 or die;
214 while (<$fh>) {
215 ;# ignore 'needs update'
217 close $fh;
220 sub list_untracked {
221 map {
222 chomp $_;
223 unquote_path($_);
225 run_cmd_pipe(qw(git ls-files --others --exclude-standard --), @ARGV);
228 my $status_fmt = '%12s %12s %s';
229 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
232 my $initial;
233 sub is_initial_commit {
234 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
235 unless defined $initial;
236 return $initial;
240 sub get_empty_tree {
241 return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
244 # Returns list of hashes, contents of each of which are:
245 # VALUE: pathname
246 # BINARY: is a binary path
247 # INDEX: is index different from HEAD?
248 # FILE: is file different from index?
249 # INDEX_ADDDEL: is it add/delete between HEAD and index?
250 # FILE_ADDDEL: is it add/delete between index and file?
252 sub list_modified {
253 my ($only) = @_;
254 my (%data, @return);
255 my ($add, $del, $adddel, $file);
256 my @tracked = ();
258 if (@ARGV) {
259 @tracked = map {
260 chomp $_;
261 unquote_path($_);
262 } run_cmd_pipe(qw(git ls-files --exclude-standard --), @ARGV);
263 return if (!@tracked);
266 my $reference;
267 if (defined $patch_mode_revision and $patch_mode_revision ne 'HEAD') {
268 $reference = $patch_mode_revision;
269 } elsif (is_initial_commit()) {
270 $reference = get_empty_tree();
271 } else {
272 $reference = 'HEAD';
274 for (run_cmd_pipe(qw(git diff-index --cached
275 --numstat --summary), $reference,
276 '--', @tracked)) {
277 if (($add, $del, $file) =
278 /^([-\d]+) ([-\d]+) (.*)/) {
279 my ($change, $bin);
280 $file = unquote_path($file);
281 if ($add eq '-' && $del eq '-') {
282 $change = 'binary';
283 $bin = 1;
285 else {
286 $change = "+$add/-$del";
288 $data{$file} = {
289 INDEX => $change,
290 BINARY => $bin,
291 FILE => 'nothing',
294 elsif (($adddel, $file) =
295 /^ (create|delete) mode [0-7]+ (.*)$/) {
296 $file = unquote_path($file);
297 $data{$file}{INDEX_ADDDEL} = $adddel;
301 for (run_cmd_pipe(qw(git diff-files --numstat --summary --), @tracked)) {
302 if (($add, $del, $file) =
303 /^([-\d]+) ([-\d]+) (.*)/) {
304 $file = unquote_path($file);
305 if (!exists $data{$file}) {
306 $data{$file} = +{
307 INDEX => 'unchanged',
308 BINARY => 0,
311 my ($change, $bin);
312 if ($add eq '-' && $del eq '-') {
313 $change = 'binary';
314 $bin = 1;
316 else {
317 $change = "+$add/-$del";
319 $data{$file}{FILE} = $change;
320 if ($bin) {
321 $data{$file}{BINARY} = 1;
324 elsif (($adddel, $file) =
325 /^ (create|delete) mode [0-7]+ (.*)$/) {
326 $file = unquote_path($file);
327 $data{$file}{FILE_ADDDEL} = $adddel;
331 for (sort keys %data) {
332 my $it = $data{$_};
334 if ($only) {
335 if ($only eq 'index-only') {
336 next if ($it->{INDEX} eq 'unchanged');
338 if ($only eq 'file-only') {
339 next if ($it->{FILE} eq 'nothing');
342 push @return, +{
343 VALUE => $_,
344 %$it,
347 return @return;
350 sub find_unique {
351 my ($string, @stuff) = @_;
352 my $found = undef;
353 for (my $i = 0; $i < @stuff; $i++) {
354 my $it = $stuff[$i];
355 my $hit = undef;
356 if (ref $it) {
357 if ((ref $it) eq 'ARRAY') {
358 $it = $it->[0];
360 else {
361 $it = $it->{VALUE};
364 eval {
365 if ($it =~ /^$string/) {
366 $hit = 1;
369 if (defined $hit && defined $found) {
370 return undef;
372 if ($hit) {
373 $found = $i + 1;
376 return $found;
379 # inserts string into trie and updates count for each character
380 sub update_trie {
381 my ($trie, $string) = @_;
382 foreach (split //, $string) {
383 $trie = $trie->{$_} ||= {COUNT => 0};
384 $trie->{COUNT}++;
388 # returns an array of tuples (prefix, remainder)
389 sub find_unique_prefixes {
390 my @stuff = @_;
391 my @return = ();
393 # any single prefix exceeding the soft limit is omitted
394 # if any prefix exceeds the hard limit all are omitted
395 # 0 indicates no limit
396 my $soft_limit = 0;
397 my $hard_limit = 3;
399 # build a trie modelling all possible options
400 my %trie;
401 foreach my $print (@stuff) {
402 if ((ref $print) eq 'ARRAY') {
403 $print = $print->[0];
405 elsif ((ref $print) eq 'HASH') {
406 $print = $print->{VALUE};
408 update_trie(\%trie, $print);
409 push @return, $print;
412 # use the trie to find the unique prefixes
413 for (my $i = 0; $i < @return; $i++) {
414 my $ret = $return[$i];
415 my @letters = split //, $ret;
416 my %search = %trie;
417 my ($prefix, $remainder);
418 my $j;
419 for ($j = 0; $j < @letters; $j++) {
420 my $letter = $letters[$j];
421 if ($search{$letter}{COUNT} == 1) {
422 $prefix = substr $ret, 0, $j + 1;
423 $remainder = substr $ret, $j + 1;
424 last;
426 else {
427 my $prefix = substr $ret, 0, $j;
428 return ()
429 if ($hard_limit && $j + 1 > $hard_limit);
431 %search = %{$search{$letter}};
433 if (ord($letters[0]) > 127 ||
434 ($soft_limit && $j + 1 > $soft_limit)) {
435 $prefix = undef;
436 $remainder = $ret;
438 $return[$i] = [$prefix, $remainder];
440 return @return;
443 # filters out prefixes which have special meaning to list_and_choose()
444 sub is_valid_prefix {
445 my $prefix = shift;
446 return (defined $prefix) &&
447 !($prefix =~ /[\s,]/) && # separators
448 !($prefix =~ /^-/) && # deselection
449 !($prefix =~ /^\d+/) && # selection
450 ($prefix ne '*') && # "all" wildcard
451 ($prefix ne '?'); # prompt help
454 # given a prefix/remainder tuple return a string with the prefix highlighted
455 # for now use square brackets; later might use ANSI colors (underline, bold)
456 sub highlight_prefix {
457 my $prefix = shift;
458 my $remainder = shift;
460 if (!defined $prefix) {
461 return $remainder;
464 if (!is_valid_prefix($prefix)) {
465 return "$prefix$remainder";
468 if (!$menu_use_color) {
469 return "[$prefix]$remainder";
472 return "$prompt_color$prefix$normal_color$remainder";
475 sub error_msg {
476 print STDERR colored $error_color, @_;
479 sub list_and_choose {
480 my ($opts, @stuff) = @_;
481 my (@chosen, @return);
482 my $i;
483 my @prefixes = find_unique_prefixes(@stuff) unless $opts->{LIST_ONLY};
485 TOPLOOP:
486 while (1) {
487 my $last_lf = 0;
489 if ($opts->{HEADER}) {
490 if (!$opts->{LIST_FLAT}) {
491 print " ";
493 print colored $header_color, "$opts->{HEADER}\n";
495 for ($i = 0; $i < @stuff; $i++) {
496 my $chosen = $chosen[$i] ? '*' : ' ';
497 my $print = $stuff[$i];
498 my $ref = ref $print;
499 my $highlighted = highlight_prefix(@{$prefixes[$i]})
500 if @prefixes;
501 if ($ref eq 'ARRAY') {
502 $print = $highlighted || $print->[0];
504 elsif ($ref eq 'HASH') {
505 my $value = $highlighted || $print->{VALUE};
506 $print = sprintf($status_fmt,
507 $print->{INDEX},
508 $print->{FILE},
509 $value);
511 else {
512 $print = $highlighted || $print;
514 printf("%s%2d: %s", $chosen, $i+1, $print);
515 if (($opts->{LIST_FLAT}) &&
516 (($i + 1) % ($opts->{LIST_FLAT}))) {
517 print "\t";
518 $last_lf = 0;
520 else {
521 print "\n";
522 $last_lf = 1;
525 if (!$last_lf) {
526 print "\n";
529 return if ($opts->{LIST_ONLY});
531 print colored $prompt_color, $opts->{PROMPT};
532 if ($opts->{SINGLETON}) {
533 print "> ";
535 else {
536 print ">> ";
538 my $line = <STDIN>;
539 if (!$line) {
540 print "\n";
541 $opts->{ON_EOF}->() if $opts->{ON_EOF};
542 last;
544 chomp $line;
545 last if $line eq '';
546 if ($line eq '?') {
547 $opts->{SINGLETON} ?
548 singleton_prompt_help_cmd() :
549 prompt_help_cmd();
550 next TOPLOOP;
552 for my $choice (split(/[\s,]+/, $line)) {
553 my $choose = 1;
554 my ($bottom, $top);
556 # Input that begins with '-'; unchoose
557 if ($choice =~ s/^-//) {
558 $choose = 0;
560 # A range can be specified like 5-7 or 5-.
561 if ($choice =~ /^(\d+)-(\d*)$/) {
562 ($bottom, $top) = ($1, length($2) ? $2 : 1 + @stuff);
564 elsif ($choice =~ /^\d+$/) {
565 $bottom = $top = $choice;
567 elsif ($choice eq '*') {
568 $bottom = 1;
569 $top = 1 + @stuff;
571 else {
572 $bottom = $top = find_unique($choice, @stuff);
573 if (!defined $bottom) {
574 error_msg "Huh ($choice)?\n";
575 next TOPLOOP;
578 if ($opts->{SINGLETON} && $bottom != $top) {
579 error_msg "Huh ($choice)?\n";
580 next TOPLOOP;
582 for ($i = $bottom-1; $i <= $top-1; $i++) {
583 next if (@stuff <= $i || $i < 0);
584 $chosen[$i] = $choose;
587 last if ($opts->{IMMEDIATE} || $line eq '*');
589 for ($i = 0; $i < @stuff; $i++) {
590 if ($chosen[$i]) {
591 push @return, $stuff[$i];
594 return @return;
597 sub singleton_prompt_help_cmd {
598 print colored $help_color, <<\EOF ;
599 Prompt help:
600 1 - select a numbered item
601 foo - select item based on unique prefix
602 - (empty) select nothing
606 sub prompt_help_cmd {
607 print colored $help_color, <<\EOF ;
608 Prompt help:
609 1 - select a single item
610 3-5 - select a range of items
611 2-3,6-9 - select multiple ranges
612 foo - select item based on unique prefix
613 -... - unselect specified items
614 * - choose all items
615 - (empty) finish selecting
619 sub status_cmd {
620 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
621 list_modified());
622 print "\n";
625 sub say_n_paths {
626 my $did = shift @_;
627 my $cnt = scalar @_;
628 print "$did ";
629 if (1 < $cnt) {
630 print "$cnt paths\n";
632 else {
633 print "one path\n";
637 sub update_cmd {
638 my @mods = list_modified('file-only');
639 return if (!@mods);
641 my @update = list_and_choose({ PROMPT => 'Update',
642 HEADER => $status_head, },
643 @mods);
644 if (@update) {
645 system(qw(git update-index --add --remove --),
646 map { $_->{VALUE} } @update);
647 say_n_paths('updated', @update);
649 print "\n";
652 sub revert_cmd {
653 my @update = list_and_choose({ PROMPT => 'Revert',
654 HEADER => $status_head, },
655 list_modified());
656 if (@update) {
657 if (is_initial_commit()) {
658 system(qw(git rm --cached),
659 map { $_->{VALUE} } @update);
661 else {
662 my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
663 map { $_->{VALUE} } @update);
664 my $fh;
665 open $fh, '| git update-index --index-info'
666 or die;
667 for (@lines) {
668 print $fh $_;
670 close($fh);
671 for (@update) {
672 if ($_->{INDEX_ADDDEL} &&
673 $_->{INDEX_ADDDEL} eq 'create') {
674 system(qw(git update-index --force-remove --),
675 $_->{VALUE});
676 print "note: $_->{VALUE} is untracked now.\n";
680 refresh();
681 say_n_paths('reverted', @update);
683 print "\n";
686 sub add_untracked_cmd {
687 my @add = list_and_choose({ PROMPT => 'Add untracked' },
688 list_untracked());
689 if (@add) {
690 system(qw(git update-index --add --), @add);
691 say_n_paths('added', @add);
693 print "\n";
696 sub run_git_apply {
697 my $cmd = shift;
698 my $fh;
699 open $fh, '| git ' . $cmd;
700 print $fh @_;
701 return close $fh;
704 sub parse_diff {
705 my ($path) = @_;
706 my @diff_cmd = split(" ", $patch_mode_flavour{DIFF});
707 if (defined $patch_mode_revision) {
708 push @diff_cmd, $patch_mode_revision;
710 my @diff = run_cmd_pipe("git", @diff_cmd, "--", $path);
711 my @colored = ();
712 if ($diff_use_color) {
713 @colored = run_cmd_pipe("git", @diff_cmd, qw(--color --), $path);
715 my (@hunk) = { TEXT => [], DISPLAY => [], TYPE => 'header' };
717 for (my $i = 0; $i < @diff; $i++) {
718 if ($diff[$i] =~ /^@@ /) {
719 push @hunk, { TEXT => [], DISPLAY => [],
720 TYPE => 'hunk' };
722 push @{$hunk[-1]{TEXT}}, $diff[$i];
723 push @{$hunk[-1]{DISPLAY}},
724 ($diff_use_color ? $colored[$i] : $diff[$i]);
726 return @hunk;
729 sub parse_diff_header {
730 my $src = shift;
732 my $head = { TEXT => [], DISPLAY => [], TYPE => 'header' };
733 my $mode = { TEXT => [], DISPLAY => [], TYPE => 'mode' };
735 for (my $i = 0; $i < @{$src->{TEXT}}; $i++) {
736 my $dest = $src->{TEXT}->[$i] =~ /^(old|new) mode (\d+)$/ ?
737 $mode : $head;
738 push @{$dest->{TEXT}}, $src->{TEXT}->[$i];
739 push @{$dest->{DISPLAY}}, $src->{DISPLAY}->[$i];
741 return ($head, $mode);
744 sub hunk_splittable {
745 my ($text) = @_;
747 my @s = split_hunk($text);
748 return (1 < @s);
751 sub parse_hunk_header {
752 my ($line) = @_;
753 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
754 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
755 $o_cnt = 1 unless defined $o_cnt;
756 $n_cnt = 1 unless defined $n_cnt;
757 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
760 sub split_hunk {
761 my ($text, $display) = @_;
762 my @split = ();
763 if (!defined $display) {
764 $display = $text;
766 # If there are context lines in the middle of a hunk,
767 # it can be split, but we would need to take care of
768 # overlaps later.
770 my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
771 my $hunk_start = 1;
773 OUTER:
774 while (1) {
775 my $next_hunk_start = undef;
776 my $i = $hunk_start - 1;
777 my $this = +{
778 TEXT => [],
779 DISPLAY => [],
780 TYPE => 'hunk',
781 OLD => $o_ofs,
782 NEW => $n_ofs,
783 OCNT => 0,
784 NCNT => 0,
785 ADDDEL => 0,
786 POSTCTX => 0,
787 USE => undef,
790 while (++$i < @$text) {
791 my $line = $text->[$i];
792 my $display = $display->[$i];
793 if ($line =~ /^ /) {
794 if ($this->{ADDDEL} &&
795 !defined $next_hunk_start) {
796 # We have seen leading context and
797 # adds/dels and then here is another
798 # context, which is trailing for this
799 # split hunk and leading for the next
800 # one.
801 $next_hunk_start = $i;
803 push @{$this->{TEXT}}, $line;
804 push @{$this->{DISPLAY}}, $display;
805 $this->{OCNT}++;
806 $this->{NCNT}++;
807 if (defined $next_hunk_start) {
808 $this->{POSTCTX}++;
810 next;
813 # add/del
814 if (defined $next_hunk_start) {
815 # We are done with the current hunk and
816 # this is the first real change for the
817 # next split one.
818 $hunk_start = $next_hunk_start;
819 $o_ofs = $this->{OLD} + $this->{OCNT};
820 $n_ofs = $this->{NEW} + $this->{NCNT};
821 $o_ofs -= $this->{POSTCTX};
822 $n_ofs -= $this->{POSTCTX};
823 push @split, $this;
824 redo OUTER;
826 push @{$this->{TEXT}}, $line;
827 push @{$this->{DISPLAY}}, $display;
828 $this->{ADDDEL}++;
829 if ($line =~ /^-/) {
830 $this->{OCNT}++;
832 else {
833 $this->{NCNT}++;
837 push @split, $this;
838 last;
841 for my $hunk (@split) {
842 $o_ofs = $hunk->{OLD};
843 $n_ofs = $hunk->{NEW};
844 my $o_cnt = $hunk->{OCNT};
845 my $n_cnt = $hunk->{NCNT};
847 my $head = ("@@ -$o_ofs" .
848 (($o_cnt != 1) ? ",$o_cnt" : '') .
849 " +$n_ofs" .
850 (($n_cnt != 1) ? ",$n_cnt" : '') .
851 " @@\n");
852 my $display_head = $head;
853 unshift @{$hunk->{TEXT}}, $head;
854 if ($diff_use_color) {
855 $display_head = colored($fraginfo_color, $head);
857 unshift @{$hunk->{DISPLAY}}, $display_head;
859 return @split;
862 sub find_last_o_ctx {
863 my ($it) = @_;
864 my $text = $it->{TEXT};
865 my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
866 my $i = @{$text};
867 my $last_o_ctx = $o_ofs + $o_cnt;
868 while (0 < --$i) {
869 my $line = $text->[$i];
870 if ($line =~ /^ /) {
871 $last_o_ctx--;
872 next;
874 last;
876 return $last_o_ctx;
879 sub merge_hunk {
880 my ($prev, $this) = @_;
881 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
882 parse_hunk_header($prev->{TEXT}[0]);
883 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
884 parse_hunk_header($this->{TEXT}[0]);
886 my (@line, $i, $ofs, $o_cnt, $n_cnt);
887 $ofs = $o0_ofs;
888 $o_cnt = $n_cnt = 0;
889 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
890 my $line = $prev->{TEXT}[$i];
891 if ($line =~ /^\+/) {
892 $n_cnt++;
893 push @line, $line;
894 next;
897 last if ($o1_ofs <= $ofs);
899 $o_cnt++;
900 $ofs++;
901 if ($line =~ /^ /) {
902 $n_cnt++;
904 push @line, $line;
907 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
908 my $line = $this->{TEXT}[$i];
909 if ($line =~ /^\+/) {
910 $n_cnt++;
911 push @line, $line;
912 next;
914 $ofs++;
915 $o_cnt++;
916 if ($line =~ /^ /) {
917 $n_cnt++;
919 push @line, $line;
921 my $head = ("@@ -$o0_ofs" .
922 (($o_cnt != 1) ? ",$o_cnt" : '') .
923 " +$n0_ofs" .
924 (($n_cnt != 1) ? ",$n_cnt" : '') .
925 " @@\n");
926 @{$prev->{TEXT}} = ($head, @line);
929 sub coalesce_overlapping_hunks {
930 my (@in) = @_;
931 my @out = ();
933 my ($last_o_ctx, $last_was_dirty);
935 for (grep { $_->{USE} } @in) {
936 if ($_->{TYPE} ne 'hunk') {
937 push @out, $_;
938 next;
940 my $text = $_->{TEXT};
941 my ($o_ofs) = parse_hunk_header($text->[0]);
942 if (defined $last_o_ctx &&
943 $o_ofs <= $last_o_ctx &&
944 !$_->{DIRTY} &&
945 !$last_was_dirty) {
946 merge_hunk($out[-1], $_);
948 else {
949 push @out, $_;
951 $last_o_ctx = find_last_o_ctx($out[-1]);
952 $last_was_dirty = $_->{DIRTY};
954 return @out;
957 sub color_diff {
958 return map {
959 colored((/^@/ ? $fraginfo_color :
960 /^\+/ ? $diff_new_color :
961 /^-/ ? $diff_old_color :
962 $diff_plain_color),
963 $_);
964 } @_;
967 sub edit_hunk_manually {
968 my ($oldtext) = @_;
970 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
971 my $fh;
972 open $fh, '>', $hunkfile
973 or die "failed to open hunk edit file for writing: " . $!;
974 print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
975 print $fh @$oldtext;
976 my $participle = $patch_mode_flavour{PARTICIPLE};
977 print $fh <<EOF;
978 # ---
979 # To remove '-' lines, make them ' ' lines (context).
980 # To remove '+' lines, delete them.
981 # Lines starting with # will be removed.
983 # If the patch applies cleanly, the edited hunk will immediately be
984 # marked for $participle. If it does not apply cleanly, you will be given
985 # an opportunity to edit again. If all lines of the hunk are removed,
986 # then the edit is aborted and the hunk is left unchanged.
988 close $fh;
990 my $editor = $ENV{GIT_EDITOR} || $repo->config("core.editor")
991 || $ENV{VISUAL} || $ENV{EDITOR} || "vi";
992 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
994 if ($? != 0) {
995 return undef;
998 open $fh, '<', $hunkfile
999 or die "failed to open hunk edit file for reading: " . $!;
1000 my @newtext = grep { !/^#/ } <$fh>;
1001 close $fh;
1002 unlink $hunkfile;
1004 # Abort if nothing remains
1005 if (!grep { /\S/ } @newtext) {
1006 return undef;
1009 # Reinsert the first hunk header if the user accidentally deleted it
1010 if ($newtext[0] !~ /^@/) {
1011 unshift @newtext, $oldtext->[0];
1013 return \@newtext;
1016 sub diff_applies {
1017 my $fh;
1018 return run_git_apply($patch_mode_flavour{APPLY_CHECK} . ' --recount --check',
1019 map { @{$_->{TEXT}} } @_);
1022 sub _restore_terminal_and_die {
1023 ReadMode 'restore';
1024 print "\n";
1025 exit 1;
1028 sub prompt_single_character {
1029 if ($use_readkey) {
1030 local $SIG{TERM} = \&_restore_terminal_and_die;
1031 local $SIG{INT} = \&_restore_terminal_and_die;
1032 ReadMode 'cbreak';
1033 my $key = ReadKey 0;
1034 ReadMode 'restore';
1035 print "$key" if defined $key;
1036 print "\n";
1037 return $key;
1038 } else {
1039 return <STDIN>;
1043 sub prompt_yesno {
1044 my ($prompt) = @_;
1045 while (1) {
1046 print colored $prompt_color, $prompt;
1047 my $line = prompt_single_character;
1048 return 0 if $line =~ /^n/i;
1049 return 1 if $line =~ /^y/i;
1053 sub edit_hunk_loop {
1054 my ($head, $hunk, $ix) = @_;
1055 my $text = $hunk->[$ix]->{TEXT};
1057 while (1) {
1058 $text = edit_hunk_manually($text);
1059 if (!defined $text) {
1060 return undef;
1062 my $newhunk = {
1063 TEXT => $text,
1064 TYPE => $hunk->[$ix]->{TYPE},
1065 USE => 1,
1066 DIRTY => 1,
1068 if (diff_applies($head,
1069 @{$hunk}[0..$ix-1],
1070 $newhunk,
1071 @{$hunk}[$ix+1..$#{$hunk}])) {
1072 $newhunk->{DISPLAY} = [color_diff(@{$text})];
1073 return $newhunk;
1075 else {
1076 prompt_yesno(
1077 'Your edited hunk does not apply. Edit again '
1078 . '(saying "no" discards!) [y/n]? '
1079 ) or return undef;
1084 sub help_patch_cmd {
1085 my $verb = lc $patch_mode_flavour{VERB};
1086 my $target = $patch_mode_flavour{TARGET};
1087 print colored $help_color, <<EOF ;
1088 y - $verb this hunk$target
1089 n - do not $verb this hunk$target
1090 q - quit, do not $verb this hunk nor any of the remaining ones
1091 a - $verb this and all the remaining hunks in the file
1092 d - do not $verb this hunk nor any of the remaining hunks in the file
1093 g - select a hunk to go to
1094 / - search for a hunk matching the given regex
1095 j - leave this hunk undecided, see next undecided hunk
1096 J - leave this hunk undecided, see next hunk
1097 k - leave this hunk undecided, see previous undecided hunk
1098 K - leave this hunk undecided, see previous hunk
1099 s - split the current hunk into smaller hunks
1100 e - manually edit the current hunk
1101 ? - print help
1105 sub apply_patch {
1106 my $cmd = shift;
1107 my $ret = run_git_apply $cmd . ' --recount', @_;
1108 if (!$ret) {
1109 print STDERR @_;
1111 return $ret;
1114 sub apply_patch_for_checkout_commit {
1115 my $reverse = shift;
1116 my $applies_index = run_git_apply 'apply '.$reverse.' --cached --recount --check', @_;
1117 my $applies_worktree = run_git_apply 'apply '.$reverse.' --recount --check', @_;
1119 if ($applies_worktree && $applies_index) {
1120 run_git_apply 'apply '.$reverse.' --cached --recount', @_;
1121 run_git_apply 'apply '.$reverse.' --recount', @_;
1122 return 1;
1123 } elsif (!$applies_index) {
1124 print colored $error_color, "The selected hunks do not apply to the index!\n";
1125 if (prompt_yesno "Apply them to the worktree anyway? ") {
1126 return run_git_apply 'apply '.$reverse.' --recount', @_;
1127 } else {
1128 print colored $error_color, "Nothing was applied.\n";
1129 return 0;
1131 } else {
1132 print STDERR @_;
1133 return 0;
1137 sub patch_update_cmd {
1138 my @all_mods = list_modified($patch_mode_flavour{FILTER});
1139 my @mods = grep { !($_->{BINARY}) } @all_mods;
1140 my @them;
1142 if (!@mods) {
1143 if (@all_mods) {
1144 print STDERR "Only binary files changed.\n";
1145 } else {
1146 print STDERR "No changes.\n";
1148 return 0;
1150 if ($patch_mode) {
1151 @them = @mods;
1153 else {
1154 @them = list_and_choose({ PROMPT => 'Patch update',
1155 HEADER => $status_head, },
1156 @mods);
1158 for (@them) {
1159 return 0 if patch_update_file($_->{VALUE});
1163 # Generate a one line summary of a hunk.
1164 sub summarize_hunk {
1165 my $rhunk = shift;
1166 my $summary = $rhunk->{TEXT}[0];
1168 # Keep the line numbers, discard extra context.
1169 $summary =~ s/@@(.*?)@@.*/$1 /s;
1170 $summary .= " " x (20 - length $summary);
1172 # Add some user context.
1173 for my $line (@{$rhunk->{TEXT}}) {
1174 if ($line =~ m/^[+-].*\w/) {
1175 $summary .= $line;
1176 last;
1180 chomp $summary;
1181 return substr($summary, 0, 80) . "\n";
1185 # Print a one-line summary of each hunk in the array ref in
1186 # the first argument, starting wih the index in the 2nd.
1187 sub display_hunks {
1188 my ($hunks, $i) = @_;
1189 my $ctr = 0;
1190 $i ||= 0;
1191 for (; $i < @$hunks && $ctr < 20; $i++, $ctr++) {
1192 my $status = " ";
1193 if (defined $hunks->[$i]{USE}) {
1194 $status = $hunks->[$i]{USE} ? "+" : "-";
1196 printf "%s%2d: %s",
1197 $status,
1198 $i + 1,
1199 summarize_hunk($hunks->[$i]);
1201 return $i;
1204 sub patch_update_file {
1205 my $quit = 0;
1206 my ($ix, $num);
1207 my $path = shift;
1208 my ($head, @hunk) = parse_diff($path);
1209 ($head, my $mode) = parse_diff_header($head);
1210 for (@{$head->{DISPLAY}}) {
1211 print;
1214 if (@{$mode->{TEXT}}) {
1215 unshift @hunk, $mode;
1218 $num = scalar @hunk;
1219 $ix = 0;
1221 while (1) {
1222 my ($prev, $next, $other, $undecided, $i);
1223 $other = '';
1225 if ($num <= $ix) {
1226 $ix = 0;
1228 for ($i = 0; $i < $ix; $i++) {
1229 if (!defined $hunk[$i]{USE}) {
1230 $prev = 1;
1231 $other .= ',k';
1232 last;
1235 if ($ix) {
1236 $other .= ',K';
1238 for ($i = $ix + 1; $i < $num; $i++) {
1239 if (!defined $hunk[$i]{USE}) {
1240 $next = 1;
1241 $other .= ',j';
1242 last;
1245 if ($ix < $num - 1) {
1246 $other .= ',J';
1248 if ($num > 1) {
1249 $other .= ',g';
1251 for ($i = 0; $i < $num; $i++) {
1252 if (!defined $hunk[$i]{USE}) {
1253 $undecided = 1;
1254 last;
1257 last if (!$undecided);
1259 if ($hunk[$ix]{TYPE} eq 'hunk' &&
1260 hunk_splittable($hunk[$ix]{TEXT})) {
1261 $other .= ',s';
1263 if ($hunk[$ix]{TYPE} eq 'hunk') {
1264 $other .= ',e';
1266 for (@{$hunk[$ix]{DISPLAY}}) {
1267 print;
1269 print colored $prompt_color, $patch_mode_flavour{VERB},
1270 ($hunk[$ix]{TYPE} eq 'mode' ? ' mode change' : ' this hunk'),
1271 $patch_mode_flavour{TARGET},
1272 " [y,n,q,a,d,/$other,?]? ";
1273 my $line = prompt_single_character;
1274 if ($line) {
1275 if ($line =~ /^y/i) {
1276 $hunk[$ix]{USE} = 1;
1278 elsif ($line =~ /^n/i) {
1279 $hunk[$ix]{USE} = 0;
1281 elsif ($line =~ /^a/i) {
1282 while ($ix < $num) {
1283 if (!defined $hunk[$ix]{USE}) {
1284 $hunk[$ix]{USE} = 1;
1286 $ix++;
1288 next;
1290 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1291 my $response = $1;
1292 my $no = $ix > 10 ? $ix - 10 : 0;
1293 while ($response eq '') {
1294 my $extra = "";
1295 $no = display_hunks(\@hunk, $no);
1296 if ($no < $num) {
1297 $extra = " (<ret> to see more)";
1299 print "go to which hunk$extra? ";
1300 $response = <STDIN>;
1301 if (!defined $response) {
1302 $response = '';
1304 chomp $response;
1306 if ($response !~ /^\s*\d+\s*$/) {
1307 error_msg "Invalid number: '$response'\n";
1308 } elsif (0 < $response && $response <= $num) {
1309 $ix = $response - 1;
1310 } else {
1311 error_msg "Sorry, only $num hunks available.\n";
1313 next;
1315 elsif ($line =~ /^d/i) {
1316 while ($ix < $num) {
1317 if (!defined $hunk[$ix]{USE}) {
1318 $hunk[$ix]{USE} = 0;
1320 $ix++;
1322 next;
1324 elsif ($line =~ /^q/i) {
1325 while ($ix < $num) {
1326 if (!defined $hunk[$ix]{USE}) {
1327 $hunk[$ix]{USE} = 0;
1329 $ix++;
1331 $quit = 1;
1332 next;
1334 elsif ($line =~ m|^/(.*)|) {
1335 my $regex = $1;
1336 if ($1 eq "") {
1337 print colored $prompt_color, "search for regex? ";
1338 $regex = <STDIN>;
1339 if (defined $regex) {
1340 chomp $regex;
1343 my $search_string;
1344 eval {
1345 $search_string = qr{$regex}m;
1347 if ($@) {
1348 my ($err,$exp) = ($@, $1);
1349 $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1350 error_msg "Malformed search regexp $exp: $err\n";
1351 next;
1353 my $iy = $ix;
1354 while (1) {
1355 my $text = join ("", @{$hunk[$iy]{TEXT}});
1356 last if ($text =~ $search_string);
1357 $iy++;
1358 $iy = 0 if ($iy >= $num);
1359 if ($ix == $iy) {
1360 error_msg "No hunk matches the given pattern\n";
1361 last;
1364 $ix = $iy;
1365 next;
1367 elsif ($line =~ /^K/) {
1368 if ($other =~ /K/) {
1369 $ix--;
1371 else {
1372 error_msg "No previous hunk\n";
1374 next;
1376 elsif ($line =~ /^J/) {
1377 if ($other =~ /J/) {
1378 $ix++;
1380 else {
1381 error_msg "No next hunk\n";
1383 next;
1385 elsif ($line =~ /^k/) {
1386 if ($other =~ /k/) {
1387 while (1) {
1388 $ix--;
1389 last if (!$ix ||
1390 !defined $hunk[$ix]{USE});
1393 else {
1394 error_msg "No previous hunk\n";
1396 next;
1398 elsif ($line =~ /^j/) {
1399 if ($other !~ /j/) {
1400 error_msg "No next hunk\n";
1401 next;
1404 elsif ($other =~ /s/ && $line =~ /^s/) {
1405 my @split = split_hunk($hunk[$ix]{TEXT}, $hunk[$ix]{DISPLAY});
1406 if (1 < @split) {
1407 print colored $header_color, "Split into ",
1408 scalar(@split), " hunks.\n";
1410 splice (@hunk, $ix, 1, @split);
1411 $num = scalar @hunk;
1412 next;
1414 elsif ($other =~ /e/ && $line =~ /^e/) {
1415 my $newhunk = edit_hunk_loop($head, \@hunk, $ix);
1416 if (defined $newhunk) {
1417 splice @hunk, $ix, 1, $newhunk;
1420 else {
1421 help_patch_cmd($other);
1422 next;
1424 # soft increment
1425 while (1) {
1426 $ix++;
1427 last if ($ix >= $num ||
1428 !defined $hunk[$ix]{USE});
1433 @hunk = coalesce_overlapping_hunks(@hunk);
1435 my $n_lofs = 0;
1436 my @result = ();
1437 for (@hunk) {
1438 if ($_->{USE}) {
1439 push @result, @{$_->{TEXT}};
1443 if (@result) {
1444 my $fh;
1445 my @patch = (@{$head->{TEXT}}, @result);
1446 my $apply_routine = $patch_mode_flavour{APPLY};
1447 &$apply_routine(@patch);
1448 refresh();
1451 print "\n";
1452 return $quit;
1455 sub diff_cmd {
1456 my @mods = list_modified('index-only');
1457 @mods = grep { !($_->{BINARY}) } @mods;
1458 return if (!@mods);
1459 my (@them) = list_and_choose({ PROMPT => 'Review diff',
1460 IMMEDIATE => 1,
1461 HEADER => $status_head, },
1462 @mods);
1463 return if (!@them);
1464 my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
1465 system(qw(git diff -p --cached), $reference, '--',
1466 map { $_->{VALUE} } @them);
1469 sub quit_cmd {
1470 print "Bye.\n";
1471 exit(0);
1474 sub help_cmd {
1475 print colored $help_color, <<\EOF ;
1476 status - show paths with changes
1477 update - add working tree state to the staged set of changes
1478 revert - revert staged set of changes back to the HEAD version
1479 patch - pick hunks and update selectively
1480 diff - view diff between HEAD and index
1481 add untracked - add contents of untracked files to the staged set of changes
1485 sub process_args {
1486 return unless @ARGV;
1487 my $arg = shift @ARGV;
1488 if ($arg =~ /--patch(?:=(.*))?/) {
1489 if (defined $1) {
1490 if ($1 eq 'reset') {
1491 $patch_mode = 'reset_head';
1492 $patch_mode_revision = 'HEAD';
1493 $arg = shift @ARGV or die "missing --";
1494 if ($arg ne '--') {
1495 $patch_mode_revision = $arg;
1496 $patch_mode = ($arg eq 'HEAD' ?
1497 'reset_head' : 'reset_nothead');
1498 $arg = shift @ARGV or die "missing --";
1500 } elsif ($1 eq 'checkout') {
1501 $arg = shift @ARGV or die "missing --";
1502 if ($arg eq '--') {
1503 $patch_mode = 'checkout_index';
1504 } else {
1505 $patch_mode_revision = $arg;
1506 $patch_mode = ($arg eq 'HEAD' ?
1507 'checkout_head' : 'checkout_nothead');
1508 $arg = shift @ARGV or die "missing --";
1510 } elsif ($1 eq 'stage' or $1 eq 'stash') {
1511 $patch_mode = $1;
1512 $arg = shift @ARGV or die "missing --";
1513 } else {
1514 die "unknown --patch mode: $1";
1516 } else {
1517 $patch_mode = 'stage';
1518 $arg = shift @ARGV or die "missing --";
1520 die "invalid argument $arg, expecting --"
1521 unless $arg eq "--";
1522 %patch_mode_flavour = %{$patch_modes{$patch_mode}};
1524 elsif ($arg ne "--") {
1525 die "invalid argument $arg, expecting --";
1529 sub main_loop {
1530 my @cmd = ([ 'status', \&status_cmd, ],
1531 [ 'update', \&update_cmd, ],
1532 [ 'revert', \&revert_cmd, ],
1533 [ 'add untracked', \&add_untracked_cmd, ],
1534 [ 'patch', \&patch_update_cmd, ],
1535 [ 'diff', \&diff_cmd, ],
1536 [ 'quit', \&quit_cmd, ],
1537 [ 'help', \&help_cmd, ],
1539 while (1) {
1540 my ($it) = list_and_choose({ PROMPT => 'What now',
1541 SINGLETON => 1,
1542 LIST_FLAT => 4,
1543 HEADER => '*** Commands ***',
1544 ON_EOF => \&quit_cmd,
1545 IMMEDIATE => 1 }, @cmd);
1546 if ($it) {
1547 eval {
1548 $it->[1]->();
1550 if ($@) {
1551 print "$@";
1557 process_args();
1558 refresh();
1559 if ($patch_mode) {
1560 patch_update_cmd();
1562 else {
1563 status_cmd();
1564 main_loop();