-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
278 lines (255 loc) · 8.27 KB
/
index.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#!/usr/bin/env node
const fs = require("fs");
const path = require("path");
const { ask, handleEnv, isCommentLine } = require("./utils");
const currentCwd = process.cwd();
let ENV_PATH = path.resolve(currentCwd, ".env");
const ENV_TYPES = ["example", "local", "dev", "development", "prod", "production", "staging", "preview"];
let extension = "";
const argvs = process.argv;
const getExtension = () => {
return extension != "" ? `.env.${extension}` : ".env";
}
const isEnvFileExists = ({ create = true }) => {
try {
const isExists = fs.existsSync(ENV_PATH);
if (isExists == false) {
console.log(`${getExtension()} does not exists.`);
if (create == true) {
createEnvFile();
}
return { data: false };
}
return { data: true };
} catch (e) {
return { error: e.message }
}
}
const createEnvFile = () => {
try {
const data = fs.openSync(ENV_PATH, "w");
console.log(`Created ${getExtension()} file`);
return { data };
} catch (e) {
return { error: e.message };
}
}
const changeLine = ({ line = null, value = "" }) => {
const data = fs.readFileSync(ENV_PATH, "utf8");
const lines = data.split("\n");
for (let i = 0; i < lines.length; i++) {
const item = lines[i];
if (i == line) {
const splitItem = item.split("=");
lines[i] = splitItem[0] + "=" + value;
}
}
const result = lines.join("\n");
fs.writeFileSync(ENV_PATH, result);
return result;
}
const removeEnvVariable = ({ variable = null }) => {
const { data, error } = isEnvFileExists({ create: false });
if (data == false) {
return;
}
const envData = fs.readFileSync(ENV_PATH, "utf8");
let lines = envData.split("\n");
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const splitted = line.split("=");
const isEnvMatch = splitted[0] == variable;
if (isCommentLine({ str: line }) == false && isEnvMatch == true) {
lines.splice(i, 1);
console.log(`✔️ : ${splitted[0]} deleted from ${getExtension()}`)
break;
}
//If variable not found
if (i == lines.length - 1) {
console.log(`❗: Could not found ${variable} on ${getExtension()}`);
console.log(`❕: Please just write the variable name not with value.`)
console.log(`❕: Please make sure to pay attention to case sensitivity.`);
}
}
const result = lines.join("\n");
fs.writeFileSync(ENV_PATH, result);
return result;
}
const updateEnvVariable = async ({ variable = null, value = null, forceUpdate = false }) => {
try {
const envData = fs.readFileSync(ENV_PATH, "utf8");
const splitted = envData.split("\n");
const pattern = new RegExp(variable);
let alreadyExists = false;
for (let i = 0; i < splitted.length; i++) {
const line = splitted[i];
const split = line.split("=");
if (split[0] == variable) {
const { ENV_VAR, ENV_VAL } = handleEnv({ str: line });
alreadyExists = true;
if(forceUpdate === true){
changeLine({ line: i, value: value });
console.log(`✔️ : ${variable} updated with "${value}" on ${getExtension()}`)
break;
}
const answer = await ask(`⚠️: <${ENV_VAR}> already exits and it's value is <${ENV_VAL}> \n Continue to edit? [Y/N] `);
if (answer.match(/n|no/i)) {
console.log(`⛔ : ${ENV_VAR} not added`);
process.exit(0);
}
if (answer.match(/y|yes/i)) {
// console.log('we will continue to add');
changeLine({ line: i, value: value });
break;
}
} else {
//If variable not found
if(i === splitted.length -1 && forceUpdate === true){
console.log(`❗: ${variable} not found in ${getExtension()}`)
}
}
}
return alreadyExists;
} catch (e) {
return { error: e.message };
}
}
const addEnvVariable = async ({ variable = null, value = null }) => {
try {
isEnvFileExists({ create: true });
if (isCommentLine({ str: variable }) || isCommentLine({ str: value })) {
console.log(`Your value looks like a comment line`);
console.log(`Please use --comment option to add comment`);
process.exit();
}
const status = await updateEnvVariable({ variable, value });
if (status == false) {
const comment = commentLineOption();
if(comment){
fs.appendFileSync(ENV_PATH, `\n${comment}`);
}
fs.appendFileSync(ENV_PATH, `\n${variable}=${value}`);
console.log(`✔️ : ${variable} added as a new variable`);
process.exit();
}
console.log(`✔️ : ${variable} edited with ${value}`);
process.exit();
} catch (e) {
return { error: e.message };
}
}
const listEnvVariables = () => {
isEnvFileExists({ create: false });
const envData = fs.readFileSync(ENV_PATH, "utf8");
const lines = envData.split("\n");
let count = 1;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const isComment = isCommentLine({ str: line });
const splitted = line.split("=");
if (line != "" && isComment == false && splitted.length > 1) {
console.log(`${count}. ${line}`);
count++;
}
}
console.log(`📄 : ${count - 1} variable${count - 1 !== 1 ? 's':''} found in ${getExtension()}`)
}
const commentLineOption = () => {
const command = argvs[4];
if (command == '--comment') {
const commentVal = argvs[5];
if (isCommentLine({ str: commentVal })) {
// fs.appendFileSync(ENV_PATH, `\n${commentVal}`);
return commentVal;
} else {
console.log(`<${commentVal}> is not a comment line`);
console.log(`It must starts with "#"`);
return null;
}
}
}
const showHelp = () => {
console.log(`
Usage envar-cli <command> <value>
Where <command> can be:
* add
* update
* remove
* list
You can add variable using:
envar-cli add PORT=8080
You can update variable using:
envar-cli update PORT=8080
You can remove variable using:
envar-cli remove PORT=8080
Default file is .env and you can change it.
Supported files:
* .env
* .env.example
* .env.local
* .env.dev
* .env.development
* .env.prod
* .env.production
* .env.staging
* .env.preview
For more details please visit:
https://github.com/kodcanlisi/envar-cli#readme
`);
}
/**
* Types can be:
* example
* local
* dev
* development
* prod
* production
* staging
* preview
*/
const envFileType = () => {
const lastArgv = argvs[argvs.length - 1];
const clearArgv = lastArgv.replace(/-/g, "");
const envTypeIndex = ENV_TYPES.indexOf(clearArgv);
if (envTypeIndex > -1) {
extension = ENV_TYPES[envTypeIndex];
ENV_PATH += "." + extension;
}
return true;
}
const start = () => {
try {
const command = argvs[2];
envFileType();
switch (command) {
case "add": {
const { ENV_VAR, ENV_VAL } = handleEnv({ str: argvs[3] });
addEnvVariable({ variable: ENV_VAR, value: ENV_VAL });
break;
}
case "update": {
const { ENV_VAR, ENV_VAL } = handleEnv({ str: argvs[3] });
updateEnvVariable({ variable: ENV_VAR, value: ENV_VAL, forceUpdate: true });
break;
}
case "del":
case "delete":
case "remove": {
removeEnvVariable({ variable: argvs[3] });
break;
}
case "list": {
listEnvVariables();
break;
}
case "help":{
showHelp();
break;
}
}
} catch (e) {
console.error(e.message);
}
}
start();