A git trick: interactively add untracked files
Attempting to patch untracked files
In order to cleanly commit my work into clear separate steps, I found myself trying to do this.
git add -p <untracked-file.cpp>
For those unfamiliar with git, what I hoped to do with this command was to add my untracked file, and patch it interactively
(-p is a shortcut for --patch) at the same time. My goal was to remove some lines that I would put back in a following commit.
Otherwise, I would have had to make a temporary copy of my source files elsewhere, edit those to adjust what would actually
be commited, run git add and git commit, and then restore the copied file into my project to proceed with the next commit.
This would work, for sure, but would be rather inconvenient and cumbersome, especially with several files to change.
To my disappointment, all I got from git was:
No changes.
Well, this error wasn't particularly helpful, so I tried:
git add -e <untracked-file.cpp>
Still no luck, but this time the error was:
fatal: empty patch. aborted
Not particularly helpful either.
It turns out that for those options to work, the file must be tracked, already in the git index. Which is not the case for
untracked files, obviously.
Enabling selective staging of untracked files
I began to resign myself to making copies of my files elsewhere, before editing them manually in order to not lose my changes.
But then, I discovered the -N aka --intent-to-add option of git-add. It allows
registering untracked files in the git index, without actually staging changes. So then, I could git add my file selectively.
To sum up:
git add -N <untracked-file.cpp>
git add -p <untracked-file.cpp>
The
-Noption also allows seeing the changes of untracked files withgit diff, since they are in the index now.
Takeaways
As always, RTFM really helps. However, I think that having git outputting clearer error messages would also help.
Anyway, I have added the --intent-to-add option into my personal git toolbox, and it's ready to use. Beware, untracked files!