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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367 |
x11
x11
x11
x11
x11
x11
x11
x11
x11
x11
x102
x103
x103
x306
x102
x104
x104
x918
x102
x151
x1208
x151
x151
x146
x1099
x157
x1647
x102
x11
x1984
x496
x11
x22
x22
x22
x22
x22
x22
x352
x22
x22
x22
x22
x22
x220
x44
x184
x46
x44
x22
x23
x23
x160
x22
x11
x11
x11
x11
x42
x42
x42
x42
x42
x107
x42
x42
x70
x42
x42
x70
x70
x42
x42
x42
x42
x240
x80
x400
x42
x42
x51
x51
x51
x52
x52
x208
x52
x260
x52
x52
x52
x52
x52
x52
x51
x51
x61
x61
x61
x280
x61
x62
x51
x51
x52
x208
x52
x52
x52
x51
x51
x51
x70
x280
x122
x208
x832
x208
x832
x208
x208
x260
x260
x260
x260
x208
x1210
x242
x208
x208
x208
x70
x70
x98
x98
x98
x99
x99
x625
x70
x42
x42
x43
x44
x44
x43
x43
x43
x43
x42
x42
x42 |
|
import type { Arg, Nullable, Promisable } from "@libs/typing"
import { Logger, type loglevel } from "@libs/logger"
import { TextLineStream } from "@std/streams"
import { debounce } from "@std/async/debounce"
import { delay } from "@std/async/delay"
export type { Logger, loglevel, Promisable }
export type options = {
logger?: Logger
env?: Deno.CommandOptions["env"]
cwd?: Deno.CommandOptions["cwd"]
raw?: boolean
stdin?: loglevel | "piped" | "inherit" | null
stdout?: loglevel | "piped" | "inherit" | null
stderr?: loglevel | "piped" | "inherit" | null
callback?: callback
buffering?: number
sync?: boolean
background?: boolean
winext?: string
os?: typeof Deno.build.os
throw?: boolean
dryrun?: boolean
}
export type result = {
success: Deno.CommandStatus["success"]
code: Deno.CommandStatus["code"]
stdio: Array<[number, 0 | 1 | 2, string]>
stdin: string
stdout: string
stderr: string
}
export type callback = (options: { stdio: Pick<result, "stdin" | "stdout" | "stderr">; i: number; write: (content: string, newline?: boolean) => Promise<void>; close: () => Promise<void>; wait: (dt: number) => Promise<void> }) => Promisable<void>
const encoder = new TextEncoder()
const decoder = new TextDecoder()
export function command(bin: string, args: string[], options?: options & { sync?: false; background: true }): { kill: (signal: Deno.Signal) => Promise<void>; unref: () => void; pid: number; result: result }
export function command(bin: string, args: string[], options?: options & { sync?: false; background?: false }): Promise<result>
export function command(bin: string, args: string[], options?: options & { sync: true }): result
export function command(
bin: string,
args: string[],
{ logger: log = new Logger(), stdin = null, stdout = "debug", stderr = "error", env, cwd, raw, callback, buffering, sync, background, throw: _throw, dryrun, winext = "", os = Deno.build.os } = {} as options,
): Promisable<result> | { kill: (signal: Deno.Signal) => Promise<void>; unref: () => void; pid: number; result: result } {
if (os === "windows") {
bin = `${bin}${winext}`
}
log = log.with({ bin })
if (callback && (handle(stdin) !== "piped")) {
stdin = "piped"
}
const command = new Deno.Command(bin, { args, stdin: !sync ? handle(stdin) : "null", stdout: handle(stdout), stderr: handle(stderr), env, cwd, windowsRawArguments: raw })
if (dryrun) {
log.wdebug(`dryrun: ${bin} not executed`)
const result = { success: true, code: 0, stdio: [], stdin: "", stdout: "", stderr: "" }
return sync ? result : Promise.resolve(result)
}
if (sync) {
return exec(command, { bin, log, throw: _throw, stdout, stderr })
}
return spawn(command, { bin, log, callback, buffering, throw: _throw, background, stdin: handle(stdin) === "piped" ? stdin as loglevel : null, stdout: handle(stdout) === "piped" ? stdout as loglevel : null, stderr: handle(stderr) === "piped" ? stderr as loglevel : null })
}
function handle(mode: Nullable<string>) {
return ["inherit", "null"].includes(`${mode}`) ? `${mode}` as "inherit" | "null" : "piped"
}
function exec(command: Deno.Command, { bin, log, throw: _throw, stdout, stderr }: { bin: string; log: Logger; throw?: boolean; stdout: Nullable<string>; stderr: Nullable<string> }) {
const start = Date.now()
const output = command.outputSync()
const { success, code } = output
const t = Date.now() - start
const stdio = {
get stdio() {
return [[t, 1, this.stdout], [t, 2, this.stderr]]
},
stdin: "",
stdout: handle(stdout) === "piped" ? decoder.decode(output.stdout) : "",
stderr: handle(stderr) === "piped" ? decoder.decode(output.stderr) : "",
} as Pick<result, "stdio" | "stdin" | "stdout" | "stderr">
for (const { channel, mode } of [{ channel: "stdout", mode: stdout }, { channel: "stderr", mode: stderr }] as const) {
if ((handle(mode) === "piped") && (stdio[channel])) {
log.with({ t, channel })[mode as loglevel]?.(stdio[channel])
}
}
if ((!success) && _throw) {
throw new EvalError(`${bin} exited with non-zero code ${code}:\n${stdio.stdout}\n${stdio.stderr}`)
}
return { success, code, ...stdio }
}
function spawn(
command: Deno.Command,
options: { bin: string; log: Logger; callback?: callback; buffering?: number; throw?: boolean; background: true; stdin: Nullable<loglevel>; stdout: Nullable<loglevel>; stderr: Nullable<loglevel> },
): { kill: (signal: Deno.Signal) => Promise<void>; unref: () => void; pid: number; result: Promise<result> }
function spawn(command: Deno.Command, options: { bin: string; log: Logger; callback?: callback; buffering?: number; throw?: boolean; background?: boolean; stdin: Nullable<loglevel>; stdout: Nullable<loglevel>; stderr: Nullable<loglevel> }): Promise<result>
function spawn(
command: Deno.Command,
{ bin, log, callback = ({ close }) => close?.(), buffering = 250, throw: _throw, background, ...channels }: {
bin: string
log: Logger
callback?: callback
buffering?: number
throw?: boolean
background?: boolean
stdin: Nullable<loglevel>
stdout: Nullable<loglevel>
stderr: Nullable<loglevel>
},
) {
const process = command.spawn()
const start = Date.now()
const stdio = {
stdio: [],
get stdin() {
return this.stdio.filter(([_, i]) => i === 0).map(([_, __, content]) => content).join("\n")
},
get stdout() {
return this.stdio.filter(([_, i]) => i === 1).map(([_, __, content]) => content).join("\n")
},
get stderr() {
return this.stdio.filter(([_, i]) => i === 2).map(([_, __, content]) => content).join("\n")
},
} as Pick<result, "stdio" | "stdin" | "stdout" | "stderr">
const options = {} as Pick<Arg<callback>, "write" | "close" | "wait">
let last = ""
const debounced = debounce(async (t: number) => {
log.with({ t }).trace("debounced")
last = ""
await callback({ stdio, i: stdio.stdin.length, ...options })
}, buffering)
if (handle(channels.stdin) === "piped") {
const writer = process.stdin.getWriter()
Object.assign(options, {
async write(content: string, newline = true) {
const t = Date.now() - start
if (channels.stdin) {
log.with({ t, channel: "stdin" })[channels.stdin]?.(content)
}
stdio.stdio.push([t, 0, content])
if (newline && (!content.endsWith("\n"))) {
content += "\n"
}
await writer.write(encoder.encode(content))
last = "stdin"
writer.releaseLock()
},
async close() {
try {
writer.releaseLock()
await process.stdin.close()
log.with({ t: Date.now() - start, closed: "stdin" }).trace()
} catch {
}
},
async wait(dt = 1000) {
const t = Date.now() - start
log.with({ t, waiting: dt }).trace()
await delay(dt)
debounced(t)
},
})
debounced(Date.now() - start)
}
const result = Promise.all(
(["stdout", "stderr"] as const).filter((channel) => handle(channels[channel]) === "piped").map(async (channel) => {
for await (const line of process[channel].pipeThrough(new TextDecoderStream()).pipeThrough(new TextLineStream())) {
const t = Date.now() - start
const stdi = { stdout: 1, stderr: 2 }[channel] as 1 | 2
if (channels[channel]) {
log.with({ t, channel })[channels[channel]!]?.(line)
}
if ((stdio.stdio.length) && (last === channel)) {
const previous = stdio.stdio.at(-1)!
if (previous[1] === stdi) {
previous[2] += `\n${line}`
}
} else {
stdio.stdio.push([t, stdi, line])
}
last = channel
debounced(t)
}
}),
).then(async () => {
debounced.flush()
const { success, code } = await process.status
if ((!success) && _throw) {
throw new EvalError(`${bin} exited with non-zero code ${code}:\n${stdio.stdout}\n${stdio.stderr}`)
}
return { success, code, ...stdio }
})
return background
? {
kill: async (signal: Deno.Signal) => {
process.kill(signal)
await process.status
},
unref: () => process.unref(),
pid: process.pid,
result,
}
: result
}
|