From dbe7af78abc2e2834af634b7476fddaa5847bd07 Mon Sep 17 00:00:00 2001 From: gnuxie Date: Tue, 22 Nov 2022 14:51:45 +0000 Subject: [PATCH] Allow config to be specified with an explicit cli argument. --- src/config.ts | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/src/config.ts b/src/config.ts index bfe0277..e62359a 100644 --- a/src/config.ts +++ b/src/config.ts @@ -15,7 +15,6 @@ limitations under the License. */ import * as fs from "fs"; -import * as path from "path"; import { load } from "js-yaml"; import { MatrixClient } from "matrix-bot-sdk"; import Config from "config"; @@ -171,7 +170,32 @@ const defaultConfig: IConfig = { }, }; -export function read(): IConfig { - const config = Config.util.extendDeep({}, defaultConfig, Config.util.toObject()) as IConfig; - return config; +/** + * Grabs an explicit path provided for mjolnir's config from an arguments vector if provided, otherwise returns undefined. + * @param argv An arguments vector sourced from `process.argv`. + * @returns The path if one was provided or undefined. + */ +function configPathFromArguments(argv: string[]): undefined|string { + const configOptionIndex = argv.findIndex(arg => arg === "--mjolnir-config"); + if (configOptionIndex > 0) { + const configOptionPath = argv.at(configOptionIndex + 1); + if (!configOptionPath) { + throw new Error("No path provided with option --mjolnir-config"); + } + return configOptionPath; + } else { + return; + } +} + +export function read(): IConfig { + const explicitConfigPath = configPathFromArguments(process.argv); + if (explicitConfigPath) { + const content = fs.readFileSync(explicitConfigPath, "utf8"); + const parsed = load(content); + return Config.util.extendDeep({}, defaultConfig, parsed); + } else { + const config = Config.util.extendDeep({}, defaultConfig, Config.util.toObject()) as IConfig; + return config; + } }