bin.js 2.0 KB

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