Hooks
A hook is a piece of code that runs at a specific lifecycle event of a CLI command. Think of a hook as a pause in the CLI command execution. The command executes as usual until it encounters a hook. It pauses while the hook code executes, and then picks up again after the hook code execution completes. Salesforce CLI supports all the Open CLI Framework (oclif) hooks.
For example, let's say you've configured the oclif hook init
in your plugin. When you run any command in the plugin, the init
hook fires after the CLI is initialized but before the command is found. If you've also configured a prerun
hook, then that one fires directly after the init
hook but before the command itself runs. If you've configured a postrun
hook, it fires directly after the command runs.
Create a hook by adding TypeScript or JavaScript code and configuration information to your custom Salesforce CLI plugin. You can create a plugin that contains only hooks. Or you can add the hook code and configuration to a plugin that contains all your business logic. It's up to you!
After a user installs the plugin that contains the hooks into their CLI, the hook fires at the appropriate lifecycle event. The hook continues to fire until the user explicitly uninstalls the custom plugin. If you want the hooks to fire in a continuous integration (CI) job, install the custom plugin before you run any Salesforce CLI commands.
The best way to show how to create a hook in your custom plugin is to show how Salesforce CLI itself uses hooks. Let's use the top-level Salesforce CLI npm package @salesforce/cli as an example.
-
Code the hook in TypeScript or JavaScript. For example, this code is for a
prerun
hook that Salesforce CLI uses to check the version of the plugin that contains the command that the user is executing. The hook alerts the user if their installed plugin version is different from the version bundled with the CLI. -
Update your plugin's
package.json
file and add ahooks
object inside theoclif
object. Thehooks
object specifies the type of oclif hook, such asprerun
, and the location of your compiled source. For example:See the @salesforce/cli package.json for another example.
-
After you release your plugin, users install it in their CLI as usual.
From this point on, or until the user uninstalls the plugin, the configured hooks fire when the user runs any Salesforce CLI command.