From 79ad7114b89cca9c3d3160bc228561b970a7ccf1 Mon Sep 17 00:00:00 2001 From: Jeffrey Hsu Date: Tue, 24 Nov 2026 12:50:49 +0800 Subject: [PATCH] Add alias command to the interactive console --- README.md | 14 ++++++++ include/ConsoleCommand.h | 14 ++++++-- main.cpp | 6 ++-- src/AppConfig.cpp | 2 +- src/ConsoleCommand.cpp | 57 ++++++++++++++++++++++++----- tests/ConsoleCommandTests.cpp | 68 ++++++++++++++++++++++++++--------- 6 files changed, 131 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 9a907f3..c2abaa4 100644 --- a/README.md +++ b/README.md @@ -111,6 +111,7 @@ bilicraft-bot [--server host:port] [--account cache-key] | 命令 | 说明 | | --- | --- | +| `alias [名称 [命令 参数...]]` | 定义或覆盖别名,单给名称查看定义,不带参数列出全部别名 | | `run 路径.act` | 完整检查脚本及导入后入队,路径可用成对引号包裹 | | `tasks` | 显示任务编号、状态、命令进度和等待剩余时间 | | `help` | 显示终端帮助 | @@ -118,6 +119,19 @@ bilicraft-bot [--server host:port] [--account cache-key] 游戏命令与脚本共用下文语法,但 `wait` 和 `import` 仅能写在操作文件中。单条交互游戏命令提交后,终端会等它完成或失败,再接收下一条输入。 +### 命令别名 + +在终端输入 `alias 名称 命令 参数...` 保存快捷命令,定义时不会执行。调用时,名称后的参数会接在已保存的命令后面。例如: + +```text +>>> alias tell sendmsg @Steve +>>> tell 收获完成 +>>> alias demo run "../../actions/demo.act" +>>> demo +``` + +第二行等同于 `sendmsg @Steve 收获完成`,第四行会将示例脚本加入队列。别名仅在本次终端会话有效。支持引用其他别名,也可以用 `alias drop drop all` 给同名游戏命令预设参数。循环引用会报错。`alias` 本身是保留名称。 + ### 调度与退出 - 游戏操作在主线程串行执行。运行中的脚本会持续执行,直到完成、失败或遇到 `wait`;新任务不会抢占它。 diff --git a/include/ConsoleCommand.h b/include/ConsoleCommand.h index eeda7a5..c8f1ce5 100644 --- a/include/ConsoleCommand.h +++ b/include/ConsoleCommand.h @@ -1,18 +1,26 @@ #pragma once #include "ActionFile.h" +#include #include #include #include namespace Bilicraft { -enum class ConsoleKind { Empty, Action, Run, Tasks, Help, Quit }; +enum class ConsoleKind { Empty, Action, Run, Tasks, Help, Quit, Display }; struct ConsoleCommand { ConsoleKind kind = ConsoleKind::Empty; - std::string path; + std::string argument; // File path for Run, console output for Display. std::optional action; }; -ConsoleCommand ParseConsoleCommand(std::string_view line); +class ConsoleCommandParser +{ + public: + ConsoleCommand Parse(std::string_view line); + + private: + std::map> aliases; +}; std::string ConsoleHelp(); } // namespace Bilicraft diff --git a/main.cpp b/main.cpp index de4f2fd..bc2a359 100644 --- a/main.cpp +++ b/main.cpp @@ -89,6 +89,7 @@ int main(int argc, char **argv) return stopRequested ? 0 : 1; } + ConsoleCommandParser commandParser; ActionScheduler scheduler; if (program) scheduler.Enqueue(std::move(*program)); console->Start(); @@ -109,14 +110,15 @@ int main(int argc, char **argv) { const auto line = console->PollLine(); if (!line) return; - const auto request = ParseConsoleCommand(*line); + const auto request = commandParser.Parse(*line); switch (request.kind) { case ConsoleKind::Empty: break; + case ConsoleKind::Display: console->Out() << request.argument; break; case ConsoleKind::Help: console->Out() << ConsoleHelp(); break; case ConsoleKind::Quit: stopRequested = 1; break; case ConsoleKind::Run: - scheduler.Enqueue(LoadActionFile(request.path)); + scheduler.Enqueue(LoadActionFile(request.argument)); break; case ConsoleKind::Tasks: { diff --git a/src/AppConfig.cpp b/src/AppConfig.cpp index ac8efa8..0908ce2 100644 --- a/src/AppConfig.cpp +++ b/src/AppConfig.cpp @@ -46,7 +46,7 @@ std::string Usage() " --action Queue an initial .act task after login and start the console\n" " --check-action Validate a .act file and imports offline, then exit\n" " --help Show help without connecting or authenticating\n" - "Console: run file.act, tasks, help, quit, or a single game command (no wait).\n" + "Console: alias [name [command args...]], run file.act, tasks, help, quit, or a single game command (no wait).\n" "Microsoft authentication is required. Ctrl+C requests shutdown.\n"; } } // namespace Bilicraft diff --git a/src/ConsoleCommand.cpp b/src/ConsoleCommand.cpp index 98c2c47..a2d69c0 100644 --- a/src/ConsoleCommand.cpp +++ b/src/ConsoleCommand.cpp @@ -1,4 +1,5 @@ #include "ConsoleCommand.h" +#include #include #include @@ -12,17 +13,57 @@ std::string_view Trim(std::string_view text) if (first == std::string_view::npos) return {}; return text.substr(first, text.find_last_not_of(" \t\v\f") - first + 1); } -} -ConsoleCommand ParseConsoleCommand(std::string_view line) +std::pair SplitFirst(std::string_view text) { - if (line.size() > 65536 || line.find_first_of("\r\n") != std::string_view::npos || - line.find('\0') != std::string_view::npos) + const auto split = text.find_first_of(" \t\v\f"); + return {text.substr(0, split), split == text.npos ? std::string_view{} : Trim(text.substr(split))}; +} +} +ConsoleCommand ConsoleCommandParser::Parse(std::string_view line) +{ + constexpr std::size_t maxLength = 65536; + if (line.size() > maxLength || line.find_first_of("\r\n") != line.npos || line.find('\0') != line.npos) throw std::runtime_error(":1: expected a single line of at most 64 KiB"); line = Trim(line.substr(0, line.find('#'))); if (line.empty()) return {}; - const auto split = line.find_first_of(" \t\v\f"); - const auto verb = line.substr(0, split); - auto rest = split == std::string_view::npos ? std::string_view{} : Trim(line.substr(split)); + auto [verb, rest] = SplitFirst(line); + std::set expanded; // Views refer to stable map keys. + std::string buffer; + for (auto it = aliases.find(verb); it != aliases.end(); it = aliases.find(verb)) + { + if (!expanded.insert(it->first).second) + throw std::runtime_error(":1: alias cycle at " + it->first); + std::string next = it->second; + if (!rest.empty()) next.append(" ").append(rest); + if (next.size() > maxLength) throw std::runtime_error(":1: expanded command exceeds 64 KiB"); + buffer = std::move(next); + line = buffer; + const auto parts = SplitFirst(line); + verb = parts.first; + rest = parts.second; + if (verb == it->first) break; // Allow a shortcut such as "alias drop drop all". + } + if (verb == "alias") + { + const auto [name, body] = SplitFirst(rest); + if (name.empty()) + { + std::string output; + for (const auto &[key, value] : aliases) + output += "alias " + key + " " + value + "\n"; + return {ConsoleKind::Display, output.empty() ? "No aliases defined.\n" : std::move(output), {}}; + } + if (body.empty()) + { + const auto it = aliases.find(name); + if (it == aliases.end()) throw std::runtime_error(":1: unknown alias: " + std::string(name)); + return {ConsoleKind::Display, "alias " + it->first + " " + it->second + "\n", {}}; + } + if (name == "alias") throw std::runtime_error(":1: alias is a reserved name"); + aliases.insert_or_assign(std::string(name), std::string(body)); + return {}; + } + if (verb == "run") { if (rest.size() >= 2 && ((rest.front() == '"' && rest.back() == '"') || @@ -42,7 +83,7 @@ ConsoleCommand ParseConsoleCommand(std::string_view line) } std::string ConsoleHelp() { - return "Console: run | tasks | help | quit (or exit)\n" + return "Console: alias [name [command args...]] | run | tasks | help | quit (or exit)\n" "Game commands: goto, rclick, lclick, grclick, glclick, sw, swb, drop, sendcmd, sendmsg\n" "rclick/lclick: add entry [t|b|s|n|w|e] for item frames; omit face to require a unique frame.\n" "A game command waits until the running action finishes or reaches wait.\n" diff --git a/tests/ConsoleCommandTests.cpp b/tests/ConsoleCommandTests.cpp index 1f8ff56..fda92bd 100644 --- a/tests/ConsoleCommandTests.cpp +++ b/tests/ConsoleCommandTests.cpp @@ -16,37 +16,72 @@ namespace using namespace Bilicraft; TEST(ConsoleCommand, ParsesControlCommandsAndPathsWithSpaces) { - EXPECT_EQ(ParseConsoleCommand(" ").kind, ConsoleKind::Empty); - EXPECT_EQ(ParseConsoleCommand("# comment").kind, ConsoleKind::Empty); - EXPECT_EQ(ParseConsoleCommand("help # help").kind, ConsoleKind::Help); - EXPECT_EQ(ParseConsoleCommand("tasks").kind, ConsoleKind::Tasks); - EXPECT_EQ(ParseConsoleCommand("exit").kind, ConsoleKind::Quit); - EXPECT_EQ(ParseConsoleCommand("quit").kind, ConsoleKind::Quit); - EXPECT_EQ(ParseConsoleCommand("run ../../actions/demo.act").path, "../../actions/demo.act"); - EXPECT_EQ(ParseConsoleCommand("run \"path with spaces.act\"").path, "path with spaces.act"); - EXPECT_EQ(ParseConsoleCommand("run 'path with spaces.act'").path, "path with spaces.act"); + ConsoleCommandParser parser; + EXPECT_EQ(parser.Parse(" ").kind, ConsoleKind::Empty); + EXPECT_EQ(parser.Parse("# comment").kind, ConsoleKind::Empty); + EXPECT_EQ(parser.Parse("help # help").kind, ConsoleKind::Help); + EXPECT_EQ(parser.Parse("tasks").kind, ConsoleKind::Tasks); + EXPECT_EQ(parser.Parse("exit").kind, ConsoleKind::Quit); + EXPECT_EQ(parser.Parse("quit").kind, ConsoleKind::Quit); + EXPECT_EQ(parser.Parse("run ../../actions/demo.act").argument, "../../actions/demo.act"); + EXPECT_EQ(parser.Parse("run \"path with spaces.act\"").argument, "path with spaces.act"); + EXPECT_EQ(parser.Parse("run 'path with spaces.act'").argument, "path with spaces.act"); } TEST(ConsoleCommand, RejectsInvalidControlsAndInteractiveWaitOrImport) { + ConsoleCommandParser parser; for (auto text : {"run", "run \"\"", "help now", "tasks 1", "quit now", "wait 3", "import demo", "sw 1\nsw 2", "sw 1\rsw 2"}) - EXPECT_THROW(ParseConsoleCommand(text), std::exception) << text; - EXPECT_THROW(ParseConsoleCommand(std::string("sw 1\0x", 6)), std::exception); + EXPECT_THROW(parser.Parse(text), std::exception) << text; + EXPECT_THROW(parser.Parse(std::string("sw 1\0x", 6)), std::exception); } TEST(ConsoleCommand, UsesTheSameGameCommandParser) { - const auto message = ParseConsoleCommand("sendmsg @Steve hello world"); + ConsoleCommandParser parser; + const auto message = parser.Parse("sendmsg @Steve hello world"); ASSERT_EQ(message.kind, ConsoleKind::Action); ASSERT_TRUE(message.action); EXPECT_EQ(message.action->recipient, "Steve"); EXPECT_EQ(message.action->text, "hello world"); - EXPECT_EQ(ParseConsoleCommand("drop all").action->kind, ActionKind::Drop); - EXPECT_TRUE(ParseConsoleCommand("drop all").action->all); + EXPECT_EQ(parser.Parse("drop all").action->kind, ActionKind::Drop); + EXPECT_TRUE(parser.Parse("drop all").action->all); +} + +TEST(ConsoleCommand, ExpandsSessionAliasesWithArguments) +{ + ConsoleCommandParser parser; + EXPECT_EQ(parser.Parse("alias tell sendmsg @Steve").kind, ConsoleKind::Empty); + parser.Parse("alias report tell 收获"); + const auto result = parser.Parse("report 完成 # comment"); + ASSERT_TRUE(result.action); + EXPECT_EQ(result.action->recipient, "Steve"); + EXPECT_EQ(result.action->text, "收获 完成"); + parser.Parse("alias tell run"); + EXPECT_EQ(parser.Parse("tell 'path with spaces.act'").argument, "path with spaces.act"); + EXPECT_EQ(parser.Parse("alias tell").argument, "alias tell run\n"); + EXPECT_EQ(parser.Parse("alias").argument, "alias report tell 收获\nalias tell run\n"); + EXPECT_THROW(ConsoleCommandParser{}.Parse("tell hello"), std::exception); +} + +TEST(ConsoleCommand, SupportsSameNameDefaultsAndRejectsAliasCyclesAndOversizedExpansion) +{ + ConsoleCommandParser parser; + parser.Parse("alias sw sw 2"); + const auto selected = parser.Parse("sw"); + ASSERT_TRUE(selected.action); + EXPECT_EQ(selected.action->slot, 2); + parser.Parse("alias a b"); + parser.Parse("alias b a"); + EXPECT_THROW(parser.Parse("a"), std::exception); + EXPECT_THROW(parser.Parse("alias alias quit"), std::exception); + parser.Parse("alias m sendmsg hello"); + EXPECT_THROW(parser.Parse("m " + std::string(65534, 'x')), std::exception); } #ifndef _WIN32 TEST(ConsoleCommand, NativePseudoTerminalWaitsForEnterAndParsesTheCommand) { + ConsoleCommandParser parser; const int master = posix_openpt(O_RDWR | O_NOCTTY); ASSERT_GE(master, 0); struct Fd @@ -75,7 +110,7 @@ TEST(ConsoleCommand, NativePseudoTerminalWaitsForEnterAndParsesTheCommand) if (!line) std::this_thread::yield(); } ASSERT_TRUE(line); - const auto command = ParseConsoleCommand(*line); + const auto command = parser.Parse(*line); ASSERT_TRUE(command.action); EXPECT_EQ(command.action->kind, ActionKind::SelectHotbar); EXPECT_EQ(command.action->slot, 3); @@ -83,6 +118,7 @@ TEST(ConsoleCommand, NativePseudoTerminalWaitsForEnterAndParsesTheCommand) TEST(ConsoleCommand, PipeInputDoesNotConsumeNextCommandUntilPreviousExecutionFinishes) { + ConsoleCommandParser parser; int descriptors[2]; ASSERT_EQ(pipe(descriptors), 0); struct Close @@ -104,7 +140,7 @@ TEST(ConsoleCommand, PipeInputDoesNotConsumeNextCommandUntilPreviousExecutionFin if (auto line = terminal.PollLine()) { ++linesRead; - scheduler.SubmitInteractive(*ParseConsoleCommand(*line).action); + scheduler.SubmitInteractive(*parser.Parse(*line).action); } }; pump();