The Problem
You’ve added a list of your top 100 albums of all time to a file. Jane is going to look through it, and pass back her own list. In the meantime, you’ve made a couple of changes to the files for work related reasons.
The problem is that you now need to commit those two changes, without committing the top 100 albums. Apparently, this sort of list isn’t praised in the company handbook.
So how can we get a Git partial commit ? We need to tell Git to stage and then commit only some parts of the file. Each changed part is called a hunk, and may contain 1 or more lines of alterations.
Let's see how we can solve this problem. In this example, the file is called ‘package.json’.
The Solution
This tells git to start adding the file, but interactively:
git add --patch package.json
Information: The command --patch is the same as -p, and a swifter way of getting to the interactive patch mode, which you can otherwise achieve by typing git add –-interactive and then selecting patch.
Git will then show the first hunk, and ask you a question with some or all of these options offered to you:
Stage this hunk [y,n,q,a,d,g,/,j,J,k,K,s,e,?]?
Select the most appropriate one, and Git will stage part of the file according to your instructions. These options mean:
y = Stage this hunk to commit next.
n = Don’t stage this hunk to commit next.
q = Quit. Don’t stage this or any other remaining hunks.
a = Stage this hunk and all later hunks to commit next.
d = Don’t stage this hunk or any other remaining to commit next.
g = Select a hunk to go to.
/ = Search for a hunk matching the given regex.
j = Leave this hunk undecided, and see the next undecided hunk.
J = Leave this hunk undecided, and see the next hunk.
k = Leave this hunk undecided, and see the previous undecided hunk.
K = Leave this hunk undecided, and see the previous hunk.
s = Split the current hunk into smaller hunks.
e = Manually edit the current hunk.
? = Print the hunk help.
This checks the file to ensure you staged the correct changes:
This interactively replays the hunk staging you performed: