Fix console command registration

This commit is contained in:
Evil Factory
2026-03-22 12:42:09 -03:00
parent 994610869d
commit de53b4514e
6 changed files with 89 additions and 58 deletions
@@ -1,11 +1,15 @@
using System;
using Barotrauma.LuaCs.Events;
using Barotrauma.Networking;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
namespace Barotrauma.LuaCs;
public class ConsoleCommandsService : IConsoleCommandsService
internal class ConsoleCommandsService : IConsoleCommandsService
{
private readonly ConcurrentDictionary<string, DebugConsole.Command> _registeredCommands = new();
@@ -15,10 +19,12 @@ public class ConsoleCommandsService : IConsoleCommandsService
{
return;
}
foreach (var cmd in _registeredCommands.Values.ToImmutableArray())
{
DebugConsole.Commands.Remove(cmd);
}
_registeredCommands.Clear();
}
@@ -28,18 +34,46 @@ public class ConsoleCommandsService : IConsoleCommandsService
get => ModUtils.Threading.GetBool(ref _isDisposed);
private set => ModUtils.Threading.SetBool(ref _isDisposed, value);
}
public FluentResults.Result RegisterCommand(string name, string help, Action<string[]> onExecute, Func<string[][]> getValidArgs = null, bool isCheat = false)
public void RegisterCommand(string name, string help, Action<string[]> onExecute, Func<string[][]> getValidArgs = null, bool isCheat = false)
{
IService.CheckDisposed(this);
var cmd = new DebugConsole.Command(name, help, onExecute, getValidArgs, isCheat);
if (!_registeredCommands.TryAdd(name, cmd))
{
return FluentResults.Result.Fail($"{nameof(RegisterCommand)}: A command with the name '{name}' is already added.");
throw new ArgumentException($"A command with the name '{name}' is already registered.");
}
DebugConsole.Commands.Add(cmd);
return FluentResults.Result.Ok();
}
public void AssignOnExecute(string names, Action<string[]> onExecute)
{
var matchingCommand = DebugConsole.Commands.Find(c => c.Names.Intersect(names.Split('|').ToIdentifiers()).Any());
if (matchingCommand == null)
{
throw new Exception("AssignOnExecute failed. Command matching the name(s) \"" + names + "\" not found.");
}
else
{
matchingCommand.OnExecute = onExecute;
}
}
#if SERVER
public void AssignOnClientRequestExecute(string names, Action<Client, Vector2, string[]> onClientRequestExecute)
{
var matchingCommand = DebugConsole.Commands.Find(c => c.Names.Intersect(names.Split('|').ToIdentifiers()).Any());
if (matchingCommand == null)
{
throw new Exception("AssignOnClientRequestExecute failed. Command matching the name(s) \"" + names + "\" not found.");
}
else
{
matchingCommand.OnClientRequestExecute = onClientRequestExecute;
}
}
#endif
public void RemoveCommand(string name)
{
IService.CheckDisposed(this);