cnd
cnd

Reputation: 33754

Is it possible to merge commits in git?

Sometimes (it happens often) I make mistakes and making a kind of "fast fix" after push.

but for some commit clarity sometimes I'm making re fork (if that was in my fork) and make, commit all changes Again.

Is there someway to merge commits?

Upvotes: 4

Views: 107

Answers (2)

c00kiemon5ter
c00kiemon5ter

Reputation: 17624

Yes. What you want to look into is rebase. try

$ git help rebase # and read it

another option is git commit --amend. If the commit you are about to make should be merge with the current HEAD, you can amend it.

Both those options, rewrite history. So you will need to git push -f to send your changes upstream, if the affected commits are already on the remote end.


for an simpe example use case of rebase, suppose you have made 5 commits,

A--B--C--D--E
^ initial   ^ HEAD

and commit B is a quick fix to commit A,
and commit E is a quick fix to commit C.
So you want to merge B to A, and E to C.

$ git rebase -i HEAD~5  

you start with this:

pick A msg
pick B msg
pick C msg
pick D msg
pick E msg

you rearrange the commits so that the ones to be merge are below the ones to be merged into; that is B below A(already there) and E below C.

pick A msg
pick B msg
pick C msg
pick E msg
pick D msg

and you tell git, not to pick the commit, but to squash it; that is merge it to the above one - or fixup it - see the man page.

pick A msg
squash B msg
pick C msg
squah E msg
pick D msg

all done, save the file and git will rearrange and squash the commits.
so now you have:

A'--C'--D

Upvotes: 1

Samy Dindane
Samy Dindane

Reputation: 18706

Yep, there's a way, and it is called squashing.

git rebase -i sha1_of_the_first_concerened_commit

Then replace all the edit of the commits below the concerned commit by squash (or s), save the file, and continue rebasing with git rebase --continue.

The next time you'll push, your push will probably be rejected, you'd need then to git push -f.


But in your specific case, there's no need to go trough this all, you can use commit --amend instead.

Let's say you commited, then made a quick fix on file1. You'd just need to add your file to the staging area:

git add file1

Then:

git ci --amend

And finally force push:

git push -f

Be careful when rewriting history, it is fine when you're the only one working on a repo, or you're sure no one pulled after you, otherwise it's a pain for the others.

Upvotes: 3

Related Questions