-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegen-util.js
More file actions
77 lines (69 loc) · 1.72 KB
/
codegen-util.js
File metadata and controls
77 lines (69 loc) · 1.72 KB
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
/********************
* String formatter
********************/
/**
* @param {string} string
* @returns {string}
*/
const snakeCaseCap = (string) => {
return string
.replace(/\W+/g, ' ')
.split(/ |\B(?=[A-Z0-9])/)
.map((word) => word.toUpperCase())
.join('_');
};
/********************
* User Input Inquirer
********************/
const readline = require('node:readline');
/**
* @param {string} query
* @returns {Promise<string>}
*/
const askQuestion = (query) => {
const interface = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve) =>
interface.question(`${query} `, (ans) => {
interface.close();
resolve(ans);
}),
);
};
/********************
* Argument Parser
********************/
const convertBoolean = (v) => {
if (v.toLowerCase() === 'true') return true;
if (v.toLowerCase() === 'false') return false;
return v;
};
const parseNamedArg = (arg) => {
if (arg.includes('=')) {
// key-value pair
const [k, v] = arg.split('=');
return [k, convertBoolean(v)];
}
return [arg, true]; // key-only arg
};
const parseArg = (arg) => {
if (arg.startsWith('-')) {
while (arg.startsWith('-')) arg = arg.slice(1); // Remove '-'symbols
return parseNamedArg(arg);
}
return ['_', arg]; // value-only arg
};
const getArgs = () => {
const result = {};
result._ = [];
const args = process.argv.slice(2); // Remove execution file
for (let i = 0; i < args.length; i++) {
const [k, v] = parseArg(args[i]);
result[k] = k === '_' ? [...result[k], v] : v;
}
if (result.length === 0) console.warn('No arguments found');
return result;
};
module.exports = { snakeCaseCap, getArgs, askQuestion };