configure.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. 'use strict'
  2. const fs = require('graceful-fs')
  3. const path = require('path')
  4. const log = require('npmlog')
  5. const os = require('os')
  6. const processRelease = require('./process-release')
  7. const win = process.platform === 'win32'
  8. const findNodeDirectory = require('./find-node-directory')
  9. const msgFormat = require('util').format
  10. var findPython = require('./find-python')
  11. if (win) {
  12. var findVisualStudio = require('./find-visualstudio')
  13. }
  14. function configure (gyp, argv, callback) {
  15. var python
  16. var buildDir = path.resolve('build')
  17. var configNames = ['config.gypi', 'common.gypi']
  18. var configs = []
  19. var nodeDir
  20. var release = processRelease(argv, gyp, process.version, process.release)
  21. findPython(gyp.opts.python, function (err, found) {
  22. if (err) {
  23. callback(err)
  24. } else {
  25. python = found
  26. getNodeDir()
  27. }
  28. })
  29. function getNodeDir () {
  30. // 'python' should be set by now
  31. process.env.PYTHON = python
  32. if (gyp.opts.nodedir) {
  33. // --nodedir was specified. use that for the dev files
  34. nodeDir = gyp.opts.nodedir.replace(/^~/, os.homedir())
  35. log.verbose('get node dir', 'compiling against specified --nodedir dev files: %s', nodeDir)
  36. createBuildDir()
  37. } else {
  38. // if no --nodedir specified, ensure node dependencies are installed
  39. if ('v' + release.version !== process.version) {
  40. // if --target was given, then determine a target version to compile for
  41. log.verbose('get node dir', 'compiling against --target node version: %s', release.version)
  42. } else {
  43. // if no --target was specified then use the current host node version
  44. log.verbose('get node dir', 'no --target version specified, falling back to host node version: %s', release.version)
  45. }
  46. if (!release.semver) {
  47. // could not parse the version string with semver
  48. return callback(new Error('Invalid version number: ' + release.version))
  49. }
  50. // If the tarball option is set, always remove and reinstall the headers
  51. // into devdir. Otherwise only install if they're not already there.
  52. gyp.opts.ensure = !gyp.opts.tarball
  53. gyp.commands.install([release.version], function (err) {
  54. if (err) {
  55. return callback(err)
  56. }
  57. log.verbose('get node dir', 'target node version installed:', release.versionDir)
  58. nodeDir = path.resolve(gyp.devDir, release.versionDir)
  59. createBuildDir()
  60. })
  61. }
  62. }
  63. function createBuildDir () {
  64. log.verbose('build dir', 'attempting to create "build" dir: %s', buildDir)
  65. fs.mkdir(buildDir, { recursive: true }, function (err, isNew) {
  66. if (err) {
  67. return callback(err)
  68. }
  69. log.verbose('build dir', '"build" dir needed to be created?', isNew)
  70. if (win) {
  71. findVisualStudio(release.semver, gyp.opts.msvs_version,
  72. createConfigFile)
  73. } else {
  74. createConfigFile()
  75. }
  76. })
  77. }
  78. function createConfigFile (err, vsInfo) {
  79. if (err) {
  80. return callback(err)
  81. }
  82. var configFilename = 'config.gypi'
  83. var configPath = path.resolve(buildDir, configFilename)
  84. log.verbose('build/' + configFilename, 'creating config file')
  85. var config = process.config || {}
  86. var defaults = config.target_defaults
  87. var variables = config.variables
  88. // default "config.variables"
  89. if (!variables) {
  90. variables = config.variables = {}
  91. }
  92. // default "config.defaults"
  93. if (!defaults) {
  94. defaults = config.target_defaults = {}
  95. }
  96. // don't inherit the "defaults" from node's `process.config` object.
  97. // doing so could cause problems in cases where the `node` executable was
  98. // compiled on a different machine (with different lib/include paths) than
  99. // the machine where the addon is being built to
  100. defaults.cflags = []
  101. defaults.defines = []
  102. defaults.include_dirs = []
  103. defaults.libraries = []
  104. // set the default_configuration prop
  105. if ('debug' in gyp.opts) {
  106. defaults.default_configuration = gyp.opts.debug ? 'Debug' : 'Release'
  107. }
  108. if (!defaults.default_configuration) {
  109. defaults.default_configuration = 'Release'
  110. }
  111. // set the target_arch variable
  112. variables.target_arch = gyp.opts.arch || process.arch || 'ia32'
  113. if (variables.target_arch === 'arm64') {
  114. defaults.msvs_configuration_platform = 'ARM64'
  115. defaults.xcode_configuration_platform = 'arm64'
  116. }
  117. // set the node development directory
  118. variables.nodedir = nodeDir
  119. // disable -T "thin" static archives by default
  120. variables.standalone_static_library = gyp.opts.thin ? 0 : 1
  121. if (win) {
  122. process.env.GYP_MSVS_VERSION = Math.min(vsInfo.versionYear, 2015)
  123. process.env.GYP_MSVS_OVERRIDE_PATH = vsInfo.path
  124. defaults.msbuild_toolset = vsInfo.toolset
  125. if (vsInfo.sdk) {
  126. defaults.msvs_windows_target_platform_version = vsInfo.sdk
  127. }
  128. if (variables.target_arch === 'arm64') {
  129. if (vsInfo.versionMajor > 15 ||
  130. (vsInfo.versionMajor === 15 && vsInfo.versionMajor >= 9)) {
  131. defaults.msvs_enable_marmasm = 1
  132. } else {
  133. log.warn('Compiling ARM64 assembly is only available in\n' +
  134. 'Visual Studio 2017 version 15.9 and above')
  135. }
  136. }
  137. variables.msbuild_path = vsInfo.msBuild
  138. }
  139. // loop through the rest of the opts and add the unknown ones as variables.
  140. // this allows for module-specific configure flags like:
  141. //
  142. // $ node-gyp configure --shared-libxml2
  143. Object.keys(gyp.opts).forEach(function (opt) {
  144. if (opt === 'argv') {
  145. return
  146. }
  147. if (opt in gyp.configDefs) {
  148. return
  149. }
  150. variables[opt.replace(/-/g, '_')] = gyp.opts[opt]
  151. })
  152. // ensures that any boolean values from `process.config` get stringified
  153. function boolsToString (k, v) {
  154. if (typeof v === 'boolean') {
  155. return String(v)
  156. }
  157. return v
  158. }
  159. log.silly('build/' + configFilename, config)
  160. // now write out the config.gypi file to the build/ dir
  161. var prefix = '# Do not edit. File was generated by node-gyp\'s "configure" step'
  162. var json = JSON.stringify(config, boolsToString, 2)
  163. log.verbose('build/' + configFilename, 'writing out config file: %s', configPath)
  164. configs.push(configPath)
  165. fs.writeFile(configPath, [prefix, json, ''].join('\n'), findConfigs)
  166. }
  167. function findConfigs (err) {
  168. if (err) {
  169. return callback(err)
  170. }
  171. var name = configNames.shift()
  172. if (!name) {
  173. return runGyp()
  174. }
  175. var fullPath = path.resolve(name)
  176. log.verbose(name, 'checking for gypi file: %s', fullPath)
  177. fs.stat(fullPath, function (err) {
  178. if (err) {
  179. if (err.code === 'ENOENT') {
  180. findConfigs() // check next gypi filename
  181. } else {
  182. callback(err)
  183. }
  184. } else {
  185. log.verbose(name, 'found gypi file')
  186. configs.push(fullPath)
  187. findConfigs()
  188. }
  189. })
  190. }
  191. function runGyp (err) {
  192. if (err) {
  193. return callback(err)
  194. }
  195. if (!~argv.indexOf('-f') && !~argv.indexOf('--format')) {
  196. if (win) {
  197. log.verbose('gyp', 'gyp format was not specified; forcing "msvs"')
  198. // force the 'make' target for non-Windows
  199. argv.push('-f', 'msvs')
  200. } else {
  201. log.verbose('gyp', 'gyp format was not specified; forcing "make"')
  202. // force the 'make' target for non-Windows
  203. argv.push('-f', 'make')
  204. }
  205. }
  206. // include all the ".gypi" files that were found
  207. configs.forEach(function (config) {
  208. argv.push('-I', config)
  209. })
  210. // For AIX and z/OS we need to set up the path to the exports file
  211. // which contains the symbols needed for linking.
  212. var nodeExpFile
  213. if (process.platform === 'aix' || process.platform === 'os390') {
  214. var ext = process.platform === 'aix' ? 'exp' : 'x'
  215. var nodeRootDir = findNodeDirectory()
  216. var candidates
  217. if (process.platform === 'aix') {
  218. candidates = [
  219. 'include/node/node',
  220. 'out/Release/node',
  221. 'out/Debug/node',
  222. 'node'
  223. ].map(function (file) {
  224. return file + '.' + ext
  225. })
  226. } else {
  227. candidates = [
  228. 'out/Release/obj.target/libnode',
  229. 'out/Debug/obj.target/libnode',
  230. 'lib/libnode'
  231. ].map(function (file) {
  232. return file + '.' + ext
  233. })
  234. }
  235. var logprefix = 'find exports file'
  236. nodeExpFile = findAccessibleSync(logprefix, nodeRootDir, candidates)
  237. if (nodeExpFile !== undefined) {
  238. log.verbose(logprefix, 'Found exports file: %s', nodeExpFile)
  239. } else {
  240. var msg = msgFormat('Could not find node.%s file in %s', ext, nodeRootDir)
  241. log.error(logprefix, 'Could not find exports file')
  242. return callback(new Error(msg))
  243. }
  244. }
  245. // this logic ported from the old `gyp_addon` python file
  246. var gypScript = path.resolve(__dirname, '..', 'gyp', 'gyp_main.py')
  247. var addonGypi = path.resolve(__dirname, '..', 'addon.gypi')
  248. var commonGypi = path.resolve(nodeDir, 'include/node/common.gypi')
  249. fs.stat(commonGypi, function (err) {
  250. if (err) {
  251. commonGypi = path.resolve(nodeDir, 'common.gypi')
  252. }
  253. var outputDir = 'build'
  254. if (win) {
  255. // Windows expects an absolute path
  256. outputDir = buildDir
  257. }
  258. var nodeGypDir = path.resolve(__dirname, '..')
  259. var nodeLibFile = path.join(nodeDir,
  260. !gyp.opts.nodedir ? '<(target_arch)' : '$(Configuration)',
  261. release.name + '.lib')
  262. argv.push('-I', addonGypi)
  263. argv.push('-I', commonGypi)
  264. argv.push('-Dlibrary=shared_library')
  265. argv.push('-Dvisibility=default')
  266. argv.push('-Dnode_root_dir=' + nodeDir)
  267. if (process.platform === 'aix' || process.platform === 'os390') {
  268. argv.push('-Dnode_exp_file=' + nodeExpFile)
  269. }
  270. argv.push('-Dnode_gyp_dir=' + nodeGypDir)
  271. // Do this to keep Cygwin environments happy, else the unescaped '\' gets eaten up,
  272. // resulting in bad paths, Ex c:parentFolderfolderanotherFolder instead of c:\parentFolder\folder\anotherFolder
  273. if (win) {
  274. nodeLibFile = nodeLibFile.replace(/\\/g, '\\\\')
  275. }
  276. argv.push('-Dnode_lib_file=' + nodeLibFile)
  277. argv.push('-Dmodule_root_dir=' + process.cwd())
  278. argv.push('-Dnode_engine=' +
  279. (gyp.opts.node_engine || process.jsEngine || 'v8'))
  280. argv.push('--depth=.')
  281. argv.push('--no-parallel')
  282. // tell gyp to write the Makefile/Solution files into output_dir
  283. argv.push('--generator-output', outputDir)
  284. // tell make to write its output into the same dir
  285. argv.push('-Goutput_dir=.')
  286. // enforce use of the "binding.gyp" file
  287. argv.unshift('binding.gyp')
  288. // execute `gyp` from the current target nodedir
  289. argv.unshift(gypScript)
  290. // make sure python uses files that came with this particular node package
  291. var pypath = [path.join(__dirname, '..', 'gyp', 'pylib')]
  292. if (process.env.PYTHONPATH) {
  293. pypath.push(process.env.PYTHONPATH)
  294. }
  295. process.env.PYTHONPATH = pypath.join(win ? ';' : ':')
  296. var cp = gyp.spawn(python, argv)
  297. cp.on('exit', onCpExit)
  298. })
  299. }
  300. function onCpExit (code) {
  301. if (code !== 0) {
  302. callback(new Error('`gyp` failed with exit code: ' + code))
  303. } else {
  304. // we're done
  305. callback()
  306. }
  307. }
  308. }
  309. /**
  310. * Returns the first file or directory from an array of candidates that is
  311. * readable by the current user, or undefined if none of the candidates are
  312. * readable.
  313. */
  314. function findAccessibleSync (logprefix, dir, candidates) {
  315. for (var next = 0; next < candidates.length; next++) {
  316. var candidate = path.resolve(dir, candidates[next])
  317. try {
  318. var fd = fs.openSync(candidate, 'r')
  319. } catch (e) {
  320. // this candidate was not found or not readable, do nothing
  321. log.silly(logprefix, 'Could not open %s: %s', candidate, e.message)
  322. continue
  323. }
  324. fs.closeSync(fd)
  325. log.silly(logprefix, 'Found readable %s', candidate)
  326. return candidate
  327. }
  328. return undefined
  329. }
  330. module.exports = configure
  331. module.exports.test = {
  332. findAccessibleSync: findAccessibleSync
  333. }
  334. module.exports.usage = 'Generates ' + (win ? 'MSVC project files' : 'a Makefile') + ' for the current module'