From 63c7fc66fead66dd740ff299caf4afd413eff9cf Mon Sep 17 00:00:00 2001 From: Eric Erhardt Date: Fri, 16 Oct 2020 22:26:03 -0500 Subject: [PATCH] Remove unused Common Extensions code (#43452) --- .../AspNetCoreBenchmarkAttribute.cs | 73 -- .../BenchmarkRunner/DefaultCoreConfig.cs | 46 - .../BenchmarkRunner/DefaultCoreDebugConfig.cs | 23 - .../BenchmarkRunner/DefaultCorePerfLabConfig.cs | 48 - .../BenchmarkRunner/DefaultCoreProfileConfig.cs | 32 - .../BenchmarkRunner/DefaultCoreValidationConfig.cs | 20 - .../ParameterizedJobConfigAttribute.cs | 15 - .../BenchmarkRunner/ParamsDisplayInfoColumn.cs | 26 - .../src/Extensions/BenchmarkRunner/Program.cs | 106 -- .../CommandLineUtils/CommandLine/AnsiConsole.cs | 143 --- .../CommandLine/CommandArgument.cs | 29 - .../CommandLine/CommandLineApplication.cs | 644 ----------- .../CommandLineUtils/CommandLine/CommandOption.cs | 108 -- .../CommandLine/CommandOptionType.cs | 13 - .../CommandLine/CommandParsingException.cs | 18 - ...t.Extensions.CommandLineUtils.Sources.projitems | 14 - .../CommandLineUtils/Utilities/ArgumentEscaper.cs | 109 -- .../CommandLineUtils/Utilities/DotNetMuxer.cs | 57 - .../Common/src/Extensions/Directory.Build.props | 24 - .../Common/src/Extensions/ReferenceAssemblyInfo.cs | 10 - .../tests/Extensions/ArgumentEscaperTests.cs | 24 - .../Extensions/CommandLineApplicationTests.cs | 1219 -------------------- .../Common/tests/Extensions/DotNetMuxerTests.cs | 24 - 23 files changed, 2825 deletions(-) delete mode 100644 src/libraries/Common/src/Extensions/BenchmarkRunner/AspNetCoreBenchmarkAttribute.cs delete mode 100644 src/libraries/Common/src/Extensions/BenchmarkRunner/DefaultCoreConfig.cs delete mode 100644 src/libraries/Common/src/Extensions/BenchmarkRunner/DefaultCoreDebugConfig.cs delete mode 100644 src/libraries/Common/src/Extensions/BenchmarkRunner/DefaultCorePerfLabConfig.cs delete mode 100644 src/libraries/Common/src/Extensions/BenchmarkRunner/DefaultCoreProfileConfig.cs delete mode 100644 src/libraries/Common/src/Extensions/BenchmarkRunner/DefaultCoreValidationConfig.cs delete mode 100644 src/libraries/Common/src/Extensions/BenchmarkRunner/ParameterizedJobConfigAttribute.cs delete mode 100644 src/libraries/Common/src/Extensions/BenchmarkRunner/ParamsDisplayInfoColumn.cs delete mode 100644 src/libraries/Common/src/Extensions/BenchmarkRunner/Program.cs delete mode 100644 src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/AnsiConsole.cs delete mode 100644 src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/CommandArgument.cs delete mode 100644 src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/CommandLineApplication.cs delete mode 100644 src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/CommandOption.cs delete mode 100644 src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/CommandOptionType.cs delete mode 100644 src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/CommandParsingException.cs delete mode 100644 src/libraries/Common/src/Extensions/CommandLineUtils/Microsoft.Extensions.CommandLineUtils.Sources.projitems delete mode 100644 src/libraries/Common/src/Extensions/CommandLineUtils/Utilities/ArgumentEscaper.cs delete mode 100644 src/libraries/Common/src/Extensions/CommandLineUtils/Utilities/DotNetMuxer.cs delete mode 100644 src/libraries/Common/src/Extensions/Directory.Build.props delete mode 100644 src/libraries/Common/src/Extensions/ReferenceAssemblyInfo.cs delete mode 100644 src/libraries/Common/tests/Extensions/ArgumentEscaperTests.cs delete mode 100644 src/libraries/Common/tests/Extensions/CommandLineApplicationTests.cs delete mode 100644 src/libraries/Common/tests/Extensions/DotNetMuxerTests.cs diff --git a/src/libraries/Common/src/Extensions/BenchmarkRunner/AspNetCoreBenchmarkAttribute.cs b/src/libraries/Common/src/Extensions/BenchmarkRunner/AspNetCoreBenchmarkAttribute.cs deleted file mode 100644 index 22ad0fb..0000000 --- a/src/libraries/Common/src/Extensions/BenchmarkRunner/AspNetCoreBenchmarkAttribute.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System; -using System.Collections.Generic; -using BenchmarkDotNet.Configs; - -namespace BenchmarkDotNet.Attributes -{ - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly)] - internal class AspNetCoreBenchmarkAttribute : Attribute, IConfigSource - { - public AspNetCoreBenchmarkAttribute() - : this(typeof(DefaultCoreConfig)) - { - } - - public AspNetCoreBenchmarkAttribute(Type configType) - : this(configType, typeof(DefaultCoreValidationConfig)) - { - } - - public AspNetCoreBenchmarkAttribute(Type configType, Type validationConfigType) - { - ConfigTypes = new Dictionary() - { - { NamedConfiguration.Default, typeof(DefaultCoreConfig) }, - { NamedConfiguration.Validation, typeof(DefaultCoreValidationConfig) }, - { NamedConfiguration.Profile, typeof(DefaultCoreProfileConfig) }, - { NamedConfiguration.Debug, typeof(DefaultCoreDebugConfig) }, - { NamedConfiguration.PerfLab, typeof(DefaultCorePerfLabConfig) }, - }; - - if (configType != null) - { - ConfigTypes[NamedConfiguration.Default] = configType; - } - - if (validationConfigType != null) - { - ConfigTypes[NamedConfiguration.Validation] = validationConfigType; - } - } - - public IConfig Config - { - get - { - if (!ConfigTypes.TryGetValue(ConfigName ?? NamedConfiguration.Default, out var configType)) - { - var message = $"Could not find a configuration matching {ConfigName}. " + - $"Known configurations: {string.Join(", ", ConfigTypes.Keys)}"; - throw new InvalidOperationException(message); - } - - return (IConfig)Activator.CreateInstance(configType, Array.Empty()); - } - } - - public Dictionary ConfigTypes { get; } - - public static string ConfigName { get; set; } = NamedConfiguration.Default; - - public static class NamedConfiguration - { - public static readonly string Default = "default"; - public static readonly string Validation = "validation"; - public static readonly string Profile = "profile"; - public static readonly string Debug = "debug"; - public static readonly string PerfLab = "perflab"; - } - } -} diff --git a/src/libraries/Common/src/Extensions/BenchmarkRunner/DefaultCoreConfig.cs b/src/libraries/Common/src/Extensions/BenchmarkRunner/DefaultCoreConfig.cs deleted file mode 100644 index 5c4b4bd..0000000 --- a/src/libraries/Common/src/Extensions/BenchmarkRunner/DefaultCoreConfig.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using BenchmarkDotNet.Columns; -using BenchmarkDotNet.Configs; -using BenchmarkDotNet.Diagnosers; -using BenchmarkDotNet.Engines; -using BenchmarkDotNet.Exporters; -using BenchmarkDotNet.Jobs; -using BenchmarkDotNet.Loggers; -using BenchmarkDotNet.Toolchains.CsProj; -using BenchmarkDotNet.Toolchains.DotNetCli; -using BenchmarkDotNet.Validators; - -namespace BenchmarkDotNet.Attributes -{ - internal class DefaultCoreConfig : ManualConfig - { - public DefaultCoreConfig() - { - Add(ConsoleLogger.Default); - Add(MarkdownExporter.GitHub); - - Add(MemoryDiagnoser.Default); - Add(StatisticColumn.OperationsPerSecond); - Add(DefaultColumnProviders.Instance); - - Add(JitOptimizationsValidator.FailOnError); - - Add(Job.Core -#if NETCOREAPP2_1 - .With(CsProjCoreToolchain.From(NetCoreAppSettings.NetCoreApp21)) -#elif NETCOREAPP3_0 - .With(CsProjCoreToolchain.From(new NetCoreAppSettings("netcoreapp3.0", null, ".NET Core 3.0"))) -#elif NETCOREAPP3_1 - .With(CsProjCoreToolchain.From(new NetCoreAppSettings("netcoreapp3.1", null, ".NET Core 3.1"))) -#elif NETCOREAPP5_0 - .With(CsProjCoreToolchain.From(new NetCoreAppSettings("net5.0", null, ".NET 5.0"))) -#else -#error Target frameworks need to be updated. -#endif - .With(new GcMode { Server = true }) - .With(RunStrategy.Throughput)); - } - } -} diff --git a/src/libraries/Common/src/Extensions/BenchmarkRunner/DefaultCoreDebugConfig.cs b/src/libraries/Common/src/Extensions/BenchmarkRunner/DefaultCoreDebugConfig.cs deleted file mode 100644 index 0f477c4..0000000 --- a/src/libraries/Common/src/Extensions/BenchmarkRunner/DefaultCoreDebugConfig.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using BenchmarkDotNet.Configs; -using BenchmarkDotNet.Engines; -using BenchmarkDotNet.Jobs; -using BenchmarkDotNet.Loggers; -using BenchmarkDotNet.Validators; - -namespace BenchmarkDotNet.Attributes -{ - internal class DefaultCoreDebugConfig : ManualConfig - { - public DefaultCoreDebugConfig() - { - Add(ConsoleLogger.Default); - Add(JitOptimizationsValidator.DontFailOnError); - - Add(Job.InProcess - .With(RunStrategy.Throughput)); - } - } -} diff --git a/src/libraries/Common/src/Extensions/BenchmarkRunner/DefaultCorePerfLabConfig.cs b/src/libraries/Common/src/Extensions/BenchmarkRunner/DefaultCorePerfLabConfig.cs deleted file mode 100644 index 25b150c..0000000 --- a/src/libraries/Common/src/Extensions/BenchmarkRunner/DefaultCorePerfLabConfig.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using BenchmarkDotNet.Columns; -using BenchmarkDotNet.Configs; -using BenchmarkDotNet.Diagnosers; -using BenchmarkDotNet.Engines; -using BenchmarkDotNet.Exporters; -using BenchmarkDotNet.Exporters.Csv; -using BenchmarkDotNet.Jobs; -using BenchmarkDotNet.Loggers; -using BenchmarkDotNet.Validators; - -namespace BenchmarkDotNet.Attributes -{ - internal class DefaultCorePerfLabConfig : ManualConfig - { - public DefaultCorePerfLabConfig() - { - Add(ConsoleLogger.Default); - - Add(MemoryDiagnoser.Default); - Add(StatisticColumn.OperationsPerSecond); - Add(new ParamsSummaryColumn()); - Add(DefaultColumnProviders.Statistics, DefaultColumnProviders.Diagnosers, DefaultColumnProviders.Target); - - // TODO: When upgrading to BDN 0.11.1, use Add(DefaultColumnProviders.Descriptor); - // DefaultColumnProviders.Target is deprecated - - Add(JitOptimizationsValidator.FailOnError); - - Add(Job.InProcess - .With(RunStrategy.Throughput)); - - Add(MarkdownExporter.GitHub); - - Add(new CsvExporter( - CsvSeparator.Comma, - new Reports.SummaryStyle - { - PrintUnitsInHeader = true, - PrintUnitsInContent = false, - TimeUnit = Horology.TimeUnit.Microsecond, - SizeUnit = SizeUnit.KB - })); - } - } -} diff --git a/src/libraries/Common/src/Extensions/BenchmarkRunner/DefaultCoreProfileConfig.cs b/src/libraries/Common/src/Extensions/BenchmarkRunner/DefaultCoreProfileConfig.cs deleted file mode 100644 index 4747570..0000000 --- a/src/libraries/Common/src/Extensions/BenchmarkRunner/DefaultCoreProfileConfig.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using BenchmarkDotNet.Columns; -using BenchmarkDotNet.Configs; -using BenchmarkDotNet.Diagnosers; -using BenchmarkDotNet.Engines; -using BenchmarkDotNet.Exporters; -using BenchmarkDotNet.Jobs; -using BenchmarkDotNet.Loggers; -using BenchmarkDotNet.Validators; - -namespace BenchmarkDotNet.Attributes -{ - internal class DefaultCoreProfileConfig : ManualConfig - { - public DefaultCoreProfileConfig() - { - Add(ConsoleLogger.Default); - Add(MarkdownExporter.GitHub); - - Add(MemoryDiagnoser.Default); - Add(StatisticColumn.OperationsPerSecond); - Add(DefaultColumnProviders.Instance); - - Add(JitOptimizationsValidator.FailOnError); - - Add(Job.InProcess - .With(RunStrategy.Throughput)); - } - } -} diff --git a/src/libraries/Common/src/Extensions/BenchmarkRunner/DefaultCoreValidationConfig.cs b/src/libraries/Common/src/Extensions/BenchmarkRunner/DefaultCoreValidationConfig.cs deleted file mode 100644 index d6937ba..0000000 --- a/src/libraries/Common/src/Extensions/BenchmarkRunner/DefaultCoreValidationConfig.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using BenchmarkDotNet.Configs; -using BenchmarkDotNet.Jobs; -using BenchmarkDotNet.Loggers; -using BenchmarkDotNet.Toolchains.InProcess; - -namespace BenchmarkDotNet.Attributes -{ - internal class DefaultCoreValidationConfig : ManualConfig - { - public DefaultCoreValidationConfig() - { - Add(ConsoleLogger.Default); - - Add(Job.Dry.With(InProcessToolchain.Instance)); - } - } -} diff --git a/src/libraries/Common/src/Extensions/BenchmarkRunner/ParameterizedJobConfigAttribute.cs b/src/libraries/Common/src/Extensions/BenchmarkRunner/ParameterizedJobConfigAttribute.cs deleted file mode 100644 index 0f84bd0..0000000 --- a/src/libraries/Common/src/Extensions/BenchmarkRunner/ParameterizedJobConfigAttribute.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System; - -namespace BenchmarkDotNet.Attributes -{ - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly)] - internal class ParameterizedJobConfigAttribute: AspNetCoreBenchmarkAttribute - { - public ParameterizedJobConfigAttribute(Type configType) : base(configType) - { - } - } -} diff --git a/src/libraries/Common/src/Extensions/BenchmarkRunner/ParamsDisplayInfoColumn.cs b/src/libraries/Common/src/Extensions/BenchmarkRunner/ParamsDisplayInfoColumn.cs deleted file mode 100644 index 08ff5fc..0000000 --- a/src/libraries/Common/src/Extensions/BenchmarkRunner/ParamsDisplayInfoColumn.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using BenchmarkDotNet.Columns; -using BenchmarkDotNet.Reports; -using BenchmarkDotNet.Running; - -namespace BenchmarkDotNet.Attributes -{ - public class ParamsSummaryColumn : IColumn - { - public string Id => nameof(ParamsSummaryColumn); - public string ColumnName { get; } = "Params"; - public bool IsDefault(Summary summary, Benchmark benchmark) => false; - public string GetValue(Summary summary, Benchmark benchmark) => benchmark.Parameters.DisplayInfo; - public bool IsAvailable(Summary summary) => true; - public bool AlwaysShow => true; - public ColumnCategory Category => ColumnCategory.Params; - public int PriorityInCategory => 0; - public override string ToString() => ColumnName; - public bool IsNumeric => false; - public UnitType UnitType => UnitType.Dimensionless; - public string GetValue(Summary summary, Benchmark benchmark, ISummaryStyle style) => GetValue(summary, benchmark); - public string Legend => $"Summary of all parameter values"; - } -} diff --git a/src/libraries/Common/src/Extensions/BenchmarkRunner/Program.cs b/src/libraries/Common/src/Extensions/BenchmarkRunner/Program.cs deleted file mode 100644 index 9fec28e..0000000 --- a/src/libraries/Common/src/Extensions/BenchmarkRunner/Program.cs +++ /dev/null @@ -1,106 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Text; -using BenchmarkDotNet.Attributes; -using BenchmarkDotNet.Configs; -using BenchmarkDotNet.Running; - -namespace Microsoft.AspNetCore.BenchmarkDotNet.Runner -{ - partial class Program - { - private static TextWriter _standardOutput; - private static StringBuilder _standardOutputText; - - static partial void BeforeMain(string[] args); - - private static int Main(string[] args) - { - BeforeMain(args); - - AssignConfiguration(ref args); - var summaries = BenchmarkSwitcher.FromAssembly(typeof(Program).GetTypeInfo().Assembly) - .Run(args, ManualConfig.CreateEmpty()); - - foreach (var summary in summaries) - { - if (summary.HasCriticalValidationErrors) - { - return Fail(summary, nameof(summary.HasCriticalValidationErrors)); - } - - foreach (var report in summary.Reports) - { - if (!report.BuildResult.IsGenerateSuccess) - { - return Fail(report, nameof(report.BuildResult.IsGenerateSuccess)); - } - - if (!report.BuildResult.IsBuildSuccess) - { - return Fail(report, nameof(report.BuildResult.IsBuildSuccess)); - } - - if (!report.AllMeasurements.Any()) - { - return Fail(report, nameof(report.AllMeasurements)); - } - } - } - - return 0; - } - - private static int Fail(object o, string message) - { - _standardOutput?.WriteLine(_standardOutputText.ToString()); - - Console.Error.WriteLine("'{0}' failed, reason: '{1}'", o, message); - return 1; - } - - private static void AssignConfiguration(ref string[] args) - { - var argsList = args.ToList(); - if (argsList.Remove("--validate") || argsList.Remove("--validate-fast")) - { - // Compat: support the old style of passing a config that is used by our build system. - SuppressConsole(); - AspNetCoreBenchmarkAttribute.ConfigName = AspNetCoreBenchmarkAttribute.NamedConfiguration.Validation; - args = argsList.ToArray(); - return; - } - - var index = argsList.IndexOf("--config"); - if (index >= 0 && index < argsList.Count -1) - { - AspNetCoreBenchmarkAttribute.ConfigName = argsList[index + 1]; - argsList.RemoveAt(index + 1); - argsList.RemoveAt(index); - args = argsList.ToArray(); - return; - } - - if (Debugger.IsAttached) - { - Console.WriteLine("Using the debug config since you are debugging. I hope that's OK!"); - Console.WriteLine("Specify a configuration with --config to override"); - AspNetCoreBenchmarkAttribute.ConfigName = AspNetCoreBenchmarkAttribute.NamedConfiguration.Debug; - return; - } - } - - private static void SuppressConsole() - { - _standardOutput = Console.Out; - _standardOutputText = new StringBuilder(); - Console.SetOut(new StringWriter(_standardOutputText)); - } - } -} diff --git a/src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/AnsiConsole.cs b/src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/AnsiConsole.cs deleted file mode 100644 index 63d6711..0000000 --- a/src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/AnsiConsole.cs +++ /dev/null @@ -1,143 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System; -using System.IO; - -namespace Microsoft.Extensions.CommandLineUtils -{ - internal class AnsiConsole - { - private AnsiConsole(TextWriter writer, bool useConsoleColor) - { - Writer = writer; - - _useConsoleColor = useConsoleColor; - if (_useConsoleColor) - { - OriginalForegroundColor = Console.ForegroundColor; - } - } - - private int _boldRecursion; - private bool _useConsoleColor; - - public static AnsiConsole GetOutput(bool useConsoleColor) - { - return new AnsiConsole(Console.Out, useConsoleColor); - } - - public static AnsiConsole GetError(bool useConsoleColor) - { - return new AnsiConsole(Console.Error, useConsoleColor); - } - - public TextWriter Writer { get; } - - public ConsoleColor OriginalForegroundColor { get; } - - private void SetColor(ConsoleColor color) - { - Console.ForegroundColor = (ConsoleColor)(((int)Console.ForegroundColor & 0x08) | ((int)color & 0x07)); - } - - private void SetBold(bool bold) - { - _boldRecursion += bold ? 1 : -1; - if (_boldRecursion > 1 || (_boldRecursion == 1 && !bold)) - { - return; - } - - Console.ForegroundColor = (ConsoleColor)((int)Console.ForegroundColor ^ 0x08); - } - - public void WriteLine(string message) - { - if (!_useConsoleColor) - { - Writer.WriteLine(message); - return; - } - - var escapeScan = 0; - for (; ;) - { - var escapeIndex = message.IndexOf("\x1b[", escapeScan); - if (escapeIndex == -1) - { - var text = message.Substring(escapeScan); - Writer.Write(text); - break; - } - else - { - var startIndex = escapeIndex + 2; - var endIndex = startIndex; - while (endIndex != message.Length && - message[endIndex] >= 0x20 && - message[endIndex] <= 0x3f) - { - endIndex += 1; - } - - var text = message.Substring(escapeScan, escapeIndex - escapeScan); - Writer.Write(text); - if (endIndex == message.Length) - { - break; - } - - switch (message[endIndex]) - { - case 'm': - int value; - if (int.TryParse(message.Substring(startIndex, endIndex - startIndex), out value)) - { - switch (value) - { - case 1: - SetBold(true); - break; - case 22: - SetBold(false); - break; - case 30: - SetColor(ConsoleColor.Black); - break; - case 31: - SetColor(ConsoleColor.Red); - break; - case 32: - SetColor(ConsoleColor.Green); - break; - case 33: - SetColor(ConsoleColor.Yellow); - break; - case 34: - SetColor(ConsoleColor.Blue); - break; - case 35: - SetColor(ConsoleColor.Magenta); - break; - case 36: - SetColor(ConsoleColor.Cyan); - break; - case 37: - SetColor(ConsoleColor.Gray); - break; - case 39: - SetColor(OriginalForegroundColor); - break; - } - } - break; - } - - escapeScan = endIndex + 1; - } - } - Writer.WriteLine(); - } - } -} diff --git a/src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/CommandArgument.cs b/src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/CommandArgument.cs deleted file mode 100644 index 562f14f..0000000 --- a/src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/CommandArgument.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System.Collections.Generic; -using System.Linq; - -namespace Microsoft.Extensions.CommandLineUtils -{ - internal class CommandArgument - { - public CommandArgument() - { - Values = new List(); - } - - public string Name { get; set; } - public bool ShowInHelpText { get; set; } = true; - public string Description { get; set; } - public List Values { get; private set; } - public bool MultipleValues { get; set; } - public string Value - { - get - { - return Values.FirstOrDefault(); - } - } - } -} diff --git a/src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/CommandLineApplication.cs b/src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/CommandLineApplication.cs deleted file mode 100644 index 9d7f5a7..0000000 --- a/src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/CommandLineApplication.cs +++ /dev/null @@ -1,644 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Microsoft.Extensions.CommandLineUtils -{ - internal class CommandLineApplication - { - // Indicates whether the parser should throw an exception when it runs into an unexpected argument. If this is - // set to true (the default), the parser will throw on the first unexpected argument. Otherwise, all unexpected - // arguments (including the first) are added to RemainingArguments. - private readonly bool _throwOnUnexpectedArg; - - // Indicates whether the parser should check remaining arguments for command or option matches after - // encountering an unexpected argument. Ignored if _throwOnUnexpectedArg is true (the default). If - // _throwOnUnexpectedArg and this are both false, the first unexpected argument and all remaining arguments are - // added to RemainingArguments. If _throwOnUnexpectedArg is false and this is true, only unexpected arguments - // are added to RemainingArguments -- allowing a mix of expected and unexpected arguments, commands and - // options. - private readonly bool _continueAfterUnexpectedArg; - - private readonly bool _treatUnmatchedOptionsAsArguments; - - public CommandLineApplication(bool throwOnUnexpectedArg = true, bool continueAfterUnexpectedArg = false, bool treatUnmatchedOptionsAsArguments = false) - { - _throwOnUnexpectedArg = throwOnUnexpectedArg; - _continueAfterUnexpectedArg = continueAfterUnexpectedArg; - _treatUnmatchedOptionsAsArguments = treatUnmatchedOptionsAsArguments; - Options = new List(); - Arguments = new List(); - Commands = new List(); - RemainingArguments = new List(); - Invoke = () => 0; - } - - public CommandLineApplication Parent { get; set; } - public string Name { get; set; } - public string FullName { get; set; } - public string Syntax { get; set; } - public string Description { get; set; } - public bool ShowInHelpText { get; set; } = true; - public string ExtendedHelpText { get; set; } - public readonly List Options; - public CommandOption OptionHelp { get; private set; } - public CommandOption OptionVersion { get; private set; } - public readonly List Arguments; - public readonly List RemainingArguments; - public bool IsShowingInformation { get; protected set; } // Is showing help or version? - public Func Invoke { get; set; } - public Func LongVersionGetter { get; set; } - public Func ShortVersionGetter { get; set; } - public readonly List Commands; - public bool AllowArgumentSeparator { get; set; } - public TextWriter Out { get; set; } = Console.Out; - public TextWriter Error { get; set; } = Console.Error; - - public IEnumerable GetOptions() - { - var expr = Options.AsEnumerable(); - var rootNode = this; - while (rootNode.Parent != null) - { - rootNode = rootNode.Parent; - expr = expr.Concat(rootNode.Options.Where(o => o.Inherited)); - } - - return expr; - } - - public CommandLineApplication Command(string name, Action configuration, - bool throwOnUnexpectedArg = true) - { - var command = new CommandLineApplication(throwOnUnexpectedArg) { Name = name, Parent = this }; - Commands.Add(command); - configuration(command); - return command; - } - - public CommandOption Option(string template, string description, CommandOptionType optionType) - => Option(template, description, optionType, _ => { }, inherited: false); - - public CommandOption Option(string template, string description, CommandOptionType optionType, bool inherited) - => Option(template, description, optionType, _ => { }, inherited); - - public CommandOption Option(string template, string description, CommandOptionType optionType, Action configuration) - => Option(template, description, optionType, configuration, inherited: false); - - public CommandOption Option(string template, string description, CommandOptionType optionType, Action configuration, bool inherited) - { - var option = new CommandOption(template, optionType) - { - Description = description, - Inherited = inherited - }; - Options.Add(option); - configuration(option); - return option; - } - - public CommandArgument Argument(string name, string description, bool multipleValues = false) - { - return Argument(name, description, _ => { }, multipleValues); - } - - public CommandArgument Argument(string name, string description, Action configuration, bool multipleValues = false) - { - var lastArg = Arguments.LastOrDefault(); - if (lastArg != null && lastArg.MultipleValues) - { - var message = string.Format("The last argument '{0}' accepts multiple values. No more argument can be added.", - lastArg.Name); - throw new InvalidOperationException(message); - } - - var argument = new CommandArgument { Name = name, Description = description, MultipleValues = multipleValues }; - Arguments.Add(argument); - configuration(argument); - return argument; - } - - public void OnExecute(Func invoke) - { - Invoke = invoke; - } - - public void OnExecute(Func> invoke) - { - Invoke = () => invoke().Result; - } - public int Execute(params string[] args) - { - CommandLineApplication command = this; - CommandOption option = null; - IEnumerator arguments = null; - var argumentsAssigned = false; - - for (var index = 0; index < args.Length; index++) - { - var arg = args[index]; - var processed = false; - if (!processed && option == null) - { - string[] longOption = null; - string[] shortOption = null; - - if (arg.StartsWith("--")) - { - longOption = arg.Substring(2).Split(new[] { ':', '=' }, 2); - } - else if (arg.StartsWith("-")) - { - shortOption = arg.Substring(1).Split(new[] { ':', '=' }, 2); - } - - if (longOption != null) - { - processed = true; - var longOptionName = longOption[0]; - option = command.GetOptions().SingleOrDefault(opt => string.Equals(opt.LongName, longOptionName, StringComparison.Ordinal)); - - if (option == null && _treatUnmatchedOptionsAsArguments) - { - if (arguments == null) - { - arguments = new CommandArgumentEnumerator(command.Arguments.GetEnumerator()); - } - if (arguments.MoveNext()) - { - processed = true; - arguments.Current.Values.Add(arg); - argumentsAssigned = true; - continue; - } - //else - //{ - // argumentsAssigned = false; - //} - } - - if (option == null) - { - var ignoreContinueAfterUnexpectedArg = false; - if (string.IsNullOrEmpty(longOptionName) && - !command._throwOnUnexpectedArg && - AllowArgumentSeparator) - { - // Skip over the '--' argument separator then consume all remaining arguments. All - // remaining arguments are unconditionally stored for further use. - index++; - ignoreContinueAfterUnexpectedArg = true; - } - - if (HandleUnexpectedArg( - command, - args, - index, - argTypeName: "option", - ignoreContinueAfterUnexpectedArg)) - { - continue; - } - - break; - } - - // If we find a help/version option, show information and stop parsing - if (command.OptionHelp == option) - { - command.ShowHelp(); - return 0; - } - else if (command.OptionVersion == option) - { - command.ShowVersion(); - return 0; - } - - if (longOption.Length == 2) - { - if (!option.TryParse(longOption[1])) - { - command.ShowHint(); - throw new CommandParsingException(command, $"Unexpected value '{longOption[1]}' for option '{option.LongName}'"); - } - option = null; - } - else if (option.OptionType == CommandOptionType.NoValue) - { - // No value is needed for this option - option.TryParse(null); - option = null; - } - } - - if (shortOption != null) - { - processed = true; - option = command.GetOptions().SingleOrDefault(opt => string.Equals(opt.ShortName, shortOption[0], StringComparison.Ordinal)); - - if (option == null && _treatUnmatchedOptionsAsArguments) - { - if (arguments == null) - { - arguments = new CommandArgumentEnumerator(command.Arguments.GetEnumerator()); - } - if (arguments.MoveNext()) - { - processed = true; - arguments.Current.Values.Add(arg); - argumentsAssigned = true; - continue; - } - //else - //{ - // argumentsAssigned = false; - //} - } - - // If not a short option, try symbol option - if (option == null) - { - option = command.GetOptions().SingleOrDefault(opt => string.Equals(opt.SymbolName, shortOption[0], StringComparison.Ordinal)); - } - - if (option == null) - { - if (HandleUnexpectedArg(command, args, index, argTypeName: "option")) - { - continue; - } - - break; - } - - // If we find a help/version option, show information and stop parsing - if (command.OptionHelp == option) - { - command.ShowHelp(); - return 0; - } - else if (command.OptionVersion == option) - { - command.ShowVersion(); - return 0; - } - - if (shortOption.Length == 2) - { - if (!option.TryParse(shortOption[1])) - { - command.ShowHint(); - throw new CommandParsingException(command, $"Unexpected value '{shortOption[1]}' for option '{option.LongName}'"); - } - option = null; - } - else if (option.OptionType == CommandOptionType.NoValue) - { - // No value is needed for this option - option.TryParse(null); - option = null; - } - } - } - - if (!processed && option != null) - { - processed = true; - if (!option.TryParse(arg)) - { - command.ShowHint(); - throw new CommandParsingException(command, $"Unexpected value '{arg}' for option '{option.LongName}'"); - } - option = null; - } - - if (!processed && !argumentsAssigned) - { - var currentCommand = command; - foreach (var subcommand in command.Commands) - { - if (string.Equals(subcommand.Name, arg, StringComparison.OrdinalIgnoreCase)) - { - processed = true; - command = subcommand; - break; - } - } - - // If we detect a subcommand - if (command != currentCommand) - { - processed = true; - } - } - - if (!processed) - { - if (arguments == null) - { - arguments = new CommandArgumentEnumerator(command.Arguments.GetEnumerator()); - } - if (arguments.MoveNext()) - { - processed = true; - arguments.Current.Values.Add(arg); - } - } - - if (!processed) - { - if (HandleUnexpectedArg(command, args, index, argTypeName: "command or argument")) - { - continue; - } - - break; - } - } - - if (option != null) - { - command.ShowHint(); - throw new CommandParsingException(command, $"Missing value for option '{option.LongName}'"); - } - - return command.Invoke(); - } - - // Helper method that adds a help option - public CommandOption HelpOption(string template) - { - // Help option is special because we stop parsing once we see it - // So we store it separately for further use - OptionHelp = Option(template, "Show help information", CommandOptionType.NoValue); - - return OptionHelp; - } - - public CommandOption VersionOption(string template, - string shortFormVersion, - string longFormVersion = null) - { - if (longFormVersion == null) - { - return VersionOption(template, () => shortFormVersion); - } - else - { - return VersionOption(template, () => shortFormVersion, () => longFormVersion); - } - } - - // Helper method that adds a version option - public CommandOption VersionOption(string template, - Func shortFormVersionGetter, - Func longFormVersionGetter = null) - { - // Version option is special because we stop parsing once we see it - // So we store it separately for further use - OptionVersion = Option(template, "Show version information", CommandOptionType.NoValue); - ShortVersionGetter = shortFormVersionGetter; - LongVersionGetter = longFormVersionGetter ?? shortFormVersionGetter; - - return OptionVersion; - } - - // Show short hint that reminds users to use help option - public void ShowHint() - { - if (OptionHelp != null) - { - Out.WriteLine(string.Format("Specify --{0} for a list of available options and commands.", OptionHelp.LongName)); - } - } - - // Show full help - public void ShowHelp(string commandName = null) - { - for (var cmd = this; cmd != null; cmd = cmd.Parent) - { - cmd.IsShowingInformation = true; - } - - Out.WriteLine(GetHelpText(commandName)); - } - - public virtual string GetHelpText(string commandName = null) - { - var headerBuilder = new StringBuilder("Usage:"); - for (var cmd = this; cmd != null; cmd = cmd.Parent) - { - headerBuilder.Insert(6, string.Format(" {0}", cmd.Name)); - } - - CommandLineApplication target; - - if (commandName == null || string.Equals(Name, commandName, StringComparison.OrdinalIgnoreCase)) - { - target = this; - } - else - { - target = Commands.SingleOrDefault(cmd => string.Equals(cmd.Name, commandName, StringComparison.OrdinalIgnoreCase)); - - if (target != null) - { - headerBuilder.AppendFormat(" {0}", commandName); - } - else - { - // The command name is invalid so don't try to show help for something that doesn't exist - target = this; - } - - } - - var optionsBuilder = new StringBuilder(); - var commandsBuilder = new StringBuilder(); - var argumentsBuilder = new StringBuilder(); - - var arguments = target.Arguments.Where(a => a.ShowInHelpText).ToList(); - if (arguments.Any()) - { - headerBuilder.Append(" [arguments]"); - - argumentsBuilder.AppendLine(); - argumentsBuilder.AppendLine("Arguments:"); - var maxArgLen = arguments.Max(a => a.Name.Length); - var outputFormat = string.Format(" {{0, -{0}}}{{1}}", maxArgLen + 2); - foreach (var arg in arguments) - { - argumentsBuilder.AppendFormat(outputFormat, arg.Name, arg.Description); - argumentsBuilder.AppendLine(); - } - } - - var options = target.GetOptions().Where(o => o.ShowInHelpText).ToList(); - if (options.Any()) - { - headerBuilder.Append(" [options]"); - - optionsBuilder.AppendLine(); - optionsBuilder.AppendLine("Options:"); - var maxOptLen = options.Max(o => o.Template.Length); - var outputFormat = string.Format(" {{0, -{0}}}{{1}}", maxOptLen + 2); - foreach (var opt in options) - { - optionsBuilder.AppendFormat(outputFormat, opt.Template, opt.Description); - optionsBuilder.AppendLine(); - } - } - - var commands = target.Commands.Where(c => c.ShowInHelpText).ToList(); - if (commands.Any()) - { - headerBuilder.Append(" [command]"); - - commandsBuilder.AppendLine(); - commandsBuilder.AppendLine("Commands:"); - var maxCmdLen = commands.Max(c => c.Name.Length); - var outputFormat = string.Format(" {{0, -{0}}}{{1}}", maxCmdLen + 2); - foreach (var cmd in commands.OrderBy(c => c.Name)) - { - commandsBuilder.AppendFormat(outputFormat, cmd.Name, cmd.Description); - commandsBuilder.AppendLine(); - } - - if (OptionHelp != null) - { - commandsBuilder.AppendLine(); - commandsBuilder.AppendFormat($"Use \"{target.Name} [command] --{OptionHelp.LongName}\" for more information about a command."); - commandsBuilder.AppendLine(); - } - } - - if (target.AllowArgumentSeparator) - { - headerBuilder.Append(" [[--] ...]"); - } - - headerBuilder.AppendLine(); - - var nameAndVersion = new StringBuilder(); - nameAndVersion.AppendLine(GetFullNameAndVersion()); - nameAndVersion.AppendLine(); - - return nameAndVersion.ToString() - + headerBuilder.ToString() - + argumentsBuilder.ToString() - + optionsBuilder.ToString() - + commandsBuilder.ToString() - + target.ExtendedHelpText; - } - - public void ShowVersion() - { - for (var cmd = this; cmd != null; cmd = cmd.Parent) - { - cmd.IsShowingInformation = true; - } - - Out.WriteLine(FullName); - Out.WriteLine(LongVersionGetter()); - } - - public string GetFullNameAndVersion() - { - return ShortVersionGetter == null ? FullName : string.Format("{0} {1}", FullName, ShortVersionGetter()); - } - - public void ShowRootCommandFullNameAndVersion() - { - var rootCmd = this; - while (rootCmd.Parent != null) - { - rootCmd = rootCmd.Parent; - } - - Out.WriteLine(rootCmd.GetFullNameAndVersion()); - Out.WriteLine(); - } - - private bool HandleUnexpectedArg( - CommandLineApplication command, - string[] args, - int index, - string argTypeName, - bool ignoreContinueAfterUnexpectedArg = false) - { - if (command._throwOnUnexpectedArg) - { - command.ShowHint(); - throw new CommandParsingException(command, $"Unrecognized {argTypeName} '{args[index]}'"); - } - else if (_continueAfterUnexpectedArg && !ignoreContinueAfterUnexpectedArg) - { - // Store argument for further use. - command.RemainingArguments.Add(args[index]); - return true; - } - else - { - // Store all remaining arguments for later use. - command.RemainingArguments.AddRange(new ArraySegment(args, index, args.Length - index)); - return false; - } - } - - private class CommandArgumentEnumerator : IEnumerator - { - private readonly IEnumerator _enumerator; - - public CommandArgumentEnumerator(IEnumerator enumerator) - { - _enumerator = enumerator; - } - - public CommandArgument Current - { - get - { - return _enumerator.Current; - } - } - - object IEnumerator.Current - { - get - { - return Current; - } - } - - public void Dispose() - { - _enumerator.Dispose(); - } - - public bool MoveNext() - { - if (Current == null || !Current.MultipleValues) - { - return _enumerator.MoveNext(); - } - - // If current argument allows multiple values, we don't move forward and - // all later values will be added to current CommandArgument.Values - return true; - } - - public void Reset() - { - _enumerator.Reset(); - } - } - } -} diff --git a/src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/CommandOption.cs b/src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/CommandOption.cs deleted file mode 100644 index 843dd09..0000000 --- a/src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/CommandOption.cs +++ /dev/null @@ -1,108 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Microsoft.Extensions.CommandLineUtils -{ - internal class CommandOption - { - public CommandOption(string template, CommandOptionType optionType) - { - Template = template; - OptionType = optionType; - Values = new List(); - - foreach (var part in Template.Split(new[] { ' ', '|' }, StringSplitOptions.RemoveEmptyEntries)) - { - if (part.StartsWith("--")) - { - LongName = part.Substring(2); - } - else if (part.StartsWith("-")) - { - var optName = part.Substring(1); - - // If there is only one char and it is not an English letter, it is a symbol option (e.g. "-?") - if (optName.Length == 1 && !IsEnglishLetter(optName[0])) - { - SymbolName = optName; - } - else - { - ShortName = optName; - } - } - else if (part.StartsWith("<") && part.EndsWith(">")) - { - ValueName = part.Substring(1, part.Length - 2); - } - else - { - throw new ArgumentException($"Invalid template pattern '{template}'", nameof(template)); - } - } - - if (string.IsNullOrEmpty(LongName) && string.IsNullOrEmpty(ShortName) && string.IsNullOrEmpty(SymbolName)) - { - throw new ArgumentException($"Invalid template pattern '{template}'", nameof(template)); - } - } - - public string Template { get; set; } - public string ShortName { get; set; } - public string LongName { get; set; } - public string SymbolName { get; set; } - public string ValueName { get; set; } - public string Description { get; set; } - public List Values { get; private set; } - public CommandOptionType OptionType { get; private set; } - public bool ShowInHelpText { get; set; } = true; - public bool Inherited { get; set; } - - public bool TryParse(string value) - { - switch (OptionType) - { - case CommandOptionType.MultipleValue: - Values.Add(value); - break; - case CommandOptionType.SingleValue: - if (Values.Any()) - { - return false; - } - Values.Add(value); - break; - case CommandOptionType.NoValue: - if (value != null) - { - return false; - } - // Add a value to indicate that this option was specified - Values.Add("on"); - break; - default: - break; - } - return true; - } - - public bool HasValue() - { - return Values.Any(); - } - - public string Value() - { - return HasValue() ? Values[0] : null; - } - - private bool IsEnglishLetter(char c) - { - return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); - } - } -} diff --git a/src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/CommandOptionType.cs b/src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/CommandOptionType.cs deleted file mode 100644 index 8f65a5a..0000000 --- a/src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/CommandOptionType.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - - -namespace Microsoft.Extensions.CommandLineUtils -{ - internal enum CommandOptionType - { - MultipleValue, - SingleValue, - NoValue - } -} diff --git a/src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/CommandParsingException.cs b/src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/CommandParsingException.cs deleted file mode 100644 index 047d714..0000000 --- a/src/libraries/Common/src/Extensions/CommandLineUtils/CommandLine/CommandParsingException.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System; - -namespace Microsoft.Extensions.CommandLineUtils -{ - internal class CommandParsingException : Exception - { - public CommandParsingException(CommandLineApplication command, string message) - : base(message) - { - Command = command; - } - - public CommandLineApplication Command { get; } - } -} diff --git a/src/libraries/Common/src/Extensions/CommandLineUtils/Microsoft.Extensions.CommandLineUtils.Sources.projitems b/src/libraries/Common/src/Extensions/CommandLineUtils/Microsoft.Extensions.CommandLineUtils.Sources.projitems deleted file mode 100644 index 72e5498..0000000 --- a/src/libraries/Common/src/Extensions/CommandLineUtils/Microsoft.Extensions.CommandLineUtils.Sources.projitems +++ /dev/null @@ -1,14 +0,0 @@ - - - - $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - true - 00947d4a-c20e-46e3-90c3-6cd6bc87ee72 - - - Microsoft.Extensions.CommandLineUtils.Sources - - - - - diff --git a/src/libraries/Common/src/Extensions/CommandLineUtils/Utilities/ArgumentEscaper.cs b/src/libraries/Common/src/Extensions/CommandLineUtils/Utilities/ArgumentEscaper.cs deleted file mode 100644 index f64ad0b..0000000 --- a/src/libraries/Common/src/Extensions/CommandLineUtils/Utilities/ArgumentEscaper.cs +++ /dev/null @@ -1,109 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Microsoft.Extensions.CommandLineUtils -{ - /// - /// A utility for escaping arguments for new processes. - /// - internal static class ArgumentEscaper - { - /// - /// Undo the processing which took place to create string[] args in Main, so that the next process will - /// receive the same string[] args. - /// - /// - /// See https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/ - /// - /// The arguments to concatenate. - /// The escaped arguments, concatenated. - public static string EscapeAndConcatenate(IEnumerable args) - => string.Join(" ", args.Select(EscapeSingleArg)); - - private static string EscapeSingleArg(string arg) - { - var sb = new StringBuilder(); - - var needsQuotes = ShouldSurroundWithQuotes(arg); - var isQuoted = needsQuotes || IsSurroundedWithQuotes(arg); - - if (needsQuotes) - { - sb.Append('"'); - } - - for (int i = 0; i < arg.Length; ++i) - { - var backslashes = 0; - - // Consume all backslashes - while (i < arg.Length && arg[i] == '\\') - { - backslashes++; - i++; - } - - if (i == arg.Length && isQuoted) - { - // Escape any backslashes at the end of the arg when the argument is also quoted. - // This ensures the outside quote is interpreted as an argument delimiter - sb.Append('\\', 2 * backslashes); - } - else if (i == arg.Length) - { - // At then end of the arg, which isn't quoted, - // just add the backslashes, no need to escape - sb.Append('\\', backslashes); - } - else if (arg[i] == '"') - { - // Escape any preceding backslashes and the quote - sb.Append('\\', (2 * backslashes) + 1); - sb.Append('"'); - } - else - { - // Output any consumed backslashes and the character - sb.Append('\\', backslashes); - sb.Append(arg[i]); - } - } - - if (needsQuotes) - { - sb.Append('"'); - } - - return sb.ToString(); - } - - private static bool ShouldSurroundWithQuotes(string argument) - { - // Don't quote already quoted strings - if (IsSurroundedWithQuotes(argument)) - { - return false; - } - - // Only quote if whitespace exists in the string - return ContainsWhitespace(argument); - } - - private static bool IsSurroundedWithQuotes(string argument) - { - if (argument.Length <= 1) - { - return false; - } - - return argument[0] == '"' && argument[argument.Length - 1] == '"'; - } - - private static bool ContainsWhitespace(string argument) - => argument.IndexOfAny(new[] { ' ', '\t', '\n' }) >= 0; - } -} diff --git a/src/libraries/Common/src/Extensions/CommandLineUtils/Utilities/DotNetMuxer.cs b/src/libraries/Common/src/Extensions/CommandLineUtils/Utilities/DotNetMuxer.cs deleted file mode 100644 index 8892852..0000000 --- a/src/libraries/Common/src/Extensions/CommandLineUtils/Utilities/DotNetMuxer.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -// System.AppContext.GetData is not available in these frameworks -#if !NET451 && !NET452 && !NET46 && !NET461 - -using System; -using System.Diagnostics; -using System.IO; - -namespace Microsoft.Extensions.CommandLineUtils -{ - /// - /// Utilities for finding the "dotnet.exe" file from the currently running .NET Core application - /// - internal static class DotNetMuxer - { - private const string MuxerName = "dotnet"; - - static DotNetMuxer() - { - MuxerPath = TryFindMuxerPath(); - } - - /// - /// The full filepath to the .NET Core muxer. - /// - public static string MuxerPath { get; } - - /// - /// Finds the full filepath to the .NET Core muxer, - /// or returns a string containing the default name of the .NET Core muxer ('dotnet'). - /// - /// The path or a string named 'dotnet'. - public static string MuxerPathOrDefault() - => MuxerPath ?? MuxerName; - - private static string TryFindMuxerPath() - { - var fileName = MuxerName; - if (OperatingSystem.IsWindows()) - { - fileName += ".exe"; - } - - var mainModule = Process.GetCurrentProcess().MainModule; - if (!string.IsNullOrEmpty(mainModule?.FileName) - && Path.GetFileName(mainModule.FileName).Equals(fileName, StringComparison.OrdinalIgnoreCase)) - { - return mainModule.FileName; - } - - return null; - } - } -} -#endif diff --git a/src/libraries/Common/src/Extensions/Directory.Build.props b/src/libraries/Common/src/Extensions/Directory.Build.props deleted file mode 100644 index 8405627..0000000 --- a/src/libraries/Common/src/Extensions/Directory.Build.props +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - netstandard1.0 - true - true - false - true - true - false - false - false - false - false - false - none - true - $(NoWarn);NU5105;CS8021 - false - - - diff --git a/src/libraries/Common/src/Extensions/ReferenceAssemblyInfo.cs b/src/libraries/Common/src/Extensions/ReferenceAssemblyInfo.cs deleted file mode 100644 index 5e55aeb..0000000 --- a/src/libraries/Common/src/Extensions/ReferenceAssemblyInfo.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -// Reference assemblies should have the ReferenceAssemblyAttribute. -[assembly:System.Runtime.CompilerServices.ReferenceAssembly] - -// Reference assemblies should have the 0x70 flag which prevents them from loading. -// This flag sets AssemblyName.ProcessorArchitecture to None. There is no public API for this. -// Cref https://github.com/dotnet/coreclr/blob/64ca544ecf55490675e72b853e98ebc8cc75a4fe/src/System.Private.CoreLib/src/System/Reflection/AssemblyName.CoreCLR.cs#L74 -[assembly:System.Reflection.AssemblyFlags((System.Reflection.AssemblyNameFlags)0x70)] diff --git a/src/libraries/Common/tests/Extensions/ArgumentEscaperTests.cs b/src/libraries/Common/tests/Extensions/ArgumentEscaperTests.cs deleted file mode 100644 index 5fc54a2..0000000 --- a/src/libraries/Common/tests/Extensions/ArgumentEscaperTests.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using Xunit; - -namespace Microsoft.Extensions.CommandLineUtils -{ - public class ArgumentEscaperTests - { - [Theory] - [InlineData(new[] { "one", "two", "three" }, "one two three")] - [InlineData(new[] { "line1\nline2", "word1\tword2" }, "\"line1\nline2\" \"word1\tword2\"")] - [InlineData(new[] { "with spaces" }, "\"with spaces\"")] - [InlineData(new[] { @"with\backslash" }, @"with\backslash")] - [InlineData(new[] { @"""quotedwith\backslash""" }, @"\""quotedwith\backslash\""")] - [InlineData(new[] { @"C:\Users\" }, @"C:\Users\")] - [InlineData(new[] { @"C:\Program Files\dotnet\" }, @"""C:\Program Files\dotnet\\""")] - [InlineData(new[] { @"backslash\""preceedingquote" }, @"backslash\\\""preceedingquote")] - public void EscapesArguments(string[] args, string expected) - { - Assert.Equal(expected, ArgumentEscaper.EscapeAndConcatenate(args)); - } - } -} diff --git a/src/libraries/Common/tests/Extensions/CommandLineApplicationTests.cs b/src/libraries/Common/tests/Extensions/CommandLineApplicationTests.cs deleted file mode 100644 index c7069b1..0000000 --- a/src/libraries/Common/tests/Extensions/CommandLineApplicationTests.cs +++ /dev/null @@ -1,1219 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System; -using System.IO; -using System.Linq; -using Microsoft.Extensions.CommandLineUtils; -using Xunit; - -namespace Microsoft.Extensions.Internal -{ - public class CommandLineApplicationTests - { - [Fact] - public void CommandNameCanBeMatched() - { - var called = false; - - var app = new CommandLineApplication(); - app.Command("test", c => - { - c.OnExecute(() => - { - called = true; - return 5; - }); - }); - - var result = app.Execute("test"); - Assert.Equal(5, result); - Assert.True(called); - } - - [Fact] - public void RemainingArgsArePassed() - { - CommandArgument first = null; - CommandArgument second = null; - - var app = new CommandLineApplication(); - - app.Command("test", c => - { - first = c.Argument("first", "First argument"); - second = c.Argument("second", "Second argument"); - c.OnExecute(() => 0); - }); - - app.Execute("test", "one", "two"); - - Assert.Equal("one", first.Value); - Assert.Equal("two", second.Value); - } - - [Fact] - public void ExtraArgumentCausesException() - { - CommandArgument first = null; - CommandArgument second = null; - - var app = new CommandLineApplication(); - - app.Command("test", c => - { - first = c.Argument("first", "First argument"); - second = c.Argument("second", "Second argument"); - c.OnExecute(() => 0); - }); - - var ex = Assert.Throws(() => app.Execute("test", "one", "two", "three")); - - Assert.Contains("three", ex.Message); - } - - [Fact] - public void ExtraArgumentAddedToRemaining() - { - CommandArgument first = null; - CommandArgument second = null; - - var app = new CommandLineApplication(); - - var testCommand = app.Command("test", c => - { - first = c.Argument("first", "First argument"); - second = c.Argument("second", "Second argument"); - c.OnExecute(() => 0); - }, - throwOnUnexpectedArg: false); - - app.Execute("test", "one", "two", "three"); - - Assert.Equal("one", first.Value); - Assert.Equal("two", second.Value); - var remaining = Assert.Single(testCommand.RemainingArguments); - Assert.Equal("three", remaining); - } - - [Fact] - public void UnknownCommandCausesException() - { - var app = new CommandLineApplication(); - - app.Command("test", c => - { - c.Argument("first", "First argument"); - c.Argument("second", "Second argument"); - c.OnExecute(() => 0); - }); - - var ex = Assert.Throws(() => app.Execute("test2", "one", "two", "three")); - - Assert.Contains("test2", ex.Message); - } - - [Fact] - public void MultipleValuesArgumentConsumesAllArgumentValues() - { - CommandArgument argument = null; - - var app = new CommandLineApplication(); - - app.Command("test", c => - { - argument = c.Argument("arg", "Argument that allows multiple values", multipleValues: true); - c.OnExecute(() => 0); - }); - - app.Execute("test", "one", "two", "three", "four", "five"); - - Assert.Equal(new[] { "one", "two", "three", "four", "five" }, argument.Values); - } - - [Fact] - public void MultipleValuesArgumentConsumesAllRemainingArgumentValues() - { - CommandArgument first = null; - CommandArgument second = null; - CommandArgument third = null; - - var app = new CommandLineApplication(); - - app.Command("test", c => - { - first = c.Argument("first", "First argument"); - second = c.Argument("second", "Second argument"); - third = c.Argument("third", "Third argument that allows multiple values", multipleValues: true); - c.OnExecute(() => 0); - }); - - app.Execute("test", "one", "two", "three", "four", "five"); - - Assert.Equal("one", first.Value); - Assert.Equal("two", second.Value); - Assert.Equal(new[] { "three", "four", "five" }, third.Values); - } - - [Fact] - public void MultipleValuesArgumentMustBeTheLastArgument() - { - var app = new CommandLineApplication(); - app.Argument("first", "First argument", multipleValues: true); - var ex = Assert.Throws(() => app.Argument("second", "Second argument")); - - Assert.Contains($"The last argument 'first' accepts multiple values. No more argument can be added.", - ex.Message); - } - - [Fact] - public void OptionSwitchMayBeProvided() - { - CommandOption first = null; - CommandOption second = null; - - var app = new CommandLineApplication(); - - app.Command("test", c => - { - first = c.Option("--first ", "First argument", CommandOptionType.SingleValue); - second = c.Option("--second ", "Second argument", CommandOptionType.SingleValue); - c.OnExecute(() => 0); - }); - - app.Execute("test", "--first", "one", "--second", "two"); - - Assert.Equal("one", first.Values[0]); - Assert.Equal("two", second.Values[0]); - } - - [Fact] - public void OptionValueMustBeProvided() - { - CommandOption first = null; - - var app = new CommandLineApplication(); - - app.Command("test", c => - { - first = c.Option("--first ", "First argument", CommandOptionType.SingleValue); - c.OnExecute(() => 0); - }); - - var ex = Assert.Throws(() => app.Execute("test", "--first")); - - Assert.Contains($"Missing value for option '{first.LongName}'", ex.Message); - } - - [Fact] - public void ValuesMayBeAttachedToSwitch() - { - CommandOption first = null; - CommandOption second = null; - - var app = new CommandLineApplication(); - - app.Command("test", c => - { - first = c.Option("--first ", "First argument", CommandOptionType.SingleValue); - second = c.Option("--second ", "Second argument", CommandOptionType.SingleValue); - c.OnExecute(() => 0); - }); - - app.Execute("test", "--first=one", "--second:two"); - - Assert.Equal("one", first.Values[0]); - Assert.Equal("two", second.Values[0]); - } - - [Fact] - public void ShortNamesMayBeDefined() - { - CommandOption first = null; - CommandOption second = null; - - var app = new CommandLineApplication(); - - app.Command("test", c => - { - first = c.Option("-1 --first ", "First argument", CommandOptionType.SingleValue); - second = c.Option("-2 --second ", "Second argument", CommandOptionType.SingleValue); - c.OnExecute(() => 0); - }); - - app.Execute("test", "-1=one", "-2", "two"); - - Assert.Equal("one", first.Values[0]); - Assert.Equal("two", second.Values[0]); - } - - [Fact] - public void ThrowsExceptionOnUnexpectedCommandOrArgumentByDefault() - { - var unexpectedArg = "UnexpectedArg"; - var app = new CommandLineApplication(); - - app.Command("test", c => - { - c.OnExecute(() => 0); - }); - - var exception = Assert.Throws(() => app.Execute("test", unexpectedArg)); - Assert.Equal($"Unrecognized command or argument '{unexpectedArg}'", exception.Message); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedArgument() - { - var unexpectedArg = "UnexpectedArg"; - var app = new CommandLineApplication(); - - var testCmd = app.Command("test", c => - { - c.OnExecute(() => 0); - }, - throwOnUnexpectedArg: false); - - // (does not throw) - app.Execute("test", unexpectedArg); - var arg = Assert.Single(testCmd.RemainingArguments); - Assert.Equal(unexpectedArg, arg); - } - - [Fact] - public void AllowArgumentBeforeNoValueOption() - { - var app = new CommandLineApplication(); - var argument = app.Argument("first", "first argument"); - var option = app.Option("--first", "first option", CommandOptionType.NoValue); - - app.Execute("one", "--first"); - - Assert.Equal("one", argument.Value); - Assert.True(option.HasValue()); - } - - [Fact] - public void AllowArgumentAfterNoValueOption() - { - var app = new CommandLineApplication(); - var argument = app.Argument("first", "first argument"); - var option = app.Option("--first", "first option", CommandOptionType.NoValue); - - app.Execute("--first", "one"); - - Assert.Equal("one", argument.Value); - Assert.True(option.HasValue()); - } - - [Fact] - public void AllowArgumentBeforeSingleValueOption() - { - var app = new CommandLineApplication(); - var argument = app.Argument("first", "first argument"); - var option = app.Option("--first ", "first option", CommandOptionType.SingleValue); - - app.Execute("one", "--first", "two"); - - Assert.Equal("one", argument.Value); - Assert.Equal("two", option.Value()); - } - - [Fact] - public void AllowArgumentAfterSingleValueOption() - { - var app = new CommandLineApplication(); - var argument = app.Argument("first", "first argument"); - var option = app.Option("--first ", "first option", CommandOptionType.SingleValue); - - app.Execute("--first", "one", "two"); - - Assert.Equal("two", argument.Value); - Assert.Equal("one", option.Value()); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedArgumentBeforeNoValueOption_Default() - { - var arguments = new[] { "UnexpectedArg", "--first" }; - var app = new CommandLineApplication(throwOnUnexpectedArg: false); - var option = app.Option("--first", "first option", CommandOptionType.NoValue); - - // (does not throw) - app.Execute(arguments); - - Assert.Equal(arguments, app.RemainingArguments.ToArray()); - Assert.False(option.HasValue()); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedArgumentBeforeNoValueOption_Continue() - { - var unexpectedArg = "UnexpectedArg"; - var app = new CommandLineApplication(throwOnUnexpectedArg: false, continueAfterUnexpectedArg: true); - var option = app.Option("--first", "first option", CommandOptionType.NoValue); - - // (does not throw) - app.Execute(unexpectedArg, "--first"); - - var arg = Assert.Single(app.RemainingArguments); - Assert.Equal(unexpectedArg, arg); - Assert.True(option.HasValue()); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedArgumentAfterNoValueOption() - { - var unexpectedArg = "UnexpectedArg"; - var app = new CommandLineApplication(throwOnUnexpectedArg: false); - var option = app.Option("--first", "first option", CommandOptionType.NoValue); - - // (does not throw) - app.Execute("--first", unexpectedArg); - - var arg = Assert.Single(app.RemainingArguments); - Assert.Equal(unexpectedArg, arg); - Assert.True(option.HasValue()); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedArgumentBeforeSingleValueOption_Default() - { - var arguments = new[] { "UnexpectedArg", "--first", "one" }; - var app = new CommandLineApplication(throwOnUnexpectedArg: false); - app.Option("--first", "first option", CommandOptionType.SingleValue); - - // (does not throw) - app.Execute(arguments); - - Assert.Equal(arguments, app.RemainingArguments.ToArray()); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedArgumentBeforeSingleValueOption_Continue() - { - var unexpectedArg = "UnexpectedArg"; - var app = new CommandLineApplication(throwOnUnexpectedArg: false, continueAfterUnexpectedArg: true); - var option = app.Option("--first", "first option", CommandOptionType.SingleValue); - - // (does not throw) - app.Execute(unexpectedArg, "--first", "one"); - - var arg = Assert.Single(app.RemainingArguments); - Assert.Equal(unexpectedArg, arg); - Assert.Equal("one", option.Value()); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedArgumentAfterSingleValueOption() - { - var unexpectedArg = "UnexpectedArg"; - var app = new CommandLineApplication(throwOnUnexpectedArg: false); - var option = app.Option("--first", "first option", CommandOptionType.SingleValue); - - // (does not throw) - app.Execute("--first", "one", unexpectedArg); - - var arg = Assert.Single(app.RemainingArguments); - Assert.Equal(unexpectedArg, arg); - Assert.Equal("one", option.Value()); - } - - [Fact] - public void ThrowsExceptionOnUnexpectedLongOptionByDefault() - { - var unexpectedOption = "--UnexpectedOption"; - var app = new CommandLineApplication(); - - app.Command("test", c => - { - c.OnExecute(() => 0); - }); - - var exception = Assert.Throws(() => app.Execute("test", unexpectedOption)); - Assert.Equal($"Unrecognized option '{unexpectedOption}'", exception.Message); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedLongOption() - { - var unexpectedOption = "--UnexpectedOption"; - var app = new CommandLineApplication(); - - var testCmd = app.Command("test", c => - { - c.OnExecute(() => 0); - }, - throwOnUnexpectedArg: false); - - // (does not throw) - app.Execute("test", unexpectedOption); - var arg = Assert.Single(testCmd.RemainingArguments); - Assert.Equal(unexpectedOption, arg); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedLongOptionBeforeNoValueOption_Default() - { - var arguments = new[] { "--unexpected", "--first" }; - var app = new CommandLineApplication(throwOnUnexpectedArg: false); - app.Option("--first", "first option", CommandOptionType.NoValue); - - // (does not throw) - app.Execute(arguments); - - Assert.Equal(arguments, app.RemainingArguments.ToArray()); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedLongOptionBeforeNoValueOption_Continue() - { - var unexpectedOption = "--unexpected"; - var app = new CommandLineApplication(throwOnUnexpectedArg: false, continueAfterUnexpectedArg: true); - var option = app.Option("--first", "first option", CommandOptionType.NoValue); - - // (does not throw) - app.Execute(unexpectedOption, "--first"); - - var arg = Assert.Single(app.RemainingArguments); - Assert.Equal(unexpectedOption, arg); - Assert.True(option.HasValue()); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedLongOptionAfterNoValueOption() - { - var unexpectedOption = "--unexpected"; - var app = new CommandLineApplication(throwOnUnexpectedArg: false); - var option = app.Option("--first", "first option", CommandOptionType.NoValue); - - // (does not throw) - app.Execute("--first", unexpectedOption); - - var arg = Assert.Single(app.RemainingArguments); - Assert.Equal(unexpectedOption, arg); - Assert.True(option.HasValue()); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedLongOptionBeforeSingleValueOption_Default() - { - var arguments = new[] { "--unexpected", "--first", "one" }; - var app = new CommandLineApplication(throwOnUnexpectedArg: false); - app.Option("--first", "first option", CommandOptionType.SingleValue); - - // (does not throw) - app.Execute(arguments); - - Assert.Equal(arguments, app.RemainingArguments.ToArray()); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedLongOptionBeforeSingleValueOption_Continue() - { - var unexpectedOption = "--unexpected"; - var app = new CommandLineApplication(throwOnUnexpectedArg: false, continueAfterUnexpectedArg: true); - var option = app.Option("--first", "first option", CommandOptionType.SingleValue); - - // (does not throw) - app.Execute(unexpectedOption, "--first", "one"); - - var arg = Assert.Single(app.RemainingArguments); - Assert.Equal(unexpectedOption, arg); - Assert.Equal("one", option.Value()); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedLongOptionAfterSingleValueOption() - { - var unexpectedOption = "--unexpected"; - var app = new CommandLineApplication(throwOnUnexpectedArg: false); - var option = app.Option("--first", "first option", CommandOptionType.SingleValue); - - // (does not throw) - app.Execute("--first", "one", unexpectedOption); - - var arg = Assert.Single(app.RemainingArguments); - Assert.Equal(unexpectedOption, arg); - Assert.Equal("one", option.Value()); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedLongOptionWithValueBeforeNoValueOption_Default() - { - var arguments = new[] { "--unexpected", "value", "--first" }; - var app = new CommandLineApplication(throwOnUnexpectedArg: false); - app.Option("--first", "first option", CommandOptionType.NoValue); - - // (does not throw) - app.Execute(arguments); - - Assert.Equal(arguments, app.RemainingArguments.ToArray()); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedLongOptionWithValueBeforeNoValueOption_Continue() - { - var unexpectedOption = "--unexpected"; - var unexpectedValue = "value"; - var app = new CommandLineApplication(throwOnUnexpectedArg: false, continueAfterUnexpectedArg: true); - var option = app.Option("--first", "first option", CommandOptionType.NoValue); - - // (does not throw) - app.Execute(unexpectedOption, unexpectedValue, "--first"); - - Assert.Equal(new[] { unexpectedOption, unexpectedValue }, app.RemainingArguments.ToArray()); - Assert.True(option.HasValue()); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedLongOptionWithValueAfterNoValueOption() - { - var unexpectedOption = "--unexpected"; - var unexpectedValue = "value"; - var app = new CommandLineApplication(throwOnUnexpectedArg: false); - var option = app.Option("--first", "first option", CommandOptionType.NoValue); - - // (does not throw) - app.Execute("--first", unexpectedOption, unexpectedValue); - - Assert.Equal(new[] { unexpectedOption, unexpectedValue }, app.RemainingArguments.ToArray()); - Assert.True(option.HasValue()); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedLongOptionWithValueBeforeSingleValueOption_Default() - { - var unexpectedOption = "--unexpected"; - var unexpectedValue = "value"; - var app = new CommandLineApplication(throwOnUnexpectedArg: false); - app.Option("--first", "first option", CommandOptionType.SingleValue); - - // (does not throw) - app.Execute(unexpectedOption, unexpectedValue, "--first", "one"); - - Assert.Equal( - new[] { unexpectedOption, unexpectedValue, "--first", "one" }, - app.RemainingArguments.ToArray()); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedLongOptionWithValueBeforeSingleValueOption_Continue() - { - var unexpectedOption = "--unexpected"; - var unexpectedValue = "value"; - var app = new CommandLineApplication(throwOnUnexpectedArg: false, continueAfterUnexpectedArg: true); - var option = app.Option("--first", "first option", CommandOptionType.SingleValue); - - // (does not throw) - app.Execute(unexpectedOption, unexpectedValue, "--first", "one"); - - Assert.Equal( - new[] { unexpectedOption, unexpectedValue }, - app.RemainingArguments.ToArray()); - Assert.Equal("one", option.Value()); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedLongOptionWithValueAfterSingleValueOption() - { - var unexpectedOption = "--unexpected"; - var unexpectedValue = "value"; - var app = new CommandLineApplication(throwOnUnexpectedArg: false); - var option = app.Option("--first", "first option", CommandOptionType.SingleValue); - - // (does not throw) - app.Execute("--first", "one", unexpectedOption, unexpectedValue); - - Assert.Equal(new[] { unexpectedOption, unexpectedValue }, app.RemainingArguments.ToArray()); - Assert.Equal("one", option.Value()); - } - - [Fact] - public void ThrowsExceptionOnUnexpectedShortOptionByDefault() - { - var unexpectedOption = "-uexp"; - var app = new CommandLineApplication(); - - app.Command("test", c => - { - c.OnExecute(() => 0); - }); - - var exception = Assert.Throws(() => app.Execute("test", unexpectedOption)); - Assert.Equal($"Unrecognized option '{unexpectedOption}'", exception.Message); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedShortOption() - { - var unexpectedOption = "-uexp"; - var app = new CommandLineApplication(); - - var testCmd = app.Command("test", c => - { - c.OnExecute(() => 0); - }, - throwOnUnexpectedArg: false); - - // (does not throw) - app.Execute("test", unexpectedOption); - var arg = Assert.Single(testCmd.RemainingArguments); - Assert.Equal(unexpectedOption, arg); - } - - [Fact] - public void ThrowsExceptionOnUnexpectedSymbolOptionByDefault() - { - var unexpectedOption = "-?"; - var app = new CommandLineApplication(); - - app.Command("test", c => - { - c.OnExecute(() => 0); - }); - - var exception = Assert.Throws(() => app.Execute("test", unexpectedOption)); - Assert.Equal($"Unrecognized option '{unexpectedOption}'", exception.Message); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedSymbolOption() - { - var unexpectedOption = "-?"; - var app = new CommandLineApplication(); - - var testCmd = app.Command("test", c => - { - c.OnExecute(() => 0); - }, - throwOnUnexpectedArg: false); - - // (does not throw) - app.Execute("test", unexpectedOption); - var arg = Assert.Single(testCmd.RemainingArguments); - Assert.Equal(unexpectedOption, arg); - } - - [Fact] - public void ThrowsExceptionOnUnexpectedOptionBeforeValidSubcommandByDefault() - { - var unexpectedOption = "--unexpected"; - CommandLineApplication subCmd = null; - var app = new CommandLineApplication(); - - app.Command("k", c => - { - subCmd = c.Command("run", _ => { }); - c.OnExecute(() => 0); - }); - - var exception = Assert.Throws(() => app.Execute("k", unexpectedOption, "run")); - Assert.Equal($"Unrecognized option '{unexpectedOption}'", exception.Message); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedOptionBeforeSubcommand() - { - var unexpectedOption = "--unexpected"; - var app = new CommandLineApplication(); - - CommandLineApplication subCmd = null; - var testCmd = app.Command("k", c => - { - subCmd = c.Command("run", _ => { }); - c.OnExecute(() => 0); - }, - throwOnUnexpectedArg: false); - - // (does not throw) - app.Execute("k", unexpectedOption, "run"); - - Assert.Empty(app.RemainingArguments); - Assert.Equal(new[] { unexpectedOption, "run" }, testCmd.RemainingArguments.ToArray()); - Assert.Empty(subCmd.RemainingArguments); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedOptionAfterSubcommand() - { - var unexpectedOption = "--unexpected"; - var app = new CommandLineApplication(); - - CommandLineApplication subCmd = null; - var testCmd = app.Command("k", c => - { - subCmd = c.Command("run", _ => { }, throwOnUnexpectedArg: false); - c.OnExecute(() => 0); - }); - - // (does not throw) - app.Execute("k", "run", unexpectedOption); - - Assert.Empty(app.RemainingArguments); - Assert.Empty(testCmd.RemainingArguments); - var arg = Assert.Single(subCmd.RemainingArguments); - Assert.Equal(unexpectedOption, arg); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedOptionBeforeValidCommand_Default() - { - var arguments = new[] { "--unexpected", "run" }; - var app = new CommandLineApplication(throwOnUnexpectedArg: false); - var commandRan = false; - app.Command("run", c => c.OnExecute(() => { commandRan = true; return 0; })); - app.OnExecute(() => 0); - - app.Execute(arguments); - - Assert.False(commandRan); - Assert.Equal(arguments, app.RemainingArguments.ToArray()); - } - - [Fact] - public void AllowNoThrowBehaviorOnUnexpectedOptionBeforeValidCommand_Continue() - { - var unexpectedOption = "--unexpected"; - var app = new CommandLineApplication(throwOnUnexpectedArg: false, continueAfterUnexpectedArg: true); - var commandRan = false; - app.Command("run", c => c.OnExecute(() => { commandRan = true; return 0; })); - app.OnExecute(() => 0); - - app.Execute(unexpectedOption, "run"); - - Assert.True(commandRan); - var remaining = Assert.Single(app.RemainingArguments); - Assert.Equal(unexpectedOption, remaining); - } - - [Fact] - public void OptionsCanBeInherited() - { - var app = new CommandLineApplication(); - var optionA = app.Option("-a|--option-a", "", CommandOptionType.SingleValue, inherited: true); - string optionAValue = null; - - var optionB = app.Option("-b", "", CommandOptionType.SingleValue, inherited: false); - - var subcmd = app.Command("subcmd", c => - { - c.OnExecute(() => - { - optionAValue = optionA.Value(); - return 0; - }); - }); - - Assert.Equal(2, app.GetOptions().Count()); - Assert.Single(subcmd.GetOptions()); - - app.Execute("-a", "A1", "subcmd"); - Assert.Equal("A1", optionAValue); - - Assert.Throws(() => app.Execute("subcmd", "-b", "B")); - - Assert.Contains("-a|--option-a", subcmd.GetHelpText()); - } - - [Fact] - public void NestedOptionConflictThrows() - { - var app = new CommandLineApplication(); - app.Option("-a|--always", "Top-level", CommandOptionType.SingleValue, inherited: true); - app.Command("subcmd", c => - { - c.Option("-a|--ask", "Nested", CommandOptionType.SingleValue); - }); - - Assert.Throws(() => app.Execute("subcmd", "-a", "b")); - } - - [Fact] - public void OptionsWithSameName() - { - var app = new CommandLineApplication(); - var top = app.Option("-a|--always", "Top-level", CommandOptionType.SingleValue, inherited: false); - CommandOption nested = null; - app.Command("subcmd", c => - { - nested = c.Option("-a|--ask", "Nested", CommandOptionType.SingleValue); - }); - - app.Execute("-a", "top"); - Assert.Equal("top", top.Value()); - Assert.Null(nested.Value()); - - top.Values.Clear(); - - app.Execute("subcmd", "-a", "nested"); - Assert.Null(top.Value()); - Assert.Equal("nested", nested.Value()); - } - - [Fact] - public void NestedInheritedOptions() - { - string globalOptionValue = null, nest1OptionValue = null, nest2OptionValue = null; - - var app = new CommandLineApplication(); - CommandLineApplication subcmd2 = null; - var g = app.Option("-g|--global", "Global option", CommandOptionType.SingleValue, inherited: true); - var subcmd1 = app.Command("lvl1", s1 => - { - var n1 = s1.Option("--nest1", "Nested one level down", CommandOptionType.SingleValue, inherited: true); - subcmd2 = s1.Command("lvl2", s2 => - { - var n2 = s2.Option("--nest2", "Nested one level down", CommandOptionType.SingleValue, inherited: true); - s2.HelpOption("-h|--help"); - s2.OnExecute(() => - { - globalOptionValue = g.Value(); - nest1OptionValue = n1.Value(); - nest2OptionValue = n2.Value(); - return 0; - }); - }); - }); - - Assert.DoesNotContain(app.GetOptions(), o => o.LongName == "nest2"); - Assert.DoesNotContain(app.GetOptions(), o => o.LongName == "nest1"); - Assert.Contains(app.GetOptions(), o => o.LongName == "global"); - - Assert.DoesNotContain(subcmd1.GetOptions(), o => o.LongName == "nest2"); - Assert.Contains(subcmd1.GetOptions(), o => o.LongName == "nest1"); - Assert.Contains(subcmd1.GetOptions(), o => o.LongName == "global"); - - Assert.Contains(subcmd2.GetOptions(), o => o.LongName == "nest2"); - Assert.Contains(subcmd2.GetOptions(), o => o.LongName == "nest1"); - Assert.Contains(subcmd2.GetOptions(), o => o.LongName == "global"); - - Assert.Throws(() => app.Execute("--nest2", "N2", "--nest1", "N1", "-g", "G")); - Assert.Throws(() => app.Execute("lvl1", "--nest2", "N2", "--nest1", "N1", "-g", "G")); - - app.Execute("lvl1", "lvl2", "--nest2", "N2", "-g", "G", "--nest1", "N1"); - Assert.Equal("G", globalOptionValue); - Assert.Equal("N1", nest1OptionValue); - Assert.Equal("N2", nest2OptionValue); - } - - [Theory] - [InlineData(new string[0], new string[0], null)] - [InlineData(new[] { "--" }, new string[0], null)] - [InlineData(new[] { "-t", "val" }, new string[0], "val")] - [InlineData(new[] { "-t", "val", "--" }, new string[0], "val")] - [InlineData(new[] { "--top", "val", "--", "a" }, new[] { "a" }, "val")] - [InlineData(new[] { "--", "a", "--top", "val" }, new[] { "a", "--top", "val" }, null)] - [InlineData(new[] { "-t", "val", "--", "a", "--", "b" }, new[] { "a", "--", "b" }, "val")] - [InlineData(new[] { "--", "--help" }, new[] { "--help" }, null)] - [InlineData(new[] { "--", "--version" }, new[] { "--version" }, null)] - public void ArgumentSeparator(string[] input, string[] expectedRemaining, string topLevelValue) - { - var app = new CommandLineApplication(throwOnUnexpectedArg: false) - { - AllowArgumentSeparator = true - }; - var optHelp = app.HelpOption("--help"); - var optVersion = app.VersionOption("--version", "1", "1.0"); - var optTop = app.Option("-t|--top ", "arg for command", CommandOptionType.SingleValue); - app.Execute(input); - - Assert.Equal(topLevelValue, optTop.Value()); - Assert.False(optHelp.HasValue()); - Assert.False(optVersion.HasValue()); - Assert.Equal(expectedRemaining, app.RemainingArguments.ToArray()); - } - - [Theory] - [InlineData(new string[0], new string[0], null, false)] - [InlineData(new[] { "--" }, new[] { "--" }, null, false)] - [InlineData(new[] { "-t", "val" }, new string[0], "val", false)] - [InlineData(new[] { "-t", "val", "--" }, new[] { "--" }, "val", false)] - [InlineData(new[] { "--top", "val", "--", "a" }, new[] { "--", "a" }, "val", false)] - [InlineData(new[] { "-t", "val", "--", "a", "--", "b" }, new[] { "--", "a", "--", "b" }, "val", false)] - [InlineData(new[] { "--help", "--" }, new string[0], null, true)] - [InlineData(new[] { "--version", "--" }, new string[0], null, true)] - public void ArgumentSeparator_TreatedAsUexpected( - string[] input, - string[] expectedRemaining, - string topLevelValue, - bool isShowingInformation) - { - var app = new CommandLineApplication(throwOnUnexpectedArg: false); - var optHelp = app.HelpOption("--help"); - var optVersion = app.VersionOption("--version", "1", "1.0"); - var optTop = app.Option("-t|--top ", "arg for command", CommandOptionType.SingleValue); - - app.Execute(input); - - Assert.Equal(topLevelValue, optTop.Value()); - Assert.Equal(expectedRemaining, app.RemainingArguments.ToArray()); - Assert.Equal(isShowingInformation, app.IsShowingInformation); - - // Help and Version options never get values; parsing ends when encountered. - Assert.False(optHelp.HasValue()); - Assert.False(optVersion.HasValue()); - } - - [Theory] - [InlineData(new[] { "--", "a", "--top", "val" }, new[] { "--", "a", "--top", "val" }, null, false)] - [InlineData(new[] { "--", "--help" }, new[] { "--", "--help" }, null, false)] - [InlineData(new[] { "--", "--version" }, new[] { "--", "--version" }, null, false)] - [InlineData(new[] { "unexpected", "--", "--version" }, new[] { "unexpected", "--", "--version" }, null, false)] - public void ArgumentSeparator_TreatedAsUexpected_Default( - string[] input, - string[] expectedRemaining, - string topLevelValue, - bool isShowingInformation) - { - var app = new CommandLineApplication(throwOnUnexpectedArg: false); - var optHelp = app.HelpOption("--help"); - var optVersion = app.VersionOption("--version", "1", "1.0"); - var optTop = app.Option("-t|--top ", "arg for command", CommandOptionType.SingleValue); - - app.Execute(input); - - Assert.Equal(topLevelValue, optTop.Value()); - Assert.Equal(expectedRemaining, app.RemainingArguments.ToArray()); - Assert.Equal(isShowingInformation, app.IsShowingInformation); - - // Help and Version options never get values; parsing ends when encountered. - Assert.False(optHelp.HasValue()); - Assert.False(optVersion.HasValue()); - } - - [Theory] - [InlineData(new[] { "--", "a", "--top", "val" }, new[] { "--", "a" }, "val", false)] - [InlineData(new[] { "--", "--help" }, new[] { "--" }, null, true)] - [InlineData(new[] { "--", "--version" }, new[] { "--" }, null, true)] - [InlineData(new[] { "unexpected", "--", "--version" }, new[] { "unexpected", "--" }, null, true)] - public void ArgumentSeparator_TreatedAsUexpected_Continue( - string[] input, - string[] expectedRemaining, - string topLevelValue, - bool isShowingInformation) - { - var app = new CommandLineApplication(throwOnUnexpectedArg: false, continueAfterUnexpectedArg: true); - var optHelp = app.HelpOption("--help"); - var optVersion = app.VersionOption("--version", "1", "1.0"); - var optTop = app.Option("-t|--top ", "arg for command", CommandOptionType.SingleValue); - - app.Execute(input); - - Assert.Equal(topLevelValue, optTop.Value()); - Assert.Equal(expectedRemaining, app.RemainingArguments.ToArray()); - Assert.Equal(isShowingInformation, app.IsShowingInformation); - - // Help and Version options never get values; parsing ends when encountered. - Assert.False(optHelp.HasValue()); - Assert.False(optVersion.HasValue()); - } - - [Fact] - public void HelpTextIgnoresHiddenItems() - { - var app = new CommandLineApplication() - { - Name = "ninja-app", - Description = "You can't see it until it is too late" - }; - - app.Command("star", c => - { - c.Option("--points

", "How many", CommandOptionType.MultipleValue); - c.ShowInHelpText = false; - }); - app.Option("--smile", "Be a nice ninja", CommandOptionType.NoValue, o => { o.ShowInHelpText = false; }); - - var a = app.Argument("name", "Pseudonym, of course"); - a.ShowInHelpText = false; - - var help = app.GetHelpText(); - - Assert.Contains("ninja-app", help); - Assert.DoesNotContain("--points", help); - Assert.DoesNotContain("--smile", help); - Assert.DoesNotContain("name", help); - } - - [Fact] - public void HelpTextUsesHelpOptionName() - { - var app = new CommandLineApplication - { - Name = "superhombre" - }; - - app.HelpOption("--ayuda-me"); - var help = app.GetHelpText(); - Assert.Contains("--ayuda-me", help); - } - - [Fact] - public void HelpTextShowsArgSeparator() - { - var app = new CommandLineApplication(throwOnUnexpectedArg: false) - { - Name = "proxy-command", - AllowArgumentSeparator = true - }; - app.HelpOption("-h|--help"); - Assert.Contains("Usage: proxy-command [options] [[--] ...]", app.GetHelpText()); - } - - [Fact] - public void HelpTextShowsExtendedHelp() - { - var app = new CommandLineApplication() - { - Name = "befuddle", - ExtendedHelpText = @" -Remarks: - This command is so confusing that I want to include examples in the help text. - -Examples: - dotnet befuddle -- I Can Haz Confusion Arguments -" - }; - - Assert.Contains(app.ExtendedHelpText, app.GetHelpText()); - } - - [Theory] - [InlineData(new[] { "--version", "--flag" }, "1.0")] - [InlineData(new[] { "-V", "-f" }, "1.0")] - [InlineData(new[] { "--help", "--flag" }, "some flag")] - [InlineData(new[] { "-h", "-f" }, "some flag")] - public void HelpAndVersionOptionStopProcessing(string[] input, string expectedOutData) - { - using var outWriter = new StringWriter(); - var app = new CommandLineApplication { Out = outWriter }; - app.HelpOption("-h --help"); - app.VersionOption("-V --version", "1", "1.0"); - var optFlag = app.Option("-f |--flag", "some flag", CommandOptionType.NoValue); - - app.Execute(input); - - outWriter.Flush(); - var outData = outWriter.ToString(); - Assert.Contains(expectedOutData, outData); - Assert.False(optFlag.HasValue()); - } - - [Theory] - [InlineData("-f:File1", "-f:File2")] - [InlineData("--file:File1", "--file:File2")] - [InlineData("--file", "File1", "--file", "File2")] - public void ThrowsExceptionOnSingleValueOptionHavingTwoValues(params string[] inputOptions) - { - var app = new CommandLineApplication(); - app.Option("-f |--file", "some file", CommandOptionType.SingleValue); - - var exception = Assert.Throws(() => app.Execute(inputOptions)); - - Assert.Equal("Unexpected value 'File2' for option 'file'", exception.Message); - } - - [Theory] - [InlineData("-v")] - [InlineData("--verbose")] - public void NoValueOptionCanBeSet(string input) - { - var app = new CommandLineApplication(); - var optVerbose = app.Option("-v |--verbose", "be verbose", CommandOptionType.NoValue); - - app.Execute(input); - - Assert.True(optVerbose.HasValue()); - } - - [Theory] - [InlineData("-v:true")] - [InlineData("--verbose:true")] - public void ThrowsExceptionOnNoValueOptionHavingValue(string inputOption) - { - var app = new CommandLineApplication(); - app.Option("-v |--verbose", "be verbose", CommandOptionType.NoValue); - - var exception = Assert.Throws(() => app.Execute(inputOption)); - - Assert.Equal("Unexpected value 'true' for option 'verbose'", exception.Message); - } - - [Fact] - public void ThrowsExceptionOnEmptyCommandOrArgument() - { - var inputOption = String.Empty; - var app = new CommandLineApplication(); - - var exception = Assert.Throws(() => app.Execute(inputOption)); - - Assert.Equal($"Unrecognized command or argument '{inputOption}'", exception.Message); - } - - [Fact] - public void ThrowsExceptionOnInvalidOption() - { - var inputOption = "-"; - var app = new CommandLineApplication(); - - var exception = Assert.Throws(() => app.Execute(inputOption)); - - Assert.Equal($"Unrecognized option '{inputOption}'", exception.Message); - } - - [Fact] - public void TreatUnmatchedOptionsAsArguments() - { - CommandArgument first = null; - CommandArgument second = null; - - CommandOption firstOption = null; - CommandOption secondOption = null; - - var firstUnmatchedOption = "-firstUnmatchedOption"; - var firstActualOption = "-firstActualOption"; - var seconUnmatchedOption = "--secondUnmatchedOption"; - var secondActualOption = "--secondActualOption"; - - var app = new CommandLineApplication(treatUnmatchedOptionsAsArguments: true); - - app.Command("test", c => - { - firstOption = c.Option("-firstActualOption", "first option", CommandOptionType.NoValue); - secondOption = c.Option("--secondActualOption", "second option", CommandOptionType.NoValue); - - first = c.Argument("first", "First argument"); - second = c.Argument("second", "Second argument"); - c.OnExecute(() => 0); - }); - - app.Execute("test", firstUnmatchedOption, firstActualOption, seconUnmatchedOption, secondActualOption); - - Assert.Equal(firstUnmatchedOption, first.Value); - Assert.Equal(seconUnmatchedOption, second.Value); - - Assert.Equal(firstActualOption, firstOption.Template); - Assert.Equal(secondActualOption, secondOption.Template); - } - - [Fact] - public void ThrowExceptionWhenUnmatchedOptionAndTreatUnmatchedOptionsAsArgumentsIsFalse() - { - CommandArgument first = null; - - var firstOption = "-firstUnmatchedOption"; - - var app = new CommandLineApplication(treatUnmatchedOptionsAsArguments: false); - app.Command("test", c => - { - first = c.Argument("first", "First argument"); - c.OnExecute(() => 0); - }); - - var exception = Assert.Throws(() => app.Execute("test", firstOption)); - - Assert.Equal($"Unrecognized option '{firstOption}'", exception.Message); - } - } -} diff --git a/src/libraries/Common/tests/Extensions/DotNetMuxerTests.cs b/src/libraries/Common/tests/Extensions/DotNetMuxerTests.cs deleted file mode 100644 index fe18922..0000000 --- a/src/libraries/Common/tests/Extensions/DotNetMuxerTests.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -#if NETCOREAPP -using System.IO; -using System.Runtime.InteropServices; -using Xunit; - -namespace Microsoft.Extensions.CommandLineUtils -{ - public class DotNetMuxerTests - { - [Fact] - public void FindsTheMuxer() - { - var muxerPath = DotNetMuxer.MuxerPath; - Assert.NotNull(muxerPath); - Assert.True(File.Exists(muxerPath), "The file did not exist"); - Assert.True(Path.IsPathRooted(muxerPath), "The path should be rooted"); - Assert.Equal("dotnet", Path.GetFileNameWithoutExtension(muxerPath), ignoreCase: true); - } - } -} -#endif -- 2.7.4