console-app/lib/Option.ts

54 lines
1.2 KiB
TypeScript

/*
* 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
*/
import { TypeValidation } from './TypeValidation/TypeValidation';
import { ErrorCallback } from './ErrorCallback';
interface SourceConfig {
console?: boolean,
configs?: string[],
interactive?: boolean,
}
interface Option {
name: string;
default?: unknown;
sources?: SourceConfig;
alias?: string;
env?: string;
message?: string;
error?: string;
error_callback?: ErrorCallback;
exit_on_interrupt?: boolean;
}
class OptionValue {
public filled = false;
public value?: unknown;
public readonly type_validation: TypeValidation;
public constructor (type_validation: TypeValidation) {
this.type_validation = type_validation;
}
public async assign_arg (
opt: Option,
value: unknown
): Promise<void> {
try {
this.value = await this.type_validation.to_type (value);
this.filled = true;
}
catch (e) {
if (typeof opt.error_callback !== 'undefined')
opt.error_callback (opt.name, value, e);
}
}
}
export { Option, OptionValue };