git-apply--interactive: Refactor patch mode code
[git/dscho.git] / git-add--interactive.perl
blob360610314e8e98c4c79a86273696317bf44cb1dd
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 apply_patch;
78 my %patch_modes = (
79 'stage' => {
80 DIFF => 'diff-files -p',
81 APPLY => sub { apply_patch 'apply --cached', @_; },
82 APPLY_CHECK => 'apply --cached',
83 VERB => 'Stage',
84 TARGET => '',
85 PARTICIPLE => 'staging',
86 FILTER => 'file-only',
90 my %patch_mode_flavour = %{$patch_modes{stage}};
92 sub run_cmd_pipe {
93 if ($^O eq 'MSWin32' || $^O eq 'msys') {
94 my @invalid = grep {m/[":*]/} @_;
95 die "$^O does not support: @invalid\n" if @invalid;
96 my @args = map { m/ /o ? "\"$_\"": $_ } @_;
97 return qx{@args};
98 } else {
99 my $fh = undef;
100 open($fh, '-|', @_) or die;
101 return <$fh>;
105 my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));
107 if (!defined $GIT_DIR) {
108 exit(1); # rev-parse would have already said "not a git repo"
110 chomp($GIT_DIR);
112 my %cquote_map = (
113 "b" => chr(8),
114 "t" => chr(9),
115 "n" => chr(10),
116 "v" => chr(11),
117 "f" => chr(12),
118 "r" => chr(13),
119 "\\" => "\\",
120 "\042" => "\042",
123 sub unquote_path {
124 local ($_) = @_;
125 my ($retval, $remainder);
126 if (!/^\042(.*)\042$/) {
127 return $_;
129 ($_, $retval) = ($1, "");
130 while (/^([^\\]*)\\(.*)$/) {
131 $remainder = $2;
132 $retval .= $1;
133 for ($remainder) {
134 if (/^([0-3][0-7][0-7])(.*)$/) {
135 $retval .= chr(oct($1));
136 $_ = $2;
137 last;
139 if (/^([\\\042btnvfr])(.*)$/) {
140 $retval .= $cquote_map{$1};
141 $_ = $2;
142 last;
144 # This is malformed -- just return it as-is for now.
145 return $_[0];
147 $_ = $remainder;
149 $retval .= $_;
150 return $retval;
153 sub refresh {
154 my $fh;
155 open $fh, 'git update-index --refresh |'
156 or die;
157 while (<$fh>) {
158 ;# ignore 'needs update'
160 close $fh;
163 sub list_untracked {
164 map {
165 chomp $_;
166 unquote_path($_);
168 run_cmd_pipe(qw(git ls-files --others --exclude-standard --), @ARGV);
171 my $status_fmt = '%12s %12s %s';
172 my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
175 my $initial;
176 sub is_initial_commit {
177 $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
178 unless defined $initial;
179 return $initial;
183 sub get_empty_tree {
184 return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
187 # Returns list of hashes, contents of each of which are:
188 # VALUE: pathname
189 # BINARY: is a binary path
190 # INDEX: is index different from HEAD?
191 # FILE: is file different from index?
192 # INDEX_ADDDEL: is it add/delete between HEAD and index?
193 # FILE_ADDDEL: is it add/delete between index and file?
195 sub list_modified {
196 my ($only) = @_;
197 my (%data, @return);
198 my ($add, $del, $adddel, $file);
199 my @tracked = ();
201 if (@ARGV) {
202 @tracked = map {
203 chomp $_;
204 unquote_path($_);
205 } run_cmd_pipe(qw(git ls-files --exclude-standard --), @ARGV);
206 return if (!@tracked);
209 my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
210 for (run_cmd_pipe(qw(git diff-index --cached
211 --numstat --summary), $reference,
212 '--', @tracked)) {
213 if (($add, $del, $file) =
214 /^([-\d]+) ([-\d]+) (.*)/) {
215 my ($change, $bin);
216 $file = unquote_path($file);
217 if ($add eq '-' && $del eq '-') {
218 $change = 'binary';
219 $bin = 1;
221 else {
222 $change = "+$add/-$del";
224 $data{$file} = {
225 INDEX => $change,
226 BINARY => $bin,
227 FILE => 'nothing',
230 elsif (($adddel, $file) =
231 /^ (create|delete) mode [0-7]+ (.*)$/) {
232 $file = unquote_path($file);
233 $data{$file}{INDEX_ADDDEL} = $adddel;
237 for (run_cmd_pipe(qw(git diff-files --numstat --summary --), @tracked)) {
238 if (($add, $del, $file) =
239 /^([-\d]+) ([-\d]+) (.*)/) {
240 $file = unquote_path($file);
241 if (!exists $data{$file}) {
242 $data{$file} = +{
243 INDEX => 'unchanged',
244 BINARY => 0,
247 my ($change, $bin);
248 if ($add eq '-' && $del eq '-') {
249 $change = 'binary';
250 $bin = 1;
252 else {
253 $change = "+$add/-$del";
255 $data{$file}{FILE} = $change;
256 if ($bin) {
257 $data{$file}{BINARY} = 1;
260 elsif (($adddel, $file) =
261 /^ (create|delete) mode [0-7]+ (.*)$/) {
262 $file = unquote_path($file);
263 $data{$file}{FILE_ADDDEL} = $adddel;
267 for (sort keys %data) {
268 my $it = $data{$_};
270 if ($only) {
271 if ($only eq 'index-only') {
272 next if ($it->{INDEX} eq 'unchanged');
274 if ($only eq 'file-only') {
275 next if ($it->{FILE} eq 'nothing');
278 push @return, +{
279 VALUE => $_,
280 %$it,
283 return @return;
286 sub find_unique {
287 my ($string, @stuff) = @_;
288 my $found = undef;
289 for (my $i = 0; $i < @stuff; $i++) {
290 my $it = $stuff[$i];
291 my $hit = undef;
292 if (ref $it) {
293 if ((ref $it) eq 'ARRAY') {
294 $it = $it->[0];
296 else {
297 $it = $it->{VALUE};
300 eval {
301 if ($it =~ /^$string/) {
302 $hit = 1;
305 if (defined $hit && defined $found) {
306 return undef;
308 if ($hit) {
309 $found = $i + 1;
312 return $found;
315 # inserts string into trie and updates count for each character
316 sub update_trie {
317 my ($trie, $string) = @_;
318 foreach (split //, $string) {
319 $trie = $trie->{$_} ||= {COUNT => 0};
320 $trie->{COUNT}++;
324 # returns an array of tuples (prefix, remainder)
325 sub find_unique_prefixes {
326 my @stuff = @_;
327 my @return = ();
329 # any single prefix exceeding the soft limit is omitted
330 # if any prefix exceeds the hard limit all are omitted
331 # 0 indicates no limit
332 my $soft_limit = 0;
333 my $hard_limit = 3;
335 # build a trie modelling all possible options
336 my %trie;
337 foreach my $print (@stuff) {
338 if ((ref $print) eq 'ARRAY') {
339 $print = $print->[0];
341 elsif ((ref $print) eq 'HASH') {
342 $print = $print->{VALUE};
344 update_trie(\%trie, $print);
345 push @return, $print;
348 # use the trie to find the unique prefixes
349 for (my $i = 0; $i < @return; $i++) {
350 my $ret = $return[$i];
351 my @letters = split //, $ret;
352 my %search = %trie;
353 my ($prefix, $remainder);
354 my $j;
355 for ($j = 0; $j < @letters; $j++) {
356 my $letter = $letters[$j];
357 if ($search{$letter}{COUNT} == 1) {
358 $prefix = substr $ret, 0, $j + 1;
359 $remainder = substr $ret, $j + 1;
360 last;
362 else {
363 my $prefix = substr $ret, 0, $j;
364 return ()
365 if ($hard_limit && $j + 1 > $hard_limit);
367 %search = %{$search{$letter}};
369 if (ord($letters[0]) > 127 ||
370 ($soft_limit && $j + 1 > $soft_limit)) {
371 $prefix = undef;
372 $remainder = $ret;
374 $return[$i] = [$prefix, $remainder];
376 return @return;
379 # filters out prefixes which have special meaning to list_and_choose()
380 sub is_valid_prefix {
381 my $prefix = shift;
382 return (defined $prefix) &&
383 !($prefix =~ /[\s,]/) && # separators
384 !($prefix =~ /^-/) && # deselection
385 !($prefix =~ /^\d+/) && # selection
386 ($prefix ne '*') && # "all" wildcard
387 ($prefix ne '?'); # prompt help
390 # given a prefix/remainder tuple return a string with the prefix highlighted
391 # for now use square brackets; later might use ANSI colors (underline, bold)
392 sub highlight_prefix {
393 my $prefix = shift;
394 my $remainder = shift;
396 if (!defined $prefix) {
397 return $remainder;
400 if (!is_valid_prefix($prefix)) {
401 return "$prefix$remainder";
404 if (!$menu_use_color) {
405 return "[$prefix]$remainder";
408 return "$prompt_color$prefix$normal_color$remainder";
411 sub error_msg {
412 print STDERR colored $error_color, @_;
415 sub list_and_choose {
416 my ($opts, @stuff) = @_;
417 my (@chosen, @return);
418 my $i;
419 my @prefixes = find_unique_prefixes(@stuff) unless $opts->{LIST_ONLY};
421 TOPLOOP:
422 while (1) {
423 my $last_lf = 0;
425 if ($opts->{HEADER}) {
426 if (!$opts->{LIST_FLAT}) {
427 print " ";
429 print colored $header_color, "$opts->{HEADER}\n";
431 for ($i = 0; $i < @stuff; $i++) {
432 my $chosen = $chosen[$i] ? '*' : ' ';
433 my $print = $stuff[$i];
434 my $ref = ref $print;
435 my $highlighted = highlight_prefix(@{$prefixes[$i]})
436 if @prefixes;
437 if ($ref eq 'ARRAY') {
438 $print = $highlighted || $print->[0];
440 elsif ($ref eq 'HASH') {
441 my $value = $highlighted || $print->{VALUE};
442 $print = sprintf($status_fmt,
443 $print->{INDEX},
444 $print->{FILE},
445 $value);
447 else {
448 $print = $highlighted || $print;
450 printf("%s%2d: %s", $chosen, $i+1, $print);
451 if (($opts->{LIST_FLAT}) &&
452 (($i + 1) % ($opts->{LIST_FLAT}))) {
453 print "\t";
454 $last_lf = 0;
456 else {
457 print "\n";
458 $last_lf = 1;
461 if (!$last_lf) {
462 print "\n";
465 return if ($opts->{LIST_ONLY});
467 print colored $prompt_color, $opts->{PROMPT};
468 if ($opts->{SINGLETON}) {
469 print "> ";
471 else {
472 print ">> ";
474 my $line = <STDIN>;
475 if (!$line) {
476 print "\n";
477 $opts->{ON_EOF}->() if $opts->{ON_EOF};
478 last;
480 chomp $line;
481 last if $line eq '';
482 if ($line eq '?') {
483 $opts->{SINGLETON} ?
484 singleton_prompt_help_cmd() :
485 prompt_help_cmd();
486 next TOPLOOP;
488 for my $choice (split(/[\s,]+/, $line)) {
489 my $choose = 1;
490 my ($bottom, $top);
492 # Input that begins with '-'; unchoose
493 if ($choice =~ s/^-//) {
494 $choose = 0;
496 # A range can be specified like 5-7 or 5-.
497 if ($choice =~ /^(\d+)-(\d*)$/) {
498 ($bottom, $top) = ($1, length($2) ? $2 : 1 + @stuff);
500 elsif ($choice =~ /^\d+$/) {
501 $bottom = $top = $choice;
503 elsif ($choice eq '*') {
504 $bottom = 1;
505 $top = 1 + @stuff;
507 else {
508 $bottom = $top = find_unique($choice, @stuff);
509 if (!defined $bottom) {
510 error_msg "Huh ($choice)?\n";
511 next TOPLOOP;
514 if ($opts->{SINGLETON} && $bottom != $top) {
515 error_msg "Huh ($choice)?\n";
516 next TOPLOOP;
518 for ($i = $bottom-1; $i <= $top-1; $i++) {
519 next if (@stuff <= $i || $i < 0);
520 $chosen[$i] = $choose;
523 last if ($opts->{IMMEDIATE} || $line eq '*');
525 for ($i = 0; $i < @stuff; $i++) {
526 if ($chosen[$i]) {
527 push @return, $stuff[$i];
530 return @return;
533 sub singleton_prompt_help_cmd {
534 print colored $help_color, <<\EOF ;
535 Prompt help:
536 1 - select a numbered item
537 foo - select item based on unique prefix
538 - (empty) select nothing
542 sub prompt_help_cmd {
543 print colored $help_color, <<\EOF ;
544 Prompt help:
545 1 - select a single item
546 3-5 - select a range of items
547 2-3,6-9 - select multiple ranges
548 foo - select item based on unique prefix
549 -... - unselect specified items
550 * - choose all items
551 - (empty) finish selecting
555 sub status_cmd {
556 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
557 list_modified());
558 print "\n";
561 sub say_n_paths {
562 my $did = shift @_;
563 my $cnt = scalar @_;
564 print "$did ";
565 if (1 < $cnt) {
566 print "$cnt paths\n";
568 else {
569 print "one path\n";
573 sub update_cmd {
574 my @mods = list_modified('file-only');
575 return if (!@mods);
577 my @update = list_and_choose({ PROMPT => 'Update',
578 HEADER => $status_head, },
579 @mods);
580 if (@update) {
581 system(qw(git update-index --add --remove --),
582 map { $_->{VALUE} } @update);
583 say_n_paths('updated', @update);
585 print "\n";
588 sub revert_cmd {
589 my @update = list_and_choose({ PROMPT => 'Revert',
590 HEADER => $status_head, },
591 list_modified());
592 if (@update) {
593 if (is_initial_commit()) {
594 system(qw(git rm --cached),
595 map { $_->{VALUE} } @update);
597 else {
598 my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
599 map { $_->{VALUE} } @update);
600 my $fh;
601 open $fh, '| git update-index --index-info'
602 or die;
603 for (@lines) {
604 print $fh $_;
606 close($fh);
607 for (@update) {
608 if ($_->{INDEX_ADDDEL} &&
609 $_->{INDEX_ADDDEL} eq 'create') {
610 system(qw(git update-index --force-remove --),
611 $_->{VALUE});
612 print "note: $_->{VALUE} is untracked now.\n";
616 refresh();
617 say_n_paths('reverted', @update);
619 print "\n";
622 sub add_untracked_cmd {
623 my @add = list_and_choose({ PROMPT => 'Add untracked' },
624 list_untracked());
625 if (@add) {
626 system(qw(git update-index --add --), @add);
627 say_n_paths('added', @add);
629 print "\n";
632 sub run_git_apply {
633 my $cmd = shift;
634 my $fh;
635 open $fh, '| git ' . $cmd;
636 print $fh @_;
637 return close $fh;
640 sub parse_diff {
641 my ($path) = @_;
642 my @diff_cmd = split(" ", $patch_mode_flavour{DIFF});
643 my @diff = run_cmd_pipe("git", @diff_cmd, "--", $path);
644 my @colored = ();
645 if ($diff_use_color) {
646 @colored = run_cmd_pipe("git", @diff_cmd, qw(--color --), $path);
648 my (@hunk) = { TEXT => [], DISPLAY => [], TYPE => 'header' };
650 for (my $i = 0; $i < @diff; $i++) {
651 if ($diff[$i] =~ /^@@ /) {
652 push @hunk, { TEXT => [], DISPLAY => [],
653 TYPE => 'hunk' };
655 push @{$hunk[-1]{TEXT}}, $diff[$i];
656 push @{$hunk[-1]{DISPLAY}},
657 ($diff_use_color ? $colored[$i] : $diff[$i]);
659 return @hunk;
662 sub parse_diff_header {
663 my $src = shift;
665 my $head = { TEXT => [], DISPLAY => [], TYPE => 'header' };
666 my $mode = { TEXT => [], DISPLAY => [], TYPE => 'mode' };
668 for (my $i = 0; $i < @{$src->{TEXT}}; $i++) {
669 my $dest = $src->{TEXT}->[$i] =~ /^(old|new) mode (\d+)$/ ?
670 $mode : $head;
671 push @{$dest->{TEXT}}, $src->{TEXT}->[$i];
672 push @{$dest->{DISPLAY}}, $src->{DISPLAY}->[$i];
674 return ($head, $mode);
677 sub hunk_splittable {
678 my ($text) = @_;
680 my @s = split_hunk($text);
681 return (1 < @s);
684 sub parse_hunk_header {
685 my ($line) = @_;
686 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
687 $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
688 $o_cnt = 1 unless defined $o_cnt;
689 $n_cnt = 1 unless defined $n_cnt;
690 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
693 sub split_hunk {
694 my ($text, $display) = @_;
695 my @split = ();
696 if (!defined $display) {
697 $display = $text;
699 # If there are context lines in the middle of a hunk,
700 # it can be split, but we would need to take care of
701 # overlaps later.
703 my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
704 my $hunk_start = 1;
706 OUTER:
707 while (1) {
708 my $next_hunk_start = undef;
709 my $i = $hunk_start - 1;
710 my $this = +{
711 TEXT => [],
712 DISPLAY => [],
713 TYPE => 'hunk',
714 OLD => $o_ofs,
715 NEW => $n_ofs,
716 OCNT => 0,
717 NCNT => 0,
718 ADDDEL => 0,
719 POSTCTX => 0,
720 USE => undef,
723 while (++$i < @$text) {
724 my $line = $text->[$i];
725 my $display = $display->[$i];
726 if ($line =~ /^ /) {
727 if ($this->{ADDDEL} &&
728 !defined $next_hunk_start) {
729 # We have seen leading context and
730 # adds/dels and then here is another
731 # context, which is trailing for this
732 # split hunk and leading for the next
733 # one.
734 $next_hunk_start = $i;
736 push @{$this->{TEXT}}, $line;
737 push @{$this->{DISPLAY}}, $display;
738 $this->{OCNT}++;
739 $this->{NCNT}++;
740 if (defined $next_hunk_start) {
741 $this->{POSTCTX}++;
743 next;
746 # add/del
747 if (defined $next_hunk_start) {
748 # We are done with the current hunk and
749 # this is the first real change for the
750 # next split one.
751 $hunk_start = $next_hunk_start;
752 $o_ofs = $this->{OLD} + $this->{OCNT};
753 $n_ofs = $this->{NEW} + $this->{NCNT};
754 $o_ofs -= $this->{POSTCTX};
755 $n_ofs -= $this->{POSTCTX};
756 push @split, $this;
757 redo OUTER;
759 push @{$this->{TEXT}}, $line;
760 push @{$this->{DISPLAY}}, $display;
761 $this->{ADDDEL}++;
762 if ($line =~ /^-/) {
763 $this->{OCNT}++;
765 else {
766 $this->{NCNT}++;
770 push @split, $this;
771 last;
774 for my $hunk (@split) {
775 $o_ofs = $hunk->{OLD};
776 $n_ofs = $hunk->{NEW};
777 my $o_cnt = $hunk->{OCNT};
778 my $n_cnt = $hunk->{NCNT};
780 my $head = ("@@ -$o_ofs" .
781 (($o_cnt != 1) ? ",$o_cnt" : '') .
782 " +$n_ofs" .
783 (($n_cnt != 1) ? ",$n_cnt" : '') .
784 " @@\n");
785 my $display_head = $head;
786 unshift @{$hunk->{TEXT}}, $head;
787 if ($diff_use_color) {
788 $display_head = colored($fraginfo_color, $head);
790 unshift @{$hunk->{DISPLAY}}, $display_head;
792 return @split;
795 sub find_last_o_ctx {
796 my ($it) = @_;
797 my $text = $it->{TEXT};
798 my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
799 my $i = @{$text};
800 my $last_o_ctx = $o_ofs + $o_cnt;
801 while (0 < --$i) {
802 my $line = $text->[$i];
803 if ($line =~ /^ /) {
804 $last_o_ctx--;
805 next;
807 last;
809 return $last_o_ctx;
812 sub merge_hunk {
813 my ($prev, $this) = @_;
814 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
815 parse_hunk_header($prev->{TEXT}[0]);
816 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
817 parse_hunk_header($this->{TEXT}[0]);
819 my (@line, $i, $ofs, $o_cnt, $n_cnt);
820 $ofs = $o0_ofs;
821 $o_cnt = $n_cnt = 0;
822 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
823 my $line = $prev->{TEXT}[$i];
824 if ($line =~ /^\+/) {
825 $n_cnt++;
826 push @line, $line;
827 next;
830 last if ($o1_ofs <= $ofs);
832 $o_cnt++;
833 $ofs++;
834 if ($line =~ /^ /) {
835 $n_cnt++;
837 push @line, $line;
840 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
841 my $line = $this->{TEXT}[$i];
842 if ($line =~ /^\+/) {
843 $n_cnt++;
844 push @line, $line;
845 next;
847 $ofs++;
848 $o_cnt++;
849 if ($line =~ /^ /) {
850 $n_cnt++;
852 push @line, $line;
854 my $head = ("@@ -$o0_ofs" .
855 (($o_cnt != 1) ? ",$o_cnt" : '') .
856 " +$n0_ofs" .
857 (($n_cnt != 1) ? ",$n_cnt" : '') .
858 " @@\n");
859 @{$prev->{TEXT}} = ($head, @line);
862 sub coalesce_overlapping_hunks {
863 my (@in) = @_;
864 my @out = ();
866 my ($last_o_ctx, $last_was_dirty);
868 for (grep { $_->{USE} } @in) {
869 my $text = $_->{TEXT};
870 my ($o_ofs) = parse_hunk_header($text->[0]);
871 if (defined $last_o_ctx &&
872 $o_ofs <= $last_o_ctx &&
873 !$_->{DIRTY} &&
874 !$last_was_dirty) {
875 merge_hunk($out[-1], $_);
877 else {
878 push @out, $_;
880 $last_o_ctx = find_last_o_ctx($out[-1]);
881 $last_was_dirty = $_->{DIRTY};
883 return @out;
886 sub color_diff {
887 return map {
888 colored((/^@/ ? $fraginfo_color :
889 /^\+/ ? $diff_new_color :
890 /^-/ ? $diff_old_color :
891 $diff_plain_color),
892 $_);
893 } @_;
896 sub edit_hunk_manually {
897 my ($oldtext) = @_;
899 my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
900 my $fh;
901 open $fh, '>', $hunkfile
902 or die "failed to open hunk edit file for writing: " . $!;
903 print $fh "# Manual hunk edit mode -- see bottom for a quick guide\n";
904 print $fh @$oldtext;
905 my $participle = $patch_mode_flavour{PARTICIPLE};
906 print $fh <<EOF;
907 # ---
908 # To remove '-' lines, make them ' ' lines (context).
909 # To remove '+' lines, delete them.
910 # Lines starting with # will be removed.
912 # If the patch applies cleanly, the edited hunk will immediately be
913 # marked for $participle. If it does not apply cleanly, you will be given
914 # an opportunity to edit again. If all lines of the hunk are removed,
915 # then the edit is aborted and the hunk is left unchanged.
917 close $fh;
919 my $editor = $ENV{GIT_EDITOR} || $repo->config("core.editor")
920 || $ENV{VISUAL} || $ENV{EDITOR} || "vi";
921 system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
923 if ($? != 0) {
924 return undef;
927 open $fh, '<', $hunkfile
928 or die "failed to open hunk edit file for reading: " . $!;
929 my @newtext = grep { !/^#/ } <$fh>;
930 close $fh;
931 unlink $hunkfile;
933 # Abort if nothing remains
934 if (!grep { /\S/ } @newtext) {
935 return undef;
938 # Reinsert the first hunk header if the user accidentally deleted it
939 if ($newtext[0] !~ /^@/) {
940 unshift @newtext, $oldtext->[0];
942 return \@newtext;
945 sub diff_applies {
946 my $fh;
947 return run_git_apply($patch_mode_flavour{APPLY_CHECK} . ' --recount --check',
948 map { @{$_->{TEXT}} } @_);
951 sub _restore_terminal_and_die {
952 ReadMode 'restore';
953 print "\n";
954 exit 1;
957 sub prompt_single_character {
958 if ($use_readkey) {
959 local $SIG{TERM} = \&_restore_terminal_and_die;
960 local $SIG{INT} = \&_restore_terminal_and_die;
961 ReadMode 'cbreak';
962 my $key = ReadKey 0;
963 ReadMode 'restore';
964 print "$key" if defined $key;
965 print "\n";
966 return $key;
967 } else {
968 return <STDIN>;
972 sub prompt_yesno {
973 my ($prompt) = @_;
974 while (1) {
975 print colored $prompt_color, $prompt;
976 my $line = prompt_single_character;
977 return 0 if $line =~ /^n/i;
978 return 1 if $line =~ /^y/i;
982 sub edit_hunk_loop {
983 my ($head, $hunk, $ix) = @_;
984 my $text = $hunk->[$ix]->{TEXT};
986 while (1) {
987 $text = edit_hunk_manually($text);
988 if (!defined $text) {
989 return undef;
991 my $newhunk = {
992 TEXT => $text,
993 TYPE => $hunk->[$ix]->{TYPE},
994 USE => 1,
995 DIRTY => 1,
997 if (diff_applies($head,
998 @{$hunk}[0..$ix-1],
999 $newhunk,
1000 @{$hunk}[$ix+1..$#{$hunk}])) {
1001 $newhunk->{DISPLAY} = [color_diff(@{$text})];
1002 return $newhunk;
1004 else {
1005 prompt_yesno(
1006 'Your edited hunk does not apply. Edit again '
1007 . '(saying "no" discards!) [y/n]? '
1008 ) or return undef;
1013 sub help_patch_cmd {
1014 my $verb = lc $patch_mode_flavour{VERB};
1015 my $target = $patch_mode_flavour{TARGET};
1016 print colored $help_color, <<EOF ;
1017 y - $verb this hunk$target
1018 n - do not $verb this hunk$target
1019 q - quit, do not $verb this hunk nor any of the remaining ones
1020 a - $verb this and all the remaining hunks in the file
1021 d - do not $verb this hunk nor any of the remaining hunks in the file
1022 g - select a hunk to go to
1023 / - search for a hunk matching the given regex
1024 j - leave this hunk undecided, see next undecided hunk
1025 J - leave this hunk undecided, see next hunk
1026 k - leave this hunk undecided, see previous undecided hunk
1027 K - leave this hunk undecided, see previous hunk
1028 s - split the current hunk into smaller hunks
1029 e - manually edit the current hunk
1030 ? - print help
1034 sub apply_patch {
1035 my $cmd = shift;
1036 my $ret = run_git_apply $cmd . ' --recount', @_;
1037 if (!$ret) {
1038 print STDERR @_;
1040 return $ret;
1043 sub patch_update_cmd {
1044 my @all_mods = list_modified($patch_mode_flavour{FILTER});
1045 my @mods = grep { !($_->{BINARY}) } @all_mods;
1046 my @them;
1048 if (!@mods) {
1049 if (@all_mods) {
1050 print STDERR "Only binary files changed.\n";
1051 } else {
1052 print STDERR "No changes.\n";
1054 return 0;
1056 if ($patch_mode) {
1057 @them = @mods;
1059 else {
1060 @them = list_and_choose({ PROMPT => 'Patch update',
1061 HEADER => $status_head, },
1062 @mods);
1064 for (@them) {
1065 return 0 if patch_update_file($_->{VALUE});
1069 # Generate a one line summary of a hunk.
1070 sub summarize_hunk {
1071 my $rhunk = shift;
1072 my $summary = $rhunk->{TEXT}[0];
1074 # Keep the line numbers, discard extra context.
1075 $summary =~ s/@@(.*?)@@.*/$1 /s;
1076 $summary .= " " x (20 - length $summary);
1078 # Add some user context.
1079 for my $line (@{$rhunk->{TEXT}}) {
1080 if ($line =~ m/^[+-].*\w/) {
1081 $summary .= $line;
1082 last;
1086 chomp $summary;
1087 return substr($summary, 0, 80) . "\n";
1091 # Print a one-line summary of each hunk in the array ref in
1092 # the first argument, starting wih the index in the 2nd.
1093 sub display_hunks {
1094 my ($hunks, $i) = @_;
1095 my $ctr = 0;
1096 $i ||= 0;
1097 for (; $i < @$hunks && $ctr < 20; $i++, $ctr++) {
1098 my $status = " ";
1099 if (defined $hunks->[$i]{USE}) {
1100 $status = $hunks->[$i]{USE} ? "+" : "-";
1102 printf "%s%2d: %s",
1103 $status,
1104 $i + 1,
1105 summarize_hunk($hunks->[$i]);
1107 return $i;
1110 sub patch_update_file {
1111 my $quit = 0;
1112 my ($ix, $num);
1113 my $path = shift;
1114 my ($head, @hunk) = parse_diff($path);
1115 ($head, my $mode) = parse_diff_header($head);
1116 for (@{$head->{DISPLAY}}) {
1117 print;
1120 if (@{$mode->{TEXT}}) {
1121 unshift @hunk, $mode;
1124 $num = scalar @hunk;
1125 $ix = 0;
1127 while (1) {
1128 my ($prev, $next, $other, $undecided, $i);
1129 $other = '';
1131 if ($num <= $ix) {
1132 $ix = 0;
1134 for ($i = 0; $i < $ix; $i++) {
1135 if (!defined $hunk[$i]{USE}) {
1136 $prev = 1;
1137 $other .= ',k';
1138 last;
1141 if ($ix) {
1142 $other .= ',K';
1144 for ($i = $ix + 1; $i < $num; $i++) {
1145 if (!defined $hunk[$i]{USE}) {
1146 $next = 1;
1147 $other .= ',j';
1148 last;
1151 if ($ix < $num - 1) {
1152 $other .= ',J';
1154 if ($num > 1) {
1155 $other .= ',g';
1157 for ($i = 0; $i < $num; $i++) {
1158 if (!defined $hunk[$i]{USE}) {
1159 $undecided = 1;
1160 last;
1163 last if (!$undecided);
1165 if ($hunk[$ix]{TYPE} eq 'hunk' &&
1166 hunk_splittable($hunk[$ix]{TEXT})) {
1167 $other .= ',s';
1169 if ($hunk[$ix]{TYPE} eq 'hunk') {
1170 $other .= ',e';
1172 for (@{$hunk[$ix]{DISPLAY}}) {
1173 print;
1175 print colored $prompt_color, $patch_mode_flavour{VERB},
1176 ($hunk[$ix]{TYPE} eq 'mode' ? ' mode change' : ' this hunk'),
1177 $patch_mode_flavour{TARGET},
1178 " [y,n,q,a,d,/$other,?]? ";
1179 my $line = prompt_single_character;
1180 if ($line) {
1181 if ($line =~ /^y/i) {
1182 $hunk[$ix]{USE} = 1;
1184 elsif ($line =~ /^n/i) {
1185 $hunk[$ix]{USE} = 0;
1187 elsif ($line =~ /^a/i) {
1188 while ($ix < $num) {
1189 if (!defined $hunk[$ix]{USE}) {
1190 $hunk[$ix]{USE} = 1;
1192 $ix++;
1194 next;
1196 elsif ($other =~ /g/ && $line =~ /^g(.*)/) {
1197 my $response = $1;
1198 my $no = $ix > 10 ? $ix - 10 : 0;
1199 while ($response eq '') {
1200 my $extra = "";
1201 $no = display_hunks(\@hunk, $no);
1202 if ($no < $num) {
1203 $extra = " (<ret> to see more)";
1205 print "go to which hunk$extra? ";
1206 $response = <STDIN>;
1207 if (!defined $response) {
1208 $response = '';
1210 chomp $response;
1212 if ($response !~ /^\s*\d+\s*$/) {
1213 error_msg "Invalid number: '$response'\n";
1214 } elsif (0 < $response && $response <= $num) {
1215 $ix = $response - 1;
1216 } else {
1217 error_msg "Sorry, only $num hunks available.\n";
1219 next;
1221 elsif ($line =~ /^d/i) {
1222 while ($ix < $num) {
1223 if (!defined $hunk[$ix]{USE}) {
1224 $hunk[$ix]{USE} = 0;
1226 $ix++;
1228 next;
1230 elsif ($line =~ /^q/i) {
1231 while ($ix < $num) {
1232 if (!defined $hunk[$ix]{USE}) {
1233 $hunk[$ix]{USE} = 0;
1235 $ix++;
1237 $quit = 1;
1238 next;
1240 elsif ($line =~ m|^/(.*)|) {
1241 my $regex = $1;
1242 if ($1 eq "") {
1243 print colored $prompt_color, "search for regex? ";
1244 $regex = <STDIN>;
1245 if (defined $regex) {
1246 chomp $regex;
1249 my $search_string;
1250 eval {
1251 $search_string = qr{$regex}m;
1253 if ($@) {
1254 my ($err,$exp) = ($@, $1);
1255 $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1256 error_msg "Malformed search regexp $exp: $err\n";
1257 next;
1259 my $iy = $ix;
1260 while (1) {
1261 my $text = join ("", @{$hunk[$iy]{TEXT}});
1262 last if ($text =~ $search_string);
1263 $iy++;
1264 $iy = 0 if ($iy >= $num);
1265 if ($ix == $iy) {
1266 error_msg "No hunk matches the given pattern\n";
1267 last;
1270 $ix = $iy;
1271 next;
1273 elsif ($line =~ /^K/) {
1274 if ($other =~ /K/) {
1275 $ix--;
1277 else {
1278 error_msg "No previous hunk\n";
1280 next;
1282 elsif ($line =~ /^J/) {
1283 if ($other =~ /J/) {
1284 $ix++;
1286 else {
1287 error_msg "No next hunk\n";
1289 next;
1291 elsif ($line =~ /^k/) {
1292 if ($other =~ /k/) {
1293 while (1) {
1294 $ix--;
1295 last if (!$ix ||
1296 !defined $hunk[$ix]{USE});
1299 else {
1300 error_msg "No previous hunk\n";
1302 next;
1304 elsif ($line =~ /^j/) {
1305 if ($other !~ /j/) {
1306 error_msg "No next hunk\n";
1307 next;
1310 elsif ($other =~ /s/ && $line =~ /^s/) {
1311 my @split = split_hunk($hunk[$ix]{TEXT}, $hunk[$ix]{DISPLAY});
1312 if (1 < @split) {
1313 print colored $header_color, "Split into ",
1314 scalar(@split), " hunks.\n";
1316 splice (@hunk, $ix, 1, @split);
1317 $num = scalar @hunk;
1318 next;
1320 elsif ($other =~ /e/ && $line =~ /^e/) {
1321 my $newhunk = edit_hunk_loop($head, \@hunk, $ix);
1322 if (defined $newhunk) {
1323 splice @hunk, $ix, 1, $newhunk;
1326 else {
1327 help_patch_cmd($other);
1328 next;
1330 # soft increment
1331 while (1) {
1332 $ix++;
1333 last if ($ix >= $num ||
1334 !defined $hunk[$ix]{USE});
1339 @hunk = coalesce_overlapping_hunks(@hunk);
1341 my $n_lofs = 0;
1342 my @result = ();
1343 for (@hunk) {
1344 if ($_->{USE}) {
1345 push @result, @{$_->{TEXT}};
1349 if (@result) {
1350 my $fh;
1351 my @patch = (@{$head->{TEXT}}, @result);
1352 my $apply_routine = $patch_mode_flavour{APPLY};
1353 &$apply_routine(@patch);
1354 refresh();
1357 print "\n";
1358 return $quit;
1361 sub diff_cmd {
1362 my @mods = list_modified('index-only');
1363 @mods = grep { !($_->{BINARY}) } @mods;
1364 return if (!@mods);
1365 my (@them) = list_and_choose({ PROMPT => 'Review diff',
1366 IMMEDIATE => 1,
1367 HEADER => $status_head, },
1368 @mods);
1369 return if (!@them);
1370 my $reference = is_initial_commit() ? get_empty_tree() : 'HEAD';
1371 system(qw(git diff -p --cached), $reference, '--',
1372 map { $_->{VALUE} } @them);
1375 sub quit_cmd {
1376 print "Bye.\n";
1377 exit(0);
1380 sub help_cmd {
1381 print colored $help_color, <<\EOF ;
1382 status - show paths with changes
1383 update - add working tree state to the staged set of changes
1384 revert - revert staged set of changes back to the HEAD version
1385 patch - pick hunks and update selectively
1386 diff - view diff between HEAD and index
1387 add untracked - add contents of untracked files to the staged set of changes
1391 sub process_args {
1392 return unless @ARGV;
1393 my $arg = shift @ARGV;
1394 if ($arg eq "--patch") {
1395 $patch_mode = 1;
1396 $arg = shift @ARGV or die "missing --";
1397 die "invalid argument $arg, expecting --"
1398 unless $arg eq "--";
1400 elsif ($arg ne "--") {
1401 die "invalid argument $arg, expecting --";
1405 sub main_loop {
1406 my @cmd = ([ 'status', \&status_cmd, ],
1407 [ 'update', \&update_cmd, ],
1408 [ 'revert', \&revert_cmd, ],
1409 [ 'add untracked', \&add_untracked_cmd, ],
1410 [ 'patch', \&patch_update_cmd, ],
1411 [ 'diff', \&diff_cmd, ],
1412 [ 'quit', \&quit_cmd, ],
1413 [ 'help', \&help_cmd, ],
1415 while (1) {
1416 my ($it) = list_and_choose({ PROMPT => 'What now',
1417 SINGLETON => 1,
1418 LIST_FLAT => 4,
1419 HEADER => '*** Commands ***',
1420 ON_EOF => \&quit_cmd,
1421 IMMEDIATE => 1 }, @cmd);
1422 if ($it) {
1423 eval {
1424 $it->[1]->();
1426 if ($@) {
1427 print "$@";
1433 process_args();
1434 refresh();
1435 if ($patch_mode) {
1436 patch_update_cmd();
1438 else {
1439 status_cmd();
1440 main_loop();