forked from npm/cli
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwindows-shims.js
279 lines (253 loc) · 8.36 KB
/
windows-shims.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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
const t = require('tap')
const { spawnSync } = require('child_process')
const { resolve, join, extname, basename, sep } = require('path')
const { copyFileSync, readFileSync, chmodSync, readdirSync, rmSync, statSync } = require('fs')
const Diff = require('diff')
const { sync: which } = require('which')
const { version } = require('../../package.json')
const readNonJsFiles = (dir) => readdirSync(dir).reduce((acc, shim) => {
const p = join(dir, shim)
if (extname(p) !== '.js' && !statSync(p).isDirectory()) {
acc[shim] = readFileSync(p, 'utf-8')
}
return acc
}, {})
const ROOT = resolve(__dirname, '../..')
const BIN = join(ROOT, 'bin')
const SHIMS = readNonJsFiles(BIN)
const NODE_GYP = readNonJsFiles(join(BIN, 'node-gyp-bin'))
const SHIM_EXTS = [...new Set(Object.keys(SHIMS).map(p => extname(p)))]
// windows requires each segment of a command path to be quoted when using shell: true
const quotePath = (cmd) => cmd
.split(sep)
.map(p => p.includes(' ') ? `"${p}"` : p)
.join(sep)
t.test('shim contents', t => {
// these scripts should be kept in sync so this tests the contents of each
// and does a diff to ensure the only differences between them are necessary
const diffFiles = (npm, npx) => Diff.diffChars(npm, npx)
.filter(v => v.added || v.removed)
.reduce((acc, v) => {
if (v.value.length === 1) {
acc.letters.add(v.value.toUpperCase())
} else {
acc.diff.push(v.value)
}
return acc
}, { diff: [], letters: new Set() })
t.plan(SHIM_EXTS.length)
t.test('bash', t => {
const { diff, letters } = diffFiles(SHIMS.npm, SHIMS.npx)
t.match(diff[0].split('\n').reverse().join(''), /^NPX_CLI_JS=/, 'has NPX_CLI')
t.equal(diff.length, 1)
t.strictSame([...letters], ['M', 'X'], 'all other changes are m->x')
t.end()
})
t.test('cmd', t => {
const { diff, letters } = diffFiles(SHIMS['npm.cmd'], SHIMS['npx.cmd'])
t.match(diff[0], /^SET "NPX_CLI_JS=/, 'has NPX_CLI')
t.equal(diff.length, 1)
t.strictSame([...letters], ['M', 'X'], 'all other changes are m->x')
t.end()
})
t.test('pwsh', t => {
const { diff, letters } = diffFiles(SHIMS['npm.ps1'], SHIMS['npx.ps1'])
t.equal(diff.length, 0)
t.strictSame([...letters], ['M', 'X'], 'all other changes are m->x')
t.end()
})
})
t.test('node-gyp', t => {
// these files need to exist to avoid breaking yarn 1.x
for (const [key, file] of Object.entries(NODE_GYP)) {
t.match(file, /npm_config_node_gyp/, `${key} contains env var`)
t.match(
file,
/[\\/]\.\.[\\/]\.\.[\\/]node_modules[\\/]node-gyp[\\/]bin[\\/]node-gyp\.js/,
`${key} contains path`
)
}
t.end()
})
t.test('run shims', t => {
const path = t.testdir({
...SHIMS,
// simulate the state where one version of npm is installed
// with node, but we should load the globally installed one
'global-prefix': {
node_modules: {
npm: t.fixture('symlink', ROOT),
},
},
// put in a shim that ONLY prints the intended global prefix,
// and should not be used for anything else.
node_modules: {
npm: {
bin: {
'npx-cli.js': `throw new Error('this should not be called')`,
'npm-cli.js': `
const assert = require('assert')
const { resolve } = require('path')
assert.equal(process.argv.slice(2).join(' '), 'prefix -g')
console.log(resolve(__dirname, '../../../global-prefix'))
`,
},
},
},
})
// hacky fix to decrease flakes of this test from `NOTEMPTY: directory not empty, rmdir`
// this should get better in tap@18 and we can try removing it then
copyFileSync(process.execPath, join(path, 'node.exe'))
t.teardown(async () => {
rmSync(join(path, 'node.exe'))
await new Promise(res => setTimeout(res, 100))
// this is superstition
rmSync(join(path, 'node.exe'), { force: true })
})
const spawnPath = (cmd, args, { log, stdioString = true, ...opts } = {}) => {
if (cmd.endsWith('bash.exe')) {
// only cygwin *requires* the -l, but the others are ok with it
args.unshift('-l')
}
const result = spawnSync(cmd, args, {
// don't hit the registry for the update check
env: { PATH: path, npm_config_update_notifier: 'false' },
cwd: path,
windowsHide: true,
...opts,
})
if (stdioString) {
result.stdout = result.stdout?.toString()?.trim()
result.stderr = result.stderr?.toString()?.trim()
}
return {
status: result.status,
signal: result.signal,
stdout: result.stdout,
stderr: result.stderr,
}
}
const getWslVersion = (cmd) => {
const defaultVersion = 1
try {
const opts = { shell: cmd, env: process.env }
const wsl = spawnPath('wslpath', [`'${which('wsl')}'`], opts).stdout
const distrosRaw = spawnPath(wsl, ['-l', '-v'], { ...opts, stdioString: false }).stdout
const distros = spawnPath('iconv', ['-f', 'unicode'], { ...opts, input: distrosRaw }).stdout
const distroArgs = distros
.replace(/\r\n/g, '\n')
.split('\n')
.slice(1)
.find(d => d.startsWith('*'))
.replace(/\s+/g, ' ')
.split(' ')
return Number(distroArgs[distroArgs.length - 1]) || defaultVersion
} catch {
return defaultVersion
}
}
for (const shim of Object.keys(SHIMS)) {
chmodSync(join(path, shim), 0o755)
}
const { ProgramFiles = '/', SystemRoot = '/', NYC_CONFIG, WINDOWS_SHIMS_TEST } = process.env
const skipDefault = WINDOWS_SHIMS_TEST || process.platform === 'win32'
? null : 'test not relevant on platform'
const shells = Object.entries({
cmd: 'cmd',
pwsh: 'pwsh',
git: join(ProgramFiles, 'Git', 'bin', 'bash.exe'),
'user git': join(ProgramFiles, 'Git', 'usr', 'bin', 'bash.exe'),
wsl: join(SystemRoot, 'System32', 'bash.exe'),
cygwin: resolve(SystemRoot, '/', 'cygwin64', 'bin', 'bash.exe'),
}).map(([name, cmd]) => {
let match = {}
const skip = { reason: skipDefault, fail: WINDOWS_SHIMS_TEST }
const isBash = cmd.endsWith('bash.exe')
const testName = `${name} ${isBash ? 'bash' : ''}`.trim()
if (!skip.reason) {
if (isBash) {
try {
// If WSL is installed, it *has* a bash.exe, but it fails if
// there is no distro installed, so we need to detect that.
if (spawnPath(cmd, ['-c', 'exit 0']).status !== 0) {
throw new Error('not installed')
}
if (name === 'cygwin' && NYC_CONFIG) {
throw new Error('does not play nicely with nyc')
}
// WSL version 1 does not work due to
// https://github.com/microsoft/WSL/issues/2370
if (name === 'wsl' && getWslVersion(cmd) === 1) {
match = {
status: 1,
stderr: 'WSL 1 is not supported. Please upgrade to WSL 2 or above.',
stdout: String,
}
}
} catch (err) {
skip.reason = err.message
}
} else {
try {
cmd = which(cmd)
} catch {
skip.reason = 'not installed'
}
}
}
return {
match,
cmd,
name: testName,
skip: {
...skip,
reason: skip.reason ? `${testName} - ${skip.reason}` : null,
},
}
})
const matchCmd = (t, cmd, bin, match) => {
const args = []
const opts = {}
switch (basename(cmd).toLowerCase()) {
case 'cmd.exe':
cmd = `${bin}.cmd`
break
case 'bash.exe':
args.push(bin)
break
case 'pwsh.exe':
cmd = quotePath(cmd)
args.push(`${bin}.ps1`)
opts.shell = true
break
default:
throw new Error('unknown shell')
}
const isNpm = bin === 'npm'
const result = spawnPath(cmd, [...args, isNpm ? 'help' : '--version'], opts)
t.match(result, {
status: 0,
signal: null,
stderr: '',
stdout: isNpm ? `npm@${version} ${ROOT}` : version,
...match,
}, `${cmd} ${bin}`)
}
// ensure that all tests are either run or skipped
t.plan(shells.length)
for (const { cmd, skip, name, match } of shells) {
t.test(name, t => {
if (skip.reason) {
if (skip.fail) {
t.fail(skip.reason)
} else {
t.skip(skip.reason)
}
return t.end()
}
t.plan(2)
matchCmd(t, cmd, 'npm', match)
matchCmd(t, cmd, 'npx', match)
})
}
})