diff --git a/.gitignore b/.gitignore index c1a17c9..a0d992f 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,6 @@ package-lock.json # Code Editor directory .vscode + +# Ignore compiled dist/tests +dist/test diff --git a/dist/get-env-vars.js b/dist/get-env-vars.js deleted file mode 100644 index 99f8a99..0000000 --- a/dist/get-env-vars.js +++ /dev/null @@ -1,66 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const parse_rc_file_1 = require("./parse-rc-file"); -const parse_env_file_1 = require("./parse-env-file"); -const RC_FILE_DEFAULT_LOCATIONS = ['./.env-cmdrc', './.env-cmdrc.js', './.env-cmdrc.json']; -const ENV_FILE_DEFAULT_LOCATIONS = ['./.env', './.env.js', './.env.json']; -function getEnvVars(options) { - return __awaiter(this, void 0, void 0, function* () { - options = options || {}; - options.envFile = options.envFile || {}; - // Check for rc file usage - if (options.rc) { - return getRCFile({ environments: options.rc.environments, filePath: options.rc.filePath }); - } - return getEnvFile({ filePath: options.envFile.filePath, fallback: options.envFile.fallback }); - }); -} -exports.getEnvVars = getEnvVars; -function getEnvFile({ filePath, fallback }) { - return __awaiter(this, void 0, void 0, function* () { - // Use env file - if (filePath) { - try { - return yield parse_env_file_1.getEnvFileVars(filePath); - } - catch (e) { } - if (!fallback) { - throw new Error(`Unable to locate env file at location (${filePath})`); - } - } - // Use the default env file locations - for (const path of ENV_FILE_DEFAULT_LOCATIONS) { - try { - return yield parse_env_file_1.getEnvFileVars(path); - } - catch (e) { } - } - throw new Error(`Unable to locate env file at default locations (${ENV_FILE_DEFAULT_LOCATIONS})`); - }); -} -exports.getEnvFile = getEnvFile; -async function getRCFile({ environments, filePath }) { - // User provided an .rc file path - if (filePath) { - try { - return await parse_rc_file_1.getRCFileVars({ environments, filePath }); - } - catch (e) { - if (e.name !== 'PathError') - console.log(e); - throw new Error(`Unable to locate .rc file at location (${filePath})`); - } - } - // Use the default .rc file locations - for (const filePath of RC_FILE_DEFAULT_LOCATIONS) { - try { - return await parse_rc_file_1.getRCFileVars({ environments, filePath }); - } - catch (e) { - if (e.name !== 'PathError') - console.log(e); - } - } - throw new Error(`Unable to locate .rc file at default locations (${RC_FILE_DEFAULT_LOCATIONS})`); -} -exports.getRCFile = getRCFile; diff --git a/dist/env-cmd.d.ts b/dist/src/env-cmd.d.ts similarity index 100% rename from dist/env-cmd.d.ts rename to dist/src/env-cmd.d.ts diff --git a/dist/env-cmd.js b/dist/src/env-cmd.js similarity index 96% rename from dist/env-cmd.js rename to dist/src/env-cmd.js index 8a3f4bc..8f24b2e 100644 --- a/dist/env-cmd.js +++ b/dist/src/env-cmd.js @@ -31,11 +31,10 @@ exports.CLI = CLI; * @param {EnvCmdOptions} { command, commandArgs, envFile, rc, options } * @returns {Promise<{ [key: string]: any }>} Returns an object containing [environment variable name]: value */ -async function EnvCmd({ command, commandArgs, envFile, rc, options }) { - options = options || {}; +async function EnvCmd({ command, commandArgs, envFile, rc, options = {} }) { let env = await get_env_vars_1.getEnvVars({ envFile, rc }); // Override the merge order if --no-override flag set - if (options.noOverride) { + if (options.noOverride === true) { env = Object.assign({}, env, process.env); } else { diff --git a/dist/get-env-vars.d.ts b/dist/src/get-env-vars.d.ts similarity index 100% rename from dist/get-env-vars.d.ts rename to dist/src/get-env-vars.d.ts diff --git a/dist/src/get-env-vars.js b/dist/src/get-env-vars.js new file mode 100644 index 0000000..3723f59 --- /dev/null +++ b/dist/src/get-env-vars.js @@ -0,0 +1,61 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const parse_rc_file_1 = require("./parse-rc-file"); +const parse_env_file_1 = require("./parse-env-file"); +const RC_FILE_DEFAULT_LOCATIONS = ['./.env-cmdrc', './.env-cmdrc.js', './.env-cmdrc.json']; +const ENV_FILE_DEFAULT_LOCATIONS = ['./.env', './.env.js', './.env.json']; +async function getEnvVars(options = {}) { + options.envFile = options.envFile !== undefined ? options.envFile : {}; + // Check for rc file usage + if (options.rc !== undefined) { + return getRCFile({ environments: options.rc.environments, filePath: options.rc.filePath }); + } + return getEnvFile({ filePath: options.envFile.filePath, fallback: options.envFile.fallback }); +} +exports.getEnvVars = getEnvVars; +async function getEnvFile({ filePath, fallback }) { + // Use env file + if (filePath !== undefined) { + try { + return await parse_env_file_1.getEnvFileVars(filePath); + } + catch (e) { } + if (fallback !== true) { + throw new Error(`Unable to locate env file at location (${filePath})`); + } + } + // Use the default env file locations + for (const path of ENV_FILE_DEFAULT_LOCATIONS) { + try { + return await parse_env_file_1.getEnvFileVars(path); + } + catch (e) { } + } + throw new Error(`Unable to locate env file at default locations (${ENV_FILE_DEFAULT_LOCATIONS})`); +} +exports.getEnvFile = getEnvFile; +async function getRCFile({ environments, filePath }) { + // User provided an .rc file path + if (filePath !== undefined) { + try { + return await parse_rc_file_1.getRCFileVars({ environments, filePath }); + } + catch (e) { + if (e.name !== 'PathError') + console.error(e); + throw new Error(`Unable to locate .rc file at location (${filePath})`); + } + } + // Use the default .rc file locations + for (const filePath of RC_FILE_DEFAULT_LOCATIONS) { + try { + return await parse_rc_file_1.getRCFileVars({ environments, filePath }); + } + catch (e) { + if (e.name !== 'PathError') + console.error(e); + } + } + throw new Error(`Unable to locate .rc file at default locations (${RC_FILE_DEFAULT_LOCATIONS})`); +} +exports.getRCFile = getRCFile; diff --git a/dist/index.d.ts b/dist/src/index.d.ts similarity index 100% rename from dist/index.d.ts rename to dist/src/index.d.ts diff --git a/dist/index.js b/dist/src/index.js similarity index 100% rename from dist/index.js rename to dist/src/index.js diff --git a/dist/parse-args.d.ts b/dist/src/parse-args.d.ts similarity index 100% rename from dist/parse-args.d.ts rename to dist/src/parse-args.d.ts diff --git a/dist/parse-args.js b/dist/src/parse-args.js similarity index 83% rename from dist/parse-args.js rename to dist/src/parse-args.js index 7419174..11d93df 100644 --- a/dist/parse-args.js +++ b/dist/src/parse-args.js @@ -15,16 +15,18 @@ function parseArgs(args) { const noOverride = !program.override; const useShell = !!program.useShell; let rc; - if (program.environments && program.environments.length) { - rc = rc || {}; - rc.environments = program.environments; - rc.filePath = program.rcFile; + if (program.environments !== undefined && program.environments.length !== 0) { + rc = { + environments: program.environments, + filePath: program.rcFile + }; } let envFile; - if (program.file) { - envFile = envFile || {}; - envFile.filePath = program.file; - envFile.fallback = program.fallback; + if (program.file !== undefined) { + envFile = { + filePath: program.file, + fallback: program.fallback + }; } return { command, diff --git a/dist/parse-env-file.d.ts b/dist/src/parse-env-file.d.ts similarity index 100% rename from dist/parse-env-file.d.ts rename to dist/src/parse-env-file.d.ts diff --git a/dist/parse-env-file.js b/dist/src/parse-env-file.js similarity index 95% rename from dist/parse-env-file.js rename to dist/src/parse-env-file.js index 57ff58a..c049c5c 100644 --- a/dist/parse-env-file.js +++ b/dist/src/parse-env-file.js @@ -15,7 +15,7 @@ async function getEnvFileVars(envFilePath) { // Get the file extension const ext = path.extname(absolutePath).toLowerCase(); let env = {}; - if (~REQUIRE_HOOK_EXTENSIONS.indexOf(ext)) { + if (REQUIRE_HOOK_EXTENSIONS.indexOf(ext) > -1) { const possiblePromise = require(absolutePath); /* eslint-disable-line */ env = utils_1.isPromise(possiblePromise) ? await possiblePromise : possiblePromise; } @@ -48,11 +48,11 @@ function parseEnvVars(envString) { while ((match = envParseRegex.exec(envString)) !== null) { // Note: match[1] is the full env=var line const key = match[2].trim(); - const value = match[3].trim() || ''; + const value = match[3].trim(); // remove any surrounding quotes matches[key] = value .replace(/(^['"]|['"]$)/g, '') - .replace(/\\n/g, `\n`); + .replace(/\\n/g, '\n'); } return matches; } diff --git a/dist/parse-rc-file.d.ts b/dist/src/parse-rc-file.d.ts similarity index 100% rename from dist/parse-rc-file.d.ts rename to dist/src/parse-rc-file.d.ts diff --git a/dist/parse-rc-file.js b/dist/src/parse-rc-file.js similarity index 95% rename from dist/parse-rc-file.js rename to dist/src/parse-rc-file.js index 1c00e4e..b8a6f3e 100644 --- a/dist/parse-rc-file.js +++ b/dist/src/parse-rc-file.js @@ -35,7 +35,7 @@ async function getRCFileVars({ environments, filePath }) { let environmentFound = false; environments.forEach((name) => { const envVars = parsedData[name]; - if (envVars) { + if (envVars !== undefined) { environmentFound = true; result = Object.assign({}, result, envVars); } @@ -63,7 +63,7 @@ function parseRCFile(fileData) { console.error(`Error: Failed to parse the .rc file. Please make sure its a valid JSON format.`); - throw new Error(`Unable to parse JSON in .rc file.`); + throw new Error('Unable to parse JSON in .rc file.'); } return data; } diff --git a/dist/signal-termination.d.ts b/dist/src/signal-termination.d.ts similarity index 91% rename from dist/signal-termination.d.ts rename to dist/src/signal-termination.d.ts index e7d97fd..18a2b35 100644 --- a/dist/signal-termination.d.ts +++ b/dist/src/signal-termination.d.ts @@ -1,7 +1,7 @@ /// import { ChildProcess } from 'child_process'; export declare class TermSignals { - private terminateSpawnedProcessFuncHandlers; + private readonly terminateSpawnedProcessFuncHandlers; _exitCalled: boolean; handleTermSignals(proc: ChildProcess): void; /** diff --git a/dist/signal-termination.js b/dist/src/signal-termination.js similarity index 95% rename from dist/signal-termination.js rename to dist/src/signal-termination.js index 0ee320b..d0a59b9 100644 --- a/dist/signal-termination.js +++ b/dist/src/signal-termination.js @@ -22,7 +22,7 @@ class TermSignals { }; process.once(signal, this.terminateSpawnedProcessFuncHandlers[signal]); }); - process.once('exit', this.terminateSpawnedProcessFuncHandlers['SIGTERM']); + process.once('exit', this.terminateSpawnedProcessFuncHandlers.SIGTERM); // Terminate parent process if child process receives termination events proc.on('exit', (code, signal) => { this._removeProcessListeners(); @@ -42,10 +42,10 @@ class TermSignals { * Terminate parent process helper */ _terminateProcess(code, signal) { - if (signal != null) { + if (signal !== undefined) { return process.kill(process.pid, signal); } - if (code != null) { + if (code !== undefined) { return process.exit(code); } throw new Error('Unable to terminate parent process successfully'); @@ -57,7 +57,7 @@ class TermSignals { SIGNALS_TO_HANDLE.forEach((signal) => { process.removeListener(signal, this.terminateSpawnedProcessFuncHandlers[signal]); }); - process.removeListener('exit', this.terminateSpawnedProcessFuncHandlers['SIGTERM']); + process.removeListener('exit', this.terminateSpawnedProcessFuncHandlers.SIGTERM); } /** * General exception handler diff --git a/dist/spawn.d.ts b/dist/src/spawn.d.ts similarity index 100% rename from dist/spawn.d.ts rename to dist/src/spawn.d.ts diff --git a/dist/spawn.js b/dist/src/spawn.js similarity index 100% rename from dist/spawn.js rename to dist/src/spawn.js diff --git a/dist/types.d.ts b/dist/src/types.d.ts similarity index 100% rename from dist/types.d.ts rename to dist/src/types.d.ts diff --git a/dist/types.js b/dist/src/types.js similarity index 100% rename from dist/types.js rename to dist/src/types.js diff --git a/dist/utils.d.ts b/dist/src/utils.d.ts similarity index 93% rename from dist/utils.d.ts rename to dist/src/utils.d.ts index 13e3d81..d3714a7 100644 --- a/dist/utils.d.ts +++ b/dist/src/utils.d.ts @@ -9,4 +9,4 @@ export declare function parseArgList(list: string): string[]; /** * A simple function to test if the value is a promise */ -export declare function isPromise(value: any | PromiseLike): boolean; +export declare function isPromise(value: any | PromiseLike): value is Promise; diff --git a/dist/utils.js b/dist/src/utils.js similarity index 89% rename from dist/utils.js rename to dist/src/utils.js index 7b5dd9b..9ae5f6b 100644 --- a/dist/utils.js +++ b/dist/src/utils.js @@ -8,7 +8,7 @@ const os = require("os"); function resolveEnvFilePath(userPath) { // Make sure a home directory exist const home = os.homedir(); - if (home) { + if (home !== undefined) { userPath = userPath.replace(/^~($|\/|\\)/, `${home}$1`); } return path.resolve(process.cwd(), userPath); @@ -25,6 +25,6 @@ exports.parseArgList = parseArgList; * A simple function to test if the value is a promise */ function isPromise(value) { - return value && typeof value.then === 'function'; + return value !== undefined && typeof value.then === 'function'; } exports.isPromise = isPromise; diff --git a/package.json b/package.json index 454d722..b1b4782 100644 --- a/package.json +++ b/package.json @@ -2,8 +2,8 @@ "name": "env-cmd", "version": "10.0.0", "description": "Executes a command using the environment variables in an env file", - "main": "dist/index.js", - "types": "dist/index.d.ts", + "main": "dist/src/index.js", + "types": "dist/src/index.d.ts", "engines": { "node": ">=8.0.0" }, @@ -48,7 +48,7 @@ }, "homepage": "https://github.com/toddbluhm/env-cmd#readme", "dependencies": { - "commander": "^2.0.0", + "commander": "^3.0.0", "cross-spawn": "^6.0.0" }, "devDependencies": { @@ -57,12 +57,13 @@ "@types/mocha": "^5.0.0", "@types/node": "^12.0.0", "@types/sinon": "^7.0.0", - "@typescript-eslint/eslint-plugin": "^1.0.0", - "@typescript-eslint/parser": "^1.0.0", + "@typescript-eslint/eslint-plugin": "^2.0.0", + "@typescript-eslint/parser": "^2.0.0", "chai": "^4.0.0", "coveralls": "^3.0.0", - "eslint": "^5.0.0", - "eslint-config-standard-with-typescript": "^8.0.0", + "eslint": "^6.0.0", + "eslint-config-standard": "^14.0.0", + "eslint-config-standard-with-typescript": "toddbluhm/eslint-config-standard-with-typescript#compiled", "eslint-plugin-import": "^2.0.0", "eslint-plugin-node": "^9.0.0", "eslint-plugin-promise": "^4.0.0", diff --git a/src/env-cmd.ts b/src/env-cmd.ts index 0620cfa..bca2a91 100644 --- a/src/env-cmd.ts +++ b/src/env-cmd.ts @@ -32,12 +32,11 @@ export async function CLI (args: string[]): Promise<{ [key: string]: any }> { * @returns {Promise<{ [key: string]: any }>} Returns an object containing [environment variable name]: value */ export async function EnvCmd ( - { command, commandArgs, envFile, rc, options }: EnvCmdOptions + { command, commandArgs, envFile, rc, options = {} }: EnvCmdOptions ): Promise<{ [key: string]: any }> { - options = options || {} let env = await getEnvVars({ envFile, rc }) // Override the merge order if --no-override flag set - if (options.noOverride) { + if (options.noOverride === true) { env = Object.assign({}, env, process.env) } else { // Add in the system environment variables to our environment list diff --git a/src/get-env-vars.ts b/src/get-env-vars.ts index 2dc662e..92eb446 100644 --- a/src/get-env-vars.ts +++ b/src/get-env-vars.ts @@ -5,11 +5,10 @@ import { getEnvFileVars } from './parse-env-file' const RC_FILE_DEFAULT_LOCATIONS = ['./.env-cmdrc', './.env-cmdrc.js', './.env-cmdrc.json'] const ENV_FILE_DEFAULT_LOCATIONS = ['./.env', './.env.js', './.env.json'] -export async function getEnvVars (options?: GetEnvVarOptions): Promise<{ [key: string]: any }> { - options = options || {} - options.envFile = options.envFile || {} +export async function getEnvVars (options: GetEnvVarOptions = {}): Promise<{ [key: string]: any }> { + options.envFile = options.envFile !== undefined ? options.envFile : {} // Check for rc file usage - if (options.rc) { + if (options.rc !== undefined) { return getRCFile({ environments: options.rc.environments, filePath: options.rc.filePath }) } return getEnvFile({ filePath: options.envFile.filePath, fallback: options.envFile.fallback }) @@ -19,11 +18,11 @@ export async function getEnvFile ( { filePath, fallback }: { filePath?: string, fallback?: boolean } ): Promise<{ [key: string]: any }> { // Use env file - if (filePath) { + if (filePath !== undefined) { try { return await getEnvFileVars(filePath) } catch (e) { } - if (!fallback) { + if (fallback !== true) { throw new Error(`Unable to locate env file at location (${filePath})`) } } @@ -42,11 +41,11 @@ export async function getRCFile ( { environments, filePath }: { environments: string[], filePath?: string } ): Promise<{ [key: string]: any }> { // User provided an .rc file path - if (filePath) { + if (filePath !== undefined) { try { return await getRCFileVars({ environments, filePath }) } catch (e) { - if (e.name !== 'PathError') console.log(e) + if (e.name !== 'PathError') console.error(e) throw new Error(`Unable to locate .rc file at location (${filePath})`) } } @@ -56,7 +55,7 @@ export async function getRCFile ( try { return await getRCFileVars({ environments, filePath }) } catch (e) { - if (e.name !== 'PathError') console.log(e) + if (e.name !== 'PathError') console.error(e) } } diff --git a/src/parse-args.ts b/src/parse-args.ts index b8a0e16..7d09b1a 100644 --- a/src/parse-args.ts +++ b/src/parse-args.ts @@ -13,21 +13,23 @@ export function parseArgs (args: string[]): EnvCmdOptions { // Reprocess the args with the command and command args removed program = parseArgsUsingCommander(args.slice(0, args.indexOf(command))) - const noOverride = !program.override - const useShell = !!program.useShell + const noOverride = !(program.override as boolean) + const useShell = !!(program.useShell as boolean) let rc: any - if (program.environments && program.environments.length) { - rc = rc || {} - rc.environments = program.environments - rc.filePath = program.rcFile + if (program.environments !== undefined && program.environments.length !== 0) { + rc = { + environments: program.environments, + filePath: program.rcFile + } } let envFile: any - if (program.file) { - envFile = envFile || {} - envFile.filePath = program.file - envFile.fallback = program.fallback + if (program.file !== undefined) { + envFile = { + filePath: program.file, + fallback: program.fallback + } } return { diff --git a/src/parse-env-file.ts b/src/parse-env-file.ts index 12869cc..d505309 100644 --- a/src/parse-env-file.ts +++ b/src/parse-env-file.ts @@ -16,7 +16,7 @@ export async function getEnvFileVars (envFilePath: string): Promise<{ [key: stri // Get the file extension const ext = path.extname(absolutePath).toLowerCase() let env = {} - if (~REQUIRE_HOOK_EXTENSIONS.indexOf(ext)) { + if (REQUIRE_HOOK_EXTENSIONS.indexOf(ext) > -1) { const possiblePromise = require(absolutePath) /* eslint-disable-line */ env = isPromise(possiblePromise) ? await possiblePromise : possiblePromise } else { @@ -50,12 +50,12 @@ export function parseEnvVars (envString: string): { [key: string]: string } { while ((match = envParseRegex.exec(envString)) !== null) { // Note: match[1] is the full env=var line const key = match[2].trim() - const value = match[3].trim() || '' + const value = match[3].trim() // remove any surrounding quotes matches[key] = value .replace(/(^['"]|['"]$)/g, '') - .replace(/\\n/g, `\n`) + .replace(/\\n/g, '\n') } return matches } diff --git a/src/parse-rc-file.ts b/src/parse-rc-file.ts index 96cae4a..77833f0 100644 --- a/src/parse-rc-file.ts +++ b/src/parse-rc-file.ts @@ -38,7 +38,7 @@ export async function getRCFileVars ( let environmentFound = false environments.forEach((name): void => { const envVars = parsedData[name] - if (envVars) { + if (envVars !== undefined) { environmentFound = true result = { ...result, @@ -70,7 +70,7 @@ export function parseRCFile (fileData: string): { [key: string]: any } { console.error(`Error: Failed to parse the .rc file. Please make sure its a valid JSON format.`) - throw new Error(`Unable to parse JSON in .rc file.`) + throw new Error('Unable to parse JSON in .rc file.') } return data } diff --git a/src/signal-termination.ts b/src/signal-termination.ts index 8a8c7d6..3c3e308 100644 --- a/src/signal-termination.ts +++ b/src/signal-termination.ts @@ -5,7 +5,7 @@ const SIGNALS_TO_HANDLE: NodeJS.Signals[] = [ ] export class TermSignals { - private terminateSpawnedProcessFuncHandlers: { [key: string]: any } = {} + private readonly terminateSpawnedProcessFuncHandlers: { [key: string]: any } = {} public _exitCalled = false public handleTermSignals (proc: ChildProcess): void { @@ -22,7 +22,7 @@ export class TermSignals { } process.once(signal, this.terminateSpawnedProcessFuncHandlers[signal]) }) - process.once('exit', this.terminateSpawnedProcessFuncHandlers['SIGTERM']) + process.once('exit', this.terminateSpawnedProcessFuncHandlers.SIGTERM) // Terminate parent process if child process receives termination events proc.on('exit', (code: number | undefined, signal: string | undefined): void => { @@ -45,10 +45,10 @@ export class TermSignals { * Terminate parent process helper */ public _terminateProcess (code?: number, signal?: string): void { - if (signal != null) { + if (signal !== undefined) { return process.kill(process.pid, signal) } - if (code != null) { + if (code !== undefined) { return process.exit(code) } throw new Error('Unable to terminate parent process successfully') @@ -61,7 +61,7 @@ export class TermSignals { SIGNALS_TO_HANDLE.forEach((signal): void => { process.removeListener(signal, this.terminateSpawnedProcessFuncHandlers[signal]) }) - process.removeListener('exit', this.terminateSpawnedProcessFuncHandlers['SIGTERM']) + process.removeListener('exit', this.terminateSpawnedProcessFuncHandlers.SIGTERM) } /** diff --git a/src/utils.ts b/src/utils.ts index 086b50d..548a8cd 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -7,7 +7,7 @@ import * as os from 'os' export function resolveEnvFilePath (userPath: string): string { // Make sure a home directory exist const home = os.homedir() - if (home) { + if (home !== undefined) { userPath = userPath.replace(/^~($|\/|\\)/, `${home}$1`) } return path.resolve(process.cwd(), userPath) @@ -22,6 +22,6 @@ export function parseArgList (list: string): string[] { /** * A simple function to test if the value is a promise */ -export function isPromise (value: any | PromiseLike): boolean { - return value && typeof value.then === 'function' +export function isPromise (value: any | PromiseLike): value is Promise { + return value !== undefined && typeof value.then === 'function' } diff --git a/test/get-env-vars.spec.ts b/test/get-env-vars.spec.ts index a51f24a..b42c8eb 100644 --- a/test/get-env-vars.spec.ts +++ b/test/get-env-vars.spec.ts @@ -7,6 +7,7 @@ import * as envFile from '../src/parse-env-file' describe('getEnvVars', (): void => { let getRCFileVarsStub: sinon.SinonStub let getEnvFileVarsStub: sinon.SinonStub + let logStub: sinon.SinonStub const pathError = new Error() pathError.name = 'PathError' @@ -14,6 +15,7 @@ describe('getEnvVars', (): void => { before((): void => { getRCFileVarsStub = sinon.stub(rcFile, 'getRCFileVars') getEnvFileVarsStub = sinon.stub(envFile, 'getEnvFileVars') + logStub = sinon.stub(console, 'error') }) after((): void => { @@ -62,6 +64,17 @@ describe('getEnvVars', (): void => { } }) + it('should log to error console on non-path errors', async (): Promise => { + getRCFileVarsStub.rejects(new Error('Non-path Error')) + try { + await getEnvVars({ rc: { environments: ['production'] } }) + assert.fail('should not get here.') + } catch (e) { + assert.match(logStub.getCall(0).args[0].message, /non-path error/gi) + assert.match(e.message, /locate \.rc/gi) + } + }) + it('should find .rc file at custom path location', async (): Promise => { getRCFileVarsStub.returns({ THANKS: 'FORALLTHEFISH' }) const envs = await getEnvVars({ @@ -84,7 +97,19 @@ describe('getEnvVars', (): void => { }) assert.fail('should not get here.') } catch (e) { - console.log(e) + assert.match(e.message, /locate \.rc/gi) + } + }) + + it('should log to error console on non-path errors', async (): Promise => { + getRCFileVarsStub.rejects(new Error('Non-path Error')) + try { + await getEnvVars({ + rc: { environments: ['production'], filePath: '../.custom-rc' } + }) + assert.fail('should not get here.') + } catch (e) { + assert.match(logStub.getCall(0).args[0].message, /non-path error/gi) assert.match(e.message, /locate \.rc/gi) } }) diff --git a/test/parse-env-file.spec.ts b/test/parse-env-file.spec.ts index 42d6a95..0ddcdcc 100644 --- a/test/parse-env-file.spec.ts +++ b/test/parse-env-file.spec.ts @@ -63,7 +63,7 @@ describe('parseEnvVars', (): void => { }) it('should preserve newlines when surrounded in quotes', (): void => { - const envVars = parseEnvVars(`ONE_NEWLINE="ONE\\n"\nTWO_NEWLINES="HELLO\\nWORLD\\n"\nTHREE_NEWLINES="HELLO\\n\\nWOR\\nLD"\n`) + const envVars = parseEnvVars('ONE_NEWLINE="ONE\\n"\nTWO_NEWLINES="HELLO\\nWORLD\\n"\nTHREE_NEWLINES="HELLO\\n\\nWOR\\nLD"\n') assert(envVars.ONE_NEWLINE === 'ONE\n') assert(envVars.TWO_NEWLINES === 'HELLO\nWORLD\n') assert(envVars.THREE_NEWLINES === 'HELLO\n\nWOR\nLD') @@ -104,47 +104,47 @@ describe('getEnvFileVars', (): void => { it('should parse a json file', async (): Promise => { const env = await getEnvFileVars('./test/test-files/test.json') assert.deepEqual(env, { - 'THANKS': 'FOR WHAT?!', - 'ANSWER': 42, - 'ONLY': 'IN PRODUCTION', - 'GALAXY': 'hitch\nhiking' + THANKS: 'FOR WHAT?!', + ANSWER: 42, + ONLY: 'IN PRODUCTION', + GALAXY: 'hitch\nhiking' }) }) it('should parse a json file keeping all newlines intact', async (): Promise => { const env = await getEnvFileVars('./test/test-files/test-newlines.json') assert.deepEqual(env, { - 'THANKS': 'FOR WHAT?!', - 'ANSWER': 42, - 'ONLY': 'IN\n PRODUCTION', - 'GALAXY': 'hitch\nhiking\n\n' + THANKS: 'FOR WHAT?!', + ANSWER: 42, + ONLY: 'IN\n PRODUCTION', + GALAXY: 'hitch\nhiking\n\n' }) }) it('should parse a js file', async (): Promise => { const env = await getEnvFileVars('./test/test-files/test.js') assert.deepEqual(env, { - 'THANKS': 'FOR ALL THE FISH', - 'ANSWER': 0, - 'GALAXY': 'hitch\nhiking' + THANKS: 'FOR ALL THE FISH', + ANSWER: 0, + GALAXY: 'hitch\nhiking' }) }) it('should parse an async js file', async (): Promise => { const env = await getEnvFileVars('./test/test-files/test-async.js') assert.deepEqual(env, { - 'THANKS': 'FOR ALL THE FISH', - 'ANSWER': 0 + THANKS: 'FOR ALL THE FISH', + ANSWER: 0 }) }) it('should parse an env file', async (): Promise => { const env = await getEnvFileVars('./test/test-files/test') assert.deepEqual(env, { - 'THANKS': 'FOR WHAT?!', - 'ANSWER': '42', - 'ONLY': 'IN=PRODUCTION', - 'GALAXY': 'hitch\nhiking' + THANKS: 'FOR WHAT?!', + ANSWER: '42', + ONLY: 'IN=PRODUCTION', + GALAXY: 'hitch\nhiking' }) }) diff --git a/test/parse-rc-file.spec.ts b/test/parse-rc-file.spec.ts index a71a948..eb793e5 100644 --- a/test/parse-rc-file.spec.ts +++ b/test/parse-rc-file.spec.ts @@ -30,9 +30,9 @@ describe('getRCFileVars', (): void => { const res = await getRCFileVars({ environments: ['production'], filePath: rcFilePath }) assert.exists(res) assert.deepEqual(res, { - 'THANKS': 'FOR WHAT?!', - 'ANSWER': 42, - 'ONLY': 'IN PRODUCTION' + THANKS: 'FOR WHAT?!', + ANSWER: 42, + ONLY: 'IN PRODUCTION' }) }) @@ -40,8 +40,8 @@ describe('getRCFileVars', (): void => { const res = await getRCFileVars({ environments: ['test'], filePath: rcJSONFilePath }) assert.exists(res) assert.deepEqual(res, { - 'THANKS': 'FOR MORE FISHIES', - 'ANSWER': 21 + THANKS: 'FOR MORE FISHIES', + ANSWER: 21 }) }) @@ -69,9 +69,9 @@ describe('getRCFileVars', (): void => { filePath: './test/test-files/.rc-test-async.js' }) assert.deepEqual(env, { - 'THANKS': 'FOR WHAT?!', - 'ANSWER': 42, - 'ONLY': 'IN PRODUCTION' + THANKS: 'FOR WHAT?!', + ANSWER: 42, + ONLY: 'IN PRODUCTION' }) }) }) diff --git a/tsconfig.json b/tsconfig.json index 3d0ff9b..bb3885c 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -10,6 +10,7 @@ ] }, "include": [ - "./src/**/*" + "./src/**/*", + "./test/**/*" ] } \ No newline at end of file