Skip to content

Commit

Permalink
cleanup: run code formatters and cleanups
Browse files Browse the repository at this point in the history
  • Loading branch information
natemcmaster committed Sep 13, 2020
1 parent 21a73b3 commit f160e87
Show file tree
Hide file tree
Showing 42 changed files with 167 additions and 225 deletions.
2 changes: 1 addition & 1 deletion src/CommandLineUtils/Abstractions/IValueParser{T}.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace McMaster.Extensions.CommandLineUtils.Abstractions
/// <summary>
/// A parser that can convert string into <typeparamref name="T" />.
/// </summary>
public interface IValueParser<T> : IValueParser
public interface IValueParser<out T> : IValueParser
{
/// <summary>
/// Parses the raw string value.
Expand Down
17 changes: 6 additions & 11 deletions src/CommandLineUtils/Abstractions/ValueParserProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,17 +75,12 @@ public IValueParser GetParser(Type type)
public IValueParser<T>? GetParser<T>()
{
var parser = GetParserImpl<T>();
if (parser == null)
return parser switch
{
return null;
}

if (parser is IValueParser<T> retVal)
{
return retVal;
}

return new GenericParserAdapter<T>(parser);
null => null,
IValueParser<T> retVal => retVal,
_ => new GenericParserAdapter<T>(parser)
};
}

internal IValueParser? GetParserImpl<T>()
Expand Down Expand Up @@ -191,7 +186,7 @@ private void SafeAdd(IValueParser parser, bool andReplace = false)
throw new ArgumentNullException(nameof(parser));
}

Type targetType = parser.TargetType;
var targetType = parser.TargetType;

if (targetType == null)
{
Expand Down
13 changes: 4 additions & 9 deletions src/CommandLineUtils/Attributes/AllowedValuesAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace McMaster.Extensions.CommandLineUtils
{
Expand All @@ -29,7 +30,7 @@ public AllowedValuesAttribute(params string[] allowedValues)
{
}

internal ReadOnlyCollection<string> AllowedValues => Array.AsReadOnly(this._allowedValues);
internal ReadOnlyCollection<string> AllowedValues => Array.AsReadOnly(_allowedValues);

/// <summary>
/// Initializes an instance of <see cref="AllowedValuesAttribute"/>.
Expand Down Expand Up @@ -73,15 +74,9 @@ public bool IgnoreCase
/// <inheritdoc />
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value is string str)
if (value is string str && _allowedValues.Any(t => str.Equals(t, Comparer)))
{
for (var i = 0; i < _allowedValues.Length; i++)
{
if (str.Equals(_allowedValues[i], Comparer))
{
return ValidationResult.Success;
}
}
return ValidationResult.Success;
}

return new ValidationResult(FormatErrorMessage(value as string));
Expand Down
15 changes: 5 additions & 10 deletions src/CommandLineUtils/Attributes/FilePathExistsAttributeBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,17 +55,12 @@ protected override ValidationResult IsValid(object value, ValidationContext vali

private static string GetDefaultErrorMessage(FilePathType filePathType)
{
if (filePathType == FilePathType.File)
return filePathType switch
{
return "The file '{0}' does not exist.";
}

if (filePathType == FilePathType.Directory)
{
return "The directory '{0}' does not exist.";
}

return "The file path '{0}' does not exist.";
FilePathType.File => "The file '{0}' does not exist.",
FilePathType.Directory => "The directory '{0}' does not exist.",
_ => "The file path '{0}' does not exist."
};
}
}
}
15 changes: 5 additions & 10 deletions src/CommandLineUtils/Attributes/FilePathNotExistsAttributeBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,17 +60,12 @@ protected override ValidationResult IsValid(object value, ValidationContext vali

private static string GetDefaultErrorMessage(FilePathType filePathType)
{
if (filePathType == FilePathType.File)
return filePathType switch
{
return "The file '{0}' already exists.";
}

if (filePathType == FilePathType.Directory)
{
return "The directory '{0}' already exists.";
}

return "The file path '{0}' already exists.";
FilePathType.File => "The file '{0}' already exists.",
FilePathType.Directory => "The directory '{0}' already exists.",
_ => "The file path '{0}' already exists."
};
}
}
}
7 changes: 2 additions & 5 deletions src/CommandLineUtils/Attributes/OptionAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace McMaster.Extensions.CommandLineUtils
/// Represents one or many command line option that is identified by flag proceeded by '-' or '--'.
/// Options are not positional. Compare to <see cref="ArgumentAttribute"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
[AttributeUsage(AttributeTargets.Property)]
public sealed class OptionAttribute : OptionAttributeBase
{
/// <summary>
Expand Down Expand Up @@ -88,10 +88,7 @@ internal CommandOption Configure(CommandLineApplication app, PropertyInfo prop)

Configure(option);

if (option.Description == null)
{
option.Description = prop.Name;
}
option.Description ??= prop.Name;

app.Options.Add(option);
return option;
Expand Down
2 changes: 1 addition & 1 deletion src/CommandLineUtils/Attributes/SubcommandAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace McMaster.Extensions.CommandLineUtils
/// <summary>
/// Represents a subcommand.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class SubcommandAttribute : Attribute
{
/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace McMaster.Extensions.CommandLineUtils
/// <summary>
/// Suppress <see cref="DefaultHelpOptionConvention"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly, Inherited = true)]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly)]
public sealed class SuppressDefaultHelpOptionAttribute : Attribute
{
}
Expand Down
4 changes: 2 additions & 2 deletions src/CommandLineUtils/CommandArgument{T}.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ public CommandArgument(IValueParser<T> valueParser)
void IInternalCommandParamOfT.Parse(CultureInfo culture)
{
_parsedValues.Clear();
for (int i = 0; i < Values.Count; i++)
foreach (var t in Values)
{
_parsedValues.Add(_valueParser.Parse(Name, Values[i], culture));
_parsedValues.Add(_valueParser.Parse(Name, t, culture));
}
}
}
Expand Down
68 changes: 20 additions & 48 deletions src/CommandLineUtils/CommandLineApplication.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ static CommandLineApplication()
private readonly HashSet<string> _names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private string? _primaryCommandName;
internal CommandLineContext _context;
private ParserConfig _parserConfig;
private readonly ParserConfig _parserConfig;
private IHelpTextGenerator _helpTextGenerator;
private CommandOption? _optionHelp;
private readonly Lazy<IServiceProvider> _services;
Expand Down Expand Up @@ -224,11 +224,9 @@ public CommandOption? OptionHelp
{
return _optionHelp;
}
if (Parent?.OptionHelp?.Inherited == true)
{
return Parent.OptionHelp;
}
return null;
return Parent?.OptionHelp?.Inherited == true
? Parent.OptionHelp
: null;
}
internal set => _optionHelp = value;
}
Expand All @@ -245,7 +243,7 @@ public CommandOption? OptionHelp
public List<CommandArgument> Arguments { get; private set; }

/// <summary>
/// When initialized when <see cref="UnrecognizedArgumentHandling"/> is <see cref="UnrecognizedArgumentHandling.StopParsingAndCollect" />,
/// When initialized when <see cref="UnrecognizedArgumentHandling"/> is <see cref="McMaster.Extensions.CommandLineUtils.UnrecognizedArgumentHandling.StopParsingAndCollect" />,
/// this will contain any unrecognized arguments.
/// </summary>
public List<string> RemainingArguments { get; private set; }
Expand Down Expand Up @@ -290,7 +288,7 @@ public UnrecognizedArgumentHandling UnrecognizedArgumentHandling
/// A response file contains additional arguments that will be treated as if they were passed in on the command line.
/// </para>
/// <para>
/// Defaults to <see cref="ResponseFileHandling.Disabled" />.
/// Defaults to <see cref="McMaster.Extensions.CommandLineUtils.ResponseFileHandling.Disabled" />.
/// </para>
/// <para>
/// Nested response false are not supported.
Expand Down Expand Up @@ -359,19 +357,16 @@ public char[] OptionNameValueSeparators
get => _parserConfig.OptionNameValueSeparators ?? Parent?.OptionNameValueSeparators ?? new[] { ' ', ':', '=' };
set
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
else if (value.Length == 0)
if (value.Length == 0)
{
throw new ArgumentException(Strings.IsEmptyArray, nameof(value));
}

_parserConfig.OptionNameValueSeparators = value;
}
}

internal bool OptionNameAndValueCanBeSpaceSeparated => Array.IndexOf(this.OptionNameValueSeparators, ' ') >= 0;
internal bool OptionNameAndValueCanBeSpaceSeparated => Array.IndexOf(OptionNameValueSeparators, ' ') >= 0;

/// <summary>
/// Gets the default value parser provider.
Expand Down Expand Up @@ -920,14 +915,9 @@ public CommandOption VersionOption(string template,
string? shortFormVersion,
string? longFormVersion = null)
{
if (longFormVersion == null)
{
return VersionOption(template, () => shortFormVersion);
}
else
{
return VersionOption(template, () => shortFormVersion, () => longFormVersion);
}
return longFormVersion == null
? VersionOption(template, () => shortFormVersion)
: VersionOption(template, () => shortFormVersion, () => longFormVersion);
}

#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
Expand Down Expand Up @@ -980,7 +970,7 @@ public virtual void ShowHint()
/// <param name="usePager">Use a console pager to display help text, if possible.</param>
public void ShowHelp(bool usePager)
{
CommandLineApplication? cmd = this;
var cmd = this;
while (cmd != null)
{
cmd.IsShowingInformation = true;
Expand Down Expand Up @@ -1015,7 +1005,7 @@ public virtual string GetHelpText()
/// </summary>
public void ShowVersion()
{
CommandLineApplication? cmd = this;
var cmd = this;
while (cmd != null)
{
cmd.IsShowingInformation = true;
Expand Down Expand Up @@ -1077,12 +1067,7 @@ public void ShowRootCommandFullNameAndVersion()

internal bool MatchesName(string name)
{
if (string.Equals(name, Name, StringComparison.OrdinalIgnoreCase))
{
return true;
}

return _names.Contains(name);
return string.Equals(name, Name, StringComparison.OrdinalIgnoreCase) || _names.Contains(name);
}

private sealed class Builder : IConventionBuilder
Expand Down Expand Up @@ -1113,17 +1098,7 @@ IConventionBuilder IConventionBuilder.AddConvention(IConvention convention)
/// <summary>
/// Gets a builder that can be used to apply conventions to
/// </summary>
public IConventionBuilder Conventions
{
get
{
if (_builder == null)
{
_builder = new Builder(this);
}
return _builder;
}
}
public IConventionBuilder Conventions => _builder ??= new Builder(this);

private protected virtual ConventionContext CreateConventionContext() => new ConventionContext(this, null);

Expand Down Expand Up @@ -1192,7 +1167,7 @@ public ServiceProvider(CommandLineApplication parent)
return _parent;
}

// prefer this type before AdditionalServces because it is common for service containers to automatically
// prefer this type before AdditionalServices because it is common for service containers to automatically
// create IEnumerable<T> to allow registration of multiple services
if (serviceType == typeof(IEnumerable<CommandOption>))
{
Expand All @@ -1219,13 +1194,10 @@ public ServiceProvider(CommandLineApplication parent)
return accessor.GetModel();
}

if (_parent.AdditionalServices != null)
var retVal = _parent.AdditionalServices?.GetService(serviceType);
if (retVal != null)
{
var retVal = _parent.AdditionalServices.GetService(serviceType);
if (retVal != null)
{
return retVal;
}
return retVal;
}

// Resolve this after AdditionalServices to support overriding IConsole from a custom service container
Expand Down
4 changes: 2 additions & 2 deletions src/CommandLineUtils/CommandOption.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,12 @@ internal CommandOption(CommandOptionType type)
}

/// <summary>
/// The short command line flag used to identify this option. On command line, this is preceeded by a single '-{ShortName}'.
/// The short command line flag used to identify this option. On command line, this is preceded by a single '-{ShortName}'.
/// </summary>
public string? ShortName { get; set; }

/// <summary>
/// The long command line flag used to identify this option. On command line, this is preceeded by a double dash: '--{LongName}'.
/// The long command line flag used to identify this option. On command line, this is preceded by a double dash: '--{LongName}'.
/// </summary>
public string? LongName { get; set; }

Expand Down
10 changes: 5 additions & 5 deletions src/CommandLineUtils/CommandOption{T}.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ public class CommandOption<T> : CommandOption, IInternalCommandParamOfT
private readonly IValueParser<T> _valueParser;

/// <summary>
/// Intializes a new instance of <see cref="CommandOption{T}" />
/// Initializes a new instance of <see cref="CommandOption{T}" />
/// </summary>
/// <param name="valueParser">The parser use to convert values into type of T.</param>
/// <param name="template">The option tempalte.</param>
/// <param name="optionType">The optiont type</param>
/// <param name="template">The option template.</param>
/// <param name="optionType">The option type</param>
public CommandOption(IValueParser<T> valueParser, string template, CommandOptionType optionType)
: base(template, optionType)
{
Expand All @@ -46,9 +46,9 @@ public CommandOption(IValueParser<T> valueParser, string template, CommandOption
void IInternalCommandParamOfT.Parse(CultureInfo culture)
{
_parsedValues.Clear();
for (int i = 0; i < Values.Count; i++)
foreach (var t in Values)
{
_parsedValues.Add(_valueParser.Parse(LongName ?? ShortName ?? SymbolName, Values[i], culture));
_parsedValues.Add(_valueParser.Parse(LongName ?? ShortName ?? SymbolName, t, culture));
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ private void ApplyImpl<TModel>(ConventionContext context)
{
if (constructors.Length == 0)
{
return () => throw new InvalidOperationException(Strings.NoAnyPublicConstuctorFound(typeof(TModel)));
return () => throw new InvalidOperationException(Strings.NoAnyPublicConstructorFound(typeof(TModel)));
}

foreach (var ctorCandidate in constructors.OrderByDescending(c => c.GetParameters().Length))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public virtual void Apply(ConventionContext context)
var setter = ReflectionHelper.GetPropertySetter(parentProp);
context.Application.OnParsingComplete(r =>
{
CommandLineApplication? subcommand = r.SelectedCommand;
var subcommand = r.SelectedCommand;
while (subcommand != null)
{
if (ReferenceEquals(context.Application, subcommand))
Expand Down
Loading

0 comments on commit f160e87

Please sign in to comment.