|
| 1 | +import fs from "fs-extra"; |
| 2 | + |
| 3 | +export interface EnvVariable { |
| 4 | + key: string; |
| 5 | + value: string; |
| 6 | + condition?: boolean; |
| 7 | +} |
| 8 | + |
| 9 | +export async function addEnvVariablesToFile( |
| 10 | + envPath: string, |
| 11 | + variables: EnvVariable[], |
| 12 | +): Promise<void> { |
| 13 | + let content = ""; |
| 14 | + |
| 15 | + if (fs.existsSync(envPath)) { |
| 16 | + content = await fs.readFile(envPath, "utf-8"); |
| 17 | + } else { |
| 18 | + // If file doesn't exist, create it |
| 19 | + await fs.ensureFile(envPath); |
| 20 | + } |
| 21 | + |
| 22 | + const existingLines = content.split("\n"); |
| 23 | + const newLines: string[] = []; |
| 24 | + const keysToAdd = new Map<string, string>(); |
| 25 | + |
| 26 | + for (const variable of variables) { |
| 27 | + if (variable.condition === false || !variable.key) { |
| 28 | + continue; |
| 29 | + } |
| 30 | + keysToAdd.set(variable.key, variable.value); |
| 31 | + } |
| 32 | + |
| 33 | + let foundKeys = new Set<string>(); |
| 34 | + |
| 35 | + for (const line of existingLines) { |
| 36 | + const trimmedLine = line.trim(); |
| 37 | + let lineProcessed = false; |
| 38 | + |
| 39 | + for (const [key, value] of keysToAdd) { |
| 40 | + if (trimmedLine.startsWith(`${key}=`)) { |
| 41 | + newLines.push(`${key}=${value}`); |
| 42 | + foundKeys.add(key); |
| 43 | + lineProcessed = true; |
| 44 | + break; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + if (!lineProcessed) { |
| 49 | + newLines.push(line); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + for (const [key, value] of keysToAdd) { |
| 54 | + if (!foundKeys.has(key)) { |
| 55 | + newLines.push(`${key}=${value}`); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + // Remove empty line at the end if it exists |
| 60 | + if (newLines.length > 0 && newLines[newLines.length - 1] === "") { |
| 61 | + newLines.pop(); |
| 62 | + } |
| 63 | + |
| 64 | + const hasChanges = foundKeys.size > 0 || keysToAdd.size > foundKeys.size; |
| 65 | + |
| 66 | + if (hasChanges) { |
| 67 | + await fs.writeFile(envPath, newLines.join("\n") + "\n"); |
| 68 | + } |
| 69 | +} |
0 commit comments