MCPcopy
hub / github.com/toddbluhm/env-cmd / getRCFileVars

Function getRCFileVars

src/parse-rc-file.ts:15–91  ·  view source on GitHub ↗
(
  { environments, filePath }:
  { environments: string[], filePath: string },
)

Source from the content-addressed store, hash-verified

13 * Gets the env vars from the rc file and rc environments
14 */
15export async function getRCFileVars(
16 { environments, filePath }:
17 { environments: string[], filePath: string },
18): Promise<Environment> {
19 const absolutePath = resolveEnvFilePath(filePath)
20 try {
21 await statAsync(absolutePath)
22 }
23 catch {
24 const pathError = new Error(`Failed to find .rc file at path: ${absolutePath}`)
25 pathError.name = 'PathError'
26 throw pathError
27 }
28
29 // Get the file extension
30 const ext = extname(absolutePath).toLowerCase()
31 let parsedData: Partial<RCEnvironment> = {}
32 try {
33 if (IMPORT_HOOK_EXTENSIONS.includes(ext)) {
34 if (/tsx?$/.test(ext)) checkIfTypescriptSupported()
35
36 // For some reason in ES Modules, only JSON file types need to be specifically delinated when importing them
37 let attributeTypes = {}
38 if (ext === '.json') {
39 attributeTypes = { with: { type: 'json' } }
40 }
41 const res = await import(pathToFileURL(absolutePath).href, attributeTypes) as RCEnvironment | { default: RCEnvironment }
42 if ('default' in res) {
43 parsedData = res.default as RCEnvironment
44 } else {
45 parsedData = res
46 }
47 // Check to see if the imported value is a promise
48 if (isPromise(parsedData)) {
49 parsedData = await parsedData
50 }
51 }
52 else {
53 const file = await readFileAsync(absolutePath, { encoding: 'utf8' })
54 parsedData = JSON.parse(file) as Partial<RCEnvironment>
55 }
56 }
57 catch (e) {
58 const errorMessage = e instanceof Error ? e.message : 'Unknown error'
59 const parseError = new Error(
60 `Failed to parse .rc file at path: ${absolutePath}.\n${errorMessage}`,
61 )
62 parseError.name = 'ParseError'
63 throw parseError
64 }
65
66 // Parse and merge multiple rc environments together
67 let result: Environment = {}
68 let environmentFound = false
69 for (const name of environments) {
70 if (name in parsedData) {
71 const envVars = parsedData[name]
72 if (envVars != null && typeof envVars === 'object') {

Callers 2

getRCFileFunction · 0.85

Calls 3

resolveEnvFilePathFunction · 0.85
isPromiseFunction · 0.85

Tested by

no test coverage detected