Handling Git Shallow Clone Issues with Custom Merge Hooks
Last updated: July 14, 2025
When using custom Git merge hooks in your Spacelift workflow, you may encounter "refusing to merge unrelated histories" errors when working with shallow clones. This article explains how to handle these situations.
Original script
#!/usr/bin/env bash
export EMAIL=spacelift@spacelift.io
export GIT_AUTHOR_NAME=spacelift
export GIT_COMMITTER_NAME=spacelift
git remote set-url origin https://$GH_TOKEN@github.com/cowpaths/mn.git
# Do this after clone so we don't expose the GH_TOKEN to stdout
set -x
git fetch origin $TF_VAR_spacelift_commit_branch:$TF_VAR_spacelift_commit_branch --filter=tree:0 -n
pushd ${TF_VAR_spacelift_workspace_root}/source
pwd
git sparse-checkout init --no-cone
# dirs to keep in the sparse checkout
git sparse-checkout set projects/fullstory/static projects/fullstory/etc/terraform
git checkout -f $TF_VAR_spacelift_commit_branch
popd
git fetch origin master:master --filter=tree:0 > /dev/null
git merge -q --no-ff -m spacelift-merge masterUnderstanding the Issue
By default, Spacelift performs shallow clones of Git repositories to optimize performance. For pull requests, it clones with a depth of 2 to fetch the virtual merge commit and its parents. This can cause issues when custom hooks need to perform operations that require deeper repository history, such as merging branches.
Solution
If your custom hook needs to merge branches, you'll need to deepen the repository clone. Here's how to modify your hook script to handle shallow clones:
if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then
# Deepen the repository for the branches we need to merge
BRANCHES_TO_DEEPEN="$TF_VAR_spacelift_commit_branch master"
for branch in $BRANCHES_TO_DEEPEN; do
git fetch origin --deepen=100 "refs/heads/$branch:refs/remotes/origin/$branch" --no-tags
done
fiChoosing the Right Depth
When setting the depth for fetching:
A larger depth (e.g., 100) ensures you can merge branches that have diverged significantly
A smaller depth means faster cloning but may fail for long-lived branches
Consider your repository's commit frequency and typical PR lifetime when choosing a depth value
Note: If you still encounter issues, you can use git fetch --unshallow to fetch the complete repository history. However, this may significantly increase clone times for large repositories.