From 3722cbfa97e7c154ca864c3624c8261ef8cdcc9f Mon Sep 17 00:00:00 2001 From: DrSmugleaf Date: Mon, 30 Nov 2020 14:00:09 +0100 Subject: [PATCH] Add remove extra components command (#2640) --- .../Commands/RemoveExtraComponents.cs | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Content.Server/Commands/RemoveExtraComponents.cs diff --git a/Content.Server/Commands/RemoveExtraComponents.cs b/Content.Server/Commands/RemoveExtraComponents.cs new file mode 100644 index 0000000000..b5b269fb83 --- /dev/null +++ b/Content.Server/Commands/RemoveExtraComponents.cs @@ -0,0 +1,74 @@ +#nullable enable +using Content.Server.Administration; +using Content.Shared.Administration; +using Robust.Server.Interfaces.Console; +using Robust.Server.Interfaces.Player; +using Robust.Shared.GameObjects; +using Robust.Shared.Interfaces.GameObjects; +using Robust.Shared.IoC; +using Robust.Shared.Prototypes; + +namespace Content.Server.Commands +{ + [AdminCommand(AdminFlags.Mapping)] + public class RemoveExtraComponents : IClientCommand + { + public string Command => "removeextracomponents"; + public string Description => "Removes all components from all entities of the specified id if that component is not in its prototype.\nIf no id is specified, it matches all entities."; + public string Help => $"{Command} / {Command}"; + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) + { + var id = args.Length == 0 ? null : string.Join(" ", args); + var entityManager = IoCManager.Resolve(); + var prototypeManager = IoCManager.Resolve(); + + IEntityQuery query; + + if (id == null) + { + query = new AllEntityQuery(); + } + else + { + if (!prototypeManager.TryIndex(id, out EntityPrototype prototype)) + { + shell.SendText(player, $"No entity prototype found with id {id}."); + return; + } + + query = new PredicateEntityQuery(e => e.Prototype == prototype); + } + + var entities = 0; + var components = 0; + + foreach (var entity in entityManager.GetEntities(query)) + { + if (entity.Prototype == null) + { + continue; + } + + var modified = false; + + foreach (var component in entity.GetAllComponents()) + { + if (!entity.Prototype.Components.ContainsKey(component.Name)) + { + entityManager.ComponentManager.RemoveComponent(entity.Uid, component); + components++; + + modified = true; + } + } + + if (modified) + { + entities++; + } + } + + shell.SendText(player, $"Removed {components} components from {entities} entities{(id == null ? "." : $" with id {id}")}"); + } + } +}