Palace Chan
Palace Chan

Reputation: 9213

How to permanently undo recent commits from git remote but keep it in my local?

I made a git repo (only a master branch) with one remote and one local. There are no other users who have cloned it but the remote path can be cloned by a few users.

My local clone is at commit #17 and I have pushed up til commit #12 to the remote. I’ve come to realize that every commit after #6 should not be shared and the remote needs to (for now) remain at #6.

I don’t want to lose all the commits 1-17 and the history but in order to reset the remote my understanding is I have to first reset local to #6 and push -f that. Is it possible for me to reset the remote to #6 while locally remaining ahead at 17 so that if someone clones the remote they can’t see the vulnerable commits?

My idea is that I would need to clone my local to a different local first so that the second local keeps all 17 commits and history before executing the reset followed by the push -f. Is this how one would approach this situation?

Upvotes: 0

Views: 98

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522626

I recommend creating a new feature branch from your local master, to record the commits up to #17. Then, do a hard reset of your local master and force push:

# from local master
git branch feature
# now hard reset to commit #6
git reset --hard HEAD~10
# force push
git push --force origin master

Now the local feature branch represents the previous state of your master branch, up to commit #17, while local master is at commit #6, and is in sync with the remote master.

Upvotes: 2

dunajski
dunajski

Reputation: 389

So you want to push another branch but have commits from remote on your local (private) repo.

  1. Then make new branch with state of this remote to get local copy of this branch git branch <branch_name>
  2. Checkout local branch that you pushed, back history to point that you want to with reset or rebase git reset --hard
  3. Push with force flag git force --push

The part I’m not sure of is that the new local git clone probably still has the same remote in its remotes - would it be invalid to then push to the remote from there?

I'm not sure what you asking about but when you pushed something to remote, then there should be this remote after your clone - that's normal.

By the way, remember:

Do not rebase commits that exist outside your repository and people may have based work on them. If you follow that guideline, you’ll be fine. If you don’t, people will hate you, and you’ll be scorned by friends and family.

Upvotes: 0

Related Questions