-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·181 lines (155 loc) · 5.12 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
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
#!/usr/bin/env node
const JSON5 = require('json5')
const fs = require("fs");
const yaml = require("js-yaml");
const rfc6902 = require("rfc6902");
const jsonmergepatch = require("json-merge-patch");
const traverse = require("traverse");
const lodash = require("lodash");
const {get} = require("lodash");
const clone = require("clone");
const {stdin} = process;
if (process.env["NJQ2_FORMAT"]) {
if (!process.env["NJQ2_INPUT_FORMAT"]) {
process.env["NJQ2_INPUT_FORMAT"] = process.env["NJQ2_FORMAT"];
}
if (!process.env["NJQ2_OUTPUT_FORMAT"]) {
process.env["NJQ2_OUTPUT_FORMAT"] = process.env["NJQ2_FORMAT"];
}
}
if (process.env["NJQ2_OUTPUT_FORMAT"] === "yaml" && typeof process.env["NJQ2_OUTPUT_DOCUMENT_SEPARATOR"] == "undefined") {
process.env["NJQ2_OUTPUT_DOCUMENT_SEPARATOR"] = "---\n"
}
function evalFile(path) {
return eval(fs.readFileSync(path, {encoding: "UTF-8"}));
}
const getStdin = async () => {
let result = '';
if (stdin.isTTY) {
return result;
}
stdin.setEncoding('utf8');
for await (const chunk of stdin) {
result += chunk;
}
return result;
};
((function main() {
let expression = process.argv[2];
if (!expression) {
printUsage();
process.exit(1);
}
if (process.env["NJQ2_MODE"] === "JsonMergePatch") {
return executeJsonMergePatch(expression).then(printResults);
} else {
return executeQuery(expression).then(printResults);
}
})()).catch(err => {
console.error(err);
process.exit(1);
});
function executeJsonMergePatch(expression) {
return getAndParseFiles().then(files => files.map(input => {
return jsonmergepatch.apply(input, JSON5.parse(expression));
}));
}
function executeQuery(expression) {
// normalize expression
expression = (() => {
if (expression.startsWith(".[")) {
// if the expression is a jq like `.[xxx]yyy`, we assume it is referring to `input[xxx]yyy`
return `input[${expression.substr(2)}`;
} else if (expression.startsWith(".")) {
try {
// case of '.1 + .2'
let result = eval(expression);
if (isNumber(result)) {
return result;
}
} catch {
}
// if the expression is a jq like `.xxx`, we assume it is referring to `input.xxx`
return `input${expression}`;
} else {
return expression
}
})();
patchArrayFilter();
return getAndParseFiles().then(files => files.map(input => {
const pristineInput = JSON.parse(JSON.stringify(input));
function genJsonPatch(value) {
return rfc6902.createPatch(pristineInput, value);
}
function genJsonMergePatch(value) {
return jsonmergepatch.generate(pristineInput, value);
}
return eval(`${expression}`);
}));
}
function printResults(results) {
results.forEach((result, i) => {
if (typeof result == "object") {
if (process.env["NJQ2_OUTPUT_FORMAT"] === "yaml") {
console.log(yaml.dump(result, JSON.parse(process.env["NJQ2_YAML_DUMP_OPTIONS"] || '{}')).trim());
} else {
console.log(JSON.stringify(result, null, 4).trim());
}
} else {
console.log(result);
}
if (i < results.length - 1 && process.env["NJQ2_OUTPUT_DOCUMENT_SEPARATOR"]) {
console.log(process.env["NJQ2_OUTPUT_DOCUMENT_SEPARATOR"]);
}
})
}
// patches array.filter so that when there's an uncaught exception in the callback function,
// it simply returns false instead of crashing.
//
// this allows for a simpler .filter() call, without worrying about
// TypeError: Cannot read property 'xxx' of undefined
// and other trivial errors
function patchArrayFilter() {
let origArrayFilter = Array.prototype.filter;
function patchedArrayFilter(...arguments) {
// hook the filter function
let origFilterFunction = arguments[0];
arguments[0] = a => {
try {
return origFilterFunction(a)
} catch (e) {
return false;
}
}
return origArrayFilter.apply(this, arguments);
}
Array.prototype.filter = patchedArrayFilter;
};
function getFiles() {
if (process.argv.length === 3) {
return getStdin().then(data => [data])
} else {
return Promise.resolve(process.argv.slice(3).map(path => fs.readFileSync(path, "utf-8")))
}
}
function getAndParseFiles() {
return getFiles().then(files => files.map(input => {
try {
// try to parse input as JSON
if (process.env["NJQ2_INPUT_FORMAT"] === "yaml") {
return yaml.load(input);
} else {
return JSON5.parse(input);
}
} catch {
// input is not a JSON, which is also fine and we leave it as is
return input;
}
}))
}
function printUsage() {
console.log("Usage: njq2 <js expression> [file...]")
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}