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
|
import fs from 'node:fs';
import { WaError } from './rpc.js';
import { format } from './format/index.js';
// Parses --params / --json: literal JSON, @file or - (stdin).
export function parseJsonArg(value, flag) {
if (value === undefined) return {};
let text = value;
try {
if (value === '-') text = fs.readFileSync(0, 'utf8');
else if (value.startsWith('@')) text = fs.readFileSync(value.slice(1), 'utf8');
} catch (e) {
throw new WaError('EINVAL', `${flag}: ${e.message}`);
}
try {
return JSON.parse(text);
} catch (e) {
throw new WaError('EINVAL', `${flag}: invalid JSON (${e.message})`);
}
}
export function print(data, fmt = 'json', { columns, output } = {}) {
let text;
try {
text = format(data, fmt, { columns });
} catch (e) {
throw new WaError(e.code || 'EINVAL', e.message);
}
if (output) {
fs.writeFileSync(output, text ? `${text}\n` : '');
} else if (text) {
process.stdout.write(`${text}\n`);
}
}
export function readStdin() {
return fs.readFileSync(0, 'utf8').replace(/\n$/, '');
}
|