| import fs from 'fs'; |
|
|
| |
| |
| |
| |
| export function parseEnvFile(filePath) { |
| const envData = {}; |
| const content = fs.readFileSync(filePath, 'utf8'); |
| const lines = content.split('\n'); |
| |
| let currentKey = null; |
| let currentValue = ''; |
| let inMultiline = false; |
| let quoteChar = null; |
| |
| for (let i = 0; i < lines.length; i++) { |
| let line = lines[i]; |
| |
| if (inMultiline) { |
| |
| currentValue += '\n' + line; |
| |
| if (line.trimEnd().endsWith(quoteChar)) { |
| |
| currentValue = currentValue.slice(0, -1); |
| envData[currentKey] = currentValue; |
| inMultiline = false; |
| currentKey = null; |
| currentValue = ''; |
| quoteChar = null; |
| } |
| } else { |
| line = line.trim(); |
| if (!line || line.startsWith('#')) continue; |
| |
| const eqIndex = line.indexOf('='); |
| if (eqIndex === -1) continue; |
| |
| const key = line.slice(0, eqIndex).trim(); |
| let value = line.slice(eqIndex + 1); |
| |
| |
| const trimmedValue = value.trimStart(); |
| if ((trimmedValue.startsWith('"') || trimmedValue.startsWith("'")) && |
| !trimmedValue.endsWith(trimmedValue[0])) { |
| |
| quoteChar = trimmedValue[0]; |
| currentKey = key; |
| currentValue = trimmedValue.slice(1); |
| inMultiline = true; |
| } else { |
| |
| value = value.trim(); |
| if ((value.startsWith('"') && value.endsWith('"')) || |
| (value.startsWith("'") && value.endsWith("'"))) { |
| value = value.slice(1, -1); |
| } |
| envData[key] = value; |
| } |
| } |
| } |
| |
| |
| if (inMultiline && currentKey) { |
| envData[currentKey] = currentValue; |
| } |
| |
| return envData; |
| } |
|
|
| |
| |
| |
| |
| export function updateEnvFile(filePath, updates) { |
| let content = fs.readFileSync(filePath, 'utf8'); |
| |
| Object.entries(updates).forEach(([key, value]) => { |
| |
| let formattedValue = value; |
| if (typeof value === 'string' && value.includes('\n')) { |
| |
| formattedValue = `"${value}"`; |
| } |
| |
| |
| |
| const singleLineRegex = new RegExp(`^${key}=.*$`, 'm'); |
| |
| const multiLineRegex = new RegExp(`^${key}=["']([\\s\\S]*?)["']$`, 'm'); |
| |
| if (multiLineRegex.test(content)) { |
| |
| content = content.replace(multiLineRegex, `${key}=${formattedValue}`); |
| } else if (singleLineRegex.test(content)) { |
| |
| content = content.replace(singleLineRegex, `${key}=${formattedValue}`); |
| } else { |
| |
| content += `\n${key}=${formattedValue}`; |
| } |
| }); |
| |
| fs.writeFileSync(filePath, content, 'utf8'); |
| } |
|
|