git/list[1] front-page[2] threads[3] people[4] search[5] about
 

[PATCH v4] git-add--interactive: manual hunk editing mode

From
Thomas Rast <trast@student.ethz.ch>
Date
Jun 13, 2008, 15:48 UTC
Message-ID
<200806131748.44867.trast@student.ethz.ch>
In-Reply-To
<20080612071311.GA32491@sigill.intra.peff.net>

Adds a new option 'e' to the 'add -p' command loop that lets you edit the current hunk in your favourite editor.

If the resulting patch applies cleanly, the edited hunk will immediately be marked for staging. 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.

Applying the changed hunk(s) relies on Johannes Schindelin's new --recount option for git-apply.

Note that the "real patch" test intentionally uses
  (echo e; echo n; echo d) | git add -p
even though the 'n' and 'd' are superfluous at first sight.  They
serve to get out of the interaction loop if git add -p wrongly
concludes the patch does not apply.

Many thanks to Jeff King <peff@peff.net> for lots of help and suggestions.

Signed-off-by: Thomas Rast <trast@student.ethz.ch>
---
Once again trying to shape this up as a complete patch.
Jeff King wrote:
> On Thu, Jun 12, 2008 at 08:55:24AM +0200, Thomas Rast wrote:
> 
> > I wanted to make the same special case that 'recount -i' has: Deleting
> > everything does not "do nothing", but actually aborts the edit.
[...]
> Ah, OK. That makes sense. I think it could be worded more explicitly,
> though. [...]

I took the liberty of copying your wording to the help and commit messages, as it is indeed much clearer that way.

> Right, but you may get false positives if a later conflicting hunk is
> not staged. Though as you say, I think it is unlikely in either case.

I'd rather reject early and offer to re-edit, than notice a problem much later, so I left it the way it was.

Changes since the last version:
* The help message mentioned above
* Use [f(...)] instead of @tmp = f(); \@tmp
* Re-added tests from v3, with an added test for a correctly formatted
  patch that does not apply
* Re-added a line about 'e' to Documentation/git-add.txt (which was in
  the original patch but got lost)

I was tempted to reintroduce globbed unlinking of the temporary file as in v3 (that is, removing TMP* instead of just TMP). In the absence of it, backup files made by the user's editor will remain in .git/. Eventually I didn't because it seems vi doesn't make backups anyway, and while emacs does, enabling that for GIT_EDITOR seems a user error. Besides, how do we know the backups match that pattern anyway. Not sure though.

- Thomas
  
 Documentation/git-add.txt  |    1 +
 git-add--interactive.perl  |  124 +++++++++++++++++++++++++++++++++++++++++++-
 t/t3701-add-interactive.sh |   67 ++++++++++++++++++++++++
 3 files changed, 191 insertions(+), 1 deletions(-)
diff --git a/Documentation/git-add.txt b/Documentation/git-add.txt
index 8620ae2..842430c 100644
--- a/Documentation/git-add.txt
+++ b/Documentation/git-add.txt
@@ -238,6 +238,7 @@ patch::
        k - leave this hunk undecided, see previous undecided hunk
        K - leave this hunk undecided, see previous hunk
        s - split the current hunk into smaller hunks
+       e - manually edit the current hunk
        ? - print help
 +
 After deciding the fate for all hunks, if there is any hunk
diff --git a/git-add--interactive.perl b/git-add--interactive.perl
index 903953e..8cc275d 100755
--- a/git-add--interactive.perl
+++ b/git-add--interactive.perl
@@ -2,6 +2,7 @@
 
 use strict;
 use Git;
+use File::Temp;
 
 my $repo = Git->repository();
 
@@ -18,6 +19,18 @@ my ($fraginfo_color) =
 	$diff_use_color ? (
 		$repo->get_color('color.diff.frag', 'cyan'),
 	) : ();
+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'),
+	) : ();
 
 my $normal_color = $repo->get_color("", "reset");
 
@@ -770,6 +783,104 @@ sub coalesce_overlapping_hunks {
 	return @out;
 }
 
+sub color_diff {
+	return map {
+		colored((/^@/  ? $fraginfo_color :
+			 /^\+/ ? $diff_new_color :
+			 /^-/  ? $diff_old_color :
+			 $diff_plain_color),
+			$_);
+	} @_;
+}
+
+sub edit_hunk_manually {
+	my ($oldtext) = @_;
+
+	my $t = File::Temp->new(
+		TEMPLATE => $repo->repo_path . "/git-hunk-edit.XXXXXX",
+		SUFFIX => '.diff'
+	);
+	print $t "# Manual hunk edit mode -- see bottom for a quick guide\n";
+	print $t @$oldtext;
+	print $t <<EOF;
+# ---
+# To remove '-' lines, make them ' ' lines (context).
+# To remove '+' lines, delete them.
+# Lines starting with # will be removed.
+#
+# If the patch applies cleanly, the edited hunk will immediately be
+# marked for staging. 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.
+EOF
+	close $t;
+
+	my $editor = $ENV{GIT_EDITOR} || $repo->config("core.editor")
+		|| $ENV{VISUAL} || $ENV{EDITOR} || "vi";
+	system('sh', '-c', $editor.' "$@"', $editor, $t);
+
+	open my $fh, '<', $t
+		or die "failed to open hunk edit file for reading: " . $!;
+	my @newtext = grep { !/^#/ } <$fh>;
+	close $fh;
+
+	# Abort if nothing remains
+	if (@newtext == 0) {
+		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 {
+	my $fh;
+	open $fh, '| git apply --recount --cached --check';
+	for my $h (@_) {
+		print $fh @{$h->{TEXT}};
+	}
+	return close $fh;
+}
+
+sub prompt_yesno {
+	my ($prompt) = @_;
+	while (1) {
+		print colored $prompt_color, $prompt;
+		my $line = <STDIN>;
+		return 0 if $line =~ /^n/i;
+		return 1 if $line =~ /^y/i;
+	}
+}
+
+sub edit_hunk_loop {
+	my ($head, $hunk, $ix) = @_;
+	my $text = $hunk->[$ix]->{TEXT};
+
+	while (1) {
+		$text = edit_hunk_manually($text);
+		if (!defined $text) {
+			return undef;
+		}
+		my $newhunk = { TEXT => $text, USE => 1 };
+		if (diff_applies($head,
+				 @{$hunk}[0..$ix-1],
+				 $newhunk,
+				 @{$hunk}[$ix+1..$#{$hunk}])) {
+			$newhunk->{DISPLAY} = [color_diff(@{$text})];
+			return $newhunk;
+		}
+		else {
+			prompt_yesno(
+				'Your edited hunk does not apply. Edit again '
+				. '(saying "no" discards!) [y/n]? '
+				) or return undef;
+		}
+	}
+}
+
 sub help_patch_cmd {
 	print colored $help_color, <<\EOF ;
 y - stage this hunk
@@ -781,6 +892,7 @@ 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
 s - split the current hunk into smaller hunks
+e - manually edit the current hunk
 ? - print help
 EOF
 }
@@ -846,6 +958,7 @@ sub patch_update_file {
 
 	$num = scalar @hunk;
 	$ix = 0;
+	my $need_recount = 0;
 
 	while (1) {
 		my ($prev, $next, $other, $undecided, $i);
@@ -885,6 +998,7 @@ sub patch_update_file {
 		if (hunk_splittable($hunk[$ix]{TEXT})) {
 			$other .= '/s';
 		}
+		$other .= '/e';
 		for (@{$hunk[$ix]{DISPLAY}}) {
 			print;
 		}
@@ -949,6 +1063,13 @@ sub patch_update_file {
 				$num = scalar @hunk;
 				next;
 			}
+			elsif ($line =~ /^e/) {
+				my $newhunk = edit_hunk_loop($head, \@hunk, $ix);
+				if (defined $newhunk) {
+					splice @hunk, $ix, 1, $newhunk;
+					$need_recount = 1;
+				}
+			}
 			else {
 				help_patch_cmd($other);
 				next;
@@ -1002,7 +1123,8 @@ sub patch_update_file {
 	if (@result) {
 		my $fh;
 
-		open $fh, '| git apply --cached';
+		open $fh, '| git apply --cached'
+			. ($need_recount ? ' --recount' : '');
 		for (@{$head->{TEXT}}, @result) {
 			print $fh $_;
 		}
diff --git a/t/t3701-add-interactive.sh b/t/t3701-add-interactive.sh
index fae64ea..e95663d 100755
--- a/t/t3701-add-interactive.sh
+++ b/t/t3701-add-interactive.sh
@@ -66,6 +66,73 @@ test_expect_success 'revert works (commit)' '
 	grep "unchanged *+3/-0 file" output
 '
 
+cat >expected <<EOF
+EOF
+cat >fake_editor.sh <<EOF
+EOF
+chmod a+x fake_editor.sh
+test_set_editor "$(pwd)/fake_editor.sh"
+test_expect_success 'dummy edit works' '
+	(echo e; echo a) | git add -p &&
+	git diff > diff &&
+	test_cmp expected diff
+'
+
+cat >patch <<EOF
+@@ -1,1 +1,4 @@
+ this
++patch
+-doesn't
+ apply
+EOF
+echo "#!$SHELL_PATH" >fake_editor.sh
+cat >>fake_editor.sh <<\EOF
+mv -f "$1" oldpatch &&
+mv -f patch "$1"
+EOF
+chmod a+x fake_editor.sh
+test_set_editor "$(pwd)/fake_editor.sh"
+test_expect_success 'bad edit rejected' '
+	git reset &&
+	(echo e; echo n; echo d) | git add -p >output &&
+	grep "hunk does not apply" output
+'
+
+cat >patch <<EOF
+this patch
+is garbage
+EOF
+test_expect_success 'garbage edit rejected' '
+	git reset &&
+	(echo e; echo n; echo d) | git add -p >output &&
+	grep "hunk does not apply" output
+'
+
+cat >patch <<EOF
+@@ -1,0 +1,0 @@
+ baseline
++content
++newcontent
++lines
+EOF
+cat >expected <<EOF
+diff --git a/file b/file
+index b5dd6c9..f910ae9 100644
+--- a/file
++++ b/file
+@@ -1,4 +1,4 @@
+ baseline
+ content
+-newcontent
++more
+ lines
+EOF
+test_expect_success 'real edit works' '
+	(echo e; echo n; echo d) | git add -p &&
+	git diff >output &&
+	test_cmp expected output
+'
+
 if test "$(git config --bool core.filemode)" = false
 then
     say 'skipping filemode tests (filesystem does not properly support modes)'
--
1.5.6.rc1.138.gb2840
Previous: Jeff KingNext: Jeff King
Message 47 of 62 in “git-add--interactive: manual hunk editing mode”
  1. git-add--interactive: manual hunk editing modeThomas Rast, May 23, 2008
  2. Ping YinMay 24, 2008
  3. Thomas RastMay 29, 2008
  4. Johannes SchindelinMay 29, 2008
  5. Thomas RastMay 29, 2008
  6. Thomas RastMay 29, 2008
  7. Jeff KingMay 29, 2008
  8. Johannes SchindelinMay 30, 2008
  9. Jakub NarebskiMay 30, 2008
  10. Thomas RastMay 30, 2008
  11. Junio C HamanoMay 30, 2008
  12. git-add--interactive: manual hunk editing mode v2Thomas Rast, Jun 1, 2008
  13. Thomas RastJun 1, 2008
  14. Jeff KingJun 1, 2008
  15. Jeff KingJun 5, 2008
  16. Thomas RastJun 5, 2008
  17. Jeff KingJun 5, 2008
  18. Thomas RastJun 5, 2008
  19. Jeff KingJun 5, 2008
  20. Thomas RastJun 5, 2008
  21. Jeff KingJun 5, 2008
  22. Junio C HamanoJun 5, 2008
  23. Jeff KingJun 5, 2008
  24. Johannes SchindelinJun 5, 2008
  25. Jeff KingJun 6, 2008
  26. Jeff KingJun 6, 2008
  27. Thomas RastJun 8, 2008
  28. Johannes SchindelinJun 8, 2008
  29. Johannes SchindelinJun 6, 2008
  30. Thomas RastJun 8, 2008
  31. Johannes SchindelinJun 8, 2008
  32. git-add--interactive: manual hunk editing modeThomas Rast, Jun 5, 2008
  33. git-add--interactive: manual hunk editing modeThomas Rast, Jun 8, 2008
  34. Johannes SchindelinJun 8, 2008
  35. Johan HerlandJun 9, 2008
  36. Jeff KingJun 9, 2008
  37. Johannes SchindelinJun 9, 2008
  38. Junio C HamanoJun 9, 2008
  39. Johan HerlandJun 9, 2008
  40. Jeff KingJun 9, 2008
  41. Johan HerlandJun 9, 2008
  42. Jeff KingJun 10, 2008
  43. Thomas RastJun 11, 2008
  44. Jeff KingJun 12, 2008
  45. Thomas RastJun 12, 2008
  46. Jeff KingJun 12, 2008
  47. git-add--interactive: manual hunk editing modeThomas Rast, Jun 13, 2008
  48. Jeff KingJun 23, 2008
  49. Johannes SchindelinJun 23, 2008
  50. Jeff KingJun 23, 2008
  51. apply --recount, was Re: [PATCH v4] git-add--interactive: manual hunk editing modeJohannes Schindelin, Jun 23, 2008
  52. Jeff KingJun 24, 2008
  53. 0/3 Manual editing for 'add' and 'add -p'Thomas Rast, Jun 24, 2008
  54. Miklos VajnaJun 24, 2008
  55. 1/3 Allow git-apply to ignore the hunk headers (AKA recountdiff)Thomas Rast, Jun 24, 2008
  56. Junio C HamanoJun 24, 2008
  57. Jeff KingJun 25, 2008
  58. Johannes SchindelinJun 27, 2008
  59. 2/3 git-add: introduce --edit (to edit the diff vs. the index)Thomas Rast, Jun 24, 2008
  60. 3/3 git-add--interactive: manual hunk editing modeThomas Rast, Jun 24, 2008
  61. Andreas EricssonJun 10, 2008
  62. Thomas RastJun 5, 2008

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.