-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.js
223 lines (197 loc) · 5.72 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
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
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const childProcess = require('child_process');
// const path = require('path');
const log = {
// eslint-disable-next-line @typescript-eslint/naming-convention
_log (color, s) {
console.log(`${color}%s\x1b[0m`, s);
},
red (s) { this._log('\x1b[31m', s); },
green (s) { this._log('\x1b[32m', s); },
yellow (s) { this._log('\x1b[33m', s); },
blue (s) { this._log('\x1b[34m', s); },
purple (s) { this._log('\x1b[35m', s); },
cyan (s) { this._log('\x1b[36m', s); },
};
function upcaseFirstLetter (str) {
return str.split('-').map(s => s[0].toUpperCase() + s.substring(1)).join('');
}
function buildCommon ({
titleName,
bundleCmd,
dtsCmd,
addon = '',
}) {
log.blue(`Start Build ${titleName}`);
let result = execSync(bundleCmd);
log.blue(`Build ${addon}${titleName} Bundle Done:`);
log.green(`${result.toString()}`);
if (dtsCmd) {
result = execSync(dtsCmd);
log.blue(`Build ${addon}${titleName} DTS Done:`);
}
log.green(`${result.toString()}`);
}
function resolveRootPath (str) {
return path.resolve(__dirname, `../${str}`);
}
function resolveRelativePath (dirname, str) {
return path.resolve(dirname, `./${str}`);
}
function resolvePackagePath (str) {
return path.resolve(__dirname, `../packages/${str}`);
}
function writeJsonIntoFile (json, filePath) {
fs.writeFileSync(checkPath(filePath), JSON.stringify(json, null, 4), 'utf-8');
}
function writeStringIntoFile (str, filePath) {
fs.writeFileSync(checkPath(filePath), str, 'utf-8');
}
function copyFile ({
src,
dest = src,
handler = null,
json = false,
}) {
src = checkPath(src);
dest = checkPath(dest);
if (handler) {
let content = json
? require(checkPath(src))
: readFile(src);
content = handler(content);
json
? writeJsonIntoFile(content, dest)
: writeStringIntoFile(content, dest);
} else {
fs.copyFileSync(src, dest);
}
}
function checkPath (filePath) {
if (filePath[0] === '@') { return resolveRootPath(filePath.substring(1)); }
if (filePath[0] === '#') { return resolvePackagePath(filePath.substring(1)); }
return filePath;
}
function mkdir (filePath) {
filePath = checkPath(filePath);
if (!fs.existsSync(filePath)) {
console.log('mkdirSync', filePath);
fs.mkdirSync(filePath);
}
}
function clearDirectory (dirPath) {
dirPath = checkPath(dirPath);
if (!fs.existsSync(dirPath)) {return;}
clearDirectoryBase(dirPath);
}
function clearDirectoryBase (dirPath) {
traverseDirectory(dirPath, ({ isDir, filepath }) => {
if (isDir) {
clearDirectoryBase(filepath);
fs.rmdirSync(filepath);
} else {
fs.unlinkSync(filepath);
}
});
}
function traverseDirectory (dirPath, callback) {
const files = fs.readdirSync(dirPath);
files.forEach((file) => {
const filePath = `${dirPath}/${file}`;
const stat = fs.statSync(filePath);
callback({
isDir: stat.isDirectory(),
filename: file,
filePath,
});
});
}
function buildPackageJson (extract = {}) {
const pkg = require(resolveRootPath('package.json'));
const attrs = [
'name', 'version', 'description', 'main', 'unpkg', 'jsdelivr', 'typings',
'repository', 'keywords', 'author', 'license', 'bugs', 'homepage',
'dependencies',
];
const npmPkg = {};
attrs.forEach(key => {
npmPkg[key] = pkg[key] || '';
});
for (const key in extract) {
npmPkg[key] = extract[key];
}
mkdir('@npm');
writeJsonIntoFile(npmPkg, '@npm/package.json');
}
async function exec (cmd) {
return new Promise((resolve) => {
if (cmd instanceof Array) {
cmd = cmd.join(' ');
}
childProcess.exec(cmd, (error, stdout, stderr) => {
console.log(error, stdout, stderr);
if (error) {
resolve({ success: false, stdout, stderr });
} else {
resolve({
success: true,
stdout,
stderr,
});
}
}).stdout.on('data', data => {
if (typeof data === 'string' && data.indexOf('sl:') === 0) {
console.log(data.replace('sl:', ''));
} else {
console.log(data);
}
});
});
}
function readFile (file) {
return fs.readFileSync(checkPath(file), 'utf8');
}
function writeFile (file, txt) {
fs.writeFileSync(checkPath(file), txt, 'utf8');
}
function execBin (name, cmd = name) {
const npmPath = checkPath(`@node_modules/${name}`);
// eslint-disable-next-line @typescript-eslint/no-require-imports
const pkg = require(`${npmPath}/package.json`);
if (!pkg.bin || !pkg.bin[cmd]) {
throw new Error(`Wrong cmd: ${name} ${cmd}`);
}
const binPath = path.resolve(npmPath, pkg.bin[cmd]);
return `node ${binPath}`;
}
function buildPackageName (dirName) {
const pkg = require(path.resolve(__dirname, `../packages/${dirName}/package.json`));
return pkg.name; // todo 修改包命名规则
}
function isNodeExec () {
return (process.argv[process.argv.length - 1] === 'EXEC');
}
module.exports = {
execBin,
exec,
copyFile,
resolveRootPath,
resolveRelativePath,
checkPath,
upcaseFirstLetter,
writeJsonIntoFile,
writeStringIntoFile,
resolvePackagePath,
buildPackageJson,
clearDirectory,
traverseDirectory,
mkdir,
readFile,
writeFile,
log,
buildCommon,
buildPackageName,
isNodeExec,
};