Fix Mistakes Using Git
We all have done it. You write a program all seems well for a time until you accidentally save broken code to Git. There are many other mistakes we can make with Git and I will go into specific scenario’s.
Scenario: You pushed a broken commit to the repository
First off we need to understand there is no option to delete a commit. Despite that, there are still ways to fix it. Instead, you push a commit onto the end that does not contain the content of the last commit. Git works this way to avoid losing past work and angering your coworkers.
Scenario: You wrote code you need to wait until later to work on
You may want to store your code for later so that you can work on an unrelated problem first. In which case git stash is the command you are looking for.
git stash
Git stash stores your uncommitted code for short term storage.
git stash pop
Git stash pop will add the code back from the last time you stashed your code. You can also give your stash a specific name using git stash save [name].
Scenario: You forgot to make a change before committing
Instead of creating new commits each time you add changes you can run
git commit - amend - no-edit
This allows you to store the code you wrote in the same commit as you last pushed.
You can squash your commits before you push them by running:
git rebase master - interactive
If you have already pushed a large number of small commits you can still squash them by running:
git rebase -i origin/master~4 master
git push origin +master
Scenario: You want to find and remove a bad commit
git bisect start
git bisect good|bad
Scenario: You want to abandon your changes for the working remote version
git fetch origin;
git reset - hard origin/master;
git clean -df;
Scenario: You are fed up with your code and want to go back to a previous version
remove the content from the remote git or recreate a remote repository
rm -rf .git
Scenario: You started trying to merge your code before it is ready
git merge --abort
Scenario: You want to archive code you may need at a later date
You can tag commits you want to remember so you know which commit contains your archived information.
Bonus
As a bonus here is a command for pulling from master without dealing with merge conflicts. It will automatically accept masters version of the files. There may be a few things you need to look at your last commit to see why it is missing though so if there is a lot of overlap in the things you want to keep this may not be the best option.
git pull -s recursive -X theirs origin master
Resources:
Git cheat sheet | Atlassian Git Tutorial
Git Cheat Sheet — 50 Git Commands You Should Know (freecodecamp.org)