-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
81 lines (75 loc) · 2.33 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
const fs = require("fs");
const path = require("path");
const execSync = require("child_process").execSync;
class Utils {
/**
* 获取某个包的安装情况
* 返回 0 表示未安装 1 表示安装并非最新 2 表示安装最新
*/
getInstalledStatus(pkgName, targetDir) {
const genObj = this.getInstalledPkgs(targetDir);
if (!genObj[pkgName]) return 0;
const lts = execSync(`npm view ${pkgName} version --json --registry=https://registry.npm.taobao.org`) + '' // buffer 转 string
const current = this.requireFrom(targetDir, path.join(pkgName, "package.json")).version;
if (current === lts.trim()) return 2;
return 1;
}
/**
* 获取路径下已经安装的 generator 包
*/
getInstalledGenerators(targetDir) {
const dependencies = this.getInstalledPkgs(targetDir);
Object.keys(dependencies).forEach(v => {
if (!v.match(/^gen-/)) delete dependencies[v];
});
return dependencies;
}
/**
* 获取路径下已经安装的包
*/
getInstalledPkgs(targetDir) {
const pkgJsonFile = path.resolve(targetDir, "package.json");
if (!fs.existsSync(pkgJsonFile)) return {};
const pkgJson = require(pkgJsonFile);
return pkgJson.dependencies || {};
}
/**
* 获取 build 方法
*/
getBuilderFn() {
const { builder } = this.getConfigs();
const status = this.getInstalledStatus(builder, process.cwd());
switch (status) {
case 0:
this.console(
`检测到工程并未添加${builder},将自动为您安装最新版`,
"red"
);
this.console(`安装${builder}中...`);
execSync(
`npm i ${builder}@latest -S --registry=https://registry.npm.taobao.org`,
{ cwd: process.cwd() }
);
break;
case 1:
this.console(
`检测到您的${builder}并非最新版,推荐在工程下 npm i ${builder}@latest -S 进行更新`
);
break;
default:
}
return this.requireFrom(process.cwd(), builder);
}
getConfigs() {
const configs = this.requireFrom(process.cwd(), "./maoda.js");
if (!configs || !configs.builder) {
this.console(
"请确保工程根路径下有 maoda.js 文件,且文件中配置了 builder 属性",
"red"
);
process.exit(1);
}
return configs;
}
}
module.exports = Utils;