From 23187859d6054c1d874704739ebb5575c630dfc2 Mon Sep 17 00:00:00 2001 From: bbassie <17990055+bbassie@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:56:48 +0000 Subject: [PATCH] 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 --- docs/managing-a-cluster.md | 2 +- docs/writing-plugins.md | 2 +- packages/ctl/ctl.ts | 19 ++++++++-------- packages/ctl/src/command_ops.ts | 32 +++++++++++++++++++-------- packages/ctl/src/commands_debug.ts | 2 +- packages/ctl/src/commands_host.ts | 4 ++-- packages/ctl/src/commands_instance.ts | 6 ++--- packages/ctl/src/commands_log.ts | 2 +- packages/ctl/src/commands_note.ts | 6 ++--- packages/ctl/src/commands_user.ts | 3 +-- test/ctl/command_ops.test.js | 13 +++++++++-- 11 files changed, 55 insertions(+), 36 deletions(-) diff --git a/docs/managing-a-cluster.md b/docs/managing-a-cluster.md index cbc36a4b..2cd6508b 100644 --- a/docs/managing-a-cluster.md +++ b/docs/managing-a-cluster.md @@ -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": "", "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. diff --git a/docs/writing-plugins.md b/docs/writing-plugins.md index d7cf7d6d..731bce10 100644 --- a/docs/writing-plugins.md +++ b/docs/writing-plugins.md @@ -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": "", "message": ""}` in json and wire mode. diff --git a/packages/ctl/ctl.ts b/packages/ctl/ctl.ts index 70792252..a737b6ef 100755 --- a/packages/ctl/ctl.ts +++ b/packages/ctl/ctl.ts @@ -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 { diff --git a/packages/ctl/src/command_ops.ts b/packages/ctl/src/command_ops.ts index 5cdf8e99..258eea00 100644 --- a/packages/ctl/src/command_ops.ts +++ b/packages/ctl/src/command_ops.ts @@ -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(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")); } } diff --git a/packages/ctl/src/commands_debug.ts b/packages/ctl/src/commands_debug.ts index edc8644f..4fca9c69 100644 --- a/packages/ctl/src/commands_debug.ts +++ b/packages/ctl/src/commands_debug.ts @@ -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; }, })); diff --git a/packages/ctl/src/commands_host.ts b/packages/ctl/src/commands_host.ts index e3672d09..8d3adeb7 100644 --- a/packages/ctl/src/commands_host.ts +++ b/packages/ctl/src/commands_host.ts @@ -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({ diff --git a/packages/ctl/src/commands_instance.ts b/packages/ctl/src/commands_instance.ts index f469e13a..a88b3b42 100644 --- a/packages/ctl/src/commands_instance.ts +++ b/packages/ctl/src/commands_instance.ts @@ -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() })); }, })); diff --git a/packages/ctl/src/commands_log.ts b/packages/ctl/src/commands_log.ts index a66abdd8..312a79c8 100644 --- a/packages/ctl/src/commands_log.ts +++ b/packages/ctl/src/commands_log.ts @@ -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; }, })); diff --git a/packages/ctl/src/commands_note.ts b/packages/ctl/src/commands_note.ts index 21dd41bd..abe8d64a 100644 --- a/packages/ctl/src/commands_note.ts +++ b/packages/ctl/src/commands_note.ts @@ -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, - }))))); + })); }, })); diff --git a/packages/ctl/src/commands_user.ts b/packages/ctl/src/commands_user.ts index 434e5a8b..54991509 100644 --- a/packages/ctl/src/commands_user.ts +++ b/packages/ctl/src/commands_user.ts @@ -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))); }, })); diff --git a/test/ctl/command_ops.test.js b/test/ctl/command_ops.test.js index 175318bd..823faa3e 100644 --- a/test/ctl/command_ops.test.js +++ b/test/ctl/command_ops.test.js @@ -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"]); + }); }); });