diff --git a/CliFx/ApplicationConfiguration.cs b/CliFx/ApplicationConfiguration.cs index bb9a2d47..1f0e4d76 100644 --- a/CliFx/ApplicationConfiguration.cs +++ b/CliFx/ApplicationConfiguration.cs @@ -29,10 +29,11 @@ public class ApplicationConfiguration public ApplicationConfiguration( IReadOnlyList commandTypes, bool isDebugModeAllowed, - bool isPreviewModeAllowed) + bool isPreviewModeAllowed + ) { CommandTypes = commandTypes; IsDebugModeAllowed = isDebugModeAllowed; IsPreviewModeAllowed = isPreviewModeAllowed; } -} \ No newline at end of file +} diff --git a/CliFx/ApplicationMetadata.cs b/CliFx/ApplicationMetadata.cs index 958dd025..7c3c8aea 100644 --- a/CliFx/ApplicationMetadata.cs +++ b/CliFx/ApplicationMetadata.cs @@ -32,11 +32,12 @@ public ApplicationMetadata( string title, string executableName, string version, - string? description) + string? description + ) { Title = title; ExecutableName = executableName; Version = version; Description = description; } -} \ No newline at end of file +} diff --git a/CliFx/Attributes/CommandAttribute.cs b/CliFx/Attributes/CommandAttribute.cs index 87efd416..6c97f95a 100644 --- a/CliFx/Attributes/CommandAttribute.cs +++ b/CliFx/Attributes/CommandAttribute.cs @@ -35,7 +35,5 @@ public CommandAttribute(string name) /// /// Initializes an instance of . /// - public CommandAttribute() - { - } -} \ No newline at end of file + public CommandAttribute() { } +} diff --git a/CliFx/Attributes/CommandOptionAttribute.cs b/CliFx/Attributes/CommandOptionAttribute.cs index 3662cd16..f4c43438 100644 --- a/CliFx/Attributes/CommandOptionAttribute.cs +++ b/CliFx/Attributes/CommandOptionAttribute.cs @@ -81,23 +81,17 @@ private CommandOptionAttribute(string? name, char? shortName) /// Initializes an instance of . /// public CommandOptionAttribute(string name, char shortName) - : this(name, (char?)shortName) - { - } + : this(name, (char?)shortName) { } /// /// Initializes an instance of . /// public CommandOptionAttribute(string name) - : this(name, null) - { - } + : this(name, null) { } /// /// Initializes an instance of . /// public CommandOptionAttribute(char shortName) - : this(null, (char?)shortName) - { - } -} \ No newline at end of file + : this(null, (char?)shortName) { } +} diff --git a/CliFx/Attributes/CommandParameterAttribute.cs b/CliFx/Attributes/CommandParameterAttribute.cs index 54cfd315..3dcbc177 100644 --- a/CliFx/Attributes/CommandParameterAttribute.cs +++ b/CliFx/Attributes/CommandParameterAttribute.cs @@ -70,4 +70,4 @@ public CommandParameterAttribute(int order) { Order = order; } -} \ No newline at end of file +} diff --git a/CliFx/CliApplication.cs b/CliFx/CliApplication.cs index 94f0f1c1..c52b8c0a 100644 --- a/CliFx/CliApplication.cs +++ b/CliFx/CliApplication.cs @@ -41,7 +41,8 @@ public CliApplication( ApplicationMetadata metadata, ApplicationConfiguration configuration, IConsole console, - ITypeActivator typeActivator) + ITypeActivator typeActivator + ) { Metadata = metadata; Configuration = configuration; @@ -58,9 +59,11 @@ private bool IsPreviewModeEnabled(CommandInput commandInput) => Configuration.IsPreviewModeAllowed && commandInput.IsPreviewDirectiveSpecified; private bool ShouldShowHelpText(CommandSchema commandSchema, CommandInput commandInput) => - commandSchema.IsHelpOptionAvailable && commandInput.IsHelpOptionSpecified || + commandSchema.IsHelpOptionAvailable && commandInput.IsHelpOptionSpecified + || // Show help text also if the fallback default command is executed without any arguments - commandSchema == FallbackDefaultCommand.Schema && !commandInput.HasArguments; + commandSchema == FallbackDefaultCommand.Schema + && !commandInput.HasArguments; private bool ShouldShowVersionText(CommandSchema commandSchema, CommandInput commandInput) => commandSchema.IsVersionOptionAvailable && commandInput.IsVersionOptionSpecified; @@ -83,7 +86,10 @@ private async ValueTask PromptDebuggerAsync() await Task.Delay(100); } - private async ValueTask RunAsync(ApplicationSchema applicationSchema, CommandInput commandInput) + private async ValueTask RunAsync( + ApplicationSchema applicationSchema, + CommandInput commandInput + ) { // Console colors may have already been overridden by the parent process, // so we need to reset it to make sure that everything we write looks properly. @@ -104,21 +110,25 @@ private async ValueTask RunAsync(ApplicationSchema applicationSchema, Comma // Try to get the command schema that matches the input var commandSchema = - (!string.IsNullOrWhiteSpace(commandInput.CommandName) - // If the command name is specified, try to find the command by name. - // This should always succeed, because the input parsing relies on - // the list of available command names. - ? applicationSchema.TryFindCommand(commandInput.CommandName) - // Otherwise, try to find the default command - : applicationSchema.TryFindDefaultCommand()) ?? + ( + !string.IsNullOrWhiteSpace(commandInput.CommandName) + // If the command name is specified, try to find the command by name. + // This should always succeed, because the input parsing relies on + // the list of available command names. + ? applicationSchema.TryFindCommand(commandInput.CommandName) + // Otherwise, try to find the default command + : applicationSchema.TryFindDefaultCommand() + ) + ?? // If a valid command was not found, use the fallback default command. // This is only used as a stub to show the help text. FallbackDefaultCommand.Schema; // Initialize an instance of the command type - var commandInstance = commandSchema == FallbackDefaultCommand.Schema - ? new FallbackDefaultCommand() // bypass the activator - : _typeActivator.CreateInstance(commandSchema.Type); + var commandInstance = + commandSchema == FallbackDefaultCommand.Schema + ? new FallbackDefaultCommand() // bypass the activator + : _typeActivator.CreateInstance(commandSchema.Type); // Assemble the help context var helpContext = new HelpContext( @@ -178,7 +188,8 @@ private async ValueTask RunAsync(ApplicationSchema applicationSchema, Comma /// public async ValueTask RunAsync( IReadOnlyList commandLineArguments, - IReadOnlyDictionary environmentVariables) + IReadOnlyDictionary environmentVariables + ) { try { @@ -213,16 +224,17 @@ public async ValueTask RunAsync( /// When running WITHOUT the debugger attached (i.e. in production), this method swallows /// all exceptions and reports them to the console. /// - public async ValueTask RunAsync(IReadOnlyList commandLineArguments) => await RunAsync( - commandLineArguments, - Environment - .GetEnvironmentVariables() - .ToDictionary( - RuntimeInformation.IsOSPlatform(OSPlatform.Windows) - ? StringComparer.OrdinalIgnoreCase - : StringComparer.Ordinal - ) - ); + public async ValueTask RunAsync(IReadOnlyList commandLineArguments) => + await RunAsync( + commandLineArguments, + Environment + .GetEnvironmentVariables() + .ToDictionary( + RuntimeInformation.IsOSPlatform(OSPlatform.Windows) + ? StringComparer.OrdinalIgnoreCase + : StringComparer.Ordinal + ) + ); /// /// Runs the application. @@ -233,9 +245,11 @@ public async ValueTask RunAsync(IReadOnlyList commandLineArguments) /// When running WITHOUT the debugger attached (i.e. in production), this method swallows /// all exceptions and reports them to the console. /// - public async ValueTask RunAsync() => await RunAsync( - Environment.GetCommandLineArgs() - .Skip(1) // first element is the file path - .ToArray() - ); -} \ No newline at end of file + public async ValueTask RunAsync() => + await RunAsync( + Environment + .GetCommandLineArgs() + .Skip(1) // first element is the file path + .ToArray() + ); +} diff --git a/CliFx/CliApplicationBuilder.cs b/CliFx/CliApplicationBuilder.cs index 7d37b7e4..5bea678d 100644 --- a/CliFx/CliApplicationBuilder.cs +++ b/CliFx/CliApplicationBuilder.cs @@ -39,8 +39,8 @@ public CliApplicationBuilder AddCommand(Type commandType) /// /// Adds a command to the application. /// - public CliApplicationBuilder AddCommand() where TCommand : ICommand => - AddCommand(typeof(TCommand)); + public CliApplicationBuilder AddCommand() + where TCommand : ICommand => AddCommand(typeof(TCommand)); /// /// Adds multiple commands to the application. @@ -62,7 +62,9 @@ public CliApplicationBuilder AddCommands(IEnumerable commandTypes) /// public CliApplicationBuilder AddCommandsFrom(Assembly commandAssembly) { - foreach (var commandType in commandAssembly.ExportedTypes.Where(CommandSchema.IsCommandType)) + foreach ( + var commandType in commandAssembly.ExportedTypes.Where(CommandSchema.IsCommandType) + ) AddCommand(commandType); return this; @@ -90,7 +92,8 @@ public CliApplicationBuilder AddCommandsFrom(IEnumerable commandAssemb /// This method looks for public non-abstract classes that implement /// and are annotated by . /// - public CliApplicationBuilder AddCommandsFromThisAssembly() => AddCommandsFrom(Assembly.GetCallingAssembly()); + public CliApplicationBuilder AddCommandsFromThisAssembly() => + AddCommandsFrom(Assembly.GetCallingAssembly()); /// /// Specifies whether debug mode (enabled with the [debug] directive) is allowed in the application. @@ -190,8 +193,9 @@ public CliApplicationBuilder UseTypeActivator(IServiceProvider serviceProvider) /// This method takes a delegate that receives the list of all added command types, so that you can /// easily register them with the service provider. /// - public CliApplicationBuilder UseTypeActivator(Func, IServiceProvider> getServiceProvider) => - UseTypeActivator(getServiceProvider(_commandTypes.ToArray())); + public CliApplicationBuilder UseTypeActivator( + Func, IServiceProvider> getServiceProvider + ) => UseTypeActivator(getServiceProvider(_commandTypes.ToArray())); /// /// Creates a configured instance of . @@ -228,8 +232,8 @@ private static string GetDefaultTitle() if (string.IsNullOrWhiteSpace(entryAssemblyName)) { throw new InvalidOperationException( - "Failed to infer the default application title. " + - $"Please specify it explicitly using `{nameof(SetTitle)}()`." + "Failed to infer the default application title. " + + $"Please specify it explicitly using `{nameof(SetTitle)}()`." ); } @@ -241,11 +245,14 @@ private static string GetDefaultExecutableName() var entryAssemblyFilePath = EnvironmentEx.EntryAssembly?.Location; var processFilePath = EnvironmentEx.ProcessPath; - if (string.IsNullOrWhiteSpace(entryAssemblyFilePath) || string.IsNullOrWhiteSpace(processFilePath)) + if ( + string.IsNullOrWhiteSpace(entryAssemblyFilePath) + || string.IsNullOrWhiteSpace(processFilePath) + ) { throw new InvalidOperationException( - "Failed to infer the default application executable name. " + - $"Please specify it explicitly using `{nameof(SetExecutableName)}()`." + "Failed to infer the default application executable name. " + + $"Please specify it explicitly using `{nameof(SetExecutableName)}()`." ); } @@ -258,8 +265,13 @@ private static string GetDefaultExecutableName() // If the process path has the same name and parent directory as the entry assembly path, // but different extension, it's a framework-dependent .NET Core app launched through the apphost. - if (PathEx.AreEqual(Path.ChangeExtension(entryAssemblyFilePath, "exe"), processFilePath) || - PathEx.AreEqual(Path.GetFileNameWithoutExtension(entryAssemblyFilePath), processFilePath)) + if ( + PathEx.AreEqual(Path.ChangeExtension(entryAssemblyFilePath, "exe"), processFilePath) + || PathEx.AreEqual( + Path.GetFileNameWithoutExtension(entryAssemblyFilePath), + processFilePath + ) + ) { return Path.GetFileNameWithoutExtension(entryAssemblyFilePath); } @@ -274,11 +286,11 @@ private static string GetDefaultVersionText() if (entryAssemblyVersion is null) { throw new InvalidOperationException( - "Failed to infer the default application version. " + - $"Please specify it explicitly using `{nameof(SetVersion)}()`." + "Failed to infer the default application version. " + + $"Please specify it explicitly using `{nameof(SetVersion)}()`." ); } return "v" + entryAssemblyVersion.ToSemanticString(); } -} \ No newline at end of file +} diff --git a/CliFx/CommandBinder.cs b/CliFx/CommandBinder.cs index 44bea96e..8e0a12de 100644 --- a/CliFx/CommandBinder.cs +++ b/CliFx/CommandBinder.cs @@ -27,7 +27,9 @@ public CommandBinder(ITypeActivator typeActivator) // Custom converter if (memberSchema.ConverterType is not null) { - var converter = _typeActivator.CreateInstance(memberSchema.ConverterType); + var converter = _typeActivator.CreateInstance( + memberSchema.ConverterType + ); return converter.Convert(rawValue); } @@ -88,7 +90,10 @@ public CommandBinder(ITypeActivator typeActivator) var parseMethodWithFormatProvider = targetType.TryGetStaticParseMethod(true); if (parseMethodWithFormatProvider is not null) { - return parseMethodWithFormatProvider.Invoke(null, new object?[] { rawValue, _formatProvider }); + return parseMethodWithFormatProvider.Invoke( + null, + new object?[] { rawValue, _formatProvider } + ); } // String-parseable (without IFormatProvider) @@ -111,7 +116,8 @@ There is no known way to convert a string value into an instance of type `{targe IMemberSchema memberSchema, IReadOnlyList rawValues, Type targetEnumerableType, - Type targetElementType) + Type targetElementType + ) { var array = rawValues .Select(v => ConvertSingle(memberSchema, v, targetElementType)) @@ -146,8 +152,11 @@ There is no known way to convert an array of `{targetElementType.FullName}` into try { // Non-scalar - var enumerableUnderlyingType = memberSchema.Property.Type.TryGetEnumerableUnderlyingType(); - if (enumerableUnderlyingType is not null && memberSchema.Property.Type != typeof(string)) + var enumerableUnderlyingType = + memberSchema.Property.Type.TryGetEnumerableUnderlyingType(); + if ( + enumerableUnderlyingType is not null && memberSchema.Property.Type != typeof(string) + ) { return ConvertMultiple( memberSchema, @@ -219,7 +228,11 @@ private void ValidateMember(IMemberSchema memberSchema, object? convertedValue) } } - private void BindMember(IMemberSchema memberSchema, ICommand commandInstance, IReadOnlyList rawValues) + private void BindMember( + IMemberSchema memberSchema, + ICommand commandInstance, + IReadOnlyList rawValues + ) { var convertedValue = ConvertMember(memberSchema, rawValues); ValidateMember(memberSchema, convertedValue); @@ -227,11 +240,17 @@ private void BindMember(IMemberSchema memberSchema, ICommand commandInstance, IR memberSchema.Property.SetValue(commandInstance, convertedValue); } - private void BindParameters(CommandInput commandInput, CommandSchema commandSchema, ICommand commandInstance) + private void BindParameters( + CommandInput commandInput, + CommandSchema commandSchema, + ICommand commandInstance + ) { // Ensure there are no unexpected parameters and that all parameters are provided var remainingParameterInputs = commandInput.Parameters.ToList(); - var remainingRequiredParameterSchemas = commandSchema.Parameters.Where(p => p.IsRequired).ToList(); + var remainingRequiredParameterSchemas = commandSchema.Parameters + .Where(p => p.IsRequired) + .ToList(); var position = 0; @@ -290,22 +309,27 @@ Missing required parameter(s): } } - private void BindOptions(CommandInput commandInput, CommandSchema commandSchema, ICommand commandInstance) + private void BindOptions( + CommandInput commandInput, + CommandSchema commandSchema, + ICommand commandInstance + ) { // Ensure there are no unrecognized options and that all required options are set var remainingOptionInputs = commandInput.Options.ToList(); - var remainingRequiredOptionSchemas = commandSchema.Options.Where(o => o.IsRequired).ToList(); + var remainingRequiredOptionSchemas = commandSchema.Options + .Where(o => o.IsRequired) + .ToList(); foreach (var optionSchema in commandSchema.Options) { - var optionInputs = commandInput - .Options + var optionInputs = commandInput.Options .Where(o => optionSchema.MatchesIdentifier(o.Identifier)) .ToArray(); - var environmentVariableInput = commandInput - .EnvironmentVariables - .FirstOrDefault(e => optionSchema.MatchesEnvironmentVariable(e.Name)); + var environmentVariableInput = commandInput.EnvironmentVariables.FirstOrDefault( + e => optionSchema.MatchesEnvironmentVariable(e.Name) + ); // Direct input if (optionInputs.Any()) @@ -361,9 +385,13 @@ Missing required option(s): } } - public void Bind(CommandInput commandInput, CommandSchema commandSchema, ICommand commandInstance) + public void Bind( + CommandInput commandInput, + CommandSchema commandSchema, + ICommand commandInstance + ) { BindParameters(commandInput, commandSchema, commandInstance); BindOptions(commandInput, commandSchema, commandInstance); } -} \ No newline at end of file +} diff --git a/CliFx/Exceptions/CliFxException.cs b/CliFx/Exceptions/CliFxException.cs index 6661e6c1..cb5f30c7 100644 --- a/CliFx/Exceptions/CliFxException.cs +++ b/CliFx/Exceptions/CliFxException.cs @@ -32,7 +32,8 @@ public CliFxException( string message, int exitCode = DefaultExitCode, bool showHelp = false, - Exception? innerException = null) + Exception? innerException = null + ) : base(message, innerException) { HasCustomMessage = !string.IsNullOrWhiteSpace(message); @@ -45,11 +46,13 @@ public partial class CliFxException { // Internal errors don't show help because they're meant for the developer and // not the end-user of the application. - internal static CliFxException InternalError(string message, Exception? innerException = null) => - new(message, DefaultExitCode, false, innerException); + internal static CliFxException InternalError( + string message, + Exception? innerException = null + ) => new(message, DefaultExitCode, false, innerException); // User errors are typically caused by invalid input and they're meant for the end-user, // so we want to show help. internal static CliFxException UserError(string message, Exception? innerException = null) => new(message, DefaultExitCode, true, innerException); -} \ No newline at end of file +} diff --git a/CliFx/Exceptions/CommandException.cs b/CliFx/Exceptions/CommandException.cs index 558c1fe9..3d26abbf 100644 --- a/CliFx/Exceptions/CommandException.cs +++ b/CliFx/Exceptions/CommandException.cs @@ -15,8 +15,7 @@ public CommandException( string message, int exitCode = DefaultExitCode, bool showHelp = false, - Exception? innerException = null) - : base(message, exitCode, showHelp, innerException) - { - } -} \ No newline at end of file + Exception? innerException = null + ) + : base(message, exitCode, showHelp, innerException) { } +} diff --git a/CliFx/Extensibility/BindingConverter.cs b/CliFx/Extensibility/BindingConverter.cs index 5af02508..b0b8a97e 100644 --- a/CliFx/Extensibility/BindingConverter.cs +++ b/CliFx/Extensibility/BindingConverter.cs @@ -17,4 +17,4 @@ public abstract class BindingConverter : IBindingConverter public abstract T Convert(string? rawValue); object? IBindingConverter.Convert(string? rawValue) => Convert(rawValue); -} \ No newline at end of file +} diff --git a/CliFx/Extensibility/BindingValidationError.cs b/CliFx/Extensibility/BindingValidationError.cs index c5f5df6e..9bd02045 100644 --- a/CliFx/Extensibility/BindingValidationError.cs +++ b/CliFx/Extensibility/BindingValidationError.cs @@ -14,4 +14,4 @@ public class BindingValidationError /// Initializes an instance of . /// public BindingValidationError(string message) => Message = message; -} \ No newline at end of file +} diff --git a/CliFx/Extensibility/BindingValidator.cs b/CliFx/Extensibility/BindingValidator.cs index 08567370..9b3e394f 100644 --- a/CliFx/Extensibility/BindingValidator.cs +++ b/CliFx/Extensibility/BindingValidator.cs @@ -32,4 +32,4 @@ public abstract class BindingValidator : IBindingValidator public abstract BindingValidationError? Validate(T? value); BindingValidationError? IBindingValidator.Validate(object? value) => Validate((T?)value); -} \ No newline at end of file +} diff --git a/CliFx/FallbackDefaultCommand.cs b/CliFx/FallbackDefaultCommand.cs index c28c2a5f..c55a89e5 100644 --- a/CliFx/FallbackDefaultCommand.cs +++ b/CliFx/FallbackDefaultCommand.cs @@ -17,4 +17,4 @@ internal class FallbackDefaultCommand : ICommand // Never actually executed [ExcludeFromCodeCoverage] public ValueTask ExecuteAsync(IConsole console) => default; -} \ No newline at end of file +} diff --git a/CliFx/Formatting/CommandInputConsoleFormatter.cs b/CliFx/Formatting/CommandInputConsoleFormatter.cs index 19077df8..703f0d2e 100644 --- a/CliFx/Formatting/CommandInputConsoleFormatter.cs +++ b/CliFx/Formatting/CommandInputConsoleFormatter.cs @@ -7,9 +7,7 @@ namespace CliFx.Formatting; internal class CommandInputConsoleFormatter : ConsoleFormatter { public CommandInputConsoleFormatter(ConsoleWriter consoleWriter) - : base(consoleWriter) - { - } + : base(consoleWriter) { } private void WriteCommandLineArguments(CommandInput commandInput) { @@ -92,6 +90,8 @@ public void WriteCommandInput(CommandInput commandInput) internal static class CommandInputConsoleFormatterExtensions { - public static void WriteCommandInput(this ConsoleWriter consoleWriter, CommandInput commandInput) => - new CommandInputConsoleFormatter(consoleWriter).WriteCommandInput(commandInput); -} \ No newline at end of file + public static void WriteCommandInput( + this ConsoleWriter consoleWriter, + CommandInput commandInput + ) => new CommandInputConsoleFormatter(consoleWriter).WriteCommandInput(commandInput); +} diff --git a/CliFx/Formatting/ConsoleFormatter.cs b/CliFx/Formatting/ConsoleFormatter.cs index 9f1463f6..c4f49259 100644 --- a/CliFx/Formatting/ConsoleFormatter.cs +++ b/CliFx/Formatting/ConsoleFormatter.cs @@ -12,8 +12,7 @@ internal class ConsoleFormatter public bool IsEmpty => _column == 0 && _row == 0; - public ConsoleFormatter(ConsoleWriter consoleWriter) => - _consoleWriter = consoleWriter; + public ConsoleFormatter(ConsoleWriter consoleWriter) => _consoleWriter = consoleWriter; public void Write(string? value) { @@ -71,4 +70,4 @@ public void WriteColumnMargin(int columnSize = 20, int offsetSize = 2) else WriteHorizontalMargin(offsetSize); } -} \ No newline at end of file +} diff --git a/CliFx/Formatting/ExceptionConsoleFormatter.cs b/CliFx/Formatting/ExceptionConsoleFormatter.cs index f4bf004a..2be312b1 100644 --- a/CliFx/Formatting/ExceptionConsoleFormatter.cs +++ b/CliFx/Formatting/ExceptionConsoleFormatter.cs @@ -10,9 +10,7 @@ namespace CliFx.Formatting; internal class ExceptionConsoleFormatter : ConsoleFormatter { public ExceptionConsoleFormatter(ConsoleWriter consoleWriter) - : base(consoleWriter) - { - } + : base(consoleWriter) { } private void WriteStackFrame(StackFrame stackFrame, int indentLevel) { @@ -126,4 +124,4 @@ internal static class ExceptionConsoleFormatterExtensions { public static void WriteException(this ConsoleWriter consoleWriter, Exception exception) => new ExceptionConsoleFormatter(consoleWriter).WriteException(exception); -} \ No newline at end of file +} diff --git a/CliFx/Formatting/HelpConsoleFormatter.cs b/CliFx/Formatting/HelpConsoleFormatter.cs index e7b0bda9..7cdac861 100644 --- a/CliFx/Formatting/HelpConsoleFormatter.cs +++ b/CliFx/Formatting/HelpConsoleFormatter.cs @@ -74,9 +74,9 @@ private void WriteCommandUsage() // Parameters foreach (var parameter in _context.CommandSchema.Parameters.OrderBy(p => p.Order)) { - Write(ConsoleColor.DarkCyan, parameter.Property.IsScalar() - ? $"<{parameter.Name}>" - : $"<{parameter.Name}...>" + Write( + ConsoleColor.DarkCyan, + parameter.Property.IsScalar() ? $"<{parameter.Name}>" : $"<{parameter.Name}...>" ); Write(' '); } @@ -84,16 +84,15 @@ private void WriteCommandUsage() // Required options foreach (var option in _context.CommandSchema.Options.Where(o => o.IsRequired)) { - Write(ConsoleColor.Yellow, !string.IsNullOrWhiteSpace(option.Name) - ? $"--{option.Name}" - : $"-{option.ShortName}" + Write( + ConsoleColor.Yellow, + !string.IsNullOrWhiteSpace(option.Name) + ? $"--{option.Name}" + : $"-{option.ShortName}" ); Write(' '); - Write(ConsoleColor.White, option.Property.IsScalar() - ? "" - : "" - ); + Write(ConsoleColor.White, option.Property.IsScalar() ? "" : ""); Write(' '); } @@ -107,9 +106,9 @@ private void WriteCommandUsage() } // Child command usage - var childCommandSchemas = _context - .ApplicationSchema - .GetChildCommands(_context.CommandSchema.Name); + var childCommandSchemas = _context.ApplicationSchema.GetChildCommands( + _context.CommandSchema.Name + ); if (childCommandSchemas.Any()) { @@ -224,7 +223,9 @@ private void WriteCommandOptions() WriteHeader("Options"); - foreach (var optionSchema in _context.CommandSchema.Options.OrderByDescending(o => o.IsRequired)) + foreach ( + var optionSchema in _context.CommandSchema.Options.OrderByDescending(o => o.IsRequired) + ) { if (optionSchema.IsRequired) { @@ -320,8 +321,7 @@ private void WriteDefaultValue(IMemberSchema schema) if (defaultValue is not string && defaultValue is IEnumerable defaultValues) { var elementType = - defaultValues.GetType().TryGetEnumerableUnderlyingType() ?? - typeof(object); + defaultValues.GetType().TryGetEnumerableUnderlyingType() ?? typeof(object); if (elementType.IsToStringOverriden()) { @@ -365,8 +365,7 @@ private void WriteDefaultValue(IMemberSchema schema) private void WriteCommandChildren() { - var childCommandSchemas = _context - .ApplicationSchema + var childCommandSchemas = _context.ApplicationSchema .GetChildCommands(_context.CommandSchema.Name) .OrderBy(a => a.Name, StringComparer.Ordinal) .ToArray(); @@ -386,10 +385,7 @@ private void WriteCommandChildren() Write( ConsoleColor.Cyan, // Relative to current command - childCommandSchema - .Name? - .Substring(_context.CommandSchema.Name?.Length ?? 0) - .Trim() + childCommandSchema.Name?.Substring(_context.CommandSchema.Name?.Length ?? 0).Trim() ); WriteColumnMargin(); @@ -402,8 +398,7 @@ private void WriteCommandChildren() } // Child commands of child command - var grandChildCommandSchemas = _context - .ApplicationSchema + var grandChildCommandSchemas = _context.ApplicationSchema .GetChildCommands(childCommandSchema.Name) .OrderBy(c => c.Name, StringComparer.Ordinal) .ToArray(); @@ -427,9 +422,8 @@ private void WriteCommandChildren() Write( ConsoleColor.Cyan, // Relative to current command (not the parent) - grandChildCommandSchema - .Name? - .Substring(_context.CommandSchema.Name?.Length ?? 0) + grandChildCommandSchema.Name + ?.Substring(_context.CommandSchema.Name?.Length ?? 0) .Trim() ); } @@ -468,4 +462,4 @@ internal static class HelpConsoleFormatterExtensions { public static void WriteHelpText(this ConsoleWriter consoleWriter, HelpContext context) => new HelpConsoleFormatter(consoleWriter, context).WriteHelpText(); -} \ No newline at end of file +} diff --git a/CliFx/Formatting/HelpContext.cs b/CliFx/Formatting/HelpContext.cs index ece079ae..6cb66b79 100644 --- a/CliFx/Formatting/HelpContext.cs +++ b/CliFx/Formatting/HelpContext.cs @@ -17,11 +17,12 @@ public HelpContext( ApplicationMetadata applicationMetadata, ApplicationSchema applicationSchema, CommandSchema commandSchema, - IReadOnlyDictionary commandDefaultValues) + IReadOnlyDictionary commandDefaultValues + ) { ApplicationMetadata = applicationMetadata; ApplicationSchema = applicationSchema; CommandSchema = commandSchema; CommandDefaultValues = commandDefaultValues; } -} \ No newline at end of file +} diff --git a/CliFx/ICommand.cs b/CliFx/ICommand.cs index ec2f856c..11bf30f7 100644 --- a/CliFx/ICommand.cs +++ b/CliFx/ICommand.cs @@ -16,4 +16,4 @@ public interface ICommand /// return default; /// ValueTask ExecuteAsync(IConsole console); -} \ No newline at end of file +} diff --git a/CliFx/Infrastructure/ConsoleReader.cs b/CliFx/Infrastructure/ConsoleReader.cs index 9d7336a2..7d2aa5bc 100644 --- a/CliFx/Infrastructure/ConsoleReader.cs +++ b/CliFx/Infrastructure/ConsoleReader.cs @@ -31,9 +31,7 @@ public ConsoleReader(IConsole console, Stream stream, Encoding encoding) /// Initializes an instance of . /// public ConsoleReader(IConsole console, Stream stream) - : this(console, stream, System.Console.InputEncoding) - { - } + : this(console, stream, System.Console.InputEncoding) { } // The following overrides are required to establish thread-safe behavior // in methods deriving from StreamReader. @@ -99,8 +97,6 @@ public override Task ReadToEndAsync() => public partial class ConsoleReader { - internal static ConsoleReader Create(IConsole console, Stream stream) => new( - console, - Stream.Synchronized(stream) - ); -} \ No newline at end of file + internal static ConsoleReader Create(IConsole console, Stream stream) => + new(console, Stream.Synchronized(stream)); +} diff --git a/CliFx/Infrastructure/ConsoleWriter.cs b/CliFx/Infrastructure/ConsoleWriter.cs index 1138a7da..444f3c1b 100644 --- a/CliFx/Infrastructure/ConsoleWriter.cs +++ b/CliFx/Infrastructure/ConsoleWriter.cs @@ -32,16 +32,15 @@ public ConsoleWriter(IConsole console, Stream stream, Encoding encoding) /// Initializes an instance of . /// public ConsoleWriter(IConsole console, Stream stream) - : this(console, stream, System.Console.OutputEncoding) - { - } + : this(console, stream, System.Console.OutputEncoding) { } // The following overrides are required to establish thread-safe behavior // in methods deriving from StreamWriter. /// [ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)] - public override void Write(char[] buffer, int index, int count) => base.Write(buffer, index, count); + public override void Write(char[] buffer, int index, int count) => + base.Write(buffer, index, count); /// [ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)] @@ -272,8 +271,6 @@ public override Task FlushAsync() public partial class ConsoleWriter { - internal static ConsoleWriter Create(IConsole console, Stream stream) => new( - console, - Stream.Synchronized(stream) - ) {AutoFlush = true}; -} \ No newline at end of file + internal static ConsoleWriter Create(IConsole console, Stream stream) => + new(console, Stream.Synchronized(stream)) { AutoFlush = true }; +} diff --git a/CliFx/Infrastructure/DefaultTypeActivator.cs b/CliFx/Infrastructure/DefaultTypeActivator.cs index 9a27b779..fb7d8054 100644 --- a/CliFx/Infrastructure/DefaultTypeActivator.cs +++ b/CliFx/Infrastructure/DefaultTypeActivator.cs @@ -29,4 +29,4 @@ public object CreateInstance(Type type) ); } } -} \ No newline at end of file +} diff --git a/CliFx/Infrastructure/DelegateTypeActivator.cs b/CliFx/Infrastructure/DelegateTypeActivator.cs index e5d4e67d..7096184c 100644 --- a/CliFx/Infrastructure/DelegateTypeActivator.cs +++ b/CliFx/Infrastructure/DelegateTypeActivator.cs @@ -34,4 +34,4 @@ public object CreateInstance(Type type) return instance; } -} \ No newline at end of file +} diff --git a/CliFx/Infrastructure/FakeConsole.cs b/CliFx/Infrastructure/FakeConsole.cs index 4947b5ce..2ef7622c 100644 --- a/CliFx/Infrastructure/FakeConsole.cs +++ b/CliFx/Infrastructure/FakeConsole.cs @@ -66,8 +66,8 @@ public ConsoleKeyInfo ReadKey(bool intercept = false) => _keys.TryDequeue(out var key) ? key : throw new InvalidOperationException( - "Cannot read key because there are no key presses enqueued. " + - $"Use the `{nameof(EnqueueKey)}(...)` method to simulate a key press." + "Cannot read key because there are no key presses enqueued. " + + $"Use the `{nameof(EnqueueKey)}(...)` method to simulate a key press." ); /// @@ -83,9 +83,7 @@ public void ResetColor() } /// - public void Clear() - { - } + public void Clear() { } /// public CancellationToken RegisterCancellationHandler() => _cancellationTokenSource.Token; @@ -112,4 +110,4 @@ public void RequestCancellation(TimeSpan? delay = null) /// public virtual void Dispose() => _cancellationTokenSource.Dispose(); -} \ No newline at end of file +} diff --git a/CliFx/Infrastructure/FakeInMemoryConsole.cs b/CliFx/Infrastructure/FakeInMemoryConsole.cs index 732ca591..daac26d0 100644 --- a/CliFx/Infrastructure/FakeInMemoryConsole.cs +++ b/CliFx/Infrastructure/FakeInMemoryConsole.cs @@ -25,9 +25,7 @@ private FakeInMemoryConsole(MemoryStream input, MemoryStream output, MemoryStrea /// Initializes an instance of . /// public FakeInMemoryConsole() - : this(new MemoryStream(), new MemoryStream(), new MemoryStream()) - { - } + : this(new MemoryStream(), new MemoryStream(), new MemoryStream()) { } /// /// Writes data to the input stream. @@ -51,9 +49,7 @@ public void WriteInput(byte[] data) /// /// Writes data to the input stream. /// - public void WriteInput(string data) => WriteInput( - Input.CurrentEncoding.GetBytes(data) - ); + public void WriteInput(string data) => WriteInput(Input.CurrentEncoding.GetBytes(data)); /// /// Reads the data written to the output stream. @@ -98,4 +94,4 @@ public override void Dispose() base.Dispose(); } -} \ No newline at end of file +} diff --git a/CliFx/Infrastructure/IConsole.cs b/CliFx/Infrastructure/IConsole.cs index 6713ea00..32e10716 100644 --- a/CliFx/Infrastructure/IConsole.cs +++ b/CliFx/Infrastructure/IConsole.cs @@ -112,7 +112,10 @@ public static class ConsoleExtensions /// Sets the specified foreground color and returns an /// that will reset the color back to its previous value upon disposal. /// - public static IDisposable WithForegroundColor(this IConsole console, ConsoleColor foregroundColor) + public static IDisposable WithForegroundColor( + this IConsole console, + ConsoleColor foregroundColor + ) { var lastColor = console.ForegroundColor; console.ForegroundColor = foregroundColor; @@ -124,7 +127,10 @@ public static IDisposable WithForegroundColor(this IConsole console, ConsoleColo /// Sets the specified background color and returns an /// that will reset the color back to its previous value upon disposal. /// - public static IDisposable WithBackgroundColor(this IConsole console, ConsoleColor backgroundColor) + public static IDisposable WithBackgroundColor( + this IConsole console, + ConsoleColor backgroundColor + ) { var lastColor = console.BackgroundColor; console.BackgroundColor = backgroundColor; @@ -139,9 +145,10 @@ public static IDisposable WithBackgroundColor(this IConsole console, ConsoleColo public static IDisposable WithColors( this IConsole console, ConsoleColor foregroundColor, - ConsoleColor backgroundColor) => + ConsoleColor backgroundColor + ) => Disposable.Merge( console.WithForegroundColor(foregroundColor), console.WithBackgroundColor(backgroundColor) ); -} \ No newline at end of file +} diff --git a/CliFx/Infrastructure/ITypeActivator.cs b/CliFx/Infrastructure/ITypeActivator.cs index 27a3511d..8a178388 100644 --- a/CliFx/Infrastructure/ITypeActivator.cs +++ b/CliFx/Infrastructure/ITypeActivator.cs @@ -27,4 +27,4 @@ public static T CreateInstance(this ITypeActivator activator, Type type) return (T)activator.CreateInstance(type); } -} \ No newline at end of file +} diff --git a/CliFx/Infrastructure/SystemConsole.cs b/CliFx/Infrastructure/SystemConsole.cs index 41348302..a2537826 100644 --- a/CliFx/Infrastructure/SystemConsole.cs +++ b/CliFx/Infrastructure/SystemConsole.cs @@ -119,4 +119,4 @@ public void Dispose() Output.Dispose(); Error.Dispose(); } -} \ No newline at end of file +} diff --git a/CliFx/Input/CommandInput.cs b/CliFx/Input/CommandInput.cs index e8891364..fa18b81d 100644 --- a/CliFx/Input/CommandInput.cs +++ b/CliFx/Input/CommandInput.cs @@ -18,10 +18,10 @@ internal partial class CommandInput public IReadOnlyList EnvironmentVariables { get; } public bool HasArguments => - !string.IsNullOrWhiteSpace(CommandName) || - Directives.Any() || - Parameters.Any() || - Options.Any(); + !string.IsNullOrWhiteSpace(CommandName) + || Directives.Any() + || Parameters.Any() + || Options.Any(); public bool IsDebugDirectiveSpecified => Directives.Any(d => d.IsDebugDirective); @@ -36,7 +36,8 @@ public CommandInput( IReadOnlyList directives, IReadOnlyList parameters, IReadOnlyList options, - IReadOnlyList environmentVariables) + IReadOnlyList environmentVariables + ) { CommandName = commandName; Directives = directives; @@ -50,7 +51,8 @@ internal partial class CommandInput { private static IReadOnlyList ParseDirectives( IReadOnlyList commandLineArguments, - ref int index) + ref int index + ) { var result = new List(); @@ -73,7 +75,8 @@ private static IReadOnlyList ParseDirectives( private static string? ParseCommandName( IReadOnlyList commandLineArguments, ISet commandNames, - ref int index) + ref int index + ) { var potentialCommandNameComponents = new List(); var commandName = default(string?); @@ -107,7 +110,8 @@ private static IReadOnlyList ParseDirectives( private static IReadOnlyList ParseParameters( IReadOnlyList commandLineArguments, - ref int index) + ref int index + ) { var result = new List(); @@ -118,13 +122,14 @@ private static IReadOnlyList ParseParameters( var isOptionIdentifier = // Name - argument.StartsWith("--", StringComparison.Ordinal) && - argument.Length > 2 && - char.IsLetter(argument[2]) || + argument.StartsWith("--", StringComparison.Ordinal) + && argument.Length > 2 + && char.IsLetter(argument[2]) + || // Short name - argument.StartsWith('-') && - argument.Length > 1 && - char.IsLetter(argument[1]); + argument.StartsWith('-') + && argument.Length > 1 + && char.IsLetter(argument[1]); // Break on the first option identifier if (isOptionIdentifier) @@ -138,7 +143,8 @@ private static IReadOnlyList ParseParameters( private static IReadOnlyList ParseOptions( IReadOnlyList commandLineArguments, - ref int index) + ref int index + ) { var result = new List(); @@ -151,9 +157,11 @@ private static IReadOnlyList ParseOptions( var argument = commandLineArguments[index]; // Name - if (argument.StartsWith("--", StringComparison.Ordinal) && - argument.Length > 2 && - char.IsLetter(argument[2])) + if ( + argument.StartsWith("--", StringComparison.Ordinal) + && argument.Length > 2 + && char.IsLetter(argument[2]) + ) { // Flush previous if (!string.IsNullOrWhiteSpace(lastOptionIdentifier)) @@ -163,9 +171,7 @@ private static IReadOnlyList ParseOptions( lastOptionValues = new List(); } // Short name - else if (argument.StartsWith('-') && - argument.Length > 1 && - char.IsLetter(argument[1])) + else if (argument.StartsWith('-') && argument.Length > 1 && char.IsLetter(argument[1])) { foreach (var identifier in argument[1..]) { @@ -194,14 +200,12 @@ private static IReadOnlyList ParseOptions( public static CommandInput Parse( IReadOnlyList commandLineArguments, IReadOnlyDictionary environmentVariables, - IReadOnlyList availableCommandNames) + IReadOnlyList availableCommandNames + ) { var index = 0; - var parsedDirectives = ParseDirectives( - commandLineArguments, - ref index - ); + var parsedDirectives = ParseDirectives(commandLineArguments, ref index); var parsedCommandName = ParseCommandName( commandLineArguments, @@ -209,15 +213,9 @@ ref index ref index ); - var parsedParameters = ParseParameters( - commandLineArguments, - ref index - ); + var parsedParameters = ParseParameters(commandLineArguments, ref index); - var parsedOptions = ParseOptions( - commandLineArguments, - ref index - ); + var parsedOptions = ParseOptions(commandLineArguments, ref index); var parsedEnvironmentVariables = environmentVariables .Select(kvp => new EnvironmentVariableInput(kvp.Key, kvp.Value)) @@ -231,4 +229,4 @@ ref index parsedEnvironmentVariables ); } -} \ No newline at end of file +} diff --git a/CliFx/Input/DirectiveInput.cs b/CliFx/Input/DirectiveInput.cs index 11dba4ff..3a5056c5 100644 --- a/CliFx/Input/DirectiveInput.cs +++ b/CliFx/Input/DirectiveInput.cs @@ -13,4 +13,4 @@ internal class DirectiveInput string.Equals(Name, "preview", StringComparison.OrdinalIgnoreCase); public DirectiveInput(string name) => Name = name; -} \ No newline at end of file +} diff --git a/CliFx/Input/EnvironmentVariableInput.cs b/CliFx/Input/EnvironmentVariableInput.cs index cad5ea25..bb085682 100644 --- a/CliFx/Input/EnvironmentVariableInput.cs +++ b/CliFx/Input/EnvironmentVariableInput.cs @@ -16,4 +16,4 @@ public EnvironmentVariableInput(string name, string value) } public IReadOnlyList SplitValues() => Value.Split(Path.PathSeparator); -} \ No newline at end of file +} diff --git a/CliFx/Input/OptionInput.cs b/CliFx/Input/OptionInput.cs index 7b8af287..08f2dd7c 100644 --- a/CliFx/Input/OptionInput.cs +++ b/CliFx/Input/OptionInput.cs @@ -9,11 +9,9 @@ internal class OptionInput public IReadOnlyList Values { get; } - public bool IsHelpOption => - OptionSchema.HelpOption.MatchesIdentifier(Identifier); + public bool IsHelpOption => OptionSchema.HelpOption.MatchesIdentifier(Identifier); - public bool IsVersionOption => - OptionSchema.VersionOption.MatchesIdentifier(Identifier); + public bool IsVersionOption => OptionSchema.VersionOption.MatchesIdentifier(Identifier); public OptionInput(string identifier, IReadOnlyList values) { @@ -21,9 +19,10 @@ public OptionInput(string identifier, IReadOnlyList values) Values = values; } - public string GetFormattedIdentifier() => Identifier switch - { - {Length: >= 2} => "--" + Identifier, - _ => '-' + Identifier - }; -} \ No newline at end of file + public string GetFormattedIdentifier() => + Identifier switch + { + { Length: >= 2 } => "--" + Identifier, + _ => '-' + Identifier + }; +} diff --git a/CliFx/Input/ParameterInput.cs b/CliFx/Input/ParameterInput.cs index bea55ff9..68aa687f 100644 --- a/CliFx/Input/ParameterInput.cs +++ b/CliFx/Input/ParameterInput.cs @@ -7,4 +7,4 @@ internal class ParameterInput public ParameterInput(string value) => Value = value; public string GetFormattedIdentifier() => $"<{Value}>"; -} \ No newline at end of file +} diff --git a/CliFx/Schema/ApplicationSchema.cs b/CliFx/Schema/ApplicationSchema.cs index a48198bc..ac3f2bf0 100644 --- a/CliFx/Schema/ApplicationSchema.cs +++ b/CliFx/Schema/ApplicationSchema.cs @@ -14,20 +14,18 @@ public ApplicationSchema(IReadOnlyList commands) Commands = commands; } - public IReadOnlyList GetCommandNames() => Commands - .Select(c => c.Name) - .WhereNotNullOrWhiteSpace() - .ToArray(); + public IReadOnlyList GetCommandNames() => + Commands.Select(c => c.Name).WhereNotNullOrWhiteSpace().ToArray(); - public CommandSchema? TryFindDefaultCommand() => - Commands.FirstOrDefault(c => c.IsDefault); + public CommandSchema? TryFindDefaultCommand() => Commands.FirstOrDefault(c => c.IsDefault); public CommandSchema? TryFindCommand(string commandName) => Commands.FirstOrDefault(c => c.MatchesName(commandName)); private IReadOnlyList GetDescendantCommands( IReadOnlyList potentialParentCommandSchemas, - string? parentCommandName) + string? parentCommandName + ) { var result = new List(); @@ -43,7 +41,8 @@ private IReadOnlyList GetDescendantCommands( var isDescendant = // Every command is a descendant of the default command - string.IsNullOrWhiteSpace(parentCommandName) || + string.IsNullOrWhiteSpace(parentCommandName) + || // Otherwise a command is a descendant if it starts with the same name segments potentialParentCommandSchema.Name.StartsWith( parentCommandName + ' ', @@ -69,9 +68,7 @@ public IReadOnlyList GetChildCommands(string? parentCommandName) // Filter out descendants of descendants, leave only direct children foreach (var descendant in descendants) { - result.RemoveRange( - GetDescendantCommands(descendants, descendant.Name) - ); + result.RemoveRange(GetDescendantCommands(descendants, descendant.Name)); } return result; @@ -80,7 +77,6 @@ public IReadOnlyList GetChildCommands(string? parentCommandName) internal partial class ApplicationSchema { - public static ApplicationSchema Resolve(IReadOnlyList commandTypes) => new( - commandTypes.Select(CommandSchema.Resolve).ToArray() - ); -} \ No newline at end of file + public static ApplicationSchema Resolve(IReadOnlyList commandTypes) => + new(commandTypes.Select(CommandSchema.Resolve).ToArray()); +} diff --git a/CliFx/Schema/BindablePropertyDescriptor.cs b/CliFx/Schema/BindablePropertyDescriptor.cs index 7ad0c946..743b8bb8 100644 --- a/CliFx/Schema/BindablePropertyDescriptor.cs +++ b/CliFx/Schema/BindablePropertyDescriptor.cs @@ -13,8 +13,7 @@ internal class BindablePropertyDescriptor : IPropertyDescriptor public BindablePropertyDescriptor(PropertyInfo property) => _property = property; - public object? GetValue(ICommand commandInstance) => - _property.GetValue(commandInstance); + public object? GetValue(ICommand commandInstance) => _property.GetValue(commandInstance); public void SetValue(ICommand commandInstance, object? value) => _property.SetValue(commandInstance, value); @@ -42,4 +41,4 @@ static Type GetUnderlyingType(Type type) return Array.Empty(); } -} \ No newline at end of file +} diff --git a/CliFx/Schema/CommandSchema.cs b/CliFx/Schema/CommandSchema.cs index e482d97b..b3244dff 100644 --- a/CliFx/Schema/CommandSchema.cs +++ b/CliFx/Schema/CommandSchema.cs @@ -31,7 +31,8 @@ public CommandSchema( string? name, string? description, IReadOnlyList parameters, - IReadOnlyList options) + IReadOnlyList options + ) { Type = type; Name = name; @@ -68,9 +69,9 @@ public bool MatchesName(string? name) => internal partial class CommandSchema { public static bool IsCommandType(Type type) => - type.Implements(typeof(ICommand)) && - type.IsDefined(typeof(CommandAttribute)) && - type is { IsAbstract: false, IsInterface: false }; + type.Implements(typeof(ICommand)) + && type.IsDefined(typeof(CommandAttribute)) + && type is { IsAbstract: false, IsInterface: false }; public static CommandSchema? TryResolve(Type type) { @@ -83,21 +84,22 @@ public static bool IsCommandType(Type type) => var description = attribute?.Description?.Trim(); var implicitOptionSchemas = string.IsNullOrWhiteSpace(name) - ? new[] {OptionSchema.HelpOption, OptionSchema.VersionOption} - : new[] {OptionSchema.HelpOption}; + ? new[] { OptionSchema.HelpOption, OptionSchema.VersionOption } + : new[] { OptionSchema.HelpOption }; var properties = type - // Get properties directly on the command type - .GetProperties() + // Get properties directly on the command type + .GetProperties() // Get non-abstract properties on interfaces (to support default interfaces members) - .Union(type - .GetInterfaces() - // Only interfaces implementing ICommand for explicitness - .Where(i => i != typeof(ICommand) && i.IsAssignableTo(typeof(ICommand))) - .SelectMany(i => i - .GetProperties() - .Where(p => !p.GetMethod.IsAbstract && !p.SetMethod.IsAbstract) - ) + .Union( + type.GetInterfaces() + // Only interfaces implementing ICommand for explicitness + .Where(i => i != typeof(ICommand) && i.IsAssignableTo(typeof(ICommand))) + .SelectMany( + i => + i.GetProperties() + .Where(p => !p.GetMethod.IsAbstract && !p.SetMethod.IsAbstract) + ) ) .ToArray(); @@ -112,13 +114,7 @@ public static bool IsCommandType(Type type) => .Concat(implicitOptionSchemas) .ToArray(); - return new CommandSchema( - type, - name, - description, - parameterSchemas, - optionSchemas - ); + return new CommandSchema(type, name, description, parameterSchemas, optionSchemas); } public static CommandSchema Resolve(Type type) @@ -139,4 +135,4 @@ public static CommandSchema Resolve(Type type) return schema; } -} \ No newline at end of file +} diff --git a/CliFx/Schema/IMemberSchema.cs b/CliFx/Schema/IMemberSchema.cs index 32f5a66e..59919c90 100644 --- a/CliFx/Schema/IMemberSchema.cs +++ b/CliFx/Schema/IMemberSchema.cs @@ -16,10 +16,11 @@ internal interface IMemberSchema internal static class MemberSchemaExtensions { - public static string GetKind(this IMemberSchema memberSchema) => memberSchema switch - { - ParameterSchema => "Parameter", - OptionSchema => "Option", - _ => throw new ArgumentOutOfRangeException(nameof(memberSchema)) - }; -} \ No newline at end of file + public static string GetKind(this IMemberSchema memberSchema) => + memberSchema switch + { + ParameterSchema => "Parameter", + OptionSchema => "Option", + _ => throw new ArgumentOutOfRangeException(nameof(memberSchema)) + }; +} diff --git a/CliFx/Schema/IPropertyDescriptor.cs b/CliFx/Schema/IPropertyDescriptor.cs index 221c095e..a59beab1 100644 --- a/CliFx/Schema/IPropertyDescriptor.cs +++ b/CliFx/Schema/IPropertyDescriptor.cs @@ -18,6 +18,6 @@ internal interface IPropertyDescriptor internal static class PropertyDescriptorExtensions { public static bool IsScalar(this IPropertyDescriptor propertyDescriptor) => - propertyDescriptor.Type == typeof(string) || - propertyDescriptor.Type.TryGetEnumerableUnderlyingType() is null; -} \ No newline at end of file + propertyDescriptor.Type == typeof(string) + || propertyDescriptor.Type.TryGetEnumerableUnderlyingType() is null; +} diff --git a/CliFx/Schema/NullPropertyDescriptor.cs b/CliFx/Schema/NullPropertyDescriptor.cs index d62a415e..e1c52578 100644 --- a/CliFx/Schema/NullPropertyDescriptor.cs +++ b/CliFx/Schema/NullPropertyDescriptor.cs @@ -9,9 +9,7 @@ internal partial class NullPropertyDescriptor : IPropertyDescriptor public object? GetValue(ICommand commandInstance) => null; - public void SetValue(ICommand commandInstance, object? value) - { - } + public void SetValue(ICommand commandInstance, object? value) { } public IReadOnlyList GetValidValues() => Array.Empty(); } @@ -19,4 +17,4 @@ public void SetValue(ICommand commandInstance, object? value) internal partial class NullPropertyDescriptor { public static NullPropertyDescriptor Instance { get; } = new(); -} \ No newline at end of file +} diff --git a/CliFx/Schema/OptionSchema.cs b/CliFx/Schema/OptionSchema.cs index 1818dda6..51962409 100644 --- a/CliFx/Schema/OptionSchema.cs +++ b/CliFx/Schema/OptionSchema.cs @@ -33,7 +33,8 @@ public OptionSchema( bool isRequired, string? description, Type? converterType, - IReadOnlyList validatorTypes) + IReadOnlyList validatorTypes + ) { Property = property; Name = name; @@ -46,20 +47,18 @@ public OptionSchema( } public bool MatchesName(string? name) => - !string.IsNullOrWhiteSpace(Name) && - string.Equals(Name, name, StringComparison.OrdinalIgnoreCase); + !string.IsNullOrWhiteSpace(Name) + && string.Equals(Name, name, StringComparison.OrdinalIgnoreCase); public bool MatchesShortName(char? shortName) => - ShortName is not null && - ShortName == shortName; + ShortName is not null && ShortName == shortName; public bool MatchesIdentifier(string identifier) => - MatchesName(identifier) || - identifier.Length == 1 && MatchesShortName(identifier[0]); + MatchesName(identifier) || identifier.Length == 1 && MatchesShortName(identifier[0]); public bool MatchesEnvironmentVariable(string environmentVariableName) => - !string.IsNullOrWhiteSpace(EnvironmentVariable) && - string.Equals(EnvironmentVariable, environmentVariableName, StringComparison.Ordinal); + !string.IsNullOrWhiteSpace(EnvironmentVariable) + && string.Equals(EnvironmentVariable, environmentVariableName, StringComparison.Ordinal); public string GetFormattedIdentifier() { @@ -68,9 +67,7 @@ public string GetFormattedIdentifier() // Short name if (ShortName is not null) { - buffer - .Append('-') - .Append(ShortName); + buffer.Append('-').Append(ShortName); } // Separator @@ -82,9 +79,7 @@ public string GetFormattedIdentifier() // Name if (!string.IsNullOrWhiteSpace(Name)) { - buffer - .Append("--") - .Append(Name); + buffer.Append("--").Append(Name); } return buffer.ToString(); @@ -120,25 +115,27 @@ internal partial class OptionSchema internal partial class OptionSchema { - public static OptionSchema HelpOption { get; } = new( - NullPropertyDescriptor.Instance, - "help", - 'h', - null, - false, - "Shows help text.", - null, - Array.Empty() - ); - - public static OptionSchema VersionOption { get; } = new( - NullPropertyDescriptor.Instance, - "version", - null, - null, - false, - "Shows version information.", - null, - Array.Empty() - ); -} \ No newline at end of file + public static OptionSchema HelpOption { get; } = + new( + NullPropertyDescriptor.Instance, + "help", + 'h', + null, + false, + "Shows help text.", + null, + Array.Empty() + ); + + public static OptionSchema VersionOption { get; } = + new( + NullPropertyDescriptor.Instance, + "version", + null, + null, + false, + "Shows version information.", + null, + Array.Empty() + ); +} diff --git a/CliFx/Schema/ParameterSchema.cs b/CliFx/Schema/ParameterSchema.cs index f7f2988e..53331476 100644 --- a/CliFx/Schema/ParameterSchema.cs +++ b/CliFx/Schema/ParameterSchema.cs @@ -29,7 +29,8 @@ public ParameterSchema( bool isRequired, string? description, Type? converterType, - IReadOnlyList validatorTypes) + IReadOnlyList validatorTypes + ) { Property = property; Order = order; @@ -40,9 +41,7 @@ public ParameterSchema( ValidatorTypes = validatorTypes; } - public string GetFormattedIdentifier() => Property.IsScalar() - ? $"<{Name}>" - : $"<{Name}...>"; + public string GetFormattedIdentifier() => Property.IsScalar() ? $"<{Name}>" : $"<{Name}...>"; } internal partial class ParameterSchema @@ -67,4 +66,4 @@ internal partial class ParameterSchema attribute.Validators ); } -} \ No newline at end of file +} diff --git a/CliFx/Utils/Disposable.cs b/CliFx/Utils/Disposable.cs index 0a71e501..22adfefb 100644 --- a/CliFx/Utils/Disposable.cs +++ b/CliFx/Utils/Disposable.cs @@ -16,12 +16,13 @@ internal partial class Disposable { public static IDisposable Create(Action dispose) => new Disposable(dispose); - public static IDisposable Merge(IEnumerable disposables) => Create(() => - { - foreach (var disposable in disposables) - disposable.Dispose(); - }); + public static IDisposable Merge(IEnumerable disposables) => + Create(() => + { + foreach (var disposable in disposables) + disposable.Dispose(); + }); public static IDisposable Merge(params IDisposable[] disposables) => - Merge((IEnumerable) disposables); -} \ No newline at end of file + Merge((IEnumerable)disposables); +} diff --git a/CliFx/Utils/EnvironmentEx.cs b/CliFx/Utils/EnvironmentEx.cs index 63da9030..64ccbe89 100644 --- a/CliFx/Utils/EnvironmentEx.cs +++ b/CliFx/Utils/EnvironmentEx.cs @@ -6,15 +6,16 @@ namespace CliFx.Utils; internal static class EnvironmentEx { - private static readonly Lazy ProcessPathLazy = new(() => - { - using var process = Process.GetCurrentProcess(); - return process.MainModule?.FileName; - }); + private static readonly Lazy ProcessPathLazy = + new(() => + { + using var process = Process.GetCurrentProcess(); + return process.MainModule?.FileName; + }); public static string? ProcessPath => ProcessPathLazy.Value; private static readonly Lazy EntryAssemblyLazy = new(Assembly.GetEntryAssembly); public static Assembly? EntryAssembly => EntryAssemblyLazy.Value; -} \ No newline at end of file +} diff --git a/CliFx/Utils/Extensions/CollectionExtensions.cs b/CliFx/Utils/Extensions/CollectionExtensions.cs index f2b901c9..bd4c4718 100644 --- a/CliFx/Utils/Extensions/CollectionExtensions.cs +++ b/CliFx/Utils/Extensions/CollectionExtensions.cs @@ -41,10 +41,11 @@ public static void RemoveRange(this ICollection source, IEnumerable ite public static Dictionary ToDictionary( this IDictionary dictionary, - IEqualityComparer comparer) => + IEqualityComparer comparer + ) => dictionary .Cast() - .ToDictionary(entry => (TKey) entry.Key, entry => (TValue) entry.Value, comparer); + .ToDictionary(entry => (TKey)entry.Key, entry => (TValue)entry.Value, comparer); public static Array ToNonGenericArray(this IEnumerable source, Type elementType) { @@ -55,4 +56,4 @@ public static Array ToNonGenericArray(this IEnumerable source, Type elemen return array; } -} \ No newline at end of file +} diff --git a/CliFx/Utils/Extensions/PropertyExtensions.cs b/CliFx/Utils/Extensions/PropertyExtensions.cs index 505dcdae..c590fcfb 100644 --- a/CliFx/Utils/Extensions/PropertyExtensions.cs +++ b/CliFx/Utils/Extensions/PropertyExtensions.cs @@ -8,11 +8,14 @@ internal static class PropertyExtensions { public static bool IsRequired(this PropertyInfo propertyInfo) => // Match attribute by name to avoid depending on .NET 7.0+ and to allow polyfilling - propertyInfo.GetCustomAttributes().Any(a => - string.Equals( - a.GetType().FullName, - "System.Runtime.CompilerServices.RequiredMemberAttribute", - StringComparison.Ordinal - ) - ); -} \ No newline at end of file + propertyInfo + .GetCustomAttributes() + .Any( + a => + string.Equals( + a.GetType().FullName, + "System.Runtime.CompilerServices.RequiredMemberAttribute", + StringComparison.Ordinal + ) + ); +} diff --git a/CliFx/Utils/Extensions/StringExtensions.cs b/CliFx/Utils/Extensions/StringExtensions.cs index 1a9831bb..997ad15c 100644 --- a/CliFx/Utils/Extensions/StringExtensions.cs +++ b/CliFx/Utils/Extensions/StringExtensions.cs @@ -6,9 +6,7 @@ namespace CliFx.Utils.Extensions; internal static class StringExtensions { public static string? NullIfWhiteSpace(this string str) => - !string.IsNullOrWhiteSpace(str) - ? str - : null; + !string.IsNullOrWhiteSpace(str) ? str : null; public static string Repeat(this char c, int count) => new(c, count); @@ -20,8 +18,9 @@ public static string JoinToString(this IEnumerable source, string separato public static string ToString( this object obj, IFormatProvider? formatProvider = null, - string? format = null) => + string? format = null + ) => obj is IFormattable formattable ? formattable.ToString(format, formatProvider) : obj.ToString(); -} \ No newline at end of file +} diff --git a/CliFx/Utils/Extensions/TypeExtensions.cs b/CliFx/Utils/Extensions/TypeExtensions.cs index 034b3c09..70d0e28e 100644 --- a/CliFx/Utils/Extensions/TypeExtensions.cs +++ b/CliFx/Utils/Extensions/TypeExtensions.cs @@ -25,8 +25,7 @@ public static bool Implements(this Type type, Type interfaceType) => if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>)) return type.GetGenericArguments().FirstOrDefault(); - return type - .GetInterfaces() + return type.GetInterfaces() .Select(TryGetEnumerableUnderlyingType) .Where(t => t is not null) // Every IEnumerable implements IEnumerable (which is essentially IEnumerable), @@ -35,15 +34,21 @@ public static bool Implements(this Type type, Type interfaceType) => .MaxBy(t => t != typeof(object)); } - public static MethodInfo? TryGetStaticParseMethod(this Type type, bool withFormatProvider = false) + public static MethodInfo? TryGetStaticParseMethod( + this Type type, + bool withFormatProvider = false + ) { var argumentTypes = withFormatProvider - ? new[] {typeof(string), typeof(IFormatProvider)} - : new[] {typeof(string)}; + ? new[] { typeof(string), typeof(IFormatProvider) } + : new[] { typeof(string) }; - return type.GetMethod("Parse", + return type.GetMethod( + "Parse", BindingFlags.Public | BindingFlags.Static, - null, argumentTypes, null + null, + argumentTypes, + null ); } @@ -52,4 +57,4 @@ public static bool IsToStringOverriden(this Type type) var toStringMethod = type.GetMethod(nameof(ToString), Type.EmptyTypes); return toStringMethod?.GetBaseDefinition()?.DeclaringType != toStringMethod?.DeclaringType; } -} \ No newline at end of file +} diff --git a/CliFx/Utils/Extensions/VersionExtensions.cs b/CliFx/Utils/Extensions/VersionExtensions.cs index 62bed505..5ace9d49 100644 --- a/CliFx/Utils/Extensions/VersionExtensions.cs +++ b/CliFx/Utils/Extensions/VersionExtensions.cs @@ -6,4 +6,4 @@ internal static class VersionExtensions { public static string ToSemanticString(this Version version) => version.Revision <= 0 ? version.ToString(3) : version.ToString(); -} \ No newline at end of file +} diff --git a/CliFx/Utils/NoPreambleEncoding.cs b/CliFx/Utils/NoPreambleEncoding.cs index 1053cb76..47e3166b 100644 --- a/CliFx/Utils/NoPreambleEncoding.cs +++ b/CliFx/Utils/NoPreambleEncoding.cs @@ -71,8 +71,13 @@ public override int GetByteCount(char[] chars, int index, int count) => public override int GetByteCount(string s) => _underlyingEncoding.GetByteCount(s); [ExcludeFromCodeCoverage] - public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) => - _underlyingEncoding.GetBytes(chars, charIndex, charCount, bytes, byteIndex); + public override int GetBytes( + char[] chars, + int charIndex, + int charCount, + byte[] bytes, + int byteIndex + ) => _underlyingEncoding.GetBytes(chars, charIndex, charCount, bytes, byteIndex); [ExcludeFromCodeCoverage] public override byte[] GetBytes(char[] chars, int index, int count) => @@ -82,8 +87,13 @@ public override byte[] GetBytes(char[] chars, int index, int count) => public override byte[] GetBytes(char[] chars) => _underlyingEncoding.GetBytes(chars); [ExcludeFromCodeCoverage] - public override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) => - _underlyingEncoding.GetBytes(s, charIndex, charCount, bytes, byteIndex); + public override int GetBytes( + string s, + int charIndex, + int charCount, + byte[] bytes, + int byteIndex + ) => _underlyingEncoding.GetBytes(s, charIndex, charCount, bytes, byteIndex); [ExcludeFromCodeCoverage] public override byte[] GetBytes(string s) => _underlyingEncoding.GetBytes(s); @@ -96,8 +106,13 @@ public override int GetCharCount(byte[] bytes, int index, int count) => public override int GetCharCount(byte[] bytes) => _underlyingEncoding.GetCharCount(bytes); [ExcludeFromCodeCoverage] - public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) => - _underlyingEncoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex); + public override int GetChars( + byte[] bytes, + int byteIndex, + int byteCount, + char[] chars, + int charIndex + ) => _underlyingEncoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex); [ExcludeFromCodeCoverage] public override char[] GetChars(byte[] bytes) => _underlyingEncoding.GetChars(bytes); @@ -122,7 +137,8 @@ public override int GetMaxCharCount(int byteCount) => _underlyingEncoding.GetMaxCharCount(byteCount); [ExcludeFromCodeCoverage] - public override bool IsAlwaysNormalized(NormalizationForm form) => _underlyingEncoding.IsAlwaysNormalized(form); + public override bool IsAlwaysNormalized(NormalizationForm form) => + _underlyingEncoding.IsAlwaysNormalized(form); [ExcludeFromCodeCoverage] public override Encoder GetEncoder() => _underlyingEncoding.GetEncoder(); @@ -131,13 +147,11 @@ public override int GetMaxCharCount(int byteCount) => public override Decoder GetDecoder() => _underlyingEncoding.GetDecoder(); [ExcludeFromCodeCoverage] - public override object Clone() => new NoPreambleEncoding((Encoding) base.Clone()); + public override object Clone() => new NoPreambleEncoding((Encoding)base.Clone()); } internal static class NoPreambleEncodingExtensions { public static Encoding WithoutPreamble(this Encoding encoding) => - encoding.GetPreamble().Length > 0 - ? new NoPreambleEncoding(encoding) - : encoding; -} \ No newline at end of file + encoding.GetPreamble().Length > 0 ? new NoPreambleEncoding(encoding) : encoding; +} diff --git a/CliFx/Utils/PathEx.cs b/CliFx/Utils/PathEx.cs index 8ba04b1d..a1765da5 100644 --- a/CliFx/Utils/PathEx.cs +++ b/CliFx/Utils/PathEx.cs @@ -13,10 +13,10 @@ internal static class PathEx public static bool AreEqual(string path1, string path2) { - static string Normalize(string path) => Path - .GetFullPath(path) - .Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + static string Normalize(string path) => + Path.GetFullPath(path) + .Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); return EqualityComparer.Equals(Normalize(path1), Normalize(path2)); } -} \ No newline at end of file +} diff --git a/CliFx/Utils/ProcessEx.cs b/CliFx/Utils/ProcessEx.cs index 8fcde5df..68c5528c 100644 --- a/CliFx/Utils/ProcessEx.cs +++ b/CliFx/Utils/ProcessEx.cs @@ -9,4 +9,4 @@ public static int GetCurrentProcessId() using var process = Process.GetCurrentProcess(); return process.Id; } -} \ No newline at end of file +} diff --git a/CliFx/Utils/StackFrame.cs b/CliFx/Utils/StackFrame.cs index b7f9dc39..19604dec 100644 --- a/CliFx/Utils/StackFrame.cs +++ b/CliFx/Utils/StackFrame.cs @@ -36,7 +36,8 @@ public StackFrame( string methodName, IReadOnlyList parameters, string? filePath, - string? lineNumber) + string? lineNumber + ) { ParentType = parentType; MethodName = methodName; @@ -52,8 +53,9 @@ internal partial class StackFrame private const string NotSpace = @"[^\x20\t]"; // Taken from https://github.com/atifaziz/StackTraceParser - private static readonly Regex Pattern = new( - $$""" + private static readonly Regex Pattern = + new( + $$""" ^ {{Space}}* \w+ {{Space}}+ @@ -81,13 +83,13 @@ internal partial class StackFrame \s* $ """, - RegexOptions.IgnoreCase | - RegexOptions.Multiline | - RegexOptions.ExplicitCapture | - RegexOptions.CultureInvariant | - RegexOptions.IgnorePatternWhitespace, - TimeSpan.FromSeconds(5) - ); + RegexOptions.IgnoreCase + | RegexOptions.Multiline + | RegexOptions.ExplicitCapture + | RegexOptions.CultureInvariant + | RegexOptions.IgnorePatternWhitespace, + TimeSpan.FromSeconds(5) + ); public static IEnumerable ParseTrace(string stackTrace) { @@ -106,8 +108,7 @@ public static IEnumerable ParseTrace(string stackTrace) } return from m in matches - select m.Groups - into groups + select m.Groups into groups let pt = groups["pt"].Captures let pn = groups["pn"].Captures select new StackFrame( @@ -121,4 +122,4 @@ from i in Enumerable.Range(0, pt.Count) groups["line"].Value.NullIfWhiteSpace() ); } -} \ No newline at end of file +}