@grandlinex/easy-cli
Version:
Cli lib to perform common tasks
66 lines (65 loc) • 2.55 kB
JavaScript
import Path from 'path';
import fs from 'fs';
import { CoreLogChannel } from '@grandlinex/core';
import { StricktOption, } from '../lib/types.js';
import ArgUtil from '../utils/ArgUtil.js';
export class ShellCommand extends CoreLogChannel {
constructor(conf) {
super(conf.name, conf.logger);
this.name = conf.name;
this.description = conf.description;
this.handler = conf.handler;
this.properties = conf.properties;
this.subCommands = conf.subCommands || [];
this.level = conf.level || 0;
}
async validateFields(args) {
for (const { key, type, required, options } of this.properties) {
const p = args.getParameters().get(key);
if (!ArgUtil.isParameterType(args, key, type) && p !== undefined) {
throw this.lError(`Parameter --${key} is not valid. Got ${p} as ${ArgUtil.checkParameterType(args, key)} but expected ${type}`);
}
if (required && ArgUtil.checkParameterType(args, key) === null) {
throw this.lError(`Parameter --${key} is not set but required`);
}
if (options &&
p !== undefined &&
!(await StricktOption(options, this.handler)).find((o) => o.key === p)) {
throw this.lError(`Parameter --${key} has invalid option ${p}`);
}
}
for (const k of args.getParameters().toKeyArray()) {
if (!this.properties.find(({ key }) => key === k)) {
throw this.lError(`Unknown Parameter --${k}`);
}
}
return true;
}
async start(parser) {
const next = this.level + 1;
if (parser.getCmdList().length > next) {
const sub = this.subCommands.find((c) => c.name === parser.getCmdList()[next]);
if (sub) {
return sub.start(parser);
}
throw this.lError(`Unknown Sub-Command ${parser.getCmdList().join(' ')}`);
}
await this.validateFields(parser);
const ext = await this.run(parser);
this.handler.onEnd();
return ext;
}
resolvePath(path) {
if (!path || typeof path !== 'string') {
throw this.lError(`Invalid path ${path}`);
}
const absPath = Path.resolve(path);
if (!fs.existsSync(absPath)) {
throw this.lError(`File ${absPath} does not exist`);
}
return absPath;
}
getStatic(key) {
return this.handler.getStatic(key);
}
}