2

I accidentally edited some files I didn't need to and pushed them to Github.

I'd like to revert them to the version on master. I tried

git checkout -- <myfile> but this had no affect.

Would anyone know what to do?

MeltingDog
  • 14,310
  • 43
  • 165
  • 295

3 Answers3

3

You need to reset your file locally to a previous version (for instance @~, which is the previous commit)

git checkout @~ -- myfile

git commit -m "reset file"
git push

If you don't mention a previous commit, git checkout would restore your file to its current state in the index... and since you did not modify the file since the last push, its index is the same as HEAD. That is why your git checkout did nothing: there was no difference.

If you haven't pushed yet, you can use the same type of command to revert to what is on GitHub:

git fetch
git checkout origin/master -- myfile
git commit -m "reset file to origin/master"
git push
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Why do you need `git add . `? My understanding is that when a file is checked out it is already added to staging. – Akavall Dec 20 '17 at 06:15
  • @Akavall Right, I was a bit hasty there. Fixed. – VonC Dec 20 '17 at 06:17
  • @VonC thanks. I've done dozens of commits and so it might be hard to find the right one. Is there not a way to simply copy the file from Master (apart from looking at the master branch on Github and copy/pasting the contents of the file)? – MeltingDog Dec 20 '17 at 22:34
  • @MeltingDog Yes, there is. I have edited the answer accordingly. – VonC Dec 20 '17 at 22:36
0

Assuming you are also on the master branch, and that the entire commit you just pushed consisted only of the incorrectly edited files, then another option to consider here is git revert:

git revert HEAD

This would add a new commit on top of master which undoes all the incorrect file edits. You would then only need to push this revert commit to the remote.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

git checkout -- <myfile> works for changes that are not committed. In your case, changes are already committed. You need to do the following

1) git reset HEAD~1 HEAD~1 takes you back one commit. You can change it to how many ever commits you want to undo.

2) git checkout -- <myfile>

3) git push origin <branch name> -f -f is necessary here to forcefully push those changes as git will resist these changes.

VonC's answer will create a new commit. Use this if you want your commit history clean.

Rajeev Desai
  • 144
  • 2
  • 12