mirror of
https://github.com/toddbluhm/env-cmd.git
synced 2025-12-08 18:23:33 +00:00
- Complete rewrite and reorganization - Expose a usable programmatic API - Support Async .env files by accepting javascript files - Update all libraries/dependencies - Support for more options in the future by using commanderjs - More thorough test cases and code-coverage - Better handling of signal terminations for both parent and child processes - Use ESLint Standard with Typescript
74 lines
1.8 KiB
TypeScript
74 lines
1.8 KiB
TypeScript
import { stat, readFile } from 'fs'
|
|
import { promisify } from 'util'
|
|
import { extname } from 'path'
|
|
import { resolveEnvFilePath } from './utils'
|
|
|
|
const statAsync = promisify(stat)
|
|
const readFileAsync = promisify(readFile)
|
|
|
|
/**
|
|
* Gets the env vars from the rc file and rc environments
|
|
*/
|
|
export async function getRCFileVars (
|
|
{ environments, filePath }:
|
|
{ environments: string[], filePath: string }
|
|
): Promise<{ [key: string]: any }> {
|
|
const absolutePath = resolveEnvFilePath(filePath)
|
|
try {
|
|
await statAsync(absolutePath)
|
|
} catch (e) {
|
|
throw new Error('Invalid .rc file path.')
|
|
}
|
|
|
|
// Get the file extension
|
|
const ext = extname(absolutePath).toLowerCase()
|
|
let parsedData: { [key: string]: any }
|
|
if (ext === '.json' || ext === '.js') {
|
|
parsedData = require(absolutePath)
|
|
} else {
|
|
const file = await readFileAsync(absolutePath, { encoding: 'utf8' })
|
|
parsedData = parseRCFile(file)
|
|
}
|
|
|
|
// Parse and merge multiple rc environments together
|
|
let result = {}
|
|
let environmentFound = false
|
|
environments.forEach((name): void => {
|
|
const envVars = parsedData[name]
|
|
if (envVars) {
|
|
environmentFound = true
|
|
result = {
|
|
...result,
|
|
...envVars
|
|
}
|
|
}
|
|
})
|
|
|
|
if (!environmentFound) {
|
|
console.error(`Error:
|
|
Could not find any environments:
|
|
${environments}
|
|
in .rc file:
|
|
${absolutePath}`)
|
|
throw new Error(`All environments (${environments}) are missing in in .rc file (${absolutePath}).`)
|
|
}
|
|
|
|
return result
|
|
}
|
|
|
|
/**
|
|
* Reads and parses the .rc file
|
|
*/
|
|
export function parseRCFile (fileData: string): { [key: string]: any } {
|
|
let data
|
|
try {
|
|
data = JSON.parse(fileData)
|
|
} catch (e) {
|
|
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.`)
|
|
}
|
|
return data
|
|
}
|