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 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 outputNo changes.
and stop. I had to tell git that I intended to track the new file first.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 optione
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:
To do this with every new files, you can run:
If you want to use it frequently, you can create an alias in your
~/.bashrc
:N.B: If you use this with an empty new file, git will not be able to patch it and skip to the next one.
There's also a very similar approach making use of the
--cached
flag...1) Turn your unstaged changes into staged, just like your added file.
2) Look at the diff (note: you can include both edits and new files).
3) Create the patch.
git add -p
is really about adding changes to already tracked files.The command to interactively select files to add is
git add -i
. For example:(The real command has colors which I couldn't cut-and-paste here, so it's nicer than it seems)
Actually, the patch command of
git add -i
does the same asgit add -p
, so the second is a subset of the first (even though I admit I loveadd -p
and hateadd -i
myself!).