Git tips and tricks for every day usage
Git is one of the tools I use on a daily basis. I can not imagine living without a version control system anymore. Most of the popular git commands are easy to find in the web and most of Git users are familiar with them. However, there are a few tricks I use on a daily basis, which are worth mention.
Commit changes skipping whitespace adjustments
From time to time there is a situation that I’m using a random text editor to adjust few files quickly. Sometimes such text editor is changing line endings from CF/LF to LF or vice versa. Sometimes there are extra spaces or empty lines added which I don’t want to commit. In such cases this command is handy:
git diff -U0 -w --no-color | git apply --cached --ignore-whitespace --unidiff-zero -
The first part generated diff output, without context lines before and after the actual change. Whitespace changes are ignored and the diff output is sent to the git apply as the patch. Git apply is patching the files, ignoring whitespaces. As the result we have a set of files staged for the commit, so we only need to commit these changes and clean up remainings.
Cleaning up the branch
After such “skip whitespace” operation as described above, I typically end up with some “whitespace only” changes I want to skip completely. The same with the test uploads, one-minute changes and so on. There are untracked files, unused directories and other stuff that I want to remove. In other words – I want to restore my branch to the clean state. In such case I use the following:
git checkout -- . && git clean -fd .
This script contains two commands. The first is reverting all changes to the tracked files to the status indicated in the last commit. The second is cleaning up untracked files and directories. Be careful – you can remove the directory you need if it is untracked.
Review the difference between branches without actual merging
Sometimes I want to check if the merge can be performed without issues or simply to check what are the differences between branches I’m working on. There is a possibility to generate merge but not to actually commit it. To do this use this one:
git merge --no-commit --no-ff [branch_to_merge]
Once the merge is done, you can review the differences using:
git diff --cached
The changes you see can now be committed as always or reverted this way:
git reset --merge