/
rc.js
79 lines (65 loc) · 2.02 KB
/
rc.js
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
67
68
69
70
71
72
73
74
75
76
77
78
79
/* @flow */
import {readFileSync} from 'fs';
import * as path from 'path';
import {CONFIG_DIRECTORY} from '../constants';
const etc = '/etc';
const isWin = process.platform === 'win32';
const home = isWin ? process.env.USERPROFILE : process.env.HOME;
function getRcPaths(name: string, cwd: string): Array<string> {
const configPaths = [];
function pushConfigPath(...segments) {
configPaths.push(path.join(...segments));
if (segments[segments.length - 1] === `.${name}rc`) {
configPaths.push(path.join(...segments.slice(0, -1), `.${name}rc.yml`));
}
}
function unshiftConfigPath(...segments) {
configPaths.unshift(path.join(...segments));
if (segments[segments.length - 1] === `.${name}rc`) {
configPaths.unshift(path.join(...segments.slice(0, -1), `.${name}rc.yml`));
}
}
if (!isWin) {
pushConfigPath(etc, name, 'config');
pushConfigPath(etc, `${name}rc`);
}
if (home) {
pushConfigPath(CONFIG_DIRECTORY);
pushConfigPath(home, '.config', name, 'config');
pushConfigPath(home, '.config', name);
pushConfigPath(home, `.${name}`, 'config');
pushConfigPath(home, `.${name}rc`);
}
// add .yarnrc locations relative to the cwd
while (true) {
unshiftConfigPath(cwd, `.${name}rc`);
const upperCwd = path.dirname(cwd);
if (upperCwd === cwd) {
// we've reached the root
break;
} else {
// continue since there's still more directories to search
cwd = upperCwd;
}
}
const envVariable = `${name}_config`.toUpperCase();
if (process.env[envVariable]) {
pushConfigPath(process.env[envVariable]);
}
return configPaths;
}
function parseRcPaths(paths: Array<string>, parser: Function): Object {
return Object.assign(
{},
...paths.map(path => {
try {
return parser(readFileSync(path).toString(), path);
} catch (error) {
return {};
}
}),
);
}
export function findRc(name: string, cwd: string, parser: Function): Object {
return parseRcPaths(getRcPaths(name, cwd), parser);
}