bin.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #!/usr/bin/env node
  2. var proc = require('child_process')
  3. var os = require('os')
  4. var path = require('path')
  5. if (!buildFromSource()) {
  6. proc.exec('node-gyp-build-optional-packages-test', function (err, stdout, stderr) {
  7. if (err) {
  8. console.error(stderr)
  9. console.error('The failure above indicates the primary issue with the native builds which are included for all' +
  10. ' major platforms. Will now attempt to build the package locally in case this can be resolved by' +
  11. ' re-compiling.')
  12. preinstall()
  13. }
  14. })
  15. } else {
  16. preinstall()
  17. }
  18. function build () {
  19. var win32 = os.platform() === 'win32'
  20. var args = [win32 ? 'node-gyp.cmd' : 'node-gyp', 'rebuild']
  21. try {
  22. var pkg = require('node-gyp/package.json')
  23. args = [
  24. process.execPath,
  25. path.join(require.resolve('node-gyp/package.json'), '..', typeof pkg.bin === 'string' ? pkg.bin : pkg.bin['node-gyp']),
  26. 'rebuild'
  27. ]
  28. } catch (_) {}
  29. proc.spawn(args[0], args.slice(1), { stdio: 'inherit', shell: win32, windowsHide: true }).on('exit', function (code) {
  30. if (code || !process.argv[3]) process.exit(code)
  31. exec(process.argv[3]).on('exit', function (code) {
  32. process.exit(code)
  33. })
  34. })
  35. }
  36. function preinstall () {
  37. if (!process.argv[2]) return build()
  38. exec(process.argv[2]).on('exit', function (code) {
  39. if (code) process.exit(code)
  40. build()
  41. })
  42. }
  43. function exec (cmd) {
  44. if (process.platform !== 'win32') {
  45. var shell = os.platform() === 'android' ? 'sh' : true
  46. return proc.spawn(cmd, [], {
  47. shell,
  48. stdio: 'inherit'
  49. })
  50. }
  51. return proc.spawn(cmd, [], {
  52. windowsVerbatimArguments: true,
  53. stdio: 'inherit',
  54. shell: true,
  55. windowsHide: true
  56. })
  57. }
  58. function buildFromSource () {
  59. return hasFlag('--build-from-source') || process.env.npm_config_build_from_source === 'true'
  60. }
  61. // TODO (next major): remove in favor of env.npm_config_* which works since npm
  62. // 0.1.8 while npm_config_argv will stop working in npm 7. See npm/rfcs#90
  63. function hasFlag (flag) {
  64. if (!process.env.npm_config_argv) return false
  65. try {
  66. return JSON.parse(process.env.npm_config_argv).original.indexOf(flag) !== -1
  67. } catch (_) {
  68. return false
  69. }
  70. }