Skip to content

Commit 1d74209

Browse files
committed
Fix handling of tilde in npm prefix path
Fixes #21
1 parent dd04056 commit 1d74209

2 files changed

Lines changed: 23 additions & 1 deletion

File tree

index.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import ini from 'ini';
66

77
const isWindows = process.platform === 'win32';
88

9+
const untildify = pathWithTilde => pathWithTilde && pathWithTilde.startsWith('~') ? path.join(os.homedir(), pathWithTilde.slice(1)) : pathWithTilde;
10+
911
const readRc = filePath => {
1012
try {
1113
return ini.parse(fs.readFileSync(filePath, 'utf8')).prefix;
@@ -69,7 +71,7 @@ const getNpmPrefix = () => {
6971
return getDefaultNpmPrefix();
7072
};
7173

72-
const npmPrefix = path.resolve(getNpmPrefix());
74+
const npmPrefix = path.resolve(untildify(getNpmPrefix()));
7375

7476
const getYarnHomeDirectory = () => {
7577
if (process.getuid?.() === 0 && !process.env.FAKEROOTKEY) {

test.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,26 @@ test.serial('yarn with PREFIX', async t => {
6262
delete process.env.PREFIX;
6363
});
6464

65+
test.serial('npm.prefix expands tilde in prefix', async t => {
66+
const savedKeys = Object.keys(process.env).filter(name => name.toLowerCase() === 'npm_config_prefix');
67+
const savedValues = Object.fromEntries(savedKeys.map(key => [key, process.env[key]]));
68+
69+
for (const key of savedKeys) {
70+
delete process.env[key];
71+
}
72+
73+
// eslint-disable-next-line camelcase
74+
process.env.npm_config_prefix = '~/.npm-global';
75+
const {default: globalDirectory} = await importFresh('./index.js');
76+
t.is(globalDirectory.npm.prefix, path.join(os.homedir(), '.npm-global'));
77+
t.false(globalDirectory.npm.prefix.includes('~'));
78+
delete process.env.npm_config_prefix;
79+
80+
for (const [key, value] of Object.entries(savedValues)) {
81+
process.env[key] = value;
82+
}
83+
});
84+
6585
test.serial('reload package and get npm.prefix with env', async t => {
6686
const savedKeys = Object.keys(process.env).filter(name => name.toLowerCase() === 'npm_config_prefix');
6787
const savedValues = Object.fromEntries(savedKeys.map(key => [key, process.env[key]]));

0 commit comments

Comments
 (0)