config source

This commit is contained in:
2020-05-18 19:18:02 +02:00
parent 71d4858189
commit 3766958b20
4 changed files with 61 additions and 10 deletions

View File

@ -12,6 +12,7 @@ import { OptionType } from './OptionType';
import { OptionSource } from './Sources/OptionSource';
import { EnvSource } from './Sources/EnvSource';
import { ArgSource } from './Sources/ArgSource';
import { ConfigSource } from './Sources/ConfigSource';
import { InteractiveSource } from './Sources/InteractiveSource';
import { Option, OptionProcess } from './Option';
@ -26,9 +27,10 @@ const types: Record<OptionType, TypeValidation> = {
};
interface SourceConfig {
env: boolean;
args: boolean;
interactive: boolean;
env?: boolean;
args?: boolean;
interactive?: boolean;
configs?: string[];
}
export class InteractiveOptions extends Persistent {
@ -38,7 +40,7 @@ export class InteractiveOptions extends Persistent {
public constructor (
options: Array<Option>,
source_config: SourceConfig = { args: true, env: true, interactive: true }
source_config: SourceConfig = {}
) {
super ();
this.options = options
@ -60,11 +62,16 @@ export class InteractiveOptions extends Persistent {
this.properties[option.name] = option.type_validation.persistent_type;
}
if (source_config.env)
if (
typeof source_config.configs !== 'undefined'
&& Array.isArray (source_config.configs)
)
this.sources.push (new ConfigSource (source_config.configs));
if (source_config.env !== false)
this.sources.push (new EnvSource);
if (source_config.args)
if (source_config.args !== false)
this.sources.push (new ArgSource);
if (source_config.interactive)
if (source_config.interactive !== false)
this.sources.push (new InteractiveSource);
}

View File

@ -0,0 +1,43 @@
/*
* 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
*/
/* eslint-disable no-await-in-loop */
import fs from 'fs-extra';
import { OptionProcess } from '../Option';
import { OptionSource } from './OptionSource';
export class ConfigSource extends OptionSource {
private _config_files: string[];
public constructor (config_files: string[]) {
super ();
this._config_files = config_files;
}
public async parse (options: OptionProcess[]): Promise<void> {
const data: Record<string, unknown> = {};
for (const f of this._config_files) {
if (await fs.pathExists (f)) {
try {
const json = JSON.parse (await fs.readFile (f, 'utf-8'));
for (const key of Object.keys (json))
data[key] = json[key];
}
catch {
continue;
}
}
}
const keys = Object.keys (data);
await Promise.all (options.map (async (opt) => {
if (keys.includes (opt.name))
await this.assign_arg (opt, data[opt.name]);
}));
}
}