console-app/lib/Sources/ArgSource.ts

76 lines
2.2 KiB
TypeScript
Raw Normal View History

2020-05-15 16:53:45 +02:00
/*
* 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
*/
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) {
2020-06-05 13:22:54 +02:00
const type = opt.type_validation.persistent_type;
2020-05-09 19:51:43 +02:00
yargs_config[opt.name] = {
alias: opt.alias,
2020-06-05 13:22:54 +02:00
// eslint-disable-next-line no-undefined
default: type === 'boolean' ? undefined : opt.default,
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-18 09:55:09 +02:00
if (typeof argv[opt.name] === 'undefined')
2020-05-09 21:30:37 +02:00
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);
}
}
}
}