UNPKG

@intuitionrobotics/ts-common

Version:
54 lines 2.41 kB
import { Module } from "../core/module.js"; import {} from "../utils/types.js"; import { BadImplementationException, ImplementationMissingException } from "../core/exceptions.js"; import { filterInstances, flatArray } from "../index.js"; class CliParamsModule_Class extends Module { paramsValue = {}; constructor() { super("CliParamsModule"); } init() { this.config.params.forEach((param) => this.paramsValue[param.keyName] = this.getParam(param)); this.printHowTo(this.config.params); return this.paramsValue; } getParam(param, args = process.argv.slice(2, process.argv.length)) { if (!this.config.params.find(_param => _param.keyName === param.keyName)) throw new BadImplementationException("Requested not existing param"); let value = this.extractParam(param, args); if (!value) value = param.defaultValue; if (!value) return value; return (param.process ? param.process(value) : value); } extractParam(param, argv) { if (param.isArray) return param.keys.reduce((values, key) => { values.push(...filterInstances(argv.map(arg => arg.match(new RegExp(`${key}=(.*)`))?.[1]))); return values; }, []); const find = param.keys.map(key => argv.map(arg => arg.match(new RegExp(`${key}=(.*)`))?.[1])); return flatArray(find).find(k => k); } printHowTo = (params) => { const missingParams = params.filter((param) => !this.paramsValue[param.keyName] && !param.optional); const foundParams = params.filter((param) => this.paramsValue[param.keyName]); this.printFoundArgs("Found Args", foundParams, this.paramsValue); if (missingParams.length === 0) return; this.printFoundArgs("Missing Args", missingParams, this.paramsValue); throw new ImplementationMissingException("Missing cli params"); }; printFoundArgs(title, params, foundArgs) { if (params.length) return; this.logInfoBold(` ${title}:`); params.forEach((param) => this.logInfo(` ${param.keys[0]}=${foundArgs[param.keyName] || `<${param.name}>`}`)); } getParams = () => { return this.paramsValue; }; } export const CliParamsModule = new CliParamsModule_Class(); //# sourceMappingURL=CliParamsModule.js.map