How to Mock git sparse-checkout Paths in Python

Simulates git sparse-checkout configuration by writing desired paths to the sparse-checkout file without running git commands.

Easy Python 3.9+ Aug 9, 2026 Git + Python 10 views 0 copies

Python code

36 lines
Python 3.9+
import subprocess
from pathlib import Path
import tempfile


def configure_sparse_checkout(repo_dir: Path, paths: list[str]) -> list[str]:
    """Simulate sparse checkout configuration by returning the paths that would be set."""
    sparse_checkout_file = repo_dir / ".git" / "info" / "sparse-checkout"
    sparse_checkout_file.parent.mkdir(parents=True, exist_ok=True)
    sparse_checkout_file.write_text("\n".join(paths) + "\n")
    return paths


def mock_git_sparse_checkout(repo_dir: Path, paths: list[str]) -> dict:
    """Mock git sparse-checkout set command without invoking git."""
    configured = configure_sparse_checkout(repo_dir, paths)
    return {
        "status": "success",
        "repository": str(repo_dir),
        "paths": configured,
        "count": len(configured),
    }


if __name__ == "__main__":
    with tempfile.TemporaryDirectory() as tmpdir:
        repo = Path(tmpdir) / "sample-repo"
        repo.mkdir()
        (repo / ".git" / "info").mkdir(parents=True)
        result = mock_git_sparse_checkout(
            repo,
            ["src/", "docs/README.md", "tests/"]
        )
        print(result)
        print("Configured file contents:")
        print((repo / ".git" / "info" / "sparse-checkout").read_text())

Output

stdout
{'status': 'success', 'repository': '/tmp/tmp1234/sample-repo', 'paths': ['src/', 'docs/README.md', 'tests/'], 'count': 3}
Configured file contents:
src/
docs/README.md
tests/

How it works

This function creates the .git/info/sparse-checkout file in a mock repository and writes the given paths, one per line. It returns the list of paths and a summary dictionary, mimicking the behavior of git sparse-checkout set. No actual git subprocess is invoked, so it's safe for tests and dry runs. The use of Path.mkdir(parents=True) ensures nested directories exist before writing.

Common mistakes

  • Forgetting to create parent directories before writing the sparse-checkout file
  • Assuming paths are automatically quoted or escaped for git
  • Overwriting an existing sparse-checkout file when you meant to append
  • Returning the file content instead of the configured paths

Variations

  1. Use `json.dump` to return the result as JSON for logging purposes.
  2. Modify the function to accept a `git` command string and run it with `subprocess.run` when not in mock mode.

Real-world use cases

  • Unit testing scripts that manage sparse checkout configurations without affecting a real repository.
  • Generating a sparse-checkout file for CI pipelines before cloning large monorepos.
  • Simulating git behavior in documentation or learning environments where git isn't installed.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Git + Python

Related tutorials and quizzes for this topic.