-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjsqry-cli.js
236 lines (213 loc) · 5.2 KB
/
jsqry-cli.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import * as std from "std";
import * as os from "os";
import jsqry from "./jsqry.js";
import colorJson from "./colorJson.js";
const VERSION = "0.1.2";
// based on code from https://github.com/twardoch/svgop/blob/master/src/app/svgop-qjs.js
const utf8ArrayToStr = (function () {
const charCache = new Array(128); // Preallocate the cache for the common single byte chars
const charFromCodePt = String.fromCodePoint || String.fromCharCode;
const result = [];
return function (array) {
let codePt, byte1;
const buffLen = array.length;
result.length = 0;
for (let i = 0; i < buffLen; ) {
byte1 = array[i++];
if (byte1 <= 0x7f) {
codePt = byte1;
} else if (byte1 <= 0xdf) {
codePt = ((byte1 & 0x1f) << 6) | (array[i++] & 0x3f);
} else if (byte1 <= 0xef) {
codePt =
((byte1 & 0x0f) << 12) |
((array[i++] & 0x3f) << 6) |
(array[i++] & 0x3f);
} else if (String.fromCodePoint) {
codePt =
((byte1 & 0x07) << 18) |
((array[i++] & 0x3f) << 12) |
((array[i++] & 0x3f) << 6) |
(array[i++] & 0x3f);
} else {
codePt = 63; // Cannot convert four byte code points, so use "?" instead
i += 3;
}
result.push(
charCache[codePt] || (charCache[codePt] = charFromCodePt(codePt))
);
}
return result.join("");
};
})();
function getstdin() {
const result = [];
let length = 0;
let chunk;
while (!std.in.eof()) {
chunk = std.in.getByte();
if (chunk > 0) {
result.push(chunk);
length += chunk.length;
}
}
return utf8ArrayToStr(result);
}
function err(msg) {
std.err.puts(msg);
std.err.puts("\n");
}
const isTtyIn = os.isatty(0);
const isTtyOut = os.isatty(1);
function unquoteResult(res) {
function isPrimitive(val) {
const type = typeof val;
return type === "string" || type === "boolean" || type === "number";
}
if (isPrimitive(res)) {
return [false, res];
} else if (Array.isArray(res)) {
return [
res.length > 0,
res.map((e) => (isPrimitive(e) ? e : JSON.stringify(e))).join("\n"),
];
} else {
return [false, JSON.stringify(res)];
}
}
function doWork(jsonStr, queryStr, queryArgs, useFirst, compact, unquote) {
let json;
try {
json = JSON.parse(jsonStr);
} catch (e) {
return "error: Wrong JSON";
}
let res;
try {
res = (useFirst ? jsqry.first : jsqry.queryWithSingleMarker)(
json,
queryStr,
...queryArgs
);
if (res != null && res._$single && res.length === 1) {
res = res[0];
}
} catch (e) {
return "error: " + e;
}
if (unquote) {
const [arrayNotEmpty, ur] = unquoteResult(res);
if (ur === "") {
if (arrayNotEmpty) {
print();
}
} else {
print(ur);
}
} else {
print(
compact
? JSON.stringify(res)
: isTtyOut
? colorJson(res, 2)
: JSON.stringify(res, null, 2)
);
}
return null;
}
const QUERY_ARG_STR = "-as";
const QUERY_ARG_STR1 = "--arg-str";
const QUERY_ARG_OTHER = "-a";
const QUERY_ARG_OTHER1 = "--arg";
const valueSwitches = {
[QUERY_ARG_STR]: 1,
[QUERY_ARG_STR1]: 1,
[QUERY_ARG_OTHER]: 1,
[QUERY_ARG_OTHER1]: 1,
};
const validSwitches = {
"-1": 1,
"--first": 1,
"-h": 1,
"--help": 1,
"-v": 1,
"--version": 1,
"-c": 1,
"--compact": 1,
"-u": 1,
"--unquote": 1,
"-as": 1,
"--arg-str": 1,
"-a": 1,
"--arg": 1,
...valueSwitches,
};
function parseArgs() {
const params = {};
const args = [];
const queryArgs = [];
let prevArg = null;
for (let i = 1; i < scriptArgs.length; i++) {
const arg = scriptArgs[i];
if (valueSwitches[prevArg]) {
queryArgs.push([prevArg, arg]);
prevArg = null;
} else {
if (arg.indexOf("-") === 0) {
if (!valueSwitches[arg]) {
params[arg] = true;
}
} else {
args.push(arg);
}
prevArg = arg;
}
}
return [params, args, queryArgs];
}
const [params, args, queryArgs] = parseArgs();
const queryArgsParsed = queryArgs.map(([switch_, arg]) =>
QUERY_ARG_STR === switch_ || QUERY_ARG_STR1 === switch_
? arg
: JSON.parse(arg)
);
const invalidSwitches = Object.keys(params).filter(
(p) => !(p in validSwitches)
);
if (invalidSwitches.length) {
err("Invalid switches: " + invalidSwitches.join(","));
std.exit(1);
}
if (params["-v"] || params["--version"]) {
print(VERSION);
} else if (
params["-h"] ||
params["--help"] ||
(isTtyIn && scriptArgs.length === 1) /* called with no params */
) {
print(`jsqry ver. ${VERSION}
Usage: echo $JSON | jsqry 'query'
-1,--first return first result element
-h,--help print help and exit
-v,--version print version and exit
-c,--compact compact output (no pretty-print)
-u,--unquote unquote output string(s)
-as ARG,
--arg-str ARG supply string query argument
-a ARG,
--arg ARG supply query argument of any other type`);
} else {
const inputStr = getstdin();
const errMsg = doWork(
inputStr,
args[0] || "",
queryArgsParsed,
params["-1"] || params["--first"],
params["-c"] || params["--compact"],
params["-u"] || params["--unquote"]
);
if (errMsg) {
err(errMsg);
std.exit(1);
}
}