1 import { join } from "path"
2 import { writeFile, readFile } from "fs/promises"
3
4 /**
5 * Exposes the API to edit Env files
6 */
7 export class EnvEditor {
8 #appRoot: string
9 #files: {
10 exists: boolean
11 contents: string[]
12 filePath: string
13 }[] = []
14
15 constructor(appRoot: string) {
16 this.#appRoot = appRoot
17 }
18
19 /**
20 * Reads a file and returns with contents. Ignores error
21 * when file is missing
22 */
23 async #readFile(filePath: string) {
24 try {
25 const contents = await readFile(filePath, "utf-8")
26 return {
27 exists: true,
28 contents: contents.split(/\r?\n/),
29 filePath,
30 }
31 } catch (error) {
32 if (error.code === "ENOENT") {
33 return {
34 exists: false,
35 contents: [],
36 filePath,
37 }
38 }
39 throw error
40 }
41 }
42
43 /**
44 * Loads .env and .env.template files for editing.
45 */
46 async load() {
47 this.#files = await Promise.all(
48 [join(this.#appRoot, ".env"), join(this.#appRoot, ".env.template")].map(
49 (filePath) => this.#readFile(filePath)
50 )
51 )
52 }
53
54 /**
55 * Returns the value for an existing key from the
56 * ".env" file
57 */
58 get(key: string): string | null {
59 const envFile = this.#files.find((file) => file.filePath.endsWith(".env"))
60 if (!envFile) {
61 return null
62 }
63 const matchingLine = envFile.contents.find((line) =>
64 line.startsWith(`${key}=`)
65 )
66 if (!matchingLine) {
67 return null
68 }
69
70 const [_, ...rest] = matchingLine.split("=")
71 return rest.join("=")
72 }
73
74 /**
75 * Set key-value pair to the dot-env files.
76 *
77 * If `withEmptyTemplateValue` is true then the key will be added with an empty value
78 * to the `.env.template` file.
79 */
80 set(
81 key: string,
82 value: string | number | boolean,
83 options?: {
84 withEmptyTemplateValue: boolean
85 }
86 ) {
87 const withEmptyTemplateValue = options?.withEmptyTemplateValue ?? false
88 this.#files.forEach((file) => {
89 let entryIndex = file.contents.findIndex((line) =>
90 line.startsWith(`${key}=`)
91 )
92 const writeIndex = entryIndex === -1 ? file.contents.length : entryIndex
93
94 if (withEmptyTemplateValue && file.filePath.endsWith(".env.template")) {
95 /**
96 * Do not remove existing template value (if any)
97 */
98 if (entryIndex === -1) {
99 file.contents[writeIndex] = `${key}=`
100 }
101 } else {
102 file.contents[writeIndex] = `${key}=${value}`
103 }
104 })
105 }
106
107 /**
108 * Get files and their contents as JSON
109 */
110 toJSON() {
111 return this.#files
112 }
113
114 /**
115 * Save changes back to the disk
116 */
117 async save() {
118 await Promise.all(
119 this.#files.map((file) => {
120 return writeFile(file.filePath, file.contents.join("\n"))
121 })
122 )
123 }
124 }