| Leo Repp | 58b9f11 | 2021-11-22 11:57:47 +0100 | [diff] [blame^] | 1 | /*! |
| 2 | * global-prefix <https://github.com/jonschlinkert/global-prefix> |
| 3 | * |
| 4 | * Copyright (c) 2015-2017 Jon Schlinkert. |
| 5 | * Licensed under the MIT license. |
| 6 | */ |
| 7 | |
| 8 | 'use strict'; |
| 9 | |
| 10 | var fs = require('fs'); |
| 11 | var path = require('path'); |
| 12 | var expand = require('expand-tilde'); |
| 13 | var homedir = require('homedir-polyfill'); |
| 14 | var ini = require('ini'); |
| 15 | var prefix; |
| 16 | |
| 17 | function getPrefix() { |
| 18 | if (process.env.PREFIX) { |
| 19 | prefix = process.env.PREFIX; |
| 20 | } else { |
| 21 | // Start by checking if the global prefix is set by the user |
| 22 | var home = homedir(); |
| 23 | if (home) { |
| 24 | // homedir() returns undefined if $HOME not set; path.resolve requires strings |
| 25 | var userConfig = path.resolve(home, '.npmrc'); |
| 26 | prefix = tryConfigPath(userConfig); |
| 27 | } |
| 28 | |
| 29 | if (!prefix) { |
| 30 | // Otherwise find the path of npm |
| 31 | var npm = tryNpmPath(); |
| 32 | if (npm) { |
| 33 | // Check the built-in npm config file |
| 34 | var builtinConfig = path.resolve(npm, '..', '..', 'npmrc'); |
| 35 | prefix = tryConfigPath(builtinConfig); |
| 36 | |
| 37 | if (prefix) { |
| 38 | // Now the global npm config can also be checked. |
| 39 | var globalConfig = path.resolve(prefix, 'etc', 'npmrc'); |
| 40 | prefix = tryConfigPath(globalConfig) || prefix; |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | if (!prefix) fallback(); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | if (prefix) { |
| 49 | return expand(prefix); |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | function fallback() { |
| 54 | var isWindows = require('is-windows'); |
| 55 | if (isWindows()) { |
| 56 | // c:\node\node.exe --> prefix=c:\node\ |
| 57 | prefix = process.env.APPDATA |
| 58 | ? path.join(process.env.APPDATA, 'npm') |
| 59 | : path.dirname(process.execPath); |
| 60 | } else { |
| 61 | // /usr/local/bin/node --> prefix=/usr/local |
| 62 | prefix = path.dirname(path.dirname(process.execPath)); |
| 63 | |
| 64 | // destdir only is respected on Unix |
| 65 | if (process.env.DESTDIR) { |
| 66 | prefix = path.join(process.env.DESTDIR, prefix); |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | function tryNpmPath() { |
| 72 | try { |
| 73 | return fs.realpathSync(require('which').sync('npm')); |
| 74 | } catch (err) {} |
| 75 | return null; |
| 76 | } |
| 77 | |
| 78 | function tryConfigPath(configPath) { |
| 79 | try { |
| 80 | var data = fs.readFileSync(configPath, 'utf-8'); |
| 81 | var config = ini.parse(data); |
| 82 | if (config.prefix) return config.prefix; |
| 83 | } catch (err) {} |
| 84 | return null; |
| 85 | } |
| 86 | |
| 87 | /** |
| 88 | * Expose `prefix` |
| 89 | */ |
| 90 | |
| 91 | Object.defineProperty(module, 'exports', { |
| 92 | enumerable: true, |
| 93 | get: function() { |
| 94 | return prefix || (prefix = getPrefix()); |
| 95 | } |
| 96 | }); |