LibZNI/Arguments/ArgumentParser.cs

75 lines
No EOL
2.9 KiB
C#

using System;
using System.Collections.Generic;
namespace LibAC.Arguments;
public class ArgumentParser
{
public List<IArgument> Arguments { get; private set; }
public ArgumentParser()
{
Arguments = new List<IArgument>();
}
/// <summary>
/// Parses a string array of arguments.
/// </summary>
/// <param name="args">The string array of arguments to parse.</param>
public void Parse(string[] args)
{
for (int i = 0; i < args.Length; i++)
{
var arg = args[i];
if (arg.StartsWith("--"))
{
string key = arg.Substring(2); // Remove the '--' part of the argument
object? value = null;
// Check if the argument has a value attached (either --arg=value or --arg value)
if (i + 1 < args.Length && !args[i + 1].StartsWith("--"))
{
value = args[i + 1]; // --arg value
i++; // Skip the next argument as it is the value
}
else if (arg.Contains("="))
{
value = arg.Substring(arg.IndexOf('=') + 1); // --arg=value
}
// Determine the argument type and add it to the list
if (int.TryParse(value?.ToString(), out var intValue))
{
Arguments.Add(new IntegerArgument(key, intValue));
}
else if (bool.TryParse(value?.ToString(), out var boolValue))
{
Arguments.Add(new BooleanArgument(key, boolValue));
}
else if (float.TryParse(value?.ToString(), out var floatValue))
{
Arguments.Add(new FloatArgument(key, floatValue));
}
else if (double.TryParse(value?.ToString(), out var doubleValue))
{
Arguments.Add(new DoubleArgument(key, doubleValue));
}
else
{
// Default to StringArgument if no matching type is found
Arguments.Add(new StringArgument(key, value?.ToString()));
}
}
}
}
/// <summary>
/// Retrieves an argument by its key.
/// </summary>
/// <param name="key">The key of the argument to retrieve.</param>
/// <returns>The IArgument associated with the key, or null if not found.</returns>
public IArgument? GetArgument(string key)
{
return Arguments.Find(arg => arg.Key.Equals(key, StringComparison.OrdinalIgnoreCase));
}
}