Introduction
Git merge conflicts can halt your CI/CD pipeline, causing delays and frustrated developers. This guide shows how to detect, prevent, and automatically resolve conflicts in automated pipelines.
Why Conflicts Appear in CI/CD
- Feature branches diverge from
mainfor a long time. - Automated rebases or merges run on every push.
- Mis‑configured merge strategies.
Step‑by‑Step Conflict Detection
- Fetch the target branch
git fetch origin $CI_MERGE_REQUEST_TARGET_BRANCH_NAME
- Attempt a dry‑run merge
git merge --no-commit --no-ff origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME || true
- Check for unresolved files
if git ls-files -u | grep .; then
echo "Merge conflicts detected"
exit 1
fi
If the job exits with a non‑zero status, the pipeline fails early, alerting the author.
Integrating the Check into GitLab CI
merge_conflict_check:
stage: test
image: alpine/git
script:
- git config --global user.email "ci@example.com"
- git config --global user.name "CI Bot"
- git fetch origin $CI_MERGE_REQUEST_TARGET_BRANCH_NAME
- git checkout $CI_COMMIT_SHA
- git merge --no-commit --no-ff origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME || true
- if git ls-files -u | grep .; then echo "Conflicts detected"; exit 1; fi
only:
- merge_requests
Automatic Conflict Resolution (Optional)
For simple, predictable conflicts you can use a custom merge driver:
# .gitattributes
*.json merge=json_merge
# .git/config
[merge "json_merge"]
name = JSON merge driver
driver = python3 scripts/json_merge.py %A %O %B %L
The json_merge.py script merges JSON objects intelligently. Add it to your repository and reference it in the CI job:
resolve_json_conflicts:
stage: merge
script:
- python3 scripts/json_merge.py
Real‑World Tips
- Keep branches short-lived – reduces the chance of divergence.
-
Enable
rebasein merge requests – GitLab can auto‑rebase before merging. - Use protected variables to store credentials for the merge bot.
Resources
Conclusion
By embedding conflict detection and optional auto‑resolution into your CI/CD pipeline, you keep the merge process fast and reliable. Your team can focus on delivering features instead of fighting merge wars.
Top comments (0)