-
Notifications
You must be signed in to change notification settings - Fork 0
/
install.js
107 lines (93 loc) · 2.63 KB
/
install.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
const fs = require('fs')
const path = require('path')
const child_process = require('child_process')
const data = require('./package.json')
const utils = require('./utils')
const versionFromPackageJSON = data.version
/**
* 日志格式化
*/
function log(msg) {
const text = `[grprogress] ${msg}`
const line = '='.repeat(text.length)
console.log(`
${line}
${text}
${line}`)
}
/**
* 递归删除目录
* @param {string} dir 指定要删除的目录
*/
function removeRecursive(dir) {
child_process.execSync(`rm -rf ${dir}`, {
cwd: path.resolve(__dirname),
stdio: 'inherit',
})
}
/**
* 通过npm安装指定包
* @param {string} pkg 包名
* @param {string} subpath 子路径,一般是包里的指定文件路径
* @param {string} binPath 指定文件迁移到的目标路径
*/
function installUsingNPM(pkg, subpath, binPath) {
const tempDir = 'grprogress-npm-install'
fs.mkdirSync(tempDir)
const installDir = path.resolve(__dirname, tempDir)
try {
fs.writeFileSync(path.join(installDir, 'package.json'), '{}')
child_process.execSync(`npm install ${pkg}@${versionFromPackageJSON} --save`, {
cwd: installDir,
stdio: 'inherit',
})
const installedBinPath = path.join(installDir, 'node_modules', pkg, subpath)
fs.renameSync(installedBinPath, binPath)
} catch (e) {
throw e
} finally {
removeRecursive(installDir)
}
}
/**
* 通过https下载tgz安装依赖
*/
function thirdInstall(pkg, subpath, binPath) {
// https://registry.npmjs.com/@grprogress/win32-x64/-/win32-x64-1.6.0.tgz
// 下载压缩包 -> 解压压缩包 -> 删除压缩包 -> 移动指定的文件 -> 删除文件夹
}
/**
* 通过npm安装依赖
*/
function secondInstall(pkg, subpath, binPath, fail) {
try {
installUsingNPM(pkg, subpath, binPath)
} catch (e) {
log('Failed to download and install from npm')
fail && fail()
}
}
/**
* 通过可选依赖项安装依赖
*/
function firstInstall(pkg, subpath, binPath, fail) {
try {
const installedBinPath = require.resolve(`${pkg}/${subpath}`)
fs.renameSync(installedBinPath, binPath)
} catch (e) {
log('Failed to download and install from optionalDependencies')
fail && fail()
}
}
async function main() {
const { packageName, platform } = utils.getPackageInfoByCurrentPlatform()
const binFilename = 'grprogress'
const subpath = platform === 'win32' ? binFilename + '.exe' : binFilename
const binPath = path.resolve(__dirname, subpath)
firstInstall(packageName, subpath, binPath, () => {
secondInstall(packageName, subpath, binPath, () => {
thirdInstall(packageName, subpath, binPath)
})
})
}
main()