Skip to content

Commit 74ed0c2

Browse files
committed
feat: Allow use of error object inside the notifier message/title
Related to micromata#7
1 parent a33fd60 commit 74ed0c2

File tree

1 file changed

+54
-1
lines changed

1 file changed

+54
-1
lines changed

lib/error-notifier.js

+54-1
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,65 @@ const notifier = require('node-notifier');
33

44
const notifierOptions = require('./notifier-options');
55

6+
const errorLiteral = 'error';
7+
8+
function errorLiteralPosition(str) {
9+
let index = str.indexOf(`\${${errorLiteral}`);
10+
let length = 0;
11+
12+
if (index > -1) {
13+
index += 2;
14+
15+
let open = 1;
16+
17+
while (length < str.length - index) {
18+
const char = str.charAt(index + length);
19+
20+
if (char === '{') {
21+
open++;
22+
} else if (char === '}') {
23+
open--;
24+
}
25+
26+
if (open === 0) {
27+
break;
28+
}
29+
30+
length++;
31+
}
32+
33+
if (open > 0) {
34+
throw new TypeError('Missing brace for error literal!');
35+
}
36+
}
37+
38+
return {index, length};
39+
}
40+
41+
function errorLiteralReplace(err, msg) {
42+
let position;
43+
44+
while ((position = errorLiteralPosition(msg)) && position.index > -1) {
45+
const lc = msg.substr(position.index, position.length);
46+
const fn = new Function(errorLiteral, `return ${lc}`); // eslint-disable-line no-new-func
47+
msg = msg.replace(`\${${lc}}`, fn(err));
48+
}
49+
50+
return msg;
51+
}
52+
653
module.exports = (command, opts) => {
754
opts = opts || {};
855

956
return new Promise((resolve, reject) => {
1057
execa.shell(command, {env: {FORCE_COLOR: true}})
1158
.then(result => resolve(result))
12-
.catch(err => notifier.notify(notifierOptions(opts), () => reject(err)));
59+
.catch(err => {
60+
const notifierOpts = notifierOptions(opts);
61+
notifierOpts.title = errorLiteralReplace(err, notifierOpts.title);
62+
notifierOpts.message = errorLiteralReplace(err, notifierOpts.message);
63+
64+
return notifier.notify(notifierOpts, () => reject(err));
65+
});
1366
});
1467
};

0 commit comments

Comments
 (0)