easy-cli-framework
Version:
A framework for building CLI applications that are robust and easy to maintain. Supports theming, configuration files, interactive prompts, and more.
71 lines (67 loc) • 2.53 kB
JavaScript
var command = require('./command.js');
/**
* A command to add an init command to the CLI that will save the configuration
*
* @template TParams The params for the command
* @template TGlobalParams The global params for the CLI
*
* @extends EasyCLICommand
*
* @example
* ```typescript
* new EasyCLIInitCommand(config, 'init', {
* globalKeysToUse: ['verbose'],
* prompts: {
* env: {
* describe: 'What environent are you setting?',
* type: 'string',
* prompt: 'always',
* demandOption: true,
* },
* },
* });
* ```
*/
class EasyCLIInitCommand extends command.EasyCLICommand {
/**
* Creates a new init command
* @param {EasyCLIConfigFile} config The configuration file to use to save the config
* @param {string} [name='init'] The name of the command
* @param {InitCommandOptions<TGlobalParams, TParams>} [options={}] The options for the command
*/
constructor(config, name = 'init', options = {}) {
if (!config) {
throw new Error('EasyCLIConfigFile is required for init command');
}
const { globalKeysToUse = [], defaults = {}, configFlag = 'config', callback, ...commandOptions } = options;
const handler = async (params, theme) => {
const logger = theme === null || theme === undefined ? undefined : theme.getLogger();
const keys = [...this.getKeys(), ...globalKeysToUse];
const clean = Object.entries(params).reduce((acc, [key, value]) => {
if (keys.includes(key)) {
acc[key] = value;
}
return acc;
}, defaults);
logger === null || logger === undefined ? undefined : logger.success('Saving config file');
await config.save(clean);
if (callback) {
await callback(params);
}
};
const validator = async (params) => {
var _a;
if (options.failOnExists &&
config.fileExists((_a = params === null || params === undefined ? undefined : params[configFlag]) !== null && _a !== undefined ? _a : null)) {
throw new Error('Config file already exists');
}
if (commandOptions.validator) {
return commandOptions.validator(params);
}
return true;
};
super(name, handler, { ...commandOptions, validator });
}
}
exports.EasyCLIInitCommand = EasyCLIInitCommand;
;