-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
94 lines (74 loc) · 2.52 KB
/
utils.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
'use strict';
const path = require('path'),
fs = require('fs'),
_ = require('lodash')
;
const utils = {};
module.exports = utils;
utils.isNodeEnvSet = isNodeEnvSet;
utils.getEnv = _.memoize(getEnv);
utils.basename = basename;
utils.getEnvPathFrom = getEnvPathFrom;
utils.getProductionPathFrom = getProductionPathFrom;
utils.resolve = _.memoize(resolve);
function isNodeEnvSet () {
return !!(process.env.hasOwnProperty('NODE_ENV') && process.env.NODE_ENV.replace(/\s/g, '').length);
}
function basename (fromFilePath) {
return `config_${utils.getEnv(fromFilePath)}.yml`;
}
function getEnv (fromFilePath) {
if (!isNodeEnvSet() || _isFileInSubModule(fromFilePath)) return 'production';
return process.env.NODE_ENV;
}
function _isFileInSubModule (fromFilePath) {
const configDirPath = utils.resolve(fromFilePath);
const parentModulePath = path.resolve(configDirPath, '../../');
return parentModulePath.split(path.sep).includes('node_modules');
}
function getProductionPathFrom (fromFilePath) {
return path.join(utils.resolve(fromFilePath), 'config_production.yml');
}
function getEnvPathFrom (fromFilePath) {
const configDirPath = utils.resolve(fromFilePath);
return path.join(configDirPath, basename(fromFilePath));
}
/**
* Resolve config directory path
* @param fromFilePath
* @returns String path
*/
function resolve (fromFilePath) {
const fileStat = fs.statSync(fromFilePath);
fromFilePath = fileStat.isFile() ? path.dirname(fromFilePath) : fromFilePath;
const packageDir = _resolve(fromFilePath),
configDir = path.join(packageDir, 'config')
;
try {
fs.readdirSync(configDir);
} catch (err) {
if (err.code === 'ENOENT') throw configDirNotFoundException(fromFilePath);
throw err;
}
return configDir;
// package.json resolver
function _resolve (dirPath) {
_resolve.i = _resolve.i || 0;
if (fs.existsSync(path.join(dirPath, 'package.json'))) {
return dirPath;
}
if (dirPath === '/' || _resolve.i === 16) throw packageNotFoundException(fromFilePath);
++_resolve.i;
return _resolve(path.dirname(dirPath));
}
}
function configDirNotFoundException (filename) {
let err = new Error(`No config dir for module ${filename}`);
err.name = 'configDirNotFoundException';
return err;
}
function packageNotFoundException (filename) {
let err = new Error(`No package path for module ${filename}`);
err.name = 'packageNotFoundException';
return err;
}