Sub topic 15
Validating Merges Automatically in CI
This chapter assumes you can resolve a conflict by hand, run sf project deploy start --dry-run, and read a basic YAML pipeline file. It shows how to run the same checks on every pull request, so a bad merge is caught by a machine and not by a teammate.
Why validate in CI
A local check depends on the person who resolved the conflict. They may skip the dry run, forget a leftover marker, or validate against the wrong org. A CI job runs the same steps every time and blocks the merge when a step fails.
Metadata merges need this more than most code. A file with a stray <<<<<<< line is not valid XML, and the failure shows up only at deploy time. Git also merges text, not meaning. It can combine two clean edits into a file that parses but breaks a reference, such as a permission set that grants access to a field that no longer exists.
CI should answer three questions, in order from cheapest to most expensive:
- Do any conflict markers remain?
- Is every changed XML file well-formed?
- Will the target org accept the deployment?
The pipeline at a glance
Ordering matters for cost. The marker scan and XML check take seconds and need no org login. The dry run needs authentication and can take minutes, so it should run only when the cheap checks pass.
Step 1: Scan for conflict markers
The simplest check is the same grep you ran locally. Anchoring to the start of the line avoids false positives from a line of equals signs inside a comment or a label value.
#!/usr/bin/env bash
set -euo pipefail
if grep -rnE '^(<<<<<<<|=======|>>>>>>>)' force-app; then
echo "Conflict markers found. Resolve them before merging." >&2
exit 1
fi
echo "No conflict markers found."grep exits with status 0 when it finds a match, so the if branch means failure. Exit status 1 from grep (no match) falls through to the success message. With set -e, a plain grep with no match would stop the script, which is why the call sits inside the if condition.
Save this as scripts/check-markers.sh and make it executable with chmod +x.
Step 2: Check that the XML is well-formed
Markers are one way to break XML. Another is a hand edit that leaves a block unclosed or duplicates a root element. xmllint catches both. To avoid scanning the whole project on every run, check only the files the pull request changed.
#!/usr/bin/env bash
set -euo pipefail
BASE_REF="${1:-origin/main}"
files=$(git diff --name-only --diff-filter=ACMR "$BASE_REF"...HEAD -- 'force-app/**/*-meta.xml')
if [ -z "$files" ]; then
echo "No metadata XML changed."
exit 0
fi
status=0
while IFS= read -r f; do
if ! xmllint --noout "$f"; then
echo "Malformed XML: $f" >&2
status=1
fi
done <<< "$files"
exit "$status"The three-dot form BASE_REF...HEAD compares against the merge base, so the list contains only what this branch changed. --diff-filter=ACMR selects added, copied, modified and renamed files and skips deleted ones, which xmllint could not open.
Note that this loop reports every bad file before it exits, instead of stopping at the first. That saves the author a round trip per file.
Step 3: Run a deployment dry run
The dry run asks the target org to validate the deployment without saving it. It catches missing references, invalid element names, and permission settings that point at components that do not exist.
sf project deploy start \
--dry-run \
--source-dir force-app \
--target-org ci-sandbox \
--test-level NoTestRun \
--wait 30Choose the test level deliberately:
| Test level | What it does | When to use it |
|---|---|---|
| `NoTestRun` | Runs no Apex tests | Pull request checks into a sandbox, where speed matters |
| `RunLocalTests` | Runs all tests except those from managed packages | Validation before a production deployment |
| `RunSpecifiedTests` | Runs only the tests you name | Large projects where you can map changes to tests |
Salesforce requires tests to run for production deployments, so a dry run against production with NoTestRun will not give you a result that predicts a real release. For pull requests, a sandbox with NoTestRun is the usual compromise. Run the full test level on a scheduled or release job.
Limit the dry run to what changed
Deploying all of force-app on every pull request gets slow as a project grows. You can validate only the changed components by comparing the branch to its base. The Salesforce CLI supports this through the --metadata and --source-dir flags, and many teams add a delta tool such as sfdx-git-delta to generate a manifest of changed components.
Be aware of the trade-off. A delta check is faster, but it can miss a problem caused by an unchanged file that now conflicts with the change. For example, you rename a field in one file, and an unchanged flow still references the old name. Running a full dry run on the main branch, nightly or after each merge, closes that gap.
Authenticating CI to the org
CI needs to log in without a person present. The Salesforce CLI supports login with an auth URL stored as a secret.
- On a trusted machine, log in to the sandbox once, then run
sf org display --target-org ci-sandbox --verbose --jsonand copy thesfdxAuthUrlvalue. - Store that value as a masked secret in your CI system. Never commit it to the repository.
- In the job, write it to a temporary file and log in with it.
echo "$SFDX_AUTH_URL" > /tmp/auth-url.txt
sf org login sfdx-url --sfdx-url-file /tmp/auth-url.txt --alias ci-sandbox
rm -f /tmp/auth-url.txtFor stronger setups, use the JWT bearer flow with a connected app and a certificate. It avoids storing a refresh token. The checks in this chapter work the same with either method.
Putting it together in a workflow
This example uses GitHub Actions. The structure carries over to other CI systems: install tools, run cheap checks, authenticate, then validate.
name: Validate metadata
on:
pull_request:
branches: [main]
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install tools
run: |
sudo apt-get update
sudo apt-get install -y libxml2-utils
npm install --global @salesforce/cli
- name: Scan for conflict markers
run: bash scripts/check-markers.sh
- name: Check XML is well-formed
run: bash scripts/check-xml.sh origin/main
- name: Authenticate to sandbox
env:
SFDX_AUTH_URL: ${{ secrets.SFDX_AUTH_URL }}
run: |
echo "$SFDX_AUTH_URL" > /tmp/auth-url.txt
sf org login sfdx-url --sfdx-url-file /tmp/auth-url.txt --alias ci-sandbox
rm -f /tmp/auth-url.txt
- name: Dry-run deployment
run: |
sf project deploy start --dry-run \
--source-dir force-app \
--target-org ci-sandbox \
--test-level NoTestRun \
--wait 30Two details are easy to miss:
fetch-depth: 0downloads full history. Without it, the checkout is shallow andgit diff origin/main...HEADcannot find a merge base.- Each step runs only if the previous one succeeded, so the dry run never starts when the cheap checks fail.
To make the check binding, mark the validate job as a required status check in the branch protection rules for main. Without that setting, the job reports a failure but does not stop the merge.
Pull request pipelines see a merge result
Many CI systems test the pull request branch merged with the target branch, not the branch alone. GitHub Actions does this for pull_request events by default. This is helpful, because it validates the combination that will land. It also means a pull request can pass today and fail tomorrow with no new commits, because main moved and the merged result now conflicts. If the checkout cannot merge cleanly, the job fails before your scripts run. The fix is to merge or rebase main into the branch, resolve the conflict locally, and push.
Common failures and how to read them
| Symptom | Likely cause | Fix |
|---|---|---|
| Marker scan fails on a file you did not touch | Markers were committed in an earlier merge | Resolve the file and commit the fix |
| `xmllint` reports `Opening and ending tag mismatch` | A block was deleted without its closing tag | Restore the missing tag |
| `xmllint: command not found` | The CI image lacks `libxml2-utils` | Add the install step |
| Dry run fails with `no CustomField named ... found` | A permission or layout references a field removed on the other branch | Remove the reference or restore the field |
| `git diff` fails with `no merge base` | Shallow checkout | Set `fetch-depth: 0` |
| Dry run passes but a real deploy fails | Different org configuration or a delta check that missed a file | Run a full dry run on `main` |
Edge cases to plan for
- Sandbox drift. If the CI sandbox differs from production, a dry run can pass or fail for reasons unrelated to the merge. Refresh the sandbox on a schedule and keep it close to production.
- Concurrent runs. Two pull requests validating at once against one sandbox are fine for dry runs, because nothing is saved. Do not mix dry runs with real deployments to the same org from CI.
- Generated files. If your project commits files that tools regenerate, such as some layouts, add them to the same checks. A re-retrieve that produces a diff in CI is a sign that someone merged a stale copy.
- Source tracking is separate. CI deploys with an explicit source directory and does not depend on source-tracking state. A tracking conflict in a scratch org is a different problem and does not appear in this pipeline.
Exercise
Your pull request pipeline runs the deployment dry run first, then the marker scan, and developers complain that failed checks take about ten minutes to report. What change would speed up feedback, and why does it work?
Show answer
Run the marker scan and the XML well-formed check before authentication and the dry run. Both cheap checks finish in seconds and need no org login. The dry run takes minutes, so it should run only after the fast checks pass. A leftover conflict marker then fails the job almost immediately.
Exercise
A pull request passed CI on Monday. On Wednesday, with no new commits, the check fails before any of your scripts run. What is the most likely cause, and what should the author do?
Show answer
The pipeline tests the pull request merged with the target branch. The target branch moved, and the merge result now conflicts, so the checkout fails. The author should merge or rebase the target branch into their branch, resolve the conflict locally, validate, and push.
Exercise
Your job runs grep -rnE '^(<<<<<<<|=======|>>>>>>>)' force-app as a bare command with set -e and no if. What goes wrong when the project is clean, and how do you fix the script?
Show answer
When no marker matches, grep exits with status 1, and set -e ends the script with a failure even though the project is clean. The fix is to put the call inside an if condition, as in if grep ...; then exit 1; fi, so a match means failure and no match continues.