bin.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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-test', function (err, stdout, stderr) {
  7. if (err) {
  8. if (verbose()) console.error(stderr)
  9. preinstall()
  10. }
  11. })
  12. } else {
  13. preinstall()
  14. }
  15. function build () {
  16. var win32 = os.platform() === 'win32'
  17. var shell = win32
  18. var args = [win32 ? 'node-gyp.cmd' : 'node-gyp', 'rebuild']
  19. try {
  20. var pkg = require('node-gyp/package.json')
  21. args = [
  22. process.execPath,
  23. path.join(require.resolve('node-gyp/package.json'), '..', typeof pkg.bin === 'string' ? pkg.bin : pkg.bin['node-gyp']),
  24. 'rebuild'
  25. ]
  26. shell = false
  27. } catch (_) {}
  28. proc.spawn(args[0], args.slice(1), { stdio: 'inherit', shell, windowsHide: true }).on('exit', function (code) {
  29. if (code || !process.argv[3]) process.exit(code)
  30. exec(process.argv[3]).on('exit', function (code) {
  31. process.exit(code)
  32. })
  33. })
  34. }
  35. function preinstall () {
  36. if (!process.argv[2]) return build()
  37. exec(process.argv[2]).on('exit', function (code) {
  38. if (code) process.exit(code)
  39. build()
  40. })
  41. }
  42. function exec (cmd) {
  43. if (process.platform !== 'win32') {
  44. var shell = os.platform() === 'android' ? 'sh' : true
  45. return proc.spawn(cmd, [], {
  46. shell,
  47. stdio: 'inherit'
  48. })
  49. }
  50. return proc.spawn(cmd, [], {
  51. windowsVerbatimArguments: true,
  52. stdio: 'inherit',
  53. shell: true,
  54. windowsHide: true
  55. })
  56. }
  57. function buildFromSource () {
  58. return hasFlag('--build-from-source') || process.env.npm_config_build_from_source === 'true'
  59. }
  60. function verbose () {
  61. return hasFlag('--verbose') || process.env.npm_config_loglevel === 'verbose'
  62. }
  63. // TODO (next major): remove in favor of env.npm_config_* which works since npm
  64. // 0.1.8 while npm_config_argv will stop working in npm 7. See npm/rfcs#90
  65. function hasFlag (flag) {
  66. if (!process.env.npm_config_argv) return false
  67. try {
  68. return JSON.parse(process.env.npm_config_argv).original.indexOf(flag) !== -1
  69. } catch (_) {
  70. return false
  71. }
  72. }