56 lines
1.6 KiB
TypeScript
56 lines
1.6 KiB
TypeScript
import { OptionSource } from '../Sources/OptionSource';
|
|
import { Option, OptionValue } from '../Option';
|
|
import { EnvSource } from '../Sources/EnvSource';
|
|
import { ArgSource } from '../Sources/ArgSource';
|
|
import { ConfigSource } from '../Sources/ConfigSource';
|
|
import { TypeValidation } from '../TypeValidation/TypeValidation';
|
|
import { InteractiveSource } from '../Sources/InteractiveSource';
|
|
|
|
export abstract class BaseOption<T> {
|
|
protected readonly sources: OptionSource[] = [];
|
|
private _config: Option;
|
|
|
|
public constructor (
|
|
config: Option
|
|
) {
|
|
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
|
|
));
|
|
}
|
|
|
|
if (sources.env !== false)
|
|
this.sources.push (new EnvSource (config.error_callback));
|
|
|
|
if (sources.console !== false)
|
|
this.sources.push (new ArgSource (config.error_callback));
|
|
|
|
if (sources.interactive !== false) {
|
|
this.sources.push (new InteractiveSource (
|
|
exit_on_interrupt,
|
|
config.error_callback
|
|
));
|
|
}
|
|
}
|
|
|
|
protected abstract get validation(): TypeValidation;
|
|
|
|
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);
|
|
|
|
if (!val.filled)
|
|
return this._config.default as T;
|
|
return val.value as T;
|
|
}
|
|
}
|