-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtool.js
72 lines (65 loc) · 1.78 KB
/
tool.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
const fs = require('fs');
const childProcess = require('child_process');
const readline = require('readline');
let lineBreak = '\n';
const checkLBStyle = (filePath) => {
if (fs.existsSync(filePath)) {
const content = fs.readFileSync(filePath, { encoding: 'utf8' });
const newlines = content.match(/(?:\r?\n)/g) || [];
if (newlines.length === 0) {
return;
}
const crlf = newlines.filter(newline => newline === '\r\n').length;
if (crlf * 2 > newlines.length) {
// console.log('lineBreak: CRLF');
lineBreak = '\r\n';
} else {
// console.log('lineBreak: LF');
}
}
};
const runCMDSync = (cmd, options) => {
options = options || {};
console.log(cmd);
const defaultOpt = { stdio: 'inherit' };
options = {
...defaultOpt,
...options
};
// fix some strange bug in win10
// https://github.com/SBoudrias/Inquirer.js/issues/792
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.close();
childProcess.execSync(cmd, options);
return true;
};
const isFilesExist = (regExp, path = '.') => {
const filterFunc = item => (regExp instanceof RegExp ? regExp.test(item) : regExp === item);
const files = fs.readdirSync(path);
const filteredFiles = files.filter(filterFunc);
return filteredFiles.length > 0;
};
const getPackageObj = () => {
const packageStr = fs.readFileSync('./package.json', { encoding: 'utf8' });
return JSON.parse(packageStr);
};
const setPackageObj = (nv) => {
const packageStr = JSON.stringify(nv, null, 2);
return fs.writeFileSync('./package.json', packageStr);
};
const init = () => {
checkLBStyle('./package.json');
return {
lineBreak,
runCMDSync,
isFilesExist,
getPackageObj,
setPackageObj,
};
};
module.exports = {
init,
};