diff --git a/src/Microsoft.TemplateEngine.Cli/Commands/BaseFilterableArgs.cs b/src/Microsoft.TemplateEngine.Cli/Commands/BaseFilterableArgs.cs new file mode 100644 index 00000000000..cac2fd0608e --- /dev/null +++ b/src/Microsoft.TemplateEngine.Cli/Commands/BaseFilterableArgs.cs @@ -0,0 +1,68 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#nullable enable + +using System.CommandLine.Parsing; + +namespace Microsoft.TemplateEngine.Cli.Commands +{ + internal class BaseFilterableArgs : GlobalArgs + { + private IReadOnlyDictionary _filters; + + internal BaseFilterableArgs(BaseCommand command, ParseResult parseResult) : base(command, parseResult) + { + if (command is not IFilterableCommand filterableCommand) + { + throw new ArgumentException($"{nameof(command)} should be {nameof(IFilterableCommand)}", nameof(command)); + } + _filters = ParseFilters(filterableCommand, parseResult); + } + + /// + /// Gets list of parsed from command. + /// + internal IEnumerable AppliedFilters => _filters.Keys; + + /// + /// Gets value for filter . + /// + /// + /// value of the filter. + /// when is not among . + internal string GetFilterValue(FilterOptionDefinition filter) + { + if (!_filters.ContainsKey(filter)) + { + throw new ArgumentException($"{nameof(filter)} is not available in parse result.", nameof(filter)); + } + + return _filters[filter].GetValueOrDefault() ?? string.Empty; + } + + /// + /// Gets token name used for filter . + /// + /// + /// Token or null when token cannot be evaluated. + internal string? GetFilterToken(FilterOptionDefinition filter) + { + return _filters[filter].Token?.Value; + } + + private static IReadOnlyDictionary ParseFilters(IFilterableCommand filterableCommand, ParseResult parseResult) + { + Dictionary filterValues = new(); + foreach (var filter in filterableCommand.Filters) + { + OptionResult? value = parseResult.FindResultFor(filter.Value); + if (value != null) + { + filterValues[filter.Key] = value; + } + } + return filterValues; + } + } +} diff --git a/src/Microsoft.TemplateEngine.Cli/Commands/FilterOptionDefinition.cs b/src/Microsoft.TemplateEngine.Cli/Commands/FilterOptionDefinition.cs index 959f8d205c5..26608871514 100644 --- a/src/Microsoft.TemplateEngine.Cli/Commands/FilterOptionDefinition.cs +++ b/src/Microsoft.TemplateEngine.Cli/Commands/FilterOptionDefinition.cs @@ -18,66 +18,52 @@ namespace Microsoft.TemplateEngine.Cli.Commands /// internal class FilterOptionDefinition { - internal FilterOptionDefinition(string name, Func