If you have been using Git for the past few months/years and you’re still struggling with it daily, you landed at the correct place. I expect a little exposure as a prerequisite. Honestly admitting, I ain’t saint & neither a certified expert in Git, but I’ve learned a lot during my quest in resolving issues. I’ll try to make this post from beginners’ to an advanced level. Consider this as a Git FAQ. For the sake of convenience, I’ll be breaking the blog in multiple parts. So, stop panicking!
Git Panic
This blog isn’t a walkthrough or TL;DR for some best practice that we follow around in MayaData, that will be covered probably in some other blog. This blog consists of the workaround or the fixes of some gitty situation where people start panicking and screws-up the working directory.
Switching your branch when your workspace is dirty or there are some uncommitted changes. Example:
$ git checkout master
error: Your local changes to the following files would be overwritten by checkout:
app/utils/util.js
Please commit your changes or stash them before you switch branches.
Aborting
Fix:
Method 1:
If you need these changes later, stash them and check out the branch. You can pop changes anytime on any branch you want.
$ git stash
Saved working directory and index state WIP on eslint--fix: b6579b1 [eslint] Run eslint app/ --fix
$ git checkout master
Switched to branch 'master'
To get the changes back again
$ git stash pop
Method 2:
If you don’t want any of those changes and want to discard them.
$ git checkout -- .
ProTip: If you want to discard some file and stash some, use both in the combination of git checkout -- path/to/filename followed by git stash.
Add the files and commit again with --amend flag.
$ git add app/index.js # index.js is missing from commit
$ git commit --amend
ProTip: git commit --amend can be used for removing unwanted files from the commit as well as rewriting the commit message.
$ git cherry-pick commit-hash
$ git reset HEAD --soft
$ git checkout my-feature-branch
# Now stage files and commit again
ProTip: To reuse your previous commit message do git commit --reuse-message=HEAD@{1} or for a shorter version of this git commit -C HEAD@{1}
$ git fetch -a
$ git cherry-pick 1acb2e
Too many untracked files
The scenario when you have so many untracked files in git and you want to get rid of it, git checkout -- . won’t work, not even git stash will work. rm -rf will work, but that may involve too many steps. Then how to get rid of all the untracked files in one shot.
$ git clean -fd
# The elegant git log
$ git log --all --graph --decorate --oneline --simplify-by-decoration
# Unstage and remove paths only from the index
$ git rm --cached
# View diff on staged file
$ git diff --staged
I hope you find this blog useful during your quest. In the next follow-up blog, I’ll write about Rebase: went wrong, multiple scenarios, and their fixes. Till then, GodSpeed!