Sub topic 17
Adding static analysis and quality gates
This chapter assumes you have a working pull request validation workflow like the one from the earlier chapters: the Salesforce CLI installed on the runner, authentication through a secret, and a check-only deployment that runs Apex tests. It also assumes basic Git branch protection knowledge.
What a quality gate is
A check-only deployment tells you whether metadata compiles and tests pass. It does not tell you whether the code is good. An Apex class can pass every test and still contain a SOQL query inside a loop, a missing sharing declaration, or an unescaped value in a dynamic query.
Static analysis reads the source without running it and reports rule violations. A quality gate turns those reports into a pass or fail decision that blocks a merge. A gate has three parts:
- A tool that produces findings.
- A threshold that decides which findings fail the build.
- An enforcement point, which on GitHub is a required status check on the protected branch.
Without the third part, a failing check is only advice.
Choosing where gates sit
Cheap gates should run first, so a pull request that breaks a style rule does not wait for a slow Apex test run. Static analysis needs no org connection, so it can run in parallel with setup or ahead of validation.
Running Salesforce Code Analyzer
Salesforce Code Analyzer is the CLI plugin that bundles several engines, including PMD for Apex, ESLint for JavaScript and Lightning Web Components, and a security-focused engine. Current versions install as a plugin named code-analyzer and run with sf code-analyzer run. Older versions used sf scanner run. Check which one your team has installed, because the flags differ.
The tool needs Java for the PMD engine. Set it up explicitly so the pipeline does not depend on the runner image's defaults.
name: Quality gates
on:
pull_request:
branches: [main]
paths:
- 'force-app/**'
jobs:
static-analysis:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: 17
- name: Install Salesforce CLI and Code Analyzer
run: |
npm install --global @salesforce/cli
sf plugins install code-analyzer
- name: Run Code Analyzer
run: >
sf code-analyzer run
--workspace force-app
--rule-selector Recommended
--severity-threshold 2
--output-file code-analyzer-results.json
- name: Upload results
if: always()
uses: actions/upload-artifact@v4
with:
name: code-analyzer-results
path: code-analyzer-results.jsonThe --severity-threshold 2 flag makes the command exit with a non-zero code when it finds a violation of severity 2 (high) or worse. Severity runs from 1 (critical) to 5 (info), so a lower number is more serious. The if: always() on the upload step keeps the report available even when the analysis step fails, which is exactly when you need it.
Choosing a threshold
A threshold that is too strict gets disabled by frustrated developers. One that is too loose never fires. Start from your current state.
| Situation | Suggested approach |
|---|---|
| New project with no existing violations | Fail at severity 3 or worse from the start |
| Mature codebase with many existing findings | Fail at severity 1 only, then lower the threshold as you fix findings |
| A rule produces false positives for your patterns | Change its severity in the configuration file instead of ignoring the whole run |
You can tune individual rules in a code-analyzer.yml file at the project root. The tool reads it automatically.
rules:
pmd:
ApexDoc:
severity: 4Commit this file so that local runs and CI runs use the same rules. A gate that behaves differently on a laptop than in the pipeline wastes time.
Enforcing a coverage minimum
Salesforce requires at least 75% Apex code coverage across the org for production deployments. RunLocalTests reports coverage, but the CLI does not fail a run merely because coverage is low in a scratch org or sandbox. If you want a stricter team standard, such as 85%, check it yourself.
coverage:
runs-on: ubuntu-latest
needs: static-analysis
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- name: Install Salesforce CLI
run: npm install --global @salesforce/cli
- name: Authenticate
env:
SFDX_AUTH_URL: ${{ secrets.SFDX_AUTH_URL }}
run: |
echo "$SFDX_AUTH_URL" > authurl.txt
sf org login sfdx-url --sfdx-url-file authurl.txt --alias target --set-default
rm authurl.txt
- name: Run tests with coverage
run: >
sf apex run test
--test-level RunLocalTests
--code-coverage
--wait 30
--target-org target
--json > test-result.json
- name: Enforce minimum coverage
env:
MINIMUM: 85
run: |
COVERAGE=$(jq -r '.result.summary.orgWideCoverage' test-result.json | tr -d '%')
echo "Org-wide coverage: ${COVERAGE}%"
if [ "$COVERAGE" -lt "$MINIMUM" ]; then
echo "Coverage is below the required ${MINIMUM}%"
exit 1
fiPlace this job under the same jobs: key as static-analysis. The needs line makes the coverage job wait for analysis to succeed, so you do not spend org time on code that already failed a rule. If sf apex run test itself fails because a test fails, the step exits and the coverage step never runs, which is the correct behavior.
Org-wide coverage is a blunt measure. It can stay above the minimum while a new class has no tests at all. If that matters to your team, compare coverage for the changed classes only, using the per-class data in the same JSON file.
Making the gate binding
A workflow does not block a merge by itself. Open the repository settings, go to branch protection rules for main, and enable "Require status checks to pass before merging". Then select the jobs you want as required, such as static-analysis and coverage.
Two edge cases cause confusion:
- The check name is the job name, not the workflow name. If you rename a job, the old required check is never reported and every pull request waits forever.
- A workflow with a
pathsfilter does not run when the changed files are outside the filter. If that workflow is a required check, pull requests that touch only documentation stay pending and cannot merge. Either remove the path filter from required workflows or add a lightweight workflow that reports the same check name.
Common failures
- The analysis step reports that Java was not found. Add the
setup-javastep, or pin a Java version that the installed plugin supports. - The step passes but you expected failures. Check that
--workspacepoints to the directory that contains your source, and that the rule selector includes the engine you care about. - The results file is empty or missing. A failed run may exit before writing output. Read the step log first, then the artifact.
- The coverage step fails with a
jqparse error. The test step probably wrote an error message instead of JSON. Opentest-result.jsonand read the message.
Exercise
Your team's pull request workflow has a path filter on force-app/**, and you mark its static-analysis job as a required status check. A developer opens a pull request that changes only README.md. What happens, and how can you fix it?
Show answer
The workflow does not run, so the required check is never reported and the pull request stays pending and cannot merge. Fix it by removing the path filter from the workflow that provides the required check, or by adding a second small workflow that reports a job with the same name when the filtered paths are not touched.
Exercise
A pipeline runs sf code-analyzer run --workspace force-app --severity-threshold 3. A scan finds one violation of severity 2 and several of severity 4. Does the step fail?
Show answer
Yes. Severity 2 is more serious than the threshold of 3, so the command exits with a non-zero code. The severity 4 findings alone would not fail the step.