config source
This commit is contained in:
		
							
								
								
									
										43
									
								
								lib/Sources/ConfigSource.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										43
									
								
								lib/Sources/ConfigSource.ts
									
									
									
									
									
										Normal 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]); | ||||
|     })); | ||||
|   } | ||||
| } | ||||
		Reference in New Issue
	
	Block a user