git-add--interactive.perl 44.9 KB
Newer Older
1
#!/usr/bin/perl
J
Junio C Hamano 已提交
2

3
use 5.008;
J
Junio C Hamano 已提交
4
use strict;
5
use warnings;
6
use Git qw(unquote_path);
7
use Git::I18N;
J
Junio C Hamano 已提交
8

9 10
binmode(STDOUT, ":raw");

J
Junio C Hamano 已提交
11 12
my $repo = Git->repository();

13 14 15 16 17 18 19
my $menu_use_color = $repo->get_colorbool('color.interactive');
my ($prompt_color, $header_color, $help_color) =
	$menu_use_color ? (
		$repo->get_color('color.interactive.prompt', 'bold blue'),
		$repo->get_color('color.interactive.header', 'bold'),
		$repo->get_color('color.interactive.help', 'red bold'),
	) : ();
20 21
my $error_color = ();
if ($menu_use_color) {
22 23
	my $help_color_spec = ($repo->config('color.interactive.help') or
				'red bold');
24 25 26
	$error_color = $repo->get_color('color.interactive.error',
					$help_color_spec);
}
J
Junio C Hamano 已提交
27

28 29 30 31 32
my $diff_use_color = $repo->get_colorbool('color.diff');
my ($fraginfo_color) =
	$diff_use_color ? (
		$repo->get_color('color.diff.frag', 'cyan'),
	) : ();
33 34 35 36 37 38 39 40 41 42 43 44
my ($diff_plain_color) =
	$diff_use_color ? (
		$repo->get_color('color.diff.plain', ''),
	) : ();
my ($diff_old_color) =
	$diff_use_color ? (
		$repo->get_color('color.diff.old', 'red'),
	) : ();
my ($diff_new_color) =
	$diff_use_color ? (
		$repo->get_color('color.diff.new', 'green'),
	) : ();
J
Junio C Hamano 已提交
45

46
my $normal_color = $repo->get_color("", "reset");
J
Junio C Hamano 已提交
47

48
my $diff_algorithm = $repo->config('diff.algorithm');
49
my $diff_filter = $repo->config('interactive.difffilter');
50

51
my $use_readkey = 0;
52 53 54
my $use_termcap = 0;
my %term_escapes;

55 56
sub ReadMode;
sub ReadKey;
57 58
if ($repo->config_bool("interactive.singlekey")) {
	eval {
59 60
		require Term::ReadKey;
		Term::ReadKey->import;
61 62
		$use_readkey = 1;
	};
63 64 65
	if (!$use_readkey) {
		print STDERR "missing Term::ReadKey, disabling interactive.singlekey\n";
	}
66 67 68 69 70 71 72 73
	eval {
		require Term::Cap;
		my $termcap = Term::Cap->Tgetent;
		foreach (values %$termcap) {
			$term_escapes{$_} = 1 if /^\e/;
		}
		$use_termcap = 1;
	};
74 75
}

J
Junio C Hamano 已提交
76 77 78 79
sub colored {
	my $color = shift;
	my $string = join("", @_);

80
	if (defined $color) {
J
Junio C Hamano 已提交
81 82 83 84 85 86 87 88 89 90 91
		# Put a color code at the beginning of each line, a reset at the end
		# color after newlines that are not at the end of the string
		$string =~ s/(\n+)(.)/$1$color$2/g;
		# reset before newlines
		$string =~ s/(\n+)/$normal_color$1/g;
		# codes at beginning and end (if necessary):
		$string =~ s/^/$color/;
		$string =~ s/$/$normal_color/ unless $string =~ /\n$/;
	}
	return $string;
}
J
Junio C Hamano 已提交
92

93
# command line options
94
my $patch_mode_only;
95
my $patch_mode;
T
Thomas Rast 已提交
96
my $patch_mode_revision;
97

98
sub apply_patch;
T
Thomas Rast 已提交
99
sub apply_patch_for_checkout_commit;
T
Thomas Rast 已提交
100
sub apply_patch_for_stash;
101 102 103 104 105 106 107

my %patch_modes = (
	'stage' => {
		DIFF => 'diff-files -p',
		APPLY => sub { apply_patch 'apply --cached', @_; },
		APPLY_CHECK => 'apply --cached',
		FILTER => 'file-only',
108
		IS_REVERSE => 0,
109
	},
T
Thomas Rast 已提交
110 111 112 113 114
	'stash' => {
		DIFF => 'diff-index -p HEAD',
		APPLY => sub { apply_patch 'apply --cached', @_; },
		APPLY_CHECK => 'apply --cached',
		FILTER => undef,
115
		IS_REVERSE => 0,
T
Thomas Rast 已提交
116
	},
T
Thomas Rast 已提交
117 118 119 120 121
	'reset_head' => {
		DIFF => 'diff-index -p --cached',
		APPLY => sub { apply_patch 'apply -R --cached', @_; },
		APPLY_CHECK => 'apply -R --cached',
		FILTER => 'index-only',
122
		IS_REVERSE => 1,
T
Thomas Rast 已提交
123 124 125 126 127 128
	},
	'reset_nothead' => {
		DIFF => 'diff-index -R -p --cached',
		APPLY => sub { apply_patch 'apply --cached', @_; },
		APPLY_CHECK => 'apply --cached',
		FILTER => 'index-only',
129
		IS_REVERSE => 0,
T
Thomas Rast 已提交
130
	},
T
Thomas Rast 已提交
131 132 133 134 135
	'checkout_index' => {
		DIFF => 'diff-files -p',
		APPLY => sub { apply_patch 'apply -R', @_; },
		APPLY_CHECK => 'apply -R',
		FILTER => 'file-only',
136
		IS_REVERSE => 1,
T
Thomas Rast 已提交
137 138 139 140 141 142
	},
	'checkout_head' => {
		DIFF => 'diff-index -p',
		APPLY => sub { apply_patch_for_checkout_commit '-R', @_ },
		APPLY_CHECK => 'apply -R',
		FILTER => undef,
143
		IS_REVERSE => 1,
T
Thomas Rast 已提交
144 145 146 147 148 149
	},
	'checkout_nothead' => {
		DIFF => 'diff-index -R -p',
		APPLY => sub { apply_patch_for_checkout_commit '', @_ },
		APPLY_CHECK => 'apply',
		FILTER => undef,
150
		IS_REVERSE => 0,
T
Thomas Rast 已提交
151
	},
152 153 154 155 156 157 158 159 160 161 162 163 164 165
	'worktree_head' => {
		DIFF => 'diff-index -p',
		APPLY => sub { apply_patch 'apply -R', @_ },
		APPLY_CHECK => 'apply -R',
		FILTER => undef,
		IS_REVERSE => 1,
	},
	'worktree_nothead' => {
		DIFF => 'diff-index -R -p',
		APPLY => sub { apply_patch 'apply', @_ },
		APPLY_CHECK => 'apply',
		FILTER => undef,
		IS_REVERSE => 0,
	},
166 167
);

168 169
$patch_mode = 'stage';
my %patch_mode_flavour = %{$patch_modes{$patch_mode}};
170

J
Junio C Hamano 已提交
171
sub run_cmd_pipe {
172
	if ($^O eq 'MSWin32') {
173 174 175 176 177 178 179 180 181
		my @invalid = grep {m/[":*]/} @_;
		die "$^O does not support: @invalid\n" if @invalid;
		my @args = map { m/ /o ? "\"$_\"": $_ } @_;
		return qx{@args};
	} else {
		my $fh = undef;
		open($fh, '-|', @_) or die;
		return <$fh>;
	}
J
Junio C Hamano 已提交
182 183 184 185 186 187 188 189 190 191 192
}

my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));

if (!defined $GIT_DIR) {
	exit(1); # rev-parse would have already said "not a git repo"
}
chomp($GIT_DIR);

sub refresh {
	my $fh;
193
	open $fh, 'git update-index --refresh |'
J
Junio C Hamano 已提交
194 195 196 197 198 199 200 201 202 203
	    or die;
	while (<$fh>) {
		;# ignore 'needs update'
	}
	close $fh;
}

sub list_untracked {
	map {
		chomp $_;
204
		unquote_path($_);
J
Junio C Hamano 已提交
205
	}
206
	run_cmd_pipe(qw(git ls-files --others --exclude-standard --), @ARGV);
J
Junio C Hamano 已提交
207 208
}

209 210 211
# TRANSLATORS: you can adjust this to align "git add -i" status menu
my $status_fmt = __('%12s %12s %s');
my $status_head = sprintf($status_fmt, __('staged'), __('unstaged'), __('path'));
J
Junio C Hamano 已提交
212

213 214 215 216 217 218 219 220 221
{
	my $initial;
	sub is_initial_commit {
		$initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
			unless defined $initial;
		return $initial;
	}
}

222 223 224 225 226 227 228 229 230
{
	my $empty_tree;
	sub get_empty_tree {
		return $empty_tree if defined $empty_tree;

		$empty_tree = run_cmd_pipe(qw(git hash-object -t tree /dev/null));
		chomp $empty_tree;
		return $empty_tree;
	}
231 232
}

233 234 235 236 237 238 239 240 241 242 243
sub get_diff_reference {
	my $ref = shift;
	if (defined $ref and $ref ne 'HEAD') {
		return $ref;
	} elsif (is_initial_commit()) {
		return get_empty_tree();
	} else {
		return 'HEAD';
	}
}

J
Junio C Hamano 已提交
244 245 246 247 248 249 250
# Returns list of hashes, contents of each of which are:
# VALUE:	pathname
# BINARY:	is a binary path
# INDEX:	is index different from HEAD?
# FILE:		is file different from index?
# INDEX_ADDDEL:	is it add/delete between HEAD and index?
# FILE_ADDDEL:	is it add/delete between index and file?
251
# UNMERGED:	is the path unmerged
J
Junio C Hamano 已提交
252 253 254 255 256 257

sub list_modified {
	my ($only) = @_;
	my (%data, @return);
	my ($add, $del, $adddel, $file);

258
	my $reference = get_diff_reference($patch_mode_revision);
J
Junio C Hamano 已提交
259
	for (run_cmd_pipe(qw(git diff-index --cached
260
			     --numstat --summary), $reference,
261
			     '--', @ARGV)) {
J
Junio C Hamano 已提交
262 263 264
		if (($add, $del, $file) =
		    /^([-\d]+)	([-\d]+)	(.*)/) {
			my ($change, $bin);
265
			$file = unquote_path($file);
J
Junio C Hamano 已提交
266
			if ($add eq '-' && $del eq '-') {
267
				$change = __('binary');
J
Junio C Hamano 已提交
268 269 270 271 272 273 274 275
				$bin = 1;
			}
			else {
				$change = "+$add/-$del";
			}
			$data{$file} = {
				INDEX => $change,
				BINARY => $bin,
276
				FILE => __('nothing'),
J
Junio C Hamano 已提交
277 278 279 280
			}
		}
		elsif (($adddel, $file) =
		       /^ (create|delete) mode [0-7]+ (.*)$/) {
281
			$file = unquote_path($file);
J
Junio C Hamano 已提交
282 283 284 285
			$data{$file}{INDEX_ADDDEL} = $adddel;
		}
	}

286
	for (run_cmd_pipe(qw(git diff-files --ignore-submodules=dirty --numstat --summary --raw --), @ARGV)) {
J
Junio C Hamano 已提交
287 288
		if (($add, $del, $file) =
		    /^([-\d]+)	([-\d]+)	(.*)/) {
289
			$file = unquote_path($file);
J
Junio C Hamano 已提交
290 291
			my ($change, $bin);
			if ($add eq '-' && $del eq '-') {
292
				$change = __('binary');
J
Junio C Hamano 已提交
293 294 295 296 297 298 299 300 301 302 303 304
				$bin = 1;
			}
			else {
				$change = "+$add/-$del";
			}
			$data{$file}{FILE} = $change;
			if ($bin) {
				$data{$file}{BINARY} = 1;
			}
		}
		elsif (($adddel, $file) =
		       /^ (create|delete) mode [0-7]+ (.*)$/) {
305
			$file = unquote_path($file);
J
Junio C Hamano 已提交
306 307
			$data{$file}{FILE_ADDDEL} = $adddel;
		}
308 309 310 311
		elsif (/^:[0-7]+ [0-7]+ [0-9a-f]+ [0-9a-f]+ (.)	(.*)$/) {
			$file = unquote_path($2);
			if (!exists $data{$file}) {
				$data{$file} = +{
312
					INDEX => __('unchanged'),
313 314 315 316 317 318 319
					BINARY => 0,
				};
			}
			if ($1 eq 'U') {
				$data{$file}{UNMERGED} = 1;
			}
		}
J
Junio C Hamano 已提交
320 321 322 323 324 325 326
	}

	for (sort keys %data) {
		my $it = $data{$_};

		if ($only) {
			if ($only eq 'index-only') {
327
				next if ($it->{INDEX} eq __('unchanged'));
J
Junio C Hamano 已提交
328 329
			}
			if ($only eq 'file-only') {
330
				next if ($it->{FILE} eq __('nothing'));
J
Junio C Hamano 已提交
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
			}
		}
		push @return, +{
			VALUE => $_,
			%$it,
		};
	}
	return @return;
}

sub find_unique {
	my ($string, @stuff) = @_;
	my $found = undef;
	for (my $i = 0; $i < @stuff; $i++) {
		my $it = $stuff[$i];
		my $hit = undef;
		if (ref $it) {
			if ((ref $it) eq 'ARRAY') {
				$it = $it->[0];
			}
			else {
				$it = $it->{VALUE};
			}
		}
		eval {
			if ($it =~ /^$string/) {
				$hit = 1;
			};
		};
		if (defined $hit && defined $found) {
			return undef;
		}
		if ($hit) {
			$found = $i + 1;
		}
	}
	return $found;
}

370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
# inserts string into trie and updates count for each character
sub update_trie {
	my ($trie, $string) = @_;
	foreach (split //, $string) {
		$trie = $trie->{$_} ||= {COUNT => 0};
		$trie->{COUNT}++;
	}
}

# returns an array of tuples (prefix, remainder)
sub find_unique_prefixes {
	my @stuff = @_;
	my @return = ();

	# any single prefix exceeding the soft limit is omitted
	# if any prefix exceeds the hard limit all are omitted
	# 0 indicates no limit
	my $soft_limit = 0;
	my $hard_limit = 3;

	# build a trie modelling all possible options
	my %trie;
	foreach my $print (@stuff) {
		if ((ref $print) eq 'ARRAY') {
			$print = $print->[0];
		}
396
		elsif ((ref $print) eq 'HASH') {
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
			$print = $print->{VALUE};
		}
		update_trie(\%trie, $print);
		push @return, $print;
	}

	# use the trie to find the unique prefixes
	for (my $i = 0; $i < @return; $i++) {
		my $ret = $return[$i];
		my @letters = split //, $ret;
		my %search = %trie;
		my ($prefix, $remainder);
		my $j;
		for ($j = 0; $j < @letters; $j++) {
			my $letter = $letters[$j];
			if ($search{$letter}{COUNT} == 1) {
				$prefix = substr $ret, 0, $j + 1;
				$remainder = substr $ret, $j + 1;
				last;
			}
			else {
				my $prefix = substr $ret, 0, $j;
				return ()
				    if ($hard_limit && $j + 1 > $hard_limit);
			}
			%search = %{$search{$letter}};
		}
424 425
		if (ord($letters[0]) > 127 ||
		    ($soft_limit && $j + 1 > $soft_limit)) {
426 427 428 429 430 431 432 433
			$prefix = undef;
			$remainder = $ret;
		}
		$return[$i] = [$prefix, $remainder];
	}
	return @return;
}

434 435 436 437 438 439 440
# filters out prefixes which have special meaning to list_and_choose()
sub is_valid_prefix {
	my $prefix = shift;
	return (defined $prefix) &&
	    !($prefix =~ /[\s,]/) && # separators
	    !($prefix =~ /^-/) &&    # deselection
	    !($prefix =~ /^\d+/) &&  # selection
441 442
	    ($prefix ne '*') &&      # "all" wildcard
	    ($prefix ne '?');        # prompt help
443 444
}

445 446 447 448 449
# given a prefix/remainder tuple return a string with the prefix highlighted
# for now use square brackets; later might use ANSI colors (underline, bold)
sub highlight_prefix {
	my $prefix = shift;
	my $remainder = shift;
J
Junio C Hamano 已提交
450 451 452 453 454 455 456 457 458

	if (!defined $prefix) {
		return $remainder;
	}

	if (!is_valid_prefix($prefix)) {
		return "$prefix$remainder";
	}

459
	if (!$menu_use_color) {
J
Junio C Hamano 已提交
460 461 462 463
		return "[$prefix]$remainder";
	}

	return "$prompt_color$prefix$normal_color$remainder";
464 465
}

466 467 468 469
sub error_msg {
	print STDERR colored $error_color, @_;
}

J
Junio C Hamano 已提交
470 471 472
sub list_and_choose {
	my ($opts, @stuff) = @_;
	my (@chosen, @return);
473 474 475
	if (!@stuff) {
	    return @return;
	}
J
Junio C Hamano 已提交
476
	my $i;
477
	my @prefixes = find_unique_prefixes(@stuff) unless $opts->{LIST_ONLY};
J
Junio C Hamano 已提交
478 479 480 481 482 483 484 485 486

      TOPLOOP:
	while (1) {
		my $last_lf = 0;

		if ($opts->{HEADER}) {
			if (!$opts->{LIST_FLAT}) {
				print "     ";
			}
J
Junio C Hamano 已提交
487
			print colored $header_color, "$opts->{HEADER}\n";
J
Junio C Hamano 已提交
488 489 490 491
		}
		for ($i = 0; $i < @stuff; $i++) {
			my $chosen = $chosen[$i] ? '*' : ' ';
			my $print = $stuff[$i];
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
			my $ref = ref $print;
			my $highlighted = highlight_prefix(@{$prefixes[$i]})
			    if @prefixes;
			if ($ref eq 'ARRAY') {
				$print = $highlighted || $print->[0];
			}
			elsif ($ref eq 'HASH') {
				my $value = $highlighted || $print->{VALUE};
				$print = sprintf($status_fmt,
				    $print->{INDEX},
				    $print->{FILE},
				    $value);
			}
			else {
				$print = $highlighted || $print;
J
Junio C Hamano 已提交
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
			}
			printf("%s%2d: %s", $chosen, $i+1, $print);
			if (($opts->{LIST_FLAT}) &&
			    (($i + 1) % ($opts->{LIST_FLAT}))) {
				print "\t";
				$last_lf = 0;
			}
			else {
				print "\n";
				$last_lf = 1;
			}
		}
		if (!$last_lf) {
			print "\n";
		}

		return if ($opts->{LIST_ONLY});

J
Junio C Hamano 已提交
525
		print colored $prompt_color, $opts->{PROMPT};
J
Junio C Hamano 已提交
526 527 528 529 530 531 532
		if ($opts->{SINGLETON}) {
			print "> ";
		}
		else {
			print ">> ";
		}
		my $line = <STDIN>;
533 534 535 536 537
		if (!$line) {
			print "\n";
			$opts->{ON_EOF}->() if $opts->{ON_EOF};
			last;
		}
J
Junio C Hamano 已提交
538
		chomp $line;
539
		last if $line eq '';
540 541 542 543 544 545
		if ($line eq '?') {
			$opts->{SINGLETON} ?
			    singleton_prompt_help_cmd() :
			    prompt_help_cmd();
			next TOPLOOP;
		}
J
Junio C Hamano 已提交
546 547 548 549 550 551 552 553
		for my $choice (split(/[\s,]+/, $line)) {
			my $choose = 1;
			my ($bottom, $top);

			# Input that begins with '-'; unchoose
			if ($choice =~ s/^-//) {
				$choose = 0;
			}
554 555 556
			# A range can be specified like 5-7 or 5-.
			if ($choice =~ /^(\d+)-(\d*)$/) {
				($bottom, $top) = ($1, length($2) ? $2 : 1 + @stuff);
J
Junio C Hamano 已提交
557 558 559 560 561 562 563 564 565 566 567
			}
			elsif ($choice =~ /^\d+$/) {
				$bottom = $top = $choice;
			}
			elsif ($choice eq '*') {
				$bottom = 1;
				$top = 1 + @stuff;
			}
			else {
				$bottom = $top = find_unique($choice, @stuff);
				if (!defined $bottom) {
568
					error_msg sprintf(__("Huh (%s)?\n"), $choice);
J
Junio C Hamano 已提交
569 570 571 572
					next TOPLOOP;
				}
			}
			if ($opts->{SINGLETON} && $bottom != $top) {
573
				error_msg sprintf(__("Huh (%s)?\n"), $choice);
J
Junio C Hamano 已提交
574 575 576
				next TOPLOOP;
			}
			for ($i = $bottom-1; $i <= $top-1; $i++) {
577
				next if (@stuff <= $i || $i < 0);
J
Junio C Hamano 已提交
578 579 580
				$chosen[$i] = $choose;
			}
		}
581
		last if ($opts->{IMMEDIATE} || $line eq '*');
J
Junio C Hamano 已提交
582 583 584 585 586 587 588 589 590
	}
	for ($i = 0; $i < @stuff; $i++) {
		if ($chosen[$i]) {
			push @return, $stuff[$i];
		}
	}
	return @return;
}

591
sub singleton_prompt_help_cmd {
592
	print colored $help_color, __ <<'EOF' ;
593 594 595 596 597 598 599 600
Prompt help:
1          - select a numbered item
foo        - select item based on unique prefix
           - (empty) select nothing
EOF
}

sub prompt_help_cmd {
601
	print colored $help_color, __ <<'EOF' ;
602 603 604 605 606 607 608 609 610 611 612
Prompt help:
1          - select a single item
3-5        - select a range of items
2-3,6-9    - select multiple ranges
foo        - select item based on unique prefix
-...       - unselect specified items
*          - choose all items
           - (empty) finish selecting
EOF
}

J
Junio C Hamano 已提交
613 614 615 616 617 618 619 620 621
sub status_cmd {
	list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
			list_modified());
	print "\n";
}

sub say_n_paths {
	my $did = shift @_;
	my $cnt = scalar @_;
622 623 624 625 626 627 628 629 630 631 632 633
	if ($did eq 'added') {
		printf(__n("added %d path\n", "added %d paths\n",
			   $cnt), $cnt);
	} elsif ($did eq 'updated') {
		printf(__n("updated %d path\n", "updated %d paths\n",
			   $cnt), $cnt);
	} elsif ($did eq 'reverted') {
		printf(__n("reverted %d path\n", "reverted %d paths\n",
			   $cnt), $cnt);
	} else {
		printf(__n("touched %d path\n", "touched %d paths\n",
			   $cnt), $cnt);
J
Junio C Hamano 已提交
634 635 636 637 638 639 640
	}
}

sub update_cmd {
	my @mods = list_modified('file-only');
	return if (!@mods);

641
	my @update = list_and_choose({ PROMPT => __('Update'),
J
Junio C Hamano 已提交
642 643 644
				       HEADER => $status_head, },
				     @mods);
	if (@update) {
645
		system(qw(git update-index --add --remove --),
J
Junio C Hamano 已提交
646 647 648 649 650 651 652
		       map { $_->{VALUE} } @update);
		say_n_paths('updated', @update);
	}
	print "\n";
}

sub revert_cmd {
653
	my @update = list_and_choose({ PROMPT => __('Revert'),
J
Junio C Hamano 已提交
654 655 656
				       HEADER => $status_head, },
				     list_modified());
	if (@update) {
657 658 659
		if (is_initial_commit()) {
			system(qw(git rm --cached),
				map { $_->{VALUE} } @update);
J
Junio C Hamano 已提交
660
		}
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
		else {
			my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
						 map { $_->{VALUE} } @update);
			my $fh;
			open $fh, '| git update-index --index-info'
			    or die;
			for (@lines) {
				print $fh $_;
			}
			close($fh);
			for (@update) {
				if ($_->{INDEX_ADDDEL} &&
				    $_->{INDEX_ADDDEL} eq 'create') {
					system(qw(git update-index --force-remove --),
					       $_->{VALUE});
676
					printf(__("note: %s is untracked now.\n"), $_->{VALUE});
677
				}
J
Junio C Hamano 已提交
678 679 680 681 682 683 684 685 686
			}
		}
		refresh();
		say_n_paths('reverted', @update);
	}
	print "\n";
}

sub add_untracked_cmd {
687
	my @add = list_and_choose({ PROMPT => __('Add untracked') },
J
Junio C Hamano 已提交
688 689 690 691
				  list_untracked());
	if (@add) {
		system(qw(git update-index --add --), @add);
		say_n_paths('added', @add);
692
	} else {
693
		print __("No untracked files.\n");
J
Junio C Hamano 已提交
694 695 696 697
	}
	print "\n";
}

698 699 700
sub run_git_apply {
	my $cmd = shift;
	my $fh;
701
	open $fh, '| git ' . $cmd . " --allow-overlap";
702 703 704 705
	print $fh @_;
	return close $fh;
}

J
Junio C Hamano 已提交
706 707
sub parse_diff {
	my ($path) = @_;
708
	my @diff_cmd = split(" ", $patch_mode_flavour{DIFF});
709
	if (defined $diff_algorithm) {
710
		splice @diff_cmd, 1, 0, "--diff-algorithm=${diff_algorithm}";
711
	}
T
Thomas Rast 已提交
712
	if (defined $patch_mode_revision) {
713
		push @diff_cmd, get_diff_reference($patch_mode_revision);
T
Thomas Rast 已提交
714
	}
715
	my @diff = run_cmd_pipe("git", @diff_cmd, "--", $path);
716 717
	my @colored = ();
	if ($diff_use_color) {
718 719 720 721 722 723 724 725
		my @display_cmd = ("git", @diff_cmd, qw(--color --), $path);
		if (defined $diff_filter) {
			# quotemeta is overkill, but sufficient for shell-quoting
			my $diff = join(' ', map { quotemeta } @display_cmd);
			@display_cmd = ("$diff | $diff_filter");
		}

		@colored = run_cmd_pipe(@display_cmd);
J
Junio C Hamano 已提交
726
	}
727
	my (@hunk) = { TEXT => [], DISPLAY => [], TYPE => 'header' };
J
Junio C Hamano 已提交
728

729 730 731 732 733 734 735 736
	if (@colored && @colored != @diff) {
		print STDERR
		  "fatal: mismatched output from interactive.diffFilter\n",
		  "hint: Your filter must maintain a one-to-one correspondence\n",
		  "hint: between its input and output lines.\n";
		exit 1;
	}

737 738
	for (my $i = 0; $i < @diff; $i++) {
		if ($diff[$i] =~ /^@@ /) {
739 740
			push @hunk, { TEXT => [], DISPLAY => [],
				TYPE => 'hunk' };
J
Junio C Hamano 已提交
741
		}
742 743
		push @{$hunk[-1]{TEXT}}, $diff[$i];
		push @{$hunk[-1]{DISPLAY}},
744
			(@colored ? $colored[$i] : $diff[$i]);
J
Junio C Hamano 已提交
745
	}
746
	return @hunk;
J
Junio C Hamano 已提交
747 748
}

749 750 751
sub parse_diff_header {
	my $src = shift;

752 753
	my $head = { TEXT => [], DISPLAY => [], TYPE => 'header' };
	my $mode = { TEXT => [], DISPLAY => [], TYPE => 'mode' };
754
	my $deletion = { TEXT => [], DISPLAY => [], TYPE => 'deletion' };
755 756

	for (my $i = 0; $i < @{$src->{TEXT}}; $i++) {
757 758 759 760
		my $dest =
		   $src->{TEXT}->[$i] =~ /^(old|new) mode (\d+)$/ ? $mode :
		   $src->{TEXT}->[$i] =~ /^deleted file/ ? $deletion :
		   $head;
761 762 763
		push @{$dest->{TEXT}}, $src->{TEXT}->[$i];
		push @{$dest->{DISPLAY}}, $src->{DISPLAY}->[$i];
	}
764
	return ($head, $mode, $deletion);
765 766
}

767 768 769 770 771 772 773 774 775 776
sub hunk_splittable {
	my ($text) = @_;

	my @s = split_hunk($text);
	return (1 < @s);
}

sub parse_hunk_header {
	my ($line) = @_;
	my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
777 778 779
	    $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
	$o_cnt = 1 unless defined $o_cnt;
	$n_cnt = 1 unless defined $n_cnt;
780 781 782
	return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
}

783 784 785 786 787 788 789 790 791
sub format_hunk_header {
	my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) = @_;
	return ("@@ -$o_ofs" .
		(($o_cnt != 1) ? ",$o_cnt" : '') .
		" +$n_ofs" .
		(($n_cnt != 1) ? ",$n_cnt" : '') .
		" @@\n");
}

792
sub split_hunk {
793
	my ($text, $display) = @_;
794
	my @split = ();
795 796 797
	if (!defined $display) {
		$display = $text;
	}
798 799 800 801
	# If there are context lines in the middle of a hunk,
	# it can be split, but we would need to take care of
	# overlaps later.

802
	my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
803 804 805 806 807 808 809 810
	my $hunk_start = 1;

      OUTER:
	while (1) {
		my $next_hunk_start = undef;
		my $i = $hunk_start - 1;
		my $this = +{
			TEXT => [],
811
			DISPLAY => [],
812
			TYPE => 'hunk',
813 814 815 816 817 818
			OLD => $o_ofs,
			NEW => $n_ofs,
			OCNT => 0,
			NCNT => 0,
			ADDDEL => 0,
			POSTCTX => 0,
819
			USE => undef,
820 821 822 823
		};

		while (++$i < @$text) {
			my $line = $text->[$i];
824
			my $display = $display->[$i];
825 826 827 828 829
			if ($line =~ /^\\/) {
				push @{$this->{TEXT}}, $line;
				push @{$this->{DISPLAY}}, $display;
				next;
			}
830 831 832 833 834 835 836 837 838 839 840
			if ($line =~ /^ /) {
				if ($this->{ADDDEL} &&
				    !defined $next_hunk_start) {
					# We have seen leading context and
					# adds/dels and then here is another
					# context, which is trailing for this
					# split hunk and leading for the next
					# one.
					$next_hunk_start = $i;
				}
				push @{$this->{TEXT}}, $line;
841
				push @{$this->{DISPLAY}}, $display;
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
				$this->{OCNT}++;
				$this->{NCNT}++;
				if (defined $next_hunk_start) {
					$this->{POSTCTX}++;
				}
				next;
			}

			# add/del
			if (defined $next_hunk_start) {
				# We are done with the current hunk and
				# this is the first real change for the
				# next split one.
				$hunk_start = $next_hunk_start;
				$o_ofs = $this->{OLD} + $this->{OCNT};
				$n_ofs = $this->{NEW} + $this->{NCNT};
				$o_ofs -= $this->{POSTCTX};
				$n_ofs -= $this->{POSTCTX};
				push @split, $this;
				redo OUTER;
			}
			push @{$this->{TEXT}}, $line;
864
			push @{$this->{DISPLAY}}, $display;
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
			$this->{ADDDEL}++;
			if ($line =~ /^-/) {
				$this->{OCNT}++;
			}
			else {
				$this->{NCNT}++;
			}
		}

		push @split, $this;
		last;
	}

	for my $hunk (@split) {
		$o_ofs = $hunk->{OLD};
		$n_ofs = $hunk->{NEW};
881 882
		my $o_cnt = $hunk->{OCNT};
		my $n_cnt = $hunk->{NCNT};
883

884
		my $head = format_hunk_header($o_ofs, $o_cnt, $n_ofs, $n_cnt);
885
		my $display_head = $head;
886
		unshift @{$hunk->{TEXT}}, $head;
887 888 889 890
		if ($diff_use_color) {
			$display_head = colored($fraginfo_color, $head);
		}
		unshift @{$hunk->{DISPLAY}}, $display_head;
891
	}
892
	return @split;
893 894
}

895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
sub find_last_o_ctx {
	my ($it) = @_;
	my $text = $it->{TEXT};
	my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
	my $i = @{$text};
	my $last_o_ctx = $o_ofs + $o_cnt;
	while (0 < --$i) {
		my $line = $text->[$i];
		if ($line =~ /^ /) {
			$last_o_ctx--;
			next;
		}
		last;
	}
	return $last_o_ctx;
}

sub merge_hunk {
	my ($prev, $this) = @_;
	my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
	    parse_hunk_header($prev->{TEXT}[0]);
	my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
	    parse_hunk_header($this->{TEXT}[0]);

	my (@line, $i, $ofs, $o_cnt, $n_cnt);
	$ofs = $o0_ofs;
	$o_cnt = $n_cnt = 0;
	for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
		my $line = $prev->{TEXT}[$i];
		if ($line =~ /^\+/) {
			$n_cnt++;
			push @line, $line;
			next;
928 929 930
		} elsif ($line =~ /^\\/) {
			push @line, $line;
			next;
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
		}

		last if ($o1_ofs <= $ofs);

		$o_cnt++;
		$ofs++;
		if ($line =~ /^ /) {
			$n_cnt++;
		}
		push @line, $line;
	}

	for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
		my $line = $this->{TEXT}[$i];
		if ($line =~ /^\+/) {
			$n_cnt++;
			push @line, $line;
			next;
949 950 951
		} elsif ($line =~ /^\\/) {
			push @line, $line;
			next;
952 953 954 955 956 957 958 959
		}
		$ofs++;
		$o_cnt++;
		if ($line =~ /^ /) {
			$n_cnt++;
		}
		push @line, $line;
	}
960
	my $head = format_hunk_header($o0_ofs, $o_cnt, $n0_ofs, $n_cnt);
961 962 963 964 965 966 967 968
	@{$prev->{TEXT}} = ($head, @line);
}

sub coalesce_overlapping_hunks {
	my (@in) = @_;
	my @out = ();

	my ($last_o_ctx, $last_was_dirty);
969
	my $ofs_delta = 0;
970

971
	for (@in) {
972 973 974 975
		if ($_->{TYPE} ne 'hunk') {
			push @out, $_;
			next;
		}
976
		my $text = $_->{TEXT};
977 978 979 980
		my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
						parse_hunk_header($text->[0]);
		unless ($_->{USE}) {
			$ofs_delta += $o_cnt - $n_cnt;
981 982 983 984 985
			# If this hunk has been edited then subtract
			# the delta that is due to the edit.
			if ($_->{OFS_DELTA}) {
				$ofs_delta -= $_->{OFS_DELTA};
			}
986 987 988 989 990 991 992
			next;
		}
		if ($ofs_delta) {
			$n_ofs += $ofs_delta;
			$_->{TEXT}->[0] = format_hunk_header($o_ofs, $o_cnt,
							     $n_ofs, $n_cnt);
		}
993 994 995 996 997
		# If this hunk was edited then adjust the offset delta
		# to reflect the edit.
		if ($_->{OFS_DELTA}) {
			$ofs_delta += $_->{OFS_DELTA};
		}
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
		if (defined $last_o_ctx &&
		    $o_ofs <= $last_o_ctx &&
		    !$_->{DIRTY} &&
		    !$last_was_dirty) {
			merge_hunk($out[-1], $_);
		}
		else {
			push @out, $_;
		}
		$last_o_ctx = find_last_o_ctx($out[-1]);
		$last_was_dirty = $_->{DIRTY};
	}
	return @out;
}
1012

1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
sub reassemble_patch {
	my $head = shift;
	my @patch;

	# Include everything in the header except the beginning of the diff.
	push @patch, (grep { !/^[-+]{3}/ } @$head);

	# Then include any headers from the hunk lines, which must
	# come before any actual hunk.
	while (@_ && $_[0] !~ /^@/) {
		push @patch, shift;
	}

	# Then begin the diff.
	push @patch, grep { /^[-+]{3}/ } @$head;

	# And then the actual hunks.
	push @patch, @_;

	return @patch;
}

1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
sub color_diff {
	return map {
		colored((/^@/  ? $fraginfo_color :
			 /^\+/ ? $diff_new_color :
			 /^-/  ? $diff_old_color :
			 $diff_plain_color),
			$_);
	} @_;
}

1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
my %edit_hunk_manually_modes = (
	stage => N__(
"If the patch applies cleanly, the edited hunk will immediately be
marked for staging."),
	stash => N__(
"If the patch applies cleanly, the edited hunk will immediately be
marked for stashing."),
	reset_head => N__(
"If the patch applies cleanly, the edited hunk will immediately be
marked for unstaging."),
	reset_nothead => N__(
"If the patch applies cleanly, the edited hunk will immediately be
marked for applying."),
	checkout_index => N__(
"If the patch applies cleanly, the edited hunk will immediately be
1060
marked for discarding."),
1061 1062 1063 1064 1065
	checkout_head => N__(
"If the patch applies cleanly, the edited hunk will immediately be
marked for discarding."),
	checkout_nothead => N__(
"If the patch applies cleanly, the edited hunk will immediately be
1066 1067 1068 1069 1070 1071
marked for applying."),
	worktree_head => N__(
"If the patch applies cleanly, the edited hunk will immediately be
marked for discarding."),
	worktree_nothead => N__(
"If the patch applies cleanly, the edited hunk will immediately be
1072 1073 1074
marked for applying."),
);

1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
sub recount_edited_hunk {
	local $_;
	my ($oldtext, $newtext) = @_;
	my ($o_cnt, $n_cnt) = (0, 0);
	for (@{$newtext}[1..$#{$newtext}]) {
		my $mode = substr($_, 0, 1);
		if ($mode eq '-') {
			$o_cnt++;
		} elsif ($mode eq '+') {
			$n_cnt++;
1085
		} elsif ($mode eq ' ' or $mode eq "\n") {
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
			$o_cnt++;
			$n_cnt++;
		}
	}
	my ($o_ofs, undef, $n_ofs, undef) =
					parse_hunk_header($newtext->[0]);
	$newtext->[0] = format_hunk_header($o_ofs, $o_cnt, $n_ofs, $n_cnt);
	my (undef, $orig_o_cnt, undef, $orig_n_cnt) =
					parse_hunk_header($oldtext->[0]);
	# Return the change in the number of lines inserted by this hunk
	return $orig_o_cnt - $orig_n_cnt - $o_cnt + $n_cnt;
}

1099 1100 1101 1102 1103 1104
sub edit_hunk_manually {
	my ($oldtext) = @_;

	my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
	my $fh;
	open $fh, '>', $hunkfile
1105
		or die sprintf(__("failed to open hunk edit file for writing: %s"), $!);
1106
	print $fh Git::comment_lines __("Manual hunk edit mode -- see bottom for a quick guide.\n");
1107
	print $fh @$oldtext;
1108 1109
	my $is_reverse = $patch_mode_flavour{IS_REVERSE};
	my ($remove_plus, $remove_minus) = $is_reverse ? ('-', '+') : ('+', '-');
1110 1111 1112 1113 1114 1115
	my $comment_line_char = Git::get_comment_line_char;
	print $fh Git::comment_lines sprintf(__ <<EOF, $remove_minus, $remove_plus, $comment_line_char),
---
To remove '%s' lines, make them ' ' lines (context).
To remove '%s' lines, delete them.
Lines starting with %s will be removed.
1116
EOF
1117 1118 1119 1120 1121 1122 1123
__($edit_hunk_manually_modes{$patch_mode}),
# TRANSLATORS: 'it' refers to the patch mentioned in the previous messages.
__ <<EOF2 ;
If it does not apply cleanly, you will be given an opportunity to
edit again.  If all lines of the hunk are removed, then the edit is
aborted and the hunk is left unchanged.
EOF2
1124 1125
	close $fh;

1126
	chomp(my $editor = run_cmd_pipe(qw(git var GIT_EDITOR)));
1127 1128
	system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);

1129 1130 1131 1132
	if ($? != 0) {
		return undef;
	}

1133
	open $fh, '<', $hunkfile
1134
		or die sprintf(__("failed to open hunk edit file for reading: %s"), $!);
1135
	my @newtext = grep { !/^\Q$comment_line_char\E/ } <$fh>;
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
	close $fh;
	unlink $hunkfile;

	# Abort if nothing remains
	if (!grep { /\S/ } @newtext) {
		return undef;
	}

	# Reinsert the first hunk header if the user accidentally deleted it
	if ($newtext[0] !~ /^@/) {
		unshift @newtext, $oldtext->[0];
	}
	return \@newtext;
}

sub diff_applies {
1152
	return run_git_apply($patch_mode_flavour{APPLY_CHECK} . ' --check',
1153
			     map { @{$_->{TEXT}} } @_);
1154 1155
}

1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
sub _restore_terminal_and_die {
	ReadMode 'restore';
	print "\n";
	exit 1;
}

sub prompt_single_character {
	if ($use_readkey) {
		local $SIG{TERM} = \&_restore_terminal_and_die;
		local $SIG{INT} = \&_restore_terminal_and_die;
		ReadMode 'cbreak';
		my $key = ReadKey 0;
		ReadMode 'restore';
1169 1170 1171 1172 1173 1174 1175 1176
		if ($use_termcap and $key eq "\e") {
			while (!defined $term_escapes{$key}) {
				my $next = ReadKey 0.5;
				last if (!defined $next);
				$key .= $next;
			}
			$key =~ s/\e/^[/;
		}
1177 1178 1179 1180 1181 1182 1183 1184
		print "$key" if defined $key;
		print "\n";
		return $key;
	} else {
		return <STDIN>;
	}
}

1185 1186 1187 1188
sub prompt_yesno {
	my ($prompt) = @_;
	while (1) {
		print colored $prompt_color, $prompt;
1189
		my $line = prompt_single_character;
1190
		return undef unless defined $line;
1191 1192 1193 1194 1195 1196
		return 0 if $line =~ /^n/i;
		return 1 if $line =~ /^y/i;
	}
}

sub edit_hunk_loop {
1197 1198 1199
	my ($head, $hunks, $ix) = @_;
	my $hunk = $hunks->[$ix];
	my $text = $hunk->{TEXT};
1200 1201

	while (1) {
1202 1203
		my $newtext = edit_hunk_manually($text);
		if (!defined $newtext) {
1204 1205
			return undef;
		}
1206
		my $newhunk = {
1207 1208
			TEXT => $newtext,
			TYPE => $hunk->{TYPE},
1209 1210
			USE => 1,
			DIRTY => 1,
1211
		};
1212 1213 1214 1215 1216 1217
		$newhunk->{OFS_DELTA} = recount_edited_hunk($text, $newtext);
		# If this hunk has already been edited then add the
		# offset delta of the previous edit to get the real
		# delta from the original unedited hunk.
		$hunk->{OFS_DELTA} and
				$newhunk->{OFS_DELTA} += $hunk->{OFS_DELTA};
1218
		if (diff_applies($head,
1219
				 @{$hunks}[0..$ix-1],
1220
				 $newhunk,
1221 1222
				 @{$hunks}[$ix+1..$#{$hunks}])) {
			$newhunk->{DISPLAY} = [color_diff(@{$newtext})];
1223 1224 1225 1226
			return $newhunk;
		}
		else {
			prompt_yesno(
1227 1228 1229 1230 1231 1232 1233 1234
				# TRANSLATORS: do not translate [y/n]
				# The program will only accept that input
				# at this point.
				# Consider translating (saying "no" discards!) as
				# (saying "n" for "no" discards!) if the translation
				# of the word "no" does not start with n.
				__('Your edited hunk does not apply. Edit again '
				   . '(saying "no" discards!) [y/n]? ')
1235 1236 1237 1238 1239
				) or return undef;
		}
	}
}

1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
my %help_patch_modes = (
	stage => N__(
"y - stage this hunk
n - do not stage this hunk
q - quit; do not stage this hunk or any of the remaining ones
a - stage this hunk and all later hunks in the file
d - do not stage this hunk or any of the later hunks in the file"),
	stash => N__(
"y - stash this hunk
n - do not stash this hunk
q - quit; do not stash this hunk or any of the remaining ones
a - stash this hunk and all later hunks in the file
d - do not stash this hunk or any of the later hunks in the file"),
	reset_head => N__(
"y - unstage this hunk
n - do not unstage this hunk
q - quit; do not unstage this hunk or any of the remaining ones
a - unstage this hunk and all later hunks in the file
d - do not unstage this hunk or any of the later hunks in the file"),
	reset_nothead => N__(
"y - apply this hunk to index
n - do not apply this hunk to index
q - quit; do not apply this hunk or any of the remaining ones
a - apply this hunk and all later hunks in the file
d - do not apply this hunk or any of the later hunks in the file"),
	checkout_index => N__(
"y - discard this hunk from worktree
n - do not discard this hunk from worktree
q - quit; do not discard this hunk or any of the remaining ones
a - discard this hunk and all later hunks in the file
d - do not discard this hunk or any of the later hunks in the file"),
	checkout_head => N__(
"y - discard this hunk from index and worktree
n - do not discard this hunk from index and worktree
q - quit; do not discard this hunk or any of the remaining ones
a - discard this hunk and all later hunks in the file
d - do not discard this hunk or any of the later hunks in the file"),
	checkout_nothead => N__(
"y - apply this hunk to index and worktree
n - do not apply this hunk to index and worktree
q - quit; do not apply this hunk or any of the remaining ones
a - apply this hunk and all later hunks in the file
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
d - do not apply this hunk or any of the later hunks in the file"),
	worktree_head => N__(
"y - discard this hunk from worktree
n - do not discard this hunk from worktree
q - quit; do not discard this hunk or any of the remaining ones
a - discard this hunk and all later hunks in the file
d - do not discard this hunk or any of the later hunks in the file"),
	worktree_nothead => N__(
"y - apply this hunk to worktree
n - do not apply this hunk to worktree
q - quit; do not apply this hunk or any of the remaining ones
a - apply this hunk and all later hunks in the file
1294 1295 1296
d - do not apply this hunk or any of the later hunks in the file"),
);

J
Junio C Hamano 已提交
1297
sub help_patch_cmd {
1298
	local $_;
1299
	my $other = $_[0] . ",?";
1300 1301 1302 1303 1304
	print colored $help_color, __($help_patch_modes{$patch_mode}), "\n",
		map { "$_\n" } grep {
			my $c = quotemeta(substr($_, 0, 1));
			$other =~ /,$c/
		} split "\n", __ <<EOF ;
W
William Pursell 已提交
1305
g - select a hunk to go to
W
William Pursell 已提交
1306
/ - search for a hunk matching the given regex
J
Junio C Hamano 已提交
1307 1308 1309 1310
j - leave this hunk undecided, see next undecided hunk
J - leave this hunk undecided, see next hunk
k - leave this hunk undecided, see previous undecided hunk
K - leave this hunk undecided, see previous hunk
1311
s - split the current hunk into smaller hunks
1312
e - manually edit the current hunk
1313
? - print help
J
Junio C Hamano 已提交
1314 1315 1316
EOF
}

1317 1318
sub apply_patch {
	my $cmd = shift;
1319
	my $ret = run_git_apply $cmd, @_;
1320 1321 1322 1323 1324 1325
	if (!$ret) {
		print STDERR @_;
	}
	return $ret;
}

T
Thomas Rast 已提交
1326 1327
sub apply_patch_for_checkout_commit {
	my $reverse = shift;
1328 1329
	my $applies_index = run_git_apply 'apply '.$reverse.' --cached --check', @_;
	my $applies_worktree = run_git_apply 'apply '.$reverse.' --check', @_;
T
Thomas Rast 已提交
1330 1331

	if ($applies_worktree && $applies_index) {
1332 1333
		run_git_apply 'apply '.$reverse.' --cached', @_;
		run_git_apply 'apply '.$reverse, @_;
T
Thomas Rast 已提交
1334 1335
		return 1;
	} elsif (!$applies_index) {
1336 1337
		print colored $error_color, __("The selected hunks do not apply to the index!\n");
		if (prompt_yesno __("Apply them to the worktree anyway? ")) {
1338
			return run_git_apply 'apply '.$reverse, @_;
T
Thomas Rast 已提交
1339
		} else {
1340
			print colored $error_color, __("Nothing was applied.\n");
T
Thomas Rast 已提交
1341 1342 1343 1344 1345 1346 1347 1348
			return 0;
		}
	} else {
		print STDERR @_;
		return 0;
	}
}

J
Junio C Hamano 已提交
1349
sub patch_update_cmd {
1350
	my @all_mods = list_modified($patch_mode_flavour{FILTER});
1351
	error_msg sprintf(__("ignoring unmerged: %s\n"), $_->{VALUE})
1352 1353 1354
		for grep { $_->{UNMERGED} } @all_mods;
	@all_mods = grep { !$_->{UNMERGED} } @all_mods;

1355
	my @mods = grep { !($_->{BINARY}) } @all_mods;
1356
	my @them;
J
Junio C Hamano 已提交
1357

1358
	if (!@mods) {
1359
		if (@all_mods) {
1360
			print STDERR __("Only binary files changed.\n");
1361
		} else {
1362
			print STDERR __("No changes.\n");
1363
		}
1364 1365
		return 0;
	}
1366
	if ($patch_mode_only) {
1367 1368 1369
		@them = @mods;
	}
	else {
1370
		@them = list_and_choose({ PROMPT => __('Patch update'),
1371 1372 1373
					  HEADER => $status_head, },
					@mods);
	}
1374
	for (@them) {
1375
		return 0 if patch_update_file($_->{VALUE});
1376
	}
W
Wincent Colaiuta 已提交
1377
}
J
Junio C Hamano 已提交
1378

1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
# Generate a one line summary of a hunk.
sub summarize_hunk {
	my $rhunk = shift;
	my $summary = $rhunk->{TEXT}[0];

	# Keep the line numbers, discard extra context.
	$summary =~ s/@@(.*?)@@.*/$1 /s;
	$summary .= " " x (20 - length $summary);

	# Add some user context.
	for my $line (@{$rhunk->{TEXT}}) {
		if ($line =~ m/^[+-].*\w/) {
			$summary .= $line;
			last;
		}
	}

	chomp $summary;
	return substr($summary, 0, 80) . "\n";
}


# Print a one-line summary of each hunk in the array ref in
1402
# the first argument, starting with the index in the 2nd.
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
sub display_hunks {
	my ($hunks, $i) = @_;
	my $ctr = 0;
	$i ||= 0;
	for (; $i < @$hunks && $ctr < 20; $i++, $ctr++) {
		my $status = " ";
		if (defined $hunks->[$i]{USE}) {
			$status = $hunks->[$i]{USE} ? "+" : "-";
		}
		printf "%s%2d: %s",
			$status,
			$i + 1,
			summarize_hunk($hunks->[$i]);
	}
	return $i;
}

1420 1421
my %patch_update_prompt_modes = (
	stage => {
1422 1423 1424
		mode => N__("Stage mode change [y,n,q,a,d%s,?]? "),
		deletion => N__("Stage deletion [y,n,q,a,d%s,?]? "),
		hunk => N__("Stage this hunk [y,n,q,a,d%s,?]? "),
1425 1426
	},
	stash => {
1427 1428 1429
		mode => N__("Stash mode change [y,n,q,a,d%s,?]? "),
		deletion => N__("Stash deletion [y,n,q,a,d%s,?]? "),
		hunk => N__("Stash this hunk [y,n,q,a,d%s,?]? "),
1430 1431
	},
	reset_head => {
1432 1433 1434
		mode => N__("Unstage mode change [y,n,q,a,d%s,?]? "),
		deletion => N__("Unstage deletion [y,n,q,a,d%s,?]? "),
		hunk => N__("Unstage this hunk [y,n,q,a,d%s,?]? "),
1435 1436
	},
	reset_nothead => {
1437 1438 1439
		mode => N__("Apply mode change to index [y,n,q,a,d%s,?]? "),
		deletion => N__("Apply deletion to index [y,n,q,a,d%s,?]? "),
		hunk => N__("Apply this hunk to index [y,n,q,a,d%s,?]? "),
1440 1441
	},
	checkout_index => {
1442 1443 1444
		mode => N__("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
		deletion => N__("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
		hunk => N__("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
1445 1446
	},
	checkout_head => {
1447 1448 1449
		mode => N__("Discard mode change from index and worktree [y,n,q,a,d%s,?]? "),
		deletion => N__("Discard deletion from index and worktree [y,n,q,a,d%s,?]? "),
		hunk => N__("Discard this hunk from index and worktree [y,n,q,a,d%s,?]? "),
1450 1451
	},
	checkout_nothead => {
1452 1453 1454
		mode => N__("Apply mode change to index and worktree [y,n,q,a,d%s,?]? "),
		deletion => N__("Apply deletion to index and worktree [y,n,q,a,d%s,?]? "),
		hunk => N__("Apply this hunk to index and worktree [y,n,q,a,d%s,?]? "),
1455
	},
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
	worktree_head => {
		mode => N__("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
		deletion => N__("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
		hunk => N__("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
	},
	worktree_nothead => {
		mode => N__("Apply mode change to worktree [y,n,q,a,d%s,?]? "),
		deletion => N__("Apply deletion to worktree [y,n,q,a,d%s,?]? "),
		hunk => N__("Apply this hunk to worktree [y,n,q,a,d%s,?]? "),
	},
1466 1467
);

W
Wincent Colaiuta 已提交
1468
sub patch_update_file {
1469
	my $quit = 0;
J
Junio C Hamano 已提交
1470
	my ($ix, $num);
W
Wincent Colaiuta 已提交
1471
	my $path = shift;
J
Junio C Hamano 已提交
1472
	my ($head, @hunk) = parse_diff($path);
1473
	($head, my $mode, my $deletion) = parse_diff_header($head);
1474 1475 1476
	for (@{$head->{DISPLAY}}) {
		print;
	}
1477 1478

	if (@{$mode->{TEXT}}) {
1479
		unshift @hunk, $mode;
1480
	}
1481 1482 1483 1484 1485
	if (@{$deletion->{TEXT}}) {
		foreach my $hunk (@hunk) {
			push @{$deletion->{TEXT}}, @{$hunk->{TEXT}};
			push @{$deletion->{DISPLAY}}, @{$hunk->{DISPLAY}};
		}
1486 1487
		@hunk = ($deletion);
	}
1488

J
Junio C Hamano 已提交
1489 1490 1491 1492
	$num = scalar @hunk;
	$ix = 0;

	while (1) {
1493
		my ($prev, $next, $other, $undecided, $i);
J
Junio C Hamano 已提交
1494 1495 1496 1497 1498
		$other = '';

		if ($num <= $ix) {
			$ix = 0;
		}
1499
		for ($i = 0; $i < $ix; $i++) {
J
Junio C Hamano 已提交
1500 1501
			if (!defined $hunk[$i]{USE}) {
				$prev = 1;
1502
				$other .= ',k';
J
Junio C Hamano 已提交
1503 1504 1505 1506
				last;
			}
		}
		if ($ix) {
1507
			$other .= ',K';
J
Junio C Hamano 已提交
1508
		}
1509
		for ($i = $ix + 1; $i < $num; $i++) {
J
Junio C Hamano 已提交
1510 1511
			if (!defined $hunk[$i]{USE}) {
				$next = 1;
1512
				$other .= ',j';
J
Junio C Hamano 已提交
1513 1514 1515 1516
				last;
			}
		}
		if ($ix < $num - 1) {
1517
			$other .= ',J';
J
Junio C Hamano 已提交
1518
		}
W
William Pursell 已提交
1519
		if ($num > 1) {
1520
			$other .= ',g,/';
W
William Pursell 已提交
1521
		}
1522
		for ($i = 0; $i < $num; $i++) {
J
Junio C Hamano 已提交
1523 1524 1525 1526 1527 1528 1529
			if (!defined $hunk[$i]{USE}) {
				$undecided = 1;
				last;
			}
		}
		last if (!$undecided);

1530 1531
		if ($hunk[$ix]{TYPE} eq 'hunk' &&
		    hunk_splittable($hunk[$ix]{TEXT})) {
1532
			$other .= ',s';
1533
		}
1534 1535 1536
		if ($hunk[$ix]{TYPE} eq 'hunk') {
			$other .= ',e';
		}
1537 1538 1539
		for (@{$hunk[$ix]{DISPLAY}}) {
			print;
		}
1540 1541 1542
		print colored $prompt_color,
			sprintf(__($patch_update_prompt_modes{$patch_mode}{$hunk[$ix]{TYPE}}), $other);

1543
		my $line = prompt_single_character;
1544
		last unless defined $line;
J
Junio C Hamano 已提交
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
		if ($line) {
			if ($line =~ /^y/i) {
				$hunk[$ix]{USE} = 1;
			}
			elsif ($line =~ /^n/i) {
				$hunk[$ix]{USE} = 0;
			}
			elsif ($line =~ /^a/i) {
				while ($ix < $num) {
					if (!defined $hunk[$ix]{USE}) {
						$hunk[$ix]{USE} = 1;
					}
					$ix++;
				}
				next;
			}
P
Phillip Wood 已提交
1561
			elsif ($line =~ /^g(.*)/) {
W
William Pursell 已提交
1562
				my $response = $1;
P
Phillip Wood 已提交
1563 1564 1565 1566
				unless ($other =~ /g/) {
					error_msg __("No other hunks to goto\n");
					next;
				}
W
William Pursell 已提交
1567 1568 1569 1570
				my $no = $ix > 10 ? $ix - 10 : 0;
				while ($response eq '') {
					$no = display_hunks(\@hunk, $no);
					if ($no < $num) {
1571 1572 1573
						print __("go to which hunk (<ret> to see more)? ");
					} else {
						print __("go to which hunk? ");
W
William Pursell 已提交
1574 1575
					}
					$response = <STDIN>;
T
Thomas Rast 已提交
1576 1577 1578
					if (!defined $response) {
						$response = '';
					}
W
William Pursell 已提交
1579 1580 1581
					chomp $response;
				}
				if ($response !~ /^\s*\d+\s*$/) {
1582 1583
					error_msg sprintf(__("Invalid number: '%s'\n"),
							     $response);
W
William Pursell 已提交
1584 1585 1586
				} elsif (0 < $response && $response <= $num) {
					$ix = $response - 1;
				} else {
1587 1588
					error_msg sprintf(__n("Sorry, only %d hunk available.\n",
							      "Sorry, only %d hunks available.\n", $num), $num);
W
William Pursell 已提交
1589 1590 1591
				}
				next;
			}
J
Junio C Hamano 已提交
1592 1593 1594 1595 1596 1597 1598 1599 1600
			elsif ($line =~ /^d/i) {
				while ($ix < $num) {
					if (!defined $hunk[$ix]{USE}) {
						$hunk[$ix]{USE} = 0;
					}
					$ix++;
				}
				next;
			}
1601
			elsif ($line =~ /^q/i) {
J
Junio C Hamano 已提交
1602 1603 1604
				for ($i = 0; $i < $num; $i++) {
					if (!defined $hunk[$i]{USE}) {
						$hunk[$i]{USE} = 0;
1605 1606 1607
					}
				}
				$quit = 1;
J
Junio C Hamano 已提交
1608
				last;
1609
			}
W
William Pursell 已提交
1610
			elsif ($line =~ m|^/(.*)|) {
1611
				my $regex = $1;
1612 1613 1614 1615
				unless ($other =~ m|/|) {
					error_msg __("No other hunks to search\n");
					next;
				}
1616
				if ($regex eq "") {
1617
					print colored $prompt_color, __("search for regex? ");
1618 1619 1620 1621 1622
					$regex = <STDIN>;
					if (defined $regex) {
						chomp $regex;
					}
				}
W
William Pursell 已提交
1623 1624
				my $search_string;
				eval {
1625
					$search_string = qr{$regex}m;
W
William Pursell 已提交
1626 1627 1628 1629
				};
				if ($@) {
					my ($err,$exp) = ($@, $1);
					$err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
1630
					error_msg sprintf(__("Malformed search regexp %s: %s\n"), $exp, $err);
W
William Pursell 已提交
1631 1632 1633 1634 1635 1636 1637 1638 1639
					next;
				}
				my $iy = $ix;
				while (1) {
					my $text = join ("", @{$hunk[$iy]{TEXT}});
					last if ($text =~ $search_string);
					$iy++;
					$iy = 0 if ($iy >= $num);
					if ($ix == $iy) {
1640
						error_msg __("No hunk matches the given pattern\n");
W
William Pursell 已提交
1641 1642 1643 1644 1645 1646
						last;
					}
				}
				$ix = $iy;
				next;
			}
1647 1648 1649 1650 1651
			elsif ($line =~ /^K/) {
				if ($other =~ /K/) {
					$ix--;
				}
				else {
1652
					error_msg __("No previous hunk\n");
1653
				}
J
Junio C Hamano 已提交
1654 1655
				next;
			}
1656 1657 1658 1659 1660
			elsif ($line =~ /^J/) {
				if ($other =~ /J/) {
					$ix++;
				}
				else {
1661
					error_msg __("No next hunk\n");
1662
				}
J
Junio C Hamano 已提交
1663 1664
				next;
			}
1665 1666 1667 1668 1669 1670 1671 1672 1673
			elsif ($line =~ /^k/) {
				if ($other =~ /k/) {
					while (1) {
						$ix--;
						last if (!$ix ||
							 !defined $hunk[$ix]{USE});
					}
				}
				else {
1674
					error_msg __("No previous hunk\n");
J
Junio C Hamano 已提交
1675 1676 1677
				}
				next;
			}
1678 1679
			elsif ($line =~ /^j/) {
				if ($other !~ /j/) {
1680
					error_msg __("No next hunk\n");
1681
					next;
J
Junio C Hamano 已提交
1682 1683
				}
			}
P
Phillip Wood 已提交
1684 1685 1686 1687 1688
			elsif ($line =~ /^s/) {
				unless ($other =~ /s/) {
					error_msg __("Sorry, cannot split this hunk\n");
					next;
				}
1689
				my @split = split_hunk($hunk[$ix]{TEXT}, $hunk[$ix]{DISPLAY});
1690
				if (1 < @split) {
1691 1692 1693 1694
					print colored $header_color, sprintf(
						__n("Split into %d hunk.\n",
						    "Split into %d hunks.\n",
						    scalar(@split)), scalar(@split));
1695
				}
1696
				splice (@hunk, $ix, 1, @split);
1697 1698 1699
				$num = scalar @hunk;
				next;
			}
P
Phillip Wood 已提交
1700 1701 1702 1703 1704
			elsif ($line =~ /^e/) {
				unless ($other =~ /e/) {
					error_msg __("Sorry, cannot edit this hunk\n");
					next;
				}
1705 1706 1707 1708 1709
				my $newhunk = edit_hunk_loop($head, \@hunk, $ix);
				if (defined $newhunk) {
					splice @hunk, $ix, 1, $newhunk;
				}
			}
J
Junio C Hamano 已提交
1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722
			else {
				help_patch_cmd($other);
				next;
			}
			# soft increment
			while (1) {
				$ix++;
				last if ($ix >= $num ||
					 !defined $hunk[$ix]{USE});
			}
		}
	}

1723 1724
	@hunk = coalesce_overlapping_hunks(@hunk);

1725
	my $n_lofs = 0;
J
Junio C Hamano 已提交
1726 1727
	my @result = ();
	for (@hunk) {
1728 1729
		if ($_->{USE}) {
			push @result, @{$_->{TEXT}};
J
Junio C Hamano 已提交
1730 1731 1732 1733
		}
	}

	if (@result) {
1734
		my @patch = reassemble_patch($head->{TEXT}, @result);
1735 1736
		my $apply_routine = $patch_mode_flavour{APPLY};
		&$apply_routine(@patch);
J
Junio C Hamano 已提交
1737 1738 1739 1740
		refresh();
	}

	print "\n";
1741
	return $quit;
J
Junio C Hamano 已提交
1742 1743 1744 1745 1746 1747
}

sub diff_cmd {
	my @mods = list_modified('index-only');
	@mods = grep { !($_->{BINARY}) } @mods;
	return if (!@mods);
1748
	my (@them) = list_and_choose({ PROMPT => __('Review diff'),
J
Junio C Hamano 已提交
1749 1750 1751 1752
				     IMMEDIATE => 1,
				     HEADER => $status_head, },
				   @mods);
	return if (!@them);
1753
	my $reference = (is_initial_commit()) ? get_empty_tree() : 'HEAD';
1754 1755
	system(qw(git diff -p --cached), $reference, '--',
		map { $_->{VALUE} } @them);
J
Junio C Hamano 已提交
1756 1757 1758
}

sub quit_cmd {
1759
	print __("Bye.\n");
J
Junio C Hamano 已提交
1760 1761 1762 1763
	exit(0);
}

sub help_cmd {
1764 1765 1766
# TRANSLATORS: please do not translate the command names
# 'status', 'update', 'revert', etc.
	print colored $help_color, __ <<'EOF' ;
J
Junio C Hamano 已提交
1767 1768 1769 1770
status        - show paths with changes
update        - add working tree state to the staged set of changes
revert        - revert staged set of changes back to the HEAD version
patch         - pick hunks and update selectively
1771
diff          - view diff between HEAD and index
J
Junio C Hamano 已提交
1772 1773 1774 1775
add untracked - add contents of untracked files to the staged set of changes
EOF
}

1776 1777 1778
sub process_args {
	return unless @ARGV;
	my $arg = shift @ARGV;
T
Thomas Rast 已提交
1779 1780 1781 1782 1783
	if ($arg =~ /--patch(?:=(.*))?/) {
		if (defined $1) {
			if ($1 eq 'reset') {
				$patch_mode = 'reset_head';
				$patch_mode_revision = 'HEAD';
1784
				$arg = shift @ARGV or die __("missing --");
T
Thomas Rast 已提交
1785 1786 1787 1788
				if ($arg ne '--') {
					$patch_mode_revision = $arg;
					$patch_mode = ($arg eq 'HEAD' ?
						       'reset_head' : 'reset_nothead');
1789
					$arg = shift @ARGV or die __("missing --");
T
Thomas Rast 已提交
1790
				}
T
Thomas Rast 已提交
1791
			} elsif ($1 eq 'checkout') {
1792
				$arg = shift @ARGV or die __("missing --");
T
Thomas Rast 已提交
1793 1794 1795 1796 1797 1798
				if ($arg eq '--') {
					$patch_mode = 'checkout_index';
				} else {
					$patch_mode_revision = $arg;
					$patch_mode = ($arg eq 'HEAD' ?
						       'checkout_head' : 'checkout_nothead');
1799
					$arg = shift @ARGV or die __("missing --");
T
Thomas Rast 已提交
1800
				}
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
			} elsif ($1 eq 'worktree') {
				$arg = shift @ARGV or die __("missing --");
				if ($arg eq '--') {
					$patch_mode = 'checkout_index';
				} else {
					$patch_mode_revision = $arg;
					$patch_mode = ($arg eq 'HEAD' ?
						       'worktree_head' : 'worktree_nothead');
					$arg = shift @ARGV or die __("missing --");
				}
T
Thomas Rast 已提交
1811 1812
			} elsif ($1 eq 'stage' or $1 eq 'stash') {
				$patch_mode = $1;
1813
				$arg = shift @ARGV or die __("missing --");
T
Thomas Rast 已提交
1814
			} else {
1815
				die sprintf(__("unknown --patch mode: %s"), $1);
T
Thomas Rast 已提交
1816 1817 1818
			}
		} else {
			$patch_mode = 'stage';
1819
			$arg = shift @ARGV or die __("missing --");
T
Thomas Rast 已提交
1820
		}
1821 1822
		die sprintf(__("invalid argument %s, expecting --"),
			       $arg) unless $arg eq "--";
T
Thomas Rast 已提交
1823
		%patch_mode_flavour = %{$patch_modes{$patch_mode}};
1824
		$patch_mode_only = 1;
1825 1826
	}
	elsif ($arg ne "--") {
1827
		die sprintf(__("invalid argument %s, expecting --"), $arg);
1828 1829 1830
	}
}

J
Junio C Hamano 已提交
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841
sub main_loop {
	my @cmd = ([ 'status', \&status_cmd, ],
		   [ 'update', \&update_cmd, ],
		   [ 'revert', \&revert_cmd, ],
		   [ 'add untracked', \&add_untracked_cmd, ],
		   [ 'patch', \&patch_update_cmd, ],
		   [ 'diff', \&diff_cmd, ],
		   [ 'quit', \&quit_cmd, ],
		   [ 'help', \&help_cmd, ],
	);
	while (1) {
1842
		my ($it) = list_and_choose({ PROMPT => __('What now'),
J
Junio C Hamano 已提交
1843 1844
					     SINGLETON => 1,
					     LIST_FLAT => 4,
1845
					     HEADER => __('*** Commands ***'),
1846
					     ON_EOF => \&quit_cmd,
J
Junio C Hamano 已提交
1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
					     IMMEDIATE => 1 }, @cmd);
		if ($it) {
			eval {
				$it->[1]->();
			};
			if ($@) {
				print "$@";
			}
		}
	}
}

1859
process_args();
J
Junio C Hamano 已提交
1860
refresh();
1861
if ($patch_mode_only) {
1862 1863 1864 1865 1866 1867
	patch_update_cmd();
}
else {
	status_cmd();
	main_loop();
}