ankit0311
ankit0311

Reputation: 735

Git squash commits after pulling other commits from master branch

Suppose I have the following commits on my local branch A, which I then push to the remote branch.

commit 1
commit 2
commit 3
commit 4

Now, I pull from the remote master, and the commit history looks like this -

//From branch A
commit 1
commit 2
commit 3
commit 4
//From master
commit 5
commit 6

If I now want to squash commits 2 and 3 using git rebase -i and git push -f, will that rewrite commits 5 and 6 as well? If yes, is there a way I can squash my earlier commits without rewriting the commits I pulled from the master branch? I'm new to Git, so please excuse me if I'm missing something very basic.

Upvotes: 1

Views: 2264

Answers (2)

MBI
MBI

Reputation: 593

If you do what you suggest then content of commits 5 and 6 will remain unchanged (if there will be no rebase conflict), however their hash will be different, because their parents will change. So it won't be commits 5 and 6 anymore, but different one with the same content. Force pushing is ok, when you are sure nobody else is using that remote branch, otherwise you rewrite something he/she already pulled from the remote. I personally wouldn't do it on remote/master.

Upvotes: 0

Blue
Blue

Reputation: 748

Rebase won't rewrite those commits if you are in the feature branch and rebasing onto master. If your rebase range happened to run over commits 5 and 6, then they would get copied and modified, but you wouldn't lose anything. This is a normal operation, git doesn't change commits in-place, new ones get created with any required changes. Running git rebase -i master while inside your feature branch will copy the unique commits of your feature branch, and then re-apply them on an updated version of your branch.

Assuming commit 6 is your HEAD, commits 5 and 6 are essentially removed and reappear previous to commit 1 when the base of your branch is updated. Then commits 1-4 are replayed according to your instructions.

If, however, commit 1 was your HEAD, git rebase -i master will undo commits 1-4, and replay them with your squash instruction, resulting in a new history: 6 <- 5 <- 4 <- 1', where commits 2 and three have been squashed, and 5 and 6 are unaffected.

More details and better explanation on rebasing can be found here.

Upvotes: 2

Related Questions