-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
77 lines (66 loc) · 2.31 KB
/
utils.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
const chalk = require('chalk');
const prettier = require('prettier');
const { execSync } = require('child_process');
const fs = require('fs');
module.exports.log = console.log;
module.exports.kebabCase = string => string
.replace(/([a-z])([A-Z])/g, "$1-$2")
.replace(/[\s_]+/g, '-')
.toLowerCase();
module.exports.toPascalCase = string => string
.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.charAt(0).toUpperCase() + x.slice(1).toLowerCase())
.join('');
module.exports.toCamelCase = (string) => string
.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
if (+match === 0) return '';
return index === 0 ? match.toLowerCase() : match.toUpperCase();
});
module.exports.isLoopBackApp = (package) => {
if (!package) return false;
const { dependencies } = package;
if (!dependencies['@loopback/core']) return false;
return true;
}
module.exports.formatCode = (filePath) => {
const rawCode = fs.readFileSync(filePath, 'utf8');
const formatedCode = prettier.format(rawCode, {
parser: 'typescript',
singleQuote: true
});
fs.writeFileSync(filePath, formatedCode);
}
module.exports.replaceText = (filePath, updateThis, updateWith, replaceAll) => {
const file = fs.readFileSync(filePath, 'utf8');
if (file.indexOf(updateWith) === -1) {
const updatedFile = file[replaceAll ? 'replaceAll' : 'replace'](
updateThis,
updateWith
);
fs.writeFileSync(filePath, updatedFile, 'utf8');
}
}
module.exports.updateFile = (filePath, updateThis, updateWith, pre, replaceAll) => {
const file = fs.readFileSync(filePath, 'utf8');
if (file.indexOf(updateWith) === -1) {
const updateWithText = pre ? updateWith + '\n' + updateThis : updateThis + '\n\t' + updateWith;
this.replaceText(filePath, updateThis, updateWithText, replaceAll);
}
}
module.exports.shouldUpdate = (filePath, updates) => {
const file = fs.readFileSync(filePath, 'utf8');
return !file.includes(updates);
}
module.exports.addImports = (filePath, newImports) => {
newImports.forEach(newImport => {
this.updateFile(filePath, 'import', newImport, true);
});
}
module.exports.execute = (command, message) => {
this.log(chalk.blue(message));
try {
execSync(command, {stdio: 'inherit'});
} catch (err) {
throw Error(`failed to execute ${command}`);
}
}