Shallow cloning with Git

Sometimes when you clone a Git repository, you just want a snapshot of the code without all the history associated with it. This is known as a shallow clone and can be accomplished through the use of the --depth argument on the command line:

git clone --depth 1 [repository URL]

The number passed to the argument specifies how many revisions to truncate the history, with 1 being the lowest possible number (using 0 will make the depth argument redundant).

For large projects, ignoring the history can make a substantial difference to the time taken to clone the repository, as well as the amount of data downloaded. A quick benchmark on the stable branch of the Linux kernel repository gave the following results on my machine (times are for counting and compressing the objects, and do not include downloading):

  • Shallow clone: 13.56 seconds, 48546 objects
  • Deep clone: 159.35 seconds, 3686666 objects

The disadvantage of a shallow clone is that the lack of history prevents you from cloning, fetching, pushing and pulling. However, the substantial reduction in data downloaded means it can be suitable for use on slow network connections or in automated deployments (e.g. using Vagrant) where you don’t want the history anyway. A shallow clone will still include the .git directory, but you can delete this if you are sure that you will not need to run any further git commands on your local copy.

A shallow clone can also be converted into a deep clone using the --unshallow argument within the cloned repository (only available in Git 1.8.3 and later):

git fetch --unshallow

If the connectivity between your machine and the remote repository is poor, you may also find that taking a shallow clone followed by conversion to a deep clone is more reliable than trying to take a full clone in one step.

Further reading

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.