Address review of ctl --output

Add a wire output format that prints the toJSON format sent over the link. Commands without a result print {"success": true}, or "Command ran successfully" in human mode. The missing URL check throws a StartupError, unexpected command errors are rethrown to the startup handler, and startup errors log as fatal. user list, note list and host plugin list print the objects they received instead of their table rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bbassieandClaude Opus 5.5 committed 2026-11-18 16:48:40 +00:00
1 parent 10beffe167
commit 8550df69eb
13 files changed
+131 -112

No files matched your search

+2 -2
View File
@@ -23,9 +23,9 @@ Common options:
* `--create-config` If the config file is missing, create a new one and carry on instead of exiting with an error.
Alternative to the `config create` command.
* `--output <human|json>` Format to print the results of cluster commands in.
* `--output <human|json|wire>` Format to print the results of cluster commands in.
Defaults to `human`.
See [Output format](/docs/managing-a-cluster.md#output-format) for what `json` prints.
See [Output format](/docs/managing-a-cluster.md#output-format) for what `json` and `wire` print.
The `plugin` and `config` commands described below always print human readable text.
+23 -32
View File
@@ -85,8 +85,9 @@ export class Ctl extends lib.Link {
}
async handleLogMessageEvent(event: lib.LogMessageEvent) {
if (this.output.json && this.output.streaming) {
this.output.result(event.info);
// Only streaming commands print log events as results, the rest log them to stderr
if (this.output.streaming) {
this.output.result(event.info, () => logger.log(event.info as any));
} else {
logger.log(event.info as any);
}
@@ -292,27 +293,30 @@ export async function runCommand(
link.output.finish();
}
async function startCtl(output: CommandOutput) {
async function startCtl() {
const {
args,
shouldRun,
rootCommands,
ctlConfig,
} = await initialize(process.argv.slice(2));
output.format = args.output;
if (!shouldRun || !rootCommands || !ctlConfig) {
return;
}
if (!ctlConfig.get("ctl.controller_url") || !ctlConfig.get("ctl.controller_token")) {
const message = "Missing URL and/or token to connect with. See README.md for setting up access.";
if (output.json) {
output.error(new lib.StartupError(message));
} else {
logger.error(message);
try {
await connectAndRun(args, rootCommands, ctlConfig);
} catch (err) {
if (args.output !== "human") {
new CommandOutput(args.output).error(err);
}
process.exitCode = 1;
return;
throw err;
}
}
async function connectAndRun(args: CtlArguments, rootCommands: lib.CommandTree, ctlConfig: lib.CtlConfig) {
if (!ctlConfig.get("ctl.controller_url") || !ctlConfig.get("ctl.controller_token")) {
throw new lib.StartupError("Missing URL and/or token to connect with. See README.md for setting up access.");
}
let controlConnector = new CtlConnector(
@@ -340,30 +344,22 @@ async function startCtl(output: CommandOutput) {
} catch (err) {
ctl.keepOpen = false;
const expected = err instanceof lib.CommandError || err instanceof lib.ClientError
|| err instanceof lib.ServerError;
if (ctl.output.json) {
ctl.output.error(err);
process.exitCode = 1;
if (!expected) {
logger.error((err as Error).stack ?? String(err));
}
} else if (err instanceof lib.CommandError) {
if (err instanceof lib.CommandError) {
logger.error(`Error running command: ${err.message}`);
process.exitCode = 1;
} else if (err instanceof lib.ClientError || err instanceof lib.UnavailableError) {
logger.error(`Error sending request: ${err.message}`);
process.exitCode = 1;
} else if (err instanceof lib.ServerError) {
logger.error(`Error sending request:\n${err.stack ?? err.message}`);
process.exitCode = 1;
} else {
throw err;
}
if (!ctl.output.human) {
ctl.output.error(err);
}
process.exitCode = 1;
} finally {
if (!ctl.keepOpen) {
@@ -373,13 +369,8 @@ async function startCtl(output: CommandOutput) {
}
export function bootstrap() {
const output = new CommandOutput();
startCtl(output).catch(err => {
startCtl().catch(err => {
process.exitCode = 1;
if (output.json) {
output.error(err);
return;
}
if (err.errors) {
logger.fatal(JSON.stringify(err.errors, null, "\t"));
}
@@ -392,7 +383,7 @@ export function bootstrap() {
${err.stack}`
);
} else {
logger.error(`
logger.fatal(`
+---------------------------------+
| Unable to to start clusterioctl |
+---------------------------------+
+24 -10
View File
@@ -39,13 +39,25 @@ export function errorToJson(err: unknown) {
return { error: "Error", message: String(err) };
}
export const outputFormats = ["human", "json"] as const;
/** JSON.stringify replacer for Sets and Maps that have no toJSON method */
function wireReplacer(key: string, value: unknown) {
if (value instanceof Set) {
return [...value];
}
if (value instanceof Map) {
return Object.fromEntries(value);
}
return value;
}
export const outputFormats = ["human", "json", "wire"] as const;
export type OutputFormat = typeof outputFormats[number];
/**
* Prints the results of a ctl command in the format chosen with --output
*
* In json mode each call to result prints one line of JSON to stdout.
* In json and wire mode each call to result prints one line of JSON to stdout. json uses the
* property names of the objects, wire uses their toJSON methods to give the format sent over the link.
*/
export class CommandOutput {
/** True once a result has been printed */
@@ -57,26 +69,28 @@ export class CommandOutput {
public format: OutputFormat = "human",
) { }
get json() {
return this.format === "json";
get human() {
return this.format === "human";
}
/**
* Print the result of a command
*
* @param data - Printed as JSON in json mode.
* @param data - Printed as JSON in json and wire mode.
* @param human - Prints the result in human mode, defaults to printing data as is.
*/
result(data: unknown, human: () => void = () => print(data)) {
this.written = true;
if (this.json) {
if (this.format === "json") {
print(JSON.stringify(toPlain(data)));
} else if (this.format === "wire") {
print(JSON.stringify(data, wireReplacer));
} else {
human();
}
}
/** Print a list of objects as a table, or as an array in json mode */
/** 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)));
}
@@ -87,10 +101,10 @@ export class CommandOutput {
print(JSON.stringify(errorToJson(err)));
}
/** Print `{}` in json mode for commands that finished without printing a result */
/** Print a success result for commands that finished without printing one */
finish() {
if (this.json && !this.written && !this.streaming) {
this.result({});
if (!this.written && !this.streaming) {
this.result({ success: true }, () => print("Command ran successfully"));
}
}
}
+2 -2
View File
@@ -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.table(plugins.map(p => ({
ctl.output.result(plugins, () => print(asTable(plugins.map(p => ({
title: p.title, version: p.version, state: p.state, npmPackage: p.npmPackage,
})));
})))));
},
}));
hostPluginCommands.add(new lib.Command({
+2 -2
View File
@@ -575,7 +575,7 @@ instanceCommands.add(new lib.Command({
return;
}
const human = !ctl.output.json;
const human = ctl.output.human;
if (human) {
print(`Starting ${instancesToStart.length} instance(s):`);
for (const instance of instancesToStart) {
@@ -662,7 +662,7 @@ instanceCommands.add(new lib.Command({
return;
}
const human = !ctl.output.json;
const human = ctl.output.human;
if (human) {
print(`Stopping ${instancesToStop.length} instance(s):`);
for (const instance of instancesToStop) {
+3 -3
View File
@@ -1,6 +1,6 @@
import * as lib from "@clusterio/lib";
import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js";
import { asTable, 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.table(notes.map(note => ({
ctl.output.result(notes, () => print(asTable(notes.map(note => ({
type: note.resourceType,
id: note.resourceId,
updatedBy: note.updatedBy,
content: note.content,
})));
})))));
},
}));
+12 -23
View File
@@ -55,29 +55,18 @@ userCommands.add(new lib.Command({
});
}],
handler: async function(args: { stats: boolean, attributes: boolean }, ctl: Ctl) {
let users = await ctl.send(new lib.UserListRequest());
for (let user of users) {
if (args.stats) {
Object.assign(user, user.playerStats);
}
// @ts-expect-error Terrible hack
delete user.playerStats;
// @ts-expect-error Terrible hack
delete user.isDeleted;
// @ts-expect-error Terrible hack
delete user.banReason;
// @ts-expect-error Terrible hack
delete user.instanceStats;
if (!args.attributes) {
// @ts-expect-error Terrible hack
delete user.isAdmin;
// @ts-expect-error Terrible hack
delete user.isWhitelisted;
// @ts-expect-error Terrible hack
delete user.isBanned;
}
}
ctl.output.table(users);
const users = await ctl.send(new lib.UserListRequest());
const rows = users.map(user => {
const {
playerStats, isDeleted, banReason, instanceStats, isAdmin, isWhitelisted, isBanned, ...row
} = user;
return {
...row,
...args.attributes && { isAdmin, isWhitelisted, isBanned },
...args.stats && playerStats,
};
});
ctl.output.result(users, () => print(asTable(rows)));
},
}));
+1
View File
@@ -60,6 +60,7 @@ export function serializedConfigToString(
export function printConfig(ctl: Ctl, config: lib.ConfigSchema, note = (name: string) => "") {
ctl.output.result(config, () => {
for (let [name, value] of Object.entries(config)) {
// Shown as an (inherited) note on each field by instance config list instead
if (name !== "instance.inherited_fields") {
print(`${name} ${JSON.stringify(value)}${note(name)}`);
}