aloo
aloo

Reputation: 5389

Take arbitrary git working copy and make exactly the same as remote branch

Say I have an arbitrary local git working directory that was cloned from some remote. I want to make the local git repository be EXACTLY the same as the remote, irrespective of what's happened to the local directory since it was cloned. I do not want to do another full clone.

Say the local working directory has:

Now I want to make this local repository reflect remote exactly. Here's my current solution but I'm not sure if it covers all cases and whether there is an easier solution:

git stash
git clean -f -x -d
git checkout master
git fetch origin
git reset --hard origin/master
git pull origin master

Is there a better way to do this?

Upvotes: 4

Views: 1506

Answers (2)

Adam Dymitruk
Adam Dymitruk

Reputation: 129664

git reset --hard

will dump any changes that you have including any you have staged.

git clean -xdf

will get rid of anything in your working directory that git is not tracking due to ignore or exclude.

git checkout HEAD

will put you on no branch so you can clean everything out.

git branch | xargs git branch -D

will delete all your local branches

git tag -l | xargs git tag -d

will delete all your tags

git prune origin

will get rid of any tracking branches that are no longer on the remote

git fetch

will get any branches and tags from the remote that you don't have. You can stop here and checkout any remote branches you want to work on while creating a local branch with

git checkout origin/master

or you can create local branches that point to where all existing remote branches are pointing to as of your fetch with

git branch -r | xargs -n 1 git checkout

Upvotes: 3

Amber
Amber

Reputation: 527103

The following set of commands should get you into an identical state with the remote branch:

git checkout -f master                # Check out the local 'master' branch
git fetch origin                      # Fetch the 'origin' remote
git reset --hard origin/master        # Reset all tracked files to remote state
git clean -dxff                       # Remove all non-tracked files

Note that (for obvious reasons), these commands are potentially destructive - that is, any local changes that are overwritten by this and not saved in a commit accessible by some other means will be lost.

Upvotes: 3

Related Questions