Blog
Git Rebase and Amend
Posted on September 2, 2020 in Git by Matt Jennings
Amend a Commit
- Amend is a shortcut that lets you make changes to the previous commit
- Example code to add a file to the last commit:
git commit -m 'Add a blog post about Python'
git add posts/python.txt
git commit --amend
What is Rebase?
- Image our tech_posts and master branch have diverged.
- We don’t want a message merge commit in our history.
- We can pull in all the later changes from master, and apply our commits on top of them by changing the parent commit.
- Rebase = give a commit a new parent
(i.e. a new base commit)
- Doesn’t show a merge commit.
- The changes create linear path.
- Get a much cleaner and linear project history.
- Example code:
git checkout tech_posts
git rebase master
Power of Rebasing
- Commits can be edited, removed, combined, re-ordered, inserted, BEFORE they’re “replayed” on top of the new HEAD.
Interactive Rebase (rebase -i
)
- Interactive rebase opens an editor with a list of “todos”:
- In the format of:
<command> <commit> <commit msg>
- git will pick commits in specificed order, or stop to take an action when editing or a conflict occurs
- Interactive rebase with a shortcut:
git rebase -i <commit_to_fix>^
- (the
^
specifies the parent commit)
- Interactive Rebase Options:
- pick
keep this commit
- reword
keep the commit, just change the message
- edit
keep the commit, but stop to edit more than the message
- squash
combine this commit with the previous one. stop to edit the message.
- fixup
combine this commit with the previous one. keep the previous commit message
- exec
run the command on this line after picking the previous commit
- drop
remove the commit (tip: if you remove this line, the commit will be dropped too!)
Tip: “Amend” any Commit with Fixup & Autosquash!
- git add new files
git commit --fixup <SHA>
This creates a new commit, the message starts with ‘fixup!’
git rebase -i autosquash <SHA>^
git will generate the right todos for you! just save and quit.
Quit a Git Rebase
- At any time before rebase is done, if things are going wrong:
git rebase --abort
Rebase Pro Tips
- Before you rebase/fixup/squash/reorder make a copy of your current branch:
git branch my_branch_backup
- git branch will make a new branch, without switching to it
- If rebase “succeeds” but you messed up…
git reset my_branch_backup --hard
- Before pushing work to a shared repo:
Rebase to clean up the commit history
Warning: Never Rewrite Public History!
- Rebase commits are copies
- If other people are working on the same repository they would be working on different commits
- You could cause massive merger conflicts
- Even worse, you can cause people to lose their work!
Leave a Reply