Sub topic 3
Sparse Checkout for Large Git Repositories
Assume you know clone, fetch, branches, and Git’s commits, trees, and blobs. A sparse checkout is a working-tree setting that checks out only selected paths. The repository can still contain metadata for other paths.
Check out only selected paths
Start with a sparse clone, then select the directories you need:
git clone --filter=blob:none --sparse https://example.com/org/monorepo.git
cd monorepo
git sparse-checkout set services/api docs
git sparse-checkout list--sparse initially checks out only top-level files. sparse-checkout set switches to the selected paths. In cone mode, paths normally represent directories, which keeps the configuration simple.
Combine partial clone and sparse checkout
In a monorepo, combine sparse checkout with a blob filter when you need one service but not every file version. Git downloads file contents for selected paths as required. Commands such as git show, checkout, or a build can therefore cause network requests.
The repository is still usable offline for objects already present. A command that needs an omitted object fails offline or waits for the remote, depending on the operation.
Server requirements
The Git server must support protocol version 2 and partial-clone filters. Modern Git hosting usually supports blob:none, but support varies for tree:0 and custom filters. If the server rejects --filter, retry without the filter or use a shallow sparse clone.
Choose a strategy
| Need | Suitable strategy |
|---|---|
| Daily work across many directories | Full clone, or sparse checkout without filtering |
| One component in a huge monorepo | Partial clone plus sparse checkout |
| Fast CI build of the current revision | `--depth 1 --single-branch --no-tags` |
| Inspect one recent commit | Shallow clone |
| Review history or run ancestry queries | Full clone, or deepen first |
CI and troubleshooting
A typical current-snapshot checkout is:
git clone --depth 1 --single-branch --no-tags --branch main \
--filter=blob:none --sparse https://example.com/org/monorepo.git
cd monorepo
git sparse-checkout set services/apiInspect the repository when behavior is surprising:
git rev-parse --is-shallow-repository
git config --get remote.origin.promisor
git config --get remote.origin.partialclonefilter
git sparse-checkout listA shallow repository can lack merge bases and older commits. Deepen it with git fetch --deepen 50, or restore complete history with git fetch --unshallow. Unexpected downloads usually indicate that a command accessed an omitted blob.
Exercise
Which strategy fits a CI job that builds only services/api from the latest main commit?
Show answer
Use a depth-one, single-branch, no-tags clone with a blob filter and sparse checkout for services/api.