Skip to content

code-analyzer-apexguru

GitHub stars sarif GitHub release (latest SemVer) GitHub last commit GitHub commit activity GitHub contributors

ApexGuru is the AI-driven engine of Salesforce Code Analyzer. Unlike the other engines, it does not analyze your sources locally: it sends your Apex classes and triggers to a connected Salesforce org, where an LLM combined with Java Virtual Machine runtime traces detects SOQL inefficiencies, critical anti-patterns and scalability hotspots that static analysis alone can not see.

Key Features:

  • Runtime-Aware Analysis: Correlates your Apex sources with JVM traces collected in the org to surface issues that only appear at execution time
  • Performance & Scalability: Detects SOQL inefficiencies, expensive schema describe calls and governor-limit hotspots
  • Actionable Recommendations: Reports exact line-level highlights, severity ratings and suggested code changes (--include-suggestions)
  • Unified Toolchain: Runs via the same Salesforce Code Analyzer v5 plugin and code-analyzer.yml configuration as the Apex, Aura, Flow and LWC engines
  • Multiple Output Formats: Supports CSV, JSON, HTML, XML and SARIF output

Requirements

ApexGuru only analyzes .cls and .trigger files, and it requires a connected org where ApexGuru is enabled. It is available at no extra charge for Unlimited Edition production orgs, full copy sandboxes, Signature orgs and Scale Test customers, and requires Scale Center to be enabled. See Activate and Use ApexGuru.

Activation

Because it needs an authenticated org, this linter is inactive by default: it activates only when the SFDX_AUTH_URL variable is defined. Store the Salesforce DX auth url of the target org in a CI secret named SFDX_AUTH_URL, and MegaLinter logs in to that org before running ApexGuru.

The scan is then explicitly sent to that org with --target-org, so the .sfdx/sfdx-config.json present at the root of most Salesforce repositories, which usually points to a long gone scratch org, can not hijack it.

Configuration

Engine settings (target_org, api_timeout_ms, api_initial_retry_ms, api_max_retry_ms, api_backoff_multiplier) go under engines.apexguru in your code-analyzer.yml.

If your root folder is not force-app, please set variable SALESFORCE_CODE_ANALYZER_APEXGURU_DIRECTORY

See more details in Help

code-analyzer-apexguru documentation

code-analyzer - GitHub

Configuration in MegaLinter

Variable Description Default value
SFDX_AUTH_URL For code-analyzer-apexguru to be active, SFDX_AUTH_URL must be defined and not empty (not set)
SALESFORCE_CODE_ANALYZER_APEXGURU_ARGUMENTS User custom arguments to add in linter CLI call
Ex: -s --foo "bar"
SALESFORCE_CODE_ANALYZER_APEXGURU_COMMAND_REMOVE_ARGUMENTS User custom arguments to remove from command line before calling the linter
Ex: -s --foo "bar"
SALESFORCE_CODE_ANALYZER_APEXGURU_FILTER_REGEX_INCLUDE Custom regex including filter
Ex: (src\|lib)
⚠️ Not available with SALESFORCE_CODE_ANALYZER_APEXGURU_CLI_LINT_MODE = project
Exclude no file
SALESFORCE_CODE_ANALYZER_APEXGURU_FILTER_REGEX_EXCLUDE Custom regex excluding filter
Ex: (test\|examples)
⚠️ Not available with SALESFORCE_CODE_ANALYZER_APEXGURU_CLI_LINT_MODE = project
Exclude no file
SALESFORCE_CODE_ANALYZER_APEXGURU_CLI_LINT_MODE Override default CLI lint mode
- project: Call the linter from the root of the project
project
SALESFORCE_CODE_ANALYZER_APEXGURU_FORWARD_EXCLUDED_DIRECTORIES In project CLI lint mode, forward excluded directories (EXCLUDED_DIRECTORIES + ADDITIONAL_EXCLUDED_DIRECTORIES) to the linter through its native exclusion arguments or generated ignore/config files true
SALESFORCE_CODE_ANALYZER_APEXGURU_PRE_COMMANDS List of bash commands to run before the linter None
SALESFORCE_CODE_ANALYZER_APEXGURU_POST_COMMANDS List of bash commands to run after the linter None
SALESFORCE_CODE_ANALYZER_APEXGURU_UNSECURED_ENV_VARIABLES List of env variables explicitly not filtered before calling SALESFORCE_CODE_ANALYZER_APEXGURU and its pre/post commands None
SALESFORCE_CODE_ANALYZER_APEXGURU_CONFIG_FILE code-analyzer-apexguru configuration file name
Use LINTER_DEFAULT to let the linter find it
code-analyzer.yml
SALESFORCE_CODE_ANALYZER_APEXGURU_RULES_PATH Path where to find linter configuration file Workspace folder, then MegaLinter default rules
SALESFORCE_CODE_ANALYZER_APEXGURU_DISABLE_ERRORS Run linter but consider errors as warnings false
SALESFORCE_CODE_ANALYZER_APEXGURU_DISABLE_ERRORS_IF_LESS_THAN Maximum number of errors allowed 0
SALESFORCE_CODE_ANALYZER_APEXGURU_TIMEOUT_SECONDS Maximum duration in seconds of the linter run, after which the linter process and its child processes are killed and reported as an error (exit code 124). Overrides LINTER_TIMEOUT_SECONDS. 0 disables the timeout 300
SALESFORCE_CODE_ANALYZER_APEXGURU_CLI_EXECUTABLE Override CLI executable ['sf']
SALESFORCE_DIRECTORY Directory containing SALESFORCE files (use any to always activate the linter) force-app

IDE Integration

Use code-analyzer-apexguru in your favorite IDE to catch errors before MegaLinter !

IDE Extension Name Install
Visual Studio Code Salesforce Code Analyzer Install in VSCode
Visual Studio Code Salesforce Extension Pack Install in VSCode

MegaLinter Flavors

This linter is available in the following flavors

Flavor Description Embedded linters Info
all Default MegaLinter Flavor 133 Docker Image Size (tag) Docker Pulls
salesforce Optimized for Salesforce based projects 58 Docker Image Size (tag) Docker Pulls

Behind the scenes

How are identified applicable files

  • Activated only if sub-directory force-app is found. (directory name can be overridden with SALESFORCE_DIRECTORY)
  • If this linter is active, all files will always be linted

How the linting is performed

code-analyzer-apexguru is called once on the whole project directory (project CLI lint mode)

  • filtering can not be done using MegaLinter configuration variables,it must be done using code-analyzer-apexguru configuration or ignore file (if existing)
  • VALIDATE_ALL_CODEBASE: false doesn't make code-analyzer-apexguru analyze only updated files

Example calls

sf code-analyzer run --rule-selector apexguru --workspace . --include-suggestions --output-file results.csv

Help content

Analyze your code with a selection of rules to ensure good coding practices.

USAGE
  $ sf code-analyzer run [--flags-dir <value>] [-w <value>...] [-t <value>...]
    [-o <value>] [-r <value>...] [-s <value>] [-v detail|table] [-f <value>...]
    [-c <value>] [--include-fixes] [--include-suggestions] [--no-suppressions]

FLAGS
  -c, --config-file=<value>         Path to the configuration file used to
                                    customize the engines and rules.
  -f, --output-file=<value>...      Name of the file where the analysis results
                                    are written. The file format depends on the
                                    extension you specify, such as .csv, .html,
                                    .xml, and so on.
  -o, --target-org=<value>          Target org username or alias for remote
                                    analysis engines.
  -r, --rule-selector=<value>...    [default: Recommended] Selection of rules,
                                    based on engine name, severity level, rule
                                    name, tag, or a combination of criteria
                                    separated by colons.
  -s, --severity-threshold=<value>  Severity level of a found violation that
                                    must be met or exceeded to cause this
                                    command to fail with a non-zero exit code.
  -t, --target=<value>...           Subset of files within your workspace to be
                                    targeted for analysis.
  -v, --view=<option>               Format to display the command results in the
                                    terminal.
                                    <options: detail|table>
  -w, --workspace=<value>...        [default: .] Set of files that make up your
                                    workspace.
      --include-fixes               Include fix data for violations when
                                    available.
      --include-suggestions         Include suggestion data for violations when
                                    available.
      --no-suppressions             Disable processing of inline and bulk
                                    suppression markers.

GLOBAL FLAGS
  --flags-dir=<value>  Import flag values from a directory.

Installation on mega-linter Docker image

  • Dockerfile commands :
    # Parent descriptor install
    # renovate: datasource=npm depName=@salesforce/cli
    ARG NPM_SALESFORCE_CLI_VERSION=2.150.6
    # renovate: datasource=npm depName=@salesforce/plugin-packaging
    ARG NPM_SALESFORCE_PLUGIN_PACKAGING_VERSION=3.0.6
    # renovate: datasource=npm depName=sfdx-hardis
    ARG SFDX_HARDIS_VERSION=8.3.0
    ENV JAVA_HOME=/usr/lib/jvm/java-21-openjdk
    ENV PATH="$JAVA_HOME/bin:${PATH}"
    ENV XDG_DATA_HOME=/usr/local/share
    RUN sf plugins install @salesforce/plugin-packaging@${NPM_SALESFORCE_PLUGIN_PACKAGING_VERSION} \
        && echo y|sf plugins install sfdx-hardis@${SFDX_HARDIS_VERSION} \
        && (npm cache clean --force || true) \
        && rm -rf /root/.npm/_cacache
    ENV SF_AUTOUPDATE_DISABLE=true SF_CLI_DISABLE_AUTOUPDATE=true
    # Linter install
    # renovate: datasource=npm depName=@salesforce/plugin-code-analyzer
    ARG SALESFORCE_CODE_ANALYZER_VERSION=5.16.0
    RUN sf plugins install code-analyzer@${SALESFORCE_CODE_ANALYZER_VERSION} \
        && (npm cache clean --force || true) \
        && rm -rf /root/.npm/_cacache
    

Known errors and resolutions

When this linter fails for a known non-lint reason (remote service unavailable, malformed config, missing credentials, etc.), MegaLinter detects the pattern below in the linter output and surfaces the matching guidance.

SALESFORCE_CODE_ANALYZER_APEXGURU_ERROR_CONFIG_INVALID

Detection pattern (regex):

(Failed to parse the configuration content|The specified configuration file .* does not exist|The specified configuration file .* has an unsupported file extension|The configuration content is invalid)

Resolution guidance:

code-analyzer could not load the configuration file (code-analyzer.yml).
Verify the file is valid v5 YAML and that its path is reachable from the workspace.
Generate a starter config with: sf code-analyzer config -f code-analyzer.yml

SALESFORCE_CODE_ANALYZER_APEXGURU_ERROR_NO_ORG

Detection pattern (regex):

(No authorization information found for|No default (environment|org) found|NoDefaultEnvError|Unable to (find|resolve) the target org|The org .* is not authenticated)

Resolution guidance:

ApexGuru needs an authenticated Salesforce org and could not resolve one.
Verify that the SFDX_AUTH_URL variable holds a valid Salesforce DX auth url, obtained with: sf org display --target-org <alias> --verbose --json
The auth url must not be expired: revoked or rotated refresh tokens make the login fail before the scan starts.

SALESFORCE_CODE_ANALYZER_APEXGURU_ERROR_ENGINE_SKIPPED

Detection pattern (regex):

ApexGuru skipped: 

Resolution guidance:

The ApexGuru engine did not analyze anything: it skipped itself and reported no violation.
The reason is printed right after `ApexGuru skipped:` in the linter output above.
MegaLinter turns this into an error on purpose, so that a run analyzing nothing is not reported as a success.

SALESFORCE_CODE_ANALYZER_APEXGURU_ERROR_NOT_ENABLED

Detection pattern (regex):

(ApexGuru is (not|un)available|ApexGuru .* not enabled|not entitled to use ApexGuru|Scale Center .* not enabled)

Resolution guidance:

ApexGuru is not enabled on the connected org.
It requires Scale Center and is available for Unlimited Edition production orgs, full copy sandboxes, Signature orgs and Scale Test customers.
Enable it by following https://help.salesforce.com/s/articleView?id=xcloud.apexguru_workflow.htm&type=5 , or disable this linter with DISABLE_LINTERS: [SALESFORCE_CODE_ANALYZER_APEXGURU]

SALESFORCE_CODE_ANALYZER_APEXGURU_ERROR_TIMEOUT

Detection pattern (regex):

(ApexGuru .* timed out|timed out after .* milliseconds|api_timeout_ms)

Resolution guidance:

The ApexGuru analysis did not complete before the engine timeout (5 minutes by default).
Raise the `api_timeout_ms` setting of the apexguru engine in your code-analyzer.yml, or reduce the analyzed scope with FILTER_REGEX_EXCLUDE.

Comments