console-app/lib/Sources/ArgSource.ts

67 lines
1.8 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';
2020-05-09 21:30:37 +02:00
import { OptionProcess } from '../Option';
2020-05-09 19:51:43 +02:00
import { OptionSource } from './OptionSource';
export class ArgSource extends OptionSource {
2020-05-09 21:30:37 +02:00
private create_config (options: OptionProcess[]): Record<string, Options> {
2020-05-09 19:51:43 +02:00
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,
2020-05-09 21:30:37 +02:00
type: opt.type_validation.persistent_type,
2020-05-09 19:51:43 +02:00
describe: opt.description
};
}
2020-05-09 21:30:37 +02:00
return yargs_config;
}
public async parse (options: OptionProcess[]): Promise<void> {
const yargs_config = this.create_config (options);
2020-05-09 19:51:43 +02:00
const argv = yargs.options (yargs_config)
.parse ();
if (argv.help) {
yargs.options (yargs_config)
.showHelp ();
process.exit (0);
}
await Promise.all (options.map ((opt) => {
2020-05-09 21:30:37 +02:00
if (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]);
2020-05-09 19:51:43 +02:00
}));
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);
}
}
}
}