If something seems messed up in my .git
folder and I can't fix it, but I want to preserve my working folder exactly the way it is, how do I "reset" my .git
folder from a remote repository?
The process below can be used to "fix" your .git
folder by re-initializing it from the remote. This process assumes that your current local branch is on the same commit as the remote branch. If not, you will lose any local commits, but you won't lose local changes. Also any local files that are "ignored" will be intact.
Also, any local-only branches will be lost. Push those branches to the remote first if you want to preserve them. You could also copy your entire pre-fixed up working folder locally, add it afterwards as a "remote", and pull those branches into your fixed up copy (after the steps below are done).
It is best to backup your entire local working folder tree before starting in case an unexpected problem occurs.
Determine which branch you are currently on:
git status
If you have custom hooks, save the .git/hooks
folder
Delete (or move) your .git
folder from your working copy
Re-initialize a git repo in your working copy:
git init
Add your origin
remote manually:
git remote add origin *url*
Fetch the remote repository:
git fetch
Re-create the branch that your working copy was on before you started:
git checkout -b *branch*
Point that branch reference to the remote branch without affecting the working copy:
git reset --mixed origin/*branch*
Copy any saved hooks into the .git/hooks
folder.
If necessary, do any cleanup like reverting files, etc.
Improvement of using git reset --mixed
instead of git reset --soft
plus git add .
provided by @MarkAdelsberger (see comments).
Improvement of saving off the .git/hooks
folder provided by @gary-kindel (see comments).
Let's assume we're in the directory above the messed up repository, which is called repo
, and we are in a shell environment with GNU Coreutils:
rm -rf repo/.git
git clone -d url://remote/repo -b some-branch new-repo
cp -a repo/. new-repo/.
Now use new-repo
, or else:
$ rm -rf repo
$ mv new-repo repo
The point here is that we get a fresh copy of the remote repo checked out to the branch we want, without any of our files being in the way of same-named files. Then we copy our working copy over top of that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With