In Git you can merge several commits into one with the powerful interactive rebase.
@dr0i You can merge as many commits as you want, as long as they are the last X commits, and not somewhere in the middle. Just run git reset --soft HEAD~10 , where 10 is the number of commits you want to merge. This can be used if you don't have a remote origin set, and you only have two commits.
You want to git rebase -i
to perform an interactive rebase.
If you're currently on your "commit 1", and the commit you want to merge, "commit 2", is the previous commit, you can run git rebase -i HEAD~2
, which will spawn an editor listing all the commits the rebase will traverse. You should see two lines starting with "pick". To proceed with squashing, change the first word of the second line from "pick" to "squash". Then save your file, and quit. Git will squash your first commit into your second last commit.
Note that this process rewrites the history of your branch. If you are pushing your code somewhere, you'll have to git push -f
and anybody sharing your code will have to jump through some hoops to pull your changes.
Note that if the two commits in question aren't the last two commits on the branch, the process will be slightly different.
Lazy simple version for forgetfuls like me:
git rebase -i HEAD~3
or however many commits instead of 3.
Turn this
pick YourCommitMessageWhatever
pick YouGetThePoint
pick IdkManItsACommitMessage
into this
pick YourCommitMessageWhatever
s YouGetThePoint
s IdkManItsACommitMessage
and do some action where you hit esc
then enter
to save the changes. [1]
When the next screen comes up, get rid of those garbage # lines [2] and create a new commit message or something, and do the same escape
enter
action. [1]
Wowee, you have fewer commits. Or you just broke everything.
[1] - or whatever works with your git configuration. This is just a sequence that's efficient given my setup.
[2] - you'll see some stuff like # this is your n'th commit
a few times, with your original commits right below these message. You want to remove these lines, and create a commit message to reflect the intentions of the n commits that you're combining into 1.
git rebase -i HEAD~<quantity of your commits>
(i.e. git rebase -i HEAD~5
)txt
file change pick
keyword to squash
for all commits, except first commit (which is on the top). For top one change it to reword
(which means you will provide a new comment for this commit in the next step) and click SAVE! If in vim, press esc
then save by entering wq!
and press enter.Done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With