Add --output json to clusterioctl

Commands print their results through a CommandOutput on the ctl link.
In json mode lists print as arrays of objects, other results as an
object, commands without a result print {} and failures print
{ error: ClassName, message } with exit code 1. log follow and
debug dump-ws print JSON lines.

Human output now goes through the shared asTable printer in every
command, results that were logged to stderr (role create, save and mod
upload/download) print to stdout, and config edit failures are logged
instead of printed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bbassieandClaude Opus 5.5 committed 2026-11-18 13:07:18 +00:00
1 parent 35f9609865
commit 10beffe167
23 files changed
+642 -269

No files matched your search

+15
View File
@@ -8,6 +8,21 @@ Before `clusterioctl` can be used it needs to be configured for the cluster it w
The easiest way to do this is to run `npx clusteriocontroller bootstrap create-ctl-config <username>` on the controller, which creates the necessary `config-ctl.json` for managing the cluster as the given user.
## Output Format
ctl> --output json <command>
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 `{}`.
If the command fails it prints `{"error": "<ClassName>", "message": "<message>"}` and exits with a non-zero exit code.
Log messages are written to stderr in both formats.
`log follow` and `debug dump-ws` keep running and print one JSON object per line as entries arrive.
`instance start-all` and `instance stop-all` print an array with an entry per instance, which has an `error` property if that instance failed to start or stop.
The default is `--output human`.
## Hosts
### List hosts
+13
View File
@@ -972,6 +972,19 @@ For a command the `definition` is the arguments to pass to [yargs.command](http:
The `handler` is an async function that's invoked when the command is executed and it's passed the parsed command line arguments and a reference to the `Ctl` class of clusterioctl.
Note that messages sent from clusterioctl needs to have `"control"` as a part of `src` for it to be accepted by the controller, see [Defining Link Messages](#defining-link-messages) for how to define the messages that can be sent to the controller.
Commands print their results through `ctl.output` so that `--output json` works for them:
```js
handler: async function(args, ctl) {
const result = await ctl.sendTo("controller", new messages.FrobnicateRequest(args.type));
ctl.output.result(result, () => console.log(`Frobnicated ${result.count} foos`));
},
```
`ctl.output.result(data, human)` prints `data` as JSON in json mode and calls `human` otherwise.
`ctl.output.table(rows)` prints an array of objects as a table or as a JSON array.
Commands that print nothing get `{}` printed for them in json mode, and errors thrown from the handler are printed as `{"error": "<ClassName>", "message": "<message>"}`.
To have the command tree become part of clusterioctl it needs to be added to the rootCommand tree in the `addCommands` hook of the ctl entrypoint:
```js
+5
View File
@@ -23,6 +23,11 @@ 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.
Defaults to `human`.
See [Output format](/docs/managing-a-cluster.md#output-format) for what `json` prints.
The `plugin` and `config` commands described below always print human readable text.
### `plugin <command>`
+61 -11
View File
@@ -17,6 +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";
/**
@@ -55,6 +56,8 @@ export class Ctl extends lib.Link {
config: lib.CtlConfig;
/** Keep the control connection alive after the command completes. */
keepOpen = false;
/** Output of the command being run. */
output = new CommandOutput();
constructor(
connector: CtlConnector,
@@ -82,12 +85,19 @@ export class Ctl extends lib.Link {
}
async handleLogMessageEvent(event: lib.LogMessageEvent) {
logger.log(event.info as any);
if (this.output.json && this.output.streaming) {
this.output.result(event.info);
} else {
logger.log(event.info as any);
}
}
async handleDebugWsMessageEvent(event: lib.DebugWsMessageEvent) {
// eslint-disable-next-line no-console
console.log("WS", event.direction, event.content);
this.output.result(
{ direction: event.direction, content: event.content },
// eslint-disable-next-line no-console
() => console.log("WS", event.direction, event.content),
);
}
async shutdown() {
@@ -126,6 +136,7 @@ interface CtlArguments {
$0: string,
_: (string | number)[],
logLevel: keyof typeof levels,
output: OutputFormat,
config: string,
pluginList: string,
bypassLockFile: boolean,
@@ -165,6 +176,13 @@ export async function initialize(
choices: Object.keys(levels),
type: "string",
})
.option("output", {
nargs: 1,
describe: "Format to print command results in",
default: "human",
choices: outputFormats,
type: "string",
})
.option("config", {
nargs: 1,
describe: "config file to get credentails from",
@@ -260,19 +278,39 @@ export function selectTargetCommand(args: CtlArguments, rootCommands: lib.Comman
return targetCommand;
}
async function startCtl() {
/**
* Run the command selected by args, printing results in the format given by args.output
*/
export async function runCommand(
args: CtlArguments,
rootCommands: lib.CommandTree,
link: lib.Link & { output?: CommandOutput },
) {
link.output = new CommandOutput(args.output);
const targetCommand = selectTargetCommand(args, rootCommands);
await targetCommand.run(args, link);
link.output.finish();
}
async function startCtl(output: CommandOutput) {
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")) {
logger.error("Missing URL and/or token to connect with. See README.md for setting up access.");
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);
}
process.exitCode = 1;
return;
}
@@ -298,12 +336,20 @@ async function startCtl() {
process.on("SIGTERM", lib.createShutdownGuard(logger, "termination", ctl.shutdown.bind(ctl)));
try {
const targetCommand = selectTargetCommand(args, rootCommands);
await targetCommand.run(args, ctl);
await runCommand(args, rootCommands, ctl);
} catch (err) {
ctl.keepOpen = false;
if (err instanceof lib.CommandError) {
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) {
logger.error(`Error running command: ${err.message}`);
process.exitCode = 1;
@@ -327,7 +373,13 @@ async function startCtl() {
}
export function bootstrap() {
startCtl().catch(err => {
const output = new CommandOutput();
startCtl(output).catch(err => {
process.exitCode = 1;
if (output.json) {
output.error(err);
return;
}
if (err.errors) {
logger.fatal(JSON.stringify(err.errors, null, "\t"));
}
@@ -347,8 +399,6 @@ ${err.stack}`
${err.stack}`
);
}
process.exitCode = 1;
});
}
+1
View File
@@ -1,5 +1,6 @@
import { bootstrap } from "./ctl.js";
export * from "./ctl.js";
export { CommandOutput, type OutputFormat } from "./src/command_ops.js";
export { BaseCtlPlugin, CtlHooks, type CtlPluginContext } from "./src/BaseCtlPlugin.js";
if (import.meta.main) {
+81
View File
@@ -13,3 +13,84 @@ function formatCell(value: unknown) {
}
export const asTable = asTableModule.configure({ delimiter: " | ", print: formatCell });
/** Convert class instances, Sets and Maps into plain JSON values, ignoring wire format toJSON methods */
export function toPlain(value: unknown): unknown {
if (value instanceof Set || value instanceof Array) {
return [...value].map(toPlain);
}
if (value instanceof Map) {
return Object.fromEntries([...value].map(([key, entry]) => [key, toPlain(entry)]));
}
if (value instanceof Date) {
return value.toISOString();
}
if (typeof value === "object" && value !== null) {
return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, toPlain(entry)]));
}
return value;
}
/** Describe an error as `{ error: ClassName, message: string }` */
export function errorToJson(err: unknown) {
if (err instanceof Error) {
return { error: err.constructor.name, message: err.message };
}
return { error: "Error", message: String(err) };
}
export const outputFormats = ["human", "json"] 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.
*/
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;
constructor(
public format: OutputFormat = "human",
) { }
get json() {
return this.format === "json";
}
/**
* Print the result of a command
*
* @param data - Printed as JSON in json 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) {
print(JSON.stringify(toPlain(data)));
} else {
human();
}
}
/** Print a list of objects as a table, or as an array in json mode */
table(rows: object[]) {
this.result(rows, () => print(asTable(rows)));
}
/** Print an error as `{ "error": ClassName, "message": string }` */
error(err: unknown) {
this.written = true;
print(JSON.stringify(errorToJson(err)));
}
/** Print `{}` in json mode for commands that finished without printing a result */
finish() {
if (this.json && !this.written && !this.streaming) {
this.result({});
}
}
}
+25 -26
View File
@@ -1,15 +1,15 @@
import fs from "node:fs/promises";
import asTableModule from "as-table";
import events from "events";
import os from "os";
import child_process from "child_process";
import * as lib from "@clusterio/lib";
import { logger } from "@clusterio/lib";
import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js";
import { serializedConfigToString, getEditor, configToKeyVal } from "./config_ops.js";
const asTable = asTableModule.configure({ delimiter: " | " });
import { asTable, print } from "./command_ops.js";
import {
serializedConfigToString, getEditor, configToKeyVal, printConfig, printRestartRequired,
} from "./config_ops.js";
export const controllerCommands = new lib.CommandTree({ name: "controller", description: "Controller management" });
controllerCommands.add(new lib.Command({
@@ -44,9 +44,8 @@ controllerCommands.add(new lib.Command({
}
if (args.restart) {
await ctl.send(new lib.ControllerRestartRequest());
} else {
print("Controller updated; a restart is required to apply the changes.");
}
printRestartRequired(ctl, !args.restart, "Controller updated");
},
}));
@@ -57,11 +56,7 @@ const controllerConfigCommands = new lib.CommandTree({
controllerConfigCommands.add(new lib.Command({
definition: ["list", "List controller configuration"],
handler: async function(args: object, ctl: Ctl) {
let config = await ctl.send(new lib.ControllerConfigGetRequest());
for (let [name, value] of Object.entries(config)) {
print(`${name} ${JSON.stringify(value)}`);
}
printConfig(ctl, await ctl.send(new lib.ControllerConfigGetRequest()));
},
}));
@@ -146,19 +141,22 @@ controllerConfigCommands.add(new lib.Command({
index,
final[index],
));
} catch (err) {
// eslint-disable-next-line
print(`Attempt to set ${index} to ${final[index] || String(null)} failed; set back to previous value.`);
print(err);
} catch (err: any) {
// If the string is empty, it's better to just print "" instead of nothing
logger.error(
`Attempt to set ${index} to ${final[index] || String(null)} failed; ` +
`set back to previous value: ${err.message}`
);
}
}
}
try {
await fs.unlink(tmpFile);
} catch (err) {
print("err: temporary file", tmpFile, "could not be deleted.");
print("This is not fatal, but they may build up over time if the issue persists.");
logger.warn(
`Temporary file ${tmpFile} could not be deleted. ` +
"This is not fatal, but they may build up over time if the issue persists."
);
}
},
}));
@@ -175,7 +173,7 @@ controllerPluginCommands.add(new lib.Command({
let url = new URL(ctl.config.get("ctl.controller_url")!);
url.pathname += "api/plugins";
let response = await fetch(url);
print(asTable(await response.json() as []));
ctl.output.table(await response.json() as object[]);
},
}));
controllerPluginCommands.add(new lib.Command({
@@ -187,9 +185,8 @@ controllerPluginCommands.add(new lib.Command({
await ctl.sendTo("controller", new lib.PluginUpdateRequest(args.plugin));
if (args.restart) {
await ctl.send(new lib.ControllerRestartRequest());
} else {
print("Plugin updated; a restart is required to apply the changes.");
}
printRestartRequired(ctl, !args.restart, "Plugin updated");
},
}));
controllerPluginCommands.add(new lib.Command({
@@ -202,13 +199,16 @@ controllerPluginCommands.add(new lib.Command({
const response = await ctl.sendTo(
"controller", new lib.PluginSearchRequest(args.query, args.page, args.pageSize)
);
print(asTable(response.results.map(plugin => ({
const results = response.results.map(plugin => ({
name: plugin.name,
version: plugin.version,
publisher: plugin.publisher ?? "",
description: plugin.description ?? "",
}))));
print(`Showing ${response.results.length} of ${response.total} results`);
}));
ctl.output.result({ total: response.total, results }, () => {
print(asTable(results));
print(`Showing ${results.length} of ${response.total} results`);
});
},
}));
controllerPluginCommands.add(new lib.Command({
@@ -220,9 +220,8 @@ controllerPluginCommands.add(new lib.Command({
await ctl.sendTo("controller", new lib.PluginInstallRequest(args.plugin));
if (args.restart) {
await ctl.send(new lib.ControllerRestartRequest());
} else {
print("Plugin installed; a restart is required to apply the changes.");
}
printRestartRequired(ctl, !args.restart, "Plugin installed");
},
}));
+3 -7
View File
@@ -1,5 +1,6 @@
import * as lib from "@clusterio/lib";
import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js";
export const debugCommands = new lib.CommandTree({ name: "debug", description: "Debugging utilities" });
debugCommands.add(new lib.Command({
@@ -7,6 +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;
},
}));
@@ -20,12 +22,6 @@ debugCommands.add(new lib.Command({
}],
handler: async function(args: { exchangeString: string, pretty: boolean }, ctl: Ctl) {
const result = lib.readMapExchangeString(args.exchangeString);
if (args.pretty) {
// eslint-disable-next-line no-console
console.log(JSON.stringify(result, null, 2));
} else {
// eslint-disable-next-line no-console
console.log(JSON.stringify(result));
}
ctl.output.result(result, () => print(JSON.stringify(result, null, args.pretty ? 2 : undefined)));
},
}));
+38 -38
View File
@@ -1,15 +1,15 @@
import fs from "node:fs/promises";
import asTableModule from "as-table";
import events from "events";
import os from "os";
import child_process from "child_process";
import * as lib from "@clusterio/lib";
import { logger } from "@clusterio/lib";
import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js";
import { serializedConfigToString, getEditor, configToKeyVal } from "./config_ops.js";
const asTable = asTableModule.configure({ delimiter: " | " });
import { asTable, print } from "./command_ops.js";
import {
serializedConfigToString, getEditor, configToKeyVal, printConfig, printRestartRequired,
} from "./config_ops.js";
export const hostCommands = new lib.CommandTree({ name: "host", description: "Host management" });
hostCommands.add(new lib.Command({
@@ -45,8 +45,7 @@ hostCommands.add(new lib.Command({
hostCommands.add(new lib.Command({
definition: [["list", "l"], "List hosts connected to the controller"],
handler: async function(args: object, ctl: Ctl) {
let hosts = await ctl.send(new lib.HostListRequest());
print(asTable(hosts));
ctl.output.table(await ctl.send(new lib.HostListRequest()));
},
}));
@@ -71,17 +70,19 @@ hostCommands.add(new lib.Command({
definition: ["pending", "List host installers waiting for approval"],
handler: async function(args: object, ctl: Ctl) {
let requests = await ctl.send(new lib.HostPairingListRequest());
if (!requests.length) {
print("No pending host requests");
return;
}
let now = Date.now();
print(asTable(requests.map(request => ({
code: request.code,
name: request.name,
address: request.remoteAddress,
age: formatAge(now - request.createdAtMs),
}))));
ctl.output.result(requests, () => {
if (!requests.length) {
print("No pending host requests");
return;
}
let now = Date.now();
print(asTable(requests.map(request => ({
code: request.code,
name: request.name,
address: request.remoteAddress,
age: formatAge(now - request.createdAtMs),
}))));
});
},
}));
@@ -99,7 +100,10 @@ hostCommands.add(new lib.Command({
name = requests.find(request => plainCode(request.code) === plainCode(args.code))?.name;
}
let hostId = await ctl.send(new lib.HostPairingApproveRequest(args.code, args.name));
print(name ? `Approved host ${name} with id ${hostId}` : `Approved host with id ${hostId}`);
ctl.output.result(
{ id: hostId, name },
() => print(name ? `Approved host ${name} with id ${hostId}` : `Approved host with id ${hostId}`),
);
},
}));
@@ -137,9 +141,8 @@ hostCommands.add(new lib.Command({
}
if (args.restart) {
await ctl.sendTo({ hostId }, new lib.HostRestartRequest());
} else {
print("Host updated; a restart is required to apply the changes.");
}
printRestartRequired(ctl, !args.restart, "Host updated");
},
}));
@@ -153,11 +156,7 @@ hostConfigCommands.add(new lib.Command({
}],
handler: async function(args: { host: string }, ctl: Ctl) {
let hostId = await lib.resolveHost(ctl, args.host);
let config = await ctl.sendTo({ hostId }, new lib.HostConfigGetRequest());
for (let [name, value] of Object.entries(config)) {
print(`${name} ${JSON.stringify(value)}`);
}
printConfig(ctl, await ctl.sendTo({ hostId }, new lib.HostConfigGetRequest()));
},
}));
@@ -255,19 +254,22 @@ hostConfigCommands.add(new lib.Command({
index,
final[index],
));
} catch (err) {
// eslint-disable-next-line
print(`Attempt to set ${index} to ${final[index] || String(null)} failed; set back to previous value.`);
} catch (err: any) {
// If the string is empty, it's better to just print "" instead of nothing
print(err);
logger.error(
`Attempt to set ${index} to ${final[index] || String(null)} failed; ` +
`set back to previous value: ${err.message}`
);
}
}
}
try {
await fs.unlink(tmpFile);
} catch (err) {
print("err: temporary file", tmpFile, "could not be deleted.");
print("This is not fatal, but they may build up over time if the issue persists.");
logger.warn(
`Temporary file ${tmpFile} could not be deleted. ` +
"This is not fatal, but they may build up over time if the issue persists."
);
}
},
}));
@@ -285,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());
print(asTable(plugins.map(p => ({
ctl.output.table(plugins.map(p => ({
title: p.title, version: p.version, state: p.state, npmPackage: p.npmPackage,
}))));
})));
},
}));
hostPluginCommands.add(new lib.Command({
@@ -301,9 +303,8 @@ hostPluginCommands.add(new lib.Command({
await ctl.sendTo({ hostId }, new lib.PluginUpdateRequest(args.plugin));
if (args.restart) {
await ctl.sendTo({ hostId }, new lib.HostRestartRequest());
} else {
print("Plugin updated; a restart is required to apply the changes.");
}
printRestartRequired(ctl, !args.restart, "Plugin updated");
},
}));
hostPluginCommands.add(new lib.Command({
@@ -317,9 +318,8 @@ hostPluginCommands.add(new lib.Command({
await ctl.sendTo({ hostId }, new lib.PluginInstallRequest(args.plugin));
if (args.restart) {
await ctl.sendTo({ hostId }, new lib.HostRestartRequest());
} else {
print("Plugin installed; a restart is required to apply the changes.");
}
printRestartRequired(ctl, !args.restart, "Plugin installed");
},
}));
hostCommands.add(hostPluginCommands);
+71 -52
View File
@@ -1,5 +1,4 @@
import fs from "node:fs/promises";
import asTableModule from "as-table";
import events from "events";
import path from "path";
import os from "os";
@@ -10,10 +9,9 @@ import util from "util";
import * as lib from "@clusterio/lib";
import { logger } from "@clusterio/lib";
import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js";
import { serializedConfigToString, getEditor, configToKeyVal } from "./config_ops.js";
import { asTable, errorToJson, print } from "./command_ops.js";
import { serializedConfigToString, getEditor, configToKeyVal, printConfig } from "./config_ops.js";
const asTable = asTableModule.configure({ delimiter: " | " });
const finished = util.promisify(stream.finished);
export const instanceCommands = new lib.CommandTree({
@@ -27,7 +25,7 @@ instanceCommands.add(new lib.Command({
}],
handler: async function(args: { templates: boolean }, ctl: Ctl) {
let list = await ctl.send(new lib.InstanceDetailsListRequest());
print(asTable(list.filter(instance => args.templates || !instance.isTemplate)));
ctl.output.table(list.filter(instance => args.templates || !instance.isTemplate));
},
}));
@@ -64,6 +62,7 @@ instanceCommands.add(new lib.Command({
instanceConfig.toRemote("controller", fields),
args.from
));
ctl.output.result({ id: instanceConfig.get("instance.id") }, () => {});
},
}));
@@ -81,19 +80,13 @@ instanceConfigCommands.add(new lib.Command({
? config["instance.inherited_fields"] as Record<string, true | string[]> ?? {}
: {};
for (let [name, value] of Object.entries(config)) {
if (name === "instance.inherited_fields") {
continue;
}
printConfig(ctl, config, name => {
const entry = inherited[name];
let note = "";
if (entry instanceof Array && entry.length) {
note = ` (inherited except ${entry.join(", ")})`;
} else if (entry) {
note = " (inherited)";
return ` (inherited except ${entry.join(", ")})`;
}
print(`${name} ${JSON.stringify(value)}${note}`);
}
return entry ? " (inherited)" : "";
});
},
}));
@@ -225,19 +218,22 @@ instanceConfigCommands.add(new lib.Command({
index,
final[index],
));
} catch (err) {
// eslint-disable-next-line
print(`Attempt to set ${index} to ${final[index] || String(null)} failed; set back to previous value.`);
} catch (err: any) {
// If the string is empty, it's better to just print "" instead of nothing
print(err);
logger.error(
`Attempt to set ${index} to ${final[index] || String(null)} failed; ` +
`set back to previous value: ${err.message}`
);
}
}
}
try {
await fs.unlink(tmpFile);
} catch (err) {
print("err: temporary file", tmpFile, "could not be deleted.");
print("This is not fatal, but they may build up over time if the issue persists.");
logger.warn(
`Temporary file ${tmpFile} could not be deleted. ` +
"This is not fatal, but they may build up over time if the issue persists."
);
}
},
}));
@@ -291,9 +287,9 @@ 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);
print(asTable(saves.map(
ctl.output.result(saves, () => print(asTable(saves.map(
({ mtimeMs, ...rest }) => ({ ...rest, mtime: new Date(mtimeMs).toLocaleString() })
)));
))));
},
}));
@@ -394,13 +390,16 @@ instanceSaveCommands.add(new lib.Command({
logger.error(requestError);
}
if (result.saves && result.saves.length) {
logger.info(`Successfully uploaded as ${result.saves[0]}`);
}
if ((result.errors || []).length || (result.request_errors || []).length) {
throw new lib.CommandError("Uploading save failed");
}
const name = result.saves?.[0];
ctl.output.result({ name }, () => {
if (name) {
print(`Successfully uploaded as ${name}`);
}
});
},
}));
@@ -439,7 +438,10 @@ instanceSaveCommands.add(new lib.Command({
args.copy
)
);
print(`Transferred as ${storedName} to ${args.targetInstance}.`);
ctl.output.result(
{ name: storedName, instanceId: targetInstanceId },
() => print(`Transferred as ${storedName} to ${args.targetInstance}.`),
);
},
}));
@@ -456,7 +458,10 @@ instanceSaveCommands.add(new lib.Command({
url.pathname += `api/stream/${streamId}`;
const filename = await lib.downloadFile(url, args.save, "rename");
logger.info(`Downloaded ${args.save}${args.save === filename ? "" : ` as ${filename}`}`);
ctl.output.result(
{ filename },
() => print(`Downloaded ${args.save}${args.save === filename ? "" : ` as ${filename}`}`),
);
},
}));
@@ -566,27 +571,34 @@ instanceCommands.add(new lib.Command({
});
if (instancesToStart.length === 0) {
print("No instances to start.");
ctl.output.result([], () => print("No instances to start."));
return;
}
print(`Starting ${instancesToStart.length} instance(s):`);
for (const instance of instancesToStart) {
print(` - ${instance.name} (ID: ${instance.id})`);
const human = !ctl.output.json;
if (human) {
print(`Starting ${instancesToStart.length} instance(s):`);
for (const instance of instancesToStart) {
print(` - ${instance.name} (ID: ${instance.id})`);
}
}
// Start all filtered instances
const startPromises = instancesToStart.map(async (instance: lib.InstanceDetails) => {
const results = await Promise.all(instancesToStart.map(async (instance: lib.InstanceDetails) => {
try {
await ctl.sendTo({ instanceId: instance.id }, new lib.InstanceStartRequest());
print(`✓ Started ${instance.name}`);
if (human) {
print(`✓ Started ${instance.name}`);
}
return { id: instance.id, name: instance.name };
} catch (error) {
print(`✗ Failed to start ${instance.name}: ${error}`);
if (human) {
print(`✗ Failed to start ${instance.name}: ${error}`);
}
return { id: instance.id, name: instance.name, error: errorToJson(error) };
}
});
await Promise.all(startPromises);
print("Start all operation completed.");
}));
ctl.output.result(results, () => print("Start all operation completed."));
},
}));
@@ -646,27 +658,34 @@ instanceCommands.add(new lib.Command({
.filter((instance: lib.InstanceDetails) => ["starting", "running"].includes(instance.status));
if (instancesToStop.length === 0) {
print("No instances to stop.");
ctl.output.result([], () => print("No instances to stop."));
return;
}
print(`Stopping ${instancesToStop.length} instance(s):`);
for (const instance of instancesToStop) {
print(` - ${instance.name} (ID: ${instance.id})`);
const human = !ctl.output.json;
if (human) {
print(`Stopping ${instancesToStop.length} instance(s):`);
for (const instance of instancesToStop) {
print(` - ${instance.name} (ID: ${instance.id})`);
}
}
// Stop all filtered instances
const stopPromises = instancesToStop.map(async (instance: lib.InstanceDetails) => {
const results = await Promise.all(instancesToStop.map(async (instance: lib.InstanceDetails) => {
try {
await ctl.sendTo({ instanceId: instance.id }, new lib.InstanceStopRequest());
print(`✓ Stopped ${instance.name}`);
if (human) {
print(`✓ Stopped ${instance.name}`);
}
return { id: instance.id, name: instance.name };
} catch (error) {
print(`✗ Failed to stop ${instance.name}: ${error}`);
if (human) {
print(`✗ Failed to stop ${instance.name}: ${error}`);
}
return { id: instance.id, name: instance.name, error: errorToJson(error) };
}
});
await Promise.all(stopPromises);
print("Stop all operation completed.");
}));
ctl.output.result(results, () => print("Stop all operation completed."));
},
}));
@@ -703,6 +722,6 @@ instanceCommands.add(new lib.Command({
);
// Factorio includes a newline in its response output.
process.stdout.write(result);
ctl.output.result({ result }, () => process.stdout.write(result));
},
}));
+13 -10
View File
@@ -27,6 +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;
},
}));
@@ -75,16 +76,18 @@ logCommands.add(new lib.Command({
result.log.reverse();
}
let stdoutLogger = winston.createLogger({
level: "verbose",
levels,
format: new lib.TerminalFormat({ showTimestamp: true }),
transports: [
new ConsoleTransport({ errorLevels: [], warnLevels: [] }),
],
ctl.output.result(result.log, () => {
let stdoutLogger = winston.createLogger({
level: "verbose",
levels,
format: new lib.TerminalFormat({ showTimestamp: true }),
transports: [
new ConsoleTransport({ errorLevels: [], warnLevels: [] }),
],
});
for (let info of result.log) {
stdoutLogger.log(info as any);
}
});
for (let info of result.log) {
stdoutLogger.log(info as any);
}
},
}));
+33 -24
View File
@@ -1,5 +1,4 @@
import fs from "node:fs/promises";
import asTableModule from "as-table";
import events from "events";
import path from "path";
import stream from "stream";
@@ -8,9 +7,7 @@ import util from "util";
import * as lib from "@clusterio/lib";
import { logger } from "@clusterio/lib";
import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js";
const asTable = asTableModule.configure({ delimiter: " | " });
import { asTable, print } from "./command_ops.js";
const finished = util.promisify(stream.finished);
export const modCommands = new lib.CommandTree({ name: "mod", description: "Manage uploaded mods" });
@@ -24,16 +21,18 @@ modCommands.add(new lib.Command({
throw new lib.CommandError("mod-version must match format digit.digit.digit");
}
let modInfo = await ctl.send(new lib.ModGetRequest(args.name, args.modVersion));
for (let [field, value] of Object.entries(modInfo)) {
if (value instanceof Array) {
print(`${field}:`);
for (let entry of value) {
print(` ${entry}`);
ctl.output.result(modInfo, () => {
for (let [field, value] of Object.entries(modInfo)) {
if (value instanceof Array) {
print(`${field}:`);
for (let entry of value) {
print(` ${entry}`);
}
} else {
print(`${field}: ${value}`);
}
} else {
print(`${field}: ${value}`);
}
}
});
},
}));
@@ -60,7 +59,7 @@ modCommands.add(new lib.Command({
}
}
}
print(asTable(mods));
ctl.output.table(mods);
},
}));
@@ -131,11 +130,19 @@ modCommands.add(new lib.Command({
}
}
}
for (let issue of response.queryIssues) {
print(issue);
}
print(`page ${args.page} of ${response.pageCount} (${response.resultCount} results)`);
print(asTable(results));
ctl.output.result({
page: args.page,
pageCount: response.pageCount,
resultCount: response.resultCount,
queryIssues: response.queryIssues,
results,
}, () => {
for (let issue of response.queryIssues) {
print(issue);
}
print(`page ${args.page} of ${response.pageCount} (${response.resultCount} results)`);
print(asTable(results));
});
},
}));
@@ -174,14 +181,16 @@ modCommands.add(new lib.Command({
logger.error(requestError);
}
if (result.mods && result.mods.length) {
const mod = lib.ModInfo.fromJSON(result.mods[0]);
logger.info(`Successfully uploaded ${mod.filename}`);
}
if ((result.errors || []).length || (result.request_errors || []).length) {
throw new lib.CommandError("Uploading mod failed");
}
const uploaded = result.mods?.length ? lib.ModInfo.fromJSON(result.mods[0]).filename : undefined;
ctl.output.result({ filename: uploaded }, () => {
if (uploaded) {
print(`Successfully uploaded ${uploaded}`);
}
});
},
}));
@@ -201,7 +210,7 @@ modCommands.add(new lib.Command({
let filename = `${args.name}_${args.modVersion}.zip`;
await lib.downloadFile(url, filename, "overwrite");
logger.info(`Downloaded ${filename}`);
ctl.output.result({ filename }, () => print(`Downloaded ${filename}`));
},
}));
+48 -41
View File
@@ -1,12 +1,8 @@
import asTableModule from "as-table";
import * as lib from "@clusterio/lib";
import { logger } from "@clusterio/lib";
import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js";
const asTable = asTableModule.configure({ delimiter: " | " });
export const modPackCommands = new lib.CommandTree({ name: "mod-pack", description: "Mod Pack" });
modPackCommands.add(new lib.Command({
definition: ["show <mod-pack>", "Show details of mod pack", (yargs) => {
@@ -19,42 +15,45 @@ modPackCommands.add(new lib.Command({
let modPack = await ctl.send(
new lib.ModPackGetRequest(await lib.resolveModPack(ctl, args.modPack))
);
for (let [field, value] of Object.entries(modPack)) {
if (field === "mods") {
print(`${field}:`);
for (let [name, entry] of value) {
const mod = mods.get(`${name}_${entry.version}`);
const missing = !mod && "? ";
const badChecksum = mod && entry.sha1 && entry.sha1 !== mod.sha1 && "! ";
const warn = missing || badChecksum || "";
const enabled = entry.enabled ? "" : "(disabled) ";
print(` ${warn}${enabled}${name} ${entry.version}${entry.sha1 ? ` (${entry.sha1})` : ""}`);
}
} else if (field === "settings") {
print(`${field}:`);
for (let [scope, settings] of Object.entries(value)) {
print(` ${scope}:`);
for (let [setting, settingValue] of settings as any) {
print(` ${setting}: ${JSON.stringify(settingValue.value)}`);
}
}
} else if (field === "exportManifest") {
print(`${field}:`);
if (value && value.assets) {
print(" assets:");
for (let [name, fileName] of Object.entries(value.assets)) {
print(` ${name}: ${fileName}`);
}
}
} else {
print(`${field}: ${value}`);
}
}
ctl.output.result(modPack, () => printModPack(modPack, mods));
},
}));
function printModPack(modPack: lib.ModPack, mods: Map<string, lib.ModInfo>) {
for (let [field, value] of Object.entries(modPack)) {
if (field === "mods") {
print(`${field}:`);
for (let [name, entry] of value) {
const mod = mods.get(`${name}_${entry.version}`);
const missing = !mod && "? ";
const badChecksum = mod && entry.sha1 && entry.sha1 !== mod.sha1 && "! ";
const warn = missing || badChecksum || "";
const enabled = entry.enabled ? "" : "(disabled) ";
print(` ${warn}${enabled}${name} ${entry.version}${entry.sha1 ? ` (${entry.sha1})` : ""}`);
}
} else if (field === "settings") {
print(`${field}:`);
for (let [scope, settings] of Object.entries(value)) {
print(` ${scope}:`);
for (let [setting, settingValue] of settings as any) {
print(` ${setting}: ${JSON.stringify(settingValue.value)}`);
}
}
} else if (field === "exportManifest") {
print(`${field}:`);
if (value && value.assets) {
print(" assets:");
for (let [name, fileName] of Object.entries(value.assets)) {
print(` ${name}: ${fileName}`);
}
}
} else {
print(`${field}: ${value}`);
}
}
}
modPackCommands.add(new lib.Command({
definition: [["list", "l"], "List mod packs in the cluster"],
handler: async function(args: object, ctl: Ctl) {
@@ -68,7 +67,7 @@ modPackCommands.add(new lib.Command({
}
}
}
print(asTable(modPacks));
ctl.output.table(modPacks);
},
}));
@@ -194,10 +193,17 @@ modPackCommands.add(new lib.Command({
setModPackModsEnabled(modPack, args.disabledMods, false);
setModPackSettings(modPack, args);
await ctl.send(new lib.ModPackCreateRequest(modPack));
print(`Created mod pack ${modPack.name} (${modPack.id})`);
printCreated(ctl, modPack);
},
}));
function printCreated(ctl: Ctl, modPack: lib.ModPack) {
ctl.output.result(
{ id: modPack.id, name: modPack.name },
() => print(`Created mod pack ${modPack.name} (${modPack.id})`),
);
}
modPackCommands.add(new lib.Command({
definition: ["import <string>", "Import mod pack string", (yargs) => {
yargs.positional("string", { describe: "Mod pack string to import", type: "string" });
@@ -205,7 +211,7 @@ modPackCommands.add(new lib.Command({
handler: async function(args: { string: string }, ctl: Ctl) {
const modPack = lib.ModPack.fromModPackString(args.string);
await ctl.send(new lib.ModPackCreateRequest(modPack));
print(`Created mod pack ${modPack.name} (${modPack.id})`);
printCreated(ctl, modPack);
},
}));
@@ -217,7 +223,8 @@ modPackCommands.add(new lib.Command({
const modPack = await ctl.send(
new lib.ModPackGetRequest(await lib.resolveModPack(ctl, args.modPack))
);
print(modPack.toModPackString());
const modPackString = modPack.toModPackString();
ctl.output.result({ modPackString }, () => print(modPackString));
},
}));
+3 -7
View File
@@ -1,11 +1,7 @@
import asTableModule from "as-table";
import * as lib from "@clusterio/lib";
import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js";
const asTable = asTableModule.configure({ delimiter: " | " });
export const noteCommands = new lib.CommandTree({
name: "note", description: "Notes attached to hosts, instances, users and other resources",
});
@@ -20,12 +16,12 @@ noteCommands.add(new lib.Command({
if (args.type !== undefined) {
notes = notes.filter(note => note.resourceType === args.type);
}
print(asTable(notes.map(note => ({
ctl.output.table(notes.map(note => ({
type: note.resourceType,
id: note.resourceId,
updatedBy: note.updatedBy,
content: note.content,
}))));
})));
},
}));
@@ -42,7 +38,7 @@ noteCommands.add(new lib.Command({
if (!note) {
throw new lib.CommandError(`No note for ${args.type} ${args.id}`);
}
print(note.content);
ctl.output.result(note, () => print(note.content));
},
}));
+1 -7
View File
@@ -1,16 +1,10 @@
import asTableModule from "as-table";
import * as lib from "@clusterio/lib";
import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js";
const asTable = asTableModule.configure({ delimiter: " | " });
export const permissionCommands = new lib.CommandTree({ name: "permission", description: "Permission inspection" });
permissionCommands.add(new lib.Command({
definition: [["list", "l"], "List permissions in the cluster"],
handler: async function(args: object, ctl: Ctl) {
let permissions = await ctl.send(new lib.PermissionListRequest());
print(asTable(permissions));
ctl.output.table(await ctl.send(new lib.PermissionListRequest()));
},
}));
+3 -5
View File
@@ -1,15 +1,13 @@
import * as lib from "@clusterio/lib";
import { logger } from "@clusterio/lib";
import type { Ctl } from "../ctl.js";
import { asTable, print } from "./command_ops.js";
import { print } from "./command_ops.js";
export const roleCommands = new lib.CommandTree({ name: "role", description: "Role management" });
roleCommands.add(new lib.Command({
definition: [["list", "l"], "List roles in the cluster"],
handler: async function(args: object, ctl: Ctl) {
let roles = await ctl.send(new lib.RoleListRequest());
print(asTable(roles));
ctl.output.table(await ctl.send(new lib.RoleListRequest()));
},
}));
@@ -27,7 +25,7 @@ roleCommands.add(new lib.Command({
args.description,
args.permissions,
));
logger.info(`Created role ID ${id}`);
ctl.output.result({ id }, () => print(`Created role ID ${id}`));
},
}));
+36 -21
View File
@@ -5,6 +5,10 @@ import * as lib from "@clusterio/lib";
import type { Ctl } from "../ctl.js";
import { asTable, print } from "./command_ops.js";
function printProperties(object: object) {
print(asTable(Object.entries(object).map(([property, value]) => ({ property, value }))));
}
export const userCommands = new lib.CommandTree({ name: "user", alias: ["u"], description: "User management" });
userCommands.add(new lib.Command({
definition: ["show <name>", "Show details for one user", (yargs) => {
@@ -21,23 +25,25 @@ userCommands.add(new lib.Command({
let instanceStats = user.instanceStats;
// @ts-expect-error Terrible hack
delete user.instanceStats;
print(asTable(Object.entries(user).map(([property, value]) => ({ property, value }))));
if (args.instanceStats) {
let instances = await ctl.send(new lib.InstanceDetailsListRequest());
function instanceName(id: number) {
let instance = instances.find(i => i.id === id);
if (instance) {
return instance.name;
}
return "<deleted>";
}
for (let [id, playerInstanceStats] of instanceStats || []) {
print();
print(`Instance ${instanceName(id)} (${id}):`);
print(asTable(Object.entries(playerInstanceStats).map(([property, value]) => ({ property, value }))));
}
if (!args.instanceStats) {
ctl.output.result(user, () => printProperties(user));
return;
}
let instances = await ctl.send(new lib.InstanceDetailsListRequest());
const stats = [...instanceStats || []].map(([id, playerInstanceStats]) => ({
id,
name: instances.find(i => i.id === id)?.name ?? "<deleted>",
stats: playerInstanceStats,
}));
ctl.output.result({ ...user, instanceStats: stats }, () => {
printProperties(user);
for (let { id, name, stats: playerInstanceStats } of stats) {
print();
print(`Instance ${name} (${id}):`);
printProperties(playerInstanceStats);
}
});
},
}));
@@ -71,7 +77,7 @@ userCommands.add(new lib.Command({
delete user.isBanned;
}
}
print(asTable(users));
ctl.output.table(users);
},
}));
@@ -219,11 +225,17 @@ async function handleImportOrRestore(args: {
new lib.UserBulkImportRequest(importType, importType === "users" ? data.users : data, restore)
);
print(`${restore ? "Restored" : "Imported"} ${importType} from ${args.filepath}`);
let backupFile: string | undefined;
if (restore && backup && !args.noBackup) {
await fs.writeFile(`${importType}-backup.json`, JSON.stringify(backup, undefined, "\t"));
print(`Wrote backup to ${importType}-backup.json`);
backupFile = `${importType}-backup.json`;
await fs.writeFile(backupFile, JSON.stringify(backup, undefined, "\t"));
}
ctl.output.result({ type: importType, backupFile }, () => {
print(`${restore ? "Restored" : "Imported"} ${importType} from ${args.filepath}`);
if (backupFile) {
print(`Wrote backup to ${backupFile}`);
}
});
}
userCommands.add(new lib.Command({
@@ -296,6 +308,9 @@ userCommands.add(new lib.Command({
await fs.writeFile(args.filepath, JSON.stringify(await ctl.send(
new lib.UserBulkExportRequest(exportType)
), undefined, "\t"));
print(`Exported ${exportType} to ${args.filepath}`);
ctl.output.result(
{ type: exportType, filepath: args.filepath },
() => print(`Exported ${exportType} to ${args.filepath}`),
);
},
}));
+22
View File
@@ -1,4 +1,6 @@
import * as lib from "@clusterio/lib";
import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js";
export async function getEditor(argsEditor: string) {
// eslint-disable-next-line
@@ -53,3 +55,23 @@ export function serializedConfigToString(
}
return allConfigElements;
}
/** Print config fields as `name value` lines, or as an object in json mode */
export function printConfig(ctl: Ctl, config: lib.ConfigSchema, note = (name: string) => "") {
ctl.output.result(config, () => {
for (let [name, value] of Object.entries(config)) {
if (name !== "instance.inherited_fields") {
print(`${name} ${JSON.stringify(value)}${note(name)}`);
}
}
});
}
/** Print whether a restart is still needed after an update or install */
export function printRestartRequired(ctl: Ctl, restartRequired: boolean, action: string) {
ctl.output.result({ restartRequired }, () => {
if (restartRequired) {
print(`${action}; a restart is required to apply the changes.`);
}
});
}
+36 -11
View File
@@ -30,14 +30,20 @@ playerSyncCommands.add(new lib.Command({
handler: async function(args: object, ctl: Ctl) {
let players = await ctl.send(new msg.ListPlayersRequest());
players.sort((a, b) => a.name.localeCompare(b.name));
print("name | generation | size | acquired by");
for (let player of players) {
print(
`${player.name} | ${player.generation ?? "-"} | ` +
`${player.size === undefined ? "-" : lib.formatBytes(player.size)} | ` +
`${await instanceName(ctl, player.instanceId)}`
);
if (ctl.output.json) {
ctl.output.result(players);
return;
}
let rows = [];
for (let player of players) {
rows.push({
name: player.name,
generation: player.generation ?? "-",
size: player.size === undefined ? "-" : lib.formatBytes(player.size),
"acquired by": await instanceName(ctl, player.instanceId),
});
}
ctl.output.table(rows);
},
}));
@@ -47,8 +53,21 @@ playerSyncCommands.add(new lib.Command({
}],
handler: async function(args: { player: string }, ctl: Ctl) {
let response = await ctl.send(new msg.GetPlayerDataRequest(args.player));
print(`acquired by: ${await instanceName(ctl, response.instanceId)}`);
let playerData = response.playerData;
if (ctl.output.json) {
ctl.output.result({
instanceId: response.instanceId,
...playerData && {
generation: playerData.generation,
size: JSON.stringify(playerData).length,
controller: playerData.controller,
force: playerData.force,
inventories: summarizePlayerInventories(playerData),
},
});
return;
}
print(`acquired by: ${await instanceName(ctl, response.instanceId)}`);
if (!playerData) {
print(`No player data stored for ${args.player}`);
return;
@@ -81,9 +100,12 @@ playerSyncCommands.add(new lib.Command({
let content = JSON.stringify(response.playerData, null, "\t");
if (args.file) {
await fs.writeFile(args.file, content);
print(`Wrote player data for ${args.player} to ${args.file}`);
ctl.output.result(
{ file: args.file },
() => print(`Wrote player data for ${args.player} to ${args.file}`),
);
} else {
print(content);
ctl.output.result(response.playerData, () => print(content));
}
},
}));
@@ -101,7 +123,10 @@ playerSyncCommands.add(new lib.Command({
playerData.name = args.player;
playerData.generation ??= 0;
let response = await ctl.send(new msg.SetPlayerDataRequest(args.player, playerData));
print(`Stored player data for ${args.player} as generation ${response.generation}`);
ctl.output.result(
{ generation: response.generation },
() => print(`Stored player data for ${args.player} as generation ${response.generation}`),
);
},
}));
+27 -6
View File
@@ -4,7 +4,7 @@ import os from "node:os";
import path from "node:path";
import * as lib from "@clusterio/lib";
import { CtlHooks } from "@clusterio/ctl";
import { CommandOutput, CtlHooks } from "@clusterio/ctl";
import * as mock from "../../../test/mock.js";
import { testRoundTripJsonSerialisable, testMatrix } from "../../../test/common.js";
@@ -295,6 +295,7 @@ describe("player_sync plugin", function() {
let printed;
let responses;
const ctl = {
output: new CommandOutput(),
async send(message) {
sent.push(message);
const handler = responses.get(message.constructor);
@@ -323,6 +324,7 @@ describe("player_sync plugin", function() {
beforeEach(function() {
sent = [];
printed = [];
ctl.output = new CommandOutput();
responses = new Map([
[lib.InstanceDetailsGetRequest, request => ({ id: request.instanceId, name: "Test" })],
[msg.ListPlayersRequest, () => [
@@ -352,10 +354,12 @@ describe("player_sync plugin", function() {
it("list should print sorted entries", async function() {
await run("list");
assert.deepEqual(printed, [
"name | generation | size | acquired by",
`alice | 2 | ${lib.formatBytes(100)} | -`,
"bob | - | - | Test (1)",
const lines = printed.join("\n").split("\n").map(line => line.trimEnd());
assert.deepEqual(lines, [
"name | generation | size | acquired by",
"--------------------------------------------",
`alice | 2 | ${lib.formatBytes(100)} | -`,
"bob | - | - | Test (1)",
]);
});
it("show should print a summary", async function() {
@@ -376,7 +380,7 @@ describe("player_sync plugin", function() {
throw new lib.PermissionError("Permission denied");
});
await run("list");
assert.equal(printed[2], "bob | - | - | 1");
assert.match(printed[0], /bob +\| - +\| - +\| 1/);
printed = [];
await run("show", { player: "alice" });
assert.equal(printed[0], "acquired by: 1");
@@ -413,6 +417,23 @@ describe("player_sync plugin", function() {
new lib.CommandError("Player data must be a JSON object"),
);
});
it("should print JSON in json mode", async function() {
ctl.output = new CommandOutput("json");
await run("list");
assert.deepEqual(JSON.parse(printed[0]), [
{ name: "alice", generation: 2, size: 100 },
{ name: "bob", instanceId: 1 },
]);
printed = [];
await run("show", { player: "alice" });
const shown = JSON.parse(printed[0]);
assert.equal(shown.instanceId, 1);
assert.equal(shown.generation, 2);
assert.deepEqual(shown.inventories[0].items[0], { name: "wood", count: 5, quality: "rare" });
printed = [];
await run("export", { player: "alice" });
assert.deepEqual(JSON.parse(printed[0]), storedData);
});
it("delete and release should send requests", async function() {
await run("delete", { player: "alice" });
await run("release", { player: "alice" });
+70
View File
@@ -0,0 +1,70 @@
import assert from "node:assert/strict";
import * as lib from "@clusterio/lib";
import { CommandOutput, errorToJson, toPlain } from "@clusterio/ctl/dist/node/src/command_ops.js";
/** Run fn and return the lines it printed with console.log */
function captureLog(fn) {
const lines = [];
const originalLog = console.log; // eslint-disable-line no-console
console.log = (...args) => lines.push(args.join(" ")); // eslint-disable-line no-console
try {
fn();
} finally {
console.log = originalLog; // eslint-disable-line no-console
}
return lines;
}
describe("ctl/command_ops", function() {
describe("toPlain()", function() {
it("converts Sets, Maps and Dates", function() {
assert.deepEqual(
toPlain({ set: new Set([1, 2]), map: new Map([[3, { a: new Set(["b"]) }]]), date: new Date(0) }),
{ set: [1, 2], map: { 3: { a: ["b"] } }, date: "1970-01-01T00:00:00.000Z" },
);
});
it("uses own properties instead of toJSON", function() {
const role = new lib.Role(1, "name", "desc", new Set(["core.admin"]));
assert.deepEqual(toPlain(role).permissions, ["core.admin"]);
});
});
describe("errorToJson()", function() {
it("uses the class name of the error", function() {
assert.deepEqual(errorToJson(new lib.NotFoundError("gone")), { error: "NotFoundError", message: "gone" });
assert.deepEqual(errorToJson("text"), { error: "Error", message: "text" });
});
});
describe("class CommandOutput", function() {
it("calls the human formatter in human mode", function() {
const output = new CommandOutput("human");
const human = () => console.log("human"); // eslint-disable-line no-console
assert.deepEqual(captureLog(() => output.result({ a: 1 }, human)), ["human"]);
assert.deepEqual(captureLog(() => output.finish()), []);
});
it("prints one line of JSON per result in json mode", function() {
const output = new CommandOutput("json");
const lines = captureLog(() => {
output.result({ a: new Set([1]) }, () => assert.fail("called human formatter"));
output.table([{ b: 2 }]);
output.finish();
});
assert.deepEqual(lines, ['{"a":[1]}', '[{"b":2}]']);
});
it("prints {} for commands without a result", function() {
assert.deepEqual(captureLog(() => new CommandOutput("json").finish()), ["{}"]);
const streaming = new CommandOutput("json");
streaming.streaming = 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.finish();
});
assert.deepEqual(lines, ['{"error":"CommandError","message":"failed"}']);
});
});
});
+35
View File
@@ -2317,6 +2317,41 @@ describe("Integration of Clusterio", function() {
});
});
describe("--output json", function() {
it("prints lists as an array of objects", async function() {
const roles = JSON.parse(await execCtlOutput("--output json role list"));
assert.deepEqual(roles.find(role => role.id === 0).permissions, ["core.admin"]);
});
it("prints single results as an object", async function() {
const { id } = JSON.parse(await execCtlOutput("--output json role create json-role"));
const roles = await getControl().send(new lib.RoleListRequest());
assert.equal(roles.find(role => role.id === id)?.name, "json-role");
assert.equal(await execCtlOutput(`--output json role delete ${id}`), "{}");
});
it("prints log queries as an array", async function() {
const log = JSON.parse(await execCtlOutput("--output json log query --controller --limit 1"));
assert.equal(log.length, 1);
assert.equal(typeof log[0].message, "string");
});
it("prints errors as JSON with a non-zero exit code", async function() {
await assert.rejects(
execCtlProcess("--output json instance stop no-such-instance"),
err => {
assert.equal(err.code, 1);
assert.deepEqual(
JSON.parse(err.stdout),
{ error: "CommandError", message: "No instance named no-such-instance" },
);
return true;
},
);
await assert.rejects(
execCtlProcess("--output json user set-admin no-such-user"),
err => JSON.parse(err.stdout).error === "NotFoundError",
);
});
});
describe("user list", function() {
it("prints roles and instances as lists", async function() {
const output = await execCtlOutput("user list");
+2 -3
View File
@@ -10,7 +10,7 @@ import events from "node:events";
import * as lib from "@clusterio/lib";
import { LineSplitter, logger } from "@clusterio/lib";
import { selectTargetCommand, initialize as initializeCtl } from "@clusterio/ctl";
import { runCommand, initialize as initializeCtl } from "@clusterio/ctl";
import { _listFactorioVersions } from "@clusterio/host/dist/node/src/server.js";
import { pairHost } from "@clusterio/host";
@@ -242,8 +242,7 @@ export async function execCtl(command) {
}
control.config = initArgs.ctlConfig;
const targetCommand = selectTargetCommand(initArgs.args, initArgs.rootCommands);
await targetCommand.run(initArgs.args, control);
await runCommand(initArgs.args, initArgs.rootCommands, control);
} finally {
process.chdir("../..");
inExecCtl = false;