jhon354
jhon354

Reputation: 3

git reset --soft strange behavior

I wanted to squash 3 commits, before I push into the develop branch in the remote repository. I thought I'll use git reset --soft HEAD~3 (to remove my last 3 commits and make them in a single commit with a new commit message). However, when I wrote the command, I noticd that it didn't reset only 3 commits, but like 20 (don't worry, I had backup). After that, I thought I'd try again with previous commits (just to test the behavior), and I saw that it wasn't only deleting 3 commits, but a random number.

What could this be from? (Note: The "HEAD~3" commit had merge conflicts when pulling before that, that were solved by me, not sure if that could be the case).

Upvotes: 0

Views: 323

Answers (2)

Chris Maes
Chris Maes

Reputation: 37742

If you reset a merge commit, then you will remove all the commits that were merged into your branch...

Suppose you had another branch with 10 commits, which you merge into your develop branch. If you run now git reset --soft HEAD~1, then you will see all changes from these 10 commits.

more in-depth explanation

Suppose you have the following commits:

abc123 last commit (HEAD)
def456 merge feature2-branch (with 10 commits)
ghi789 add feature
jkl123 fix bug

HEAD (where you are in your history) is at abc123. When you execute now the command git reset --soft HEAD~3,

  • this does NOT mean: git, please remove the last 3 commits.
  • this does mean: git, please move HEAD to jkl123, but leave all files as they are.

So git does not have a notion of a number of commits, nor whether they are merge commits or whatever.

Upvotes: 1

tmaj
tmaj

Reputation: 34987

It looks like you merged into your branch then then run reset.

Here's a plan that could work.

  1. On your branch find the commit before you merged.
  2. git checkout last_commit_before_merge
  3. git branch -b feature/_X_attempt2
  4. Do you squashing - I recommend git rebase --interactive
  5. Follow your usual flow: merge master, push, create PR

After you rewind to your branch before the merge you can just rebase master on your branch with git rebase -i master. See Merging vs. Rebasing.


Note: This is all in the context that you don't share branches with others because rebasing (as well as your git reset method) rewrites history.

Upvotes: 0

Related Questions