git-cheatsheet
Last tended June 28, 2023.
Amend a previous commit
You’ve finished your code, submitted the PR, and the CICD server spits out an issue with a 1-line change. You fix it and commit your change, just to get the next one. Then there’s another, and another, and another one. Rather than having many simple changes for 1 error at a time, you can amend your previous commit with the change so the commit history is cleaner.
git commit --amend
Go back to an old commit
This command will rewind history locally to the specified git commit.
git reset --hard <commit hash>
If you want to erase the changes that followed on the remote copy, you can additionally run:
git push -f
Which will force git to push your current history and overwrite whatever currently exists on remote.
Merge changes from branch A into branch B
This is generally not the best way to go as it replays all the changes in the git history. Instead consider a rebase.
First, make sure you have the latest remote changes locally.
git fetch
git pull
Make sure you have the branch you want to merge changes into checked out locally:
git checkout <BranchB>
And then merge the changes from branch A in:
git merge <BranchA>
Rebase changes in a branch onto a newer commit from the parent branch
This creates a clean, linear history of changes and avoids the need for merge resolutions when completing a PR.
Make sure you have the latest commits from the branch you made changes to (delta
in this example) and the main
branch that has been updated:
git checkout main
git fetch
git pull
git checkout delta
git fetch
git pull
The rebase the changes in delta
onto the latest commits from main
. Note that this needs to be done while delta
is checked out:
git checkout delta
git rebase main
Move changes from a protected branch to a feature branch after accidentally committing without switching branches first
Often I will pull latest from the main
branch and start making changes for the ticket I’m working on. After some progress I will then commit my changes, forgetting that I didn’t make a feature branch first. Since the main
branch is protected and requires a PR to push to origin
(the remote copy), I can’t do anything with those changes. In this scenario I need to move my changes from main
to a feature branch. There are a couple ways I’ve found to do this.
Option 1 works conceptually by taking the following actions:
- Undo my last commit to
main
- create & checkout a new feature branch
- commit my changes to it
git reset --soft HEAD~1
git checkout -b feature/my-new-feature
git commit
Option 2:
- Create a branch from my commit locally
- Push my new branch with changes
- Checkout my local
main
branch - Reset it to the same commit as on
origin