codekingpro/portable-devtools
115k
1// This file is a bit weird, so let me explain with some context: we're working2// to implement a tool called "Corepack" in Node. This tool will allow us to3// provide a Yarn shim to everyone using Node, meaning that they won't need to4// run `npm install -g yarn`.5//6// Still, we don't want to break the experience of people that already use `npm7// install -g yarn`! And one annoying thing with npm is that they install their8// binaries directly inside the Node bin/ folder. And Because of this, they9// refuse to overwrite binaries when they detect they don't belong to npm. Which10// 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 being14// installed as a global binary, and remove the existing symlink if it detects15// it belongs to Corepack. Since preinstall scripts run, in npm, before the global16// symlink is created, we bypass this way the ownership check.17//18// More info:19// https://github.com/arcanis/pmm/issues/620 21if (process.env.npm_config_global) {22 var cp = require('child_process');23 var fs = require('fs');24 var path = require('path');25 26 try {27 var targetPath = cp.execFileSync(process.execPath, [process.env.npm_execpath, 'bin', '-g'], {28 encoding: 'utf8',29 stdio: ['ignore', undefined, 'ignore'],30 }).replace(/\n/g, '');31 32 var manifest = require('./package.json');33 var binNames = typeof manifest.bin === 'string'34 ? [manifest.name.replace(/^@[^\/]+\//, '')]35 : typeof manifest.bin === 'object' && manifest.bin !== null36 ? Object.keys(manifest.bin)37 : [];38 39 binNames.forEach(function (binName) {40 var binPath = path.join(targetPath, binName);41 42 var binTarget;43 try {44 binTarget = fs.readlinkSync(binPath);45 } catch (err) {46 return;47 }48 49 if (binTarget.startsWith('../lib/node_modules/corepack/')) {50 try {51 fs.unlinkSync(binPath);52 } catch (err) {53 return;54 }55 }56 });57 } catch (err) {58 // ignore errors59 }60}61 