Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I restore a Git repo and its Github remote to a previous commit without using reset?

Tags:

git

github

I have a Git repo and a remote on Github. (Please don't edit out the fact that it's on Github. It's relevant and it makes a difference in the answer. Thanks.)

I want to restore the master branch to a state 25 commits back.

I don't want to use git --reset hard ... and git push -f because I'd rather not wipe out the history.

Is there some way I can tell Git, effectively...

"Make everything in my working copy exactly like this previous commit back here, including removing files that didn't exist then."

...and then commit that state, and then push that to the remote?


I tried git revert but here's what happens...

$ git revert --no-commit d3289a7ab82fd76386d99bdd2c5e6496ecc62529..
error: Commit e88336ec528bc87dd6df3df82280b0fbd8c5a38d is a merge but no -m option was given.
fatal: revert failed

Then tried...

$ git revert -m 1 --no-commit d3289a7ab82fd76386d99bdd2c5e6496ecc62529..
error: Mainline was specified but commit 84ccf1084d17d470ee03b89a7649c4a783f2b914 is not a merge.
fatal: revert failed
like image 705
Ethan Avatar asked Feb 15 '23 18:02

Ethan


2 Answers

Yes, you can do (from the top-level directory):

git revert --no-commit <relevant SHA>..

You then commit as normal and push.

Note that you can get something similar using git checkout <relevant SHA> -- ., but that this doesn't delete files that have been added since the relevant commit.

like image 155
Stuart Golodetz Avatar answered Feb 17 '23 18:02

Stuart Golodetz


git revert is certainly the quicker way to do this, but it's worth mention that git reset is more flexible than just --hard:

git reset --hard $commit
git reset --soft '@{1}'
git commit

This means:

  1. Change the current branch to point to $commit. Make the index and working copy look like $commit.
  2. Change the current branch to point to where it was before you ran the first command, but leave the index and working copy looking like $commit. This should leave you with whatever changes are necessary to revert to $commit.
  3. Commit.
like image 39
Eevee Avatar answered Feb 17 '23 19:02

Eevee