This repository has been archived on 2023-02-02. You can view files and clone it, but cannot push or open issues or pull requests.
mfgames-toolbuilder-cil/src/MfGames.ToolBuilder/GlobalOptionHelper.cs
2022-01-02 02:14:51 -06:00

44 lines
1.3 KiB
C#

using System.CommandLine;
using System.CommandLine.Parsing;
namespace MfGames.ToolBuilder
{
/// <summary>
/// Helper methods for pulling out values without performing the full parse.
/// </summary>
public static class GlobalOptionHelper
{
public static TType GetArgumentValue<TType>(
Option<TType> option,
string[] arguments,
TType defaultValue)
{
// Normally, we should be using `RootCommand` here because it does
// the "right" thing with regards to picking up the executable name
// and path from the environment. However, it appears when the
// library/executable is stripped, it blows up. So we use Command
// directly and fake the RootCommand.
//
// We don't need a "real" executable name here, so we just hard-code
// a faked one.
var rootCommand = new Command("_executable", string.Empty)
{
option,
};
rootCommand.TreatUnmatchedTokensAsErrors = false;
ParseResult results = rootCommand.Parse(arguments);
if (!results.HasOption(option))
{
return defaultValue;
}
TType value = results.GetValueForOption(option)!;
return value;
}
}
}