The "cli" app manages CLI commands that you can access by running
node .. Each app has the option of adding commands or
command groups to the CLI, which can be invoked by the app name
(ie, "node . config", "node . db", or "node . my_custom_app").
A command group would be a single command mounted at that app name,
whereas a command group would be when that command has multiple
subparsers.
The "cli" service uses the argparse module to manage an argparse instance with subparsers.
Each app that defines CLI commands should document them, but the general formula for executing a CLI command for an app is this:
node . <app_name>
Most of the time, a group of commands is exposed, in which case each command is runnable like this:
node . <app_name> <command_name>
You can define a CLI command or command group by writing the file
cli.js in an app directory (apps/my_custom_app/cli.js, for example).
It should create an instance of argparse.ArgumentParser and export it by the
name parser. You set a default func, a function which takes the passed
arguments as an object. A simple example:
// apps/my_custom_app/cli.js
const argparse = require('argparse');
const parser = new argparse.ArgumentParser({ add_help: true });
parser.add_argument("name", { help: "Your name." });
parser.set_defaults({func: (args) => {
console.log(`Hello, ${args.name}`);
}});
module.exports = { parser };
If you app is installed, you can then execute the command like this:
$ node . my_custom_app John
Hello, John
If you wanted to define a group of command instead, use subparsers:
// apps/my_custom_app/cli.js
const argparse = require('argparse');
const parser = new argparse.ArgumentParser({ add_help: true });
let subs = parser.add_subparsers();
let helloCommand = subs.add_parser('say_hello');
helloCommand.add_argument("name", { help: "Your name." });
helloCommand.set_defaults({func: (args) => {
console.log(`Hello, ${args.name}`);
}});
// add other subcommands
module.exports = { parser };
Then you would run the "say_hello" command like this:
$ node . my_custom_app say_hello John
Hello, John
When the CLI is used, only some of the basic apps are loaded. If you know that
code you would call from your command's handler function requires the db
app, for example, you should call App.initialLoad:
// apps/my_custom_app/cli.js
const argparse = require('argparse');
const App = require('@carolina/core');
const parser = new argparse.ArgumentParser({ add_help: true });
let subs = parser.add_subparsers();
let helloCommand = subs.add_parser('say_hello');
helloCommand.add_argument("name", { help: "Your name." });
helloCommand.set_defaults({func: async (args) => {
await App.initialLoad('db');
const DbSvc = App.$db;
// do something
}});
// add other subcommands
module.exports = { parser };