find-visualstudio.js 14 KB

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