Git Checkout Subdirectory with Sparse Shallow Checkout

A frequently asked question for git is How can I checkout only part of a repository? or How can I clone just a subfolder with git? Git doesn’t directly support this option, but since version 1.9 it comes pretty close. The answer is to use a combination of features, a git sparse checkout and shallow checkout.

Git sparse checkout

Git sparse checkout allows you to work on just a section of the repository covered by git, however even when you use a sparse checkout, it is only the checkout that is sparse, the entire repository with all its history. A git sparse checkout therefore only solves part of the problem, and certainly it prevents the developer from accidentally working on an unintended part of the repository.

Git shallow checkout

A git shallow checkout is a way of checking out and fetching only the very recent part of the git archive. It fetches the whole repository, but not the whole history - if you don’t want - this makes the checkout overall rather smaller. Provide an argument of –depth=1 to the git clone command to copy only the latest revision of a repo.

Git sparse and shallow checkout combined

Below is an example of how you do this combination in practice

 git init <repo> 
 cd <repo>
 git remote add origin <url to remote repo> 
 git config core.sparsecheckout true 
 echo "draft/*" >> .git/info/sparse-checkout 
 git pull --depth=1 origin master 

You can continue to commit and push as normal. To fetch new updates from the orgin repository use:

 git pull origin master