gitshallow-clone

Convert git full clone into a shallow clone


How can a deep clone of a repository be turned into a shallow copy IN PLACE?

I am managing separate installations of our software using git to track any changes to the code in the installation made runtime (untracked & dirty files), but the repository is pretty large (800MB), so having about a few hundreds of copies laying around is not the best idea.

So it would be great if these repositories could be turned into a shallow copy containing only the currently deployed commit, rather than the full tree. During an upgrade the repo would be converted back to a deep clone, the specific commit checked out, and then made into a shallow clone of the new commit.

git fetch --depth=1 --update-shallow does not shrink the .git directory size, I guess it would fetch any new commits, but it doesn't delete the old data. Adding --shallow-exclude=HEAD^2 makes git throw an error, not entirely sure how that should work though, I would hazard a guess it's getting conflicting requirements removing HEAD^2, but wanting to check out HEAD, which would depend on HEAD^2 in a deep clone.

error: RPC failed; curl 18 transfer closed with outstanding read data remaining
fatal: The remote end hung up unexpectedly

Solution

  • Ok, so this was the solution in the end:

    ORIGIN_URL=$(git remote get-url origin)
    COMMIT=$(git rev-parse HEAD)
    
    rm -rf .git
    git init .
    git remote add origin $ORIGIN_URL
    git fetch origin $COMMIT --depth 1
    git reset --mixed $COMMIT