HarvesteR HarvesteR - 3 months ago 21
Git Question

Clear out git working directory

I've just finished a git clone here on a new computer, and I now have the repo in an interesting state:

There is no branch checked out. The working directory is empty, but the repo is all here, compressed in the .git metadata.

Of course, the missing step here is to do a

git checkout
to get the working copy onto a branch, but this state got me thinking. This is a fairly large repo, one which I don't expect to need access to very frequently either, so I'm now wondering, is there a way to return to this 'clean' state, where no branches are checked out, and the files exist only as metadata?

It would go a long way in saving up some disk space.

I thought about deleting all local files once I'm done, but that would then show up as uncommitted removals on that branch. I'd like to find out if there is a way to simply 'clear out' the working directory, disconnecting it from all branches on the repo, and leaving only the metadata in the repo directory.

One possible solution here might be to create a branch where all files are deleted, but that doesn't sound very elegant. Maybe a more direct approach exists?

As always, thanks in advance!

Cheers

Answer

Well, I believe I've found my own answer here. It is possible!

Git has the concept of 'orphan' branches. This is a branch that has no history relationship to any other commits on the repo history. This allows us to check out to 'no commit' by doing:

git checkout --orphan none

and then

git rm -rf .

That effectively gets rid of all files, and because the 'none' branch has no ancestry, the deletions don't appear as removals. The metadata folder stays put, so to return to a valid branch, you just do another checkout.

More info here: https://coderwall.com/p/0n3soa/create-a-disconnected-git-branch

Gotta love git!

Cheers