UNPKG

1.58 kBJavaScriptView Raw
1'use strict'
2
3const fs = require('fs-extra')
4const path = require('path')
5const which = require('which')
6const execa = require('execa')
7const semver = require('semver')
8
9/**
10 * 获取 npm-lifecycle 版本
11 *
12 * @returns {string} npm-lifecycle version
13 */
14function getNpmLifecycleVersion () {
15 const npmPath = which.sync('npm', {
16 nothrow: true
17 })
18
19 if (!npmPath) {
20 return ''
21 }
22
23 const pathSuffix = process.platform === 'win32'
24 ? '../node_modules/npm/node_modules/npm-lifecycle/package.json'
25 : '../../node_modules/npm-lifecycle/package.json'
26
27 const lifecyclePkgPath = path.join(fs.realpathSync(npmPath), pathSuffix)
28
29 if (!fs.existsSync(lifecyclePkgPath)) {
30 return ''
31 }
32
33 // eslint-disable-next-line global-require
34 return require(lifecyclePkgPath).version
35}
36
37/**
38 * 检查 npm 版本
39 *
40 * npm 使用 npm-lifecycle 执行 hooks,但是某些版本存在 bug
41 * https://github.com/npm/npm-lifecycle/pull/13/files
42 *
43 * 规则: npm-lifecycle 存在,且版本 < 2.0.2,报错并提示用户升级 npm,具体规则链接到 README
44 */
45
46const npmVersion = execa.sync('npm', ['-v']).stdout
47const npmLifecycleVersion = getNpmLifecycleVersion()
48let pass = true
49
50/**
51 * 检测到 npm-lifecycle 的时候(新版本都有),要求 npm-lifecycle >= 2.0.2
52 * 检测不到 npm-lifecycle 的时候,要求 npm 不能在 5.1.0 ~ 6.1.0
53 */
54if (npmLifecycleVersion) {
55 pass = semver.gte(npmLifecycleVersion, '2.0.2')
56} else {
57 pass = semver.satisfies(npmVersion, '<5.1.0 || >6.1.0')
58}
59
60module.exports = {
61 npmVersion,
62 npmLifecycleVersion,
63 pass
64}