git add -p: new "quit" command at the prompt.
[git/gitweb.git] / git-add--interactive.perl
blob4fbd033215a28342d93114956daa0ba6960326d7
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 => [] };
625 for (my $i = 0; $i < @diff; $i++) {
626 if ($diff[$i] =~ /^@@ /) {
627 push @hunk, { TEXT => [], DISPLAY => [] };
629 push @{$hunk[-1]{TEXT}}, $diff[$i];
630 push @{$hunk[-1]{DISPLAY}},
631 ($diff_use_color ? $colored[$i] : $diff[$i]);
633 return @hunk;
636 sub parse_diff_header {
637 my $src = shift;
639 my $head = { TEXT => [], DISPLAY => [] };
640 my $mode = { TEXT => [], DISPLAY => [] };
642 for (my $i = 0; $i < @{$src->{TEXT}}; $i++) {
643 my $dest = $src->{TEXT}->[$i] =~ /^(old|new) mode (\d+)$/ ?
644 $mode : $head;
645 push @{$dest->{TEXT}}, $src->{TEXT}->[$i];
646 push @{$dest->{DISPLAY}}, $src->{DISPLAY}->[$i];
648 return ($head, $mode);
651 sub hunk_splittable {
652 my ($text) = @_;
654 my @s = split_hunk($text);
655 return (1 < @s);
658 sub parse_hunk_header {
659 my ($line) = @_;
660 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
661 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
662 $o_cnt = 1 unless defined $o_cnt;
663 $n_cnt = 1 unless defined $n_cnt;
664 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
667 sub split_hunk {
668 my ($text, $display) = @_;
669 my @split = ();
670 if (!defined $display) {
671 $display = $text;
673 # If there are context lines in the middle of a hunk,
674 # it can be split, but we would need to take care of
675 # overlaps later.
677 my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
678 my $hunk_start = 1;
680 OUTER:
681 while (1) {
682 my $next_hunk_start = undef;
683 my $i = $hunk_start - 1;
684 my $this = +{
685 TEXT => [],
686 DISPLAY => [],
687 OLD => $o_ofs,
688 NEW => $n_ofs,
689 OCNT => 0,
690 NCNT => 0,
691 ADDDEL => 0,
692 POSTCTX => 0,
693 USE => undef,
696 while (++$i < @$text) {
697 my $line = $text->[$i];
698 my $display = $display->[$i];
699 if ($line =~ /^ /) {
700 if ($this->{ADDDEL} &&
701 !defined $next_hunk_start) {
702 # We have seen leading context and
703 # adds/dels and then here is another
704 # context, which is trailing for this
705 # split hunk and leading for the next
706 # one.
707 $next_hunk_start = $i;
709 push @{$this->{TEXT}}, $line;
710 push @{$this->{DISPLAY}}, $display;
711 $this->{OCNT}++;
712 $this->{NCNT}++;
713 if (defined $next_hunk_start) {
714 $this->{POSTCTX}++;
716 next;
719 # add/del
720 if (defined $next_hunk_start) {
721 # We are done with the current hunk and
722 # this is the first real change for the
723 # next split one.
724 $hunk_start = $next_hunk_start;
725 $o_ofs = $this->{OLD} + $this->{OCNT};
726 $n_ofs = $this->{NEW} + $this->{NCNT};
727 $o_ofs -= $this->{POSTCTX};
728 $n_ofs -= $this->{POSTCTX};
729 push @split, $this;
730 redo OUTER;
732 push @{$this->{TEXT}}, $line;
733 push @{$this->{DISPLAY}}, $display;
734 $this->{ADDDEL}++;
735 if ($line =~ /^-/) {
736 $this->{OCNT}++;
738 else {
739 $this->{NCNT}++;
743 push @split, $this;
744 last;
747 for my $hunk (@split) {
748 $o_ofs = $hunk->{OLD};
749 $n_ofs = $hunk->{NEW};
750 my $o_cnt = $hunk->{OCNT};
751 my $n_cnt = $hunk->{NCNT};
753 my $head = ("@@ -$o_ofs" .
754 (($o_cnt != 1) ? ",$o_cnt" : '') .
755 " +$n_ofs" .
756 (($n_cnt != 1) ? ",$n_cnt" : '') .
757 " @@\n");
758 my $display_head = $head;
759 unshift @{$hunk->{TEXT}}, $head;
760 if ($diff_use_color) {
761 $display_head = colored($fraginfo_color, $head);
763 unshift @{$hunk->{DISPLAY}}, $display_head;
765 return @split;
769 sub color_diff {
770 return map {
771 colored((/^@/ ? $fraginfo_color :
772 /^\+/ ? $diff_new_color :
773 /^-/ ? $diff_old_color :
774 $diff_plain_color),
775 $_);
776 } @_;
779 sub edit_hunk_manually {
780 my ($oldtext) = @_;
782 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
783 my $fh;
784 open $fh, '>', $hunkfile
785 or die "failed to open hunk edit file for writing: " . $!;
786 print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
787 print $fh @$oldtext;
788 print $fh <<EOF;
789 # ---
790 # To remove '-' lines, make them ' ' lines (context).
791 # To remove '+' lines, delete them.
792 # Lines starting with # will be removed.
794 # If the patch applies cleanly, the edited hunk will immediately be
795 # marked for staging. If it does not apply cleanly, you will be given
796 # an opportunity to edit again. If all lines of the hunk are removed,
797 # then the edit is aborted and the hunk is left unchanged.
799 close $fh;
801 my $editor = $ENV{GIT_EDITOR} || $repo->config("core.editor")
802 || $ENV{VISUAL} || $ENV{EDITOR} || "vi";
803 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
805 open $fh, '<', $hunkfile
806 or die "failed to open hunk edit file for reading: " . $!;
807 my @newtext = grep { !/^#/ } <$fh>;
808 close $fh;
809 unlink $hunkfile;
811 # Abort if nothing remains
812 if (!grep { /\S/ } @newtext) {
813 return undef;
816 # Reinsert the first hunk header if the user accidentally deleted it
817 if ($newtext[0] !~ /^@/) {
818 unshift @newtext, $oldtext->[0];
820 return \@newtext;
823 sub diff_applies {
824 my $fh;
825 open $fh, '| git apply --recount --cached --check';
826 for my $h (@_) {
827 print $fh @{$h->{TEXT}};
829 return close $fh;
832 sub _restore_terminal_and_die {
833 ReadMode 'restore';
834 print "\n";
835 exit 1;
838 sub prompt_single_character {
839 if ($use_readkey) {
840 local $SIG{TERM} = \&_restore_terminal_and_die;
841 local $SIG{INT} = \&_restore_terminal_and_die;
842 ReadMode 'cbreak';
843 my $key = ReadKey 0;
844 ReadMode 'restore';
845 print "$key" if defined $key;
846 print "\n";
847 return $key;
848 } else {
849 return <STDIN>;
853 sub prompt_yesno {
854 my ($prompt) = @_;
855 while (1) {
856 print colored $prompt_color, $prompt;
857 my $line = prompt_single_character;
858 return 0 if $line =~ /^n/i;
859 return 1 if $line =~ /^y/i;
863 sub edit_hunk_loop {
864 my ($head, $hunk, $ix) = @_;
865 my $text = $hunk->[$ix]->{TEXT};
867 while (1) {
868 $text = edit_hunk_manually($text);
869 if (!defined $text) {
870 return undef;
872 my $newhunk = { TEXT => $text, USE => 1 };
873 if (diff_applies($head,
874 @{$hunk}[0..$ix-1],
875 $newhunk,
876 @{$hunk}[$ix+1..$#{$hunk}])) {
877 $newhunk->{DISPLAY} = [color_diff(@{$text})];
878 return $newhunk;
880 else {
881 prompt_yesno(
882 'Your edited hunk does not apply. Edit again '
883 . '(saying "no" discards!) [y/n]? '
884 ) or return undef;
889 sub help_patch_cmd {
890 print colored $help_color, <<\EOF ;
891 y - stage this hunk
892 n - do not stage this hunk
893 q - quit, do not stage this hunk nor any of the remaining ones
894 a - stage this and all the remaining hunks in the file
895 d - do not stage this hunk nor any of the remaining hunks in the file
896 g - select a hunk to go to
897 / - search for a hunk matching the given regex
898 j - leave this hunk undecided, see next undecided hunk
899 J - leave this hunk undecided, see next hunk
900 k - leave this hunk undecided, see previous undecided hunk
901 K - leave this hunk undecided, see previous hunk
902 s - split the current hunk into smaller hunks
903 e - manually edit the current hunk
904 ? - print help
908 sub patch_update_cmd {
909 my @all_mods = list_modified('file-only');
910 my @mods = grep { !($_->{BINARY}) } @all_mods;
911 my @them;
913 if (!@mods) {
914 if (@all_mods) {
915 print STDERR "Only binary files changed.\n";
916 } else {
917 print STDERR "No changes.\n";
919 return 0;
921 if ($patch_mode) {
922 @them = @mods;
924 else {
925 @them = list_and_choose({ PROMPT => 'Patch update',
926 HEADER => $status_head, },
927 @mods);
929 for (@them) {
930 return 0 if patch_update_file($_->{VALUE});
934 # Generate a one line summary of a hunk.
935 sub summarize_hunk {
936 my $rhunk = shift;
937 my $summary = $rhunk->{TEXT}[0];
939 # Keep the line numbers, discard extra context.
940 $summary =~ s/@@(.*?)@@.*/$1 /s;
941 $summary .= " " x (20 - length $summary);
943 # Add some user context.
944 for my $line (@{$rhunk->{TEXT}}) {
945 if ($line =~ m/^[+-].*\w/) {
946 $summary .= $line;
947 last;
951 chomp $summary;
952 return substr($summary, 0, 80) . "\n";
956 # Print a one-line summary of each hunk in the array ref in
957 # the first argument, starting wih the index in the 2nd.
958 sub display_hunks {
959 my ($hunks, $i) = @_;
960 my $ctr = 0;
961 $i ||= 0;
962 for (; $i < @$hunks && $ctr < 20; $i++, $ctr++) {
963 my $status = " ";
964 if (defined $hunks->[$i]{USE}) {
965 $status = $hunks->[$i]{USE} ? "+" : "-";
967 printf "%s%2d: %s",
968 $status,
969 $i + 1,
970 summarize_hunk($hunks->[$i]);
972 return $i;
975 sub patch_update_file {
976 my $quit = 0;
977 my ($ix, $num);
978 my $path = shift;
979 my ($head, @hunk) = parse_diff($path);
980 ($head, my $mode) = parse_diff_header($head);
981 for (@{$head->{DISPLAY}}) {
982 print;
985 if (@{$mode->{TEXT}}) {
986 while (1) {
987 print @{$mode->{DISPLAY}};
988 print colored $prompt_color,
989 "Stage mode change [y/n/a/d/?]? ";
990 my $line = prompt_single_character;
991 if ($line =~ /^y/i) {
992 $mode->{USE} = 1;
993 last;
995 elsif ($line =~ /^n/i) {
996 $mode->{USE} = 0;
997 last;
999 elsif ($line =~ /^a/i) {
1000 $_->{USE} = 1 foreach ($mode, @hunk);
1001 last;
1003 elsif ($line =~ /^d/i) {
1004 $_->{USE} = 0 foreach ($mode, @hunk);
1005 last;
1007 elsif ($line =~ /^q/i) {
1008 $_->{USE} = 0 foreach ($mode, @hunk);
1009 $quit = 1;
1010 last;
1012 else {
1013 help_patch_cmd('');
1014 next;
1019 $num = scalar @hunk;
1020 $ix = 0;
1022 while (1) {
1023 my ($prev, $next, $other, $undecided, $i);
1024 $other = '';
1026 if ($num <= $ix) {
1027 $ix = 0;
1029 for ($i = 0; $i < $ix; $i++) {
1030 if (!defined $hunk[$i]{USE}) {
1031 $prev = 1;
1032 $other .= ',k';
1033 last;
1036 if ($ix) {
1037 $other .= ',K';
1039 for ($i = $ix + 1; $i < $num; $i++) {
1040 if (!defined $hunk[$i]{USE}) {
1041 $next = 1;
1042 $other .= ',j';
1043 last;
1046 if ($ix < $num - 1) {
1047 $other .= ',J';
1049 if ($num > 1) {
1050 $other .= ',g';
1052 for ($i = 0; $i < $num; $i++) {
1053 if (!defined $hunk[$i]{USE}) {
1054 $undecided = 1;
1055 last;
1058 last if (!$undecided);
1060 if (hunk_splittable($hunk[$ix]{TEXT})) {
1061 $other .= ',s';
1063 $other .= ',e';
1064 for (@{$hunk[$ix]{DISPLAY}}) {
1065 print;
1067 print colored $prompt_color, "Stage this hunk [y,n,a,d,/$other,?]? ";
1068 my $line = prompt_single_character;
1069 if ($line) {
1070 if ($line =~ /^y/i) {
1071 $hunk[$ix]{USE} = 1;
1073 elsif ($line =~ /^n/i) {
1074 $hunk[$ix]{USE} = 0;
1076 elsif ($line =~ /^a/i) {
1077 while ($ix < $num) {
1078 if (!defined $hunk[$ix]{USE}) {
1079 $hunk[$ix]{USE} = 1;
1081 $ix++;
1083 next;
1085 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1086 my $response = $1;
1087 my $no = $ix > 10 ? $ix - 10 : 0;
1088 while ($response eq '') {
1089 my $extra = "";
1090 $no = display_hunks(\@hunk, $no);
1091 if ($no < $num) {
1092 $extra = " (<ret> to see more)";
1094 print "go to which hunk$extra? ";
1095 $response = <STDIN>;
1096 if (!defined $response) {
1097 $response = '';
1099 chomp $response;
1101 if ($response !~ /^\s*\d+\s*$/) {
1102 error_msg "Invalid number: '$response'\n";
1103 } elsif (0 < $response && $response <= $num) {
1104 $ix = $response - 1;
1105 } else {
1106 error_msg "Sorry, only $num hunks available.\n";
1108 next;
1110 elsif ($line =~ /^d/i) {
1111 while ($ix < $num) {
1112 if (!defined $hunk[$ix]{USE}) {
1113 $hunk[$ix]{USE} = 0;
1115 $ix++;
1117 next;
1119 elsif ($line =~ /^q/i) {
1120 while ($ix < $num) {
1121 if (!defined $hunk[$ix]{USE}) {
1122 $hunk[$ix]{USE} = 0;
1124 $ix++;
1126 $quit = 1;
1127 next;
1129 elsif ($line =~ m|^/(.*)|) {
1130 my $regex = $1;
1131 if ($1 eq "") {
1132 print colored $prompt_color, "search for regex? ";
1133 $regex = <STDIN>;
1134 if (defined $regex) {
1135 chomp $regex;
1138 my $search_string;
1139 eval {
1140 $search_string = qr{$regex}m;
1142 if ($@) {
1143 my ($err,$exp) = ($@, $1);
1144 $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1145 error_msg "Malformed search regexp $exp: $err\n";
1146 next;
1148 my $iy = $ix;
1149 while (1) {
1150 my $text = join ("", @{$hunk[$iy]{TEXT}});
1151 last if ($text =~ $search_string);
1152 $iy++;
1153 $iy = 0 if ($iy >= $num);
1154 if ($ix == $iy) {
1155 error_msg "No hunk matches the given pattern\n";
1156 last;
1159 $ix = $iy;
1160 next;
1162 elsif ($line =~ /^K/) {
1163 if ($other =~ /K/) {
1164 $ix--;
1166 else {
1167 error_msg "No previous hunk\n";
1169 next;
1171 elsif ($line =~ /^J/) {
1172 if ($other =~ /J/) {
1173 $ix++;
1175 else {
1176 error_msg "No next hunk\n";
1178 next;
1180 elsif ($line =~ /^k/) {
1181 if ($other =~ /k/) {
1182 while (1) {
1183 $ix--;
1184 last if (!$ix ||
1185 !defined $hunk[$ix]{USE});
1188 else {
1189 error_msg "No previous hunk\n";
1191 next;
1193 elsif ($line =~ /^j/) {
1194 if ($other !~ /j/) {
1195 error_msg "No next hunk\n";
1196 next;
1199 elsif ($other =~ /s/ && $line =~ /^s/) {
1200 my @split = split_hunk($hunk[$ix]{TEXT}, $hunk[$ix]{DISPLAY});
1201 if (1 < @split) {
1202 print colored $header_color, "Split into ",
1203 scalar(@split), " hunks.\n";
1205 splice (@hunk, $ix, 1, @split);
1206 $num = scalar @hunk;
1207 next;
1209 elsif ($line =~ /^e/) {
1210 my $newhunk = edit_hunk_loop($head, \@hunk, $ix);
1211 if (defined $newhunk) {
1212 splice @hunk, $ix, 1, $newhunk;
1215 else {
1216 help_patch_cmd($other);
1217 next;
1219 # soft increment
1220 while (1) {
1221 $ix++;
1222 last if ($ix >= $num ||
1223 !defined $hunk[$ix]{USE});
1228 my $n_lofs = 0;
1229 my @result = ();
1230 if ($mode->{USE}) {
1231 push @result, @{$mode->{TEXT}};
1233 for (@hunk) {
1234 if ($_->{USE}) {
1235 push @result, @{$_->{TEXT}};
1239 if (@result) {
1240 my $fh;
1242 open $fh, '| git apply --cached --recount';
1243 for (@{$head->{TEXT}}, @result) {
1244 print $fh $_;
1246 if (!close $fh) {
1247 for (@{$head->{TEXT}}, @result) {
1248 print STDERR $_;
1251 refresh();
1254 print "\n";
1255 return $quit;
1258 sub diff_cmd {
1259 my @mods = list_modified('index-only');
1260 @mods = grep { !($_->{BINARY}) } @mods;
1261 return if (!@mods);
1262 my (@them) = list_and_choose({ PROMPT => 'Review diff',
1263 IMMEDIATE => 1,
1264 HEADER => $status_head, },
1265 @mods);
1266 return if (!@them);
1267 my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
1268 system(qw(git diff -p --cached), $reference, '--',
1269 map { $_->{VALUE} } @them);
1272 sub quit_cmd {
1273 print "Bye.\n";
1274 exit(0);
1277 sub help_cmd {
1278 print colored $help_color, <<\EOF ;
1279 status - show paths with changes
1280 update - add working tree state to the staged set of changes
1281 revert - revert staged set of changes back to the HEAD version
1282 patch - pick hunks and update selectively
1283 diff - view diff between HEAD and index
1284 add untracked - add contents of untracked files to the staged set of changes
1288 sub process_args {
1289 return unless @ARGV;
1290 my $arg = shift @ARGV;
1291 if ($arg eq "--patch") {
1292 $patch_mode = 1;
1293 $arg = shift @ARGV or die "missing --";
1294 die "invalid argument $arg, expecting --"
1295 unless $arg eq "--";
1297 elsif ($arg ne "--") {
1298 die "invalid argument $arg, expecting --";
1302 sub main_loop {
1303 my @cmd = ([ 'status', \&status_cmd, ],
1304 [ 'update', \&update_cmd, ],
1305 [ 'revert', \&revert_cmd, ],
1306 [ 'add untracked', \&add_untracked_cmd, ],
1307 [ 'patch', \&patch_update_cmd, ],
1308 [ 'diff', \&diff_cmd, ],
1309 [ 'quit', \&quit_cmd, ],
1310 [ 'help', \&help_cmd, ],
1312 while (1) {
1313 my ($it) = list_and_choose({ PROMPT => 'What now',
1314 SINGLETON => 1,
1315 LIST_FLAT => 4,
1316 HEADER => '*** Commands ***',
1317 ON_EOF => \&quit_cmd,
1318 IMMEDIATE => 1 }, @cmd);
1319 if ($it) {
1320 eval {
1321 $it->[1]->();
1323 if ($@) {
1324 print "$@";
1330 process_args();
1331 refresh();
1332 if ($patch_mode) {
1333 patch_update_cmd();
1335 else {
1336 status_cmd();
1337 main_loop();