preinstall.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // This file is a bit weird, so let me explain with some context: we're working
  2. // to implement a tool called "Corepack" in Node. This tool will allow us to
  3. // provide a Yarn shim to everyone using Node, meaning that they won't need to
  4. // run `npm install -g yarn`.
  5. //
  6. // Still, we don't want to break the experience of people that already use `npm
  7. // install -g yarn`! And one annoying thing with npm is that they install their
  8. // binaries directly inside the Node bin/ folder. And Because of this, they
  9. // refuse to overwrite binaries when they detect they don't belong to npm. Which
  10. // means that, since the "yarn" Corepack symlink belongs to Corepack and not npm,
  11. // running `npm install -g yarn` would crash by refusing to override the binary :/
  12. //
  13. // And thus we have this preinstall script, which checks whether Yarn is being
  14. // installed as a global binary, and remove the existing symlink if it detects
  15. // it belongs to Corepack. Since preinstall scripts run, in npm, before the global
  16. // symlink is created, we bypass this way the ownership check.
  17. //
  18. // More info:
  19. // https://github.com/arcanis/pmm/issues/6
  20. if (process.env.npm_config_global) {
  21. var cp = require('child_process');
  22. var fs = require('fs');
  23. var path = require('path');
  24. try {
  25. var targetPath = cp.execFileSync(process.execPath, [process.env.npm_execpath, 'bin', '-g'], {
  26. encoding: 'utf8',
  27. stdio: ['ignore', undefined, 'ignore'],
  28. }).replace(/\n/g, '');
  29. var manifest = require('./package.json');
  30. var binNames = typeof manifest.bin === 'string'
  31. ? [manifest.name.replace(/^@[^\/]+\//, '')]
  32. : typeof manifest.bin === 'object' && manifest.bin !== null
  33. ? Object.keys(manifest.bin)
  34. : [];
  35. binNames.forEach(function (binName) {
  36. var binPath = path.join(targetPath, binName);
  37. var binTarget;
  38. try {
  39. binTarget = fs.readlinkSync(binPath);
  40. } catch (err) {
  41. return;
  42. }
  43. if (binTarget.startsWith('../lib/node_modules/corepack/')) {
  44. try {
  45. fs.unlinkSync(binPath);
  46. } catch (err) {
  47. return;
  48. }
  49. }
  50. });
  51. } catch (err) {
  52. // ignore errors
  53. }
  54. }