mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-21 08:03:13 +09:00
Address second review of ctl --output
CommandOutput.error takes a human reporter like result, so command errors log their message in human mode and print JSON in json and wire mode. table takes a map applied to each row in human mode, which note list, host plugin list, user list and save list now use. Rename streaming to streamingLog, and print startup errors with errorToJson directly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8550df69eb
commit
23187859d6
11 files changed
+55
-36
No files matched your search
@@ -15,7 +15,7 @@ The easiest way to do this is to run `npx clusteriocontroller bootstrap create-c
|
||||
Print the result of the command as JSON on stdout instead of text meant for reading.
|
||||
Lists are printed as an array of objects, other results as an object, and commands that have no result print `{"success": true}`.
|
||||
If the command fails it prints `{"error": "<ClassName>", "message": "<message>"}` and exits with a non-zero exit code.
|
||||
Log messages, including the error message, are written to stderr in all formats.
|
||||
Log messages are written to stderr in all formats.
|
||||
|
||||
`--output wire` prints the same results in the format they are sent between the controller, hosts and clusterioctl, which uses snake_case names like `is_admin`.
|
||||
The `json` format uses the property names shown in the tables of the human format.
|
||||
|
||||
@@ -982,7 +982,7 @@ handler: async function(args, ctl) {
|
||||
```
|
||||
|
||||
`ctl.output.result(data, human)` prints `data` as JSON in json and wire mode and calls `human` otherwise.
|
||||
`ctl.output.table(rows)` prints an array of objects as a table or as a JSON array.
|
||||
`ctl.output.table(rows, map)` prints an array of objects as a JSON array, or as a table in human mode with `map` applied to each row first.
|
||||
`ctl.output.human` is true when the output is meant for reading.
|
||||
Commands that print nothing get `Command ran successfully` or `{"success": true}` printed for them, and errors thrown from the handler are printed as `{"error": "<ClassName>", "message": "<message>"}` in json and wire mode.
|
||||
|
||||
|
||||
+9
-10
@@ -17,7 +17,7 @@ import { ConsoleTransport, levels, logger } from "@clusterio/lib";
|
||||
|
||||
import * as commands from "./src/commands.js";
|
||||
import { BaseCtlPlugin, CtlHooks } from "./src/BaseCtlPlugin.js";
|
||||
import { CommandOutput, outputFormats, type OutputFormat } from "./src/command_ops.js";
|
||||
import { CommandOutput, errorToJson, outputFormats, print, type OutputFormat } from "./src/command_ops.js";
|
||||
|
||||
|
||||
/**
|
||||
@@ -85,8 +85,8 @@ export class Ctl extends lib.Link {
|
||||
}
|
||||
|
||||
async handleLogMessageEvent(event: lib.LogMessageEvent) {
|
||||
// Only streaming commands print log events as results, the rest log them to stderr
|
||||
if (this.output.streaming) {
|
||||
// Only log following commands print log events as results, the rest log them to stderr
|
||||
if (this.output.streamingLog) {
|
||||
this.output.result(event.info, () => logger.log(event.info as any));
|
||||
} else {
|
||||
logger.log(event.info as any);
|
||||
@@ -308,7 +308,7 @@ async function startCtl() {
|
||||
await connectAndRun(args, rootCommands, ctlConfig);
|
||||
} catch (err) {
|
||||
if (args.output !== "human") {
|
||||
new CommandOutput(args.output).error(err);
|
||||
print(JSON.stringify(errorToJson(err)));
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
@@ -344,21 +344,20 @@ async function connectAndRun(args: CtlArguments, rootCommands: lib.CommandTree,
|
||||
|
||||
} catch (err) {
|
||||
ctl.keepOpen = false;
|
||||
let message: string;
|
||||
if (err instanceof lib.CommandError) {
|
||||
logger.error(`Error running command: ${err.message}`);
|
||||
message = `Error running command: ${err.message}`;
|
||||
|
||||
} else if (err instanceof lib.ClientError || err instanceof lib.UnavailableError) {
|
||||
logger.error(`Error sending request: ${err.message}`);
|
||||
message = `Error sending request: ${err.message}`;
|
||||
|
||||
} else if (err instanceof lib.ServerError) {
|
||||
logger.error(`Error sending request:\n${err.stack ?? err.message}`);
|
||||
message = `Error sending request:\n${err.stack ?? err.message}`;
|
||||
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
if (!ctl.output.human) {
|
||||
ctl.output.error(err);
|
||||
}
|
||||
ctl.output.error(err, () => logger.error(message));
|
||||
process.exitCode = 1;
|
||||
|
||||
} finally {
|
||||
|
||||
@@ -62,8 +62,8 @@ export type OutputFormat = typeof outputFormats[number];
|
||||
export class CommandOutput {
|
||||
/** True once a result has been printed */
|
||||
written = false;
|
||||
/** Command prints a JSON line per item as it runs instead of a single result */
|
||||
streaming = false;
|
||||
/** Command prints log events as results while it runs and has no final result */
|
||||
streamingLog = false;
|
||||
|
||||
constructor(
|
||||
public format: OutputFormat = "human",
|
||||
@@ -90,20 +90,34 @@ export class CommandOutput {
|
||||
}
|
||||
}
|
||||
|
||||
/** Print a list of objects as a table, or as an array in json and wire mode */
|
||||
table(rows: object[]) {
|
||||
this.result(rows, () => print(asTable(rows)));
|
||||
/**
|
||||
* Print a list of objects as a table, or as an array in json and wire mode
|
||||
*
|
||||
* @param rows - Printed as is in json and wire mode.
|
||||
* @param map - Converts each row into the table row printed in human mode.
|
||||
*/
|
||||
table<T extends object>(rows: T[], map: (row: T) => object = row => row) {
|
||||
this.result(rows, () => print(asTable(rows.map(map))));
|
||||
}
|
||||
|
||||
/** Print an error as `{ "error": ClassName, "message": string }` */
|
||||
error(err: unknown) {
|
||||
/**
|
||||
* Print an error as `{ "error": ClassName, "message": string }` in json and wire mode
|
||||
*
|
||||
* @param err - Error to print.
|
||||
* @param human - Reports the error in human mode.
|
||||
*/
|
||||
error(err: unknown, human: () => void) {
|
||||
this.written = true;
|
||||
print(JSON.stringify(errorToJson(err)));
|
||||
if (this.human) {
|
||||
human();
|
||||
} else {
|
||||
print(JSON.stringify(errorToJson(err)));
|
||||
}
|
||||
}
|
||||
|
||||
/** Print a success result for commands that finished without printing one */
|
||||
finish() {
|
||||
if (!this.written && !this.streaming) {
|
||||
if (!this.written && !this.streamingLog) {
|
||||
this.result({ success: true }, () => print("Command ran successfully"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ debugCommands.add(new lib.Command({
|
||||
handler: async function(args: object, ctl: Ctl) {
|
||||
await ctl.send(new lib.DebugDumpWsRequest());
|
||||
ctl.keepOpen = true;
|
||||
ctl.output.streaming = true;
|
||||
ctl.output.streamingLog = true;
|
||||
},
|
||||
}));
|
||||
|
||||
|
||||
@@ -287,9 +287,9 @@ hostPluginCommands.add(new lib.Command({
|
||||
handler: async function(args: { host: string }, ctl: Ctl) {
|
||||
let hostId = await lib.resolveHost(ctl, args.host);
|
||||
const plugins = await ctl.sendTo({ hostId }, new lib.PluginListRequest());
|
||||
ctl.output.result(plugins, () => print(asTable(plugins.map(p => ({
|
||||
ctl.output.table(plugins, p => ({
|
||||
title: p.title, version: p.version, state: p.state, npmPackage: p.npmPackage,
|
||||
})))));
|
||||
}));
|
||||
},
|
||||
}));
|
||||
hostPluginCommands.add(new lib.Command({
|
||||
|
||||
@@ -9,7 +9,7 @@ import util from "util";
|
||||
import * as lib from "@clusterio/lib";
|
||||
import { logger } from "@clusterio/lib";
|
||||
import type { Ctl } from "../ctl.js";
|
||||
import { asTable, errorToJson, print } from "./command_ops.js";
|
||||
import { errorToJson, print } from "./command_ops.js";
|
||||
import { serializedConfigToString, getEditor, configToKeyVal, printConfig } from "./config_ops.js";
|
||||
|
||||
const finished = util.promisify(stream.finished);
|
||||
@@ -287,9 +287,7 @@ instanceSaveCommands.add(new lib.Command({
|
||||
let instanceId = await lib.resolveInstance(ctl, args.instance);
|
||||
let saves = await ctl.sendTo("controller", new lib.InstanceSaveDetailsListRequest());
|
||||
saves = saves.filter(save => save.instanceId === instanceId);
|
||||
ctl.output.result(saves, () => print(asTable(saves.map(
|
||||
({ mtimeMs, ...rest }) => ({ ...rest, mtime: new Date(mtimeMs).toLocaleString() })
|
||||
))));
|
||||
ctl.output.table(saves, ({ mtimeMs, ...rest }) => ({ ...rest, mtime: new Date(mtimeMs).toLocaleString() }));
|
||||
},
|
||||
}));
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ logCommands.add(new lib.Command({
|
||||
let hostIds = args.host ? [await lib.resolveHost(ctl, args.host)] : [];
|
||||
await ctl.setLogSubscriptions({ all: args.all, controller: args.controller, hostIds, instanceIds });
|
||||
ctl.keepOpen = true;
|
||||
ctl.output.streaming = true;
|
||||
ctl.output.streamingLog = true;
|
||||
},
|
||||
}));
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as lib from "@clusterio/lib";
|
||||
import type { Ctl } from "../ctl.js";
|
||||
import { asTable, print } from "./command_ops.js";
|
||||
import { print } from "./command_ops.js";
|
||||
|
||||
export const noteCommands = new lib.CommandTree({
|
||||
name: "note", description: "Notes attached to hosts, instances, users and other resources",
|
||||
@@ -16,12 +16,12 @@ noteCommands.add(new lib.Command({
|
||||
if (args.type !== undefined) {
|
||||
notes = notes.filter(note => note.resourceType === args.type);
|
||||
}
|
||||
ctl.output.result(notes, () => print(asTable(notes.map(note => ({
|
||||
ctl.output.table(notes, note => ({
|
||||
type: note.resourceType,
|
||||
id: note.resourceId,
|
||||
updatedBy: note.updatedBy,
|
||||
content: note.content,
|
||||
})))));
|
||||
}));
|
||||
},
|
||||
}));
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ userCommands.add(new lib.Command({
|
||||
}],
|
||||
handler: async function(args: { stats: boolean, attributes: boolean }, ctl: Ctl) {
|
||||
const users = await ctl.send(new lib.UserListRequest());
|
||||
const rows = users.map(user => {
|
||||
ctl.output.table(users, user => {
|
||||
const {
|
||||
playerStats, isDeleted, banReason, instanceStats, isAdmin, isWhitelisted, isBanned, ...row
|
||||
} = user;
|
||||
@@ -66,7 +66,6 @@ userCommands.add(new lib.Command({
|
||||
...args.stats && playerStats,
|
||||
};
|
||||
});
|
||||
ctl.output.result(users, () => print(asTable(rows)));
|
||||
},
|
||||
}));
|
||||
|
||||
|
||||
@@ -64,16 +64,25 @@ describe("ctl/command_ops", function() {
|
||||
it("prints success for commands without a result", function() {
|
||||
assert.deepEqual(captureLog(() => new CommandOutput("json").finish()), ['{"success":true}']);
|
||||
const streaming = new CommandOutput("json");
|
||||
streaming.streaming = true;
|
||||
streaming.streamingLog = true;
|
||||
assert.deepEqual(captureLog(() => streaming.finish()), []);
|
||||
});
|
||||
it("prints errors as JSON", function() {
|
||||
const output = new CommandOutput("json");
|
||||
const lines = captureLog(() => {
|
||||
output.error(new lib.CommandError("failed"));
|
||||
output.error(new lib.CommandError("failed"), () => assert.fail("called human formatter"));
|
||||
output.finish();
|
||||
});
|
||||
assert.deepEqual(lines, ['{"error":"CommandError","message":"failed"}']);
|
||||
});
|
||||
it("calls the human error reporter in human mode", function() {
|
||||
const output = new CommandOutput("human");
|
||||
const human = () => console.log("failed"); // eslint-disable-line no-console
|
||||
const lines = captureLog(() => {
|
||||
output.error(new lib.CommandError("failed"), human);
|
||||
output.finish();
|
||||
});
|
||||
assert.deepEqual(lines, ["failed"]);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user