When I run git add -p
, is there a way for git to select newly made files as hunks to select??
So if I make a new file called foo.java
, then run git add -p, git will not let me choose that file's content to be added into the index.
When I tried git add -p someNewFile.txt
on a new file (an untracked file), git would simply output No changes.
and stop. I had to tell git that I intended to track the new file first.
git add -N someNewFile.txt
git add -p
However, since the file was untracked, it would show up as one giant hunk that couldn't be split (because it is all new!). So, then I needed to edit the hunk into smaller bits. If you're not familiar with that, checkout this reference to get started.
Update - Hunk editing info
I wanted to update this in case the above reference goes away. Because the new file is untracked, git add -p
will show every line in the file as a new line in one hunk. It will then ask you what you want to do with that hunk, giving you the following prompt:
Stage this hunk [y,n,q,a,d,/,e,?]?
Assuming that you do not want to commit the whole hunk (and thus, the whole file; because I am not sure why you would want to use git add -p
in that case?), you will want to specify option e
to tell git that you want to edit the hunk.
Once you tell git that you want to edit the hunk, it should drop you into your editor of choice so you can make your changes. All lines should be prefixed with a +
and git has some explanatory comments (prefixed with a #
) at the end of the file. Simply delete any lines that you do not want in your initial commit of the file. Then save and quit the editor.
Git's explanation of git's hunk options:
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
g - select a hunk to go to
/ - search for a hunk matching the given regex
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
s - split the current hunk into smaller hunks
e - manually edit the current hunk
? - print help