Last Updated: March 06, 2019
·
4.608K
· gvanderest

Git Hunk Splitting

This just changed my git life: git add -p {files}

You've possibly done this before, cycled through the hunks of code to be patched in.. Maybe even hit (s)plit at this point and went on your merry way, but one option is to manually (e)dit the hunk.

You will be shown the following:

# ...
@@ -1,2 +1,4 @@ 
 this is some existing content 
+hello 
+world 
 and a little more too 
# ...

Say you're adding a new feature that uses all the "hello"s in the files, and calls to the "hello" function, so we don't need the "world" line... Delete it.

You're not deleting the code forever, you're only deleting it from this patch being applied to the code, making up this upcoming commit; BUT, the working copy in your files will still have that line in it, it's just not part of this commit.

Be careful though, you still need to keep the "and a little more too" line, because the patch is using that as an anchor. Make your edits, save your file, close your editor, and then perform the following commands to see what happened:

git diff --cached - This compares the currently staged commit against your local repository

--- a/example-file
+++ b/example-file
@@ -1,2 +1,3 @@
 this is some existing content
+hello
 and a little more too

git diff - This compares the working files (files in your directory) against the currently staged commit

--- a/example-file
+++ b/example-file
@@ -1,3 +1,4 @@
 this is some existing content
 hello
+world
 and a little more too

The reason this shows the "hello" line, is because that's what's sitting in your staged commit right now.. So everything is awesome.

And if you want to undo what you just did? You can always git reset HEAD and go back, starting the process again.