Clone arbitrary single Git commit
git clone
allows cloning single commits without history
for existing branches and tags through syntax…
git clone --depth 1 --branch <BRANCH_OR_TAG> <REMOTE_URL>
…but not for arbitrary commits. It's not impossible though, and if you want to clone arbitrary single commits — say in CI — it can be done using a trick.
The idea is simple:
instead of git clone
we combine
git init
,
git remote add
,
git fetch
and
git checkout
— but how?
Let me demo that for cloning
commit 9c6d51b71caeb1e773cabf4ad9ded9bd6e142229
from repository hartwork/git-delete-merged-branches
in practice in a Linux Bash terminal:
# 0. Jump to an empty temporary directory cd "$(mktemp -d)" # 1. Create an empty Git repository (rather than using "git clone"), without warnings git -c init.defaultbranch=main init # 2. Add the target repository as a new remote "origin" git remote add origin https://github.com/hartwork/git-delete-merged-branches # 3. Fetch a single commit (and all trees and blobs needed for it) git fetch --depth 1 origin 9c6d51b71caeb1e773cabf4ad9ded9bd6e142229 # 4. Check out the commit we just fetched, without warnings git -c advice.detachedHead=false checkout FETCH_HEAD # 5. Done.
I myself got the idea from GitHub Action actions/checkout
— thanks to them!
Did you just learn something of value? Are you struggling with any things Git? Let me know!
Sebastian Pipping
Berlin, 2024