Sometimes you might make some mistakes in the source control process. In this reading, some common issues are outlined along with their solutions.
Say you're preparing to commit some work and you instinctively ran git add . without checking git status beforehand and staged all changed files. Say you ended up adding a file with sensitive information inside that should not end up on a public repository.
To fix this, you can simply run the following command:
git reset <file path>
This will unstage the file and you can commit as usual.
git reset can do more than un-stage files; it can roll back entire commits. Say you didn't notice you git added a file and already committed. Worry not! It's not the end of the world (yet). If you haven't pushed the code, it won't be publicly viewable yet.
To roll back the last commit you just made, run the following command:
git reset --soft HEAD~1
This will un-commit the last commit and keep all the changes you made, just not staged and committed.
If you want to roll back the commit entirely and erase all the changes you made, run:
git reset --hard HEAD~1
Say you've massively screwed up and made multiple commits unchecked. To revert to a previous known commit, get the commit ID and run:
git reset --hard <commit ID>
To get a list of your commit history, you can run:
git log
Say you're working on a branch and realize you were supposed to make the changes on a different branch. When you try to checkout to the other branch, Git gives you the following error:
error: Your local changes to the following files would be overwritten by checkout:
<files that would be overwritten>
Please commit your changes or stash them before you switch branches.
Aborting
One option would be to commit the changes as mentioned and then merge the current branch into the one you should've made the changes on. However, this is cumbersome and requires you to go through the risky process of merging and/or making a pull request.
Instead, you can use the following command to "stash" your changes:
git stash
This temporarily stores all your changes on modified or tracked files so that you can switch branches safely. Once you've switched to the branch where you want these changes actually made, you can run:
git stash pop
This brings in all the changes you made on the first branch. If you decide that you no longer want the stashed changes, you can just run:
git stash drop
This is by no means a comprehensive guide to fixing your Git and GitHub related issues. Check out GitHub's Git Cheatsheet for more useful commands.