-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathargsToQueryResult.js
More file actions
88 lines (71 loc) · 1.94 KB
/
Copy pathargsToQueryResult.js
File metadata and controls
88 lines (71 loc) · 1.94 KB
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
const fs = require('fs');
const { Command } = require('commander');
Object.assign(exports, { argsToQueryResult });
const progName = 'jpc';
const extraHelp = `
Valid values for <library>:
1 = jmespath (the official JavaScript library)
2 = @metrichor/jmespath`;
/**
* Calls process.exit in case of bad input.
*
* @param {string[]} args
* @param {Stream} stream
* @return {string}
*/
async function argsToQueryResult(args, stream) {
const program = new Command();
program
.option(
'-u, --unquoted',
"print result without quotes if it's a string",
false,
)
.option(
'-l, --library <library>',
'JavaScript library to use for JMESPath',
'1',
)
.argument('<query>', 'JMESPath query');
program.addHelpText('after', extraHelp);
program.parse(args);
if (program.args.length > 1) {
console.error(`${progName}: fatal error: too many arguments`);
process.exit(1);
}
const lib = program.opts().library;
if (lib !== '1' && lib !== '2') {
console.error(`${progName}: fatal error: invalid library: ${lib}`);
process.exit(1);
}
if (stream.isTTY) {
console.warn('Warning: input stream is a terminal');
}
let inputString = '';
stream.on('data', (x) => {
inputString += x.toString();
});
await new Promise((resolve) => {
stream.on('end', resolve);
});
let input;
try {
input = JSON.parse(inputString);
} catch (e) {
console.error(`${progName}: fatal error: invalid JSON: ${e.message}`);
process.exit(1);
}
const pkg = [, 'jmespath', '@metrichor/jmespath'][lib];
return runQuery(pkg, input, program.args[0], program.opts().unquoted);
}
/**
* @return {string}
*/
function runQuery(pkg, input, query, unquoted) {
const tmp = require(pkg);
const search = tmp.search.bind(tmp);
const queryResult = search(input, query);
return unquoted && typeof queryResult === 'string'
? queryResult
: JSON.stringify(queryResult, null, 2);
}