find-visualstudio.js 14 KB

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