forked from benawad/gen-env-types
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgen-env-types.js
206 lines (169 loc) · 5.29 KB
/
gen-env-types.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#!/usr/bin/env node
const {
readFileSync,
writeFileSync,
existsSync,
lstatSync,
} = require("fs");
const pkg = require("./package.json");
const chalk = require("chalk");
const { join } = require("path");
const { parse } = require("./parse");
const printVersion = () => console.log("v" + pkg.version);
const printHelp = (exitCode) => {
console.log(
chalk`{blue gen-env-types} - Generate a .d.ts and .env.example file from your .env file.
{bold USAGE}
{blue gen-env-types} path/to/.env
{bold OPTIONS}
-V, --version Show version number
-h, --help Show usage information
-o, --types-output Output name/path for types file | defaults to \`env.d.ts\`
-e, --example-env-path Path to save .env.example file
-r, --rename-example-env Custom name for .env example output file | defaults to \`env.example\` if omitted
-k, --keep-comments Keep comments/blank lines in .env example output file | defaults to false if omitted.
Not accepting the value. When specified, it will be true.
`
);
return process.exit(exitCode);
};
function showError(msg) {
console.log(chalk`{red Error:} ${msg}`);
process.exit(1);
}
const parseArgs = (args) => {
const cliConfig = {
typesOutput: "env.d.ts",
exampleEnvOutput: ".env.example",
keepComments: false,
};
while (args.length > 0) {
const arg = args.shift();
if (arg == null) break;
switch (arg) {
case "-h":
case "--help":
cliConfig.help = true;
break;
case "-V":
case "--version":
cliConfig.version = true;
break;
case "-o":
case "--types-output":
const typesOutput = args.shift();
if (!typesOutput || !typesOutput.endsWith(".d.ts")) {
showError(
"Expected output file to end in .d.ts, bad input: " + typesOutput
);
}
cliConfig.typesOutput = typesOutput;
break;
case "-e":
case "--example-env-path":
const exampleEnvPath = args.shift();
if (!exampleEnvPath) {
showError("Expected example env path but none found");
}
if (!existsSync(exampleEnvPath)) {
showError("Example env path does not exist: " + exampleEnvPath);
}
cliConfig.exampleEnvPath = exampleEnvPath;
break;
case "-r":
case "--rename-example-env":
cliConfig.exampleEnvOutput = args.shift();
break;
case "-k":
case "--keep-comments":
cliConfig.keepComments = true;
break;
default: {
if (!existsSync(arg)) {
showError(".env file doesn't exist at path: " + arg);
}
if (!lstatSync(arg).isFile()) {
showError(`${arg} is not a file.`);
}
cliConfig.envPath = arg;
}
}
}
if (!cliConfig.envPath && existsSync(join(process.cwd(), ".env"))) {
cliConfig.envPath = join(process.cwd(), ".env");
}
return cliConfig;
};
const cliConfig = parseArgs(process.argv.slice(2));
if (!cliConfig.envPath) {
printHelp(1);
}
if (cliConfig.help) {
return printHelp(0);
}
if (cliConfig.version) {
return printVersion();
}
const envString = readFileSync(cliConfig.envPath, {
encoding: "utf8",
});
// Parse env string with comments and blank lines
const parsedEnvString = parse(envString);
// Filter out blank lines and comments
const filteredEnvString = parsedEnvString.filter((line) => line.isEnvVar);
function writeEnvTypes(path) {
const existingModuleDeclaration =
existsSync(path) && readFileSync(path, { encoding: "utf-8" });
const moduleDeclaration = `declare global {
namespace NodeJS {
interface ProcessEnv {
${filteredEnvString
.map(({key}, i) => {
if (!existingModuleDeclaration) {
return `${i ? " " : ""}${key}: string;`;
}
const existingPropertySignature = existingModuleDeclaration
.split("\n")
.find((line) => line.includes(`${key}:`));
if (!existingPropertySignature) {
return `${i ? " " : ""}${key}: string;`;
}
return `${i ? " " : ""}${existingPropertySignature.trim()}`;
})
.join("\n")}
}
}
}
export {}
`;
writeFileSync(path, moduleDeclaration);
console.log("Wrote env types to: ", path);
}
function writeExampleEnv(parsedExistingEnvString, path, isNew) {
const out = (cliConfig.keepComments? parsedEnvString: filteredEnvString)
.map(({key, isEnvVar,value}) => {
if(isEnvVar) return `${key}=`;
// Comment or blank value
return value;
})
.join("\n");
const withExistingEnvVariables = parsedExistingEnvString.reduce((strContent, {key, value}) => {
return strContent.replace(`${key}=`, `${key}=${value}`);
}, out);
writeFileSync(path, isNew ? out : withExistingEnvVariables);
console.log("Wrote example env to: ", path);
}
writeEnvTypes(cliConfig.typesOutput);
if (cliConfig.exampleEnvPath) {
const outputExampleEnvPath = join(
cliConfig.exampleEnvPath,
cliConfig.exampleEnvOutput
);
if (existsSync(outputExampleEnvPath)) {
const parsedExistingEnvString = parse(
readFileSync(outputExampleEnvPath, { encoding: "utf-8" })
);
return writeExampleEnv(parsedExistingEnvString, outputExampleEnvPath);
}
writeExampleEnv(filteredEnvString, outputExampleEnvPath, true);
}