This repository has been archived by the owner on Jan 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
184 lines (165 loc) · 5.59 KB
/
index.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
const { delimiter, dirname, resolve } = require('path')
const { promisify } = require('util')
const read = promisify(require('read'))
const Arborist = require('@npmcli/arborist')
const ciDetect = require('@npmcli/ci-detect')
const logger = require('proc-log')
const mkdirp = require('mkdirp-infer-owner')
const npa = require('npm-package-arg')
const pacote = require('pacote')
const readPackageJson = require('read-package-json-fast')
const cacheInstallDir = require('./cache-install-dir.js')
const { fileExists, localFileExists } = require('./file-exists.js')
const getBinFromManifest = require('./get-bin-from-manifest.js')
const manifestMissing = require('./manifest-missing.js')
const noTTY = require('./no-tty.js')
const runScript = require('./run-script.js')
const isWindows = require('./is-windows.js')
/* istanbul ignore next */
const PATH = (
process.env.PATH || process.env.Path || process.env.path
).split(delimiter)
const exec = async (opts) => {
const {
args = [],
call = '',
color = false,
localBin = resolve('./node_modules/.bin'),
locationMsg = undefined,
globalBin = '',
output,
packages: _packages = [],
path = '.',
runPath = '.',
scriptShell = isWindows ? process.env.ComSpec || 'cmd' : 'sh',
yes = undefined,
...flatOptions
} = opts
const log = flatOptions.log || logger
// dereferences values because we manipulate it later
const packages = [..._packages]
const pathArr = [...PATH]
const _run = () => runScript({
args,
call,
color,
flatOptions,
locationMsg,
log,
output,
path,
pathArr,
runPath,
scriptShell,
})
// nothing to maybe install, skip the arborist dance
if (!call && !args.length && !packages.length)
return await _run()
const needPackageCommandSwap = args.length && !packages.length
// if there's an argument and no package has been explicitly asked for
// check the local and global bin paths for a binary named the same as
// the argument and run it if it exists, otherwise fall through to
// the behavior of treating the single argument as a package name
if (needPackageCommandSwap) {
let binExists = false
const dir = dirname(dirname(localBin))
const localBinPath = await localFileExists(dir, args[0])
if (localBinPath) {
pathArr.unshift(localBinPath)
binExists = true
} else if (await fileExists(`${globalBin}/${args[0]}`)) {
pathArr.unshift(globalBin)
binExists = true
}
if (binExists)
return await _run()
packages.push(args[0])
}
// If we do `npm exec foo`, and have a `foo` locally, then we'll
// always use that, so we don't really need to fetch the manifest.
// So: run npa on each packages entry, and if it is a name with a
// rawSpec==='', then try to readPackageJson at
// node_modules/${name}/package.json, and only pacote fetch if
// that fails.
const manis = await Promise.all(packages.map(async p => {
const spec = npa(p, path)
if (spec.type === 'tag' && spec.rawSpec === '') {
// fall through to the pacote.manifest() approach
try {
const pj = resolve(path, 'node_modules', spec.name, 'package.json')
return await readPackageJson(pj)
} catch (er) {}
}
// Force preferOnline to true so we are making sure to pull in the latest
// This is especially useful if the user didn't give us a version, and
// they expect to be running @latest
return await pacote.manifest(p, {
...flatOptions,
preferOnline: true,
})
}))
if (needPackageCommandSwap)
args[0] = getBinFromManifest(manis[0])
// figure out whether we need to install stuff, or if local is fine
const localArb = new Arborist({
...flatOptions,
path,
})
const tree = await localArb.loadActual()
// do we have all the packages in manifest list?
const needInstall =
manis.some(manifest => manifestMissing({ tree, manifest }))
if (needInstall) {
const { npxCache } = flatOptions
const installDir = cacheInstallDir({ npxCache, packages })
await mkdirp(installDir)
const arb = new Arborist({
...flatOptions,
path: installDir,
})
const tree = await arb.loadActual()
// at this point, we have to ensure that we get the exact same
// version, because it's something that has only ever been installed
// by npm exec in the cache install directory
const add = manis.filter(mani => manifestMissing({
tree,
manifest: {
...mani,
_from: `${mani.name}@${mani.version}`,
},
}))
.map(mani => mani._from)
.sort((a, b) => a.localeCompare(b, 'en'))
// no need to install if already present
if (add.length) {
if (!yes) {
// set -n to always say no
if (yes === false)
throw new Error('canceled')
if (noTTY() || ciDetect()) {
log.warn('exec', `The following package${
add.length === 1 ? ' was' : 's were'
} not found and will be installed: ${
add.map((pkg) => pkg.replace(/@$/, '')).join(', ')
}`)
} else {
const addList = add.map(a => ` ${a.replace(/@$/, '')}`)
.join('\n') + '\n'
const prompt = `Need to install the following packages:\n${
addList
}Ok to proceed? `
const confirm = await read({ prompt, default: 'y' })
if (confirm.trim().toLowerCase().charAt(0) !== 'y')
throw new Error('canceled')
}
}
await arb.reify({
...flatOptions,
add,
})
}
pathArr.unshift(resolve(installDir, 'node_modules/.bin'))
}
return await _run()
}
module.exports = exec