>>FIRST MISSION//LOGS//cli//checkout-specific-directory-within-git-repo.MD
[ + ] TARGET_LOCKED200 OK
AUG 01, 2019timer 3 MIN READSYS_TAG: cli STATUS: VERIFIED_WORKING

Checkout Specific Directory Within Git Repo

ENGINE: KERNEL // STABLE
BASE_ARCH: x86_64
HOST: VASTORIGINS.COM
GPG: OKSIG_ID: 0x4EB27DB0

I believe that the first test of a truly great man is his humility. Really great men have a curious feeling that the greatness is not in them but through them. And they see something divine in every other man and are endlessly, incredibly merciful.

~ John Ruskin.

One day I was working on a driver port to macOS (Apple Macintosh OS), and the only open source code for it could be found inside the Linux kernel source tree. That should be simple, right? Just clone the kernel and dig in. Except there was one small problem.

Heck! The Linux kernel repository is around 2GB including all history, and I only needed a single specific directory inside the entire repository. Downloading two gigabytes just to look at one folder felt absurd. After searching the whole internet I found an answer1: sparse checkout, a built in Git feature that lets you clone only the parts of a repository you actually need.

🧰 Sparse Checkout, Step by Step

Here are the steps to clone a specific directory from a git repository:

1. Create a Local Repository

First and foremost you need to create a local blank repository on your workstation:

git init <repo-name>

2. Map the Remote Repository

Inside the created repository, map the remote URL of the remote repository you want to clone:

cd <repo-name>
git remote add origin <remote-repo-url>

3. Enable Sparse Checkout

Then, set up the git config and specify that you’ll be doing a sparse checkout:

git config core.sparsecheckout true

4. Select the Directories

Create and add all the directories you want to checkout in the sparse-checkout file that can be found in .git/info/sparse-checkout:

echo "<needed-directory>/*" >> .git/info/sparse-checkout

5. Pull What You Need

When all the above steps are done, finally pull the repository objects:

git pull --depth=1 origin master

That is the whole trick. The --depth=1 flag on the last step also limits the history to a single commit, which keeps the download even smaller. One note for modern repositories: many projects now use main instead of master as their default branch, so if your pull fails, try origin main first.

So guys if you have any questions, hit me up on my social media accounts. That’s all there is that is needed. Now it’s already cloned, and you can get straight to work on the directory you actually needed, without two gigabytes of files you will never open.

❌ Originally posted on August 5, 2019.


  1. https://stackoverflow.com/a/28039894 ↩︎
[ SIGNATURE VERIFIED // GPG 0x4EB27DB0 // PROVENANCE SECURE ]
➔ RETURN TO LOGS