3

I made an unintended commit and pushed to the remote. But then I wanted to undo it. So I executed:

git reset --hard HEAD^

HEAD is now at b760747 random commit

Then I made some changes and attempted to add+commit+push it. But it failed with the following error message:

! [rejected] postacl -> postacl (non-fast-forward) error: failed to push some refs to (repository-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.

How can I get everything back to normal?

Tanmay
  • 3,009
  • 9
  • 53
  • 83
  • 1
    Possible duplicate of [Resetting remote to a certain commit](https://stackoverflow.com/questions/5816688/resetting-remote-to-a-certain-commit) – The Godfather Aug 19 '18 at 13:26

2 Answers2

2

You need to do force push to remote server. That way it would fix your problem. You can do it by the following command.

git push -f origin branch_name

But be careful, because this would overwrite the git history. You can read about the problems in this article

Arghya Saha
  • 5,599
  • 4
  • 26
  • 48
  • Is that a problem if git history is overwritten? – Tanmay Aug 19 '18 at 10:30
  • I have attached an article. Kindly go through it and also consult your other team members before you do `git push --force` – Arghya Saha Aug 19 '18 at 10:33
  • 1
    You should also be aware that it is now preferable to use '--force-with-lease' that bring a little more security by preventing the lost of other developers commits that you didn't see/fetched. – Philippe Aug 19 '18 at 12:32
0

( Disclaimer : if you're alone on your repo, go for argo's quick and efficient method! )

I'd like to add the alternative to the forced push method which could, in some contexts, be a big no-no (namely, if you're not alone on the repo then people could (and will!) have history conflicts with your rewritten master on the repo).

It's no big secret but let's add it for completion :

# make sure you're on the right branch (here I assume it's "master")
git checkout master
# let's get upo-to-date with the (now wrong) remote master
git pull
# alternatively to this pull, you could have undone your reset with reflog
# be free to use the one you're more familiar with

# locate the "bad" commit and store its hash for further use
# (I'll do a log but you could have prefered methods.)
git log --oneline

# create a commit which has the exact opposite modifications of <bad> commit.
git revert <bad>
# (no need to commit the previous action since the commit is already created)

# push the new commit on top of remote master (I assume "origin" for your remote)
git push origin master

I'll grant you it seems slightly clunkier and adds noise to the history, BUT you didn't rewrite history and your co-users will hate you less. Hurray!

Romain Valeri
  • 19,645
  • 3
  • 36
  • 61