source: node_modules/node-gyp/lib/find-visualstudio.js@ 81bc7da

finki-main main
Last change on this file since 81bc7da was 81bc7da, checked in by Klimentina Efremova <klimentina08642@…>, 3 months ago

Initial commit

  • Property mode set to 100644
File size: 13.9 KB
Line 
1'use strict'
2
3const log = require('npmlog')
4const execFile = require('child_process').execFile
5const fs = require('fs')
6const path = require('path').win32
7const logWithPrefix = require('./util').logWithPrefix
8const regSearchKeys = require('./util').regSearchKeys
9
10function findVisualStudio (nodeSemver, configMsvsVersion, callback) {
11 const finder = new VisualStudioFinder(nodeSemver, configMsvsVersion,
12 callback)
13 finder.findVisualStudio()
14}
15
16function VisualStudioFinder (nodeSemver, configMsvsVersion, callback) {
17 this.nodeSemver = nodeSemver
18 this.configMsvsVersion = configMsvsVersion
19 this.callback = callback
20 this.errorLog = []
21 this.validVersions = []
22}
23
24VisualStudioFinder.prototype = {
25 log: logWithPrefix(log, 'find VS'),
26
27 regSearchKeys: regSearchKeys,
28
29 // Logs a message at verbose level, but also saves it to be displayed later
30 // at error level if an error occurs. This should help diagnose the problem.
31 addLog: function addLog (message) {
32 this.log.verbose(message)
33 this.errorLog.push(message)
34 },
35
36 findVisualStudio: function findVisualStudio () {
37 this.configVersionYear = null
38 this.configPath = null
39 if (this.configMsvsVersion) {
40 this.addLog('msvs_version was set from command line or npm config')
41 if (this.configMsvsVersion.match(/^\d{4}$/)) {
42 this.configVersionYear = parseInt(this.configMsvsVersion, 10)
43 this.addLog(
44 `- looking for Visual Studio version ${this.configVersionYear}`)
45 } else {
46 this.configPath = path.resolve(this.configMsvsVersion)
47 this.addLog(
48 `- looking for Visual Studio installed in "${this.configPath}"`)
49 }
50 } else {
51 this.addLog('msvs_version not set from command line or npm config')
52 }
53
54 if (process.env.VCINSTALLDIR) {
55 this.envVcInstallDir =
56 path.resolve(process.env.VCINSTALLDIR, '..')
57 this.addLog('running in VS Command Prompt, installation path is:\n' +
58 `"${this.envVcInstallDir}"\n- will only use this version`)
59 } else {
60 this.addLog('VCINSTALLDIR not set, not running in VS Command Prompt')
61 }
62
63 this.findVisualStudio2017OrNewer((info) => {
64 if (info) {
65 return this.succeed(info)
66 }
67 this.findVisualStudio2015((info) => {
68 if (info) {
69 return this.succeed(info)
70 }
71 this.findVisualStudio2013((info) => {
72 if (info) {
73 return this.succeed(info)
74 }
75 this.fail()
76 })
77 })
78 })
79 },
80
81 succeed: function succeed (info) {
82 this.log.info(`using VS${info.versionYear} (${info.version}) found at:` +
83 `\n"${info.path}"` +
84 '\nrun with --verbose for detailed information')
85 process.nextTick(this.callback.bind(null, null, info))
86 },
87
88 fail: function fail () {
89 if (this.configMsvsVersion && this.envVcInstallDir) {
90 this.errorLog.push(
91 'msvs_version does not match this VS Command Prompt or the',
92 'installation cannot be used.')
93 } else if (this.configMsvsVersion) {
94 // If msvs_version was specified but finding VS failed, print what would
95 // have been accepted
96 this.errorLog.push('')
97 if (this.validVersions) {
98 this.errorLog.push('valid versions for msvs_version:')
99 this.validVersions.forEach((version) => {
100 this.errorLog.push(`- "${version}"`)
101 })
102 } else {
103 this.errorLog.push('no valid versions for msvs_version were found')
104 }
105 }
106
107 const errorLog = this.errorLog.join('\n')
108
109 // For Windows 80 col console, use up to the column before the one marked
110 // with X (total 79 chars including logger prefix, 62 chars usable here):
111 // X
112 const infoLog = [
113 '**************************************************************',
114 'You need to install the latest version of Visual Studio',
115 'including the "Desktop development with C++" workload.',
116 'For more information consult the documentation at:',
117 'https://github.com/nodejs/node-gyp#on-windows',
118 '**************************************************************'
119 ].join('\n')
120
121 this.log.error(`\n${errorLog}\n\n${infoLog}\n`)
122 process.nextTick(this.callback.bind(null, new Error(
123 'Could not find any Visual Studio installation to use')))
124 },
125
126 // Invoke the PowerShell script to get information about Visual Studio 2017
127 // or newer installations
128 findVisualStudio2017OrNewer: function findVisualStudio2017OrNewer (cb) {
129 var ps = path.join(process.env.SystemRoot, 'System32',
130 'WindowsPowerShell', 'v1.0', 'powershell.exe')
131 var csFile = path.join(__dirname, 'Find-VisualStudio.cs')
132 var psArgs = [
133 '-ExecutionPolicy',
134 'Unrestricted',
135 '-NoProfile',
136 '-Command',
137 '&{Add-Type -Path \'' + csFile + '\';' + '[VisualStudioConfiguration.Main]::PrintJson()}'
138 ]
139
140 this.log.silly('Running', ps, psArgs)
141 var child = execFile(ps, psArgs, { encoding: 'utf8' },
142 (err, stdout, stderr) => {
143 this.parseData(err, stdout, stderr, cb)
144 })
145 child.stdin.end()
146 },
147
148 // Parse the output of the PowerShell script and look for an installation
149 // of Visual Studio 2017 or newer to use
150 parseData: function parseData (err, stdout, stderr, cb) {
151 this.log.silly('PS stderr = %j', stderr)
152
153 const failPowershell = () => {
154 this.addLog(
155 'could not use PowerShell to find Visual Studio 2017 or newer, try re-running with \'--loglevel silly\' for more details')
156 cb(null)
157 }
158
159 if (err) {
160 this.log.silly('PS err = %j', err && (err.stack || err))
161 return failPowershell()
162 }
163
164 var vsInfo
165 try {
166 vsInfo = JSON.parse(stdout)
167 } catch (e) {
168 this.log.silly('PS stdout = %j', stdout)
169 this.log.silly(e)
170 return failPowershell()
171 }
172
173 if (!Array.isArray(vsInfo)) {
174 this.log.silly('PS stdout = %j', stdout)
175 return failPowershell()
176 }
177
178 vsInfo = vsInfo.map((info) => {
179 this.log.silly(`processing installation: "${info.path}"`)
180 info.path = path.resolve(info.path)
181 var ret = this.getVersionInfo(info)
182 ret.path = info.path
183 ret.msBuild = this.getMSBuild(info, ret.versionYear)
184 ret.toolset = this.getToolset(info, ret.versionYear)
185 ret.sdk = this.getSDK(info)
186 return ret
187 })
188 this.log.silly('vsInfo:', vsInfo)
189
190 // Remove future versions or errors parsing version number
191 vsInfo = vsInfo.filter((info) => {
192 if (info.versionYear) {
193 return true
194 }
195 this.addLog(`unknown version "${info.version}" found at "${info.path}"`)
196 return false
197 })
198
199 // Sort to place newer versions first
200 vsInfo.sort((a, b) => b.versionYear - a.versionYear)
201
202 for (var i = 0; i < vsInfo.length; ++i) {
203 const info = vsInfo[i]
204 this.addLog(`checking VS${info.versionYear} (${info.version}) found ` +
205 `at:\n"${info.path}"`)
206
207 if (info.msBuild) {
208 this.addLog('- found "Visual Studio C++ core features"')
209 } else {
210 this.addLog('- "Visual Studio C++ core features" missing')
211 continue
212 }
213
214 if (info.toolset) {
215 this.addLog(`- found VC++ toolset: ${info.toolset}`)
216 } else {
217 this.addLog('- missing any VC++ toolset')
218 continue
219 }
220
221 if (info.sdk) {
222 this.addLog(`- found Windows SDK: ${info.sdk}`)
223 } else {
224 this.addLog('- missing any Windows SDK')
225 continue
226 }
227
228 if (!this.checkConfigVersion(info.versionYear, info.path)) {
229 continue
230 }
231
232 return cb(info)
233 }
234
235 this.addLog(
236 'could not find a version of Visual Studio 2017 or newer to use')
237 cb(null)
238 },
239
240 // Helper - process version information
241 getVersionInfo: function getVersionInfo (info) {
242 const match = /^(\d+)\.(\d+)\..*/.exec(info.version)
243 if (!match) {
244 this.log.silly('- failed to parse version:', info.version)
245 return {}
246 }
247 this.log.silly('- version match = %j', match)
248 var ret = {
249 version: info.version,
250 versionMajor: parseInt(match[1], 10),
251 versionMinor: parseInt(match[2], 10)
252 }
253 if (ret.versionMajor === 15) {
254 ret.versionYear = 2017
255 return ret
256 }
257 if (ret.versionMajor === 16) {
258 ret.versionYear = 2019
259 return ret
260 }
261 if (ret.versionMajor === 17) {
262 ret.versionYear = 2022
263 return ret
264 }
265 this.log.silly('- unsupported version:', ret.versionMajor)
266 return {}
267 },
268
269 // Helper - process MSBuild information
270 getMSBuild: function getMSBuild (info, versionYear) {
271 const pkg = 'Microsoft.VisualStudio.VC.MSBuild.Base'
272 const msbuildPath = path.join(info.path, 'MSBuild', 'Current', 'Bin', 'MSBuild.exe')
273 if (info.packages.indexOf(pkg) !== -1) {
274 this.log.silly('- found VC.MSBuild.Base')
275 if (versionYear === 2017) {
276 return path.join(info.path, 'MSBuild', '15.0', 'Bin', 'MSBuild.exe')
277 }
278 if (versionYear === 2019) {
279 return msbuildPath
280 }
281 }
282 // visual studio 2022 don't has msbuild pkg
283 if (fs.existsSync(msbuildPath)) {
284 return msbuildPath
285 }
286 return null
287 },
288
289 // Helper - process toolset information
290 getToolset: function getToolset (info, versionYear) {
291 const pkg = 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64'
292 const express = 'Microsoft.VisualStudio.WDExpress'
293
294 if (info.packages.indexOf(pkg) !== -1) {
295 this.log.silly('- found VC.Tools.x86.x64')
296 } else if (info.packages.indexOf(express) !== -1) {
297 this.log.silly('- found Visual Studio Express (looking for toolset)')
298 } else {
299 return null
300 }
301
302 if (versionYear === 2017) {
303 return 'v141'
304 } else if (versionYear === 2019) {
305 return 'v142'
306 } else if (versionYear === 2022) {
307 return 'v143'
308 }
309 this.log.silly('- invalid versionYear:', versionYear)
310 return null
311 },
312
313 // Helper - process Windows SDK information
314 getSDK: function getSDK (info) {
315 const win8SDK = 'Microsoft.VisualStudio.Component.Windows81SDK'
316 const win10SDKPrefix = 'Microsoft.VisualStudio.Component.Windows10SDK.'
317
318 var Win10SDKVer = 0
319 info.packages.forEach((pkg) => {
320 if (!pkg.startsWith(win10SDKPrefix)) {
321 return
322 }
323 const parts = pkg.split('.')
324 if (parts.length > 5 && parts[5] !== 'Desktop') {
325 this.log.silly('- ignoring non-Desktop Win10SDK:', pkg)
326 return
327 }
328 const foundSdkVer = parseInt(parts[4], 10)
329 if (isNaN(foundSdkVer)) {
330 // Microsoft.VisualStudio.Component.Windows10SDK.IpOverUsb
331 this.log.silly('- failed to parse Win10SDK number:', pkg)
332 return
333 }
334 this.log.silly('- found Win10SDK:', foundSdkVer)
335 Win10SDKVer = Math.max(Win10SDKVer, foundSdkVer)
336 })
337
338 if (Win10SDKVer !== 0) {
339 return `10.0.${Win10SDKVer}.0`
340 } else if (info.packages.indexOf(win8SDK) !== -1) {
341 this.log.silly('- found Win8SDK')
342 return '8.1'
343 }
344 return null
345 },
346
347 // Find an installation of Visual Studio 2015 to use
348 findVisualStudio2015: function findVisualStudio2015 (cb) {
349 return this.findOldVS({
350 version: '14.0',
351 versionMajor: 14,
352 versionMinor: 0,
353 versionYear: 2015,
354 toolset: 'v140'
355 }, cb)
356 },
357
358 // Find an installation of Visual Studio 2013 to use
359 findVisualStudio2013: function findVisualStudio2013 (cb) {
360 if (this.nodeSemver.major >= 9) {
361 this.addLog(
362 'not looking for VS2013 as it is only supported up to Node.js 8')
363 return cb(null)
364 }
365 return this.findOldVS({
366 version: '12.0',
367 versionMajor: 12,
368 versionMinor: 0,
369 versionYear: 2013,
370 toolset: 'v120'
371 }, cb)
372 },
373
374 // Helper - common code for VS2013 and VS2015
375 findOldVS: function findOldVS (info, cb) {
376 const regVC7 = ['HKLM\\Software\\Microsoft\\VisualStudio\\SxS\\VC7',
377 'HKLM\\Software\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VC7']
378 const regMSBuild = 'HKLM\\Software\\Microsoft\\MSBuild\\ToolsVersions'
379
380 this.addLog(`looking for Visual Studio ${info.versionYear}`)
381 this.regSearchKeys(regVC7, info.version, [], (err, res) => {
382 if (err) {
383 this.addLog('- not found')
384 return cb(null)
385 }
386
387 const vsPath = path.resolve(res, '..')
388 this.addLog(`- found in "${vsPath}"`)
389
390 const msBuildRegOpts = process.arch === 'ia32' ? [] : ['/reg:32']
391 this.regSearchKeys([`${regMSBuild}\\${info.version}`],
392 'MSBuildToolsPath', msBuildRegOpts, (err, res) => {
393 if (err) {
394 this.addLog(
395 '- could not find MSBuild in registry for this version')
396 return cb(null)
397 }
398
399 const msBuild = path.join(res, 'MSBuild.exe')
400 this.addLog(`- MSBuild in "${msBuild}"`)
401
402 if (!this.checkConfigVersion(info.versionYear, vsPath)) {
403 return cb(null)
404 }
405
406 info.path = vsPath
407 info.msBuild = msBuild
408 info.sdk = null
409 cb(info)
410 })
411 })
412 },
413
414 // After finding a usable version of Visual Studio:
415 // - add it to validVersions to be displayed at the end if a specific
416 // version was requested and not found;
417 // - check if this is the version that was requested.
418 // - check if this matches the Visual Studio Command Prompt
419 checkConfigVersion: function checkConfigVersion (versionYear, vsPath) {
420 this.validVersions.push(versionYear)
421 this.validVersions.push(vsPath)
422
423 if (this.configVersionYear && this.configVersionYear !== versionYear) {
424 this.addLog('- msvs_version does not match this version')
425 return false
426 }
427 if (this.configPath &&
428 path.relative(this.configPath, vsPath) !== '') {
429 this.addLog('- msvs_version does not point to this installation')
430 return false
431 }
432 if (this.envVcInstallDir &&
433 path.relative(this.envVcInstallDir, vsPath) !== '') {
434 this.addLog('- does not match this Visual Studio Command Prompt')
435 return false
436 }
437
438 return true
439 }
440}
441
442module.exports = findVisualStudio
443module.exports.test = {
444 VisualStudioFinder: VisualStudioFinder,
445 findVisualStudio: findVisualStudio
446}
Note: See TracBrowser for help on using the repository browser.