console-app/lib/Sources/ArgSource.ts
2020-05-18 09:55:09 +02:00

74 lines
2.1 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 { OptionProcess } from '../Option';
import { OptionSource } from './OptionSource';
export class ArgSource extends OptionSource {
private create_config (options: OptionProcess[]): Record<string, Options> {
const yargs_config: Record<string, Options> = {
quiet: {
alias: 'q',
default: false,
type: 'boolean',
describe: 'do not ask for options interactively'
},
help: {
alias: 'h',
default: false,
type: 'boolean',
describe: ''
}
};
for (const opt of options) {
yargs_config[opt.name] = {
alias: opt.alias,
default: opt.default,
type: opt.type_validation.persistent_type,
describe: opt.description
};
}
return yargs_config;
}
public async parse (options: OptionProcess[]): Promise<void> {
const yargs_config = this.create_config (options);
const argv = yargs.options (yargs_config)
.parse ();
if (argv.help) {
yargs.options (yargs_config)
.showHelp ();
process.exit (0);
}
await Promise.all (options.map ((opt) => {
if (typeof argv[opt.name] === 'undefined')
return Promise.resolve ();
if (
opt.type === 'array'
&& (argv[opt.name] as Array<unknown>)
.filter ((v) => typeof v !== 'undefined').length <= 0
)
return Promise.resolve ();
return this.assign_arg (opt, argv[opt.name]);
}));
if (argv.quiet) {
const missing = options.filter ((o) => !o.filled && o.required)
.map ((o) => o.name);
if (missing.length > 0) {
console.error ('missing arguments:');
console.error (missing.join (', '));
process.exit (0);
}
}
}
}