2026年5月14日 星期四

[Git] Sparse Checkout

Sparse Checkout

 git     sparse-checkout  

A subcommand in git used to reduce the files present in the working tree to a subset of all tracked files. Also, the name of the file in the $GIT_DIR/info directory used to track the sparsity patterns corresponding to the user’s desired subset.


Steps

1.Init An Empty Repository

mkdir {project}
cd {project}
git init
git remote add -f origin ssh://git@xxxxx/project.git


Now git updates and fetches the origin without cloning anything.

2.Enable Sparse Checkout

git config --local core.sparseCheckout true 


3.Define Sparsity Patterns

Define the sparsity patterns (file paths) that we're only interested.

echo "some/dir/" >> .git/info/sparse-checkout
echo "another/sub/file" >> .git/info/sparse-checkout


Or by the git sparse-checkout set command, notice this overwrite ".git/info/sparse-checkout":

git sparse-checkout set "some/dir/" "another/sub/file


Or by the git sparse-checkout add command that append the path to ".git/info/sparse-checkout":

git sparse-checkout add "some/dir/"
git sparse-checkout add "another/sub/file"


The sparsity patterns supports excluding a path by putting ! before the path.

.git/info/sparse-checkout

/*
!src/


  • /*: includes everything at the root and all subdirectories.
  • !src/: excludes the src/ folder and everything inside it.

4.Completing Sparse Checkout

And after that, we can do pull, switch or checkout to certain branch, and only the pathes defined in ".git/info/sparse-checkout" will be presented in the working tree.

git pull
git switch my-branch
git checkout my-branch


Other Commands

git sparse-checkout list

Show the sparsity patterns defined.

git sparse-checkout reapply

We can change the sparsity patterns anytime by git sparse-checkout command and it will take effect right away. But if we edit the ".git/info/sparse-checkout", remember to re-apply the changes. e.g.

sed -i "/.*log/d" .git/info/sparse-checkout
git sparse-checkout reapply



Reference

沒有留言:

張貼留言