Sub topic 11
Sparse checkout in CI and automation
CI jobs are the best place to use sparse checkout. A developer clones a monorepo once and works in it for months. A CI job starts from an empty disk, often hundreds of times a day, and needs only a few directories. Every file it skips saves network and disk time on every run.
This chapter assumes you can do the following:
- Use
git sparse-checkout set,add, anddisable. - Explain cone mode.
- Explain what
--filter=blob:nonedoes in a partial clone. - Read a short shell script and a YAML workflow file.
What changes in automation
Interactive and automated use differ in four ways:
- No history is needed. A build needs one commit, so a shallow clone (
--depth 1) is usually enough. - The checkout is disposable. Nobody edits the files. A bad sparse set fails the job and is fixed in the next run.
- The sparse set should be derived, not typed. It comes from the job (the "api" job needs
services/api) or from the diff (only the services that changed). - Failures must be loud. A missing directory should stop the job at the start, not produce a confusing error at the end.
The usual recipe combines three techniques you have already seen:
- A shallow clone limits the commits downloaded.
- A partial clone with
blob:nonelimits the file contents downloaded. - Sparse checkout limits the files written to disk.
The diagram shows where each one acts.
The order matters. Git downloads trees (directory listings) first. Only when the checkout runs does it learn which file contents are needed, and it requests just those blobs from the server in one batch.
The minimal CI clone
The minimal form is a single clone followed by one command:
git clone --depth 1 --filter=blob:none --sparse https://example.com/org/monorepo.git
cd monorepo
git sparse-checkout set services/api libs/common--sparse makes the initial checkout contain only the top-level files. The set command then fetches and writes the two directories. Recent Git versions (2.37 and later) use cone mode by default for set. Pass --cone explicitly if your runners have mixed Git versions.
Using the built-in support in GitHub Actions
Most CI systems provide this as configuration, so you rarely script the clone yourself. In GitHub Actions, the actions/checkout action (version 4 and later) has sparse-checkout and filter inputs.
name: api-ci
on:
pull_request:
paths:
- "services/api/**"
- "libs/common/**"
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 1
filter: blob:none
sparse-checkout: |
services/api
libs/common
- name: Show what was checked out
run: git sparse-checkout listThe paths filter decides whether the job runs at all. The sparse-checkout input decides what the job downloads once it does. They solve different problems, and a monorepo pipeline usually needs both. Keep the two lists in sync, or a change in a directory that is sparse-checked-out but not in paths will never trigger the job.
Other CI systems follow the same pattern. GitLab CI controls depth with the GIT_DEPTH variable, and Jenkins has a sparse checkout extension in its Git plugin. When a system has no built-in option, add the three commands above in a script step with the built-in checkout turned off.
Building the sparse set from the diff
A pull request pipeline often wants to test only the services that changed. That requires knowing the changed paths before the checkout, so the order of operations differs. The script below clones without writing files, fetches the base and head commits, computes the directories, and then checks out.
#!/usr/bin/env bash
set -euo pipefail
repo_url=$1
base_sha=$2
head_sha=$3
git init --quiet workdir
cd workdir
git remote add origin "$repo_url"
# Fetch both commits as shallow, blob-less history.
git fetch --quiet --depth 1 --filter=blob:none origin "$base_sha" "$head_sha"
# Directory names only: no file contents are needed to compare two trees.
mapfile -t changed < <(
git diff --name-only "$base_sha" "$head_sha" \
| awk -F/ '$1 == "services" && NF > 2 { print $1 "/" $2 }' \
| sort -u
)
# Shared code is always needed.
dirs=("${changed[@]}" libs/common)
git sparse-checkout set --cone "${dirs[@]}"
git checkout --quiet --detach "$head_sha"
echo "Checked out:"
git sparse-checkout listFour details make this work:
- Both commits are fetched at depth 1. Git can compare two trees without the commits between them, so no ancestry is needed. A diff against
origin/mainwould fail in a depth-1 clone because the merge base is missing. git diff --name-onlyneeds only trees. It does not download blobs, so the blob-less filter costs nothing here.- The
awkfilter keeps the first two path components. A change toservices/api/src/main.pybecomesservices/api, which is what cone mode expects, a directory and not a file. libs/commonis added unconditionally. Dependencies are the part a diff cannot tell you about. See the pitfalls below.
Choosing a strategy
The right approach depends on how much the job knows in advance.
| Strategy | Sparse set comes from | Good for | Main risk |
|---|---|---|---|
| Static list in the job definition | A fixed list written in the CI config | One job per service | The list drifts from real dependencies |
| Diff-derived | `git diff --name-only` | Pull request validation | Missing a dependency that did not change |
| Manifest-derived | A dependency file or build graph query | Large repos with a build tool such as Bazel or Nx | The manifest must be accurate and cheap to read |
| Full checkout | Nothing | Release builds, repo-wide linters | Slowest, but safest |
A common compromise is sparse checkout for pull request checks and a full checkout for the release pipeline. A missed dependency then fails a fast check and is caught, instead of shipping a broken artifact.
Caching and repeatable runs
Persistent CI runners can reuse a clone, which changes how you configure the job.
- Reusing a workspace. Run
git sparse-checkout seton every job, not only the first. The set is stored in the repository's.gitdirectory, so a previous job's directories would otherwise remain. - Cleaning up. Use
git clean -ffdxbefore reuse, or start from a fresh clone. Build output inside the sparse directories is untracked, and stale output causes false passes. - Caching the object store. A cached
.gitdirectory from a blob-less clone holds only the blobs earlier jobs fetched. A later job asking for other directories fetches those on demand, which is correct but slower than the cache implies. - Keeping runs reproducible. Log the SHA and the output of
git sparse-checkout listat the start of every job, as the script above does. When a build fails because a file is missing, the log shows the set that was used.
Limitations and pitfalls in automation
A build needs files outside the set. This is the most common failure. A service imports from a library that nobody listed, or a root-level script reads a config in another directory. The symptom is a missing file or import error, not a Git error. Git works as designed and the directory is simply absent. Fix the set, not the build.
Lazy fetches hide network use. In a partial clone, a command that reads old file contents contacts the server. git log -p, git blame, and git grep against a commit other than the checked-out one all do this. They can be slow or fail on a runner with no network access after checkout. Run such commands in a separate job with a fuller clone.
Shallow clones break history-based tools. Version-from-tag scripts, changelog generators, and git describe need tags and commits that depth 1 does not provide. Fetch tags or deepen history only in the jobs that need them:
git fetch --depth 50 origin main
git fetch --tags --depth 1 originSubmodules and Git LFS are separate. Sparse checkout does not limit submodule content. LFS files in the sparse set are downloaded, and LFS files outside it are not. Configure both explicitly.
Tools that scan the whole repository see a partial one. A linter that walks every directory from the root will only see what is on disk, so it may report success for code it never saw. Run repo-wide checks in a job with a full checkout, and name them as such.
Pattern mode is rarely worth it in CI. Cone mode is faster and its behavior is the same across Git versions. If a job truly needs an exclusion such as "everything except docs/", use git sparse-checkout set --no-cone '/*' '!/docs/'. Keep that job small and test it on the Git version your runners have.
Exercise
A pull request job uses a depth-1 blob-less clone and runs git diff --name-only origin/main...HEAD to find changed services. The command fails. Why, and what is the smallest change that fixes it?
Show answer
The three-dot form needs the merge base between origin/main and HEAD. A depth-1 clone has neither the base branch history nor the commits between, so Git cannot find it. The smallest fix is to fetch the pull request's base commit at depth 1 (git fetch --depth 1 --filter=blob:none origin "$base_sha") and run git diff --name-only "$base_sha" HEAD. Comparing two trees needs no ancestry.
Exercise
Your sparse-checkout CI job for services/billing passes the build, but a teammate's local build of the same service fails with an import error from libs/money. What is the likely cause, and where should you fix it?
Show answer
The CI job's sparse set probably includes libs/money (for example through a stale cached workspace or a broader static list), while the teammate's local set does not. Or the reverse: the local set was never updated after the service started depending on the library. Fix the source of truth for the dependency list, such as the manifest or the job's sparse-checkout input, so that CI and local setup use the same directories. Also run git sparse-checkout set on every job and clean reused workspaces so leftover state cannot hide the problem.