Robert Robert - 26 days ago 12
Git Question

Converting git repository to shallow?

How can I convert an already cloned git repository to a shallow repository?

The git repository is downloaded through a script outside of my control so I cannot do a shallow clone.

The reason for doing this is to save disk space. (Yes, I'm really short on disk space so even though a shallow repository doesn't save much, it is needed.)

I already tried

git repack -a -d -f -depth=1


But that actually made the repository larger.

Answer

Let's say the earliest commit you want to keep has a SHA1 of c0ffee.

  1. Create a new empty branch
  2. Checkout the tree of the earliest commit you want to keep, without actually checking out the commit: git checkout c0ffee -- . (Now HEAD is still pointing to your new empty branch, but your working tree and index both look like the tree of c0ffee)
  3. Commit the whole tree: git commit -m "Initial commit, copied from c0ffee"
  4. At this point git diff-tree newbranch c0ffee should produce no output -- they have the same tree. (Alternatively, you could do git show -s c0ffee --format=%T and git show -s newbranch --format=%T and they should show the same hash.)
  5. git rebase --onto newbranch c0ffee master
  6. git branch -d newbranch
  7. git gc
Comments