console-app/lib/Sources/ArgSource.ts

56 lines
1.5 KiB
TypeScript
Raw Normal View History

2020-05-09 19:51:43 +02:00
/* eslint-disable no-console */
/* eslint-disable no-process-exit */
import yargs, { Options } from 'yargs';
import { OptionProcess } from '../Types';
import { OptionSource } from './OptionSource';
export class ArgSource extends OptionSource {
public async parse (options: OptionProcess[]): Promise<void> {
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.string_type,
describe: opt.description
};
}
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 this.assign_arg (opt, argv[opt.name]);
return Promise.resolve ();
}));
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);
}
}
}
}