Search code examples
gitgithubcommitgit-pushgit-commit

push to the top leaving middle two commits


Let's say I have following commits

cccc[recent]

bbbb

aaaa

Now I have bugs in cccc and I have rolled back to aaaa by

git reset --hard aaaa

and I have worked here,this all happened in bugs branch

Now when I try to push the cmmits to the bugs branch it is telling

! [rejected]        bugs -> bugs (non-fast-forward)
error: failed to push some refs to 'my url'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

I want to push my changes and remove the bbbb and 'cccc` commits.

how to do this?


Solution

  • Since you already pushed it you should do a git revert instead of a forced push

    $ git revert cccc
    $ git revert bbbb
    

    This will leave the commits cccc and bbbb in the history and introduces new commits on top of them that revert the changes.

    o-----o-----o-----o-----o
    ^     ^     ^     ^     ^
    |     |     |     |     |
    aaaa  bbbb  cccc  cccc' bbbb'
    

    If you want revert bbbb and cccc in one commit do

    $ git revert --no-commit bbbb
    $ git revert --no-commit cccc
    $ git commit -m 'Reverted commit bbbb and cccc'
    

    If you want to revert the changes by doing a forced push

    $ git reset --hard aaaa
    $ git push -f
    

    you should make sure that no other developer has already made commits on top of bbbb or cccc.