How To Clone Sub-Folder From GitHub Repo Using Git Sparse Checkout

How To Clone Sub-Folder From GitHub Repo Using Git Sparse Checkout

·

2 min read

Introduction

Git is commonly known as a version changes tracker in a project and it helps to improve collaboration between the development team.

From version 2.25.0, Git introduced a new feature called git-sparse-checkout to reduce your working tree to a subset of tracked files. For more details, please check it out here.

The use case here is sometimes, you find an interesting Github repository that includes a lot of different folders. But you only need one of them to work with, to get only one needed folder, you can use the git-sparse-checkout feature to keep your cloned project looking clean and focused.

Git Sparse Checkout

In this guidance, I have a repository that includes some folders as below.

Let's say the only folder I need is the ExpressoTS folder in the project.

Firstly, to use git-sparse-checkout feature, you need to upgrade your git to 2.25.0 version or higher.

On your local computer, run the following steps:

1. Clone the repository using this command.

  • We use --no-checkout to make sure that we don't create any checkout action when cloning is done. It only takes the tracking info of the repository without any folders or files.

  • After this command is executed, we can not see any folders or files in the play-with-node repository.

git clone --no-checkout git@github.com:ad0x99/play-with-node.git

2. Change your directory to the folder you’ve cloned

cd play-with-node

3. Use the following command to specify the folders you want to pull to

  • set option: enables the necessary sparse-checkout config settings and changes to a sparse checkout with all files (at any depth) under the ExpressoTS folder present in the working copy (plus all files immediately under ExpressoTS/ and the top-level directory). Note that this command will also delete all ignored files in any directory that no longer has either tracked or non-ignored-untracked files present.

      git sparse-checkout set ExpressoTS
    
  • To check the list of sparse checkouts, use this command.

    • As you can see, we’ve added the ExpressoTS folder to the sparse checkout list successfully.

  • After setting the ExpressoTS folder to the sparse-checkout list, we still can not see the ExpressoTS folder in the directory. To show it, we need to checkout all the files in the ExpressoTS folder by using the following command.

      git checkout
    
  • Now you can see all the files in the ExpressoTS folder.

  • If you run git status, you can see the following information about sparse checkout of the repository.

That’s it. Hope you find it helpful from my little guidance. Thanks!

References

Git - git-sparse-checkout Documentation