diff --git a/CHANGELOG.md b/CHANGELOG.md index eea8ad12..fd03d221 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,31 @@ All notable changes to this project will be documented in this file. CommandLineParser project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [2.9.5] 2026-03-17 + +### +- got rid of the rest of the F# support +- lots of ReSharper fixes + +## [2.9.4] 2026-03-17 + +### +- Lots of little ReSharper fixes +- Ripped out most of the F# support + +## [2.9.3-unixwiz] + +### +- Updated frameworks, went from "netstandard2.0;net40;net45;net461" to "net8.0". +- Deleted LangVersion = 8.0 (way too old) + +## [2.9.2-unixwiz] + +### +- First Unixwiz private build +- Ensured that OptionAttribute and ValueAttribute classes are not sealed. +- Started mucking w/ the package version stuff + ## [2.9.0-preview2] ### Added diff --git a/CommandLine.sln.DotSettings b/CommandLine.sln.DotSettings new file mode 100644 index 00000000..f29b1d5f --- /dev/null +++ b/CommandLine.sln.DotSettings @@ -0,0 +1,2 @@ + + True \ No newline at end of file diff --git a/README.md b/README.md index 79a16fa7..1096772d 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,19 @@ [![NuGet](https://img.shields.io/nuget/vpre/commandlineparser.svg)](https://www.nuget.org/packages/CommandLineParser/) [![Join the Gitter chat!](https://badges.gitter.im/gsscoder/commandline.svg)](https://gitter.im/gsscoder/commandline?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +# Unixwiz.net update + +This is a private, independently-maintained fork of the excellent CommandLineParser package +for modern .NET applications, and has dropped support for anything but recent .NET versions. +We have an application that required a change - un-sealing the "OptionValue" and "ValueAttribute" +classes - and needed to share this with a small circle of customers. + +Sorry, FSharp and .netstandard support has been removed. The docs below will be edited at some +point to ensure that this README.md is not lying. + +Do not enable `GeneratePackageOnBuild` - it interferes with expected behavior of `dotnet pack -c Release` +after a clean build and caused missing-output packaging failures. + # Command Line Parser Library for CLR and NetStandard **Note:** the API surface has changed since v1.9.x and earlier. If you are looking for documentation on v1.9.x, please see [stable-1.9.71.2](https://github.com/gsscoder/commandline/tree/stable-1.9.71.2) diff --git a/src/CommandLine/BaseAttribute.cs b/src/CommandLine/BaseAttribute.cs index be0a3826..88be9324 100644 --- a/src/CommandLine/BaseAttribute.cs +++ b/src/CommandLine/BaseAttribute.cs @@ -11,7 +11,6 @@ public abstract class BaseAttribute : Attribute { private int min; private int max; - private object @default; private Infrastructure.LocalizableAttributeProperty helpText; private string metaValue; private Type resourceType; @@ -44,12 +43,12 @@ public bool Required /// If not set, no lower range is enforced. public int Min { - get { return min; } + get => min; set { if (value < 0) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } min = value; @@ -63,12 +62,12 @@ public int Min /// If not set, no upper range is enforced. public int Max { - get { return max; } + get => max; set { if (value < 0) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } max = value; @@ -78,14 +77,7 @@ public int Max /// /// Gets or sets mapped property default value. /// - public object Default - { - get { return @default; } - set - { - @default = value; - } - } + public object Default { get; set; } /// /// Gets or sets a short description of this command line option. Usually a sentence summary. @@ -93,7 +85,7 @@ public object Default public string HelpText { get => helpText.Value??string.Empty; - set => helpText.Value = value ?? throw new ArgumentNullException("value"); + set => helpText.Value = value ?? throw new ArgumentNullException(nameof(value)); } /// @@ -101,16 +93,8 @@ public string HelpText /// public string MetaValue { - get { return metaValue; } - set - { - if (value == null) - { - throw new ArgumentNullException("value"); - } - - metaValue = value; - } + get => metaValue; + set => metaValue = value ?? throw new ArgumentNullException(nameof(value)); } /// @@ -127,12 +111,8 @@ public bool Hidden /// public Type ResourceType { - get { return resourceType; } - set - { - resourceType = - helpText.ResourceType = value; - } + get => resourceType; + set => resourceType = helpText.ResourceType = value; } } } diff --git a/src/CommandLine/CommandLine.csproj b/src/CommandLine/CommandLine.csproj index 04496eb8..bc7d2cd4 100644 --- a/src/CommandLine/CommandLine.csproj +++ b/src/CommandLine/CommandLine.csproj @@ -3,36 +3,29 @@ CommandLine Library - netstandard2.0;net40;net45;net461 + net8.0 $(DefineConstants);CSX_EITHER_INTERNAL;CSX_REM_EITHER_BEYOND_2;CSX_ENUM_INTERNAL;ERRH_INTERNAL;CSX_MAYBE_INTERNAL;CSX_REM_EITHER_FUNC;CSX_REM_CRYPTORAND;ERRH_ADD_MAYBE_METHODS - $(DefineConstants);SKIP_FSHARP true ..\..\CommandLine.snk true - CommandLineParser - CommandLineParser.FSharp - gsscoder;nemec;ericnewton76;moh-hassan - Command Line Parser Library + Unixwiz.CommandLineParser + gsscoder;nemec;ericnewton76;moh-hassan;SJFriedl + Command Line Parser Library - Unixwiz.net fork $(VersionSuffix) - 0.0.0 - Terse syntax C# command line parser for .NET. For FSharp support see CommandLineParser.FSharp. The Command Line Parser Library offers to CLR applications a clean and concise API for manipulating command line arguments and related tasks. - Terse syntax C# command line parser for .NET with F# support. The Command Line Parser Library offers to CLR applications a clean and concise API for manipulating command line arguments and related tasks. + 2.9.5 + Terse syntax C# command line parser for .NET. The Command Line Parser Library offers to CLR applications a clean and concise API for manipulating command line arguments and related tasks. Copyright (c) 2005 - 2020 Giacomo Stelluti Scala & Contributors License.md CommandLine20.png - https://github.com/commandlineparser/commandline + https://github.com/SJFriedl/commandline command line;commandline;argument;option;parser;parsing;library;syntax;shell - https://github.com/commandlineparser/commandline/blob/master/CHANGELOG.md - true - 8.0 + https://github.com/SJFriedl/commandline/blob/master/CHANGELOG.md + False true snupkg + Unixwiz.CommandLineParser - - - - true @@ -40,12 +33,6 @@ - - - - - - diff --git a/src/CommandLine/Core/GetoptTokenizer.cs b/src/CommandLine/Core/GetoptTokenizer.cs index b8c97fc2..0c1dc24e 100644 --- a/src/CommandLine/Core/GetoptTokenizer.cs +++ b/src/CommandLine/Core/GetoptTokenizer.cs @@ -3,10 +3,8 @@ using System; using System.Collections.Generic; using System.Linq; -using CommandLine.Infrastructure; using CSharpx; using RailwaySharp.ErrorHandling; -using System.Text.RegularExpressions; namespace CommandLine.Core { @@ -145,7 +143,7 @@ private static IEnumerable TokenizeShortName( // First option char that requires a value means we swallow the rest of the string as the value // But if there is no rest of the string, then instead we swallow the next argument - string chars = arg.Substring(1); + string chars = arg[1..]; int len = chars.Length; if (len > 0 && Char.IsDigit(chars[0])) { @@ -164,7 +162,7 @@ private static IEnumerable TokenizeShortName( if (i+1 < len) { // Rest of this is the value (e.g. "-sfoo" where "-s" is a string-consuming arg) - yield return Token.Value(chars.Substring(i+1)); + yield return Token.Value(chars[(i+1)..]); yield break; } else @@ -192,7 +190,7 @@ private static IEnumerable TokenizeLongName( Action onUnknownOption, Action onConsumeNext) { - string[] parts = arg.Substring(2).Split(new char[] { '=' }, 2); + string[] parts = arg[2..].Split(new char[] { '=' }, 2); string name = parts[0]; string value = (parts.Length > 1) ? parts[1] : null; // A parameter like "--stringvalue=" is acceptable, and makes stringvalue be the empty string diff --git a/src/CommandLine/Core/InstanceBuilder.cs b/src/CommandLine/Core/InstanceBuilder.cs index f48127b1..10137e26 100644 --- a/src/CommandLine/Core/InstanceBuilder.cs +++ b/src/CommandLine/Core/InstanceBuilder.cs @@ -94,7 +94,7 @@ public static ParserResult Build( var valueSpecPropsResult = ValueMapper.MapValues( (from pt in specProps where pt.Specification.IsValue() orderby ((ValueSpecification)pt.Specification).Index select pt), - valuesPartition, + valuesPartition, (vals, type, isScalar) => TypeConverter.ChangeType(vals, type, isScalar, false, parsingCulture, ignoreValueCase)); var missingValueErrors = from token in errorsPartition @@ -110,7 +110,7 @@ public static ParserResult Build( //build the instance, determining if the type is mutable or not. T instance; - if(typeInfo.IsMutable() == true) + if (typeInfo.IsMutable() == true) { instance = BuildMutable(factory, specPropsWithValue, setPropertyErrors); } @@ -156,8 +156,8 @@ private static T BuildMutable(Maybe> factory, IEnumerable sp.Value.IsJust(), + specPropsWithValue, + sp => sp.Value.IsJust(), sp => sp.Value.FromJustOrFail() ) ); @@ -173,8 +173,8 @@ private static T BuildMutable(Maybe> factory, IEnumerable sp.Value.IsNothing() - && sp.Specification.TargetType == TargetType.Sequence + sp => sp.Value.IsNothing() + && sp.Specification.TargetType == TargetType.Sequence && sp.Specification.DefaultValue.MatchNothing(), sp => sp.Property.PropertyType.GetTypeInfo().GetGenericArguments().Single().CreateEmptyArray() ) @@ -189,7 +189,7 @@ private static T BuildImmutable(Type typeInfo, Maybe> factory, IEnume specProps.Select(sp => sp.Property.PropertyType).ToArray() ); - if(ctor == null) + if (ctor == null) { throw new InvalidOperationException($"Type {typeInfo.FullName} appears to be immutable, but no constructor found to accept values."); } diff --git a/src/CommandLine/Core/InstanceChooser.cs b/src/CommandLine/Core/InstanceChooser.cs index 72307bf2..97258cab 100644 --- a/src/CommandLine/Core/InstanceChooser.cs +++ b/src/CommandLine/Core/InstanceChooser.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; -using CommandLine.Infrastructure; using CSharpx; using RailwaySharp.ErrorHandling; @@ -141,7 +140,7 @@ private static ParserResult MatchVerb( parsingCulture, autoHelp, autoVersion, - allowMultiInstance, + allowMultiInstance, nonFatalErrors); } diff --git a/src/CommandLine/Core/OptionSpecification.cs b/src/CommandLine/Core/OptionSpecification.cs index 1c2e4f88..620fd7e1 100644 --- a/src/CommandLine/Core/OptionSpecification.cs +++ b/src/CommandLine/Core/OptionSpecification.cs @@ -9,25 +9,18 @@ namespace CommandLine.Core { sealed class OptionSpecification : Specification { - private readonly string shortName; - private readonly string longName; - private readonly char separator; - private readonly string setName; - private readonly string group; - private readonly bool flagCounter; - public OptionSpecification(string shortName, string longName, bool required, string setName, Maybe min, Maybe max, char separator, Maybe defaultValue, string helpText, string metaValue, IEnumerable enumValues, Type conversionType, TargetType targetType, string group, bool flagCounter = false, bool hidden = false) : base(SpecificationType.Option, required, min, max, defaultValue, helpText, metaValue, enumValues, conversionType, conversionType == typeof(int) && flagCounter ? TargetType.Switch : targetType, hidden) { - this.shortName = shortName; - this.longName = longName; - this.separator = separator; - this.setName = setName; - this.group = group; - this.flagCounter = flagCounter; + this.ShortName = shortName; + this.LongName = longName; + this.Separator = separator; + this.SetName = setName; + this.Group = group; + this.FlagCounter = flagCounter; } public static OptionSpecification FromAttribute(OptionAttribute attribute, Type conversionType, IEnumerable enumValues) @@ -57,37 +50,19 @@ public static OptionSpecification NewSwitch(string shortName, string longName, b '\0', Maybe.Nothing(), helpText, metaValue, Enumerable.Empty(), typeof(bool), TargetType.Switch, string.Empty, false, hidden); } - public string ShortName - { - get { return shortName; } - } + public string ShortName { get; } - public string LongName - { - get { return longName; } - } + public string LongName { get; } - public char Separator - { - get { return separator; } - } + public char Separator { get; } - public string SetName - { - get { return setName; } - } + public string SetName { get; } - public string Group - { - get { return group; } - } + public string Group { get; } /// /// Whether this is an int option that counts how many times a flag was set rather than taking a value on the command line /// - public bool FlagCounter - { - get { return flagCounter; } - } + public bool FlagCounter { get; } } } diff --git a/src/CommandLine/Core/PartitionExtensions.cs b/src/CommandLine/Core/PartitionExtensions.cs index 47cc397e..917b4301 100644 --- a/src/CommandLine/Core/PartitionExtensions.cs +++ b/src/CommandLine/Core/PartitionExtensions.cs @@ -2,8 +2,6 @@ using System; using System.Collections.Generic; -using System.Linq; -using CSharpx; namespace CommandLine.Core { diff --git a/src/CommandLine/Core/ReflectionExtensions.cs b/src/CommandLine/Core/ReflectionExtensions.cs index 622e1e6e..8d2a5de9 100644 --- a/src/CommandLine/Core/ReflectionExtensions.cs +++ b/src/CommandLine/Core/ReflectionExtensions.cs @@ -65,7 +65,7 @@ private static IEnumerable FlattenHierarchy(this Type type) private static IEnumerable SafeGetInterfaces(this Type type) { - return type == null ? Enumerable.Empty() : type.GetTypeInfo().GetInterfaces(); + return type?.GetTypeInfo().GetInterfaces() ?? Enumerable.Empty(); } public static TargetType ToTargetType(this Type type) @@ -125,13 +125,13 @@ public static object GetDefaultValue(this Type type) public static bool IsMutable(this Type type) { - if(type == typeof(object)) + if (type == typeof(object)) return true; // Find all inherited defined properties and fields on the type var inheritedTypes = type.GetTypeInfo().FlattenHierarchy().Select(i => i.GetTypeInfo()); - foreach (var inheritedType in inheritedTypes) + foreach (var inheritedType in inheritedTypes) { if ( inheritedType.GetTypeInfo().GetProperties(BindingFlags.Public | BindingFlags.Instance).Any(p => p.CanWrite) || @@ -162,7 +162,7 @@ public static object AutoDefault(this Type type) } var ctorTypes = type.GetSpecifications(pi => pi.PropertyType).ToArray(); - + return ReflectionHelper.CreateDefaultImmutableInstance(type, ctorTypes); } @@ -206,7 +206,7 @@ public static bool IsPrimitiveEx(this Type type) return (type.GetTypeInfo().IsValueType && type != typeof(Guid)) || type.GetTypeInfo().IsPrimitive - || new [] { + || new [] { typeof(string) ,typeof(decimal) ,typeof(DateTime) diff --git a/src/CommandLine/Core/Specification.cs b/src/CommandLine/Core/Specification.cs index b95b998c..b69ed0e4 100644 --- a/src/CommandLine/Core/Specification.cs +++ b/src/CommandLine/Core/Specification.cs @@ -24,99 +24,54 @@ enum TargetType abstract class Specification { - private readonly SpecificationType tag; - private readonly bool required; - private readonly bool hidden; - private readonly Maybe min; - private readonly Maybe max; - private readonly Maybe defaultValue; - private readonly string helpText; - private readonly string metaValue; - private readonly IEnumerable enumValues; - /// This information is denormalized to decouple Specification from PropertyInfo. - private readonly Type conversionType; - private readonly TargetType targetType; - protected Specification(SpecificationType tag, bool required, Maybe min, Maybe max, Maybe defaultValue, string helpText, string metaValue, IEnumerable enumValues, Type conversionType, TargetType targetType, bool hidden = false) { - this.tag = tag; - this.required = required; - this.min = min; - this.max = max; - this.defaultValue = defaultValue; - this.conversionType = conversionType; - this.targetType = targetType; - this.helpText = helpText; - this.metaValue = metaValue; - this.enumValues = enumValues; - this.hidden = hidden; + this.Tag = tag; + this.Required = required; + this.Min = min; + this.Max = max; + this.DefaultValue = defaultValue; + this.ConversionType = conversionType; + this.TargetType = targetType; + this.HelpText = helpText; + this.MetaValue = metaValue; + this.EnumValues = enumValues; + this.Hidden = hidden; } - public SpecificationType Tag - { - get { return tag; } - } + public SpecificationType Tag { get; } - public bool Required - { - get { return required; } - } + public bool Required { get; } - public Maybe Min - { - get { return min; } - } + public Maybe Min { get; } - public Maybe Max - { - get { return max; } - } + public Maybe Max { get; } - public Maybe DefaultValue - { - get { return defaultValue; } - } + public Maybe DefaultValue { get; } - public string HelpText - { - get { return helpText; } - } + public string HelpText { get; } - public string MetaValue - { - get { return metaValue; } - } + public string MetaValue { get; } - public IEnumerable EnumValues - { - get { return enumValues; } - } + public IEnumerable EnumValues { get; } - public Type ConversionType - { - get { return conversionType; } - } + /// This information is denormalized to decouple Specification from PropertyInfo. + public Type ConversionType { get; } - public TargetType TargetType - { - get { return targetType; } - } + public TargetType TargetType { get; } - public bool Hidden - { - get { return hidden; } - } + public bool Hidden { get; } public static Specification FromProperty(PropertyInfo property) - { + { var attrs = property.GetCustomAttributes(true); var oa = attrs.OfType(); if (oa.Count() == 1) { var spec = OptionSpecification.FromAttribute(oa.Single(), property.PropertyType, - ReflectionHelper.GetNamesOfEnum(property.PropertyType)); + ReflectionHelper.GetNamesOfEnum(property.PropertyType)); if (spec.ShortName.Length == 0 && spec.LongName.Length == 0) { diff --git a/src/CommandLine/Core/SpecificationExtensions.cs b/src/CommandLine/Core/SpecificationExtensions.cs index c080e983..64d79c9f 100644 --- a/src/CommandLine/Core/SpecificationExtensions.cs +++ b/src/CommandLine/Core/SpecificationExtensions.cs @@ -59,9 +59,7 @@ public static IEnumerable ThrowingValidate(this IEnumerable predicate) { - int min; - int max; - if (specification.Min.MatchJust(out min) && specification.Max.MatchJust(out max)) + if (specification.Min.MatchJust(out var min) && specification.Max.MatchJust(out var max)) { return predicate(min, max); } @@ -70,8 +68,7 @@ public static bool HavingRange(this Specification specification, Func predicate) { - int min; - if (specification.Min.MatchJust(out min)) + if (specification.Min.MatchJust(out var min)) { return predicate(min); } @@ -80,8 +77,7 @@ public static bool HavingMin(this Specification specification, Func p public static bool HavingMax(this Specification specification, Func predicate) { - int max; - if (specification.Max.MatchJust(out max)) + if (specification.Max.MatchJust(out var max)) { return predicate(max); } diff --git a/src/CommandLine/Core/SpecificationProperty.cs b/src/CommandLine/Core/SpecificationProperty.cs index f6cea24f..29b5caff 100644 --- a/src/CommandLine/Core/SpecificationProperty.cs +++ b/src/CommandLine/Core/SpecificationProperty.cs @@ -8,37 +8,24 @@ namespace CommandLine.Core { class SpecificationProperty { - private readonly Specification specification; - private readonly PropertyInfo property; - private readonly Maybe value; - private SpecificationProperty(Specification specification, PropertyInfo property, Maybe value) { - this.property = property; - this.specification = specification; - this.value = value; + this.Property = property; + this.Specification = specification; + this.Value = value; } public static SpecificationProperty Create(Specification specification, PropertyInfo property, Maybe value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw new ArgumentNullException(nameof(value)); return new SpecificationProperty(specification, property, value); } - public Specification Specification - { - get { return specification; } - } + public Specification Specification { get; } - public PropertyInfo Property - { - get { return property; } - } + public PropertyInfo Property { get; } - public Maybe Value - { - get { return value; } - } + public Maybe Value { get; } } } diff --git a/src/CommandLine/Core/Token.cs b/src/CommandLine/Core/Token.cs index 90bbe54d..a21f19c8 100644 --- a/src/CommandLine/Core/Token.cs +++ b/src/CommandLine/Core/Token.cs @@ -8,13 +8,10 @@ enum TokenType { Name, Value } abstract class Token { - private readonly TokenType tag; - private readonly string text; - protected Token(TokenType tag, string text) { - this.tag = tag; - this.text = text; + this.Tag = tag; + this.Text = text; } public static Token Name(string text) @@ -42,15 +39,9 @@ public static Token ValueFromSeparator(string text) return new Value(text, false, false, true); } - public TokenType Tag - { - get { return tag; } - } + public TokenType Tag { get; } - public string Text - { - get { return text; } - } + public string Text { get; } } class Name : Token, IEquatable @@ -62,8 +53,7 @@ public Name(string text) public override bool Equals(object obj) { - var other = obj as Name; - if (other != null) + if (obj is Name other) { return Equals(other); } @@ -89,10 +79,6 @@ public bool Equals(Name other) class Value : Token, IEquatable { - private readonly bool explicitlyAssigned; - private readonly bool forced; - private readonly bool fromSeparator; - public Value(string text) : this(text, false, false, false) { @@ -106,39 +92,29 @@ public Value(string text, bool explicitlyAssigned) public Value(string text, bool explicitlyAssigned, bool forced, bool fromSeparator) : base(TokenType.Value, text) { - this.explicitlyAssigned = explicitlyAssigned; - this.forced = forced; - this.fromSeparator = fromSeparator; + this.ExplicitlyAssigned = explicitlyAssigned; + this.Forced = forced; + this.FromSeparator = fromSeparator; } /// /// Whether this value came from a long option with "=" separating the name from the value /// - public bool ExplicitlyAssigned - { - get { return explicitlyAssigned; } - } + public bool ExplicitlyAssigned { get; } /// /// Whether this value came from a sequence specified with a separator (e.g., "--files a.txt,b.txt,c.txt") /// - public bool FromSeparator - { - get { return fromSeparator; } - } + public bool FromSeparator { get; } /// /// Whether this value came from args after the -- separator (when EnableDashDash = true) /// - public bool Forced - { - get { return forced; } - } + public bool Forced { get; } public override bool Equals(object obj) { - var other = obj as Value; - if (other != null) + if (obj is Value other) { return Equals(other); } diff --git a/src/CommandLine/Core/TokenPartitioner.cs b/src/CommandLine/Core/TokenPartitioner.cs index 4dc25f7f..3d1800fb 100644 --- a/src/CommandLine/Core/TokenPartitioner.cs +++ b/src/CommandLine/Core/TokenPartitioner.cs @@ -15,7 +15,7 @@ Tuple>>, IEnumerable tokens, Func> typeLookup) { - IEqualityComparer tokenComparer = ReferenceEqualityComparer.Default; + IEqualityComparer tokenComparer = CommandLine.Infrastructure.ReferenceEqualityComparer.Default; var tokenList = tokens.Memoize(); var partitioned = PartitionTokensByType(tokenList, typeLookup); @@ -151,8 +151,8 @@ public static Tuple, IEnumerable, IEnumerable, } break; } - } } + } foreach (var kvp in sequences) { @@ -179,6 +179,5 @@ private enum SequenceState SequenceTokenFound, ScalarTokenFound, } - } } diff --git a/src/CommandLine/Core/Tokenizer.cs b/src/CommandLine/Core/Tokenizer.cs index fe94fc61..5d9e52ea 100644 --- a/src/CommandLine/Core/Tokenizer.cs +++ b/src/CommandLine/Core/Tokenizer.cs @@ -155,7 +155,7 @@ private static IEnumerable TokenizeShortName( } if (value.Length > 1 && value[0] == '-' && value[1] != '-') { - var text = value.Substring(1); + var text = value[1..]; if (char.IsDigit(text[0])) { @@ -184,7 +184,7 @@ private static IEnumerable TokenizeShortName( if (i < text.Length) { - yield return Token.Value(text.Substring(i)); + yield return Token.Value(text[i..]); } } } @@ -195,7 +195,7 @@ private static IEnumerable TokenizeLongName( { if (value.Length > 2 && value.StartsWith("--", StringComparison.Ordinal)) { - var text = value.Substring(2); + var text = value[2..]; var equalIndex = text.IndexOf('='); if (equalIndex <= 0) { diff --git a/src/CommandLine/Core/TypeConverter.cs b/src/CommandLine/Core/TypeConverter.cs index 2e27af40..704dc0e8 100644 --- a/src/CommandLine/Core/TypeConverter.cs +++ b/src/CommandLine/Core/TypeConverter.cs @@ -78,27 +78,13 @@ private static Result ChangeTypeScalarImpl(string value, Type var isFsOption = ReflectionHelper.IsFSharpOptionType(conversionType); Func getUnderlyingType = - () => -#if !SKIP_FSHARP - isFsOption - ? FSharpOptionHelper.GetUnderlyingType(conversionType) : -#endif - Nullable.GetUnderlyingType(conversionType); + () => Nullable.GetUnderlyingType(conversionType); var type = getUnderlyingType() ?? conversionType; Func withValue = - () => -#if !SKIP_FSHARP - isFsOption - ? FSharpOptionHelper.Some(type, ConvertString(value, type, conversionCulture)) : -#endif - ConvertString(value, type, conversionCulture); -#if !SKIP_FSHARP - Func empty = () => isFsOption ? FSharpOptionHelper.None(type) : null; -#else + () => ConvertString(value, type, conversionCulture); Func empty = () => null; -#endif return (value == null) ? empty() : withValue(); }; diff --git a/src/CommandLine/Core/TypeDescriptor.cs b/src/CommandLine/Core/TypeDescriptor.cs index bb2c27fc..990396c4 100644 --- a/src/CommandLine/Core/TypeDescriptor.cs +++ b/src/CommandLine/Core/TypeDescriptor.cs @@ -7,35 +7,22 @@ namespace CommandLine.Core { struct TypeDescriptor { - private readonly TargetType targetType; - private readonly Maybe maxItems; - private readonly Maybe nextValue; - private TypeDescriptor(TargetType targetType, Maybe maxItems, Maybe nextValue = null) { - this.targetType = targetType; - this.maxItems = maxItems; - this.nextValue = nextValue; + this.TargetType = targetType; + this.MaxItems = maxItems; + this.NextValue = nextValue; } - public TargetType TargetType - { - get { return targetType; } - } + public TargetType TargetType { get; } - public Maybe MaxItems - { - get { return maxItems; } - } + public Maybe MaxItems { get; } - public Maybe NextValue - { - get { return this.nextValue; } - } + public Maybe NextValue { get; } public static TypeDescriptor Create(TargetType tag, Maybe maximumItems, TypeDescriptor next = default(TypeDescriptor)) { - if (maximumItems == null) throw new ArgumentNullException("maximumItems"); + if (maximumItems == null) throw new ArgumentNullException(nameof(maximumItems)); return new TypeDescriptor(tag, maximumItems, next.ToMaybe()); } @@ -48,4 +35,4 @@ public static TypeDescriptor WithNextValue(this TypeDescriptor descriptor, Maybe return TypeDescriptor.Create(descriptor.TargetType, descriptor.MaxItems, nextValue.GetValueOrDefault(default(TypeDescriptor))); } } -} \ No newline at end of file +} diff --git a/src/CommandLine/Core/ValueMapper.cs b/src/CommandLine/Core/ValueMapper.cs index ab01e006..cbc753c7 100644 --- a/src/CommandLine/Core/ValueMapper.cs +++ b/src/CommandLine/Core/ValueMapper.cs @@ -62,7 +62,7 @@ private static IEnumerable>> MapValues converted => Tuple.Create(pt.WithValue(Maybe.Just(converted)), Maybe.Nothing()), Tuple.Create>( pt, Maybe.Just(new BadFormatConversionError(NameInfo.EmptyName)))); - + foreach (var value in MapValuesImpl(specProps.Skip(1), values.Skip(taken.Count()), converter)) { yield return value; @@ -92,4 +92,4 @@ private static Maybe MakeErrorInCaseOfMinConstraint(this Specification sp : Maybe.Nothing(); } } -} \ No newline at end of file +} diff --git a/src/CommandLine/Core/ValueSpecification.cs b/src/CommandLine/Core/ValueSpecification.cs index bd90252e..e0d6eb73 100644 --- a/src/CommandLine/Core/ValueSpecification.cs +++ b/src/CommandLine/Core/ValueSpecification.cs @@ -8,16 +8,13 @@ namespace CommandLine.Core { sealed class ValueSpecification : Specification { - private readonly int index; - private readonly string metaName; - public ValueSpecification(int index, string metaName, bool required, Maybe min, Maybe max, Maybe defaultValue, string helpText, string metaValue, IEnumerable enumValues, Type conversionType, TargetType targetType, bool hidden = false) : base(SpecificationType.Value, required, min, max, defaultValue, helpText, metaValue, enumValues, conversionType, targetType, hidden) { - this.index = index; - this.metaName = metaName; + this.Index = index; + this.MetaName = metaName; } public static ValueSpecification FromAttribute(ValueAttribute attribute, Type conversionType, IEnumerable enumValues) @@ -37,14 +34,8 @@ public static ValueSpecification FromAttribute(ValueAttribute attribute, Type co attribute.Hidden); } - public int Index - { - get { return index; } - } + public int Index { get; } - public string MetaName - { - get { return metaName;} - } + public string MetaName { get; } } -} \ No newline at end of file +} diff --git a/src/CommandLine/Error.cs b/src/CommandLine/Error.cs index 21c2fdcd..ee6052b6 100644 --- a/src/CommandLine/Error.cs +++ b/src/CommandLine/Error.cs @@ -90,12 +90,9 @@ public enum ErrorType /// /// Base type of all errors. /// - /// All errors are defined within the system. There's no reason to create custom derivate types. + /// All errors are defined within the system. There's no reason to create custom derivative types. public abstract class Error : IEquatable { - private readonly ErrorType tag; - private readonly bool stopsProcessing; - /// /// Initializes a new instance of the class. /// @@ -103,8 +100,8 @@ public abstract class Error : IEquatable /// Tells if error stops parsing process. protected internal Error(ErrorType tag, bool stopsProcessing) { - this.tag = tag; - this.stopsProcessing = stopsProcessing; + this.Tag = tag; + this.StopsProcessing = stopsProcessing; } /// @@ -119,19 +116,13 @@ protected internal Error(ErrorType tag) /// /// Error type discriminator, defined as enumeration. /// - public ErrorType Tag - { - get { return tag; } - } + public ErrorType Tag { get; } /// /// Tells if error stops parsing process. /// Filtered by . /// - public bool StopsProcessing - { - get { return stopsProcessing; } - } + public bool StopsProcessing { get; } /// /// Determines whether the specified is equal to the current . @@ -140,8 +131,7 @@ public bool StopsProcessing /// true if the specified is equal to the current ; otherwise, false. public override bool Equals(object obj) { - var other = obj as Error; - if (other != null) + if (obj is Error other) { return Equals(other); } @@ -179,8 +169,6 @@ public bool Equals(Error other) /// public abstract class TokenError : Error, IEquatable { - private readonly string token; - /// /// Initializes a new instance of the class. /// @@ -189,18 +177,13 @@ public abstract class TokenError : Error, IEquatable protected internal TokenError(ErrorType tag, string token) : base(tag) { - if (token == null) throw new ArgumentNullException("token"); - - this.token = token; + this.Token = token ?? throw new ArgumentNullException(nameof(token)); } /// /// The string containing the token text. /// - public string Token - { - get { return token; } - } + public string Token { get; } /// /// Determines whether the specified is equal to the current . @@ -209,8 +192,7 @@ public string Token /// true if the specified is equal to the current ; otherwise, false. public override bool Equals(object obj) { - var other = obj as TokenError; - if (other != null) + if (obj is TokenError other) { return Equals(other); } @@ -255,12 +237,10 @@ internal BadFormatTokenError(string token) } /// - /// Base type of all erros with name information. + /// Base type of all errors with name information. /// public abstract class NamedError : Error, IEquatable { - private readonly NameInfo nameInfo; - /// /// Initializes a new instance of the class. /// @@ -270,16 +250,13 @@ public abstract class NamedError : Error, IEquatable protected internal NamedError(ErrorType tag, NameInfo nameInfo) : base(tag) { - this.nameInfo = nameInfo; + this.NameInfo = nameInfo; } /// /// Name information relative to this error instance. /// - public NameInfo NameInfo - { - get { return nameInfo; } - } + public NameInfo NameInfo { get; } /// /// Determines whether the specified is equal to the current . @@ -288,8 +265,7 @@ public NameInfo NameInfo /// true if the specified is equal to the current ; otherwise, false. public override bool Equals(object obj) { - var other = obj as NamedError; - if (other != null) + if (obj is NamedError other) { return Equals(other); } @@ -356,25 +332,20 @@ internal MissingRequiredOptionError(NameInfo nameInfo) } /// - /// Models an error generated when a an option from another set is defined. + /// Models an error generated when an option from another set is defined. /// public sealed class MutuallyExclusiveSetError : NamedError { - private readonly string setName; - internal MutuallyExclusiveSetError(NameInfo nameInfo, string setName) : base(ErrorType.MutuallyExclusiveSetError, nameInfo) { - this.setName = setName; + this.SetName = setName; } /// /// Option's set name. /// - public string SetName - { - get { return setName; } - } + public string SetName { get; } } /// @@ -437,41 +408,28 @@ internal HelpRequestedError() /// public sealed class HelpVerbRequestedError : Error { - private readonly string verb; - private readonly Type type; - private readonly bool matched; - internal HelpVerbRequestedError(string verb, Type type, bool matched) : base(ErrorType.HelpVerbRequestedError, true) { - this.verb = verb; - this.type = type; - this.matched = matched; + this.Verb = verb; + this.Type = type; + this.Matched = matched; } /// /// Verb command string. /// - public string Verb - { - get { return verb; } - } + public string Verb { get; } /// /// of verb command. /// - public Type Type - { - get { return type; } - } + public Type Type { get; } /// /// true if verb command is found; otherwise false. /// - public bool Matched - { - get { return matched; } - } + public bool Matched { get; } } /// @@ -501,31 +459,22 @@ internal VersionRequestedError() /// public sealed class SetValueExceptionError : NamedError { - private readonly Exception exception; - private readonly object value; - internal SetValueExceptionError(NameInfo nameInfo, Exception exception, object value) : base(ErrorType.SetValueExceptionError, nameInfo) { - this.exception = exception; - this.value = value; + this.Exception = exception; + this.Value = value; } /// - /// The expection thrown from Property.SetValue + /// The exception thrown from Property.SetValue /// - public Exception Exception - { - get { return exception; } - } + public Exception Exception { get; } /// /// The value that had to be set to the property /// - public object Value - { - get { return value; } - } + public object Value { get; } } /// @@ -545,30 +494,20 @@ public sealed class MissingGroupOptionError : Error, IEquatable, IEquatab { public const string ErrorMessage = "At least one option in a group must have value."; - private readonly string group; - private readonly IEnumerable names; - internal MissingGroupOptionError(string group, IEnumerable names) : base(ErrorType.MissingGroupOptionError) { - this.group = group; - this.names = names; + this.Group = group; + this.Names = names; } - public string Group - { - get { return group; } - } + public string Group { get; } - public IEnumerable Names - { - get { return names; } - } + public IEnumerable Names { get; } public new bool Equals(Error obj) { - var other = obj as MissingGroupOptionError; - if (other != null) + if (obj is MissingGroupOptionError other) { return Equals(other); } diff --git a/src/CommandLine/Infrastructure/CSharpx/Either.cs b/src/CommandLine/Infrastructure/CSharpx/Either.cs index 3d985948..4b510126 100644 --- a/src/CommandLine/Infrastructure/CSharpx/Either.cs +++ b/src/CommandLine/Infrastructure/CSharpx/Either.cs @@ -3,6 +3,7 @@ using System; +// ReSharper disable once CheckNamespace namespace CSharpx { #region Either Type @@ -16,7 +17,7 @@ enum EitherType /// Left, /// - /// Sccessful computation case. + /// Successful computation case. /// Right } @@ -26,17 +27,12 @@ enum EitherType #endif abstract class Either { - private readonly EitherType tag; - protected Either(EitherType tag) { - this.tag = tag; + this.Tag = tag; } - public EitherType Tag - { - get { return this.tag; } - } + public EitherType Tag { get; } #region Basic Match Methods public bool MatchLeft(out TLeft value) @@ -58,18 +54,13 @@ public bool MatchRight(out TRight value) #endif sealed class Left : Either { - private readonly TLeft value; - internal Left(TLeft value) : base(EitherType.Left) { - this.value = value; + this.Value = value; } - public TLeft Value - { - get { return value; } - } + public TLeft Value { get; } } #if !CSX_EITHER_INTERNAL @@ -77,18 +68,13 @@ public TLeft Value #endif sealed class Right : Either { - private readonly TRight value; - internal Right(TRight value) : base(EitherType.Right) { - this.value = value; + Value = value; } - public TRight Value - { - get { return value; } - } + public TRight Value { get; } } #endregion @@ -131,8 +117,7 @@ public static Either Fail(string message) /// public static Either Bind(Either either, Func> func) { - TRight right; - if (either.MatchRight(out right)) { + if (either.MatchRight(out var right)) { return func(right); } return Either.Left(either.GetLeft()); @@ -141,12 +126,11 @@ public static Either Bind(Either - /// Transforms a Either's right value by using a specified mapping function. + /// Transforms an Either's right value by using a specified mapping function. /// public static Either Map(Either either, Func func) { - TRight right; - if (either.MatchRight(out right)) { + if (either.MatchRight(out var right)) { return Either.Right(func(right)); } return Either.Left(either.GetLeft()); @@ -155,13 +139,12 @@ public static Either Map(Either - /// Maps both parts of a Either type. Applies the first function if Either is Left. - /// Otherwise applies the second function. + /// Maps both parts of an Either type. Applies the first function if Either is Left. + /// Otherwise, applies the second function. /// public static Either Bimap(Either either, Func mapLeft, Func mapRight) { - TRight right; - if (either.MatchRight(out right)) { + if (either.MatchRight(out var right)) { return Either.Right(mapRight(right)); } return Either.Left(mapLeft(either.GetLeft())); @@ -187,37 +170,34 @@ public static Either SelectMany(this Eit #endregion /// - /// Returns a Either Right or fail with an exception. + /// Returns an Either Right or fail with an exception. /// public static TRight GetOrFail(Either either) { - TRight value; - if (either.MatchRight(out value)) { + if (either.MatchRight(out var value)) { return value; } throw new ArgumentException(nameof(either), string.Format("The either value was Left {0}", either)); } /// - /// Returns a Either Left or a defualt value. + /// Returns an Either Left or a default value. /// public static TLeft GetLeftOrDefault(Either either, TLeft @default) { - TLeft value; - return either.MatchLeft(out value) ? value : @default; + return either.MatchLeft(out var value) ? value : @default; } /// - /// Returns a Either Right or a defualt value. + /// Returns an Either Right or a default value. /// public static TRight GetRightOrDefault(Either either, TRight @default) { - TRight value; - return either.MatchRight(out value) ? value : @default; + return either.MatchRight(out var value) ? value : @default; } /// - /// Wraps a function, encapsulates any exception thrown within to a Either. + /// Wraps a function, encapsulates any exception thrown within to an Either. /// public static Either Try(Func func) { @@ -262,8 +242,7 @@ static class EitherExtensions #region Alternative Match Methods public static void Match(this Either either, Action ifLeft, Action ifRight) { - TLeft left; - if (either.MatchLeft(out left)) { + if (either.MatchLeft(out var left)) { ifLeft(left); return; } diff --git a/src/CommandLine/Infrastructure/CSharpx/EnumerableExtensions.cs b/src/CommandLine/Infrastructure/CSharpx/EnumerableExtensions.cs index b668eb46..f81bc1d2 100644 --- a/src/CommandLine/Infrastructure/CSharpx/EnumerableExtensions.cs +++ b/src/CommandLine/Infrastructure/CSharpx/EnumerableExtensions.cs @@ -11,6 +11,7 @@ using System.Text; using LinqEnumerable = System.Linq.Enumerable; +// ReSharper disable once CheckNamespace namespace CSharpx { #if !CSX_ENUM_INTERNAL @@ -47,8 +48,7 @@ public static Maybe> ToMaybe(this IEnumerable source) private static IEnumerable AssertCountImpl(IEnumerable source, int count, Func errorSelector) { - var collection = source as ICollection; // Optimization for collections - if (collection != null) + if (source is ICollection collection) // Optimization for collections { if (collection.Count != count) { throw errorSelector(collection.Count.CompareTo(count), count); @@ -266,9 +266,9 @@ public static void ForEach(this IEnumerable source, Action action) /// /// Returns a sequence resulting from applying a function to each - /// element in the source sequence and its - /// predecessor, with the exception of the first element which is - /// only returned as the predecessor of the second element. + /// element in the source sequence and its /predecessor, except + /// the first element which is /only returned as the + /// predecessor of the second element. /// public static IEnumerable Pairwise(this IEnumerable source, Func resultSelector) { @@ -418,7 +418,7 @@ public static T Choice(this IEnumerable source) } /// - /// Takes an element and a sequence and `intersperses' that element between its elements. + /// Takes an element and a sequence and "intersperses" that element between its elements. /// public static IEnumerable Intersperse(this IEnumerable source, T element) { @@ -447,7 +447,7 @@ public static IEnumerable FlattenOnce(this IEnumerable> sou } /// - /// Reduces a sequence of strings to a sequence of parts, splitted by space, + /// Reduces a sequence of strings to a sequence of parts, split by space, /// of each original string. /// public static IEnumerable FlattenOnce(this IEnumerable source) @@ -460,4 +460,4 @@ public static IEnumerable FlattenOnce(this IEnumerable source) } } } -} \ No newline at end of file +} diff --git a/src/CommandLine/Infrastructure/CSharpx/Maybe.cs b/src/CommandLine/Infrastructure/CSharpx/Maybe.cs index 044bb681..5f1c71a3 100644 --- a/src/CommandLine/Infrastructure/CSharpx/Maybe.cs +++ b/src/CommandLine/Infrastructure/CSharpx/Maybe.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Linq; +// ReSharper disable once CheckNamespace namespace CSharpx { #region Maybe Type @@ -21,7 +22,7 @@ enum MaybeType } /// - /// The Maybe type models an optional value. A value of type Maybe a either contains a value of type a (represented as Just a), + /// The Maybe type models an optional value. A value of type Maybe either contains a value of type a (represented as Just a), /// or it is empty (represented as Nothing). /// #if !CSX_MAYBE_INTERNAL @@ -29,17 +30,15 @@ enum MaybeType #endif abstract class Maybe { - private readonly MaybeType tag; - protected Maybe(MaybeType tag) { - this.tag = tag; + this.Tag = tag; } /// /// Type discriminator. /// - public MaybeType Tag { get { return tag; } } + public MaybeType Tag { get; } #region Basic Match Methods /// @@ -68,7 +67,7 @@ public bool MatchNothing() #if !CSX_MAYBE_INTERNAL public #endif - sealed class Nothing : Maybe + sealed class Nothing : Maybe { internal Nothing() : base(MaybeType.Nothing) @@ -82,23 +81,18 @@ internal Nothing() #if !CSX_MAYBE_INTERNAL public #endif - sealed class Just : Maybe + sealed class Just : Maybe { - private readonly T value; - internal Just(T value) : base(MaybeType.Just) { - this.value = value; + this.Value = value; } /// /// The wrapped value. /// - public T Value - { - get { return value; } - } + public T Value { get; } } /// @@ -141,30 +135,26 @@ public static Maybe Return(T value) /// public static Maybe Bind(Maybe maybe, Func> func) { - T1 value1; - return maybe.MatchJust(out value1) ? func(value1) : Maybe.Nothing(); + return maybe.MatchJust(out var value1) ? func(value1) : Maybe.Nothing(); } #endregion #region Functor /// - /// Transforms an maybe value by using a specified mapping function. + /// Transforms a Maybe value by using a specified mapping function. /// public static Maybe Map(Maybe maybe, Func func) { - T1 value1; - return maybe.MatchJust(out value1) ? Maybe.Just(func(value1)) : Maybe.Nothing(); + return maybe.MatchJust(out var value1) ? Maybe.Just(func(value1)) : Maybe.Nothing(); } #endregion /// - /// If both maybes contain a value, it merges them into a maybe with a tupled value. + /// If both Maybes contain a value, it merges them into a Maybe with a tupled value. /// public static Maybe> Merge(Maybe first, Maybe second) { - T1 value1; - T2 value2; - if (first.MatchJust(out value1) && second.MatchJust(out value2)) { + if (first.MatchJust(out var value1) && second.MatchJust(out var value2)) { return Maybe.Just(Tuple.Create(value1, value2)); } return Maybe.Nothing>(); @@ -198,8 +188,7 @@ static class MaybeExtensions /// public static void Match(this Maybe maybe, Action ifJust, Action ifNothing) { - T value; - if (maybe.MatchJust(out value)) { + if (maybe.MatchJust(out var value)) { ifJust(value); return; } @@ -211,9 +200,7 @@ public static void Match(this Maybe maybe, Action ifJust, Action ifNoth /// public static void Match(this Maybe> maybe, Action ifJust, Action ifNothing) { - T1 value1; - T2 value2; - if (maybe.MatchJust(out value1, out value2)) { + if (maybe.MatchJust(out var value1, out var value2)) { ifJust(value1, value2); return; } @@ -225,8 +212,7 @@ public static void Match(this Maybe> maybe, Action /// public static bool MatchJust(this Maybe> maybe, out T1 value1, out T2 value2) { - Tuple value; - if (maybe.MatchJust(out value)) { + if (maybe.MatchJust(out var value)) { value1 = value.Item1; value2 = value.Item2; return true; @@ -294,27 +280,24 @@ public static Maybe SelectMany( /// public static void Do(this Maybe maybe, Action action) { - T value; - if (maybe.MatchJust(out value)) { + if (maybe.MatchJust(out var value)) { action(value); } } /// - /// If contans a value executes an delegate over it. + /// If contains a value executes an delegate over it. /// public static void Do(this Maybe> maybe, Action action) { - T1 value1; - T2 value2; - if (maybe.MatchJust(out value1, out value2)) { + if (maybe.MatchJust(out var value1, out var value2)) { action(value1, value2); } } #endregion /// - /// Returns true iffits argument is of the form . + /// Returns true if its argument is of the form . /// public static bool IsJust(this Maybe maybe) { @@ -322,7 +305,7 @@ public static bool IsJust(this Maybe maybe) } /// - /// Returns true iffits argument is of the form . + /// Returns true if its argument is of the form . /// public static bool IsNothing(this Maybe maybe) { @@ -334,8 +317,7 @@ public static bool IsNothing(this Maybe maybe) /// public static T FromJust(this Maybe maybe) { - T value; - if (maybe.MatchJust(out value)) { + if (maybe.MatchJust(out var value)) { return value; } return default(T); @@ -346,8 +328,7 @@ public static T FromJust(this Maybe maybe) /// public static T FromJustOrFail(this Maybe maybe, Exception exceptionToThrow = null) { - T value; - if (maybe.MatchJust(out value)) { + if (maybe.MatchJust(out var value)) { return value; } throw exceptionToThrow ?? new ArgumentException("Value empty."); @@ -358,8 +339,7 @@ public static T FromJustOrFail(this Maybe maybe, Exception exceptionToThro /// public static T GetValueOrDefault(this Maybe maybe, T noneValue) { - T value; - return maybe.MatchJust(out value) ? value : noneValue; + return maybe.MatchJust(out var value) ? value : noneValue; } /// @@ -367,16 +347,14 @@ public static T GetValueOrDefault(this Maybe maybe, T noneValue) /// public static T2 MapValueOrDefault(this Maybe maybe, Func func, T2 noneValue) { - T1 value1; - return maybe.MatchJust(out value1) ? func(value1) : noneValue; + return maybe.MatchJust(out var value1) ? func(value1) : noneValue; } /// /// If contains a values executes a mapping function over it, otherwise returns the value from . /// public static T2 MapValueOrDefault(this Maybe maybe, Func func, Func noneValueFactory) { - T1 value1; - return maybe.MatchJust(out value1) ? func(value1) : noneValueFactory(); + return maybe.MatchJust(out var value1) ? func(value1) : noneValueFactory(); } /// @@ -384,11 +362,10 @@ public static T2 MapValueOrDefault(this Maybe maybe, Func fu /// public static IEnumerable ToEnumerable(this Maybe maybe) { - T value; - if (maybe.MatchJust(out value)) { + if (maybe.MatchJust(out var value)) { return Enumerable.Empty().Concat(new[] { value }); } return Enumerable.Empty(); } } -} \ No newline at end of file +} diff --git a/src/CommandLine/Infrastructure/ErrorHandling.cs b/src/CommandLine/Infrastructure/ErrorHandling.cs index 8aee4bac..66f2ece2 100644 --- a/src/CommandLine/Infrastructure/ErrorHandling.cs +++ b/src/CommandLine/Infrastructure/ErrorHandling.cs @@ -10,6 +10,7 @@ using CSharpx; #endif +// ReSharper disable once CheckNamespace namespace RailwaySharp.ErrorHandling { #if !ERRH_INTERNAL @@ -31,17 +32,12 @@ enum ResultType #endif abstract class Result { - private readonly ResultType _tag; - protected Result(ResultType tag) { - _tag = tag; + Tag = tag; } - public ResultType Tag - { - get { return _tag; } - } + public ResultType Tag { get; } public override string ToString() { @@ -81,15 +77,9 @@ public Ok(TSuccess success, IEnumerable messages) _value = Tuple.Create(success, messages); } - public TSuccess Success - { - get { return _value.Item1; } - } + public TSuccess Success => _value.Item1; - public IEnumerable Messages - { - get { return _value.Item2; } - } + public IEnumerable Messages => _value.Item2; } /// @@ -102,20 +92,13 @@ public IEnumerable Messages #endif sealed class Bad : Result { - private readonly IEnumerable _messages; - public Bad(IEnumerable messages) : base(ResultType.Bad) { - if (messages == null) throw new ArgumentException(nameof(messages)); - - _messages = messages; + Messages = messages ?? throw new ArgumentException(nameof(messages)); } - public IEnumerable Messages - { - get { return _messages; } - } + public IEnumerable Messages { get; } } #if !ERRH_INTERNAL @@ -267,8 +250,7 @@ public static TResult Either( if (successFunc == null) throw new ArgumentException(nameof(successFunc)); if (failureFunc == null) throw new ArgumentException(nameof(failureFunc)); - var ok = trialResult as Ok; - if (ok != null) { + if (trialResult is Ok ok) { return successFunc(ok.Success, ok.Messages); } var bad = (Bad)trialResult; @@ -277,7 +259,7 @@ public static TResult Either( /// /// If the given result is a Success the wrapped value will be returned. - /// Otherwise the function throws an exception with Failure message of the result. + /// Otherwise, the function throws an exception with Failure message of the result. /// #if ERRH_ENABLE_INLINE_METHODS [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -319,7 +301,7 @@ public static Result MergeMessages( /// /// If the result is a Success it executes the given function on the value. - /// Otherwise the exisiting failure is propagated. + /// Otherwise, the existing failure is propagated. /// #if ERRH_ENABLE_INLINE_METHODS [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -353,7 +335,7 @@ public static Result Flatten( /// /// If the wrapped function is a success and the given result is a success the function is applied on the value. - /// Otherwise the exisiting error messages are propagated. + /// Otherwise, the existing error messages are propagated. /// #if ERRH_ENABLE_INLINE_METHODS [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -472,8 +454,7 @@ public static void Match(this Result res if (ifSuccess == null) throw new ArgumentException(nameof(ifSuccess)); if (ifFailure == null) throw new ArgumentException(nameof(ifFailure)); - var ok = result as Ok; - if (ok != null) { + if (result is Ok ok) { ifSuccess(ok.Success, ok.Messages); return; } @@ -546,7 +527,7 @@ public static Result, TMessage> Flatten /// If the result is a Success it executes the given Func on the value. - /// Otherwise the exisiting failure is propagated. + /// Otherwise, the existing failure is propagated. /// #if ERRH_ENABLE_INLINE_METHODS [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -560,7 +541,7 @@ public static Result SelectMany( /// /// If the result is a Success it executes the given Func on the value. /// If the result of the Func is a Success it maps it using the given Func. - /// Otherwise the exisiting failure is propagated. + /// Otherwise, the existing failure is propagated. /// #if ERRH_ENABLE_INLINE_METHODS [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -661,4 +642,4 @@ public static Maybe ToMaybe(this Result) - .MakeGenericType(type) - .StaticMethod( - "Some", value); - } - - public static object None(Type type) - { - return typeof(FSharpOption<>) - .MakeGenericType(type) - .StaticProperty( - "None"); - } - - public static object ValueOf(object value) - { - return typeof(FSharpOption<>) - .MakeGenericType(GetUnderlyingType(value.GetType())) - .InstanceProperty( - "Value", value); - } - - public static bool IsSome(object value) - { - return (bool)typeof(FSharpOption<>) - .MakeGenericType(GetUnderlyingType(value.GetType())) - .StaticMethod( - "get_IsSome", value); - } - } -} \ No newline at end of file diff --git a/src/CommandLine/Infrastructure/LocalizableAttributeProperty.cs b/src/CommandLine/Infrastructure/LocalizableAttributeProperty.cs index b8bd1398..c2d55965 100644 --- a/src/CommandLine/Infrastructure/LocalizableAttributeProperty.cs +++ b/src/CommandLine/Infrastructure/LocalizableAttributeProperty.cs @@ -17,7 +17,7 @@ public LocalizableAttributeProperty(string propertyName) public string Value { - get { return GetLocalizedValue(); } + get => GetLocalizedValue(); set { _localizationPropertyInfo = null; diff --git a/src/CommandLine/Infrastructure/StringBuilderExtensions.cs b/src/CommandLine/Infrastructure/StringBuilderExtensions.cs index ae4ccbc4..0957d0df 100644 --- a/src/CommandLine/Infrastructure/StringBuilderExtensions.cs +++ b/src/CommandLine/Infrastructure/StringBuilderExtensions.cs @@ -73,7 +73,7 @@ public static string SafeToString(this StringBuilder builder) public static int SafeLength(this StringBuilder builder) { - return builder == null ? 0 : builder.Length; + return builder?.Length ?? 0; } public static StringBuilder TrimEnd(this StringBuilder builder, char c) diff --git a/src/CommandLine/Infrastructure/StringExtensions.cs b/src/CommandLine/Infrastructure/StringExtensions.cs index db8aa0bd..c575a86a 100644 --- a/src/CommandLine/Infrastructure/StringExtensions.cs +++ b/src/CommandLine/Infrastructure/StringExtensions.cs @@ -50,7 +50,7 @@ public static bool EqualsOrdinalIgnoreCase(this string strA, string strB) public static int SafeLength(this string value) { - return value == null ? 0 : value.Length; + return value?.Length ?? 0; } public static string JoinTo(this string value, params string[] others) diff --git a/src/CommandLine/NameInfo.cs b/src/CommandLine/NameInfo.cs index baf259ef..fa820f18 100644 --- a/src/CommandLine/NameInfo.cs +++ b/src/CommandLine/NameInfo.cs @@ -1,7 +1,6 @@ // Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information. using System; -using CommandLine.Core; namespace CommandLine { @@ -15,48 +14,32 @@ public sealed class NameInfo : IEquatable /// rather than options. /// public static readonly NameInfo EmptyName = new NameInfo(string.Empty, string.Empty); - private readonly string longName; - private readonly string shortName; internal NameInfo(string shortName, string longName) { - if (shortName == null) throw new ArgumentNullException("shortName"); - if (longName == null) throw new ArgumentNullException("longName"); - - this.longName = longName; - this.shortName = shortName; + this.LongName = longName ?? throw new ArgumentNullException(nameof(longName)); + this.ShortName = shortName ?? throw new ArgumentNullException(nameof(shortName)); } /// /// Gets the short name of the name information. /// - public string ShortName - { - get { return shortName; } - } + public string ShortName { get; } /// /// Gets the long name of the name information. /// - public string LongName - { - get { return longName; } - } + public string LongName { get; } /// /// Gets a formatted text with unified name information. /// - public string NameText - { - get - { - return ShortName.Length > 0 && LongName.Length > 0 - ? ShortName + ", " + LongName - : ShortName.Length > 0 - ? ShortName - : LongName; - } - } + public string NameText => + ShortName.Length > 0 && LongName.Length > 0 + ? ShortName + ", " + LongName + : ShortName.Length > 0 + ? ShortName + : LongName; /// /// Determines whether the specified is equal to the current . @@ -65,8 +48,7 @@ public string NameText /// true if the specified is equal to the current ; otherwise, false. public override bool Equals(object obj) { - var other = obj as NameInfo; - if (other != null) + if (obj is NameInfo other) { return Equals(other); } @@ -98,4 +80,4 @@ public bool Equals(NameInfo other) return ShortName.Equals(other.ShortName) && LongName.Equals(other.LongName); } } -} \ No newline at end of file +} diff --git a/src/CommandLine/NullInstance.cs b/src/CommandLine/NullInstance.cs index c2ebd77a..820a2f30 100644 --- a/src/CommandLine/NullInstance.cs +++ b/src/CommandLine/NullInstance.cs @@ -3,10 +3,10 @@ namespace CommandLine { /// - /// Models a null result when constructing a in a faling verbs scenario. + /// Models a null result when constructing a in a failing verbs scenario. /// public sealed class NullInstance { internal NullInstance() { } } -} \ No newline at end of file +} diff --git a/src/CommandLine/OptionAttribute.cs b/src/CommandLine/OptionAttribute.cs index 6ae51dac..01a64f38 100644 --- a/src/CommandLine/OptionAttribute.cs +++ b/src/CommandLine/OptionAttribute.cs @@ -10,24 +10,16 @@ namespace CommandLine /// Models an option specification. /// [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] - public sealed class OptionAttribute : BaseAttribute + public class OptionAttribute : BaseAttribute { - private readonly string longName; - private readonly string shortName; private string setName; - private bool flagCounter; - private char separator; - private string group=string.Empty; private OptionAttribute(string shortName, string longName) : base() { - if (shortName == null) throw new ArgumentNullException("shortName"); - if (longName == null) throw new ArgumentNullException("longName"); - - this.shortName = shortName; - this.longName = longName; + this.ShortName = shortName ?? throw new ArgumentNullException(nameof(shortName)); + this.LongName = longName ?? throw new ArgumentNullException(nameof(longName)); setName = string.Empty; - separator = '\0'; + Separator = '\0'; } /// @@ -61,7 +53,7 @@ public OptionAttribute(char shortName, string longName) /// /// Initializes a new instance of the class. /// - /// The short name of the option.. + /// The short name of the option. public OptionAttribute(char shortName) : this(shortName.ToOneCharString(), string.Empty) { @@ -70,60 +62,37 @@ public OptionAttribute(char shortName) /// /// Gets long name of this command line option. This name is usually a single english word. /// - public string LongName - { - get { return longName; } - } + public string LongName { get; } /// /// Gets a short name of this command line option, made of one character. /// - public string ShortName - { - get { return shortName; } - } + public string ShortName { get; } /// /// Gets or sets the option's mutually exclusive set name. /// public string SetName { - get { return setName; } - set - { - if (value == null) throw new ArgumentNullException("value"); - - setName = value; - } + get => setName; + set => setName = value ?? throw new ArgumentNullException(nameof(value)); } /// /// If true, this is an int option that counts how many times a flag was set (e.g. "-v -v -v" or "-vvv" would return 3). /// The property must be of type int (signed 32-bit integer). /// - public bool FlagCounter - { - get { return flagCounter; } - set { flagCounter = value; } - } + public bool FlagCounter { get; set; } /// /// When applying attribute to target properties, /// it allows you to split an argument and consume its content as a sequence. /// - public char Separator - { - get { return separator; } - set { separator = value; } - } + public char Separator { get; set; } /// /// Gets or sets the option group name. When one or more options are grouped, at least one of them should have value. Required rules are ignored. /// - public string Group - { - get { return group; } - set { group = value; } - } + public string Group { get; set; } = string.Empty; } } diff --git a/src/CommandLine/Parser.cs b/src/CommandLine/Parser.cs index 4301aa52..291a82dc 100644 --- a/src/CommandLine/Parser.cs +++ b/src/CommandLine/Parser.cs @@ -37,7 +37,7 @@ public Parser() /// aspects and behaviors of the parser. public Parser(Action configuration) { - if (configuration == null) throw new ArgumentNullException("configuration"); + if (configuration == null) throw new ArgumentNullException(nameof(configuration)); settings = new ParserSettings(); configuration(settings); @@ -61,18 +61,12 @@ internal Parser(ParserSettings settings) /// /// Gets the singleton instance created with basic defaults. /// - public static Parser Default - { - get { return DefaultParser.Value; } - } + public static Parser Default => DefaultParser.Value; /// /// Gets the instance that implements in use. /// - public ParserSettings Settings - { - get { return settings; } - } + public ParserSettings Settings => settings; /// /// Parses a string array of command line arguments constructing values in an instance of type . @@ -85,7 +79,7 @@ public ParserSettings Settings /// Thrown if one or more arguments are null. public ParserResult ParseArguments(IEnumerable args) { - if (args == null) throw new ArgumentNullException("args"); + if (args == null) throw new ArgumentNullException(nameof(args)); var factory = typeof(T).IsMutable() ? Maybe.Just>(Activator.CreateInstance) @@ -118,9 +112,9 @@ public ParserResult ParseArguments(IEnumerable args) /// Thrown if one or more arguments are null. public ParserResult ParseArguments(Func factory, IEnumerable args) { - if (factory == null) throw new ArgumentNullException("factory"); - if (!typeof(T).IsMutable()) throw new ArgumentException("factory"); - if (args == null) throw new ArgumentNullException("args"); + if (factory == null) throw new ArgumentNullException(nameof(factory)); + if (!typeof(T).IsMutable()) throw new ArgumentException(nameof(factory)); + if (args == null) throw new ArgumentNullException(nameof(args)); return MakeParserResult( InstanceBuilder.Build( @@ -151,9 +145,9 @@ public ParserResult ParseArguments(Func factory, IEnumerable ar /// All types must expose a parameterless constructor. It's strongly recommended to use a generic overload. public ParserResult ParseArguments(IEnumerable args, params Type[] types) { - if (args == null) throw new ArgumentNullException("args"); - if (types == null) throw new ArgumentNullException("types"); - if (types.Length == 0) throw new ArgumentOutOfRangeException("types"); + if (args == null) throw new ArgumentNullException(nameof(args)); + if (types == null) throw new ArgumentNullException(nameof(types)); + if (types.Length == 0) throw new ArgumentOutOfRangeException(nameof(types)); return MakeParserResult( InstanceChooser.Choose( diff --git a/src/CommandLine/ParserExtensions.cs b/src/CommandLine/ParserExtensions.cs index 1c78ce9d..1e7d7fe2 100644 --- a/src/CommandLine/ParserExtensions.cs +++ b/src/CommandLine/ParserExtensions.cs @@ -25,7 +25,7 @@ public static class ParserExtensions /// All types must expose a parameterless constructor. public static ParserResult ParseArguments(this Parser parser, IEnumerable args) { - if (parser == null) throw new ArgumentNullException("parser"); + if (parser == null) throw new ArgumentNullException(nameof(parser)); return parser.ParseArguments(args, new[] { typeof(T1), typeof(T2) }); } @@ -46,7 +46,7 @@ public static ParserResult ParseArguments(this Parser parser, IE /// All types must expose a parameterless constructor. public static ParserResult ParseArguments(this Parser parser, IEnumerable args) { - if (parser == null) throw new ArgumentNullException("parser"); + if (parser == null) throw new ArgumentNullException(nameof(parser)); return parser.ParseArguments(args, new[] { typeof(T1), typeof(T2), typeof(T3) }); } @@ -68,7 +68,7 @@ public static ParserResult ParseArguments(this Parser parser /// All types must expose a parameterless constructor. public static ParserResult ParseArguments(this Parser parser, IEnumerable args) { - if (parser == null) throw new ArgumentNullException("parser"); + if (parser == null) throw new ArgumentNullException(nameof(parser)); return parser.ParseArguments(args, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) }); } @@ -91,7 +91,7 @@ public static ParserResult ParseArguments(this Parser pa /// All types must expose a parameterless constructor. public static ParserResult ParseArguments(this Parser parser, IEnumerable args) { - if (parser == null) throw new ArgumentNullException("parser"); + if (parser == null) throw new ArgumentNullException(nameof(parser)); return parser.ParseArguments(args, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5) }); } @@ -115,7 +115,7 @@ public static ParserResult ParseArguments(this Parse /// All types must expose a parameterless constructor. public static ParserResult ParseArguments(this Parser parser, IEnumerable args) { - if (parser == null) throw new ArgumentNullException("parser"); + if (parser == null) throw new ArgumentNullException(nameof(parser)); return parser.ParseArguments(args, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6) }); } @@ -140,7 +140,7 @@ public static ParserResult ParseArguments(this P /// All types must expose a parameterless constructor. public static ParserResult ParseArguments(this Parser parser, IEnumerable args) { - if (parser == null) throw new ArgumentNullException("parser"); + if (parser == null) throw new ArgumentNullException(nameof(parser)); return parser.ParseArguments(args, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7) }); } @@ -166,7 +166,7 @@ public static ParserResult ParseArguments(th /// All types must expose a parameterless constructor. public static ParserResult ParseArguments(this Parser parser, IEnumerable args) { - if (parser == null) throw new ArgumentNullException("parser"); + if (parser == null) throw new ArgumentNullException(nameof(parser)); return parser.ParseArguments(args, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8) }); } @@ -193,7 +193,7 @@ public static ParserResult ParseArgumentsAll types must expose a parameterless constructor. public static ParserResult ParseArguments(this Parser parser, IEnumerable args) { - if (parser == null) throw new ArgumentNullException("parser"); + if (parser == null) throw new ArgumentNullException(nameof(parser)); return parser.ParseArguments(args, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8), typeof(T9) }); @@ -222,7 +222,7 @@ public static ParserResult ParseArgumentsAll types must expose a parameterless constructor. public static ParserResult ParseArguments(this Parser parser, IEnumerable args) { - if (parser == null) throw new ArgumentNullException("parser"); + if (parser == null) throw new ArgumentNullException(nameof(parser)); return parser.ParseArguments(args, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8), typeof(T9), typeof(T10) }); @@ -252,7 +252,7 @@ public static ParserResult ParseArgumentsAll types must expose a parameterless constructor. public static ParserResult ParseArguments(this Parser parser, IEnumerable args) { - if (parser == null) throw new ArgumentNullException("parser"); + if (parser == null) throw new ArgumentNullException(nameof(parser)); return parser.ParseArguments(args, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8), typeof(T9), typeof(T10), typeof(T11) }); @@ -283,7 +283,7 @@ public static ParserResult ParseArgumentsAll types must expose a parameterless constructor. public static ParserResult ParseArguments(this Parser parser, IEnumerable args) { - if (parser == null) throw new ArgumentNullException("parser"); + if (parser == null) throw new ArgumentNullException(nameof(parser)); return parser.ParseArguments(args, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8), typeof(T9), typeof(T10), typeof(T11), typeof(T12) }); @@ -315,7 +315,7 @@ public static ParserResult ParseArgumentsAll types must expose a parameterless constructor. public static ParserResult ParseArguments(this Parser parser, IEnumerable args) { - if (parser == null) throw new ArgumentNullException("parser"); + if (parser == null) throw new ArgumentNullException(nameof(parser)); return parser.ParseArguments(args, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8), typeof(T9), typeof(T10), typeof(T11), typeof(T12), typeof(T13) }); @@ -348,7 +348,7 @@ public static ParserResult ParseArgumentsAll types must expose a parameterless constructor. public static ParserResult ParseArguments(this Parser parser, IEnumerable args) { - if (parser == null) throw new ArgumentNullException("parser"); + if (parser == null) throw new ArgumentNullException(nameof(parser)); return parser.ParseArguments(args, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8), typeof(T9), typeof(T10), typeof(T11), typeof(T12), typeof(T13), typeof(T14) }); @@ -382,7 +382,7 @@ public static ParserResult ParseArgumentsAll types must expose a parameterless constructor. public static ParserResult ParseArguments(this Parser parser, IEnumerable args) { - if (parser == null) throw new ArgumentNullException("parser"); + if (parser == null) throw new ArgumentNullException(nameof(parser)); return parser.ParseArguments(args, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8), typeof(T9), typeof(T10), typeof(T11), typeof(T12), typeof(T13), typeof(T14), typeof(T15) }); @@ -417,10 +417,10 @@ public static ParserResult ParseArgumentsAll types must expose a parameterless constructor. public static ParserResult ParseArguments(this Parser parser, IEnumerable args) { - if (parser == null) throw new ArgumentNullException("parser"); + if (parser == null) throw new ArgumentNullException(nameof(parser)); return parser.ParseArguments(args, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8), typeof(T9), typeof(T10), typeof(T11), typeof(T12), typeof(T13), typeof(T14), typeof(T15), typeof(T16) }); } } -} \ No newline at end of file +} diff --git a/src/CommandLine/ParserResult.cs b/src/CommandLine/ParserResult.cs index c7c9c833..d74a8efb 100644 --- a/src/CommandLine/ParserResult.cs +++ b/src/CommandLine/ParserResult.cs @@ -8,24 +8,15 @@ namespace CommandLine { public sealed class TypeInfo { - private readonly Type current; - private readonly IEnumerable choices; - private TypeInfo(Type current, IEnumerable choices) { - this.current = current; - this.choices = choices; + this.Current = current; + this.Choices = choices; } - public Type Current - { - get { return this.current; } - } + public Type Current { get; } - public IEnumerable Choices - { - get { return this.choices; } - } + public IEnumerable Choices { get; } internal static TypeInfo Create(Type current) { @@ -61,40 +52,31 @@ public enum ParserResultType /// The type with attributes that define the syntax of parsing rules. public abstract class ParserResult { - private readonly ParserResultType tag; - private readonly TypeInfo typeInfo; - internal ParserResult(IEnumerable errors, TypeInfo typeInfo) { - this.tag = ParserResultType.NotParsed; - this.typeInfo = typeInfo ?? TypeInfo.Create(typeof(T)); - Errors = errors ?? new Error[0]; + this.Tag = ParserResultType.NotParsed; + this.TypeInfo = typeInfo ?? TypeInfo.Create(typeof(T)); + Errors = errors ?? Array.Empty(); Value = default; } internal ParserResult(T value, TypeInfo typeInfo) { Value = value ?? throw new ArgumentNullException(nameof(value)); - this.tag = ParserResultType.Parsed; - this.typeInfo = typeInfo ?? TypeInfo.Create(value.GetType()); - Errors = new Error[0]; + this.Tag = ParserResultType.Parsed; + this.TypeInfo = typeInfo ?? TypeInfo.Create(value.GetType()); + Errors = Array.Empty(); } /// /// Parser result type discriminator, defined as enumeration. /// - public ParserResultType Tag - { - get { return this.tag; } - } + public ParserResultType Tag { get; } - public TypeInfo TypeInfo - { - get { return typeInfo; } - } + public TypeInfo TypeInfo { get; } /// - /// Gets the instance with parsed values. If one or more errors occures, is returned. + /// Gets the instance with parsed values. If one or more errors occurs, is returned. /// public T Value { get; } diff --git a/src/CommandLine/ParserResultExtensions.cs b/src/CommandLine/ParserResultExtensions.cs index 66201dbb..a5ddd3b6 100644 --- a/src/CommandLine/ParserResultExtensions.cs +++ b/src/CommandLine/ParserResultExtensions.cs @@ -20,8 +20,7 @@ public static partial class ParserResultExtensions /// The same instance. public static ParserResult WithParsed(this ParserResult result, Action action) { - var parsed = result as Parsed; - if (parsed != null) + if (result is Parsed parsed) { action(parsed.Value); } @@ -37,8 +36,7 @@ public static ParserResult WithParsed(this ParserResult result, Action< /// The same instance. public static ParserResult WithParsed(this ParserResult result, Action action) { - var parsed = result as Parsed; - if (parsed != null) + if (result is Parsed parsed) { if (parsed.Value is T) { @@ -58,8 +56,7 @@ public static ParserResult WithParsed(this ParserResult resul /// The same instance. public static ParserResult WithNotParsed(this ParserResult result, Action> action) { - var notParsed = result as NotParsed; - if (notParsed != null) + if (result is NotParsed notParsed) { action(notParsed.Errors); } @@ -79,8 +76,7 @@ public static TResult MapResult(this ParserResult res Func parsedFunc, Func, TResult> notParsedFunc) { - var parsed = result as Parsed; - if (parsed != null) + if (result is Parsed parsed) { return parsedFunc(parsed.Value); } @@ -100,8 +96,7 @@ public static TResult MapResult(this ParserResult result, Func parsedFunc1, Func, TResult> notParsedFunc) { - var parsed = result as Parsed; - if (parsed != null) + if (result is Parsed parsed) { if (parsed.Value is T1) { @@ -128,8 +123,7 @@ public static TResult MapResult(this ParserResult resul Func parsedFunc2, Func, TResult> notParsedFunc) { - var parsed = result as Parsed; - if (parsed != null) + if (result is Parsed parsed) { if (parsed.Value is T1) { @@ -163,8 +157,7 @@ public static TResult MapResult(this ParserResult r Func parsedFunc3, Func, TResult> notParsedFunc) { - var parsed = result as Parsed; - if (parsed != null) + if (result is Parsed parsed) { if (parsed.Value is T1) { @@ -205,8 +198,7 @@ public static TResult MapResult(this ParserResult parsedFunc4, Func, TResult> notParsedFunc) { - var parsed = result as Parsed; - if (parsed != null) + if (result is Parsed parsed) { if (parsed.Value is T1) { @@ -254,8 +246,7 @@ public static TResult MapResult(this ParserResult parsedFunc5, Func, TResult> notParsedFunc) { - var parsed = result as Parsed; - if (parsed != null) + if (result is Parsed parsed) { if (parsed.Value is T1) { @@ -310,8 +301,7 @@ public static TResult MapResult(this ParserResu Func parsedFunc6, Func, TResult> notParsedFunc) { - var parsed = result as Parsed; - if (parsed != null) + if (result is Parsed parsed) { if (parsed.Value is T1) { @@ -373,8 +363,7 @@ public static TResult MapResult(this Parser Func parsedFunc7, Func, TResult> notParsedFunc) { - var parsed = result as Parsed; - if (parsed != null) + if (result is Parsed parsed) { if (parsed.Value is T1) { @@ -443,8 +432,7 @@ public static TResult MapResult(this Pa Func parsedFunc8, Func, TResult> notParsedFunc) { - var parsed = result as Parsed; - if (parsed != null) + if (result is Parsed parsed) { if (parsed.Value is T1) { @@ -520,8 +508,7 @@ public static TResult MapResult(thi Func parsedFunc9, Func, TResult> notParsedFunc) { - var parsed = result as Parsed; - if (parsed != null) + if (result is Parsed parsed) { if (parsed.Value is T1) { @@ -604,8 +591,7 @@ public static TResult MapResult parsedFunc10, Func, TResult> notParsedFunc) { - var parsed = result as Parsed; - if (parsed != null) + if (result is Parsed parsed) { if (parsed.Value is T1) { @@ -695,8 +681,7 @@ public static TResult MapResult parsedFunc11, Func, TResult> notParsedFunc) { - var parsed = result as Parsed; - if (parsed != null) + if (result is Parsed parsed) { if (parsed.Value is T1) { @@ -793,8 +778,7 @@ public static TResult MapResult parsedFunc12, Func, TResult> notParsedFunc) { - var parsed = result as Parsed; - if (parsed != null) + if (result is Parsed parsed) { if (parsed.Value is T1) { @@ -898,8 +882,7 @@ public static TResult MapResult parsedFunc13, Func, TResult> notParsedFunc) { - var parsed = result as Parsed; - if (parsed != null) + if (result is Parsed parsed) { if (parsed.Value is T1) { @@ -1010,8 +993,7 @@ public static TResult MapResult parsedFunc14, Func, TResult> notParsedFunc) { - var parsed = result as Parsed; - if (parsed != null) + if (result is Parsed parsed) { if (parsed.Value is T1) { @@ -1129,8 +1111,7 @@ public static TResult MapResult parsedFunc15, Func, TResult> notParsedFunc) { - var parsed = result as Parsed; - if (parsed != null) + if (result is Parsed parsed) { if (parsed.Value is T1) { @@ -1255,8 +1236,7 @@ public static TResult MapResult parsedFunc16, Func, TResult> notParsedFunc) { - var parsed = result as Parsed; - if (parsed != null) + if (result is Parsed parsed) { if (parsed.Value is T1) { diff --git a/src/CommandLine/ParserSettings.cs b/src/CommandLine/ParserSettings.cs index 5ed73f30..e3594eb3 100644 --- a/src/CommandLine/ParserSettings.cs +++ b/src/CommandLine/ParserSettings.cs @@ -25,7 +25,6 @@ public class ParserSettings : IDisposable private bool autoVersion; private CultureInfo parsingCulture; private Maybe enableDashDash; - private int maximumDisplayWidth; private Maybe allowMultiInstance; private bool getoptMode; private Maybe posixlyCorrect; @@ -40,7 +39,7 @@ public ParserSettings() autoHelp = true; autoVersion = true; parsingCulture = CultureInfo.InvariantCulture; - maximumDisplayWidth = GetWindowWidth(); + MaximumDisplayWidth = GetWindowWidth(); getoptMode = false; enableDashDash = Maybe.Nothing(); allowMultiInstance = Maybe.Nothing(); @@ -78,24 +77,24 @@ private int GetWindowWidth() } /// - /// Gets or sets a value indicating whether perform case sensitive comparisons. + /// Gets or sets a value indicating whether perform case-sensitive comparisons. /// Note that case insensitivity only applies to parameters, not the values /// assigned to them (for example, enum parsing). /// public bool CaseSensitive { - get { return caseSensitive; } - set { PopsicleSetter.Set(Consumed, ref caseSensitive, value); } + get => caseSensitive; + set => PopsicleSetter.Set(Consumed, ref caseSensitive, value); } /// - /// Gets or sets a value indicating whether perform case sensitive comparisons of values. + /// Gets or sets a value indicating whether perform case-sensitive comparisons of values. /// Note that case insensitivity only applies to values, not the parameters. /// public bool CaseInsensitiveEnumValues { - get { return caseInsensitiveEnumValues; } - set { PopsicleSetter.Set(Consumed, ref caseInsensitiveEnumValues, value); } + get => caseInsensitiveEnumValues; + set => PopsicleSetter.Set(Consumed, ref caseInsensitiveEnumValues, value); } /// @@ -106,10 +105,10 @@ public bool CaseInsensitiveEnumValues /// public CultureInfo ParsingCulture { - get { return parsingCulture; } + get => parsingCulture; set { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw new ArgumentNullException(nameof(value)); PopsicleSetter.Set(Consumed, ref parsingCulture, value); } @@ -124,13 +123,13 @@ public CultureInfo ParsingCulture /// public TextWriter HelpWriter { - get { return helpWriter; } - set { PopsicleSetter.Set(Consumed, ref helpWriter, value); } + get => helpWriter; + set => PopsicleSetter.Set(Consumed, ref helpWriter, value); } /// /// Gets or sets a value indicating whether the parser shall move on to the next argument and ignore the given argument if it - /// encounter an unknown arguments + /// encounters an unknown arguments /// /// /// true to allow parsing the arguments with different class options that do not have all the arguments. @@ -141,8 +140,8 @@ public TextWriter HelpWriter /// public bool IgnoreUnknownArguments { - get { return ignoreUnknownArguments; } - set { PopsicleSetter.Set(Consumed, ref ignoreUnknownArguments, value); } + get => ignoreUnknownArguments; + set => PopsicleSetter.Set(Consumed, ref ignoreUnknownArguments, value); } /// @@ -150,8 +149,8 @@ public bool IgnoreUnknownArguments /// public bool AutoHelp { - get { return autoHelp; } - set { PopsicleSetter.Set(Consumed, ref autoHelp, value); } + get => autoHelp; + set => PopsicleSetter.Set(Consumed, ref autoHelp, value); } /// @@ -159,8 +158,8 @@ public bool AutoHelp /// public bool AutoVersion { - get { return autoVersion; } - set { PopsicleSetter.Set(Consumed, ref autoVersion, value); } + get => autoVersion; + set => PopsicleSetter.Set(Consumed, ref autoVersion, value); } /// @@ -177,11 +176,7 @@ public bool EnableDashDash /// /// Gets or sets the maximum width of the display. This determines word wrap when displaying the text. /// - public int MaximumDisplayWidth - { - get { return maximumDisplayWidth; } - set { maximumDisplayWidth = value; } - } + public int MaximumDisplayWidth { get; set; } /// /// Gets or sets a value indicating whether options are allowed to be specified multiple times. @@ -212,15 +207,10 @@ public bool PosixlyCorrect set => PopsicleSetter.Set(Consumed, ref posixlyCorrect, Maybe.Just(value)); } - internal StringComparer NameComparer - { - get - { - return CaseSensitive - ? StringComparer.Ordinal - : StringComparer.OrdinalIgnoreCase; - } - } + internal StringComparer NameComparer => + CaseSensitive + ? StringComparer.Ordinal + : StringComparer.OrdinalIgnoreCase; internal bool Consumed { get; set; } diff --git a/src/CommandLine/Text/CopyrightInfo.cs b/src/CommandLine/Text/CopyrightInfo.cs index c8bc3593..eb1ea23f 100644 --- a/src/CommandLine/Text/CopyrightInfo.cs +++ b/src/CommandLine/Text/CopyrightInfo.cs @@ -10,7 +10,7 @@ namespace CommandLine.Text { /// - /// Models the copyright part of an help text. + /// Models the copyright part of a help text. /// You can assign it where you assign any instance. /// public class CopyrightInfo @@ -27,13 +27,7 @@ public class CopyrightInfo /// /// An empty object used for initialization. /// - public static CopyrightInfo Empty - { - get - { - return new CopyrightInfo("author", DateTime.Now.Year); - } - } + public static CopyrightInfo Empty => new("author", DateTime.Now.Year); /// /// Initializes a new instance of the class @@ -71,8 +65,8 @@ public CopyrightInfo(string author, params int[] years) /// Thrown when parameter is not supplied. public CopyrightInfo(bool isSymbolUpper, string author, params int[] copyrightYears) { - if (string.IsNullOrWhiteSpace(author)) throw new ArgumentException("author"); - if (copyrightYears.Length == 0) throw new ArgumentOutOfRangeException("copyrightYears"); + if (string.IsNullOrWhiteSpace(author)) throw new ArgumentException(nameof(author)); + if (copyrightYears.Length == 0) throw new ArgumentOutOfRangeException(nameof(copyrightYears)); const int ExtraLength = 10; this.isSymbolUpper = isSymbolUpper; @@ -129,10 +123,7 @@ public static CopyrightInfo Default /// /// Gets a different copyright word when overridden in a derived class. /// - protected virtual string CopyrightWord - { - get { return DefaultCopyrightWord; } - } + protected virtual string CopyrightWord => DefaultCopyrightWord; /// /// Converts the copyright instance to a . diff --git a/src/CommandLine/Text/Example.cs b/src/CommandLine/Text/Example.cs index 4d73b754..2170f7e3 100644 --- a/src/CommandLine/Text/Example.cs +++ b/src/CommandLine/Text/Example.cs @@ -11,10 +11,6 @@ namespace CommandLine.Text /// public sealed class Example : IEquatable { - private readonly string helpText; - private readonly IEnumerable formatStyles; - private readonly object sample; - /// /// Initializes a new instance of the class. /// @@ -23,13 +19,11 @@ public sealed class Example : IEquatable /// A sample instance. public Example(string helpText, IEnumerable formatStyles, object sample) { - if (string.IsNullOrEmpty(helpText)) throw new ArgumentException("helpText can't be null or empty", "helpText"); - if (formatStyles == null) throw new ArgumentNullException("formatStyles"); - if (sample == null) throw new ArgumentNullException("sample"); + if (string.IsNullOrEmpty(helpText)) throw new ArgumentException("helpText can't be null or empty", nameof(helpText)); - this.helpText = helpText; - this.formatStyles = formatStyles; - this.sample = sample; + this.HelpText = helpText; + this.FormatStyles = formatStyles ?? throw new ArgumentNullException(nameof(formatStyles)); + this.Sample = sample ?? throw new ArgumentNullException(nameof(sample)); } /// @@ -56,26 +50,17 @@ public Example(string helpText, object sample) /// /// Example description. /// - public string HelpText - { - get { return helpText; } - } - + public string HelpText { get; } + /// /// A sequence of format styles. /// - public IEnumerable FormatStyles - { - get { return this.formatStyles; } - } + public IEnumerable FormatStyles { get; } /// /// A sample instance. /// - public object Sample - { - get { return sample; } - } + public object Sample { get; } /// /// Determines whether the specified is equal to the current . @@ -84,8 +69,7 @@ public object Sample /// true if the specified is equal to the current ; otherwise, false. public override bool Equals(object obj) { - var other = obj as Example; - if (other != null) + if (obj is Example other) { return Equals(other); } diff --git a/src/CommandLine/Text/HeadingInfo.cs b/src/CommandLine/Text/HeadingInfo.cs index 41e264f7..368ec84a 100644 --- a/src/CommandLine/Text/HeadingInfo.cs +++ b/src/CommandLine/Text/HeadingInfo.cs @@ -10,7 +10,7 @@ namespace CommandLine.Text { /// - /// Models the heading part of an help text. + /// Models the heading part of help text. /// You can assign it where you assign any instance. /// public class HeadingInfo @@ -27,7 +27,7 @@ public class HeadingInfo /// Thrown when parameter is null or empty string. public HeadingInfo(string programName, string version = null) { - if (string.IsNullOrWhiteSpace("programName")) throw new ArgumentException("programName"); + if (string.IsNullOrWhiteSpace("programName")) throw new ArgumentException(nameof(programName)); this.programName = programName; this.version = version; @@ -36,20 +36,14 @@ public HeadingInfo(string programName, string version = null) /// /// An empty object used for initialization. /// - public static HeadingInfo Empty - { - get - { - return new HeadingInfo(""); - } - } + public static HeadingInfo Empty => new(string.Empty); /// /// Gets the default heading instance. /// The title is retrieved from , - /// or the assembly short name if its not defined. + /// or the assembly short name if it's not defined. /// The version is retrieved from , - /// or the assembly version if its not defined. + /// or the assembly version if it's not defined. /// public static HeadingInfo Default { @@ -102,8 +96,8 @@ public override string ToString() /// Thrown when parameter is null. public void WriteMessage(string message, TextWriter writer) { - if (string.IsNullOrWhiteSpace("message")) throw new ArgumentException("message"); - if (writer == null) throw new ArgumentNullException("writer"); + if (string.IsNullOrWhiteSpace("message")) throw new ArgumentException(nameof(message)); + if (writer == null) throw new ArgumentNullException(nameof(writer)); writer.WriteLine( new StringBuilder(programName.Length + message.Length + 2) diff --git a/src/CommandLine/Text/HelpText.cs b/src/CommandLine/Text/HelpText.cs index f5e9a7b9..4dc7be09 100644 --- a/src/CommandLine/Text/HelpText.cs +++ b/src/CommandLine/Text/HelpText.cs @@ -16,12 +16,10 @@ namespace CommandLine.Text { /// - /// Provides means to format an help screen. + /// Provides means to format a help screen. /// You can assign it in place of a instance. /// - - public struct ComparableOption { public bool Required; @@ -101,17 +99,9 @@ ComparableOption ToComparableOption(Specification spec, int index) private const int TotalOptionPadding = OptionToHelpTextSeparatorWidth + OptionPrefixWidth; private readonly StringBuilder preOptionsHelp; private readonly StringBuilder postOptionsHelp; - private readonly SentenceBuilder sentenceBuilder; - private int maximumDisplayWidth; private string heading; private string copyright; - private bool additionalNewLineAfterOption; private StringBuilder optionsHelp; - private bool addDashesToOption; - private bool addEnumValuesToHelpText; - private bool autoHelp; - private bool autoVersion; - private bool addNewLineBetweenHelpSections; /// /// Initializes a new instance of the class. @@ -137,7 +127,7 @@ public HelpText(SentenceBuilder sentenceBuilder) /// Initializes a new instance of the class /// specifying heading string. /// - /// An heading string or an instance of . + /// A heading string or an instance of . /// Thrown when parameter is null or empty string. public HelpText(string heading) : this(SentenceBuilder.Create(), heading, string.Empty) @@ -177,29 +167,29 @@ public HelpText(string heading, string copyright) /// Thrown when one or more parameters are null or empty strings. public HelpText(SentenceBuilder sentenceBuilder, string heading, string copyright) { - if (sentenceBuilder == null) throw new ArgumentNullException("sentenceBuilder"); - if (heading == null) throw new ArgumentNullException("heading"); - if (copyright == null) throw new ArgumentNullException("copyright"); + if (sentenceBuilder == null) throw new ArgumentNullException(nameof(sentenceBuilder)); + if (heading == null) throw new ArgumentNullException(nameof(heading)); + if (copyright == null) throw new ArgumentNullException(nameof(copyright)); preOptionsHelp = new StringBuilder(BuilderCapacity); postOptionsHelp = new StringBuilder(BuilderCapacity); try { - maximumDisplayWidth = Console.WindowWidth; - if (maximumDisplayWidth < 1) + MaximumDisplayWidth = Console.WindowWidth; + if (MaximumDisplayWidth < 1) { - maximumDisplayWidth = DefaultMaximumLength; + MaximumDisplayWidth = DefaultMaximumLength; } } catch (IOException) { - maximumDisplayWidth = DefaultMaximumLength; + MaximumDisplayWidth = DefaultMaximumLength; } - this.sentenceBuilder = sentenceBuilder; + this.SentenceBuilder = sentenceBuilder; this.heading = heading; this.copyright = copyright; - this.autoHelp = true; - this.autoVersion = true; + this.AutoHelp = true; + this.AutoVersion = true; } /// @@ -208,13 +198,8 @@ public HelpText(SentenceBuilder sentenceBuilder, string heading, string copyrigh /// public string Heading { - get { return heading; } - set - { - if (value == null) throw new ArgumentNullException("value"); - - heading = value; - } + get => heading; + set => heading = value ?? throw new ArgumentNullException(nameof(value)); } /// @@ -223,87 +208,51 @@ public string Heading /// public string Copyright { - get { return copyright; } - set - { - if (value == null) throw new ArgumentNullException("value"); - - copyright = value; - } + get => copyright; + set => copyright = value ?? throw new ArgumentNullException(nameof(value)); } /// /// Gets or sets the maximum width of the display. This determines word wrap when displaying the text. /// /// The maximum width of the display. - public int MaximumDisplayWidth - { - get { return maximumDisplayWidth; } - set { maximumDisplayWidth = value; } - } + public int MaximumDisplayWidth { get; set; } /// /// Gets or sets a value indicating whether the format of options should contain dashes. /// It modifies behavior of method. /// - public bool AddDashesToOption - { - get { return addDashesToOption; } - set { addDashesToOption = value; } - } + public bool AddDashesToOption { get; set; } /// - /// Gets or sets a value indicating whether to add an additional line after the description of the specification. + /// Gets or sets a value indicating whether to add a line after the description of the specification. /// - public bool AdditionalNewLineAfterOption - { - get { return additionalNewLineAfterOption; } - set { additionalNewLineAfterOption = value; } - } + public bool AdditionalNewLineAfterOption { get; set; } /// /// Gets or sets a value indicating whether to add newlines between help sections. /// - public bool AddNewLineBetweenHelpSections - { - get { return addNewLineBetweenHelpSections; } - set { addNewLineBetweenHelpSections = value; } - } + public bool AddNewLineBetweenHelpSections { get; set; } /// /// Gets or sets a value indicating whether to add the values of an enum after the description of the specification. /// - public bool AddEnumValuesToHelpText - { - get { return addEnumValuesToHelpText; } - set { addEnumValuesToHelpText = value; } - } + public bool AddEnumValuesToHelpText { get; set; } /// /// Gets or sets a value indicating whether implicit option or verb 'help' should be supported. /// - public bool AutoHelp - { - get { return autoHelp; } - set { autoHelp = value; } - } + public bool AutoHelp { get; set; } /// /// Gets or sets a value indicating whether implicit option or verb 'version' should be supported. /// - public bool AutoVersion - { - get { return autoVersion; } - set { autoVersion = value; } - } + public bool AutoVersion { get; set; } /// /// Gets the instance specified in constructor. /// - public SentenceBuilder SentenceBuilder - { - get { return sentenceBuilder; } - } + public SentenceBuilder SentenceBuilder { get; } /// /// Creates a new instance of the class using common defaults. @@ -316,7 +265,7 @@ public SentenceBuilder SentenceBuilder /// A delegate used to customize model used to render text block of usage examples. /// If true the output style is consistent with verb commands (no dashes), otherwise it outputs options. /// The maximum width of the display. - /// The parameter is not ontly a metter of formatting, it controls whether to handle verbs or options. + /// The parameter is not only a matter of formatting, it controls whether to handle verbs or options. public static HelpText AutoBuild( ParserResult parserResult, Func onError, @@ -419,7 +368,7 @@ public static HelpText AutoBuild(ParserResult parserResult, int maxDisplay public static HelpText AutoBuild(ParserResult parserResult, Func onError, int maxDisplayWidth = DefaultMaximumLength) { if (parserResult.Tag != ParserResultType.NotParsed) - throw new ArgumentException("Excepting NotParsed type.", "parserResult"); + throw new ArgumentException("Excepting NotParsed type.", nameof(parserResult)); var errors = ((NotParsed)parserResult).Errors; @@ -455,8 +404,8 @@ public static HelpText AutoBuild(ParserResult parserResult, FuncThe instance. public static HelpText DefaultParsingErrorsHandler(ParserResult parserResult, HelpText current) { - if (parserResult == null) throw new ArgumentNullException("parserResult"); - if (current == null) throw new ArgumentNullException("current"); + if (parserResult == null) throw new ArgumentNullException(nameof(parserResult)); + if (current == null) throw new ArgumentNullException(nameof(current)); if (((NotParsed)parserResult).Errors.OnlyMeaningfulOnes().Empty()) return current; @@ -558,7 +507,7 @@ public HelpText AddPostOptionsText(string text) /// Thrown when parameter is null. public HelpText AddOptions(ParserResult result) { - if (result == null) throw new ArgumentNullException("result"); + if (result == null) throw new ArgumentNullException(nameof(result)); return AddOptionsImpl( GetSpecificationsFromType(result.TypeInfo.Current), @@ -575,8 +524,8 @@ public HelpText AddOptions(ParserResult result) /// Thrown if array is empty. public HelpText AddVerbs(params Type[] types) { - if (types == null) throw new ArgumentNullException("types"); - if (types.Length == 0) throw new ArgumentOutOfRangeException("types"); + if (types == null) throw new ArgumentNullException(nameof(types)); + if (types.Length == 0) throw new ArgumentOutOfRangeException(nameof(types)); return AddOptionsImpl( AdaptVerbsToSpecifications(types), @@ -593,7 +542,7 @@ public HelpText AddVerbs(params Type[] types) /// Thrown when parameter is null. public HelpText AddOptions(int maximumLength, ParserResult result) { - if (result == null) throw new ArgumentNullException("result"); + if (result == null) throw new ArgumentNullException(nameof(result)); return AddOptionsImpl( GetSpecificationsFromType(result.TypeInfo.Current), @@ -611,8 +560,8 @@ public HelpText AddOptions(int maximumLength, ParserResult result) /// Thrown if array is empty. public HelpText AddVerbs(int maximumLength, params Type[] types) { - if (types == null) throw new ArgumentNullException("types"); - if (types.Length == 0) throw new ArgumentOutOfRangeException("types"); + if (types == null) throw new ArgumentNullException(nameof(types)); + if (types.Length == 0) throw new ArgumentOutOfRangeException(nameof(types)); return AddOptionsImpl( AdaptVerbsToSpecifications(types), @@ -654,7 +603,7 @@ public static IEnumerable RenderParsingErrorsTextAsLines( Func, string> formatMutuallyExclusiveSetErrors, int indent) { - if (parserResult == null) throw new ArgumentNullException("parserResult"); + if (parserResult == null) throw new ArgumentNullException(nameof(parserResult)); var meaningfulErrors = ((NotParsed)parserResult).Errors.OnlyMeaningfulOnes(); @@ -713,7 +662,7 @@ public static string RenderUsageText(ParserResult parserResult, FuncResulting formatted text. public static IEnumerable RenderUsageTextAsLines(ParserResult parserResult, Func mapperFunc) { - if (parserResult == null) throw new ArgumentNullException("parserResult"); + if (parserResult == null) throw new ArgumentNullException(nameof(parserResult)); var usage = GetUsageFromType(parserResult.TypeInfo.Current); if (usage.MatchNothing()) @@ -819,9 +768,9 @@ private IEnumerable GetSpecificationsFromType(Type type) var specs = type.GetSpecifications(Specification.FromProperty); var optionSpecs = specs .OfType(); - if (autoHelp) + if (AutoHelp) optionSpecs = optionSpecs.Concat(new[] { MakeHelpEntry() }); - if (autoVersion) + if (AutoVersion) optionSpecs = optionSpecs.Concat(new[] { MakeVersionEntry() }); var valueSpecs = specs .OfType() @@ -857,9 +806,9 @@ private IEnumerable AdaptVerbsToSpecifications(IEnumerable verbTuple.Item1.IsDefault ? "(Default Verb) " + verbTuple.Item1.HelpText : verbTuple.Item1.HelpText, //Default verb string.Empty, verbTuple.Item1.Hidden); - if (autoHelp) + if (AutoHelp) optionSpecs = optionSpecs.Concat(new[] { MakeHelpEntry() }); - if (autoVersion) + if (AutoVersion) optionSpecs = optionSpecs.Concat(new[] { MakeVersionEntry() }); return optionSpecs; } @@ -912,7 +861,7 @@ private OptionSpecification MakeHelpEntry() string.Empty, "help", false, - sentenceBuilder.HelpCommandText(AddDashesToOption), + SentenceBuilder.HelpCommandText(AddDashesToOption), string.Empty, false); } @@ -923,7 +872,7 @@ private OptionSpecification MakeVersionEntry() string.Empty, "version", false, - sentenceBuilder.VersionCommandText(AddDashesToOption), + SentenceBuilder.VersionCommandText(AddDashesToOption), string.Empty, false); } @@ -968,7 +917,7 @@ specification is OptionSpecification optionSpecification && var optionHelpText = specification.HelpText; - if (addEnumValuesToHelpText && specification.EnumValues.Any()) + if (AddEnumValuesToHelpText && specification.EnumValues.Any()) optionHelpText += " Valid values: " + string.Join(", ", specification.EnumValues); specification.DefaultValue.Do( @@ -991,7 +940,7 @@ specification is OptionSpecification optionSpecification && optionsHelp .Append(indented) .Append(Environment.NewLine) - .AppendWhen(additionalNewLineAfterOption, Environment.NewLine); + .AppendWhen(AdditionalNewLineAfterOption, Environment.NewLine); return this; } @@ -1003,14 +952,14 @@ private string AddOptionName(int maxLength, OptionSpecification specification) .MapIf( specification.ShortName.Length > 0, it => it - .AppendWhen(addDashesToOption, '-') + .AppendWhen(AddDashesToOption, '-') .AppendFormat("{0}", specification.ShortName) .AppendFormatWhen(specification.MetaValue.Length > 0, " {0}", specification.MetaValue) .AppendWhen(specification.LongName.Length > 0, ", ")) .MapIf( specification.LongName.Length > 0, it => it - .AppendWhen(addDashesToOption, "--") + .AppendWhen(AddDashesToOption, "--") .AppendFormat("{0}", specification.LongName) .AppendFormatWhen(specification.MetaValue.Length > 0, "={0}", specification.MetaValue)) .ToString(); diff --git a/src/CommandLine/Text/MultiLineTextAttribute.cs b/src/CommandLine/Text/MultiLineTextAttribute.cs index 039655df..3ee7eab3 100644 --- a/src/CommandLine/Text/MultiLineTextAttribute.cs +++ b/src/CommandLine/Text/MultiLineTextAttribute.cs @@ -74,17 +74,11 @@ protected MultilineTextAttribute(string line1, string line2, string line3, strin /// The fifth line of text. protected MultilineTextAttribute(string line1, string line2, string line3, string line4, string line5) { - if (line1 == null) throw new ArgumentException("line1"); - if (line2 == null) throw new ArgumentException("line2"); - if (line3 == null) throw new ArgumentException("line3"); - if (line4 == null) throw new ArgumentException("line4"); - if (line5 == null) throw new ArgumentException("line5"); - - this.line1 = line1; - this.line2 = line2; - this.line3 = line3; - this.line4 = line4; - this.line5 = line5; + this.line1 = line1 ?? throw new ArgumentException(nameof(line1)); + this.line2 = line2 ?? throw new ArgumentException(nameof(line2)); + this.line3 = line3 ?? throw new ArgumentException(nameof(line3)); + this.line4 = line4 ?? throw new ArgumentException(nameof(line4)); + this.line5 = line5 ?? throw new ArgumentException(nameof(line5)); } /// @@ -110,42 +104,27 @@ public virtual string Value /// /// Gets the first line of text. /// - public string Line1 - { - get { return line1; } - } + public string Line1 => line1; /// /// Gets the second line of text. /// - public string Line2 - { - get { return line2; } - } + public string Line2 => line2; /// /// Gets third line of text. /// - public string Line3 - { - get { return line3; } - } + public string Line3 => line3; /// /// Gets the fourth line of text. /// - public string Line4 - { - get { return line4; } - } + public string Line4 => line4; /// /// Gets the fifth line of text. /// - public string Line5 - { - get { return line5; } - } + public string Line5 => line5; internal HelpText AddToHelpText(HelpText helpText, Func func) { @@ -176,4 +155,4 @@ protected virtual int GetLastLineWithText(string[] value) return index + 1; } } -} \ No newline at end of file +} diff --git a/src/CommandLine/Text/SentenceBuilder.cs b/src/CommandLine/Text/SentenceBuilder.cs index 842ae675..0a638180 100644 --- a/src/CommandLine/Text/SentenceBuilder.cs +++ b/src/CommandLine/Text/SentenceBuilder.cs @@ -56,7 +56,7 @@ public static SentenceBuilder Create() public abstract Func HelpCommandText { get; } /// - /// Get a delegate that returns the help text of vesion command. + /// Get a delegate that returns the help text of version command. /// The delegates must accept a boolean that is equal true for options; otherwise false for verbs. /// public abstract Func VersionCommandText { get; } @@ -126,10 +126,10 @@ public override Func FormatError case ErrorType.UnknownOptionError: return "Option '".JoinTo(((UnknownOptionError)error).Token, "' is unknown."); case ErrorType.MissingRequiredOptionError: - var errMisssing = ((MissingRequiredOptionError)error); - return errMisssing.NameInfo.Equals(NameInfo.EmptyName) + var errMissing = ((MissingRequiredOptionError)error); + return errMissing.NameInfo.Equals(NameInfo.EmptyName) ? "A required value not bound to option name is missing." - : "Required option '".JoinTo(errMisssing.NameInfo.NameText, "' is missing."); + : "Required option '".JoinTo(errMissing.NameInfo.NameText, "' is missing."); case ErrorType.BadFormatConversionError: var badFormat = ((BadFormatConversionError)error); return badFormat.NameInfo.Equals(NameInfo.EmptyName) @@ -199,11 +199,11 @@ group e by e.SetName into g new StringBuilder("Option") .AppendWhen(namesCount > 1, "s") .Append(": ") - .Append(names.Substring(0, names.Length - 2)) + .Append(names[..^2]) .Append(' ') .AppendIf(namesCount > 1, "are", "is") .Append(" not compatible with: ") - .Append(incompat.Substring(0, incompat.Length - 2)) + .Append(incompat[..^2]) .Append('.') .ToString(); }).ToArray(); diff --git a/src/CommandLine/Text/TextWrapper.cs b/src/CommandLine/Text/TextWrapper.cs index 19a93f15..0a3bd01a 100644 --- a/src/CommandLine/Text/TextWrapper.cs +++ b/src/CommandLine/Text/TextWrapper.cs @@ -123,7 +123,7 @@ private string [] WordWrapLine(string line,int columnWidth) /// The same list as is passed in private static List AddWordToLastLineOrCreateNewLineIfNecessary(List lines, string word,int columnWidth) { - //The current indentation level is based on the previous line but we need to be careful + //The current indentation level is based on the previous line, but we need to be careful var previousLine = lines.LastOrDefault()?.ToString() ??string.Empty; var wouldWrap = !lines.Any() || (word.Length>0 && previousLine.Length + word.Length > columnWidth); @@ -163,7 +163,7 @@ private static string RightString(string str,int n) { return (n >= str.Length || str.Length==0) ? string.Empty - : str.Substring(n); + : str[n..]; } /// /// Return the left part of a string in a way that compensates for Substring's deficiencies @@ -173,7 +173,7 @@ private static string LeftString(string str,int n) return (n >= str.Length || str.Length==0) ? str - : str.Substring(0,n); + : str[..n]; } } } diff --git a/src/CommandLine/UnParserExtensions.cs b/src/CommandLine/UnParserExtensions.cs index e823a7fa..1c09fff2 100644 --- a/src/CommandLine/UnParserExtensions.cs +++ b/src/CommandLine/UnParserExtensions.cs @@ -2,7 +2,6 @@ using System; using System.Collections; -using System.Collections.Generic; using System.Linq; using System.Text; using CommandLine.Core; @@ -27,8 +26,8 @@ public class UnParserSettings /// public bool PreferShortName { - get { return preferShortName; } - set { PopsicleSetter.Set(Consumed, ref preferShortName, value); } + get => preferShortName; + set => PopsicleSetter.Set(Consumed, ref preferShortName, value); } /// @@ -36,8 +35,8 @@ public bool PreferShortName /// public bool GroupSwitches { - get { return groupSwitches; } - set { PopsicleSetter.Set(Consumed, ref groupSwitches, value); } + get => groupSwitches; + set => PopsicleSetter.Set(Consumed, ref groupSwitches, value); } /// @@ -45,8 +44,8 @@ public bool GroupSwitches /// public bool UseEqualToken { - get { return useEqualToken; } - set { PopsicleSetter.Set(Consumed, ref useEqualToken, value); } + get => useEqualToken; + set => PopsicleSetter.Set(Consumed, ref useEqualToken, value); } /// @@ -54,21 +53,21 @@ public bool UseEqualToken /// public bool ShowHidden { - get { return showHidden; } - set { PopsicleSetter.Set(Consumed, ref showHidden, value); } + get => showHidden; + set => PopsicleSetter.Set(Consumed, ref showHidden, value); } /// /// Gets or sets a value indicating whether unparsing process shall skip options with DefaultValue. /// public bool SkipDefault { - get { return skipDefault; } - set { PopsicleSetter.Set(Consumed, ref skipDefault, value); } + get => skipDefault; + set => PopsicleSetter.Set(Consumed, ref skipDefault, value); } /// /// Factory method that creates an instance of with GroupSwitches set to true. /// - /// A properly initalized instance. + /// A properly initialized instance. public static UnParserSettings WithGroupSwitchesOnly() { return new UnParserSettings { GroupSwitches = true }; @@ -77,7 +76,7 @@ public static UnParserSettings WithGroupSwitchesOnly() /// /// Factory method that creates an instance of with UseEqualToken set to true. /// - /// A properly initalized instance. + /// A properly initialized instance. public static UnParserSettings WithUseEqualTokenOnly() { return new UnParserSettings { UseEqualToken = true }; @@ -122,11 +121,11 @@ public static string[] FormatCommandLineArgs(this Parser parser, T options) /// Parser instance. /// A parsed (or manually correctly constructed instance). /// The lambda used to configure - /// aspects and behaviors of the unparsersing process. + /// aspects and behaviors of the unparser-ing process. /// A string with command line arguments. public static string FormatCommandLine(this Parser parser, T options, Action configuration) { - if (options == null) throw new ArgumentNullException("options"); + if (options == null) throw new ArgumentNullException(nameof(options)); var settings = new UnParserSettings(); configuration(settings); @@ -207,7 +206,7 @@ orderby v.Index /// Parser instance. /// A parsed (or manually correctly constructed instance). /// The lambda used to configure - /// aspects and behaviors of the unparsersing process. + /// aspects and behaviors of the unparser-ing process. /// A string[] with command line arguments. public static string[] FormatCommandLineArgs(this Parser parser, T options, Action configuration) { @@ -222,7 +221,7 @@ private static string FormatValue(Specification spec, object value) builder.Append(FormatWithQuotesIfString(value)); break; case TargetType.Sequence: - var sep = spec.SeperatorOrSpace(); + var sep = spec.SeparatorOrSpace(); Func format = v => sep == ' ' ? FormatWithQuotesIfString(v) : v; var e = ((IEnumerable)value).GetEnumerator(); @@ -248,7 +247,7 @@ private static object FormatWithQuotesIfString(object value) ? "\"".JoinTo(doubQt(v), "\"") : v, value); } - private static char SeperatorOrSpace(this Specification spec) + private static char SeparatorOrSpace(this Specification spec) { return (spec as OptionSpecification).ToMaybe() .MapValueOrDefault(o => o.Separator != '\0' ? o.Separator : ' ', ' '); @@ -280,14 +279,6 @@ private static string FormatName(this OptionSpecification optionSpec, object val private static object NormalizeValue(this object value) { -#if !SKIP_FSHARP - if (value != null - && ReflectionHelper.IsFSharpOptionType(value.GetType()) - && FSharpOptionHelper.IsSome(value)) - { - return FSharpOptionHelper.ValueOf(value); - } -#endif return value; } @@ -298,9 +289,6 @@ private static bool IsEmpty(this object value, Specification specification, bool if (skipDefault && value.Equals(specification.DefaultValue.FromJust())) return true; if (Nullable.GetUnderlyingType(specification.ConversionType) != null) return false; //nullable -#if !SKIP_FSHARP - if (ReflectionHelper.IsFSharpOptionType(value.GetType()) && !FSharpOptionHelper.IsSome(value)) return true; -#endif if (value is ValueType && value.Equals(value.GetType().GetDefaultValue())) return true; if (value is string && ((string)value).Length == 0) return true; if (value is IEnumerable && !((IEnumerable)value).GetEnumerator().MoveNext()) return true; diff --git a/src/CommandLine/ValueAttribute.cs b/src/CommandLine/ValueAttribute.cs index ba2c0ef9..21dd0f5f 100644 --- a/src/CommandLine/ValueAttribute.cs +++ b/src/CommandLine/ValueAttribute.cs @@ -5,12 +5,11 @@ namespace CommandLine { /// - /// Models an value specification, or better how to handle values not bound to options. + /// Models a value specification, or better how to handle values not bound to options. /// [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] - public sealed class ValueAttribute : BaseAttribute + public /*sealed*/ class ValueAttribute : BaseAttribute { - private readonly int index; private string metaName; /// @@ -18,28 +17,22 @@ public sealed class ValueAttribute : BaseAttribute /// public ValueAttribute(int index) : base() { - this.index = index; + this.Index = index; this.metaName = string.Empty; } /// /// Gets the position this option has on the command line. /// - public int Index - { - get { return index; } - } + public int Index { get; } /// /// Gets or sets name of this positional value specification. /// public string MetaName { - get { return metaName; } - set - { - metaName = value ?? throw new ArgumentNullException("value"); - } + get => metaName; + set => metaName = value ?? throw new ArgumentNullException(nameof(value)); } } -} \ No newline at end of file +} diff --git a/src/CommandLine/VerbAttribute.cs b/src/CommandLine/VerbAttribute.cs index 6ee6024d..51089309 100644 --- a/src/CommandLine/VerbAttribute.cs +++ b/src/CommandLine/VerbAttribute.cs @@ -1,7 +1,6 @@ // Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information. using System; -using System.Collections.Generic; namespace CommandLine { @@ -53,7 +52,7 @@ public bool Hidden public string HelpText { get => helpText.Value ?? string.Empty; - set => helpText.Value = value ?? throw new ArgumentNullException("value"); + set => helpText.Value = value ?? throw new ArgumentNullException(nameof(value)); } /// /// Gets or sets the that contains the resources for . diff --git a/tests/CommandLine.Tests/CommandLine.Tests.csproj b/tests/CommandLine.Tests/CommandLine.Tests.csproj index d4dbcab0..e53af03a 100644 --- a/tests/CommandLine.Tests/CommandLine.Tests.csproj +++ b/tests/CommandLine.Tests/CommandLine.Tests.csproj @@ -2,21 +2,16 @@ Library - net461;netcoreapp3.1 - $(DefineConstants);SKIP_FSHARP + net8.0 ..\..\CommandLine.snk true - gsscoder;nemec;ericnewton76 + gsscoder;nemec;ericnewton76;SJFriedl Command Line Parser Library $(VersionSuffix) 2.5.0 Copyright (c) 2005 - 2018 Giacomo Stelluti Scala & Contributors true - - - - $(DefineConstants);PLATFORM_DOTNET @@ -26,13 +21,15 @@ - - + + + + - \ No newline at end of file + diff --git a/tests/CommandLine.Tests/Fakes/CustomAttribute.cs b/tests/CommandLine.Tests/Fakes/CustomAttribute.cs index 845fb2dd..72f44a0d 100644 --- a/tests/CommandLine.Tests/Fakes/CustomAttribute.cs +++ b/tests/CommandLine.Tests/Fakes/CustomAttribute.cs @@ -1,4 +1,5 @@ using System; +// ReSharper disable once CheckNamespace [AttributeUsage(AttributeTargets.All)] -class CustomAttribute: Attribute {} \ No newline at end of file +class CustomAttribute: Attribute {} diff --git a/tests/CommandLine.Tests/Fakes/HelpTextWithLineBreaks_Options.cs b/tests/CommandLine.Tests/Fakes/HelpTextWithLineBreaks_Options.cs index b8974ca7..6bdd1baa 100644 --- a/tests/CommandLine.Tests/Fakes/HelpTextWithLineBreaks_Options.cs +++ b/tests/CommandLine.Tests/Fakes/HelpTextWithLineBreaks_Options.cs @@ -2,7 +2,7 @@ { public class HelpTextWithLineBreaks_Options { - [Option(HelpText = + [Option(HelpText = @"This is a help text description. It has multiple lines. We also want to ensure that indentation is correct.")] @@ -12,12 +12,12 @@ It has multiple lines. [Option(HelpText = @"This is a help text description where we want the left pad after a linebreak to be honoured so that we can sub-indent within a description.")] - public string StringValu2 { get; set; } + public string StringValue2 { get; set; } [Option(HelpText = @"This is a help text description where we want The left pad after a linebreak to be honoured and the indentation to be preserved across to the next line in a way that looks pleasing")] - public string StringValu3 { get; set; } + public string StringValue3 { get; set; } } } diff --git a/tests/CommandLine.Tests/Fakes/HelpTextWithMixedLineBreaks_Options.cs b/tests/CommandLine.Tests/Fakes/HelpTextWithMixedLineBreaks_Options.cs index 9950dbc7..39cbd091 100644 --- a/tests/CommandLine.Tests/Fakes/HelpTextWithMixedLineBreaks_Options.cs +++ b/tests/CommandLine.Tests/Fakes/HelpTextWithMixedLineBreaks_Options.cs @@ -2,7 +2,7 @@ { public class HelpTextWithMixedLineBreaks_Options { - [Option(HelpText = + [Option(HelpText = "This is a help text description\n It has multiple lines.\r\n Third line")] public string StringValue { get; set; } } diff --git a/tests/CommandLine.Tests/Fakes/Immutable_Simple_Options.cs b/tests/CommandLine.Tests/Fakes/Immutable_Simple_Options.cs index ae829e7d..7df0f29d 100644 --- a/tests/CommandLine.Tests/Fakes/Immutable_Simple_Options.cs +++ b/tests/CommandLine.Tests/Fakes/Immutable_Simple_Options.cs @@ -20,18 +20,18 @@ public Immutable_Simple_Options(string stringValue, IEnumerable intSequence } [Option(HelpText = "Define a string value here.")] - public string StringValue { get { return stringValue; } } + public string StringValue => stringValue; [Option('i', Min = 3, Max = 4, HelpText = "Define a int sequence here.")] - public IEnumerable IntSequence { get { return intSequence; } } + public IEnumerable IntSequence => intSequence; [Option('x', HelpText = "Define a boolean or switch value here.")] - public bool BoolValue { get { return boolValue; } } + public bool BoolValue => boolValue; [Value(0)] - public long LongValue { get { return longValue; } } + public long LongValue => longValue; } - + public class Immutable_Simple_Options_Invalid_Ctor_Args { private readonly string stringValue; diff --git a/tests/CommandLine.Tests/Fakes/Immutable_Verb_Fakes.cs b/tests/CommandLine.Tests/Fakes/Immutable_Verb_Fakes.cs index 5e8f8993..b01c0332 100644 --- a/tests/CommandLine.Tests/Fakes/Immutable_Verb_Fakes.cs +++ b/tests/CommandLine.Tests/Fakes/Immutable_Verb_Fakes.cs @@ -7,72 +7,61 @@ namespace CommandLine.Tests.Fakes [Verb("add", HelpText = "Add file contents to the index.")] class Immutable_Add_Verb { - private readonly bool patch; - private readonly bool force; - private readonly string fileName; - public Immutable_Add_Verb(bool patch, bool force, string fileName) { - this.patch = patch; - this.force = force; - this.fileName = fileName; + Patch = patch; + Force = force; + FileName = fileName; } [Option('p', "patch", SetName = "mode", HelpText = "Interactively choose hunks of patch between the index and the work tree and add them to the index.")] - public bool Patch { get { return patch; } } + public bool Patch { get; } [Option('f', "force", SetName = "mode", HelpText = "Allow adding otherwise ignored files.")] - public bool Force { get { return force; } } + public bool Force { get; } [Value(0)] - public string FileName { get { return fileName; } } + public string FileName { get; } } [Verb("commit", HelpText = "Record changes to the repository.")] class Immutable_Commit_Verb { - private readonly bool patch; - private readonly bool amend; - public Immutable_Commit_Verb(bool patch, bool amend) { - this.patch = patch; - this.amend = amend; + Patch = patch; + Amend = amend; } [Option('p', "patch", HelpText = "Use the interactive patch selection interface to chose which changes to commit.")] - public bool Patch { get { return patch; } } + public bool Patch { get; } [Option("amend", HelpText = "Used to amend the tip of the current branch.")] - public bool Amend { get { return amend; } } + public bool Amend { get; } } [Verb("clone", HelpText = "Clone a repository into a new directory.")] class Immutable_Clone_Verb { - private readonly bool noHardLinks; - private readonly bool quiet; - private readonly IEnumerable urls; - public Immutable_Clone_Verb(bool noHardLinks, bool quiet, IEnumerable urls) { - this.noHardLinks = noHardLinks; - this.quiet = quiet; - this.urls = urls; + NoHardLinks = noHardLinks; + Quiet = quiet; + Urls = urls; } [Option("no-hardlinks", HelpText = "Optimize the cloning process from a repository on a local filesystem by copying files.")] - public bool NoHardLinks { get { return noHardLinks; } } + public bool NoHardLinks { get; } [Option('q', "quiet", HelpText = "Suppress summary message.")] - public bool Quiet { get { return quiet; } } + public bool Quiet { get; } [Value(0)] - public IEnumerable Urls { get { return urls; } } + public IEnumerable Urls { get; } } -} \ No newline at end of file +} diff --git a/tests/CommandLine.Tests/Fakes/Mutable_Without_Empty_Constructor.cs b/tests/CommandLine.Tests/Fakes/Mutable_Without_Empty_Constructor.cs index 6f311bb1..80285d8b 100644 --- a/tests/CommandLine.Tests/Fakes/Mutable_Without_Empty_Constructor.cs +++ b/tests/CommandLine.Tests/Fakes/Mutable_Without_Empty_Constructor.cs @@ -1,17 +1,17 @@ // Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information. -namespace CommandLine.Tests.Fakes +namespace CommandLine.Tests.Fakes { - class Mutable_Without_Empty_Constructor + class Mutable_Without_Empty_Constructor { [Option("amend", HelpText = "Used to amend the tip of the current branch.")] public bool Amend { get; set; } - private Mutable_Without_Empty_Constructor() + private Mutable_Without_Empty_Constructor() { } - public static Mutable_Without_Empty_Constructor Create() + public static Mutable_Without_Empty_Constructor Create() { return new Mutable_Without_Empty_Constructor(); } diff --git a/tests/CommandLine.Tests/Fakes/Options_HelpText_Ordering.cs b/tests/CommandLine.Tests/Fakes/Options_HelpText_Ordering.cs index 27c7fa6b..8d98bafa 100644 --- a/tests/CommandLine.Tests/Fakes/Options_HelpText_Ordering.cs +++ b/tests/CommandLine.Tests/Fakes/Options_HelpText_Ordering.cs @@ -2,7 +2,7 @@ namespace CommandLine.Tests.Fakes { - + [Verb("verb1")] class Options_HelpText_Ordering_Verb1 { diff --git a/tests/CommandLine.Tests/Fakes/Options_With_FSharpOption.cs b/tests/CommandLine.Tests/Fakes/Options_With_FSharpOption.cs deleted file mode 100644 index 0bc67b08..00000000 --- a/tests/CommandLine.Tests/Fakes/Options_With_FSharpOption.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information. - -using Microsoft.FSharp.Core; - -namespace CommandLine.Tests.Fakes -{ - public class Options_With_FSharpOption - { - [Option] - public FSharpOption FileName { get; set; } - - [Value(0)] - public FSharpOption Offset { get; set; } - } -} \ No newline at end of file diff --git a/tests/CommandLine.Tests/Fakes/Options_With_Property_Throwing_Exception.cs b/tests/CommandLine.Tests/Fakes/Options_With_Property_Throwing_Exception.cs index 031dcb6c..de24000f 100644 --- a/tests/CommandLine.Tests/Fakes/Options_With_Property_Throwing_Exception.cs +++ b/tests/CommandLine.Tests/Fakes/Options_With_Property_Throwing_Exception.cs @@ -13,10 +13,7 @@ class Options_With_Property_Throwing_Exception [Option('e')] public string OptValue { - get - { - return optValue; - } + get => optValue; set { if (value != "good") diff --git a/tests/CommandLine.Tests/Fakes/Options_With_Sequence.cs b/tests/CommandLine.Tests/Fakes/Options_With_Sequence.cs index 78de940e..ced75d92 100644 --- a/tests/CommandLine.Tests/Fakes/Options_With_Sequence.cs +++ b/tests/CommandLine.Tests/Fakes/Options_With_Sequence.cs @@ -10,6 +10,6 @@ class Options_With_Sequence public IEnumerable IntSequence { get; set; } //[Option("string-seq")] - //public IEnumerable StringSequence { get; set; } + //public IEnumerable StringSequence { get; set; } } } diff --git a/tests/CommandLine.Tests/Fakes/Options_With_Sequence_Having_Separator_And_Values.cs b/tests/CommandLine.Tests/Fakes/Options_With_Sequence_Having_Separator_And_Values.cs index 6099b5b5..552982c2 100644 --- a/tests/CommandLine.Tests/Fakes/Options_With_Sequence_Having_Separator_And_Values.cs +++ b/tests/CommandLine.Tests/Fakes/Options_With_Sequence_Having_Separator_And_Values.cs @@ -35,7 +35,7 @@ public class Options_For_Issue_510 [Option('b', "bb", Required = false)] public string B { get; set; } - + [Value(0, Required = true)] public string C { get; set; } } @@ -44,12 +44,12 @@ public enum FMode { C, D, S }; public class Options_For_Issue_617 { - [Option("fm", Separator=',', Default = new[] { FMode.S })] + [Option("fm", Separator=',', Default = new[] { FMode.S })] public IEnumerable Mode { get; set; } - + [Option('q')] public bool q { get;set; } - + [Value(0)] public IList Files { get; set; } } diff --git a/tests/CommandLine.Tests/Fakes/Options_With_Sequence_Having_Separator_Set.cs b/tests/CommandLine.Tests/Fakes/Options_With_Sequence_Having_Separator_Set.cs index 1729786e..2728aff4 100644 --- a/tests/CommandLine.Tests/Fakes/Options_With_Sequence_Having_Separator_Set.cs +++ b/tests/CommandLine.Tests/Fakes/Options_With_Sequence_Having_Separator_Set.cs @@ -10,6 +10,6 @@ class Options_With_Sequence_Having_Separator_Set public IEnumerable LongSequence { get; set; } [Option('s', Min = 1, Max = 100, Separator = ',')] - public IEnumerable StringSequence { get; set; } + public IEnumerable StringSequence { get; set; } } } diff --git a/tests/CommandLine.Tests/Fakes/Options_With_Sequence_Without_Range_For_Value.cs b/tests/CommandLine.Tests/Fakes/Options_With_Sequence_Without_Range_For_Value.cs index 9071d8a7..4635b2df 100644 --- a/tests/CommandLine.Tests/Fakes/Options_With_Sequence_Without_Range_For_Value.cs +++ b/tests/CommandLine.Tests/Fakes/Options_With_Sequence_Without_Range_For_Value.cs @@ -7,6 +7,6 @@ namespace CommandLine.Tests.Fakes class Options_With_Sequence_Without_Range_For_Value { [Value(0)] - public IEnumerable LongSequence { get; set; } + public IEnumerable LongSequence { get; set; } } } diff --git a/tests/CommandLine.Tests/Fakes/Options_With_Uri_And_SimpleType.cs b/tests/CommandLine.Tests/Fakes/Options_With_Uri_And_SimpleType.cs index f2eedaf1..d0409e23 100644 --- a/tests/CommandLine.Tests/Fakes/Options_With_Uri_And_SimpleType.cs +++ b/tests/CommandLine.Tests/Fakes/Options_With_Uri_And_SimpleType.cs @@ -15,10 +15,7 @@ public MySimpleType(string value) this.value = value; } - public string Value - { - get { return value; } - } + public string Value => value; } class Options_With_Uri_And_SimpleType diff --git a/tests/CommandLine.Tests/Fakes/Options_With_Value_Sequence_And_Normal_Option.cs b/tests/CommandLine.Tests/Fakes/Options_With_Value_Sequence_And_Normal_Option.cs index e8e7bf47..5cd4237e 100644 --- a/tests/CommandLine.Tests/Fakes/Options_With_Value_Sequence_And_Normal_Option.cs +++ b/tests/CommandLine.Tests/Fakes/Options_With_Value_Sequence_And_Normal_Option.cs @@ -4,10 +4,10 @@ namespace CommandLine.Tests.Fakes { public class Options_With_Value_Sequence_And_Normal_Option - { + { [Option('c', "compress", HelpText = "Compress Match Pattern, Pipe Separated (|) ", - Separator = '|', + Separator = '|', Default = new[] { "*.txt", "*.log", "*.ini" @@ -15,7 +15,7 @@ public class Options_With_Value_Sequence_And_Normal_Option public IEnumerable Compress { get; set; } [Value(0, - HelpText = "Input Directories.", + HelpText = "Input Directories.", Required = true)] public IEnumerable InputDirs { get; set; } diff --git a/tests/CommandLine.Tests/Fakes/ResourceFakes.cs b/tests/CommandLine.Tests/Fakes/ResourceFakes.cs index 1b18da6e..3b882d3b 100644 --- a/tests/CommandLine.Tests/Fakes/ResourceFakes.cs +++ b/tests/CommandLine.Tests/Fakes/ResourceFakes.cs @@ -2,7 +2,7 @@ { public static class StaticResource { - public static string HelpText { get { return "Localized HelpText"; } } + public static string HelpText => "Localized HelpText"; public static TypeWithImplicitCast ImplicitCastHelpText => new TypeWithImplicitCast("Localized HelpText"); public static TypeWithExplicitCast ExplicitCastHelpText => new TypeWithExplicitCast("Localized HelpText"); public static TypeWithWrongImplicitCast WrongImplicitCastHelpText => new TypeWithWrongImplicitCast(); @@ -11,9 +11,9 @@ public static class StaticResource public class NonStaticResource { - public static string HelpText { get { return "Localized HelpText"; } } - public static string WriteOnlyText { set { value?.ToString(); } } - private static string PrivateHelpText { get { return "Localized HelpText"; } } + public static string HelpText => "Localized HelpText"; + public static string WriteOnlyText { set => value?.ToString(); } + private static string PrivateHelpText => "Localized HelpText"; public static TypeWithImplicitCast ImplicitCastHelpText => new TypeWithImplicitCast("Localized HelpText"); public static TypeWithExplicitCast ExplicitCastHelpText => new TypeWithExplicitCast("Localized HelpText"); public static TypeWithWrongImplicitCast WrongImplicitCastHelpText => new TypeWithWrongImplicitCast(); @@ -22,12 +22,12 @@ public class NonStaticResource public class NonStaticResource_WithNonStaticProperty { - public string HelpText { get { return "Localized HelpText"; } } + public string HelpText => "Localized HelpText"; } internal class InternalResource { - public static string HelpText { get { return "Localized HelpText"; } } + public static string HelpText => "Localized HelpText"; } public class TypeWithImplicitCast diff --git a/tests/CommandLine.Tests/Unit/Core/GetoptTokenizerTests.cs b/tests/CommandLine.Tests/Unit/Core/GetoptTokenizerTests.cs index 337a9a3f..1349d624 100644 --- a/tests/CommandLine.Tests/Unit/Core/GetoptTokenizerTests.cs +++ b/tests/CommandLine.Tests/Unit/Core/GetoptTokenizerTests.cs @@ -22,7 +22,7 @@ public void Explode_scalar_with_separator_in_odd_args_input_returns_sequence() var specs = new[] { new OptionSpecification(string.Empty, "string-seq", false, string.Empty, Maybe.Nothing(), Maybe.Nothing(), ',', null, string.Empty, string.Empty, new List(), typeof(IEnumerable), TargetType.Sequence, string.Empty)}; - // Exercize system + // Exercise system var result = GetoptTokenizer.ExplodeOptionList( Result.Succeed( @@ -45,7 +45,7 @@ public void Explode_scalar_with_separator_in_even_args_input_returns_sequence() var specs = new[] { new OptionSpecification(string.Empty, "string-seq", false, string.Empty, Maybe.Nothing(), Maybe.Nothing(), ',', null, string.Empty, string.Empty, new List(), typeof(IEnumerable), TargetType.Sequence, string.Empty)}; - // Exercize system + // Exercise system var result = GetoptTokenizer.ExplodeOptionList( Result.Succeed( @@ -63,7 +63,7 @@ public void Explode_scalar_with_separator_in_even_args_input_returns_sequence() [Fact] public void Should_properly_parse_option_with_equals_in_value() { - /** + /* * This is how the arg. would look in `static void Main(string[] args)` * if passed from the command-line and the option-value wrapped in quotes. * Ex.) ./app --connectionString="Server=localhost;Data Source..." @@ -90,7 +90,7 @@ public void Should_return_error_if_option_format_with_equals_is_not_correct() var errors = result.SuccessMessages(); Assert.NotNull(errors); - Assert.Equal(1, errors.Count()); + Assert.Single(errors); Assert.Equal(ErrorType.BadFormatTokenError, errors.First().Tag); var tokens = result.SucceededWith(); diff --git a/tests/CommandLine.Tests/Unit/Core/InstanceBuilderTests.cs b/tests/CommandLine.Tests/Unit/Core/InstanceBuilderTests.cs index 2f8d02b7..94c4c876 100644 --- a/tests/CommandLine.Tests/Unit/Core/InstanceBuilderTests.cs +++ b/tests/CommandLine.Tests/Unit/Core/InstanceBuilderTests.cs @@ -1,6 +1,5 @@ // Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information. -using Microsoft.FSharp.Core; using CommandLine.Core; using CommandLine.Infrastructure; using CommandLine.Tests.Fakes; @@ -71,7 +70,7 @@ public void Explicit_help_request_generates_help_requested_error() var expectedResult = new NotParsed( TypeInfo.Create(typeof(Simple_Options)), new Error[] { new HelpRequestedError() }); - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "--help" }); @@ -87,7 +86,7 @@ public void Parse_negative_long_value(string[] arguments, long expected) { // Fixture setup in attributes - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -105,7 +104,7 @@ public void Parse_double_value(string[] arguments, double expected) { // Fixture setup in attributes - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -124,7 +123,7 @@ public void Parse_int_sequence(string[] arguments, int[] expected) { // Fixture setup in attributes - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -141,7 +140,7 @@ public void Parse_int_sequence_with_range(string[] arguments, int[] expected) { // Fixture setup in attributes - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -159,7 +158,7 @@ public void Parse_string_sequence_with_only_min_constraint(string[] arguments, s { // Fixture setup with attributes - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -176,7 +175,7 @@ public void Parse_string_sequence_with_only_max_constraint(string[] arguments, s { // Fixture setup with attributes - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -190,7 +189,7 @@ public void Breaking_min_constraint_in_string_sequence_generates_MissingValueOpt // Fixture setup var expectedResult = new[] { new MissingValueOptionError(new NameInfo("s", "string-seq")) }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "-s" }); @@ -204,7 +203,7 @@ public void Breaking_min_constraint_in_string_sequence_as_value_generates_Sequen // Fixture setup var expectedResult = new[] { new SequenceOutOfRangeError(NameInfo.EmptyName) }; - // Exercize system + // Exercise system var result = InvokeBuild( new string[] { }); @@ -218,7 +217,7 @@ public void Breaking_max_constraint_in_string_sequence_does_not_generate_Sequenc // Fixture setup var expectedResult = new[] { "one", "two", "three" }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "--string-seq=one", "two", "three", "this-is-too-much" }); @@ -233,7 +232,7 @@ public void Breaking_max_constraint_in_string_sequence_as_value_generates_Sequen // Fixture setup var expectedResult = new[] { new SequenceOutOfRangeError(NameInfo.EmptyName) }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "one", "two", "three", "this-is-too-much" }); @@ -252,7 +251,7 @@ public void Parse_enum_value(string[] arguments, Colors expected) { // Fixture setup in attribute - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -271,7 +270,7 @@ public void Parse_enum_value_ignore_case(string[] arguments, Colors expected) { // Fixture setup in attribute - // Exercize system + // Exercise system var result = InvokeBuildEnumValuesCaseIgnore( arguments); @@ -285,7 +284,7 @@ public void Parse_enum_value_with_wrong_index_generates_BadFormatConversionError // Fixture setup var expectedResult = new[] { new BadFormatConversionError(new NameInfo("", "colors")) }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "--colors", "3" }); @@ -299,7 +298,7 @@ public void Parse_enum_value_with_wrong_item_name_generates_BadFormatConversionE // Fixture setup var expectedResult = new[] { new BadFormatConversionError(new NameInfo("", "colors")) }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "--colors", "Yellow" }); @@ -313,7 +312,7 @@ public void Parse_enum_value_with_wrong_item_name_case_generates_BadFormatConver // Fixture setup var expectedResult = new[] { new BadFormatConversionError(new NameInfo("", "colors")) }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "--colors", "RED" }); @@ -333,7 +332,7 @@ public void Parse_values_partitioned_between_sequence_and_scalar() IntValue = 20 }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "10", "a", "b", "c", "20" }); @@ -351,7 +350,7 @@ public void Parse_sequence_value_without_range_constraints(string[] arguments, l { // Fixture setup in attributes - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -368,7 +367,7 @@ public void Parse_long_sequence_with_separator(string[] arguments, long[] expect { // Fixture setup in attributes - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -385,7 +384,7 @@ public void Parse_string_sequence_with_separator(string[] arguments, string[] ex { // Fixture setup in attributes - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -409,7 +408,7 @@ public void Double_dash_force_subsequent_arguments_as_values() }; var arguments = new[] { "--stringvalue", "str1", "--", "10", "-a", "--bee", "-c", "20" }; - // Exercize system + // Exercise system var result = InstanceBuilder.Build( Maybe.Just>(() => new Simple_Options_With_Values()), (a, optionSpecs) => @@ -437,7 +436,7 @@ public void Parse_option_from_different_sets_generates_MutuallyExclusiveSetError new MutuallyExclusiveSetError(new NameInfo("", "ftpurl"), string.Empty) }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "--weburl", "http://mywebsite.org/", "--ftpurl", "fpt://ftpsite.org/" }); @@ -454,7 +453,7 @@ public void Two_required_options_at_the_same_set_and_both_are_true() FtpUrl = "str1", WebUrl = "str2" }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "--ftpurl", "str1", "--weburl", "str2" }); @@ -472,7 +471,7 @@ public void Two_required_options_at_the_same_set_and_none_are_true() new MissingRequiredOptionError(new NameInfo("", "ftpurl")), new MissingRequiredOptionError(new NameInfo("", "weburl")) }; - // Exercize system + // Exercise system var result = InvokeBuild( new string[] { }); @@ -486,7 +485,7 @@ public void Omitting_required_option_generates_MissingRequiredOptionError() // Fixture setup var expectedResult = new[] { new MissingRequiredOptionError(new NameInfo("", "str")) }; - // Exercize system + // Exercise system var result = InvokeBuild( new string[] { }); @@ -500,7 +499,7 @@ public void Wrong_range_in_sequence_generates_SequenceOutOfRangeError() // Fixture setup var expectedResult = new[] { new SequenceOutOfRangeError(new NameInfo("i", "")) }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "-i", "10" }); @@ -514,7 +513,7 @@ public void Parse_unknown_long_option_generates_UnknownOptionError() // Fixture setup var expectedResult = new[] { new UnknownOptionError("xyz") }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "--stringvalue", "abc", "--xyz" }); @@ -528,7 +527,7 @@ public void Parse_unknown_short_option_generates_UnknownOptionError() // Fixture setup var expectedResult = new[] { new UnknownOptionError("z") }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "-z", "-x" }); @@ -542,7 +541,7 @@ public void Parse_unknown_short_option_in_option_group_generates_UnknownOptionEr // Fixture setup var expectedResult = new[] { new UnknownOptionError("z") }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "-zx" }); @@ -557,7 +556,7 @@ public void Omitting_names_assumes_identifier_as_long_name(string[] arguments, s { // Fixture setup in attributes - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -571,7 +570,7 @@ public void Breaking_required_constraint_in_string_scalar_as_value_generates_Mis // Fixture setup var expectedResult = new[] { new MissingRequiredOptionError(NameInfo.EmptyName) }; - // Exercize system + // Exercise system var result = InvokeBuild( new string[] { }); @@ -588,7 +587,7 @@ public void Parse_utf8_string_correctly(string[] arguments, string expected) { // Fixture setup in attributes - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -602,7 +601,7 @@ public void Breaking_equal_min_max_constraint_in_string_sequence_as_value_genera // Fixture setup var expectedResult = new[] { new SequenceOutOfRangeError(NameInfo.EmptyName) }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "one", "two", "this-is-too-much" }); @@ -619,7 +618,7 @@ public void Parse_nullable_int(string[] arguments, int? expected) { // Fixture setup in attributes - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -636,7 +635,7 @@ public void Parse_nullable_long(string[] arguments, long? expected) { // Fixture setup in attributes - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -644,51 +643,10 @@ public void Parse_nullable_long(string[] arguments, long? expected) expected.Should().Be(((Parsed)result).Value.NullableLong); } -#if !SKIP_FSHARP - [Theory] - [InlineData(new[] { "--filename", "log-20150626.txt" }, "log-20150626.txt", true)] - [InlineData(new string[] { }, null, false)] - public void Parse_fsharp_option_string(string[] arguments, string expectedValue, bool expectedSome) - { - // Fixture setup in attributes - - // Exercize system - var result = InvokeBuild( - arguments); - - // Verify outcome - if (((Parsed)result).Value.FileName != null) - { - expectedValue.Should().BeEquivalentTo(((Parsed)result).Value.FileName.Value); - } - expectedSome.Should().Be(FSharpOption.get_IsSome(((Parsed)result).Value.FileName)); - } - - [Theory] - [InlineData(new[] { "1234567" }, 1234567, true)] - [InlineData(new string[] { }, default(int), false)] - public void Parse_fsharp_option_int(string[] arguments, int expectedValue, bool expectedSome) - { - // Fixture setup in attributes - - // Exercize system - var result = InvokeBuild( - arguments); - - // Verify outcome - if (((Parsed)result).Value.Offset != null) - { - expectedValue.Should().Be(((Parsed)result).Value.Offset.Value); - } - expectedSome.Should().Be(FSharpOption.get_IsSome(((Parsed)result).Value.Offset)); - } -#endif - - [Fact] public void Min_constraint_set_to_zero_throws_exception() { - // Exercize system + // Exercise system Action test = () => InvokeBuild( new string[] { }); @@ -699,7 +657,7 @@ public void Min_constraint_set_to_zero_throws_exception() [Fact] public void Max_constraint_set_to_zero_throws_exception() { - // Exercize system + // Exercise system Action test = () => InvokeBuild( new string[] { }); @@ -710,7 +668,7 @@ public void Max_constraint_set_to_zero_throws_exception() [Fact] public void Min_and_max_constraint_set_to_zero_throws_exception() { - // Exercize system + // Exercise system Action test = () => InvokeBuild( new string[] { }); @@ -726,7 +684,7 @@ public void Min_and_max_constraint_set_to_zero_throws_exception() [InlineData(new[] { "--interactive", "--weburl=wvalue", "--verbose", "--ftpurl=wvalue" }, ParserResultType.NotParsed, 2)] public void Empty_set_options_allowed_with_mutually_exclusive_sets(string[] arguments, ParserResultType type, int expected) { - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -745,7 +703,7 @@ public void Empty_set_options_allowed_with_mutually_exclusive_sets(string[] argu [InlineData(new[] { "--stringvalue", "abc", "--stringvalue", "def" }, 1)] public void Specifying_options_two_or_more_times_generates_RepeatedOptionError(string[] arguments, int expected) { - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -757,7 +715,7 @@ public void Specifying_options_two_or_more_times_generates_RepeatedOptionError(s [InlineData(new[] { "-s", "abc", "-s", "def" }, 1)] public void Specifying_options_two_or_more_times_with_short_options_generates_RepeatedOptionError(string[] arguments, int expected) { - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -769,7 +727,7 @@ public void Specifying_options_two_or_more_times_with_short_options_generates_Re [InlineData(new[] { "--shortandlong", "abc", "--shortandlong", "def" }, 1)] public void Specifying_options_two_or_more_times_with_long_options_generates_RepeatedOptionError(string[] arguments, int expected) { - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -781,7 +739,7 @@ public void Specifying_options_two_or_more_times_with_long_options_generates_Rep [InlineData(new[] { "-s", "abc", "--shortandlong", "def" }, 1)] public void Specifying_options_two_or_more_times_with_mixed_short_long_options_generates_RepeatedOptionError(string[] arguments, int expected) { - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -792,9 +750,9 @@ public void Specifying_options_two_or_more_times_with_mixed_short_long_options_g [Theory] [InlineData(new[] { "--inputfile=file1.bin" }, "file1.bin")] [InlineData(new[] { "--inputfile", "file2.txt" }, "file2.txt")] - public void Can_define_options_on_explicit_interface_properties(string[] arguments, string expected) + public void Can_define_options_on_explicit_interface_properties(string[] arguments, string expected) { - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -808,7 +766,7 @@ public void Can_define_options_on_explicit_interface_properties(string[] argumen [InlineData(new[] { "--inputfile", "file2.txt" }, "file2.txt")] public void Can_define_options_on_interface_properties(string[] arguments, string expected) { - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -826,7 +784,7 @@ public void Can_define_options_on_interface_properties(string[] arguments, strin [InlineData(new string[] { }, ParserResultType.NotParsed, 2)] public void Enforce_required_within_mutually_exclusive_set_only(string[] arguments, ParserResultType type, int expected) { - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -847,7 +805,7 @@ public void Parse_string_scalar_with_required_constraint_as_value(string[] argum { // Fixture setup in attributes - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -861,7 +819,7 @@ public void Parse_string_scalar_and_sequence_adjacent(string[] arguments, Option { // Fixture setup in attributes - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -875,7 +833,7 @@ public void Parse_to_mutable() // Fixture setup var expectedResult = new Simple_Options { StringValue = "strval0", IntSequence = new[] { 9, 7, 8 }, BoolValue = true, LongValue = 9876543210L }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "--stringvalue=strval0", "-i", "9", "7", "8", "-x", "9876543210" }); @@ -892,7 +850,7 @@ public void Parse_to_mutable() [InlineData(new[] { "--long", "9", "--int=11" }, 1)] public void Breaking_required_constraint_generate_MissingRequiredOptionError(string[] arguments, int expected) { - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -907,7 +865,7 @@ public void Parse_to_immutable_instance(string[] arguments, Immutable_Simple_Opt { // Fixture setup in attributes - // Exercize system + // Exercise system var result = InvokeBuildImmutable( arguments); @@ -922,7 +880,7 @@ public void Parse_to_immutable_instance_with_Invalid_Ctor_Args(string[] argument { // Fixture setup in attributes - // Exercize system + // Exercise system Action act = () => InvokeBuildImmutable( arguments); @@ -938,7 +896,7 @@ public void Parse_to_type_with_single_string_ctor_builds_up_correct_instance() // Fixture setup var expectedResult = new Options_With_Uri_And_SimpleType { EndPoint = new Uri("http://localhost/test/"), MyValue = new MySimpleType("custom-value") }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "--endpoint=http://localhost/test/", "custom-value" }); @@ -952,7 +910,7 @@ public void Parse_option_with_exception_thrown_from_setter_generates_SetValueExc // Fixture setup var expectedResult = new[] { new SetValueExceptionError(new NameInfo("e", ""), new ArgumentException(), "bad") }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "-e", "bad" }); @@ -968,7 +926,7 @@ public void Parse_default_bool_type_string_SetValueExceptionError() var expectedResult = new[] { new SetValueExceptionError(new NameInfo("", name), new ArgumentException(InvalidAttributeConfigurationError.ErrorMessage), "bad") }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { name, "bad" }); @@ -990,7 +948,7 @@ public void Parse_string_with_dashes_except_in_beginning(string[] arguments, str { // Fixture setup in attributes - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -1004,7 +962,7 @@ public void Parse_without_auto_help_should_not_recognize_help_option(string[] ar { // Fixture setup in attributes - // Exercize system + // Exercise system var result = InvokeBuild(arguments, autoHelp: false); // Verify outcome @@ -1021,7 +979,7 @@ public void Parse_with_custom_help_option(string[] arguments, bool isHelp) { // Fixture setup in attributes - // Exercize system + // Exercise system var result = InvokeBuild(arguments, autoHelp: false); // Verify outcome @@ -1035,7 +993,7 @@ public void Parse_without_auto_version_should_not_recognize_version_option(strin { // Fixture setup in attributes - // Exercize system + // Exercise system var result = InvokeBuild(arguments, autoVersion: false); // Verify outcome @@ -1052,7 +1010,7 @@ public void Parse_with_custom_version_option(string[] arguments, bool isVersion) { // Fixture setup in attributes - // Exercize system + // Exercise system var result = InvokeBuild(arguments, autoVersion: false); // Verify outcome @@ -1066,7 +1024,7 @@ public void Parse_Guid(string[] arguments, Options_With_Guid expected) { // Fixture setup in attributes - // Exercize system + // Exercise system var result = InvokeBuild( arguments); @@ -1080,7 +1038,7 @@ public void Parse_TimeSpan() // Fixture setup var expectedResult = new Options_With_TimeSpan { Duration = TimeSpan.FromMinutes(42) }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "--duration=00:42:00" }); @@ -1092,7 +1050,7 @@ public void Parse_TimeSpan() [Fact] public void Should_not_parse_quoted_TimeSpan() { - // Exercize system + // Exercise system var result = InvokeBuild(new[] { "--duration=\"00:42:00\"" }); var outcome = result as NotParsed; @@ -1134,7 +1092,7 @@ public void Options_In_Group_With_No_Values_Generates_MissingGroupOptionError() }; var expectedResult = new[] { new MissingGroupOptionError("err-group", optionNames) }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "-v 10.42" }); @@ -1162,7 +1120,7 @@ public void Options_In_Group_With_No_Values_Generates_MissingGroupOptionErrors() new MissingGroupOptionError("err-group2", optionNames2) }; - // Exercize system + // Exercise system var result = InvokeBuild( new[] { "-v 10.42" }); @@ -1176,7 +1134,7 @@ public void Options_In_Group_With_No_Values_Generates_MissingGroupOptionErrors() [InlineData("-v", "10.5", "--option2", "test2")] public void Options_In_Group_With_Values_Does_Not_Generate_MissingGroupOptionError(params string[] args) { - // Exercize system + // Exercise system var result = InvokeBuild(args); // Verify outcome @@ -1194,7 +1152,7 @@ public void Options_In_Group_WithRequired_Does_Not_Generate_RequiredError() }; var expectedResult = new[] { new MissingGroupOptionError("string-group", optionNames) }; - // Exercize system + // Exercise system var result = InvokeBuild(new string[] { "-x" }); // Verify outcome @@ -1214,7 +1172,7 @@ public void Options_In_Group_Ignore_Option_Group_If_Option_Group_Name_Empty() new MissingRequiredOptionError(new NameInfo("s", "shortandlong")) }; - // Exercize system + // Exercise system var result = InvokeBuild(new string[] { "-x" }); // Verify outcome @@ -1227,7 +1185,7 @@ public void Options_In_Group_Ignore_Option_Group_If_Option_Group_Name_Empty() [Fact] public void Options_In_Group_Use_Option_Default_Value_When_Available() { - // Exercize system + // Exercise system var result = InvokeBuild(new string[] { "-x" }); // Verify outcome @@ -1243,7 +1201,7 @@ public void Options_In_Group_Do_Not_Allow_Mutually_Exclusive_Set() new GroupOptionAmbiguityError(new NameInfo("s", "shortandlong")) }; - // Exercize system + // Exercise system var result = InvokeBuild(new string[] { "-x" }); // Verify outcome @@ -1264,8 +1222,8 @@ public void Parse_int_sequence_with_multi_instance() ((Parsed)result).Value.IntSequence.Should().BeEquivalentTo(expected); } - #region custom types - + #region custom types + [Theory] [InlineData(new[] { "-c", "localhost:8080" }, "localhost", 8080)] diff --git a/tests/CommandLine.Tests/Unit/Core/InstanceChooserTests.cs b/tests/CommandLine.Tests/Unit/Core/InstanceChooserTests.cs index d5cb9a21..78cb6613 100644 --- a/tests/CommandLine.Tests/Unit/Core/InstanceChooserTests.cs +++ b/tests/CommandLine.Tests/Unit/Core/InstanceChooserTests.cs @@ -37,7 +37,7 @@ public void Parse_empty_array_returns_NullInstance() // Fixture setup var expectedErrors = new[] { new NoVerbSelectedError() }; - // Exercize system + // Exercise system var result = InvokeChoose( new[] { typeof(Add_Verb), typeof(Commit_Verb), typeof(Clone_Verb) }, new string[] { }); @@ -54,7 +54,7 @@ public void Explicit_help_request_generates_HelpVerbRequestedError() // Fixture setup var expectedErrors = new[] { new HelpVerbRequestedError(null, null, false) }; - // Exercize system + // Exercise system var result = InvokeChoose( new[] { typeof(Add_Verb), typeof(Commit_Verb), typeof(Clone_Verb) }, new[] { "help" }); @@ -71,7 +71,7 @@ public void Explicit_help_request_for_a_valid_verb_generates_HelpVerbRequestedEr // Fixture setup var expectedErrors = new[] { new HelpVerbRequestedError("commit", typeof(Commit_Verb), true) }; - // Exercize system + // Exercise system var result = InvokeChoose( new[] { typeof(Add_Verb), typeof(Commit_Verb), typeof(Clone_Verb) }, new[] { "help", "commit" }); @@ -88,7 +88,7 @@ public void Explicit_help_request_for_an_invalid_verb_generates_HelpVerbRequeste // Fixture setup var expectedErrors = new[] { new HelpVerbRequestedError(null, null, false) }; - // Exercize system + // Exercise system var result = InvokeChoose( new[] { typeof(Add_Verb), typeof(Commit_Verb), typeof(Clone_Verb) }, new[] { "help", "earthunderalienattack" }); @@ -105,7 +105,7 @@ public void Parse_existing_verb_returns_verb_instance() // Fixture setup var expected = new Add_Verb { Patch = true, FileName = "dummy.bin"}; - // Exercize system + // Exercise system var result = InvokeChoose( new[] { typeof(Add_Verb), typeof(Commit_Verb), typeof(Clone_Verb) }, new[] { "add", "--patch", "dummy.bin" }); @@ -122,7 +122,7 @@ public void Parse_existing_verb_returns_verb_immutable_instance() // Fixture setup var expected = new Immutable_Add_Verb(true, default(bool), "dummy.bin"); - // Exercize system + // Exercise system var result = InvokeChoose( new[] { typeof(Immutable_Add_Verb), typeof(Immutable_Commit_Verb), typeof(Immutable_Clone_Verb) }, new[] { "add", "--patch", "dummy.bin" }); @@ -132,14 +132,14 @@ public void Parse_existing_verb_returns_verb_immutable_instance() expected.Should().BeEquivalentTo(((Parsed)result).Value); // Teardown } - + [Fact] public void Parse_sequence_verb_returns_verb_instance() { // Fixture setup var expected = new SequenceOptions { LongSequence = new long[] { }, StringSequence = new[] { "aa", "b" } }; - // Exercize system + // Exercise system var result = InvokeChoose( new[] { typeof(Add_Verb), typeof(Commit_Verb), typeof(Clone_Verb), typeof(SequenceOptions) }, new[] { "sequence", "-s", "aa", "b" }); @@ -160,7 +160,7 @@ public void Parse_sequence_verb_with_separator_returns_verb_instance(string[] ar // Fixture setup var expected = new SequenceOptions { LongSequence = new long[] { }, StringSequence = expectedString }; - // Exercize system + // Exercise system var result = InvokeChoose( new[] { typeof(Add_Verb), typeof(Commit_Verb), typeof(Clone_Verb), typeof(SequenceOptions) }, arguments); diff --git a/tests/CommandLine.Tests/Unit/Core/KeyValuePairHelperTests.cs b/tests/CommandLine.Tests/Unit/Core/KeyValuePairHelperTests.cs index 3f1fb293..7de18719 100644 --- a/tests/CommandLine.Tests/Unit/Core/KeyValuePairHelperTests.cs +++ b/tests/CommandLine.Tests/Unit/Core/KeyValuePairHelperTests.cs @@ -15,7 +15,7 @@ public void Empty_token_sequence_creates_an_empty_KeyValuePair_sequence() var expected = new KeyValuePair>[] { }; var result = KeyValuePairHelper.ForSequence(new Token[] { }); - + AssertEqual(expected, result); } @@ -29,7 +29,7 @@ public void Token_sequence_creates_a_KeyValuePair_sequence() var result = KeyValuePairHelper.ForSequence(new [] { - Token.Name("seq"), Token.Value("seq0"), Token.Value("seq1"), Token.Value("seq2") + Token.Name("seq"), Token.Value("seq0"), Token.Value("seq1"), Token.Value("seq2") }).ToArray(); AssertEqual(expected, result); diff --git a/tests/CommandLine.Tests/Unit/Core/NameLookupTests.cs b/tests/CommandLine.Tests/Unit/Core/NameLookupTests.cs index f009c49e..e1e79b63 100644 --- a/tests/CommandLine.Tests/Unit/Core/NameLookupTests.cs +++ b/tests/CommandLine.Tests/Unit/Core/NameLookupTests.cs @@ -19,7 +19,7 @@ public void Lookup_name_of_sequence_option_with_separator() var specs = new[] { new OptionSpecification(string.Empty, "string-seq", false, string.Empty, Maybe.Nothing(), Maybe.Nothing(), '.', null, string.Empty, string.Empty, new List(), typeof(IEnumerable), TargetType.Sequence, string.Empty)}; - // Exercize system + // Exercise system var result = NameLookup.HavingSeparator("string-seq", specs, StringComparer.Ordinal); // Verify outcome expected.Should().BeEquivalentTo(result); @@ -37,7 +37,7 @@ public void Get_name_from_option_specification() var expected = new NameInfo(ShortName, LongName); var spec = new OptionSpecification(ShortName, LongName, false, string.Empty, Maybe.Nothing(), Maybe.Nothing(), '.', null, string.Empty, string.Empty, new List(), typeof(IEnumerable), TargetType.Sequence, string.Empty); - // Exercize system + // Exercise system var result = spec.FromOptionSpecification(); // Verify outcome diff --git a/tests/CommandLine.Tests/Unit/Core/OptionMapperTests.cs b/tests/CommandLine.Tests/Unit/Core/OptionMapperTests.cs index 0a948cea..5fb402e1 100644 --- a/tests/CommandLine.Tests/Unit/Core/OptionMapperTests.cs +++ b/tests/CommandLine.Tests/Unit/Core/OptionMapperTests.cs @@ -33,7 +33,7 @@ public void Map_boolean_switch_creates_boolean_value() Maybe.Nothing()) }; - // Exercize system + // Exercise system var result = OptionMapper.MapValues( specProps.Where(pt => pt.Specification.IsOption()), tokenPartitions, diff --git a/tests/CommandLine.Tests/Unit/Core/ReflectionExtensions.cs b/tests/CommandLine.Tests/Unit/Core/ReflectionExtensions.cs index 035b9e03..40038ca1 100644 --- a/tests/CommandLine.Tests/Unit/Core/ReflectionExtensions.cs +++ b/tests/CommandLine.Tests/Unit/Core/ReflectionExtensions.cs @@ -5,6 +5,7 @@ using CommandLine.Core; using CommandLine.Tests.Fakes; +// ReSharper disable once CheckNamespace namespace CommandLine.Tests.Unit.Infrastructure { public class ReflectionHelperTests diff --git a/tests/CommandLine.Tests/Unit/Core/TokenPartitionerTests.cs b/tests/CommandLine.Tests/Unit/Core/TokenPartitionerTests.cs index 20006e59..8a206a0c 100644 --- a/tests/CommandLine.Tests/Unit/Core/TokenPartitionerTests.cs +++ b/tests/CommandLine.Tests/Unit/Core/TokenPartitionerTests.cs @@ -25,7 +25,7 @@ public void Partition_sequence_returns_sequence() new OptionSpecification("i", string.Empty, false, string.Empty, Maybe.Just(3), Maybe.Just(4), '\0', null, string.Empty, string.Empty, new List(), typeof(IEnumerable), TargetType.Sequence, string.Empty) }; - // Exercize system + // Exercise system var result = TokenPartitioner.Partition( new[] { Token.Name("i"), Token.Value("10"), Token.Value("20"), Token.Value("30"), Token.Value("40") }, name => TypeLookup.FindTypeDescriptorAndSibling(name, specs, StringComparer.Ordinal) @@ -52,7 +52,7 @@ public void Partition_sequence_returns_sequence_with_duplicates() new OptionSpecification("i", string.Empty, false, string.Empty, Maybe.Just(3), Maybe.Just(4), '\0', null, string.Empty, string.Empty, new List(), typeof(IEnumerable), TargetType.Sequence, string.Empty) }; - // Exercize system + // Exercise system var result = TokenPartitioner.Partition( new[] { Token.Name("i"), Token.Value("10"), Token.Value("10"), Token.Value("30"), Token.Value("40") }, name => TypeLookup.FindTypeDescriptorAndSibling(name, specs, StringComparer.Ordinal) diff --git a/tests/CommandLine.Tests/Unit/Core/TokenizerTests.cs b/tests/CommandLine.Tests/Unit/Core/TokenizerTests.cs index ea7268be..2bbe441a 100644 --- a/tests/CommandLine.Tests/Unit/Core/TokenizerTests.cs +++ b/tests/CommandLine.Tests/Unit/Core/TokenizerTests.cs @@ -23,7 +23,7 @@ public void Explode_scalar_with_separator_in_odd_args_input_returns_sequence() var specs = new[] { new OptionSpecification(string.Empty, "string-seq", false, string.Empty, Maybe.Nothing(), Maybe.Nothing(), ',', null, string.Empty, string.Empty, new List(), typeof(IEnumerable), TargetType.Sequence, string.Empty)}; - // Exercize system + // Exercise system var result = Tokenizer.ExplodeOptionList( Result.Succeed( @@ -46,7 +46,7 @@ public void Explode_scalar_with_separator_in_even_args_input_returns_sequence() var specs = new[] { new OptionSpecification(string.Empty, "string-seq", false, string.Empty, Maybe.Nothing(), Maybe.Nothing(), ',', null, string.Empty, string.Empty, new List(), typeof(IEnumerable), TargetType.Sequence, string.Empty)}; - // Exercize system + // Exercise system var result = Tokenizer.ExplodeOptionList( Result.Succeed( @@ -71,7 +71,7 @@ public void Normalize_should_remove_all_names_and_values_with_explicit_assignmen Func nameLookup = name => name.Equals("x") || name.Equals("string-seq") || name.Equals("switch"); - // Exercize system + // Exercise system var result = Tokenizer.Normalize( //Result.Succeed( @@ -99,7 +99,7 @@ public void Normalize_should_remove_all_names_of_non_existing_names() Func nameLookup = name => name.Equals("x") || name.Equals("string-seq") || name.Equals("switch"); - // Exercize system + // Exercise system var result = Tokenizer.Normalize( //Result.Succeed( diff --git a/tests/CommandLine.Tests/Unit/Core/TypeConverterTests.cs b/tests/CommandLine.Tests/Unit/Core/TypeConverterTests.cs index c3e93781..087a8b9a 100644 --- a/tests/CommandLine.Tests/Unit/Core/TypeConverterTests.cs +++ b/tests/CommandLine.Tests/Unit/Core/TypeConverterTests.cs @@ -144,7 +144,7 @@ public static IEnumerable ChangeType_flagCounters_source { return new[] { - new object[] {new string[0], typeof (int), false, 0}, + new object[] { Array.Empty(), typeof (int), false, 0}, new object[] {new[] {"true"}, typeof (int), false, 1}, new object[] {new[] {"true", "true"}, typeof (int), false, 2}, new object[] {new[] {"true", "true", "true"}, typeof (int), false, 3}, diff --git a/tests/CommandLine.Tests/Unit/Infrastructure/FSharpOptionHelperTests.cs b/tests/CommandLine.Tests/Unit/Infrastructure/FSharpOptionHelperTests.cs deleted file mode 100644 index 80f0fc61..00000000 --- a/tests/CommandLine.Tests/Unit/Infrastructure/FSharpOptionHelperTests.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information. - -using System.Reflection; -using CommandLine.Infrastructure; -using CommandLine.Tests.Fakes; -using Microsoft.FSharp.Core; -using FluentAssertions; -using Xunit; - -namespace CommandLine.Tests.Unit.Infrastructure -{ - public class FSharpOptionHelperTests - { - [Fact] - public void Match_type_returns_true_if_FSharpOption() - { - ReflectionHelper.IsFSharpOptionType(TestData.PropertyType) - .Should().BeTrue(); - } - - [Fact] - public void Get_underlying_type() - { - FSharpOptionHelper.GetUnderlyingType(TestData.PropertyType).FullName - .Should().BeEquivalentTo("System.String"); - } - - [Fact] - public void Create_some() - { - var expected = FSharpOptionHelper.Some(FSharpOptionHelper.GetUnderlyingType(TestData.PropertyType), "with data"); - - expected.Should().BeOfType>(); - FSharpOption.get_IsSome((FSharpOption)expected).Should().BeTrue(); - } - - [Fact] - public void Create_none() - { - var expected = FSharpOptionHelper.None(FSharpOptionHelper.GetUnderlyingType(TestData.PropertyType)); - - FSharpOption.get_IsNone((FSharpOption)expected).Should().BeTrue(); - } - - private PropertyInfo TestData - { - get { return typeof(Options_With_FSharpOption).GetProperty("FileName", BindingFlags.Public | BindingFlags.Instance); } - } - } -} diff --git a/tests/CommandLine.Tests/Unit/Issue104Tests.cs b/tests/CommandLine.Tests/Unit/Issue104Tests.cs index ca35689e..ee81de16 100644 --- a/tests/CommandLine.Tests/Unit/Issue104Tests.cs +++ b/tests/CommandLine.Tests/Unit/Issue104Tests.cs @@ -11,12 +11,11 @@ namespace CommandLine.Tests.Unit { public class Issue104Tests { - [Fact] public void Create_instance_with_enum_options_enabled_and_nullable_enum() { // Fixture setup - // Exercize system + // Exercise system var sut = new HelpText { AddDashesToOption = true, AddEnumValuesToHelpText = true, MaximumDisplayWidth = 80 } .AddPreOptionsLine("pre-options") .AddOptions(new NotParsed(TypeInfo.Create(typeof(Options_With_Enum_Having_HelpText)), Enumerable.Empty())) @@ -39,7 +38,7 @@ public void Create_instance_with_enum_options_enabled_and_nullable_enum() public void Help_with_enum_options_enabled_and_nullable_enum() { // Fixture setup - // Exercize system + // Exercise system var args = "--help".Split(); var sut = new Parser(config => config.HelpWriter = null); var parserResult = sut.ParseArguments(args); diff --git a/tests/CommandLine.Tests/Unit/Issue389Tests.cs b/tests/CommandLine.Tests/Unit/Issue389Tests.cs index 5c81e6e0..d3dd528a 100644 --- a/tests/CommandLine.Tests/Unit/Issue389Tests.cs +++ b/tests/CommandLine.Tests/Unit/Issue389Tests.cs @@ -8,7 +8,6 @@ namespace CommandLine.Tests.Unit //Reference: PR# 392 public class Issue389Tests { - private const int ERROR_SUCCESS = 0; // Test method (xUnit) which fails @@ -23,8 +22,6 @@ public void CallMain_GiveHelpArgument_ExpectSuccess() // main program internal class Program { - - internal static int __Main(string[] args) { bool hasError = false; @@ -33,12 +30,12 @@ internal static int __Main(string[] args) ParserResult parsedOptions = Parser.Default.ParseArguments(args) .WithNotParsed(errors => { helpOrVersionRequested = errors.Any( - x => x.Tag == ErrorType.HelpRequestedError + x => x.Tag == ErrorType.HelpRequestedError || x.Tag == ErrorType.VersionRequestedError); hasError = true; }); - if(helpOrVersionRequested) + if (helpOrVersionRequested) { return ERROR_SUCCESS; } @@ -53,7 +50,6 @@ internal static int __Main(string[] args) // Options internal class Options { - [Option('c', "connectionString", Required = true, HelpText = "Texts.ExplainConnection")] public string ConnectionString { get; set; } @@ -61,16 +57,13 @@ internal class Options public int JobId { get; set; } [Usage(ApplicationAlias = "Importer.exe")] - public static IEnumerable Examples - { - get => new[] { + public static IEnumerable Examples => + new[] { new Example("Texts.ExplainExampleExecution", new Options() { ConnectionString="Server=MyServer;Database=MyDatabase", JobId = 5 }), }; - } - } } } diff --git a/tests/CommandLine.Tests/Unit/Issue418Tests.cs b/tests/CommandLine.Tests/Unit/Issue418Tests.cs index cac1e9f1..e35220ad 100644 --- a/tests/CommandLine.Tests/Unit/Issue418Tests.cs +++ b/tests/CommandLine.Tests/Unit/Issue418Tests.cs @@ -17,15 +17,15 @@ public void Explicit_version_request_generates_version_info_screen_with_eol() var help = new StringWriter(); var sut = new Parser(config => config.HelpWriter = help); - // Exercize system + // Exercise system sut.ParseArguments(new[] { "--version" }); - var result = help.ToString(); + var result = help.ToString(); // Verify outcome - var lines = result.ToNotEmptyLines(); + var lines = result.ToNotEmptyLines(); result.Length.Should().BeGreaterThan(0); result.Should().EndWith(Environment.NewLine); result.ToNotEmptyLines().Length.Should().Be(1); - + // Teardown } } diff --git a/tests/CommandLine.Tests/Unit/Issue482Tests.cs b/tests/CommandLine.Tests/Unit/Issue482Tests.cs index 9d2ea971..815fe594 100644 --- a/tests/CommandLine.Tests/Unit/Issue482Tests.cs +++ b/tests/CommandLine.Tests/Unit/Issue482Tests.cs @@ -19,8 +19,8 @@ public void AutoBuild_without_ordering() var parser = Parser.Default; var parseResult = parser.ParseArguments( new[] { "verb1", "--help" }) - .WithNotParsed(errors => { ; }) - .WithParsed(args => {; }); + .WithNotParsed(errors => { }) + .WithParsed(args => { }); var message = HelpText.AutoBuild(parseResult, error =>error, @@ -48,8 +48,6 @@ public void AutoBuild_without_ordering() expect.Trim().Should().Be(helps[i].Trim()); i++; } - - ; } [Fact] @@ -61,8 +59,8 @@ public void AutoBuild_with_ordering() var parser = Parser.Default; var parseResult = parser.ParseArguments( new[] { "verb1", "--help" }) - .WithNotParsed(errors => { ; }) - .WithParsed(args => {; }); + .WithNotParsed(errors => { }) + .WithParsed(args => { }); Comparison comparison = HelpText.RequiredThenAlphaComparison; @@ -96,8 +94,6 @@ public void AutoBuild_with_ordering() expect.Trim().Should().Be(helps[i].Trim()); i++; } - - ; } [Fact] @@ -109,8 +105,8 @@ public void AutoBuild_with_ordering_on_shortName() var parser = Parser.Default; var parseResult = parser.ParseArguments( new[] { "verb1", "--help" }) - .WithNotParsed(errors => { ; }) - .WithParsed(args => {; }); + .WithNotParsed(errors => { }) + .WithParsed(args => { }); Comparison orderOnShortName = (ComparableOption attr1, ComparableOption attr2) => { diff --git a/tests/CommandLine.Tests/Unit/Issue543Tests.cs b/tests/CommandLine.Tests/Unit/Issue543Tests.cs index 61a83512..fffcd1a6 100644 --- a/tests/CommandLine.Tests/Unit/Issue543Tests.cs +++ b/tests/CommandLine.Tests/Unit/Issue543Tests.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using System.Linq; using Xunit; using CommandLine.Text; @@ -8,7 +7,6 @@ namespace CommandLine.Tests.Unit //Reference: PR# 634 public class Issue543Tests { - private const int ERROR_SUCCESS = 0; [Fact] @@ -76,15 +74,13 @@ internal class Options public int JobId { get; set; } [Usage(ApplicationAlias = "Importer.exe")] - public static IEnumerable Examples - { - get => new[] { + public static IEnumerable Examples => + new[] { new Example("Texts.ExplainExampleExecution", new Options() { ConnectionString="Server=MyServer;Database=MyDatabase", JobId = 5 }), }; - } } // Options diff --git a/tests/CommandLine.Tests/Unit/Issue6Tests.cs b/tests/CommandLine.Tests/Unit/Issue6Tests.cs index 2f6ea3f4..bb79cafc 100644 --- a/tests/CommandLine.Tests/Unit/Issue6Tests.cs +++ b/tests/CommandLine.Tests/Unit/Issue6Tests.cs @@ -5,7 +5,6 @@ using CommandLine.Tests.Fakes; using CommandLine.Text; using FluentAssertions; -using Microsoft.FSharp.Core; using Xunit; using Xunit.Abstractions; diff --git a/tests/CommandLine.Tests/Unit/ParserTests.cs b/tests/CommandLine.Tests/Unit/ParserTests.cs index b079ce0f..cfd721a4 100644 --- a/tests/CommandLine.Tests/Unit/ParserTests.cs +++ b/tests/CommandLine.Tests/Unit/ParserTests.cs @@ -20,7 +20,7 @@ public void When_HelpWriter_is_set_help_screen_is_generated() var writer = new StringWriter(); var sut = new Parser(with => with.HelpWriter = writer); - // Exercize system + // Exercise system sut.ParseArguments(new string[] { }); // Verify outcome @@ -36,7 +36,7 @@ public void When_HelpWriter_is_set_help_screen_is_generated_in_verbs_scenario() var writer = new StringWriter(); var sut = new Parser(with => with.HelpWriter = writer); - // Exercize system + // Exercise system sut.ParseArguments(new string[] { }, typeof(Add_Verb), typeof(Commit_Verb), typeof(Clone_Verb)); // Verify outcome @@ -52,7 +52,7 @@ public void When_HelpWriter_is_set_help_screen_is_generated_in_verbs_scenario_us var writer = new StringWriter(); var sut = new Parser(with => with.HelpWriter = writer); - // Exercize system + // Exercise system sut.ParseArguments(new string[] { }); // Verify outcome @@ -68,7 +68,7 @@ public void Parse_options() var expectedOptions = new Simple_Options { StringValue = "strvalue", IntSequence = new[] { 1, 2, 3 } }; var sut = new Parser(); - // Exercize system + // Exercise system var result = sut.ParseArguments(new[] { "--stringvalue=strvalue", "-i1", "2", "3" }); // Verify outcome @@ -87,7 +87,7 @@ public void Parse_options_with_short_name(string outputFile, string[] args) var expectedOptions = new Options_With_Switches { OutputFile = outputFile }; var sut = new Parser(); - // Exercize system + // Exercise system var result = sut.ParseArguments(args); // Verify outcome @@ -116,7 +116,7 @@ public void Parse_FlagCounter_options_with_short_name(string[] args, int verbose var expectedOptions = new Options_With_FlagCounter_Switches { Verbose = verboseCount, Silent = silentCount }; var sut = new Parser(with => with.AllowMultiInstance = true); - // Exercize system + // Exercise system var result = sut.ParseArguments(args); // Verify outcome @@ -131,7 +131,7 @@ public void Parse_repeated_options_with_default_parser() // Fixture setup var sut = Parser.Default; - // Exercize system + // Exercise system var result = sut.ParseArguments(new[] { "-i", "-i", "-o", "file" }); // Verify outcome @@ -153,7 +153,7 @@ public void Parse_options_with_double_dash() }; var sut = new Parser(with => with.EnableDashDash = true); - // Exercize system + // Exercise system var result = sut.ParseArguments( new[] { "--stringvalue", "astring", "--", "20", "--aaa", "-b", "--ccc", "30" }); @@ -189,7 +189,7 @@ public void Parse_options_with_double_dash_and_option_sequence() var sut = new Parser(with => with.EnableDashDash = true); - // Exercize system + // Exercise system var result = sut.ParseArguments( new[] { "--option-seq", "option1", "option2", "option3", "--", "value1", "value2", "value3" }); @@ -205,7 +205,7 @@ public void Parse_options_with_double_dash_in_verbs_scenario() var expectedOptions = new Add_Verb { Patch = true, FileName = "--strange-fn" }; var sut = new Parser(with => with.EnableDashDash = true); - // Exercize system + // Exercise system var result = sut.ParseArguments( new[] { "add", "-p", "--", "--strange-fn" }, typeof(Add_Verb), @@ -226,7 +226,7 @@ public void Parse_options_with_single_dash() var expectedOptions = new Options_With_Switches(); var sut = new Parser(); - // Exercize system + // Exercise system var result = sut.ParseArguments(args); // Verify outcome @@ -250,7 +250,7 @@ public void Parse_verbs() }; var sut = new Parser(); - // Exercize system + // Exercise system var result = sut.ParseArguments( new[] { "clone", "-q", "http://gsscoder.github.com/", "http://yes-to-nooo.github.com/" }, @@ -275,7 +275,7 @@ public void Parse_options_with_short_name_in_verbs_scenario(string message, stri var expectedOptions = new Commit_Verb() { Message = message }; var sut = new Parser(); - // Exercize system + // Exercise system var result = sut.ParseArguments( args, typeof(Add_Verb), typeof(Commit_Verb), typeof(Clone_Verb)); @@ -292,7 +292,7 @@ public void Parse_repeated_options_with_default_parser_in_verbs_scenario() // Fixture setup var sut = Parser.Default; - // Exercize system + // Exercise system var result = sut.ParseArguments( new[] { "clone", "-q", "-q", "http://gsscoder.github.com/", "http://yes-to-nooo.github.com/" }, typeof(Add_Verb), typeof(Commit_Verb), typeof(Clone_Verb)); @@ -319,7 +319,7 @@ public void Parse_verbs_using_generic_overload() }; var sut = new Parser(); - // Exercize system + // Exercise system var result = sut.ParseArguments( new[] { "clone", "-q", "http://gsscoder.github.com/", "http://yes-to-nooo.github.com/" }); @@ -337,7 +337,7 @@ public void Parse_to_immutable_instance() var expectedOptions = new Immutable_Simple_Options("strvalue", new[] { 1, 2, 3 }, default(bool), default(long)); var sut = new Parser(); - // Exercize system + // Exercise system var result = sut.ParseArguments(new[] { "--stringvalue=strvalue", "-i1", "2", "3" }); // Verify outcome @@ -352,7 +352,7 @@ public void Explicit_help_request_with_immutable_instance_generates_help_request var expectedError = new HelpRequestedError(); var sut = new Parser(); - // Exercize system + // Exercise system var result = sut.ParseArguments(new[] { "--help" }); // Verify outcome @@ -368,7 +368,7 @@ public void Explicit_help_request_with_immutable_instance_generates_help_screen( var help = new StringWriter(); var sut = new Parser(config => config.HelpWriter = help); - // Exercize system + // Exercise system sut.ParseArguments(new[] { "--help" }); var result = help.ToString(); @@ -384,7 +384,7 @@ public void Explicit_version_request_generates_version_requested_error() var expectedError = new VersionRequestedError(); var sut = new Parser(); - // Exercize system + // Exercise system var result = sut.ParseArguments(new[] { "--version" }); // Verify outcome @@ -400,7 +400,7 @@ public void Explicit_version_request_generates_version_info_screen() var help = new StringWriter(); var sut = new Parser(config => config.HelpWriter = help); - // Exercize system + // Exercise system sut.ParseArguments(new[] { "--version" }); var result = help.ToString(); @@ -419,7 +419,7 @@ public void Implicit_help_screen_in_verb_scenario() var help = new StringWriter(); var sut = new Parser(config => config.HelpWriter = help); - // Exercize system + // Exercise system sut.ParseArguments(new string[] { }); var result = help.ToString(); @@ -437,7 +437,7 @@ public void Implicit_help_screen_in_verb_scenario() lines[8].Should().BeEquivalentTo("version Display version information."); // Teardown } - + [Fact] public void Help_screen_in_default_verb_scenario() { @@ -448,7 +448,7 @@ public void Help_screen_in_default_verb_scenario() // Exercise system sut.ParseArguments(new string[] {"--help" }); var result = help.ToString(); - + // Verify outcome result.Length.Should().BeGreaterThan(0); var lines = result.ToNotEmptyLines().TrimStringArray(); @@ -459,7 +459,7 @@ public void Help_screen_in_default_verb_scenario() lines[4].Should().BeEquivalentTo("clone Clone a repository into a new directory."); lines[5].Should().BeEquivalentTo("help Display more information on a specific command."); lines[6].Should().BeEquivalentTo("version Display version information."); - + } [Fact] public void Double_dash_help_dispalys_verbs_index_in_verbs_scenario() @@ -468,7 +468,7 @@ public void Double_dash_help_dispalys_verbs_index_in_verbs_scenario() var help = new StringWriter(); var sut = new Parser(config => config.HelpWriter = help); - // Exercize system + // Exercise system sut.ParseArguments(new[] { "--help" }); var result = help.ToString(); @@ -493,7 +493,7 @@ public void Explicit_version_request_generates_version_info_screen_in_verbs_scen var help = new StringWriter(); var sut = new Parser(config => config.HelpWriter = help); - // Exercize system + // Exercise system sut.ParseArguments(new[] { command }); var result = help.ToString(); @@ -512,7 +512,7 @@ public void Errors_of_type_MutuallyExclusiveSetError_are_properly_formatted() var help = new StringWriter(); var sut = new Parser(config => config.HelpWriter = help); - // Exercize system + // Exercise system sut.ParseArguments(new[] { "--weburl=value.com", "--ftpurl=value.org" }); var result = help.ToString(); @@ -538,7 +538,7 @@ public void Explicit_help_request_with_specific_verb_generates_help_screen() var help = new StringWriter(); var sut = new Parser(config => config.HelpWriter = help); - // Exercize system + // Exercise system sut.ParseArguments(new[] { "commit", "--help" }); var result = help.ToString(); @@ -558,7 +558,7 @@ public void Properly_formatted_help_screen_is_displayed_when_usage_is_defined_in config.MaximumDisplayWidth = 80; }); - // Exercize system + // Exercise system sut.ParseArguments( new[] { "clone", "--badoption=@bad?value" }); var result = help.ToString(); @@ -593,10 +593,10 @@ public void Properly_formatted_help_screen_is_displayed_when_there_is_a_hidden_v var help = new StringWriter(); var sut = new Parser(config => config.HelpWriter = help); - // Exercize system + // Exercise system sut.ParseArguments(new string[] { }); var result = help.ToString(); - + // Verify outcome var lines = result.ToNotEmptyLines().TrimStringArray(); lines[0].Should().Be(HeadingInfo.Default.ToString()); @@ -617,10 +617,10 @@ public void Properly_formatted_help_screen_is_displayed_when_there_is_a_hidden_v var help = new StringWriter(); var sut = new Parser(config => config.HelpWriter = help); - // Exercize system + // Exercise system sut.ParseArguments(new string[] { "secert", "--help" }); var result = help.ToString(); - + // Verify outcome var lines = result.ToNotEmptyLines().TrimStringArray(); lines[0].Should().Be(HeadingInfo.Default.ToString()); @@ -631,7 +631,7 @@ public void Properly_formatted_help_screen_is_displayed_when_there_is_a_hidden_v // Teardown } - + [Fact] public void Parse_options_when_given_hidden_verb() { @@ -640,9 +640,9 @@ public void Parse_options_when_given_hidden_verb() var help = new StringWriter(); var sut = new Parser(config => config.HelpWriter = help); - // Exercize system + // Exercise system var result = sut.ParseArguments(new string[] { "secert", "--force" }); - + // Verify outcome result.Tag.Should().BeEquivalentTo(ParserResultType.Parsed); @@ -660,9 +660,9 @@ public void Parse_options_when_given_hidden_verb_with_hidden_option() var help = new StringWriter(); var sut = new Parser(config => config.HelpWriter = help); - // Exercize system + // Exercise system var result = sut.ParseArguments(new string[] { "secert", "--force", "--secert-option", "shhh" }); - + // Verify outcome result.Tag.Should().BeEquivalentTo(ParserResultType.Parsed); result.GetType().Should().Be>(); @@ -682,7 +682,7 @@ public void Specific_verb_help_screen_should_be_displayed_regardless_other_argum config.MaximumDisplayWidth = 80; }); - // Exercize system + // Exercise system sut.ParseArguments( new[] { "help", "clone", "extra-arg" }); var result = help.ToString(); @@ -710,7 +710,7 @@ public void When_IgnoreUnknownArguments_is_set_valid_unknown_arguments_avoid_a_f // Fixture setup var sut = new Parser(config => config.IgnoreUnknownArguments = true); - // Exercize system + // Exercise system var result = sut.ParseArguments(arguments); // Verify outcome @@ -729,7 +729,7 @@ public void When_IgnoreUnknownArguments_is_set_valid_unknown_arguments_avoid_a_f // Fixture setup var sut = new Parser(config => config.IgnoreUnknownArguments = true); - // Exercize system + // Exercise system var result = sut.ParseArguments(arguments); // Verify outcome @@ -750,7 +750,7 @@ public void Properly_formatted_help_screen_excludes_help_as_unknown_option() config.MaximumDisplayWidth = 80; }); - // Exercize system + // Exercise system sut.ParseArguments( new[] { "clone", "--bad-arg", "--help" }); var result = help.ToString(); @@ -783,13 +783,13 @@ public static void Breaking_mutually_exclusive_set_constraint_with_both_set_name }; var sut = new Parser(); - // Exercize system + // Exercise system var result = sut.ParseArguments( new[] { "--weburl", "value", "--somethingelse", "othervalue" }); // Verify outcome ((NotParsed)result).Errors.Should().BeEquivalentTo(expectedResult); - + } [Fact] @@ -867,7 +867,7 @@ public void Parse_verb_with_same_option_and_value_args() { var parser = Parser.Default; var result = parser.ParseArguments( - new[] { "test", "arg", "-o", "arg" }, + new[] { "test", "arg", "-o", "arg" }, typeof(Verb_With_Option_And_Value_Of_String_Type)); result .WithNotParsed(errors => { throw new InvalidOperationException("Must be parsed."); }) @@ -902,10 +902,10 @@ public void Blank_lines_are_inserted_between_verbs() var help = new StringWriter(); var sut = new Parser(config => config.HelpWriter = help); - // Exercize system + // Exercise system sut.ParseArguments(new string[] { }); var result = help.ToString(); - + // Verify outcome var lines = result.ToLines().TrimStringArray(); lines[6].Should().BeEquivalentTo("add Add file contents to the index."); @@ -1018,7 +1018,7 @@ public void Parse_default_verb_with_empty_name() public void When_HelpWriter_is_null_it_should_not_fire_exception() { // Arrange - + //Act var sut = new Parser(config => config.HelpWriter = null); sut.ParseArguments(new[] {"--dummy"}); diff --git a/tests/CommandLine.Tests/Unit/StringBuilderExtensionsTests.cs b/tests/CommandLine.Tests/Unit/StringBuilderExtensionsTests.cs index fdbd6526..6e123490 100644 --- a/tests/CommandLine.Tests/Unit/StringBuilderExtensionsTests.cs +++ b/tests/CommandLine.Tests/Unit/StringBuilderExtensionsTests.cs @@ -36,8 +36,6 @@ public class StringBuilderExtensionsTests new object[] { "test string" } }; - - [Theory] [MemberData(nameof(GoodStartsWithData))] [MemberData(nameof(BadTestData))] diff --git a/tests/CommandLine.Tests/Unit/Text/HelpTextAutoBuildFix.cs b/tests/CommandLine.Tests/Unit/Text/HelpTextAutoBuildFix.cs index d777c8f9..9bd552ab 100644 --- a/tests/CommandLine.Tests/Unit/Text/HelpTextAutoBuildFix.cs +++ b/tests/CommandLine.Tests/Unit/Text/HelpTextAutoBuildFix.cs @@ -13,7 +13,7 @@ public class HelpTextAutoBuildFix public void HelpText_with_AdditionalNewLineAfterOption_true_should_have_newline() { // Fixture setup - // Exercize system + // Exercise system var sut = new HelpText { AdditionalNewLineAfterOption = true } .AddOptions(new NotParsed(TypeInfo.Create(typeof(Simple_Options)), Enumerable.Empty())); @@ -38,7 +38,7 @@ public void HelpText_with_AdditionalNewLineAfterOption_true_should_have_newline( public void HelpText_with_AdditionalNewLineAfterOption_false_should_not_have_newline() { // Fixture setup - // Exercize system + // Exercise system var sut = new HelpText { AdditionalNewLineAfterOption = false } .AddOptions(new NotParsed(TypeInfo.Create(typeof(Simple_Options)), Enumerable.Empty())); @@ -57,7 +57,7 @@ public void HelpText_with_AdditionalNewLineAfterOption_false_should_not_have_new public void HelpText_with_by_default_should_include_help_version_option() { // Fixture setup - // Exercize system + // Exercise system var sut = new HelpText () .AddOptions(new NotParsed(TypeInfo.Create(typeof(Simple_Options)), Enumerable.Empty())); @@ -75,7 +75,7 @@ public void HelpText_with_by_default_should_include_help_version_option() public void HelpText_with_AutoHelp_false_should_hide_help_option() { // Fixture setup - // Exercize system + // Exercise system var sut = new HelpText { AutoHelp = false,AutoVersion = false} .AddOptions(new NotParsed(TypeInfo.Create(typeof(Simple_Options)), Enumerable.Empty())); diff --git a/tests/CommandLine.Tests/Unit/Text/HelpTextTests.cs b/tests/CommandLine.Tests/Unit/Text/HelpTextTests.cs index 9811f7be..d556c9f9 100644 --- a/tests/CommandLine.Tests/Unit/Text/HelpTextTests.cs +++ b/tests/CommandLine.Tests/Unit/Text/HelpTextTests.cs @@ -36,7 +36,7 @@ public void Create_empty_instance() public void Create_instance_without_options(bool newlineBetweenSections) { // Fixture setup - // Exercize system + // Exercise system var sut = new HelpText(new HeadingInfo("Unit-tests", "2.0"), new CopyrightInfo(true, "Author", 2005, 2013)); sut.AddNewLineBetweenHelpSections = newlineBetweenSections; @@ -72,7 +72,7 @@ public void Create_instance_without_options(bool newlineBetweenSections) public void Create_instance_with_options(bool newlineBetweenSections) { // Fixture setup - // Exercize system + // Exercise system var sut = new HelpText { AddDashesToOption = true, AddNewLineBetweenHelpSections = newlineBetweenSections } .AddPreOptionsLine("pre-options") .AddOptions(new NotParsed(TypeInfo.Create(typeof(Simple_Options)), Enumerable.Empty())) @@ -103,7 +103,7 @@ public void Create_instance_with_options(bool newlineBetweenSections) public void Create_instance_with_enum_options_enabled() { // Fixture setup - // Exercize system + // Exercise system var sut = new HelpText { AddDashesToOption = true, AddEnumValuesToHelpText = true, MaximumDisplayWidth = 80 } .AddPreOptionsLine("pre-options") .AddOptions(new NotParsed(TypeInfo.Create(typeof(Options_With_Enum_Having_HelpText)), Enumerable.Empty())) @@ -126,7 +126,7 @@ public void Create_instance_with_enum_options_enabled() public void Create_instance_with_enum_options_disabled() { // Fixture setup - // Exercize system + // Exercise system var sut = new HelpText { AddDashesToOption = true } .AddPreOptionsLine("pre-options") .AddOptions(new NotParsed(TypeInfo.Create(typeof(Options_With_Enum_Having_HelpText)), Enumerable.Empty())) @@ -148,7 +148,7 @@ public void Create_instance_with_enum_options_disabled() public void When_defined_MetaValue_should_be_rendered() { // Fixture setup - // Exercize system + // Exercise system var sut = new HelpText("Meta Value.").AddOptions( new NotParsed(TypeInfo.Create(typeof(Options_With_MetaValue)), Enumerable.Empty())); @@ -164,7 +164,7 @@ public void When_defined_MetaValue_should_be_rendered() public void When_help_text_is_longer_than_width_it_will_wrap_around_as_if_in_a_column_given_width_of_40() { // Fixture setup - // Exercize system + // Exercise system var sut = new HelpText(headingInfo); sut.MaximumDisplayWidth = 40; sut.AddOptions( @@ -174,7 +174,7 @@ public void When_help_text_is_longer_than_width_it_will_wrap_around_as_if_in_a_c // Verify outcome var lines = sut.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None); - lines[2].Should().BeEquivalentTo(" v, verbose This is the description"); //"The first line should have the arguments and the start of the Help Text."); + lines[2].Should().BeEquivalentTo(" v, verbose This is the description"); //"The first line should have the arguments and the start of the Help Text." //string formattingMessage = "Beyond the second line should be formatted as though it's in a column."; lines[3].Should().BeEquivalentTo(" of the verbosity to test"); lines[4].Should().BeEquivalentTo(" out the wrapping"); @@ -187,7 +187,7 @@ public void When_help_text_is_longer_than_width_it_will_wrap_around_as_if_in_a_c public void When_help_text_is_longer_than_width_it_will_wrap_around_as_if_in_a_column_given_width_of_100() { // Fixture setup - // Exercize system + // Exercise system var sut = new HelpText(headingInfo) { MaximumDisplayWidth = 100 }; sut.AddOptions( new NotParsed( @@ -196,7 +196,7 @@ public void When_help_text_is_longer_than_width_it_will_wrap_around_as_if_in_a_c // Verify outcome var lines = sut.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None); - lines[2].Should().BeEquivalentTo(" v, verbose This is the description of the verbosity to test out the wrapping capabilities of"); //"The first line should have the arguments and the start of the Help Text."); + lines[2].Should().BeEquivalentTo(" v, verbose This is the description of the verbosity to test out the wrapping capabilities of"); //"The first line should have the arguments and the start of the Help Text." //string formattingMessage = "Beyond the second line should be formatted as though it's in a column."; lines[3].Should().BeEquivalentTo(" the Help Text."); // Teardown @@ -206,7 +206,7 @@ public void When_help_text_is_longer_than_width_it_will_wrap_around_as_if_in_a_c public void When_help_text_has_hidden_option_it_should_not_be_added_to_help_text_output() { // Fixture setup - // Exercize system + // Exercise system var sut = new HelpText(headingInfo); sut.MaximumDisplayWidth = 80; sut.AddOptions( @@ -216,7 +216,7 @@ public void When_help_text_has_hidden_option_it_should_not_be_added_to_help_text // Verify outcome var lines = sut.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None); - lines[2].Should().BeEquivalentTo(" v, verbose This is the description of the verbosity to test out the"); //"The first line should have the arguments and the start of the Help Text."); + lines[2].Should().BeEquivalentTo(" v, verbose This is the description of the verbosity to test out the"); //"The first line should have the arguments and the start of the Help Text." //string formattingMessage = "Beyond the second line should be formatted as though it's in a column."; lines[3].Should().BeEquivalentTo(" wrapping capabilities of the Help Text."); // Teardown @@ -226,7 +226,7 @@ public void When_help_text_has_hidden_option_it_should_not_be_added_to_help_text public void Long_help_text_without_spaces() { // Fixture setup - // Exercize system + // Exercise system var sut = new HelpText(headingInfo); sut.MaximumDisplayWidth = 40; sut.AddOptions( @@ -249,7 +249,7 @@ public void Long_help_text_without_spaces() public void Long_pre_and_post_lines_without_spaces() { // Fixture setup - // Exercize system + // Exercise system var sut = new HelpText("Heading Info."); sut.MaximumDisplayWidth = 40; sut.AddPreOptionsLine("Before 0123456789012345678901234567890123456789012 After") @@ -322,7 +322,7 @@ public void Invoking_RenderParsingErrorsText_returns_appropriate_formatted_text( Func, string> fakeMutExclRenderer = _ => string.Empty; - // Exercize system + // Exercise system var errorsText = HelpText.RenderParsingErrorsText(fakeResult, fakeRenderer, fakeMutExclRenderer, 2); // Verify outcome @@ -350,7 +350,7 @@ public void Invoke_AutoBuild_for_Options_returns_appropriate_formatted_text() new SequenceOutOfRangeError(new NameInfo("i", "")) }); - // Exercize system + // Exercise system var helpText = HelpText.AutoBuild(fakeResult); // Verify outcome @@ -385,7 +385,7 @@ public void Invoke_AutoBuild_for_Verbs_with_specific_verb_returns_appropriate_fo new HelpVerbRequestedError("commit", typeof(Commit_Verb), true) }); - // Exercize system + // Exercise system var helpText = HelpText.AutoBuild(fakeResult); // Verify outcome @@ -416,7 +416,7 @@ public void Invoke_AutoBuild_for_Verbs_with_specific_verb_returns_appropriate_fo new HelpVerbRequestedError("commit", typeof(Commit_Verb), true) }); - // Exercize system + // Exercise system var helpText = HelpText.AutoBuild(fakeResult, maxDisplayWidth: 100); // Verify outcome @@ -441,7 +441,7 @@ public void Invoke_AutoBuild_for_Verbs_with_unknown_verb_returns_appropriate_for verbTypes), new Error[] { new HelpVerbRequestedError(null, null, false) }); - // Exercize system + // Exercise system var helpText = HelpText.AutoBuild(fakeResult); // Verify outcome @@ -461,7 +461,7 @@ public void Invoke_AutoBuild_for_Verbs_with_unknown_verb_returns_appropriate_for public void Create_instance_with_options_and_values() { // Fixture setup - // Exercize system + // Exercise system var sut = new HelpText { AddDashesToOption = true, AdditionalNewLineAfterOption = false } .AddPreOptionsLine("pre-options") .AddOptions(new NotParsed(TypeInfo.Create(typeof(Options_With_HelpText_And_MetaValue)), Enumerable.Empty())) @@ -493,7 +493,7 @@ public static void RenderUsageText_returns_properly_formatted_text() new NotParsed( TypeInfo.Create(typeof(Options_With_Usage_Attribute)), Enumerable.Empty()); - // Exercize system + // Exercise system var text = HelpText.RenderUsageText(result); // Verify outcome @@ -526,7 +526,7 @@ public void Invoke_AutoBuild_for_Options_with_Usage_returns_appropriate_formatte new BadFormatTokenError("badtoken") }); - // Exercize system + // Exercise system var helpText = HelpText.AutoBuild(fakeResult, h => { @@ -600,7 +600,7 @@ public void AutoBuild_with_errors_and_preoptions_renders_correctly(bool startWit new BadFormatTokenError("badtoken") }); - // Exercize system + // Exercise system var helpText = HelpText.AutoBuild(fakeResult, h => { @@ -645,7 +645,7 @@ public void Default_set_to_sequence_should_be_properly_printed() typeof(Options_With_Default_Set_To_Sequence).ToTypeInfo(), new Error[] { new BadFormatTokenError("badtoken") }); - // Exercize system + // Exercise system handlers.ChangeCulture(); var helpText = HelpText.AutoBuild(fakeResult); handlers.ResetCulture(); @@ -664,12 +664,12 @@ public void Default_set_to_sequence_should_be_properly_printed() [Fact] public void AutoBuild_when_no_assembly_attributes() { - string expectedCopyright = $"Copyright (C) {DateTime.Now.Year} author"; + string expectedCopyright = $"Copyright (C) {DateTime.Now.Year} author"; - ReflectionHelper.SetAttributeOverride(new Attribute[0]); + ReflectionHelper.SetAttributeOverride(Array.Empty()); ParserResult fakeResult = new NotParsed( - TypeInfo.Create(typeof(Simple_Options)), new Error[0]); + TypeInfo.Create(typeof(Simple_Options)), Array.Empty()); HelpText actualResult = HelpText.AutoBuild(fakeResult, ht => ht, ex => ex); actualResult.Copyright.Should().Be(expectedCopyright); } @@ -688,7 +688,7 @@ public void AutoBuild_with_assembly_title_and_version_attributes_only() }); ParserResult fakeResult = new NotParsed( - TypeInfo.Create(typeof(Simple_Options)), new Error[0]); + TypeInfo.Create(typeof(Simple_Options)), Array.Empty()); HelpText actualResult = HelpText.AutoBuild(fakeResult, ht => ht, ex => ex); actualResult.Heading.Should().Be(string.Format("{0} {1}", expectedTitle, expectedVersion)); } @@ -704,7 +704,7 @@ public void AutoBuild_with_assembly_company_attribute_only() }); ParserResult fakeResult = new NotParsed( - TypeInfo.Create(typeof(Simple_Options)), new Error[0]); + TypeInfo.Create(typeof(Simple_Options)), Array.Empty()); bool onErrorCalled = false; HelpText actualResult = HelpText.AutoBuild(fakeResult, ht => { @@ -731,7 +731,7 @@ public void Add_line_with_two_empty_spaces_at_the_end() public void HelpTextHonoursLineBreaks() { // Fixture setup - // Exercize system + // Exercise system var sut = new HelpText { AddDashesToOption = true } .AddOptions(new NotParsed(TypeInfo.Create(typeof(HelpTextWithLineBreaks_Options)), Enumerable.Empty())); @@ -750,7 +750,7 @@ public void HelpTextHonoursLineBreaks() public void HelpTextHonoursIndentationAfterLineBreaks() { // Fixture setup - // Exercize system + // Exercise system var sut = new HelpText { AddDashesToOption = true } .AddOptions(new NotParsed(TypeInfo.Create(typeof(HelpTextWithLineBreaks_Options)), Enumerable.Empty())); @@ -769,7 +769,7 @@ public void HelpTextHonoursIndentationAfterLineBreaks() public void HelpTextPreservesIndentationAcrossWordWrap() { // Fixture setup - // Exercise system + // Exercise system var sut = new HelpText { AddDashesToOption = true, MaximumDisplayWidth = 60 } .AddOptions(new NotParsed(TypeInfo.Create(typeof(HelpTextWithLineBreaksAndSubIndentation_Options)), Enumerable.Empty())); @@ -792,7 +792,7 @@ public void HelpTextPreservesIndentationAcrossWordWrap() public void HelpTextIsConsitentRegardlessOfCompileTimeLineStyle() { // Fixture setup - // Exercize system + // Exercise system var sut = new HelpText { AddDashesToOption = true } .AddOptions(new NotParsed(TypeInfo.Create(typeof(HelpTextWithMixedLineBreaks_Options)), Enumerable.Empty())); @@ -811,7 +811,7 @@ public void HelpTextIsConsitentRegardlessOfCompileTimeLineStyle() public void HelpTextPreservesIndentationAcrossWordWrapWithSmallMaximumDisplayWidth() { // Fixture setup - // Exercise system + // Exercise system var sut = new HelpText { AddDashesToOption = true, MaximumDisplayWidth = 10 } .AddOptions(new NotParsed(TypeInfo.Create(typeof(HelpTextWithLineBreaksAndSubIndentation_Options)), Enumerable.Empty())); @@ -834,7 +834,7 @@ public void Options_should_be_separated_by_spaces() Enumerable.Empty() ); - // Exercize system + // Exercise system handlers.ChangeCulture(); var helpText = HelpText.AutoBuild(fakeResult); handlers.ResetCulture(); @@ -842,7 +842,7 @@ public void Options_should_be_separated_by_spaces() // Verify outcome var text = helpText.ToString(); var lines = text.ToLines().TrimStringArray(); - + lines[3].Should().Be("-z, --strseq (Default: a b c)"); lines[5].Should().Be("-y, --intseq (Default: 1 2 3)"); lines[7].Should().Be("-q, --dblseq (Default: 1.1 2.2 3.3)"); @@ -912,7 +912,7 @@ public void Options_Should_Render_Multiple_OptionGroups_When_Available() } #region Custom Help - + [Fact] [Trait("Category", "CustomHelp")] public void AutoBuild_with_custom_copyright_using_onError_action() @@ -966,7 +966,7 @@ public void Invoke_Custom_AutoBuild_for_Verbs_with_specific_verb_and_no_Addition new HelpVerbRequestedError("commit", typeof(Commit_Verb), true) }); - // Exercize system + // Exercise system var helpText = HelpText.AutoBuild(fakeResult, h => { h.AdditionalNewLineAfterOption = false; return h; @@ -998,7 +998,7 @@ public void Invoke_AutoBuild_for_Options_with_custom_help_returns_appropriate_fo new SequenceOutOfRangeError(new NameInfo("i", "")) }); - // Exercize system + // Exercise system var helpText = HelpText.AutoBuild(fakeResult, h => h); // Verify outcome @@ -1019,7 +1019,7 @@ public void Invoke_AutoBuild_for_Options_with_custom_help_returns_appropriate_fo lines[13].Should().BeEquivalentTo("-x Define a boolean or switch value here."); lines[14].Should().BeEmpty(); lines[15].Should().BeEquivalentTo("--help Display this help screen."); - + } #endregion } diff --git a/tests/CommandLine.Tests/Unit/UnParserExtensionsTests.cs b/tests/CommandLine.Tests/Unit/UnParserExtensionsTests.cs index 7e878f32..66516049 100644 --- a/tests/CommandLine.Tests/Unit/UnParserExtensionsTests.cs +++ b/tests/CommandLine.Tests/Unit/UnParserExtensionsTests.cs @@ -7,10 +7,7 @@ using Xunit; using FluentAssertions; using CommandLine.Tests.Fakes; -#if !SKIP_FSHARP -using Microsoft.FSharp.Core; -#endif - + namespace CommandLine.Tests.Unit { public class UnParserExtensionsTests @@ -31,7 +28,7 @@ public static void UnParsing_instance_with_splitArgs_returns_same_option_class(S new Parser() .FormatCommandLineArgs(options) .Should().BeEquivalentTo(result.SplitArgs()); - + } [Theory] @@ -87,17 +84,6 @@ public static void Unparsing_hidden_option_returns_command_line(Hidden_Option op .Should().BeEquivalentTo(result); } -#if !SKIP_FSHARP - [Theory] - [MemberData(nameof(UnParseDataFSharpOption))] - public static void UnParsing_instance_with_fsharp_option_returns_command_line(Options_With_FSharpOption options, string result) - { - new Parser() - .FormatCommandLine(options) - .Should().BeEquivalentTo(result); - } -#endif - [Fact] public static void UnParsing_instance_with_group_switches_returns_command_line_with_switches_grouped() { @@ -300,7 +286,7 @@ public static void UnParsing_instance_with_nullable_bool(bool? flag, string expe [InlineData(" --shape Circle ", new[] { "--shape", "Circle" })] [InlineData("-a --shape Circle", new[] {"-a", "--shape", "Circle" })] [InlineData("-a --shape Circle -- -x1 -x2", new[] { "-a", "--shape", "Circle","--","-x1","-x2" })] - [InlineData("--name \"name with space and quote\" -x1", new[] { "--name", "name with space and quote","-x1" })] + [InlineData("--name \"name with space and quote\" -x1", new[] { "--name", "name with space and quote","-x1" })] public static void Split_arguments(string command, string[] expectedArgs) { var args = command.SplitArgs(); @@ -426,17 +412,5 @@ public static IEnumerable UnParseDataHidden yield return new object[] { new Hidden_Option { HiddenOption = "hidden" }, false, "" }; } } -#if !SKIP_FSHARP - public static IEnumerable UnParseDataFSharpOption - { - get - { - yield return new object[] { new Options_With_FSharpOption(), "" }; - yield return new object[] { new Options_With_FSharpOption { FileName = FSharpOption.Some("myfile.bin") }, "--filename myfile.bin" }; - yield return new object[] { new Options_With_FSharpOption { Offset = FSharpOption.Some(123456789) }, "123456789" }; - yield return new object[] { new Options_With_FSharpOption { FileName = FSharpOption.Some("myfile.bin"), Offset = FSharpOption.Some(123456789) }, "--filename myfile.bin 123456789" }; - } - } -#endif } } diff --git a/tests/CommandLine.Tests/Unit/VerbAttributeTests.cs b/tests/CommandLine.Tests/Unit/VerbAttributeTests.cs index 386e3015..d3616c03 100644 --- a/tests/CommandLine.Tests/Unit/VerbAttributeTests.cs +++ b/tests/CommandLine.Tests/Unit/VerbAttributeTests.cs @@ -1,6 +1,7 @@ using System; using Xunit; +// ReSharper disable once CheckNamespace namespace CommandLine.Tests { //Test localization of VerbAttribute @@ -16,7 +17,7 @@ public static void VerbHelpText(string helpText, Type resourceType, string expec { TestVerbAttribute verbAttribute = new TestVerbAttribute { - HelpText = helpText, + HelpText = helpText, ResourceType = resourceType }; @@ -32,7 +33,7 @@ public void ThrowsHelpText(string helpText, Type resourceType) { TestVerbAttribute verbAttribute = new TestVerbAttribute { - HelpText = helpText, + HelpText = helpText, ResourceType = resourceType };