Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reset my entire .git folder from a remote repository without affecting my checked out working folder?

Tags:

git

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?

like image 917
MikeJansen Avatar asked Jan 27 '23 01:01

MikeJansen


2 Answers

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.

  1. Determine which branch you are currently on:

    git status

  2. If you have custom hooks, save the .git/hooks folder

  3. Delete (or move) your .git folder from your working copy

  4. Re-initialize a git repo in your working copy:

    git init

  5. Add your origin remote manually:

    git remote add origin *url*

  6. Fetch the remote repository:

    git fetch

  7. Re-create the branch that your working copy was on before you started:

    git checkout -b *branch*

  8. Point that branch reference to the remote branch without affecting the working copy:

    git reset --mixed origin/*branch*

  9. Copy any saved hooks into the .git/hooks folder.

  10. 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).

like image 190
MikeJansen Avatar answered Jan 29 '23 08:01

MikeJansen


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.

like image 27
Kaz Avatar answered Jan 29 '23 06:01

Kaz