-
Notifications
You must be signed in to change notification settings - Fork 996
/
utils.cjs
108 lines (96 loc) · 2.12 KB
/
utils.cjs
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
'use strict';
const Hash = require('hashish');
const {format} = require('util');
// capture terminal output, so that we might
// assert against it.
exports.checkOutput = function checkOutput(f, argv, cb) {
let exit = false;
let exitCode = 0;
const _exit = process.exit;
const _emit = process.emit;
const _emitWarning = process.emitWarning;
const _env = process.env;
const _argv = process.argv;
const _error = console.error;
const _log = console.log;
const _warn = console.warn;
process.exit = code => {
exit = true;
exitCode = code;
};
process.env = Hash.merge(process.env, {_: 'node'});
process.argv = argv || ['./usage'];
const errors = [];
const logs = [];
const warnings = [];
const emittedWarnings = [];
console.error = (...msg) => {
errors.push(format(...msg));
};
console.log = (...msg) => {
logs.push(format(...msg));
};
console.warn = (...msg) => {
warnings.push(format(...msg));
};
process.emitWarning = warning => {
emittedWarnings.push(warning);
};
let result;
if (typeof cb === 'function') {
process.exit = () => {
exit = true;
cb(null, done());
};
process.emit = function emit(ev, value) {
if (ev === 'uncaughtException') {
cb(value, done());
return true;
}
return _emit.apply(this, arguments);
};
f();
} else {
try {
result = f();
if (typeof result.then === 'function') {
return result
.then(() => {
reset();
return done();
})
.catch(() => {
reset();
return done();
});
} else {
reset();
}
} catch (_err) {
reset();
}
return done();
}
function reset() {
process.exit = _exit;
process.emit = _emit;
process.env = _env;
process.argv = _argv;
process.emitWarning = _emitWarning;
console.error = _error;
console.log = _log;
console.warn = _warn;
}
function done() {
reset();
return {
errors,
logs,
warnings,
emittedWarnings,
exit,
exitCode,
result,
};
}
};