Sub topic 2
Running Your First Salesforce Code Analyzer Scan
Assume you have the Salesforce CLI (sf), the Code Analyzer plugin, a Salesforce DX project, and basic Apex or JavaScript knowledge. Code Analyzer runs rules from several engines, such as PMD for Apex, ESLint for JavaScript, and Regex for pattern checks.
Run a scan
From the project root, scan the force-app directory with the Recommended rule set:
sf code-analyzer run --workspace force-app --rule-selector Recommended --view tableThe --workspace option identifies the code to scan. The --rule-selector option chooses the rules. A selector can name a set, engine, tag, or specific rule.
For example, this Apex method contains DML inside a loop:
public class AccountUpdater {
public static void renameAll(List<Account> accounts) {
for (Account acc : accounts) {
acc.Name = acc.Name + ' Inc.';
update acc;
}
}
}PMD can report this because repeated DML operations can exceed Salesforce governor limits.
Scope the scan
Use --target to narrow a workspace scan to one file or directory:
sf code-analyzer run \
--workspace force-app \
--target force-app/main/default/classes/AccountUpdater.cls \
--rule-selector pmd:SecurityThe workspace provides the scan context. The target limits which files are analyzed within that context.
Read results and severity
Each finding normally identifies the engine, rule, severity, file, line, and message. Severity numbers run from 1 for Critical to 5 for Info. Lower numbers are more serious.
| Severity | Meaning |
|---|---|
| 1 | Critical |
| 2 | High |
| 3 | Moderate |
| 4 | Low |
| 5 | Info |
Choose an output format
Use --view table for a compact terminal report. Use --view detail when you need fuller finding information. Use an output filename to save a report:
sf code-analyzer run \
--workspace force-app \
--rule-selector Recommended \
--output-file results.htmlThe filename extension selects a file format such as HTML or SARIF.
Fail serious scans
Set a severity threshold in scripts or CI:
sf code-analyzer run \
--workspace force-app \
--rule-selector Recommended \
--severity-threshold 2This command exits unsuccessfully when it finds severity 2 or a more serious finding. A threshold of 3 also fails for Moderate, High, and Critical findings.
Exercise
Which option narrows a scan to one file, and what does a threshold of 2 do?
Show answer
Use --target for the file. A severity threshold of 2 makes the command fail when it finds Critical or High violations.