-
Notifications
You must be signed in to change notification settings - Fork 0
/
postproc.js
338 lines (318 loc) · 14.1 KB
/
postproc.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#!/usr/bin/env node
/*!
** PostProc -- Post-Process Output of Program
** Copyright (c) 2020-2022 Dr. Ralf S. Engelschall <rse@engelschall.com>
**
** Permission is hereby granted, free of charge, to any person obtaining
** a copy of this software and associated documentation files (the
** "Software"), to deal in the Software without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Software, and to
** permit persons to whom the Software is furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* own package information */
const my = require("./package.json")
/* internal requirements */
const fs = require("fs")
/* external requirements */
const yargs = require("yargs")
const execa = require("execa")
const byline = require("byline")
const chalk = require("chalk")
const Tokenizr = require("tokenizr")
const moment = require("moment")
const ansiStyles = require("ansi-styles")
const tail = require("tail")
/* establish asynchronous context */
;(async () => {
/* command-line option parsing */
const argv = yargs()
/* eslint indent: off */
.parserConfiguration({
"duplicate-arguments-array": true,
"set-placeholder-key": true,
"flatten-duplicate-arrays": true,
"camel-case-expansion": true,
"strip-aliased": false,
"dot-notation": false,
"halt-at-non-option": true
})
.version(false)
.usage("Usage: postproc [-h|--help] [-V|--version] [-C|--chdir <directory>] [-i|--inject <file>] [-e|--execute <rule>] <command> ...")
.option("h", {
describe: "show program help information",
alias: "help", type: "boolean", default: false
})
.option("V", {
describe: "show program version information",
alias: "version", type: "boolean", default: false
})
.option("C", {
describe: "directory to change to before executing command",
alias: "change-directory", type: "string", nargs: 1, default: process.cwd()
})
.option("i", {
describe: "inject output from pipe/file into stdout/stderr streams",
alias: "inject", type: "string", nargs: 1, default: []
})
.option("e", {
describe: "rule to execute",
alias: "execute", type: "string", nargs: 1, default: []
})
.strict(true)
.showHelpOnFail(true)
.demand(0)
.parse(process.argv.slice(2))
/* short-circuit processing of "-V" command-line option */
if (argv.version) {
process.stderr.write(`${my.name} ${my.version} <${my.homepage}>\n`)
process.stderr.write(`${my.description}\n`)
process.stderr.write(`Copyright (c) 2020-2022 ${my.author.name} <${my.author.url}>\n`)
process.stderr.write(`Licensed under ${my.license} <http://spdx.org/licenses/${my.license}.html>\n`)
process.exit(0)
}
/* fix array option handling of yargs */
if (typeof argv.execute === "string")
argv.execute = [ argv.execute ]
if (typeof argv.inject === "string")
argv.inject = [ argv.inject ]
/* sanity check command-line arguments */
if (argv._.length < 1)
throw new Error("invalid number of arguments")
const cmd = argv._[0]
const args = argv._.slice(1)
const chdir = argv.changeDirectory
/* parse named pipe usage */
argv.inject = argv.inject.map((spec) => {
const m = spec.match(/^(stdout|stderr):(.+)$/)
if (m === null)
throw new Error("invalid injection specification")
return { stream: m[1], path: m[2] }
})
/* parse a single rule */
const parseRule = (rule) => {
const lexer = new Tokenizr()
lexer.rule("condition", /(!?)\/((?:\\\/|[^/])+)\//, (ctx, match) => {
ctx.accept("condition", { type: "regexp", not: !!match[1], regexp: new RegExp(match[2]) })
})
lexer.rule("condition", /(!?)#([a-zA-Z][a-zA-Z0-9]*)/, (ctx, match) => {
ctx.accept("condition", { type: "tag", not: !!match[1], tag: match[2] })
})
lexer.rule("condition", /\s+/, (ctx, match) => {
ctx.ignore()
})
lexer.rule("condition", /:/, (ctx, match) => {
ctx.state("action")
ctx.ignore()
})
lexer.rule("action", /"((?:\\"|[^\r\n])*)"/, (ctx, match) => {
ctx.accept("action", { type: "replace", string: match[1].replace(/\\"/g, "\"") })
})
lexer.rule("action", /(!?)#([a-zA-Z][a-zA-Z0-9]*)/, (ctx, match) => {
ctx.accept("action", { type: "tag", not: !!match[1], tag: match[2] })
})
lexer.rule("action", /(repeat|break|ignore)/, (ctx, match) => {
ctx.accept("action", { type: "command", command: match[1] })
})
lexer.rule("action", /\s+/, (ctx, match) => {
ctx.ignore()
})
lexer.input(rule)
lexer.state("condition")
lexer.debug(false)
return lexer.tokens()
}
/* parse all rules */
const rules = []
argv.execute.forEach((arg) => {
const tokens = parseRule(arg)
const rule = { conditions: [], actions: [] }
tokens.forEach((token) => {
if (token.type === "condition")
rule.conditions.push(token.value)
else if (token.type === "action")
rule.actions.push(token.value)
})
if (rule.actions.length === 0)
throw new Error(`invalid rule "${arg}": action(s) missing`)
rules.push(rule)
})
/* process a line of output */
const processLine = (line, tags) => {
/* repeat entry point */
let repeat = true
while (repeat) {
repeat = false
repeated: {
/* iterate over all rules */
for (const rule of rules) {
/* check whether all conditions matched */
let matched = true
let capture = null
for (const condition of rule.conditions) {
if (condition.type === "tag") {
/* tag: !#foo or #foo */
if (!( ( condition.not && !tags[condition.tag])
|| (!condition.not && tags[condition.tag]))) {
matched = false
break
}
}
else if (condition.type === "regexp") {
/* regexp !/foo/ or /foo/ */
capture = condition.regexp.exec(line)
if (!( ( condition.not && !capture)
|| (!condition.not && capture))) {
matched = false
break
}
}
if (!matched)
break
}
/* if all conditions matched, process the actions */
if (matched) {
/* provide capture fallback */
if (capture === null) {
capture = [ line ]
capture.index = 0
capture.input = line
}
/* iterate over all actions */
for (const action of rule.actions) {
if (action.type === "command") {
/* process commands: repeat, break or ignore */
if (action.command === "repeat") {
repeat = true
break repeated
}
else if (action.command === "break") {
repeat = false
break repeated
}
else if (action.command === "ignore") {
repeat = false
line = null
break repeated
}
}
else if (action.type === "tag") {
/* process tag: !#foo or #foo */
if (action.not)
delete tags[action.tag]
else
tags[action.tag] = true
}
else if (action.type === "replace") {
/* process replace: "foo" */
let replacer = action.string
replacer = replacer
/* replace "$N" */
.replace(/\$(\d)/g, (m, num) => {
num = parseInt(num)
return (capture[num] !== undefined ? capture[num] : "")
})
/* replace "%x(...)" */
.replace(/%([ct])(?:\((.+?)\))?/g, (m, func, args) => {
let result = ""
args = args ? args.split(/\s*,\s*/) : []
if (func === "c") {
if (args.length === 0)
args = [ "red" ]
let style = ansiStyles
for (const arg of args) {
if (style[arg] === undefined)
throw new Error(`invalid style "${arg}"`)
style = style[arg]
}
result = style.open
}
else if (func === "t") {
if (args.length === 0)
args = [ "YYYY-MM-DD hh:mm:ss.SS" ]
result = moment().format(...args)
}
return result
})
/* reassemble line */
line =
line.substring(0, capture.index) +
replacer +
line.substring(capture.index + capture[0].length)
}
}
}
}
}
}
return line
}
/* the global tag store */
const stdoutTags = { stdout: true }
const stderrTags = { stderr: true }
/* optionally listen on named pipes */
for (const inject of argv.inject) {
const stats = await fs.promises.stat(inject.path).catch(() => null)
if (stats === null)
throw new Error(`invalid injection path "${inject.path}": cannot access`)
if (stats.isFIFO()) {
const stream = byline(fs.createReadStream(inject.path, { encoding: "utf8" }))
stream.on("data", (line) => {
line = line.toString()
line = processLine(line, inject.stream === "stdout" ? stdoutTags : stderrTags)
if (line !== null)
process[inject.stream].write(`${line}\n`)
})
}
else if (stats.isFile()) {
const stream = new tail.Tail(inject.path, { follow: true, encoding: "utf8" })
stream.on("line", (line) => {
line = line.toString()
line = processLine(line, inject.stream === "stdout" ? stdoutTags : stderrTags)
if (line !== null)
process[inject.stream].write(`${line}\n`)
})
}
else
throw new Error(`invalid injection path "${inject.path}": neither fifo/pipe nor file`)
}
/* fork off shell command */
const proc = execa(cmd, args, {
stripFinalNewline: false,
stdio: [ "inherit", "pipe", "pipe" ],
reject: false,
cwd: chdir
})
/* post-process stdout/stderr of command */
const streams = [ "stdout", "stderr" ]
streams.forEach((name) => {
const stream = byline.createStream(proc[name])
stream.on("data", (line) => {
line = line.toString()
line = processLine(line, name === "stdout" ? stdoutTags : stderrTags)
if (line !== null)
process[name].write(`${line}\n`)
})
})
/* wait for command to exit and pass-through exit code */
const result = await proc
if (result.exitCode === undefined)
throw new Error(result.originalMessage)
process.exit(result.exitCode)
})().catch((err) => {
/* handle fatal error */
process.stderr.write(`postproc: ${chalk.red("ERROR:")} ${err}\n`)
process.exit(1)
})