using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Robust.Shared.Console;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Utility;
namespace Robust.Shared.Configuration
{
public static class CVarCommandUtil
{
///
/// Parses a string into an object of the given type.
///
/// Thrown if the string could not be parsed into the given type.
/// Thrown if the type is not supported.
public static object ParseObject(Type type, string input)
{
if (type == typeof(bool))
{
if (bool.TryParse(input, out var val))
return val;
if (Parse.TryInt32(input, out var intVal))
{
if (intVal == 0) return false;
if (intVal == 1) return true;
}
throw new FormatException($"Could not parse bool value: {input}");
}
if (type == typeof(string))
{
return input;
}
if (type == typeof(int))
{
return Parse.Int32(input);
}
if (type == typeof(float))
{
return Parse.Float(input);
}
if (type == typeof(long))
{
return long.Parse(input);
}
if (type == typeof(ushort))
{
return ushort.Parse(input);
}
throw new NotSupportedException();
}
}
[SuppressMessage("ReSharper", "StringLiteralTypo")]
internal sealed class CVarCommand : LocalizedCommands
{
[Dependency] private readonly IConfigurationManager _cfg = default!;
public override string Command => "cvar";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (args.Length is < 1 or > 2)
{
shell.WriteError(Loc.GetString("cmd-cvar-invalid-args"));
return;
}
var name = args[0];
if (name == "?")
{
var cvars = _cfg.GetRegisteredCVars().OrderBy(c => c);
shell.WriteLine(string.Join("\n", cvars));
return;
}
if (!_cfg.IsCVarRegistered(name))
{
shell.WriteError(Loc.GetString("cmd-cvar-not-registered", ("cvar", name)));
return;
}
if (args.Length == 1)
{
// Read CVar
var value = _cfg.GetCVar