Compare commits

..
Author SHA1 Message Date
blacksmith-sh[bot] d2121bcd7a Migrate workflows to Blacksmith 2026-11-20 12:32:37 +00:00
44 changed files with 376 additions and 1113 deletions

No files matched your search

+2 -2
View File
@@ -15,10 +15,10 @@ jobs:
check: check:
# Bot pull requests do not fill in the template. # Bot pull requests do not fill in the template.
if: github.event.pull_request.user.type != 'Bot' if: github.event.pull_request.user.type != 'Bot'
runs-on: ubuntu-latest runs-on: blacksmith-4vcpu-ubuntu-2604
timeout-minutes: 5 timeout-minutes: 5
steps: steps:
- uses: actions/checkout@v7 - uses: useblacksmith/checkout@v1
with: with:
sparse-checkout: scripts sparse-checkout: scripts
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
+2 -2
View File
@@ -15,14 +15,14 @@ on:
jobs: jobs:
changes: changes:
runs-on: ubuntu-latest runs-on: blacksmith-4vcpu-ubuntu-2604
timeout-minutes: 5 timeout-minutes: 5
outputs: outputs:
build_and_test: ${{ steps.syntax.outputs.build_and_test || steps.paths.outputs.code }} build_and_test: ${{ steps.syntax.outputs.build_and_test || steps.paths.outputs.code }}
js_lint: ${{ steps.lint.outputs.js_lint }} js_lint: ${{ steps.lint.outputs.js_lint }}
lua_lint: ${{ steps.lint.outputs.lua_lint }} lua_lint: ${{ steps.lint.outputs.lua_lint }}
steps: steps:
- uses: actions/checkout@v7 - uses: useblacksmith/checkout@v1
with: with:
fetch-depth: 0 fetch-depth: 0
- uses: dorny/paths-filter@v4 - uses: dorny/paths-filter@v4
+2 -2
View File
@@ -18,9 +18,9 @@ jobs:
lint: lint:
needs: changes needs: changes
if: ${{ !cancelled() && needs.changes.outputs.lua_lint != 'false' }} if: ${{ !cancelled() && needs.changes.outputs.lua_lint != 'false' }}
runs-on: ubuntu-latest runs-on: blacksmith-4vcpu-ubuntu-2604
steps: steps:
- uses: actions/checkout@v7 - uses: useblacksmith/checkout@v1
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
with: with:
node-version: lts/* node-version: lts/*
+4 -4
View File
@@ -23,7 +23,7 @@ jobs:
test: test:
needs: changes needs: changes
if: ${{ !cancelled() && needs.changes.outputs.build_and_test != 'false' }} if: ${{ !cancelled() && needs.changes.outputs.build_and_test != 'false' }}
runs-on: ubuntu-latest runs-on: blacksmith-4vcpu-ubuntu-2604
timeout-minutes: 15 timeout-minutes: 15
strategy: strategy:
fail-fast: false fail-fast: false
@@ -89,7 +89,7 @@ jobs:
version-compat: version-compat:
needs: changes needs: changes
if: ${{ !cancelled() && needs.changes.outputs.build_and_test != 'false' }} if: ${{ !cancelled() && needs.changes.outputs.build_and_test != 'false' }}
runs-on: ubuntu-latest runs-on: blacksmith-4vcpu-ubuntu-2604
timeout-minutes: 15 timeout-minutes: 15
env: env:
# npm version spec for the published side of the compatibility test. # npm version spec for the published side of the compatibility test.
@@ -121,7 +121,7 @@ jobs:
lint: lint:
needs: changes needs: changes
if: ${{ !cancelled() && needs.changes.outputs.js_lint != 'false' }} if: ${{ !cancelled() && needs.changes.outputs.js_lint != 'false' }}
runs-on: ubuntu-latest runs-on: blacksmith-4vcpu-ubuntu-2604
timeout-minutes: 5 timeout-minutes: 5
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v7
@@ -134,7 +134,7 @@ jobs:
build: build:
needs: changes needs: changes
if: ${{ !cancelled() && needs.changes.outputs.build_and_test != 'false' }} if: ${{ !cancelled() && needs.changes.outputs.build_and_test != 'false' }}
runs-on: ubuntu-latest runs-on: blacksmith-4vcpu-ubuntu-2604
timeout-minutes: 5 timeout-minutes: 5
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v7
+4 -4
View File
@@ -12,10 +12,10 @@ permissions:
jobs: jobs:
npm: npm:
runs-on: ubuntu-latest runs-on: blacksmith-4vcpu-ubuntu-2604
steps: steps:
- uses: actions/checkout@v7 - uses: useblacksmith/checkout@v1
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
with: with:
@@ -30,10 +30,10 @@ jobs:
files: pnpm-lock.yaml files: pnpm-lock.yaml
factorio: factorio:
runs-on: ubuntu-latest runs-on: blacksmith-4vcpu-ubuntu-2604
steps: steps:
- uses: actions/checkout@v7 - uses: useblacksmith/checkout@v1
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
with: with:
+2 -38
View File
@@ -31,47 +31,11 @@ Many thanks to the following for contributing to this release:
[@username](https://github.com/username) [@username](https://github.com/username)
--> -->
## Version 2.1.1 ## Unreleased
### Features
- Hosts on ARM64 Linux download and run the ARM64 headless build of Factorio, available from Factorio 2.1.18. [#1228](<https://github.com/clusterio/clusterio/pull/1228>)
- Added `requiredMods` to plugin declarations. Instances refuse to start when their mod pack lacks a mod a loaded plugin requires, and the controller downloads missing required mods and their dependencies from the mod portal on start. Subspace Storage requires the subspace_storage mod. [#535](<https://github.com/clusterio/clusterio/issues/535>)
- Added `--output json` and `--output wire` to clusterioctl for machine readable results and errors. [#1230](<https://github.com/clusterio/clusterio/pull/1230>)
### Fixes ### Fixes
- Fixed a newly paired host reporting that it needs a restart. [#1204](<https://github.com/clusterio/clusterio/issues/1204>) - Fixed cramped plugin rows and wrapping header branding on mobile screens.
- Fixed the installer's run-controller and run-host scripts exiting with 0 when the controller or host exited with 8 to stop the restart loop. [#1208](<https://github.com/clusterio/clusterio/issues/1208>)
- Fixed clusterioctl user list, user show and role list printing [object Set] for roles, instances and permissions. [#1205](<https://github.com/clusterio/clusterio/issues/1205>)
- Fixed typo in the delete instance confirmation. [#1209](<https://github.com/clusterio/clusterio/issues/1209>)
- The Search Mod Portal dialog now opens on the default mod pack's Factorio version instead of always 2.0. [#1209](<https://github.com/clusterio/clusterio/issues/1209>)
- Fixed the mod portal cache key logging "undefined" when hide_deprecated was not sent. [#1209](<https://github.com/clusterio/clusterio/issues/1209>)
- Fixed player_sync losing quick bar slots of blueprint library records when a player joins an instance for the first time. [#1219](<https://github.com/clusterio/clusterio/issues/1219>)
- Fixed cramped plugin rows and wrapping header branding on mobile screens. [#1223](<https://github.com/clusterio/clusterio/pull/1223>)
- Fixed player_sync keeping an instance's old copy of a player after the controller refused its upload, which let an instance restarted after a crash overwrite newer player data. [#1218](<https://github.com/clusterio/clusterio/issues/1218>)
### Changes
- Restarting the controller or a host from the web interface now asks for confirmation, and for hosts lists the running instances that will be stopped. [#1207](<https://github.com/clusterio/clusterio/issues/1207>)
- New clusters default controller.default_mod_pack_id to the newest Base Game mod pack, so instances can create saves and start without setting it first. [#1203](<https://github.com/clusterio/clusterio/issues/1203>)
- Output from npm during `plugin install` now goes through the logger. [#1224](<https://github.com/clusterio/clusterio/pull/1224>)
- The controller collects system info, including restart required, right after it starts and when a host connects instead of waiting for the first system metrics interval. [#1227](<https://github.com/clusterio/clusterio/pull/1227>)
- clusterioctl prints all tables with the same formatter and prints command results to stdout instead of the log. [#1230](<https://github.com/clusterio/clusterio/pull/1230>)
- clusterioctl prints "Command ran successfully" for commands that have no other output. [#1230](<https://github.com/clusterio/clusterio/pull/1230>)
### Meta
- Added a CI check that pull request descriptions have a valid changelog section. [#1226](<https://github.com/clusterio/clusterio/pull/1226>)
### Contributors
Many thanks to the following for contributing to this release:
[@bbassie](<https://github.com/bbassie>), [@ILLISIS](<https://github.com/ILLISIS>), [@Danielv123](<https://github.com/Danielv123>)
### Statistics
Commits: 44 Pull Requests: 19 Files Changed: 81 Additions: +2,676 Deletions: -739
## Version 2.1.0 ## Version 2.1.0
-18
View File
@@ -8,24 +8,6 @@ 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. 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 `{"success": true}`.
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 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.
`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`, which prints `Command ran successfully` for commands that have no result.
## Hosts ## Hosts
### List hosts ### List hosts
-14
View File
@@ -995,20 +995,6 @@ 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. 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. 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 and wire mode and calls `human` otherwise.
`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.
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: 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 ```js
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@clusterio/controller", "name": "@clusterio/controller",
"version": "2.1.1", "version": "2.1.0",
"description": "Implementation of Clusterio controller", "description": "Implementation of Clusterio controller",
"homepage": "https://github.com/clusterio/clusterio#readme", "homepage": "https://github.com/clusterio/clusterio#readme",
"author": "Hornwitser <github@hornwitser.no>", "author": "Hornwitser <github@hornwitser.no>",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@clusterio/create", "name": "@clusterio/create",
"version": "2.1.1", "version": "2.1.0",
"description": "Installer for clusterio", "description": "Installer for clusterio",
"homepage": "https://github.com/clusterio/clusterio#readme", "homepage": "https://github.com/clusterio/clusterio#readme",
"author": "Hornwitser <github@hornwitser.no>", "author": "Hornwitser <github@hornwitser.no>",
-5
View File
@@ -23,11 +23,6 @@ Common options:
* `--create-config` If the config file is missing, create a new one and carry on instead of exiting with an error. * `--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. Alternative to the `config create` command.
* `--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` and `wire` print.
The `plugin` and `config` commands described below always print human readable text.
### `plugin <command>` ### `plugin <command>`
+17 -57
View File
@@ -17,7 +17,6 @@ import { ConsoleTransport, levels, logger } from "@clusterio/lib";
import * as commands from "./src/commands.js"; import * as commands from "./src/commands.js";
import { BaseCtlPlugin, CtlHooks } from "./src/BaseCtlPlugin.js"; import { BaseCtlPlugin, CtlHooks } from "./src/BaseCtlPlugin.js";
import { CommandOutput, errorToJson, outputFormats, print, type OutputFormat } from "./src/command_ops.js";
/** /**
@@ -56,8 +55,6 @@ export class Ctl extends lib.Link {
config: lib.CtlConfig; config: lib.CtlConfig;
/** Keep the control connection alive after the command completes. */ /** Keep the control connection alive after the command completes. */
keepOpen = false; keepOpen = false;
/** Output of the command being run. */
output = new CommandOutput();
constructor( constructor(
connector: CtlConnector, connector: CtlConnector,
@@ -85,20 +82,12 @@ export class Ctl extends lib.Link {
} }
async handleLogMessageEvent(event: lib.LogMessageEvent) { async handleLogMessageEvent(event: lib.LogMessageEvent) {
// Only log following commands print log events as results, the rest log them to stderr logger.log(event.info as any);
if (this.output.streamingLog) {
this.output.result(event.info, () => logger.log(event.info as any));
} else {
logger.log(event.info as any);
}
} }
async handleDebugWsMessageEvent(event: lib.DebugWsMessageEvent) { async handleDebugWsMessageEvent(event: lib.DebugWsMessageEvent) {
this.output.result( // eslint-disable-next-line no-console
{ direction: event.direction, content: event.content }, console.log("WS", event.direction, event.content);
// eslint-disable-next-line no-console
() => console.log("WS", event.direction, event.content),
);
} }
async shutdown() { async shutdown() {
@@ -137,7 +126,6 @@ interface CtlArguments {
$0: string, $0: string,
_: (string | number)[], _: (string | number)[],
logLevel: keyof typeof levels, logLevel: keyof typeof levels,
output: OutputFormat,
config: string, config: string,
pluginList: string, pluginList: string,
bypassLockFile: boolean, bypassLockFile: boolean,
@@ -177,13 +165,6 @@ export async function initialize(
choices: Object.keys(levels), choices: Object.keys(levels),
type: "string", type: "string",
}) })
.option("output", {
nargs: 1,
describe: "Format to print command results in",
default: "human",
choices: outputFormats,
type: "string",
})
.option("config", { .option("config", {
nargs: 1, nargs: 1,
describe: "config file to get credentails from", describe: "config file to get credentails from",
@@ -279,20 +260,6 @@ export function selectTargetCommand(args: CtlArguments, rootCommands: lib.Comman
return targetCommand; return targetCommand;
} }
/**
* 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() { async function startCtl() {
const { const {
args, args,
@@ -304,19 +271,10 @@ async function startCtl() {
return; return;
} }
try {
await connectAndRun(args, rootCommands, ctlConfig);
} catch (err) {
if (args.output !== "human") {
print(JSON.stringify(errorToJson(err)));
}
throw err;
}
}
async function connectAndRun(args: CtlArguments, rootCommands: lib.CommandTree, ctlConfig: lib.CtlConfig) {
if (!ctlConfig.get("ctl.controller_url") || !ctlConfig.get("ctl.controller_token")) { 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."); logger.error("Missing URL and/or token to connect with. See README.md for setting up access.");
process.exitCode = 1;
return;
} }
let controlConnector = new CtlConnector( let controlConnector = new CtlConnector(
@@ -340,25 +298,26 @@ async function connectAndRun(args: CtlArguments, rootCommands: lib.CommandTree,
process.on("SIGTERM", lib.createShutdownGuard(logger, "termination", ctl.shutdown.bind(ctl))); process.on("SIGTERM", lib.createShutdownGuard(logger, "termination", ctl.shutdown.bind(ctl)));
try { try {
await runCommand(args, rootCommands, ctl); const targetCommand = selectTargetCommand(args, rootCommands);
await targetCommand.run(args, ctl);
} catch (err) { } catch (err) {
ctl.keepOpen = false; ctl.keepOpen = false;
let message: string;
if (err instanceof lib.CommandError) { if (err instanceof lib.CommandError) {
message = `Error running command: ${err.message}`; logger.error(`Error running command: ${err.message}`);
process.exitCode = 1;
} else if (err instanceof lib.ClientError || err instanceof lib.UnavailableError) { } else if (err instanceof lib.ClientError || err instanceof lib.UnavailableError) {
message = `Error sending request: ${err.message}`; logger.error(`Error sending request: ${err.message}`);
process.exitCode = 1;
} else if (err instanceof lib.ServerError) { } else if (err instanceof lib.ServerError) {
message = `Error sending request:\n${err.stack ?? err.message}`; logger.error(`Error sending request:\n${err.stack ?? err.message}`);
process.exitCode = 1;
} else { } else {
throw err; throw err;
} }
ctl.output.error(err, () => logger.error(message));
process.exitCode = 1;
} finally { } finally {
if (!ctl.keepOpen) { if (!ctl.keepOpen) {
@@ -369,7 +328,6 @@ async function connectAndRun(args: CtlArguments, rootCommands: lib.CommandTree,
export function bootstrap() { export function bootstrap() {
startCtl().catch(err => { startCtl().catch(err => {
process.exitCode = 1;
if (err.errors) { if (err.errors) {
logger.fatal(JSON.stringify(err.errors, null, "\t")); logger.fatal(JSON.stringify(err.errors, null, "\t"));
} }
@@ -382,13 +340,15 @@ export function bootstrap() {
${err.stack}` ${err.stack}`
); );
} else { } else {
logger.fatal(` logger.error(`
+---------------------------------+ +---------------------------------+
| Unable to to start clusterioctl | | Unable to to start clusterioctl |
+---------------------------------+ +---------------------------------+
${err.stack}` ${err.stack}`
); );
} }
process.exitCode = 1;
}); });
} }
-1
View File
@@ -1,6 +1,5 @@
import { bootstrap } from "./ctl.js"; import { bootstrap } from "./ctl.js";
export * 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"; export { BaseCtlPlugin, CtlHooks, type CtlPluginContext } from "./src/BaseCtlPlugin.js";
if (import.meta.main) { if (import.meta.main) {
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@clusterio/ctl", "name": "@clusterio/ctl",
"version": "2.1.1", "version": "2.1.0",
"description": "Clusterio command line management tool", "description": "Clusterio command line management tool",
"homepage": "https://github.com/clusterio/clusterio#readme", "homepage": "https://github.com/clusterio/clusterio#readme",
"author": "Hornwitser <github@hornwitser.no>", "author": "Hornwitser <github@hornwitser.no>",
-117
View File
@@ -13,120 +13,3 @@ function formatCell(value: unknown) {
} }
export const asTable = asTableModule.configure({ delimiter: " | ", print: formatCell }); export const asTable = asTableModule.configure({ delimiter: " | ", print: formatCell });
/** Copy of object with only the given fields, or all of them if fields includes "all" */
export function pickFields(object: object, fields: string[]) {
if (fields.includes("all")) {
return object;
}
return Object.fromEntries(Object.entries(object).filter(([field]) => fields.includes(field)));
}
/** 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) };
}
/** 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 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 */
written = false;
/** Command prints log events as results while it runs and has no final result */
streamingLog = false;
constructor(
public format: OutputFormat = "human",
) { }
get human() {
return this.format === "human";
}
/**
* Print the result of a command
*
* @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.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 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 }` 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;
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.streamingLog) {
this.result({ success: true }, () => print("Command ran successfully"));
}
}
}
+26 -25
View File
@@ -1,15 +1,15 @@
import fs from "node:fs/promises"; import fs from "node:fs/promises";
import asTableModule from "as-table";
import events from "events"; import events from "events";
import os from "os"; import os from "os";
import child_process from "child_process"; import child_process from "child_process";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import { logger } from "@clusterio/lib";
import type { Ctl } from "../ctl.js"; import type { Ctl } from "../ctl.js";
import { asTable, print } from "./command_ops.js"; import { print } from "./command_ops.js";
import { import { serializedConfigToString, getEditor, configToKeyVal } from "./config_ops.js";
serializedConfigToString, getEditor, configToKeyVal, printConfig, printRestartRequired,
} from "./config_ops.js"; const asTable = asTableModule.configure({ delimiter: " | " });
export const controllerCommands = new lib.CommandTree({ name: "controller", description: "Controller management" }); export const controllerCommands = new lib.CommandTree({ name: "controller", description: "Controller management" });
controllerCommands.add(new lib.Command({ controllerCommands.add(new lib.Command({
@@ -44,8 +44,9 @@ controllerCommands.add(new lib.Command({
} }
if (args.restart) { if (args.restart) {
await ctl.send(new lib.ControllerRestartRequest()); await ctl.send(new lib.ControllerRestartRequest());
} else {
print("Controller updated; a restart is required to apply the changes.");
} }
printRestartRequired(ctl, !args.restart, "Controller updated");
}, },
})); }));
@@ -56,7 +57,11 @@ const controllerConfigCommands = new lib.CommandTree({
controllerConfigCommands.add(new lib.Command({ controllerConfigCommands.add(new lib.Command({
definition: ["list", "List controller configuration"], definition: ["list", "List controller configuration"],
handler: async function(args: object, ctl: Ctl) { handler: async function(args: object, ctl: Ctl) {
printConfig(ctl, await ctl.send(new lib.ControllerConfigGetRequest())); let config = await ctl.send(new lib.ControllerConfigGetRequest());
for (let [name, value] of Object.entries(config)) {
print(`${name} ${JSON.stringify(value)}`);
}
}, },
})); }));
@@ -141,22 +146,19 @@ controllerConfigCommands.add(new lib.Command({
index, index,
final[index], final[index],
)); ));
} catch (err: any) { } catch (err) {
// eslint-disable-next-line
print(`Attempt to set ${index} to ${final[index] || String(null)} failed; set back to previous value.`);
print(err);
// If the string is empty, it's better to just print "" instead of nothing // 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 { try {
await fs.unlink(tmpFile); await fs.unlink(tmpFile);
} catch (err) { } catch (err) {
logger.warn( print("err: temporary file", tmpFile, "could not be deleted.");
`Temporary file ${tmpFile} could not be deleted. ` + print("This is not fatal, but they may build up over time if the issue persists.");
"This is not fatal, but they may build up over time if the issue persists."
);
} }
}, },
})); }));
@@ -173,7 +175,7 @@ controllerPluginCommands.add(new lib.Command({
let url = new URL(ctl.config.get("ctl.controller_url")!); let url = new URL(ctl.config.get("ctl.controller_url")!);
url.pathname += "api/plugins"; url.pathname += "api/plugins";
let response = await fetch(url); let response = await fetch(url);
ctl.output.table(await response.json() as object[]); print(asTable(await response.json() as []));
}, },
})); }));
controllerPluginCommands.add(new lib.Command({ controllerPluginCommands.add(new lib.Command({
@@ -185,8 +187,9 @@ controllerPluginCommands.add(new lib.Command({
await ctl.sendTo("controller", new lib.PluginUpdateRequest(args.plugin)); await ctl.sendTo("controller", new lib.PluginUpdateRequest(args.plugin));
if (args.restart) { if (args.restart) {
await ctl.send(new lib.ControllerRestartRequest()); 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({ controllerPluginCommands.add(new lib.Command({
@@ -199,16 +202,13 @@ controllerPluginCommands.add(new lib.Command({
const response = await ctl.sendTo( const response = await ctl.sendTo(
"controller", new lib.PluginSearchRequest(args.query, args.page, args.pageSize) "controller", new lib.PluginSearchRequest(args.query, args.page, args.pageSize)
); );
const results = response.results.map(plugin => ({ print(asTable(response.results.map(plugin => ({
name: plugin.name, name: plugin.name,
version: plugin.version, version: plugin.version,
publisher: plugin.publisher ?? "", publisher: plugin.publisher ?? "",
description: plugin.description ?? "", description: plugin.description ?? "",
})); }))));
ctl.output.result({ total: response.total, results }, () => { print(`Showing ${response.results.length} of ${response.total} results`);
print(asTable(results));
print(`Showing ${results.length} of ${response.total} results`);
});
}, },
})); }));
controllerPluginCommands.add(new lib.Command({ controllerPluginCommands.add(new lib.Command({
@@ -220,8 +220,9 @@ controllerPluginCommands.add(new lib.Command({
await ctl.sendTo("controller", new lib.PluginInstallRequest(args.plugin)); await ctl.sendTo("controller", new lib.PluginInstallRequest(args.plugin));
if (args.restart) { if (args.restart) {
await ctl.send(new lib.ControllerRestartRequest()); await ctl.send(new lib.ControllerRestartRequest());
} else {
print("Plugin installed; a restart is required to apply the changes.");
} }
printRestartRequired(ctl, !args.restart, "Plugin installed");
}, },
})); }));
+7 -3
View File
@@ -1,6 +1,5 @@
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import type { Ctl } from "../ctl.js"; import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js";
export const debugCommands = new lib.CommandTree({ name: "debug", description: "Debugging utilities" }); export const debugCommands = new lib.CommandTree({ name: "debug", description: "Debugging utilities" });
debugCommands.add(new lib.Command({ debugCommands.add(new lib.Command({
@@ -8,7 +7,6 @@ debugCommands.add(new lib.Command({
handler: async function(args: object, ctl: Ctl) { handler: async function(args: object, ctl: Ctl) {
await ctl.send(new lib.DebugDumpWsRequest()); await ctl.send(new lib.DebugDumpWsRequest());
ctl.keepOpen = true; ctl.keepOpen = true;
ctl.output.streamingLog = true;
}, },
})); }));
@@ -22,6 +20,12 @@ debugCommands.add(new lib.Command({
}], }],
handler: async function(args: { exchangeString: string, pretty: boolean }, ctl: Ctl) { handler: async function(args: { exchangeString: string, pretty: boolean }, ctl: Ctl) {
const result = lib.readMapExchangeString(args.exchangeString); const result = lib.readMapExchangeString(args.exchangeString);
ctl.output.result(result, () => print(JSON.stringify(result, null, args.pretty ? 2 : undefined))); 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));
}
}, },
})); }));
+38 -38
View File
@@ -1,15 +1,15 @@
import fs from "node:fs/promises"; import fs from "node:fs/promises";
import asTableModule from "as-table";
import events from "events"; import events from "events";
import os from "os"; import os from "os";
import child_process from "child_process"; import child_process from "child_process";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import { logger } from "@clusterio/lib";
import type { Ctl } from "../ctl.js"; import type { Ctl } from "../ctl.js";
import { asTable, print } from "./command_ops.js"; import { print } from "./command_ops.js";
import { import { serializedConfigToString, getEditor, configToKeyVal } from "./config_ops.js";
serializedConfigToString, getEditor, configToKeyVal, printConfig, printRestartRequired,
} from "./config_ops.js"; const asTable = asTableModule.configure({ delimiter: " | " });
export const hostCommands = new lib.CommandTree({ name: "host", description: "Host management" }); export const hostCommands = new lib.CommandTree({ name: "host", description: "Host management" });
hostCommands.add(new lib.Command({ hostCommands.add(new lib.Command({
@@ -45,7 +45,8 @@ hostCommands.add(new lib.Command({
hostCommands.add(new lib.Command({ hostCommands.add(new lib.Command({
definition: [["list", "l"], "List hosts connected to the controller"], definition: [["list", "l"], "List hosts connected to the controller"],
handler: async function(args: object, ctl: Ctl) { handler: async function(args: object, ctl: Ctl) {
ctl.output.table(await ctl.send(new lib.HostListRequest())); let hosts = await ctl.send(new lib.HostListRequest());
print(asTable(hosts));
}, },
})); }));
@@ -70,19 +71,17 @@ hostCommands.add(new lib.Command({
definition: ["pending", "List host installers waiting for approval"], definition: ["pending", "List host installers waiting for approval"],
handler: async function(args: object, ctl: Ctl) { handler: async function(args: object, ctl: Ctl) {
let requests = await ctl.send(new lib.HostPairingListRequest()); let requests = await ctl.send(new lib.HostPairingListRequest());
ctl.output.result(requests, () => { if (!requests.length) {
if (!requests.length) { print("No pending host requests");
print("No pending host requests"); return;
return; }
} let now = Date.now();
let now = Date.now(); print(asTable(requests.map(request => ({
print(asTable(requests.map(request => ({ code: request.code,
code: request.code, name: request.name,
name: request.name, address: request.remoteAddress,
address: request.remoteAddress, age: formatAge(now - request.createdAtMs),
age: formatAge(now - request.createdAtMs), }))));
}))));
});
}, },
})); }));
@@ -100,10 +99,7 @@ hostCommands.add(new lib.Command({
name = requests.find(request => plainCode(request.code) === plainCode(args.code))?.name; name = requests.find(request => plainCode(request.code) === plainCode(args.code))?.name;
} }
let hostId = await ctl.send(new lib.HostPairingApproveRequest(args.code, args.name)); let hostId = await ctl.send(new lib.HostPairingApproveRequest(args.code, args.name));
ctl.output.result( print(name ? `Approved host ${name} with id ${hostId}` : `Approved host with id ${hostId}`);
{ id: hostId, name },
() => print(name ? `Approved host ${name} with id ${hostId}` : `Approved host with id ${hostId}`),
);
}, },
})); }));
@@ -141,8 +137,9 @@ hostCommands.add(new lib.Command({
} }
if (args.restart) { if (args.restart) {
await ctl.sendTo({ hostId }, new lib.HostRestartRequest()); 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");
}, },
})); }));
@@ -156,7 +153,11 @@ hostConfigCommands.add(new lib.Command({
}], }],
handler: async function(args: { host: string }, ctl: Ctl) { handler: async function(args: { host: string }, ctl: Ctl) {
let hostId = await lib.resolveHost(ctl, args.host); let hostId = await lib.resolveHost(ctl, args.host);
printConfig(ctl, await ctl.sendTo({ hostId }, new lib.HostConfigGetRequest())); let config = await ctl.sendTo({ hostId }, new lib.HostConfigGetRequest());
for (let [name, value] of Object.entries(config)) {
print(`${name} ${JSON.stringify(value)}`);
}
}, },
})); }));
@@ -254,22 +255,19 @@ hostConfigCommands.add(new lib.Command({
index, index,
final[index], final[index],
)); ));
} catch (err: any) { } catch (err) {
// eslint-disable-next-line
print(`Attempt to set ${index} to ${final[index] || String(null)} failed; set back to previous value.`);
// If the string is empty, it's better to just print "" instead of nothing // If the string is empty, it's better to just print "" instead of nothing
logger.error( print(err);
`Attempt to set ${index} to ${final[index] || String(null)} failed; ` +
`set back to previous value: ${err.message}`
);
} }
} }
} }
try { try {
await fs.unlink(tmpFile); await fs.unlink(tmpFile);
} catch (err) { } catch (err) {
logger.warn( print("err: temporary file", tmpFile, "could not be deleted.");
`Temporary file ${tmpFile} could not be deleted. ` + print("This is not fatal, but they may build up over time if the issue persists.");
"This is not fatal, but they may build up over time if the issue persists."
);
} }
}, },
})); }));
@@ -287,9 +285,9 @@ hostPluginCommands.add(new lib.Command({
handler: async function(args: { host: string }, ctl: Ctl) { handler: async function(args: { host: string }, ctl: Ctl) {
let hostId = await lib.resolveHost(ctl, args.host); let hostId = await lib.resolveHost(ctl, args.host);
const plugins = await ctl.sendTo({ hostId }, new lib.PluginListRequest()); const plugins = await ctl.sendTo({ hostId }, new lib.PluginListRequest());
ctl.output.table(plugins, p => ({ print(asTable(plugins.map(p => ({
title: p.title, version: p.version, state: p.state, npmPackage: p.npmPackage, title: p.title, version: p.version, state: p.state, npmPackage: p.npmPackage,
})); }))));
}, },
})); }));
hostPluginCommands.add(new lib.Command({ hostPluginCommands.add(new lib.Command({
@@ -303,8 +301,9 @@ hostPluginCommands.add(new lib.Command({
await ctl.sendTo({ hostId }, new lib.PluginUpdateRequest(args.plugin)); await ctl.sendTo({ hostId }, new lib.PluginUpdateRequest(args.plugin));
if (args.restart) { if (args.restart) {
await ctl.sendTo({ hostId }, new lib.HostRestartRequest()); 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({ hostPluginCommands.add(new lib.Command({
@@ -318,8 +317,9 @@ hostPluginCommands.add(new lib.Command({
await ctl.sendTo({ hostId }, new lib.PluginInstallRequest(args.plugin)); await ctl.sendTo({ hostId }, new lib.PluginInstallRequest(args.plugin));
if (args.restart) { if (args.restart) {
await ctl.sendTo({ hostId }, new lib.HostRestartRequest()); 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); hostCommands.add(hostPluginCommands);
+55 -72
View File
@@ -1,4 +1,5 @@
import fs from "node:fs/promises"; import fs from "node:fs/promises";
import asTableModule from "as-table";
import events from "events"; import events from "events";
import path from "path"; import path from "path";
import os from "os"; import os from "os";
@@ -9,9 +10,10 @@ import util from "util";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import { logger } from "@clusterio/lib"; import { logger } from "@clusterio/lib";
import type { Ctl } from "../ctl.js"; import type { Ctl } from "../ctl.js";
import { errorToJson, print } from "./command_ops.js"; import { print } from "./command_ops.js";
import { serializedConfigToString, getEditor, configToKeyVal, printConfig } from "./config_ops.js"; import { serializedConfigToString, getEditor, configToKeyVal } from "./config_ops.js";
const asTable = asTableModule.configure({ delimiter: " | " });
const finished = util.promisify(stream.finished); const finished = util.promisify(stream.finished);
export const instanceCommands = new lib.CommandTree({ export const instanceCommands = new lib.CommandTree({
@@ -25,7 +27,7 @@ instanceCommands.add(new lib.Command({
}], }],
handler: async function(args: { templates: boolean }, ctl: Ctl) { handler: async function(args: { templates: boolean }, ctl: Ctl) {
let list = await ctl.send(new lib.InstanceDetailsListRequest()); let list = await ctl.send(new lib.InstanceDetailsListRequest());
ctl.output.table(list.filter(instance => args.templates || !instance.isTemplate)); print(asTable(list.filter(instance => args.templates || !instance.isTemplate)));
}, },
})); }));
@@ -62,7 +64,6 @@ instanceCommands.add(new lib.Command({
instanceConfig.toRemote("controller", fields), instanceConfig.toRemote("controller", fields),
args.from args.from
)); ));
ctl.output.result({ id: instanceConfig.get("instance.id") }, () => {});
}, },
})); }));
@@ -80,13 +81,19 @@ instanceConfigCommands.add(new lib.Command({
? config["instance.inherited_fields"] as Record<string, true | string[]> ?? {} ? config["instance.inherited_fields"] as Record<string, true | string[]> ?? {}
: {}; : {};
printConfig(ctl, config, name => { for (let [name, value] of Object.entries(config)) {
const entry = inherited[name]; if (name === "instance.inherited_fields") {
if (entry instanceof Array && entry.length) { continue;
return ` (inherited except ${entry.join(", ")})`;
} }
return entry ? " (inherited)" : ""; const entry = inherited[name];
}); let note = "";
if (entry instanceof Array && entry.length) {
note = ` (inherited except ${entry.join(", ")})`;
} else if (entry) {
note = " (inherited)";
}
print(`${name} ${JSON.stringify(value)}${note}`);
}
}, },
})); }));
@@ -218,22 +225,19 @@ instanceConfigCommands.add(new lib.Command({
index, index,
final[index], final[index],
)); ));
} catch (err: any) { } catch (err) {
// eslint-disable-next-line
print(`Attempt to set ${index} to ${final[index] || String(null)} failed; set back to previous value.`);
// If the string is empty, it's better to just print "" instead of nothing // If the string is empty, it's better to just print "" instead of nothing
logger.error( print(err);
`Attempt to set ${index} to ${final[index] || String(null)} failed; ` +
`set back to previous value: ${err.message}`
);
} }
} }
} }
try { try {
await fs.unlink(tmpFile); await fs.unlink(tmpFile);
} catch (err) { } catch (err) {
logger.warn( print("err: temporary file", tmpFile, "could not be deleted.");
`Temporary file ${tmpFile} could not be deleted. ` + print("This is not fatal, but they may build up over time if the issue persists.");
"This is not fatal, but they may build up over time if the issue persists."
);
} }
}, },
})); }));
@@ -287,7 +291,9 @@ instanceSaveCommands.add(new lib.Command({
let instanceId = await lib.resolveInstance(ctl, args.instance); let instanceId = await lib.resolveInstance(ctl, args.instance);
let saves = await ctl.sendTo("controller", new lib.InstanceSaveDetailsListRequest()); let saves = await ctl.sendTo("controller", new lib.InstanceSaveDetailsListRequest());
saves = saves.filter(save => save.instanceId === instanceId); saves = saves.filter(save => save.instanceId === instanceId);
ctl.output.table(saves, ({ mtimeMs, ...rest }) => ({ ...rest, mtime: new Date(mtimeMs).toLocaleString() })); print(asTable(saves.map(
({ mtimeMs, ...rest }) => ({ ...rest, mtime: new Date(mtimeMs).toLocaleString() })
)));
}, },
})); }));
@@ -388,16 +394,13 @@ instanceSaveCommands.add(new lib.Command({
logger.error(requestError); 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) { if ((result.errors || []).length || (result.request_errors || []).length) {
throw new lib.CommandError("Uploading save failed"); throw new lib.CommandError("Uploading save failed");
} }
const name = result.saves?.[0];
ctl.output.result({ name }, () => {
if (name) {
print(`Successfully uploaded as ${name}`);
}
});
}, },
})); }));
@@ -436,10 +439,7 @@ instanceSaveCommands.add(new lib.Command({
args.copy args.copy
) )
); );
ctl.output.result( print(`Transferred as ${storedName} to ${args.targetInstance}.`);
{ name: storedName, instanceId: targetInstanceId },
() => print(`Transferred as ${storedName} to ${args.targetInstance}.`),
);
}, },
})); }));
@@ -456,10 +456,7 @@ instanceSaveCommands.add(new lib.Command({
url.pathname += `api/stream/${streamId}`; url.pathname += `api/stream/${streamId}`;
const filename = await lib.downloadFile(url, args.save, "rename"); const filename = await lib.downloadFile(url, args.save, "rename");
ctl.output.result( logger.info(`Downloaded ${args.save}${args.save === filename ? "" : ` as ${filename}`}`);
{ filename },
() => print(`Downloaded ${args.save}${args.save === filename ? "" : ` as ${filename}`}`),
);
}, },
})); }));
@@ -569,34 +566,27 @@ instanceCommands.add(new lib.Command({
}); });
if (instancesToStart.length === 0) { if (instancesToStart.length === 0) {
ctl.output.result([], () => print("No instances to start.")); print("No instances to start.");
return; return;
} }
const human = ctl.output.human; print(`Starting ${instancesToStart.length} instance(s):`);
if (human) { for (const instance of instancesToStart) {
print(`Starting ${instancesToStart.length} instance(s):`); print(` - ${instance.name} (ID: ${instance.id})`);
for (const instance of instancesToStart) {
print(` - ${instance.name} (ID: ${instance.id})`);
}
} }
// Start all filtered instances // Start all filtered instances
const results = await Promise.all(instancesToStart.map(async (instance: lib.InstanceDetails) => { const startPromises = instancesToStart.map(async (instance: lib.InstanceDetails) => {
try { try {
await ctl.sendTo({ instanceId: instance.id }, new lib.InstanceStartRequest()); await ctl.sendTo({ instanceId: instance.id }, new lib.InstanceStartRequest());
if (human) { print(`✓ Started ${instance.name}`);
print(`✓ Started ${instance.name}`);
}
return { id: instance.id, name: instance.name };
} catch (error) { } catch (error) {
if (human) { print(`✗ Failed to start ${instance.name}: ${error}`);
print(`✗ Failed to start ${instance.name}: ${error}`);
}
return { id: instance.id, name: instance.name, error: errorToJson(error) };
} }
})); });
ctl.output.result(results, () => print("Start all operation completed."));
await Promise.all(startPromises);
print("Start all operation completed.");
}, },
})); }));
@@ -656,34 +646,27 @@ instanceCommands.add(new lib.Command({
.filter((instance: lib.InstanceDetails) => ["starting", "running"].includes(instance.status)); .filter((instance: lib.InstanceDetails) => ["starting", "running"].includes(instance.status));
if (instancesToStop.length === 0) { if (instancesToStop.length === 0) {
ctl.output.result([], () => print("No instances to stop.")); print("No instances to stop.");
return; return;
} }
const human = ctl.output.human; print(`Stopping ${instancesToStop.length} instance(s):`);
if (human) { for (const instance of instancesToStop) {
print(`Stopping ${instancesToStop.length} instance(s):`); print(` - ${instance.name} (ID: ${instance.id})`);
for (const instance of instancesToStop) {
print(` - ${instance.name} (ID: ${instance.id})`);
}
} }
// Stop all filtered instances // Stop all filtered instances
const results = await Promise.all(instancesToStop.map(async (instance: lib.InstanceDetails) => { const stopPromises = instancesToStop.map(async (instance: lib.InstanceDetails) => {
try { try {
await ctl.sendTo({ instanceId: instance.id }, new lib.InstanceStopRequest()); await ctl.sendTo({ instanceId: instance.id }, new lib.InstanceStopRequest());
if (human) { print(`✓ Stopped ${instance.name}`);
print(`✓ Stopped ${instance.name}`);
}
return { id: instance.id, name: instance.name };
} catch (error) { } catch (error) {
if (human) { print(`✗ Failed to stop ${instance.name}: ${error}`);
print(`✗ Failed to stop ${instance.name}: ${error}`);
}
return { id: instance.id, name: instance.name, error: errorToJson(error) };
} }
})); });
ctl.output.result(results, () => print("Stop all operation completed."));
await Promise.all(stopPromises);
print("Stop all operation completed.");
}, },
})); }));
@@ -720,6 +703,6 @@ instanceCommands.add(new lib.Command({
); );
// Factorio includes a newline in its response output. // Factorio includes a newline in its response output.
ctl.output.result({ result }, () => process.stdout.write(result)); process.stdout.write(result);
}, },
})); }));
+10 -13
View File
@@ -27,7 +27,6 @@ logCommands.add(new lib.Command({
let hostIds = args.host ? [await lib.resolveHost(ctl, args.host)] : []; let hostIds = args.host ? [await lib.resolveHost(ctl, args.host)] : [];
await ctl.setLogSubscriptions({ all: args.all, controller: args.controller, hostIds, instanceIds }); await ctl.setLogSubscriptions({ all: args.all, controller: args.controller, hostIds, instanceIds });
ctl.keepOpen = true; ctl.keepOpen = true;
ctl.output.streamingLog = true;
}, },
})); }));
@@ -76,18 +75,16 @@ logCommands.add(new lib.Command({
result.log.reverse(); result.log.reverse();
} }
ctl.output.result(result.log, () => { let stdoutLogger = winston.createLogger({
let stdoutLogger = winston.createLogger({ level: "verbose",
level: "verbose", levels,
levels, format: new lib.TerminalFormat({ showTimestamp: true }),
format: new lib.TerminalFormat({ showTimestamp: true }), transports: [
transports: [ new ConsoleTransport({ errorLevels: [], warnLevels: [] }),
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);
}
}, },
})); }));
+43 -32
View File
@@ -1,4 +1,5 @@
import fs from "node:fs/promises"; import fs from "node:fs/promises";
import asTableModule from "as-table";
import events from "events"; import events from "events";
import path from "path"; import path from "path";
import stream from "stream"; import stream from "stream";
@@ -7,7 +8,9 @@ import util from "util";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import { logger } from "@clusterio/lib"; import { logger } from "@clusterio/lib";
import type { Ctl } from "../ctl.js"; import type { Ctl } from "../ctl.js";
import { asTable, pickFields, print } from "./command_ops.js"; import { print } from "./command_ops.js";
const asTable = asTableModule.configure({ delimiter: " | " });
const finished = util.promisify(stream.finished); const finished = util.promisify(stream.finished);
export const modCommands = new lib.CommandTree({ name: "mod", description: "Manage uploaded mods" }); export const modCommands = new lib.CommandTree({ name: "mod", description: "Manage uploaded mods" });
@@ -21,18 +24,16 @@ modCommands.add(new lib.Command({
throw new lib.CommandError("mod-version must match format digit.digit.digit"); throw new lib.CommandError("mod-version must match format digit.digit.digit");
} }
let modInfo = await ctl.send(new lib.ModGetRequest(args.name, args.modVersion)); let modInfo = await ctl.send(new lib.ModGetRequest(args.name, args.modVersion));
ctl.output.result(modInfo, () => { for (let [field, value] of Object.entries(modInfo)) {
for (let [field, value] of Object.entries(modInfo)) { if (value instanceof Array) {
if (value instanceof Array) { print(`${field}:`);
print(`${field}:`); for (let entry of value) {
for (let entry of value) { print(` ${entry}`);
print(` ${entry}`);
}
} else {
print(`${field}: ${value}`);
} }
} else {
print(`${field}: ${value}`);
} }
}); }
}, },
})); }));
@@ -49,7 +50,17 @@ modCommands.add(new lib.Command({
}], }],
handler: async function(args: { fields: string[] }, ctl: Ctl) { handler: async function(args: { fields: string[] }, ctl: Ctl) {
let mods = await ctl.send(new lib.ModListRequest()); let mods = await ctl.send(new lib.ModListRequest());
ctl.output.table(mods, mod => pickFields(mod, args.fields)); if (!args.fields.includes("all")) {
for (let entry of mods) {
for (let field of Object.keys(entry)) {
if (!args.fields.includes(field)) {
// @ts-expect-error terrible hack
delete entry[field];
}
}
}
}
print(asTable(mods));
}, },
})); }));
@@ -110,19 +121,21 @@ modCommands.add(new lib.Command({
args.sortOrder args.sortOrder
)); ));
let results = response.results.flatMap(result => result.versions); let results = response.results.flatMap(result => result.versions);
ctl.output.result({ if (!args.fields.includes("all")) {
page: args.page, for (let entry of results) {
pageCount: response.pageCount, for (let field of Object.keys(entry)) {
resultCount: response.resultCount, if (!args.fields.includes(field)) {
queryIssues: response.queryIssues, // @ts-expect-error terrible hack
results, delete entry[field];
}, () => { }
for (let issue of response.queryIssues) { }
print(issue);
} }
print(`page ${args.page} of ${response.pageCount} (${response.resultCount} results)`); }
print(asTable(results.map(mod => pickFields(mod, args.fields)))); for (let issue of response.queryIssues) {
}); print(issue);
}
print(`page ${args.page} of ${response.pageCount} (${response.resultCount} results)`);
print(asTable(results));
}, },
})); }));
@@ -161,16 +174,14 @@ modCommands.add(new lib.Command({
logger.error(requestError); 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) { if ((result.errors || []).length || (result.request_errors || []).length) {
throw new lib.CommandError("Uploading mod failed"); 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}`);
}
});
}, },
})); }));
@@ -190,7 +201,7 @@ modCommands.add(new lib.Command({
let filename = `${args.name}_${args.modVersion}.zip`; let filename = `${args.name}_${args.modVersion}.zip`;
await lib.downloadFile(url, filename, "overwrite"); await lib.downloadFile(url, filename, "overwrite");
ctl.output.result({ filename }, () => print(`Downloaded ${filename}`)); logger.info(`Downloaded ${filename}`);
}, },
})); }));
+51 -49
View File
@@ -1,7 +1,11 @@
import asTableModule from "as-table";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import { logger } from "@clusterio/lib"; import { logger } from "@clusterio/lib";
import type { Ctl } from "../ctl.js"; import type { Ctl } from "../ctl.js";
import { pickFields, print } from "./command_ops.js"; import { print } from "./command_ops.js";
const asTable = asTableModule.configure({ delimiter: " | " });
export const modPackCommands = new lib.CommandTree({ name: "mod-pack", description: "Mod Pack" }); export const modPackCommands = new lib.CommandTree({ name: "mod-pack", description: "Mod Pack" });
modPackCommands.add(new lib.Command({ modPackCommands.add(new lib.Command({
@@ -15,50 +19,56 @@ modPackCommands.add(new lib.Command({
let modPack = await ctl.send( let modPack = await ctl.send(
new lib.ModPackGetRequest(await lib.resolveModPack(ctl, args.modPack)) new lib.ModPackGetRequest(await lib.resolveModPack(ctl, args.modPack))
); );
ctl.output.result(modPack, () => printModPack(modPack, mods));
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}`);
}
}
}, },
})); }));
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({ modPackCommands.add(new lib.Command({
definition: [["list", "l"], "List mod packs in the cluster"], definition: [["list", "l"], "List mod packs in the cluster"],
handler: async function(args: object, ctl: Ctl) { handler: async function(args: object, ctl: Ctl) {
let modPacks = await ctl.send(new lib.ModPackListRequest()); let modPacks = await ctl.send(new lib.ModPackListRequest());
ctl.output.table(modPacks, modPack => pickFields(modPack, ["id", "name", "factorioVersion"])); let fields = ["id", "name", "factorioVersion"];
for (let entry of modPacks) {
for (let field of Object.keys(entry)) {
if (!fields.includes(field)) {
// @ts-expect-error terrible hack
delete entry[field];
}
}
}
print(asTable(modPacks));
}, },
})); }));
@@ -184,17 +194,10 @@ modPackCommands.add(new lib.Command({
setModPackModsEnabled(modPack, args.disabledMods, false); setModPackModsEnabled(modPack, args.disabledMods, false);
setModPackSettings(modPack, args); setModPackSettings(modPack, args);
await ctl.send(new lib.ModPackCreateRequest(modPack)); await ctl.send(new lib.ModPackCreateRequest(modPack));
printCreated(ctl, modPack); print(`Created mod pack ${modPack.name} (${modPack.id})`);
}, },
})); }));
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({ modPackCommands.add(new lib.Command({
definition: ["import <string>", "Import mod pack string", (yargs) => { definition: ["import <string>", "Import mod pack string", (yargs) => {
yargs.positional("string", { describe: "Mod pack string to import", type: "string" }); yargs.positional("string", { describe: "Mod pack string to import", type: "string" });
@@ -202,7 +205,7 @@ modPackCommands.add(new lib.Command({
handler: async function(args: { string: string }, ctl: Ctl) { handler: async function(args: { string: string }, ctl: Ctl) {
const modPack = lib.ModPack.fromModPackString(args.string); const modPack = lib.ModPack.fromModPackString(args.string);
await ctl.send(new lib.ModPackCreateRequest(modPack)); await ctl.send(new lib.ModPackCreateRequest(modPack));
printCreated(ctl, modPack); print(`Created mod pack ${modPack.name} (${modPack.id})`);
}, },
})); }));
@@ -214,8 +217,7 @@ modPackCommands.add(new lib.Command({
const modPack = await ctl.send( const modPack = await ctl.send(
new lib.ModPackGetRequest(await lib.resolveModPack(ctl, args.modPack)) new lib.ModPackGetRequest(await lib.resolveModPack(ctl, args.modPack))
); );
const modPackString = modPack.toModPackString(); print(modPack.toModPackString());
ctl.output.result({ modPackString }, () => print(modPackString));
}, },
})); }));
+7 -3
View File
@@ -1,7 +1,11 @@
import asTableModule from "as-table";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import type { Ctl } from "../ctl.js"; import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js"; import { print } from "./command_ops.js";
const asTable = asTableModule.configure({ delimiter: " | " });
export const noteCommands = new lib.CommandTree({ export const noteCommands = new lib.CommandTree({
name: "note", description: "Notes attached to hosts, instances, users and other resources", name: "note", description: "Notes attached to hosts, instances, users and other resources",
}); });
@@ -16,12 +20,12 @@ noteCommands.add(new lib.Command({
if (args.type !== undefined) { if (args.type !== undefined) {
notes = notes.filter(note => note.resourceType === args.type); notes = notes.filter(note => note.resourceType === args.type);
} }
ctl.output.table(notes, note => ({ print(asTable(notes.map(note => ({
type: note.resourceType, type: note.resourceType,
id: note.resourceId, id: note.resourceId,
updatedBy: note.updatedBy, updatedBy: note.updatedBy,
content: note.content, content: note.content,
})); }))));
}, },
})); }));
@@ -38,7 +42,7 @@ noteCommands.add(new lib.Command({
if (!note) { if (!note) {
throw new lib.CommandError(`No note for ${args.type} ${args.id}`); throw new lib.CommandError(`No note for ${args.type} ${args.id}`);
} }
ctl.output.result(note, () => print(note.content)); print(note.content);
}, },
})); }));
+7 -1
View File
@@ -1,10 +1,16 @@
import asTableModule from "as-table";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import type { Ctl } from "../ctl.js"; 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" }); export const permissionCommands = new lib.CommandTree({ name: "permission", description: "Permission inspection" });
permissionCommands.add(new lib.Command({ permissionCommands.add(new lib.Command({
definition: [["list", "l"], "List permissions in the cluster"], definition: [["list", "l"], "List permissions in the cluster"],
handler: async function(args: object, ctl: Ctl) { handler: async function(args: object, ctl: Ctl) {
ctl.output.table(await ctl.send(new lib.PermissionListRequest())); let permissions = await ctl.send(new lib.PermissionListRequest());
print(asTable(permissions));
}, },
})); }));
+5 -3
View File
@@ -1,13 +1,15 @@
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import { logger } from "@clusterio/lib";
import type { Ctl } from "../ctl.js"; import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js"; import { asTable, print } from "./command_ops.js";
export const roleCommands = new lib.CommandTree({ name: "role", description: "Role management" }); export const roleCommands = new lib.CommandTree({ name: "role", description: "Role management" });
roleCommands.add(new lib.Command({ roleCommands.add(new lib.Command({
definition: [["list", "l"], "List roles in the cluster"], definition: [["list", "l"], "List roles in the cluster"],
handler: async function(args: object, ctl: Ctl) { handler: async function(args: object, ctl: Ctl) {
ctl.output.table(await ctl.send(new lib.RoleListRequest())); let roles = await ctl.send(new lib.RoleListRequest());
print(asTable(roles));
}, },
})); }));
@@ -25,7 +27,7 @@ roleCommands.add(new lib.Command({
args.description, args.description,
args.permissions, args.permissions,
)); ));
ctl.output.result({ id }, () => print(`Created role ID ${id}`)); logger.info(`Created role ID ${id}`);
}, },
})); }));
+48 -42
View File
@@ -5,10 +5,6 @@ import * as lib from "@clusterio/lib";
import type { Ctl } from "../ctl.js"; import type { Ctl } from "../ctl.js";
import { asTable, print } from "./command_ops.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" }); export const userCommands = new lib.CommandTree({ name: "user", alias: ["u"], description: "User management" });
userCommands.add(new lib.Command({ userCommands.add(new lib.Command({
definition: ["show <name>", "Show details for one user", (yargs) => { definition: ["show <name>", "Show details for one user", (yargs) => {
@@ -18,23 +14,30 @@ userCommands.add(new lib.Command({
}); });
}], }],
handler: async function(args: { name: string, instanceStats: boolean }, ctl: Ctl) { handler: async function(args: { name: string, instanceStats: boolean }, ctl: Ctl) {
const user = await ctl.send(new lib.UserGetRequest(args.name)); let user = await ctl.send(new lib.UserGetRequest(args.name));
const { playerStats, instanceStats, ...properties } = user; Object.assign(user, user.playerStats);
const instances = args.instanceStats && ctl.output.human // @ts-expect-error Terrible hack
? await ctl.send(new lib.InstanceDetailsListRequest()) delete user.playerStats;
: []; let instanceStats = user.instanceStats;
ctl.output.result(user, () => { // @ts-expect-error Terrible hack
printProperties({ ...properties, ...playerStats }); delete user.instanceStats;
if (!args.instanceStats) { print(asTable(Object.entries(user).map(([property, value]) => ({ property, value }))));
return;
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) { for (let [id, playerInstanceStats] of instanceStats || []) {
const name = instances.find(i => i.id === id)?.name ?? "<deleted>";
print(); print();
print(`Instance ${name} (${id}):`); print(`Instance ${instanceName(id)} (${id}):`);
printProperties(playerInstanceStats); print(asTable(Object.entries(playerInstanceStats).map(([property, value]) => ({ property, value }))));
} }
}); }
}, },
})); }));
@@ -46,17 +49,29 @@ userCommands.add(new lib.Command({
}); });
}], }],
handler: async function(args: { stats: boolean, attributes: boolean }, ctl: Ctl) { handler: async function(args: { stats: boolean, attributes: boolean }, ctl: Ctl) {
const users = await ctl.send(new lib.UserListRequest()); let users = await ctl.send(new lib.UserListRequest());
ctl.output.table(users, user => { for (let user of users) {
const { if (args.stats) {
playerStats, isDeleted, banReason, instanceStats, isAdmin, isWhitelisted, isBanned, ...row Object.assign(user, user.playerStats);
} = user; }
return { // @ts-expect-error Terrible hack
...row, delete user.playerStats;
...args.attributes && { isAdmin, isWhitelisted, isBanned }, // @ts-expect-error Terrible hack
...args.stats && playerStats, 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;
}
}
print(asTable(users));
}, },
})); }));
@@ -204,17 +219,11 @@ async function handleImportOrRestore(args: {
new lib.UserBulkImportRequest(importType, importType === "users" ? data.users : data, restore) new lib.UserBulkImportRequest(importType, importType === "users" ? data.users : data, restore)
); );
let backupFile: string | undefined; print(`${restore ? "Restored" : "Imported"} ${importType} from ${args.filepath}`);
if (restore && backup && !args.noBackup) { if (restore && backup && !args.noBackup) {
backupFile = `${importType}-backup.json`; await fs.writeFile(`${importType}-backup.json`, JSON.stringify(backup, undefined, "\t"));
await fs.writeFile(backupFile, JSON.stringify(backup, undefined, "\t")); print(`Wrote backup to ${importType}-backup.json`);
} }
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({ userCommands.add(new lib.Command({
@@ -287,9 +296,6 @@ userCommands.add(new lib.Command({
await fs.writeFile(args.filepath, JSON.stringify(await ctl.send( await fs.writeFile(args.filepath, JSON.stringify(await ctl.send(
new lib.UserBulkExportRequest(exportType) new lib.UserBulkExportRequest(exportType)
), undefined, "\t")); ), undefined, "\t"));
ctl.output.result( print(`Exported ${exportType} to ${args.filepath}`);
{ type: exportType, filepath: args.filepath },
() => print(`Exported ${exportType} to ${args.filepath}`),
);
}, },
})); }));
-23
View File
@@ -1,6 +1,4 @@
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js";
export async function getEditor(argsEditor: string) { export async function getEditor(argsEditor: string) {
// eslint-disable-next-line // eslint-disable-next-line
@@ -55,24 +53,3 @@ export function serializedConfigToString(
} }
return allConfigElements; 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)) {
// 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)}`);
}
}
});
}
/** 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.`);
}
});
}
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@clusterio/host", "name": "@clusterio/host",
"version": "2.1.1", "version": "2.1.0",
"description": "Implementation of Clusterio host server", "description": "Implementation of Clusterio host server",
"homepage": "https://github.com/clusterio/clusterio#readme", "homepage": "https://github.com/clusterio/clusterio#readme",
"author": "Hornwitser <github@hornwitser.no>", "author": "Hornwitser <github@hornwitser.no>",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@clusterio/lib", "name": "@clusterio/lib",
"version": "2.1.1", "version": "2.1.0",
"description": "Shared library for Clusterio", "description": "Shared library for Clusterio",
"homepage": "https://github.com/clusterio/clusterio#readme", "homepage": "https://github.com/clusterio/clusterio#readme",
"author": "Hornwitser <github@hornwitser.no>", "author": "Hornwitser <github@hornwitser.no>",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@clusterio/web_ui", "name": "@clusterio/web_ui",
"version": "2.1.1", "version": "2.1.0",
"description": "Clusterio web interface implementation", "description": "Clusterio web interface implementation",
"homepage": "https://github.com/clusterio/clusterio#readme", "homepage": "https://github.com/clusterio/clusterio#readme",
"author": "Hornwitser", "author": "Hornwitser",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@clusterio/plugin-global_chat", "name": "@clusterio/plugin-global_chat",
"version": "2.1.1", "version": "2.1.0",
"description": "Clusterio plugin forwarding between Factorio servers", "description": "Clusterio plugin forwarding between Factorio servers",
"homepage": "https://github.com/clusterio/clusterio#readme", "homepage": "https://github.com/clusterio/clusterio#readme",
"author": "Hornwitser <github@hornwitser.no>", "author": "Hornwitser <github@hornwitser.no>",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@clusterio/plugin-player_auth", "name": "@clusterio/plugin-player_auth",
"version": "2.1.1", "version": "2.1.0",
"description": "Clusterio plugin authenticating logged in players to the web interface", "description": "Clusterio plugin authenticating logged in players to the web interface",
"homepage": "https://github.com/clusterio/clusterio#readme", "homepage": "https://github.com/clusterio/clusterio#readme",
"author": "Hornwitser <github@hornwitser.no>", "author": "Hornwitser <github@hornwitser.no>",
+25 -50
View File
@@ -30,20 +30,14 @@ playerSyncCommands.add(new lib.Command({
handler: async function(args: object, ctl: Ctl) { handler: async function(args: object, ctl: Ctl) {
let players = await ctl.send(new msg.ListPlayersRequest()); let players = await ctl.send(new msg.ListPlayersRequest());
players.sort((a, b) => a.name.localeCompare(b.name)); players.sort((a, b) => a.name.localeCompare(b.name));
if (!ctl.output.human) { print("name | generation | size | acquired by");
ctl.output.result(players);
return;
}
let rows = [];
for (let player of players) { for (let player of players) {
rows.push({ print(
name: player.name, `${player.name} | ${player.generation ?? "-"} | ` +
generation: player.generation ?? "-", `${player.size === undefined ? "-" : lib.formatBytes(player.size)} | ` +
size: player.size === undefined ? "-" : lib.formatBytes(player.size), `${await instanceName(ctl, player.instanceId)}`
"acquired by": await instanceName(ctl, player.instanceId), );
});
} }
ctl.output.table(rows);
}, },
})); }));
@@ -53,37 +47,24 @@ playerSyncCommands.add(new lib.Command({
}], }],
handler: async function(args: { player: string }, ctl: Ctl) { handler: async function(args: { player: string }, ctl: Ctl) {
let response = await ctl.send(new msg.GetPlayerDataRequest(args.player)); let response = await ctl.send(new msg.GetPlayerDataRequest(args.player));
print(`acquired by: ${await instanceName(ctl, response.instanceId)}`);
let playerData = response.playerData; let playerData = response.playerData;
const summary = { if (!playerData) {
instanceId: response.instanceId, print(`No player data stored for ${args.player}`);
...playerData && { return;
generation: playerData.generation, }
size: JSON.stringify(playerData).length, print(`generation: ${playerData.generation}`);
controller: playerData.controller, print(`size: ${lib.formatBytes(JSON.stringify(playerData).length)}`);
force: playerData.force, print(`controller: ${playerData.controller}`);
inventories: summarizePlayerInventories(playerData), print(`force: ${playerData.force}`);
}, for (let inventory of summarizePlayerInventories(playerData)) {
}; print(`${inventory.name}:`);
const acquiredBy = ctl.output.human ? await instanceName(ctl, response.instanceId) : ""; for (let item of inventory.items) {
ctl.output.result(summary, () => { let quality = item.quality ? ` (${item.quality})` : "";
print(`acquired by: ${acquiredBy}`); let size = item.exportSize ? ` ${lib.formatBytes(item.exportSize)}` : "";
if (!playerData) { print(` ${item.count} ${item.name}${quality}${size}`);
print(`No player data stored for ${args.player}`);
return;
} }
print(`generation: ${summary.generation}`); }
print(`size: ${lib.formatBytes(summary.size!)}`);
print(`controller: ${summary.controller}`);
print(`force: ${summary.force}`);
for (let inventory of summary.inventories!) {
print(`${inventory.name}:`);
for (let item of inventory.items) {
let quality = item.quality ? ` (${item.quality})` : "";
let size = item.exportSize ? ` ${lib.formatBytes(item.exportSize)}` : "";
print(` ${item.count} ${item.name}${quality}${size}`);
}
}
});
}, },
})); }));
@@ -100,12 +81,9 @@ playerSyncCommands.add(new lib.Command({
let content = JSON.stringify(response.playerData, null, "\t"); let content = JSON.stringify(response.playerData, null, "\t");
if (args.file) { if (args.file) {
await fs.writeFile(args.file, content); await fs.writeFile(args.file, content);
ctl.output.result( print(`Wrote player data for ${args.player} to ${args.file}`);
{ file: args.file },
() => print(`Wrote player data for ${args.player} to ${args.file}`),
);
} else { } else {
ctl.output.result(response.playerData, () => print(content)); print(content);
} }
}, },
})); }));
@@ -123,10 +101,7 @@ playerSyncCommands.add(new lib.Command({
playerData.name = args.player; playerData.name = args.player;
playerData.generation ??= 0; playerData.generation ??= 0;
let response = await ctl.send(new msg.SetPlayerDataRequest(args.player, playerData)); let response = await ctl.send(new msg.SetPlayerDataRequest(args.player, playerData));
ctl.output.result( print(`Stored player data for ${args.player} as generation ${response.generation}`);
{ generation: response.generation },
() => print(`Stored player data for ${args.player} as generation ${response.generation}`),
);
}, },
})); }));
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@clusterio/plugin-player_sync", "name": "@clusterio/plugin-player_sync",
"version": "2.1.1", "version": "2.1.0",
"description": "Clusterio plugin forwarding between Factorio servers", "description": "Clusterio plugin forwarding between Factorio servers",
"homepage": "https://github.com/clusterio/clusterio#readme", "homepage": "https://github.com/clusterio/clusterio#readme",
"author": "Danielv <danielv@danielv.no>", "author": "Danielv <danielv@danielv.no>",
+6 -27
View File
@@ -4,7 +4,7 @@ import os from "node:os";
import path from "node:path"; import path from "node:path";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import { CommandOutput, CtlHooks } from "@clusterio/ctl"; import { CtlHooks } from "@clusterio/ctl";
import * as mock from "../../../test/mock.js"; import * as mock from "../../../test/mock.js";
import { testRoundTripJsonSerialisable, testMatrix } from "../../../test/common.js"; import { testRoundTripJsonSerialisable, testMatrix } from "../../../test/common.js";
@@ -303,7 +303,6 @@ describe("player_sync plugin", function() {
let printed; let printed;
let responses; let responses;
const ctl = { const ctl = {
output: new CommandOutput(),
async send(message) { async send(message) {
sent.push(message); sent.push(message);
const handler = responses.get(message.constructor); const handler = responses.get(message.constructor);
@@ -332,7 +331,6 @@ describe("player_sync plugin", function() {
beforeEach(function() { beforeEach(function() {
sent = []; sent = [];
printed = []; printed = [];
ctl.output = new CommandOutput();
responses = new Map([ responses = new Map([
[lib.InstanceDetailsGetRequest, request => ({ id: request.instanceId, name: "Test" })], [lib.InstanceDetailsGetRequest, request => ({ id: request.instanceId, name: "Test" })],
[msg.ListPlayersRequest, () => [ [msg.ListPlayersRequest, () => [
@@ -362,12 +360,10 @@ describe("player_sync plugin", function() {
it("list should print sorted entries", async function() { it("list should print sorted entries", async function() {
await run("list"); await run("list");
const lines = printed.join("\n").split("\n").map(line => line.trimEnd()); assert.deepEqual(printed, [
assert.deepEqual(lines, [ "name | generation | size | acquired by",
"name | generation | size | acquired by", `alice | 2 | ${lib.formatBytes(100)} | -`,
"--------------------------------------------", "bob | - | - | Test (1)",
`alice | 2 | ${lib.formatBytes(100)} | -`,
"bob | - | - | Test (1)",
]); ]);
}); });
it("show should print a summary", async function() { it("show should print a summary", async function() {
@@ -388,7 +384,7 @@ describe("player_sync plugin", function() {
throw new lib.PermissionError("Permission denied"); throw new lib.PermissionError("Permission denied");
}); });
await run("list"); await run("list");
assert.match(printed[0], /bob +\| - +\| - +\| 1/); assert.equal(printed[2], "bob | - | - | 1");
printed = []; printed = [];
await run("show", { player: "alice" }); await run("show", { player: "alice" });
assert.equal(printed[0], "acquired by: 1"); assert.equal(printed[0], "acquired by: 1");
@@ -425,23 +421,6 @@ describe("player_sync plugin", function() {
new lib.CommandError("Player data must be a JSON object"), 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() { it("delete and release should send requests", async function() {
await run("delete", { player: "alice" }); await run("delete", { player: "alice" });
await run("release", { player: "alice" }); await run("release", { player: "alice" });
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@clusterio/plugin-research_sync", "name": "@clusterio/plugin-research_sync",
"version": "2.1.1", "version": "2.1.0",
"description": "Clusterio plugin for synchronizing research between Factorio servers", "description": "Clusterio plugin for synchronizing research between Factorio servers",
"homepage": "https://github.com/clusterio/clusterio#readme", "homepage": "https://github.com/clusterio/clusterio#readme",
"author": "Hornwitser <github@hornwitser.no>", "author": "Hornwitser <github@hornwitser.no>",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@clusterio/plugin-statistics_exporter", "name": "@clusterio/plugin-statistics_exporter",
"version": "2.1.1", "version": "2.1.0",
"description": "Clusterio plugin for gathering statistics from Factorio servers", "description": "Clusterio plugin for gathering statistics from Factorio servers",
"homepage": "https://github.com/clusterio/clusterio#readme", "homepage": "https://github.com/clusterio/clusterio#readme",
"author": "Hornwitser <github@hornwitser.no>", "author": "Hornwitser <github@hornwitser.no>",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@clusterio/plugin-subspace_storage", "name": "@clusterio/plugin-subspace_storage",
"version": "2.1.1", "version": "2.1.0",
"description": "Clusterio plugin for sharing storage between Factorio servers", "description": "Clusterio plugin for sharing storage between Factorio servers",
"homepage": "https://github.com/clusterio/clusterio#readme", "homepage": "https://github.com/clusterio/clusterio#readme",
"author": "Hornwitser <github@hornwitser.no>", "author": "Hornwitser <github@hornwitser.no>",
-95
View File
@@ -1,95 +0,0 @@
import assert from "node:assert/strict";
import * as lib from "@clusterio/lib";
import { CommandOutput, errorToJson, pickFields, 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("pickFields()", function() {
it("keeps only the given fields unless all is given", function() {
assert.deepEqual(pickFields({ a: 1, b: 2 }, ["a"]), { a: 1 });
assert.deepEqual(pickFields({ a: 1, b: 2 }, ["all"]), { a: 1, b: 2 });
});
});
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 a success line in human mode for commands without a result", function() {
assert.deepEqual(captureLog(() => new CommandOutput("human").finish()), ["Command ran successfully"]);
});
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 the toJSON format in wire mode", function() {
const output = new CommandOutput("wire");
const role = new lib.Role(1, "name", "desc", new Set(["core.admin"]));
const lines = captureLog(() => output.result({ role, set: new Set([1]), map: new Map([["a", 2]]) }));
assert.deepEqual(JSON.parse(lines[0]), { role: JSON.parse(JSON.stringify(role)), set: [1], map: { a: 2 } });
});
it("prints success for commands without a result", function() {
assert.deepEqual(captureLog(() => new CommandOutput("json").finish()), ['{"success":true}']);
const streaming = new CommandOutput("json");
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"), () => 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"]);
});
});
});
-88
View File
@@ -1,88 +0,0 @@
import assert from "node:assert/strict";
import * as lib from "@clusterio/lib";
import { modCommands } from "@clusterio/ctl/dist/node/src/commands_mod.js";
import { modPackCommands } from "@clusterio/ctl/dist/node/src/commands_mod_pack.js";
import { userCommands } from "@clusterio/ctl/dist/node/src/commands_user.js";
import { CommandOutput } from "@clusterio/ctl/dist/node/src/command_ops.js";
/** Run fn and return the lines it printed with console.log */
async 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 {
await fn();
} finally {
console.log = originalLog; // eslint-disable-line no-console
}
return lines;
}
/** Mock ctl answering requests by their class */
function mockCtl(responses) {
return {
output: new CommandOutput(),
async send(message) {
return responses.get(message.constructor)(message);
},
async sendTo(destination, message) {
return this.send(message);
},
};
}
describe("ctl/commands", function() {
describe("mod show", function() {
const show = modCommands.get("show");
it("prints list fields one entry per line", async function() {
const ctl = mockCtl(new Map([
[lib.ModGetRequest, () => ({ name: "a_mod", dependencies: ["base", "? other"] })],
]));
const lines = await captureLog(() => show.run({ name: "a_mod", modVersion: "1.0.0" }, ctl));
assert.deepEqual(lines, ["name: a_mod", "dependencies:", " base", " ? other"]);
});
it("rejects an invalid version", async function() {
await assert.rejects(
show.run({ name: "a_mod", modVersion: "latest" }, mockCtl(new Map())),
new lib.CommandError("mod-version must match format digit.digit.digit"),
);
});
});
describe("mod-pack show", function() {
it("marks missing mods and checksum mismatches and lists export assets", async function() {
const modPack = lib.ModPack.fromJSON({ id: 7, name: "pack" });
modPack.mods.set("gone", { name: "gone", enabled: true, version: "1.0.0" });
modPack.mods.set("changed", { name: "changed", enabled: false, version: "1.0.0", sha1: "aaa" });
modPack.exportManifest = { assets: { settings: "settings.json" } };
const ctl = mockCtl(new Map([
[lib.ModListRequest, () => [{ id: "changed_1.0.0", sha1: "bbb" }]],
[lib.ModPackListRequest, () => [modPack]],
[lib.ModPackGetRequest, () => modPack],
]));
const lines = await captureLog(() => modPackCommands.get("show").run({ modPack: "pack" }, ctl));
assert(lines.includes(" ? gone 1.0.0"), lines.join("\n"));
assert(lines.includes(" ! (disabled) changed 1.0.0 (aaa)"), lines.join("\n"));
assert(lines.includes(" settings: settings.json"), lines.join("\n"));
});
});
describe("user show", function() {
const show = userCommands.get("show");
it("prints stats per instance", async function() {
const stats = new lib.PlayerStats();
stats.joinCount = 2;
const user = new lib.UserDetails("alice");
user.instanceStats = new Map([[1, stats], [2, stats]]);
user.recalculatePlayerStats();
const ctl = mockCtl(new Map([
[lib.UserGetRequest, () => user],
[lib.InstanceDetailsListRequest, () => [{ id: 1, name: "one" }]],
]));
const lines = await captureLog(() => show.run({ name: "alice", instanceStats: true }, ctl));
assert(lines.includes("Instance one (1):"), lines.join("\n"));
assert(lines.includes("Instance <deleted> (2):"), lines.join("\n"));
assert(lines.some(line => /joinCount +\| 4/.test(line)), lines.join("\n"));
});
});
});
-91
View File
@@ -1,91 +0,0 @@
import assert from "node:assert/strict";
import * as lib from "@clusterio/lib";
import { instanceCommands } from "@clusterio/ctl/dist/node/src/commands_instance.js";
import { CommandOutput } from "@clusterio/ctl/dist/node/src/command_ops.js";
/** Run fn and return the lines it printed with console.log */
async 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 {
await fn();
} finally {
console.log = originalLog; // eslint-disable-line no-console
}
return lines;
}
describe("ctl/commands_instance", function() {
let instances;
let sentTo;
const ctl = {
output: new CommandOutput(),
async send(message) {
assert(message instanceof lib.InstanceDetailsListRequest);
return instances;
},
async sendTo(destination, message) {
sentTo.push([destination.instanceId, message.constructor.name]);
if (destination.instanceId === 2) {
throw new lib.CommandError("broken");
}
},
};
beforeEach(function() {
sentTo = [];
instances = [
{ id: 1, name: "one", status: "stopped", excludeFromStartAll: false },
{ id: 2, name: "two", status: "stopped", excludeFromStartAll: false },
{ id: 3, name: "three", status: "stopped", excludeFromStartAll: true },
{ id: 4, name: "four", status: "running", excludeFromStartAll: false },
];
});
describe("start-all", function() {
const startAll = instanceCommands.get("start-all");
it("starts stopped instances and reports each one", async function() {
ctl.output = new CommandOutput("human");
const lines = await captureLog(() => startAll.run({ force: false }, ctl));
assert.deepEqual(sentTo, [[1, "InstanceStartRequest"], [2, "InstanceStartRequest"]]);
assert(lines.includes("✓ Started one"), lines.join("\n"));
assert(lines.some(line => line.startsWith("✗ Failed to start two")), lines.join("\n"));
});
it("prints an entry per instance in json mode", async function() {
ctl.output = new CommandOutput("json");
const lines = await captureLog(() => startAll.run({ force: true }, ctl));
assert.deepEqual(JSON.parse(lines[0]), [
{ id: 1, name: "one" },
{ id: 2, name: "two", error: { error: "CommandError", message: "broken" } },
{ id: 3, name: "three" },
]);
});
it("reports when there is nothing to start", async function() {
instances = [];
ctl.output = new CommandOutput("human");
assert.deepEqual(await captureLog(() => startAll.run({ force: false }, ctl)), ["No instances to start."]);
});
});
describe("stop-all", function() {
const stopAll = instanceCommands.get("stop-all");
it("stops running instances and reports each one", async function() {
instances[1].status = "running";
ctl.output = new CommandOutput("human");
const lines = await captureLog(() => stopAll.run({}, ctl));
assert.deepEqual(sentTo, [[2, "InstanceStopRequest"], [4, "InstanceStopRequest"]]);
assert(lines.includes("✓ Stopped four"), lines.join("\n"));
assert(lines.some(line => line.startsWith("✗ Failed to stop two")), lines.join("\n"));
});
it("prints an entry per instance in json mode", async function() {
ctl.output = new CommandOutput("json");
const lines = await captureLog(() => stopAll.run({}, ctl));
assert.deepEqual(JSON.parse(lines[0]), [{ id: 4, name: "four" }]);
});
it("reports when there is nothing to stop", async function() {
instances = [];
ctl.output = new CommandOutput("human");
assert.deepEqual(await captureLog(() => stopAll.run({}, ctl)), ["No instances to stop."]);
});
});
});
-56
View File
@@ -1,56 +0,0 @@
import assert from "node:assert/strict";
import * as lib from "@clusterio/lib";
import { Ctl } from "@clusterio/ctl/dist/node/ctl.js";
import { CommandOutput } from "@clusterio/ctl/dist/node/src/command_ops.js";
/** Run fn and return the lines it printed with console.log */
async 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 {
await fn();
} finally {
console.log = originalLog; // eslint-disable-line no-console
}
return lines;
}
describe("ctl/ctl", function() {
describe("class Ctl", function() {
let ctl;
beforeEach(function() {
const connector = new lib.VirtualConnector(
lib.Address.fromShorthand({ controlId: 1 }),
lib.Address.fromShorthand("controller"),
);
ctl = new Ctl(connector, new lib.CtlConfig("control"));
});
it("prints log events as JSON lines only when streaming the log", async function() {
const info = { level: "info", message: "hello" };
ctl.output = new CommandOutput("json");
const logged = await captureLog(() => ctl.handleLogMessageEvent(new lib.LogMessageEvent({ ...info })));
assert(logged.every(line => !line.startsWith("{")), "log event printed as a result");
ctl.output.streamingLog = true;
assert.deepEqual(
await captureLog(() => ctl.handleLogMessageEvent(new lib.LogMessageEvent({ ...info, timestamp: 1 }))),
['{"level":"info","message":"hello","timestamp":1}'],
);
});
it("logs log events in human mode", async function() {
ctl.output.streamingLog = true;
const info = { level: "verbose", message: "hello" };
assert.deepEqual(await captureLog(() => ctl.handleLogMessageEvent(new lib.LogMessageEvent(info))), []);
});
it("prints debug WebSocket messages", async function() {
const event = new lib.DebugWsMessageEvent("in", "content");
assert.deepEqual(await captureLog(() => ctl.handleDebugWsMessageEvent(event)), ["WS in content"]);
ctl.output = new CommandOutput("json");
assert.deepEqual(
await captureLog(() => ctl.handleDebugWsMessageEvent(event)),
['{"direction":"in","content":"content"}'],
);
});
});
});
-124
View File
@@ -2064,9 +2064,6 @@ describe("Integration of Clusterio", function() {
const roundtrip = lib.ModPack.fromModPackString(result.stdout.trim()); const roundtrip = lib.ModPack.fromModPackString(result.stdout.trim());
roundtrip.id = reference.id; roundtrip.id = reference.id;
assert.deepEqual(roundtrip, reference); assert.deepEqual(roundtrip, reference);
const shown = await execCtlOutput("mod-pack show imported-pack");
assert.match(shown, /empty_mod 1\.0\.0/);
assert.match(shown, /MyDouble: 12\.25/);
}); });
}); });
@@ -2122,7 +2119,6 @@ describe("Integration of Clusterio", function() {
describe("mod show", function() { describe("mod show", function() {
it("gives details of a mod", async function() { it("gives details of a mod", async function() {
assert.match(await execCtlOutput("mod show empty_mod 1.0.0"), /name: empty_mod/);
let result = await execCtlProcess("mod show empty_mod 1.0.0"); let result = await execCtlProcess("mod show empty_mod 1.0.0");
let hash = await lib.hashFile(path.join("temp", "test", "mods", "empty_mod_1.0.0.zip")); let hash = await lib.hashFile(path.join("temp", "test", "mods", "empty_mod_1.0.0.zip"));
let stat = await fs.stat(path.join("temp", "test", "mods", "empty_mod_1.0.0.zip")); let stat = await fs.stat(path.join("temp", "test", "mods", "empty_mod_1.0.0.zip"));
@@ -2321,126 +2317,6 @@ describe("Integration of Clusterio", function() {
}); });
}); });
describe("config edit", function() {
/** Write an editor script that replaces the edited file with content */
async function writeEditor(content) {
const file = path.resolve("temp", "test", "editor.sh");
await fs.writeFile(file, `#!/bin/sh\ncat > "$1" <<'EOF'\n${content}\nEOF\n`, { mode: 0o755 });
return file;
}
before(function() {
if (process.platform === "win32") {
this.skip();
}
});
it("sets controller config fields and reports failed ones", async function() {
const config = await getControl().send(new lib.ControllerConfigGetRequest());
const name = config["controller.name"];
const editor = await writeEditor("controller.name = Edited-Cluster\ncontroller.no_such_field = 1");
await execCtl(`controller config edit ${editor}`);
const edited = await getControl().send(new lib.ControllerConfigGetRequest());
assert.equal(edited["controller.name"], "Edited-Cluster");
await execCtl(`controller config set controller.name ${name}`);
});
it("sets host config fields and reports failed ones", async function() {
const config = await getControl().sendTo({ hostId }, new lib.HostConfigGetRequest());
const editor = await writeEditor(`host.name = ${config["host.name"]}\nhost.no_such_field = 1`);
await execCtl(`host config edit ${hostId} ${editor}`);
});
it("sets instance config fields and reports failed ones", async function() {
const { id } = JSON.parse(await execCtlOutput("--output json instance create config-edit"));
try {
const editor = await writeEditor("instance.auto_start = true\ninstance.no_such_field = 1");
await execCtl(`instance config edit ${id} ${editor}`);
const config = await getControl().send(new lib.InstanceConfigGetRequest(id));
assert.equal(config["instance.auto_start"], true);
} finally {
await execCtl(`instance delete ${id}`);
}
});
});
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}`), '{"success":true}');
});
it("prints the toJSON format in wire mode", async function() {
const [jsonUser] = JSON.parse(await execCtlOutput("--output json user list"));
const [wireUser] = JSON.parse(await execCtlOutput("--output wire user list"));
assert("roleIds" in jsonUser);
assert(!("roleIds" in wireUser));
assert.equal(wireUser.name, jsonUser.name);
});
it("prints a success line for commands without a result", async function() {
const { id } = JSON.parse(await execCtlOutput("--output json role create human-role"));
assert.equal(await execCtlOutput(`role delete ${id}`), "Command ran successfully");
});
it("prints whole objects for lists that hide fields in human mode", async function() {
const [mod] = JSON.parse(await execCtlOutput("--output json mod list"));
assert("sha1" in mod);
const [wireMod] = JSON.parse(await execCtlOutput("--output wire mod list"));
assert("factorio_version" in wireMod);
const [modPack] = JSON.parse(await execCtlOutput("--output wire mod-pack list"));
assert("mods" in modPack);
const user = JSON.parse(await execCtlOutput("--output wire user show test --instance-stats"));
assert.equal(user.name, "test");
});
it("prints the user and instance stats in human mode", async function() {
const output = await execCtlOutput("user show test --instance-stats");
assert.match(output, /name +\| test/);
});
it("prints the result of human mode commands with more options", async function() {
assert.match(await execCtlOutput("user list --stats --attributes"), /isAdmin/);
const exchange = JSON.parse(await execCtlOutput(
`--output json debug parse-exchange-string ${testStrings.default.replace(/\s/g, "")}`
));
assert.equal(typeof exchange, "object");
});
it("follows the log without a final result", async function() {
try {
assert.equal(await execCtlOutput("--output json log follow --controller"), "");
} finally {
getControl().keepOpen = false;
}
});
it("prints log queries in human mode", async function() {
assert.notEqual(await execCtlOutput("log query --controller --limit 1"), "");
});
it("prints pending host requests in human mode", async function() {
assert.notEqual(await execCtlOutput("host pending"), "");
});
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() { describe("user list", function() {
it("prints roles and instances as lists", async function() { it("prints roles and instances as lists", async function() {
const output = await execCtlOutput("user list"); const output = await execCtlOutput("user list");
+3 -2
View File
@@ -10,7 +10,7 @@ import events from "node:events";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import { LineSplitter, logger } from "@clusterio/lib"; import { LineSplitter, logger } from "@clusterio/lib";
import { runCommand, initialize as initializeCtl } from "@clusterio/ctl"; import { selectTargetCommand, initialize as initializeCtl } from "@clusterio/ctl";
import { _listFactorioVersions } from "@clusterio/host/dist/node/src/server.js"; import { _listFactorioVersions } from "@clusterio/host/dist/node/src/server.js";
import { pairHost } from "@clusterio/host"; import { pairHost } from "@clusterio/host";
@@ -242,7 +242,8 @@ export async function execCtl(command) {
} }
control.config = initArgs.ctlConfig; control.config = initArgs.ctlConfig;
await runCommand(initArgs.args, initArgs.rootCommands, control); const targetCommand = selectTargetCommand(initArgs.args, initArgs.rootCommands);
await targetCommand.run(initArgs.args, control);
} finally { } finally {
process.chdir("../.."); process.chdir("../..");
inExecCtl = false; inExecCtl = false;