-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
80 lines (74 loc) · 1.89 KB
/
index.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
#!/usr/bin/env node
const spawn = require('cross-spawn');
const { readdir } = require('fs');
const { join, resolve, sep } = require('path');
parseArgs()
.then(state => requireFiles(state))
.then(state => process.exitCode = spawnNextCommand(state).status)
;
async function parseArgs() {
const args = process.argv.slice(2);
const barrier = args.indexOf('--');
if (-1 === barrier) {
const modules = await listDirectory('./node_modules/');
for (const parentDirectory of modules.filter(m => m.indexOf(`${sep}@`) >= 0)) {
modules.push(...await listDirectory(parentDirectory));
}
const filesToRequire = [];
for (const module of modules) {
const packageJSON = safeRequire(resolve(module, 'package.json'));
if (packageJSON && packageJSON.dynenv) {
filesToRequire.push(resolve(module, packageJSON.dynenv));
}
}
return {
filesToRequire,
nextCommand: args[0],
nextCommandArgs: args.slice(1),
};
}
else {
return {
filesToRequire: args.slice(0, barrier),
nextCommand: args[barrier + 1],
nextCommandArgs: args.slice(barrier + 2),
};
}
}
function listDirectory(ref) {
return new Promise((resolve, reject) => {
readdir(ref, (err, results) => err
? reject(err)
: resolve(results.map(result => join(ref, result))),
);
});
}
async function requireFiles(state) {
state.env = Object.assign({}, process.env);
for (const fileToRequire of state.filesToRequire) {
const exports = safeRequire(fileToRequire.startsWith('./')
? resolve(fileToRequire)
: fileToRequire);
const newEnv = typeof exports === 'function'
? await exports()
: exports;
if (newEnv) {
Object.assign(state.env, newEnv);
}
}
return state;
}
function safeRequire(ref) {
try {
return require(ref);
}
catch (err) {
return null;
}
}
function spawnNextCommand({ nextCommand, nextCommandArgs, env }) {
return spawn.sync(nextCommand, nextCommandArgs, {
stdio: 'inherit',
env,
});
}