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 |
x1
x7
x7
x7
x7
x7
x7
x7
x7
x1
x7
x7
x37
x38
x38
x111
x37
x39
x39
x333
x37
x39
x312
x39
x39
x37
x336
x48
x472
x37
x7
x7
x936
x234
x7
x7
x18
x18
x18
x18
x18
x18
x336
x18
x18
x18
x18
x18
x180
x40
x168
x42
x40
x18
x19
x19
x140
x18
x7
x7
x7
x7
x24
x24
x24
x24
x24
x57
x24
x24
x41
x24
x24
x41
x41
x24
x24
x24
x24
x123
x41
x205
x24
x24
x24
x33
x33
x33
x34
x34
x136
x34
x170
x34
x34
x34
x34
x34
x34
x33
x33
x43
x43
x43
x208
x43
x44
x44
x33
x33
x34
x136
x34
x34
x34
x33
x33
x33
x24
x24
x96
x54
x74
x296
x74
x296
x74
x74
x81
x81
x81
x81
x74
x435
x87
x74
x74
x74
x24
x24
x24
x24
x24
x25
x25
x200
x24 |
|
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
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) => 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 }): 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, throw: _throw, dryrun, winext = "", os = Deno.build.os } = {} as options): Promisable<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, 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 }
}
async function spawn(
command: Deno.Command,
{ bin, log, callback = ({ close }) => close?.(), buffering = 250, throw: _throw, ...channels }: { bin: string; log: Logger; callback?: callback; buffering?: number; throw?: 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)
}
await 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)
}
}),
)
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 }
}
|