Search code examples
gitbranchgit-merge

How to completely ignore pushed commits and merged with master branch?


After pushing some commits on the dev branch, and merging them with master branch. I want to back to 4 commits ago. I can do that using git reset --hard <hash-id> (which hash-id is the 4th previous commits)

but when I want to push it again on the dev branch, it says "do a git pull first" because news changes exits on the remote dev branch.

To fix the problem, I run the following commands:

git reset --hard <hash-id>
git clean -d -f
git push -f origin dev

Now the dev branch is what I want, but when I want to merge it with the master branch it says "no changes found".

It is very strange, because the code base is different in branch dev and master, but it says that no changes were found. How can I make the dev branch and master the same content?


Solution

  • This is happening because you cannot remove commits using merge, and you already merged those 4 commits that used to be on dev into master. If you want them gone from master also you'll need to do a hard reset of master to before the merge of dev, and then force push master as well. (This assumes you are OK with force pushing master; see the Side Note below for an alternative.)

    The reason you see "no changes found" when merging dev into master, is because Git looks at the commit IDs to see which commit IDs are on dev that are not on master. Whether you reset dev back 1 commit, or 100 commits you'd still get that same message because there aren't any new commits on dev that aren't already on master.

    Side Note: An alternative way to "undo" those 4 commits, instead of resetting backwards like you did, is to use revert. If the merge of dev into master created a merge commit on master, then you can simply revert that merge commit on master and it will undo the changes brought in by those 4 commits. Whether you should reset or revert is usually dependent on whether the branch is shared or not. If other people are using the master branch then resetting and force pushing it could mess them up, so revert would be preferred.

    Another Side Note: You also mentioned:

    How can I make the dev branch and master the same content?

    Doing as mentioned above will achieve your goal, however if by "same content" you also mean that dev and master should point to the same commit, then your reset command of master could simply be:

    git switch master # checkout master
    git reset --hard dev # point master to what dev is pointing to
    git push --force-with-lease # this is safer than just --force