console-app/lib/Options/BaseOption.ts

62 lines
1.8 KiB
TypeScript
Raw Normal View History

2020-10-03 15:14:14 +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>, October 2020
*/
2020-06-09 13:13:27 +02:00
import { OptionSource } from '../Sources/OptionSource';
2020-06-09 13:58:29 +02:00
import { Option, OptionValue } from '../Option';
2020-06-09 13:13:27 +02:00
import { EnvSource } from '../Sources/EnvSource';
import { ArgSource } from '../Sources/ArgSource';
import { ConfigSource } from '../Sources/ConfigSource';
import { TypeValidation } from '../TypeValidation/TypeValidation';
2020-06-09 21:03:10 +02:00
import { InteractiveSource } from '../Sources/InteractiveSource';
2020-06-09 13:13:27 +02:00
export abstract class BaseOption<T> {
protected readonly sources: OptionSource[] = [];
private _config: Option;
public constructor (
config: Option
2020-06-09 13:13:27 +02:00
) {
this._config = config;
const sources = config.sources || {};
const exit_on_interrupt = config.exit_on_interrupt !== false;
if (typeof sources.configs !== 'undefined') {
this.sources.push (new ConfigSource (
sources.configs,
config.error_callback
));
}
2020-06-09 13:13:27 +02:00
2020-06-12 14:34:45 +02:00
this.sources.push (new EnvSource (config.error_callback));
2020-06-09 13:13:27 +02:00
if (sources.console !== false)
this.sources.push (new ArgSource (config.error_callback));
2020-06-09 13:13:27 +02:00
if (sources.interactive !== false) {
this.sources.push (new InteractiveSource (
exit_on_interrupt,
config.error_callback
2020-06-09 13:13:27 +02:00
));
}
}
protected abstract get validation(): TypeValidation;
2020-06-09 13:58:29 +02:00
public async parse (): Promise<T> {
const val = new OptionValue (this.validation);
for (const source of this.sources)
// eslint-disable-next-line no-await-in-loop
await source.parse (this._config, val);
2020-06-09 21:03:10 +02:00
if (!val.filled)
return this._config.default as T;
return val.value as T;
2020-06-09 13:58:29 +02:00
}
2020-06-09 13:13:27 +02:00
}