命令行允许输入""来表示一个完整的字符串

This commit is contained in:
milimoe 2026-05-12 22:31:40 +08:00
parent 1598eef40b
commit 47e8b1cd1f
Signed by: milimoe
GPG Key ID: 9554D37E4B8991D0
3 changed files with 72 additions and 4 deletions

View File

@ -101,8 +101,8 @@ while (Running)
ServerHelper.Type();
if (input != "" && Running)
{
string[] strings = input.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (strings.Length > 0)
List<string> strings = ConsoleModel.ParseCommandLine(input);
if (strings.Count > 0)
{
string order = strings[0].ToLower();
string[] inputArgs = [.. strings.Skip(1)];

View File

@ -204,6 +204,74 @@ namespace Milimoe.FunGame.Server.Model
}
}
public static List<string> ParseCommandLine(string input)
{
ReadOnlySpan<char> inputSpan = input.AsSpan();
List<string> strings = [];
StringBuilder current = new();
bool inQuotes = false;
for (int i = 0; i < inputSpan.Length; i++)
{
char c = inputSpan[i];
if (inQuotes)
{
if (c == '"')
{
// 检查是否是转义引号 \"
if (i + 1 < inputSpan.Length && inputSpan[i + 1] == '"')
{
current.Append('"');
// 跳过下一个引号
i++;
}
else
{
// 结束引号
inQuotes = false;
}
}
else if (c == '\\' && i + 1 < inputSpan.Length && inputSpan[i + 1] == '"')
{
current.Append('"');
i++;
}
else
{
current.Append(c);
}
}
else
{
if (c == '"')
{
inQuotes = true;
}
else if (char.IsWhiteSpace(c))
{
if (current.Length > 0)
{
strings.Add(current.ToString());
current.Clear();
}
}
else
{
current.Append(c);
}
}
}
// 收尾最后一个参数
if (current.Length > 0)
{
strings.Add(current.ToString());
}
return strings;
}
public static string GetOrderAliases(string order)
{
string[] alias = [.. FunGameSystem.OrderAliasList.Where(kv => kv.Value == order).Select(kv => kv.Key)];

View File

@ -296,8 +296,8 @@ async Task GetConsoleOrder()
ServerHelper.Type();
if (input != "")
{
string[] strings = input.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (strings.Length > 0)
List<string> strings = ConsoleModel.ParseCommandLine(input);
if (strings.Count > 0)
{
string order = strings[0].ToLower();
string[] args = [.. strings.Skip(1)];