console-app/lib/Sources/ArgSource.ts

51 lines
1.3 KiB
TypeScript

/*
* Copyright (C) Sapphirecode - All Rights Reserved
* This file is part of console-app which is released under MIT.
* See file 'LICENSE' for full license details.
* Created by Timo Hocker <timo@scode.ovh>, May 2020
*/
/* eslint-disable no-console */
/* eslint-disable no-process-exit */
import yargs, { Options } from 'yargs';
import { Option, OptionValue } from '../Option';
import { OptionSource } from './OptionSource';
export class ArgSource extends OptionSource {
private create_config (
config: Option,
persistent_type: string
): Record<string, Options> {
return {
[config.name]: {
alias: config.alias,
// eslint-disable-next-line no-undefined
default: undefined,
type: persistent_type
}
} as Record<string, Options>;
}
public async parse (opt: Option, val: OptionValue): Promise<void> {
const yargs_config = this.create_config (
opt,
val.type_validation.persistent_type
);
const argv = yargs.options (yargs_config)
.parse ();
if (typeof argv[opt.name] === 'undefined')
return;
if (
val.type_validation.option_type === 'array'
&& (argv[opt.name] as Array<unknown>)
.filter ((v) => typeof v !== 'undefined').length <= 0
)
return;
await val.assign_arg (opt, argv[opt.name]);
}
}