Cleaning Your Workspace
It is common to get rid of unwanted changes in your workspace. But cleaning up is not straight forward as it should be. We use clean command to remove untracked files/folders and checkout for unstaged changes on tracked file.
Remove Untracked Files and Directories
git clean -f # removes files git clean -d # removes directories git clean -fd # short hand for the above two git clean -n # dry runs the command and shows list of removing files
It is not possible to get back files removed with git clean command the safer option is to use git stash –all
Undo Unstaged Changes in Tracked Files
git checkout # undo a single file git checkout . # undo all file under current directory
another alternative to clean and checkout commands is stash and remove the stash
git stash # git stash the uncommitted/untracked changes git stash drop # get rid of the stash
Resetting Changes
Resetting staged changes
$ git reset # resets staged changes to unstaged $ get reset --hard # resets and deletes staged changes
Resetting the last commit
$ git rest HEAD^ # resets the last commit to unstaged
Resolving Common Git Issues
Refusing to merge unrelated histories
This may happen on first pull request after adding a remote git repo. Use this flag to resolve it.
--allow-unrelated-historie
Squashing Commits
It is highly recommended to get rid of noisy commit message and squash them into a single message. This is specially important when you are done working on your dev branch and ready to merge into master.
Squash last 5 commits and give them a single commit message
$ git reset --soft HEAD~5 && git commit # Squash last 5 commits into one
Cherry Picking
Sometimes you want to pick only a specific commits from another branch and add it to a current branch. This is specially useful when you have difficulty resolving conflict during merge or rebasing.
$ git cherry-pick <commit_hash> $ git cherry-pick <commit_has_oldest>..<commit_has_newest> #pick range of commits