Package Exports
- @salesforce/command
- @salesforce/command/lib/test
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@salesforce/command) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Description
This package contains the base command class for Salesforce CLI, SfdxCommand. Extend this class for convenient access to common Salesforce CLI parameters, a logger, CLI output formatting, scratch orgs, and Dev Hubs. This class extends @oclif/command and is available within a plug-in generated by Salesforce Plug-In Generator.
Usage
Requirements
Commands that extend SfdxCommand can only be used with Salesforce CLI version 6.8.2 or later. To check your Salesforce CLI version:
$ sfdx --version
sfdx-cli/6.42.0-ae478b3cb8 (darwin-x64) node-v8.9.4Features
To learn more about the features of the Command Library see the Salesforce CLI Plug-In Developer Guide.
There are many features that can be enabled with SfdxCommand subclasses simply by setting static properties on the subclassed command. Other features are always available for your command, such as a logger and output renderer.
- Static Properties -
SfdxCommandhas a handful of static properties for easy toggling of Salesforce CLI features such as adding a scratch org to your command instance or requiring a command to run from within a Salesforce DX project. - Instance Properties - Many instance properties are added to your command for convenient access to orgs (including Dev Hubs), project files, parameters, and more.
- Salesforce CLI Parameters - All
SfdxCommandsubclasses have the--jsonand--loglevelparameters automatically added to their command. Other Salesforce CLI parameters are enabled either by setting static properties directly on the command or within the flagsConfig static property. - Varargs Parameters - Varargs-style parameters are enabled via the
varargsstatic property, which enables 0 to n key=value pairs to be accepted as command input. - Table Rendering - It's easy for your command to output results in a table format. Simple table formatting is defined with the tableColumnData static property. For complete control over rendering use the result static property.
- Error Handling - Errors thrown during the command lifecycle are handled for you. If an
SfdxErroris not thrown then the error handler wraps the error in anSfdxErrorfor consistent error display.
Static Properties
- supportsUsername - Set to
trueto add the--targetusername (-u)and--apiversionflags to this command, and to have the org added (if provided) as an instance property which you can access in your command asthis.org.
static supportsUsername = true;- requiresUsername - Set to
trueto add the--targetusername (-u)and--apiversionflags to this command and to require that a target username is set, either via the flag or by having a default set in your Salesforce CLI config.
static requiresUsername = true;- supportsDevhubUsername - Set to
trueto add the--targetdevhubusername (-v)and--apiversionflags to this command, and to have the dev hub org added (if provided) as an instance property which you can access in your command asthis.hubOrg.
static supportsDevhubUsername = true;- requiresDevhubUsername - Set to
trueto add the--targetdevhubusername (-v)and--apiversionflags to this command and to require that a target dev hub username is set, either via the flag or by having a default set in your Salesforce CLI config.
static requiresDevhubUsername = true;- requiresProject - Set to
trueif this command must be run within a Salesforce DX project, and to have the project object added as an instance property which you can access in your command asthis.project.
static requiresProject = true;- flagsConfig - Use this property to enable, disable, or override Salesforce CLI parameters, and to configure new parameters.
static flagsConfig = {
name: flags.string({ char: 'n', type: 'string', description: messages.getMessage('nameFlagDescription') }),
force: flags.boolean({ char: 'f', type: 'boolean', description: messages.getMessage('forceFlagDescription') }),
quiet: flags.quiet()
};- varargs - Set to
trueto enablekey=valueparameter input to the command. To require at least one vararg, or to define a varargs validator function, use theVarargsConfigobject definition. Be sure to throw an error from the validator function with a helpful error message and action when validation fails.
static varargs = true;static varargs = {
required: true,
validator: (name, value) => {
// Whitelist varargs parameter names
if (!myWhitelist.includes(name)) {
const errMsg = `Invalid parameter [${name}] found`;
const errName = 'InvalidVarargName';
const errAction = `Please choose from this list of parameter names: ${myWhitelist.join()}`;
throw new SfdxError(errMsg, errName, [errAction]);
}
}
}- tableColumnData - Use this string array to define table columns for simple command output table formatting.
static tableColumnData = ['id', 'name', 'description'];- result - Use for full control over command output formatting and display, or to override certain pieces of default display behavior. See oclif/cli-ux table for more granular details of table rendering.
static result = {
tableColumnData: [
{key: 'id', label: 'ID'},
{key: 'name', label: 'Name'},
{key: 'description', label: 'Description'}
],
display(): {
if (Array.isArray(this.data) && this.data.length) {
if (this.data.length > 100) {
// special display for large number of results
} else {
this.ux.table(this.data, this.tableColumnData);
}
}
}
};Instance Properties
- args - The parsed args from the command line.
- flags - The parsed flags (parameters) from the command line.
- org - The org associated with the username provided via the
--targetusername (-u)flag or a default defined in the Salesforce CLI config. - hubOrg - The Dev Hub org associated with the username provided via the
--targetdevhubusername (-v)flag or a default defined in the Salesforce CLI config. - project - The Salesforce DX project object.
- configAggregator - The ConfigAggregator object.
- logger - The Salesforce CLI logger.
- ux - The UX object for command output. The UX methods respect the
--jsonflag so that output is suppressed when set. - result - The result instance where data and formatting can be manipulated after the command's
runmethod has completed.
Salesforce CLI Parameters
Extending SfdxCommand makes many Salesforce CLI parameters and parameter types available. As mentioned above, some of these parameters are added when static properties are set on your command (such as supportsUsername), some are added by default (such as --json and --loglevel), and some can be added or removed from your command via the flagsConfig static property. You can also override the flags implementation completely by defining your own static flags property. See the oclif flags docs for details.
Global Salesforce CLI Parameters These parameters are either available by default or used by many Salesforce CLI commands. Global parameters do not have short names.
json- Suppresses output fromthis.ux.*methods and formats output as JSON. This flag is available by default on all Salesforce CLI commands. Its value treated as true if provided, false otherwise.loglevel- Sets the logging level for this command invocation. Logs are stored in$HOME/.sfdx/sfdx.log. This enum flag accepts only known (lowercase) logging options and is available on all Salesforce CLI commands. See the LoggerLevel docs for more info.apiversion- Overrides the defaultapiVersionfor API requests made by this command.targetusername- Sets a username or alias for the target org. Overrides the default target org.targetdevhubusername- Sets a username or alias for the target Dev Hub org. Overrides the default Dev Hub org.concise- A common flag name to use for writing brief command output to stdout. Your command is responsible for modifying output based on this flag. This flag's value is treated as true if provided, false otherwise.quiet- A common flag name to use for suppressing command output to stdout. Your command is responsible for modifying output based on this flag. This flag's value is treated as true if provided, false otherwise.verbose- A common flag name to use for additional command output to stdout. Your command is responsible for modifying output based on this flag. This flag's value is treated as true if provided, false otherwise.
Salesforce CLI Parameter Types You can use more specific parameter types when defining flags for your command. This will provide some validation for the format of the parameter values, and give users a better idea of the expected value for the parameter. These are a super-set of the available oclif flag types. Most flags require a
description.boolean- The parameter has no value. Including it sets the output flag value totrue, andfalseotherwise.enum- The parameter expects a string value from one of an enumeration ofoptions.help- Augments the built-inhelpflag with an optional, customcharvalue, such ash. Abooleanflag that causes the CLI to emit help information and exit.integer- The parameter expects an integer value. For example:42.option- The parameter expects astringvalue, to be processed by a customparsefunction.string- The parameter expects astringvalue.version- Abooleanflag that causes the CLI to emit version information and exit.array- The parameter expects an array of comma-separated values. For example:first,second,thirdor"first name, last name, suffix". May accept a custom delimiter string and/or a custom array element mapping function.date- The parameter expects a date. For example:01-02-2000.datetime- The parameter expects a datetime. For example:"01/02/2000 01:02:34".directory- The parameter expects a path to a directory. For example:/my/path/to.email- The parameter expects an email address. For example:me@example.com.filepath- The parameter expects a filepath. For example:/my/path/to/myfile.json.id- The parameter expects a Salesforce ID. For example:00Dxxxxxxxxxxxx.milliseconds- The parameter expects an integer to be interpreted as a number of milliseconds. For example:5000.minutes- The parameter expects an integer to be interpreted as a number of minutes. For example:2.number- The parameter expects a number. For example:42.seconds- The parameter expects an integer to be interpreted as a number of seconds. For example:15.url- The parameter expects a URL. For example:https://www.salesforce.com.
Example
static flagsConfig = {
// use a Salesforce CLI parameter type
names: flags.array({ char: 'n', required: true, description: 'names to update' }),
// use an oclif flag builder
force: flags.boolean({ char: 'f', description: 'force the name updates' }),
// enable the SFDX verbose built-in flag
verbose: flags.builtin(),
// create a custom flag with its own parser
metadata: flags.option({ char: 'd', description: 'support data as json', parser: JSON.parse })
};Error Handling
SfdxCommand handles runtime errors in the catch method for consistent error-handling format and behavior. By default, the exit code will be 1 unless otherwise specified within the SfdxError. Stack traces are suppressed unless the SFDX_ENV environment variable's value is set to development. Override the catch method if you'd prefer to handle errors within your command.
Related Docs and Repositories
- @salesforce/command - Contains the base Salesforce CLI command,
SfdxCommand. - @oclif/command - Base oclif
Command, whichSfdxCommandextends. - @salesforce/plugin-generator - The generator plug-in for building plug-ins for the Salesforce CLI.