Meltemi Meltemi - 1 month ago 14
Git Question

Github: reset to previous commit

Small team. A colleague pushed to

origin:master
by mistake. He has reset his local repo but cannot
push -f
to Github because repo is protected.

I have
fetch
ed the repo but not merged his errant commit into my local
master
...yet.

How can I, assuming I can
push -f
to origin, reset
origin
on Github so that it reflects the state it was in before his mistake?

$ git push origin 2860a4c:master
To github.com:example/myproj.git
! [rejected] 2860a4c -> master (non-fast-forward)
error: failed to push some refs to 'git@github.com:example/myproj.git'
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.


Do I really need to integrate the bad commit (with
git pull
) before I can then, I assume,
reset hard 2860a4c
and then
push -f origin
?

I just don't want to make things worse.

Answer

Below are the steps you may do, assuming you have permission for git push -f.

On your machine, do:

# Step 1: Take the changes from remote
git pull

# Step 2: Note the commit to which you want for restoring your repo to 
# using `git log`. Say the commit id is "x". 
git log

# Step 3: Do hard reset for that commit. All the changes after commit "x" will be gone
git reset --hard x    # where x is the commit id

# Step 4: Push to remote
git push -f

Then on collegue's machine, do step 1 to step 3 and then do git pull to merge the remote changes


In case you do NOT have permission for git push -f, do:

git pull

git revert <commit id>   # may get it via "git log"

git push

With git revert, changes from the reverted commit will be removed, but this commit will remain in the commit history.