feat: add regex argument type to console command builder
This commit is contained in:
@@ -8,13 +8,20 @@ public enum CommandArgType
|
||||
Int,
|
||||
Float,
|
||||
Bool,
|
||||
Choice
|
||||
Choice,
|
||||
Regex
|
||||
}
|
||||
|
||||
public sealed record CommandArgSpec(string Name, CommandArgType Type, IReadOnlyList<string> Choices = null)
|
||||
{
|
||||
public override string ToString() =>
|
||||
Type == CommandArgType.Choice && Choices is not null
|
||||
? string.Join("|", Choices)
|
||||
: Type.ToString().ToLowerInvariant();
|
||||
public sealed record CommandArgSpec(
|
||||
string Name,
|
||||
CommandArgType Type,
|
||||
IReadOnlyList<string> Choices = null,
|
||||
string Pattern = null
|
||||
) {
|
||||
public override string ToString() => Type switch
|
||||
{
|
||||
CommandArgType.Choice when Choices is not null => string.Join("|", Choices),
|
||||
CommandArgType.Regex when Pattern is not null => "regex",
|
||||
_ => Type.ToString().ToLowerInvariant()
|
||||
};
|
||||
}
|
||||
|
||||
@@ -36,5 +36,11 @@ public sealed class CommandArgsBuilder
|
||||
return this;
|
||||
}
|
||||
|
||||
public CommandArgsBuilder AddRegexArg(string name, string pattern)
|
||||
{
|
||||
_specs.Add(new CommandArgSpec(name, CommandArgType.Regex, Pattern: pattern));
|
||||
return this;
|
||||
}
|
||||
|
||||
public IReadOnlyList<CommandArgSpec> Build() => _specs.ToArray();
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using Game.Features.Console.Contracts;
|
||||
|
||||
namespace Game.Features.Console.Domain;
|
||||
@@ -18,6 +19,7 @@ public static class CommandArgValidator
|
||||
CommandArgType.Float => float.TryParse(rawValue, NumberStyles.Float, CultureInfo.InvariantCulture, out _),
|
||||
CommandArgType.Bool => bool.TryParse(rawValue, out _),
|
||||
CommandArgType.Choice => spec.Choices is not null && ChoicesContain(spec.Choices, rawValue),
|
||||
CommandArgType.Regex => spec.Pattern is not null && Regex.IsMatch(rawValue, spec.Pattern),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(spec), spec.Type, null)
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user