@grandlinex/easy-cli
Version:
Cli lib to perform common tasks
101 lines (100 loc) • 3.66 kB
JavaScript
import * as process from 'process';
import { CMap, CoreLogChannel, DefaultLogger, LogLevel, } from '@grandlinex/core';
import getVersion from './utils/Version.js';
import CliParser from './class/CliParser.js';
import HelpAction from './commands/base/HelpAction.js';
import VersionAction from './commands/base/VersionAction.js';
import InteractiveAction from './commands/base/InteractiveAction.js';
import ArgUtil from './utils/ArgUtil.js';
import InteractionArgs from './class/InteractionArgs.js';
export default class CommandHandler extends CoreLogChannel {
constructor(cnf) {
super(cnf?.cmdName || 'easy-script', cnf?.logger || new DefaultLogger());
this.cmdName = cnf?.cmdName || 'easy-script';
this.dev = cnf?.isDev || false;
this.pageSize = cnf?.pageSize || 6;
this.defaultInteractive = cnf?.defaultInteractive || false;
const l = new DefaultLogger();
l.setPrintTimestamp(false);
if (this.dev) {
l.setLogLevel(LogLevel.VERBOSE);
}
this.logger = l;
this.cmdMap = new CMap();
this.baseCmd = new CMap();
const props = { logger: this.logger, handler: this };
this.addBaseCmd(new HelpAction(props), new InteractiveAction(props), new VersionAction(props));
}
getCmdName() {
return this.cmdName;
}
addCmd(fc) {
for (const c of fc({ logger: this.logger, handler: this })) {
this.cmdMap.set(c.name, c);
}
}
addBaseCmd(...cmd) {
for (const c of cmd) {
this.baseCmd.set(c.name, c);
}
}
getCmds(full) {
if (full) {
return [...this.baseCmd.toValueArray(), ...this.cmdMap.toValueArray()];
}
return this.cmdMap.toValueArray();
}
async run(iArgs) {
this.debug(`Startup: v${getVersion()}`);
try {
const cmds = this.getCmds(true);
const args = iArgs || new CliParser(this.logger);
ArgUtil.printDebug(this, args);
const list = args.getCmdList();
if (list.length > 0) {
const cmd = cmds.find((c) => c.name === list[0]);
if (cmd) {
await cmd.start(args);
return;
}
}
else if (list.length === 0 && args.getLength() > 0) {
const [option] = args.getParameters().toKeyArray();
const dx = this.baseCmd.get(option);
if (dx) {
const result = await dx.start(args);
if (result) {
return;
}
throw this.lError(`Execution error`);
}
}
else if (list.length === 0 &&
args.getLength() === 0 &&
this.defaultInteractive &&
!iArgs) {
const dx = this.baseCmd.get('interactive');
if (dx) {
const arg = new InteractionArgs();
arg.param.set('interactive', null);
const result = await dx.start(arg);
if (result) {
return;
}
throw this.lError(`Execution error`);
}
}
throw this.lError(`Unknown command ${list[0]}`);
}
catch (e) {
this.error('Exit with error! Run "easy-script --help" for more information');
process.exit(1);
}
}
isDev() {
return this.dev;
}
getPageSize() {
return this.pageSize;
}
}