CI 想先判断两个分支能不能合并,又不想真的执行 git merge,可以用 git merge-tree --write-tree。它会自动找合并基线,干净合并时返回 0,有冲突时返回 1。
环境:Git 2.39+、Bash、Linux 或 macOS,需要 mktemp。下面只操作临时仓库:
set -eu
repo=$(mktemp -d)
trap 'rm -rf -- "$repo"' EXIT
git init -q -b main "$repo"
git -C "$repo" config user.name 'Merge Tree Demo'
git -C "$repo" config user.email '[email protected]'
printf 'mode=base\n' >"$repo/app.conf"
git -C "$repo" add app.conf
git -C "$repo" commit -qm base
git -C "$repo" switch -qc feature
printf 'mode=feature\n' >"$repo/app.conf"
git -C "$repo" commit -qam feature
git -C "$repo" switch -q main
printf 'mode=main\n' >"$repo/app.conf"
git -C "$repo" commit -qam main
before=$(git -C "$repo" status --porcelain)
if git -C "$repo" merge-tree --write-tree main feature; then
printf 'unexpected clean merge\n' >&2
exit 1
else
status=$?
fi
test "$status" -eq 1
test "$(git -C "$repo" status --porcelain)" = "$before"
printf 'conflict detected, worktree unchanged\n'
输出里会带冲突文件和阶段信息,脚本可以直接按退出状态拦截后续步骤。它不会改工作区、索引或分支引用,不过会向对象库写入合并过程中生成的对象;如果仓库必须逐字节不变,放到临时 clone 里跑更稳。