-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
66 lines (50 loc) · 1.77 KB
/
index.js
File metadata and controls
66 lines (50 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const path = require('path');
const os = require('os');
const fs = require('fs');
const ini = require('ini');
const util = require('util');
const readFile = util.promisify(fs.readFile);
module.exports = async (options) => {
options = Object.assign({
name: null,
directory: null,
globalConfig: '/etc/npmrc',
userConfig: path.join(os.homedir(), '.npmrc')
}, options || {});
const config = {};
if (!options.directory && !options.name) {
throw new Error("A directory or a package name must be given");
}
if (options.directory) {
const packageInfo = JSON.parse(await readFile(path.join(options.directory, 'package.json')));
options.name = options.name || packageInfo.name;
const packageConfig = await readINIConfig(path.join(options.directory, 'npmrc'), options.name);
Object.assign(config, packageInfo.config);
Object.assign(config, packageConfig);
}
if (options.globalConfig) {
Object.assign(config, await readINIConfig(options.globalConfig, options.name));
}
if (options.userConfig) {
Object.assign(config, await readINIConfig(options.userConfig, options.name));
}
return config;
};
async function readINIConfig(path, packageName) {
try {
const contents = await readFile(path);
const config = ini.parse(contents.toString('utf8'));
const result = {};
for (const key of Object.keys(config)) {
if (key.startsWith(packageName + ':')) {
result[key.slice(packageName.length + 1)] = config[key];
}
};
return result;
} catch (error) {
if (error.code === 'ENOENT') {
return {};
}
throw error;
}
}