mirror of
https://github.com/Tyrrrz/CliFx.git
synced 2025-10-25 15:19:17 +00:00
Compare commits
35 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
99c59431c4 | ||
|
|
f376081489 | ||
|
|
00a1e12b5c | ||
|
|
81f8b17451 | ||
|
|
aa8315b68d | ||
|
|
e52781c25a | ||
|
|
01f29a5375 | ||
|
|
013cb8f66b | ||
|
|
9c715f458e | ||
|
|
90d93a57ee | ||
|
|
8da4a61eb7 | ||
|
|
f718370642 | ||
|
|
83c7af72bf | ||
|
|
eff84fd7ae | ||
|
|
f66fa97b87 | ||
|
|
9f309b5d4a | ||
|
|
456099591a | ||
|
|
bf7f607f9b | ||
|
|
a4041ab019 | ||
|
|
a0fde872ec | ||
|
|
f0c040c7b9 | ||
|
|
a09818d452 | ||
|
|
1c331df4b1 | ||
|
|
dc20fe9730 | ||
|
|
31ae0271b9 | ||
|
|
6ed6d2ced9 | ||
|
|
01a4846159 | ||
|
|
02dc7de127 | ||
|
|
a1ff1a1539 | ||
|
|
a02951f755 | ||
|
|
7cb25254e8 | ||
|
|
3d9ad16117 | ||
|
|
d0ad3bc45d | ||
|
|
6541ce568d | ||
|
|
32d3b66185 |
66
Changelog.md
66
Changelog.md
@@ -1,28 +1,42 @@
|
||||
### v2.3.1 (08-Dec-2022)
|
||||
# Changelog
|
||||
|
||||
## v2.3.4 (18-May-2023)
|
||||
|
||||
- Added an overload of `CliApplicationBuilder.UseTypeActivator(...)` that accepts a `Func<IReadOnlyList<Type>, IServiceProvider>` delegate. The first parameter in the delegate is the list of all command types registered in the application. You can use this overload to more easily add the commands to a DI container. See the readme for an [updated example](https://github.com/Tyrrrz/CliFx/tree/2.3.4#type-activation).
|
||||
|
||||
## v2.3.3 (28-Apr-2023)
|
||||
|
||||
- Fixed an issue where the analyzers failed to load in some projects, due to targeting a Roslyn version that was too high.
|
||||
|
||||
## v2.3.2 (06-Apr-2023)
|
||||
|
||||
- Added name-based ordering to subcommands when displayed in the help text. (Thanks [@CartBlanche](https://github.com/CartBlanche))
|
||||
|
||||
## v2.3.1 (08-Dec-2022)
|
||||
|
||||
- Added support for the `required` keyword introduced in C# 11. Command options bound to required properties are now marked as required by default (equivalent to setting `IsRequired = true` on the attribute). Also added analyzers that prevent marking an option or parameter non-required if it's bound to a required property.
|
||||
|
||||
### v2.3 (12-Jul-2022)
|
||||
## v2.3 (12-Jul-2022)
|
||||
|
||||
- Added console dimension properties `WindowWidth` and `WindowHeight` to `IConsole` interface and implementing classes.
|
||||
- Improved inline documentation for members of `IConsole` interface.
|
||||
|
||||
### v2.2.6 (14-Jun-2022)
|
||||
## v2.2.6 (14-Jun-2022)
|
||||
|
||||
- Added an overload of `CliApplicationBuilder.UseTypeActivator(...)` that accepts an instance of `IServiceProvider`. This slightly simplifies integration with many DI containers.
|
||||
- Fixed minor grammar mistakes in user-facing error messages.
|
||||
|
||||
### v2.2.5 (10-May-2022)
|
||||
## v2.2.5 (10-May-2022)
|
||||
|
||||
- Updated default value resolution for the application executable name. It will now resolve to `myapp.exe` instead of `dotnet myapp.dll` when the application is launched through the EXE apphost on Windows. On other platforms, or when running the application through the .NET CLI, the behavior will be the same as before.
|
||||
|
||||
### v2.2.4 (22-Apr-2022)
|
||||
## v2.2.4 (22-Apr-2022)
|
||||
|
||||
- Added more contextual information to analyzer diagnostics.
|
||||
- Fixed an issue where the analyzer incorrectly reported an error on converters that didn't directly match the target type but were compatible through known built-in conversions.
|
||||
- Fixed an issue where MSBuild produced a lot of analyzer-related warnings in certain circumstances.
|
||||
|
||||
### v2.2.3 (17-Apr-2022)
|
||||
## v2.2.3 (17-Apr-2022)
|
||||
|
||||
- Changed method signature of `IConsole.ReadKey()` to return `ConsoleKeyInfo` instead of `void`. The return type was originally defined as `void` by mistake. This change is source-backwards-compatible but may break on binary level if you were previously calling this method indirectly (i.e. through a library).
|
||||
- Added `FakeConsole.EnqueueKey(...)` to facilitate the testing of `IConsole.ReadKey()`. You can use this method to simulate key presses in your application.
|
||||
@@ -30,57 +44,57 @@
|
||||
- Improved diagnostics produced by analyzers. Where relevant, highlighted code is now limited to the property or type identifier, instead of the whole property or type declaration. Also extended the diagnostic messages with additional information.
|
||||
- Fixed an issue where throwing an exception inside a constructor of a command type resulted in an unrelated error message about the absence of a parameterless constructor.
|
||||
|
||||
### v2.2.2 (30-Jan-2022)
|
||||
## v2.2.2 (30-Jan-2022)
|
||||
|
||||
- Fixed an issue where `ConsoleWriter` and `ConsoleReader` were not properly thread-safe.
|
||||
- Fixed an issue where the analyzer failed to load under certain circumstances when running inside Visual Studio.
|
||||
|
||||
### v2.2.1 (16-Jan-2022)
|
||||
## v2.2.1 (16-Jan-2022)
|
||||
|
||||
- Fixed an issue which caused help text to not show default values for optional parameters. (Thanks [@AliReZa Sabouri](https://github.com/alirezanet))
|
||||
|
||||
### v2.2 (11-Jan-2022)
|
||||
## v2.2 (11-Jan-2022)
|
||||
|
||||
- Added support for optional parameters. A parameter can be marked as optional by setting `IsRequired = false` on the attribute. Only one parameter is allowed to be optional and such parameter must be the last in order. (Thanks [@AliReZa Sabouri](https://github.com/alirezanet))
|
||||
- Fixed an issue where parameters and options bound to properties implemented as default interface members were not working correctly. (Thanks [@AliReZa Sabouri](https://github.com/alirezanet))
|
||||
|
||||
### v2.1 (04-Jan-2022)
|
||||
## v2.1 (04-Jan-2022)
|
||||
|
||||
- Added `IConsole.Clear()` with corresponding implementations in `SystemConsole`, `FakeConsole`, and `FakeInMemoryConsole`. (Thanks [@Alex Rosenfeld](https://github.com/alexrosenfeld10))
|
||||
- Added `IConsole.ReadKey()` with corresponding implementations in `SystemConsole`, `FakeConsole`, and `FakeInMemoryConsole`. (Thanks [@Alex Rosenfeld](https://github.com/alexrosenfeld10))
|
||||
- Fixed an issue that caused parameters to appear out of order in the usage format section of the help text. (Thanks [@David Fallah](https://github.com/TAGC))
|
||||
|
||||
### v2.0.6 (17-Jul-2021)
|
||||
## v2.0.6 (17-Jul-2021)
|
||||
|
||||
- Fixed an issue where an exception thrown via reflection during parameter or option binding resulted in `Exception has been thrown by the target of an invocation` error instead of a more useful message. Such exceptions will now be unwrapped to provide better user experience.
|
||||
|
||||
### v2.0.5 (09-Jul-2021)
|
||||
## v2.0.5 (09-Jul-2021)
|
||||
|
||||
- Fixed an issue where calling `IConsole.Output.Encoding.EncodingName` and some other members threw an exception.
|
||||
- Added readme file to the package.
|
||||
|
||||
### v2.0.4 (24-Apr-2021)
|
||||
## v2.0.4 (24-Apr-2021)
|
||||
|
||||
- Fixed an issue where output and error streams in `SystemConsole` defaulted to UTF8 encoding with BOM when the application was running with UTF8 codepage. `ConsoleWriter` will now discard preamble from the specified encoding. This fix brings the behavior of `SystemConsole` in line with .NET's own `System.Console` which also discards preamble for output and error streams.
|
||||
- Fixed an issue where help text tried to show default values for parameters and options whose type does not override `ToString()` method.
|
||||
- Fixed an issue where help text didn't show default values for parameters and options whose type is an enumerable of nullable enums. (Thanks [@Robert Dailey](https://github.com/rcdailey))
|
||||
- Fixed an issue where specific parts of the help text weren't legible in some terminals due to low color resolution. Removed the usage of `ConsoleColor.DarkGray` in help text.
|
||||
|
||||
### v2.0.3 (09-Apr-2021)
|
||||
## v2.0.3 (09-Apr-2021)
|
||||
|
||||
- Improved help text by showing valid values for non-scalar enum parameters and options. (Thanks [@Robert Dailey](https://github.com/rcdailey))
|
||||
|
||||
### v2.0.2 (31-Mar-2021)
|
||||
## v2.0.2 (31-Mar-2021)
|
||||
|
||||
- Fixed an issue where having a transitive reference to CliFx sometimes resulted in `SystemConsoleShouldBeAvoidedAnalyzer` throwing `NullReferenceException` during build.
|
||||
- Fixed some documentation typos and inconsistencies.
|
||||
|
||||
### v2.0.1 (24-Mar-2021)
|
||||
## v2.0.1 (24-Mar-2021)
|
||||
|
||||
- Fixed an issue where some exceptions with async stack traces generated on .NET 3.1 or earlier were not parsed and formatted correctly.
|
||||
- Fixed an issue where help text applied slightly incorrect formatting when displaying choices for enum-based parameters and properties.
|
||||
|
||||
### v2.0 (21-Mar-2021)
|
||||
## v2.0 (21-Mar-2021)
|
||||
|
||||
> Note: this major release includes many breaking changes.
|
||||
> Please refer to the readme to find updated instructions and usage examples.
|
||||
@@ -100,7 +114,7 @@
|
||||
- Assigned separate colors to parameters and options to make them visually stand out
|
||||
- Usage section no longer lists usage formats of all descendant commands
|
||||
- Command section now also lists available subcommands for each of the current command's subcommands
|
||||
- Changed the behavior of `[preview]` directive. Running the application with this directive will now also print all resolved environment variables, in addition to parsed command line arguments.
|
||||
- Changed the behavior of `[preview]` directive. Running the application with this directive will now also print all resolved environment variables, in addition to parsed command-line arguments.
|
||||
- Reworked `IArgumentValueConverter`/`ArgumentValueConverter` into `BindingConverter`. Method `ConvertFrom(...)` has been renamed to `Convert(...)`.
|
||||
- Reworked `ArgumentValueValidator` into `BindingValidator`. This class exposes an abstract `Validate(...)` method that returns a nullable `BindingValidationError`. This class also provides utility methods `Ok()` and `Error(...)` to help create corresponding validation results.
|
||||
- Changed the type of `IConsole.Output` and `IConsole.Error` from `StreamWriter` to `ConsoleWriter`. This type derives from `StreamWriter` and additionally exposes a `Console` property that refers to the console instance that owns the stream. This change enables you to author extension methods scoped specifically to console output and error streams.
|
||||
@@ -114,34 +128,34 @@
|
||||
- `ITypeActivator`/`DefaultTypeActivator`/`DelegateTypeActivator` moved from `CliFx` to `CliFx.Infrastructure`
|
||||
- `BindingValidator`/`BindingConverter` moved from `CliFx` to `CliFx.Extensibility`
|
||||
|
||||
### v1.6 (06-Dec-2020)
|
||||
## v1.6 (06-Dec-2020)
|
||||
|
||||
- Added support for custom value validators. You can now create a type that inherits from `CliFx.ArgumentValueValidator<T>` to implement reusable validation logic for command arguments. To use a validator, include it in the `Validators` property on the `CommandOption` or `CommandParameter` attribute. (Thanks [@Oleksandr Shustov](https://github.com/AlexandrShustov))
|
||||
- Added `CliFx.ArgumentValueConverter<T>` class that you can inherit from to implement custom value converters. `CliFx.IArgumentValueConverter` interface is still available, but it is recommended to inherit from the generic class instead, due to the type safety it provides. The interface may become internal or get removed in one of the future major versions.
|
||||
- Updated requirements for option names and short names: short names now must be letter characters (lowercase or uppercase), while names must now start with a letter character. This means option names can no longer start with a digit or a special character. This change makes it possible to pass negative number values without the need to quote them, i.e. `--my-number -5`.
|
||||
|
||||
### v1.5 (23-Oct-2020)
|
||||
## v1.5 (23-Oct-2020)
|
||||
|
||||
- Added pretty-printing for unhandled exceptions thrown from within the application. This makes the errors easier to parse visually and should help in troubleshooting. This change does not affect `CommandException`, as it already has special treatment. (Thanks [@Mårten Åsberg](https://github.com/89netraM))
|
||||
- Added support for custom value converters. You can now create a type that implements `CliFx.IArgumentValueConverter` and specify it as a converter for your parameters or options via the `Converter` named property. This should enable conversion between raw argument values and custom types which are not string-initializable. (Thanks [@Oleksandr Shustov](https://github.com/AlexandrShustov))
|
||||
- Improved help text so that it also shows minimal usage examples for child and descendant commands, besides the actual command it was requested on. This should improve user experience for applications with many nested commands. (Thanks [@Nikiforov Alexey](https://github.com/NikiforovAll))
|
||||
|
||||
### v1.4 (20-Aug-2020)
|
||||
## v1.4 (20-Aug-2020)
|
||||
|
||||
- Added `VirtualConsole.CreateBuffered()` method to simplify test setup when using in-memory backing stores for output and error streams. Please refer to the readme for updated recommendations on how to test applications built with CliFx.
|
||||
- Added generic `CliApplicationBuilder.AddCommand<TCommand>()`. This overload simplifies adding commands one-by-one as it also checks that the type implements `ICommand`.
|
||||
|
||||
### v1.3.2 (31-Jul-2020)
|
||||
## v1.3.2 (31-Jul-2020)
|
||||
|
||||
- Fixed an issue where a command was incorrectly allowed to execute when the user did not specify any value for a non-scalar parameter. Since they are always required, a parameter needs to be bound to at least one value. (Thanks [@Daniel Hix](https://github.com/ADustyOldMuffin))
|
||||
- Fixed an issue where `CliApplication.RunAsync(...)` threw `ArgumentException` if there were two environment variables, whose names differed only in case. Environment variable names are now treated case-sensitively. (Thanks [@Ron Myers](https://github.com/ron-myers))
|
||||
|
||||
### v1.3.1 (19-Jul-2020)
|
||||
## v1.3.1 (19-Jul-2020)
|
||||
|
||||
- Running the application with the debug directive (`myapp [debug]`) will now also try to launch a debugger instance. In most cases it will save time as you won't need to attach the debugger manually. (Thanks [@Volodymyr Shkolka](https://github.com/BlackGad))
|
||||
- Fixed an issue where unhandled generic exceptions (i.e. not `CommandException`) sometimes caused the application to incorrectly return successful exit code due to an overflow issue on Unix systems. Starting from this version, all unhandled generic exceptions will produce `1` as the exit code when thrown. Instances of `CommandException` can still be configured to return any specified exit code, but it's recommended to constrain the values between `1` and `255` to avoid overflow issues. (Thanks [@Ihor Nechyporuk](https://github.com/inech))
|
||||
|
||||
### v1.3 (23-May-2020)
|
||||
## v1.3 (23-May-2020)
|
||||
|
||||
- Changed analyzers to report errors instead of warnings. If you find that some analyzer works incorrectly, please report it on GitHub. You can also configure inspection severity overrides in your project if you need to.
|
||||
- Improved help text by showing default values for non-required options. This only works on types that have a custom override for `ToString()` method. Additionally, if the type implements `IFormattable`, the overload with a format provider will be used instead. (Thanks [@Domn Werner](https://github.com/domn1995))
|
||||
@@ -149,7 +163,7 @@
|
||||
- Fixed an issue where it was possible to define a command with an option that has the same name or short name as built-in help or version options. Previously it would lead to the user-defined option being ignored in favor of the built-in option. Now this will throw an exception instead.
|
||||
- Changed the underlying representation of `StreamReader`/`StreamWriter` objects used in `SystemConsole` and `VirtualConsole` to be thread-safe.
|
||||
|
||||
### v1.2 (11-May-2020)
|
||||
## v1.2 (11-May-2020)
|
||||
|
||||
- Added built-in Roslyn analyzers that help catch incorrect usage of the library. Currently, all analyzers report issues as warnings so as to not prevent the project from building. In the future that may change.
|
||||
- Added an optional parameter to `new CommandException(...)` called `showHelp` which can be used to instruct CliFx to show help for the current command after printing the error. (Thanks [@Domn Werner](https://github.com/domn1995))
|
||||
@@ -160,7 +174,7 @@
|
||||
- Improved exception messages.
|
||||
- Improved exceptions related to user input by also showing help text after the error message. (Thanks [@Domn Werner](https://github.com/domn1995))
|
||||
|
||||
### v1.1 (16-Mar-2020)
|
||||
## v1.1 (16-Mar-2020)
|
||||
|
||||
- Changed `IConsole` interface (and as a result, `SystemConsole` and `VirtualConsole`) to support writing binary data. Instead of `TextReader`/`TextWriter` instances, the streams are now exposed as `StreamReader`/`StreamWriter` which provide the `BaseStream` property that allows raw access. Existing usages inside commands should remain the same because `StreamReader`/`StreamWriter` are compatible with their base classes `TextReader`/`TextWriter`, but if you were using `VirtualConsole` in tests, you may have to update it to the new API. Refer to the readme for more info.
|
||||
- Changed argument binding behavior so that an error is produced if the user provides an argument that doesn't match with any parameter or option. This is done in order to improve user experience, as otherwise the user may make a typo without knowing that their input wasn't taken into account.
|
||||
|
||||
@@ -9,11 +9,11 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Basic.Reference.Assemblies.Net70" Version="1.4.1" />
|
||||
<PackageReference Include="GitHubActionsTestLogger" Version="2.0.1" PrivateAssets="all" />
|
||||
<PackageReference Include="FluentAssertions" Version="6.8.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.0" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.4.0" />
|
||||
<PackageReference Include="Basic.Reference.Assemblies.Net70" Version="1.4.2" />
|
||||
<PackageReference Include="GitHubActionsTestLogger" Version="2.2.0" PrivateAssets="all" />
|
||||
<PackageReference Include="FluentAssertions" Version="6.11.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.6.0" />
|
||||
<PackageReference Include="xunit" Version="2.4.2" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5" PrivateAssets="all" />
|
||||
<PackageReference Include="coverlet.collector" Version="3.2.0" PrivateAssets="all" />
|
||||
|
||||
@@ -69,7 +69,7 @@ public class CommandMustBeAnnotatedAnalyzerSpecs
|
||||
"""
|
||||
public class Foo
|
||||
{
|
||||
public int Bar { get; set; } = 5;
|
||||
public int Bar { get; init; } = 5;
|
||||
}
|
||||
""";
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ public class CommandMustImplementInterfaceAnalyzerSpecs
|
||||
"""
|
||||
public class Foo
|
||||
{
|
||||
public int Bar { get; set; } = 5;
|
||||
public int Bar { get; init; } = 5;
|
||||
}
|
||||
""";
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ public class OptionMustBeInsideCommandAnalyzerSpecs
|
||||
public class MyClass
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
}
|
||||
""";
|
||||
|
||||
@@ -37,7 +37,7 @@ public class OptionMustBeInsideCommandAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -57,7 +57,7 @@ public class OptionMustBeInsideCommandAnalyzerSpecs
|
||||
public abstract class MyCommand
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
}
|
||||
""";
|
||||
|
||||
@@ -75,7 +75,7 @@ public class OptionMustBeInsideCommandAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ public class OptionMustBeRequiredIfPropertyRequiredAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption('f', IsRequired = false)]
|
||||
public required string Foo { get; set; }
|
||||
public required string Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -39,8 +39,8 @@ public class OptionMustBeRequiredIfPropertyRequiredAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption('f', IsRequired = true)]
|
||||
public required string Foo { get; set; }
|
||||
[CommandOption('f')]
|
||||
public required string Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -61,7 +61,7 @@ public class OptionMustBeRequiredIfPropertyRequiredAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption('f', IsRequired = false)]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -81,8 +81,8 @@ public class OptionMustBeRequiredIfPropertyRequiredAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption('f', IsRequired = true)]
|
||||
public string Foo { get; set; }
|
||||
[CommandOption('f')]
|
||||
public required string Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -102,7 +102,7 @@ public class OptionMustBeRequiredIfPropertyRequiredAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
public required string Foo { get; set; }
|
||||
public required string Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ public class OptionMustHaveNameOrShortNameAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption(null)]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -40,7 +40,7 @@ public class OptionMustHaveNameOrShortNameAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -61,7 +61,7 @@ public class OptionMustHaveNameOrShortNameAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -81,7 +81,7 @@ public class OptionMustHaveNameOrShortNameAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
|
||||
@@ -19,10 +19,10 @@ public class OptionMustHaveUniqueNameAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
[CommandOption("foo")]
|
||||
public string Bar { get; set; }
|
||||
public string? Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -43,10 +43,10 @@ public class OptionMustHaveUniqueNameAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
[CommandOption("bar")]
|
||||
public string Bar { get; set; }
|
||||
public string? Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -67,7 +67,7 @@ public class OptionMustHaveUniqueNameAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -87,7 +87,7 @@ public class OptionMustHaveUniqueNameAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
|
||||
@@ -19,10 +19,10 @@ public class OptionMustHaveUniqueShortNameAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
[CommandOption('f')]
|
||||
public string Bar { get; set; }
|
||||
public string? Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -43,10 +43,10 @@ public class OptionMustHaveUniqueShortNameAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
[CommandOption('b')]
|
||||
public string Bar { get; set; }
|
||||
public string? Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -67,10 +67,10 @@ public class OptionMustHaveUniqueShortNameAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
[CommandOption('F')]
|
||||
public string Bar { get; set; }
|
||||
public string? Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -91,7 +91,7 @@ public class OptionMustHaveUniqueShortNameAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -111,7 +111,7 @@ public class OptionMustHaveUniqueShortNameAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
|
||||
@@ -17,15 +17,15 @@ public class OptionMustHaveValidConverterAnalyzerSpecs
|
||||
"""
|
||||
public class MyConverter
|
||||
{
|
||||
public string Convert(string rawValue) => rawValue;
|
||||
public string Convert(string? rawValue) => rawValue;
|
||||
}
|
||||
|
||||
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption("foo", Converter = typeof(MyConverter))]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -43,15 +43,15 @@ public class OptionMustHaveValidConverterAnalyzerSpecs
|
||||
"""
|
||||
public class MyConverter : BindingConverter<int>
|
||||
{
|
||||
public override int Convert(string rawValue) => 42;
|
||||
public override int Convert(string? rawValue) => 42;
|
||||
}
|
||||
|
||||
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption("foo", Converter = typeof(MyConverter))]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -69,15 +69,15 @@ public class OptionMustHaveValidConverterAnalyzerSpecs
|
||||
"""
|
||||
public class MyConverter : BindingConverter<string>
|
||||
{
|
||||
public override string Convert(string rawValue) => rawValue;
|
||||
public override string Convert(string? rawValue) => rawValue;
|
||||
}
|
||||
|
||||
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption("foo", Converter = typeof(MyConverter))]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -95,15 +95,15 @@ public class OptionMustHaveValidConverterAnalyzerSpecs
|
||||
"""
|
||||
public class MyConverter : BindingConverter<int>
|
||||
{
|
||||
public override int Convert(string rawValue) => 42;
|
||||
public override int Convert(string? rawValue) => 42;
|
||||
}
|
||||
|
||||
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption("foo", Converter = typeof(MyConverter))]
|
||||
public int? Foo { get; set; }
|
||||
|
||||
public int? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -121,15 +121,15 @@ public class OptionMustHaveValidConverterAnalyzerSpecs
|
||||
"""
|
||||
public class MyConverter : BindingConverter<string>
|
||||
{
|
||||
public override string Convert(string rawValue) => rawValue;
|
||||
public override string Convert(string? rawValue) => rawValue;
|
||||
}
|
||||
|
||||
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption("foo", Converter = typeof(MyConverter))]
|
||||
public IReadOnlyList<string> Foo { get; set; }
|
||||
|
||||
public IReadOnlyList<string>? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -149,8 +149,8 @@ public class OptionMustHaveValidConverterAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -169,8 +169,8 @@ public class OptionMustHaveValidConverterAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
public string Foo { get; set; }
|
||||
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
|
||||
@@ -19,7 +19,7 @@ public class OptionMustHaveValidNameAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption("f")]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -40,7 +40,7 @@ public class OptionMustHaveValidNameAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption("1foo")]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -61,7 +61,7 @@ public class OptionMustHaveValidNameAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -82,7 +82,7 @@ public class OptionMustHaveValidNameAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -102,7 +102,7 @@ public class OptionMustHaveValidNameAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ public class OptionMustHaveValidShortNameAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption('1')]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -40,7 +40,7 @@ public class OptionMustHaveValidShortNameAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -61,7 +61,7 @@ public class OptionMustHaveValidShortNameAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -81,7 +81,7 @@ public class OptionMustHaveValidShortNameAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ public class OptionMustHaveValidValidatorsAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption("foo", Validators = new[] {typeof(MyValidator)})]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -50,7 +50,7 @@ public class OptionMustHaveValidValidatorsAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption("foo", Validators = new[] {typeof(MyValidator)})]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -76,7 +76,7 @@ public class OptionMustHaveValidValidatorsAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption("foo", Validators = new[] {typeof(MyValidator)})]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -97,7 +97,7 @@ public class OptionMustHaveValidValidatorsAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -117,7 +117,7 @@ public class OptionMustHaveValidValidatorsAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ public class ParameterMustBeInsideCommandAnalyzerSpecs
|
||||
public class MyClass
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
public required string Foo { get; init; }
|
||||
}
|
||||
""";
|
||||
|
||||
@@ -37,8 +37,8 @@ public class ParameterMustBeInsideCommandAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -57,7 +57,7 @@ public class ParameterMustBeInsideCommandAnalyzerSpecs
|
||||
public abstract class MyCommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
public required string Foo { get; init; }
|
||||
}
|
||||
""";
|
||||
|
||||
@@ -75,8 +75,8 @@ public class ParameterMustBeInsideCommandAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
public string Foo { get; set; }
|
||||
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
|
||||
@@ -19,11 +19,11 @@ public class ParameterMustBeLastIfNonRequiredAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0, IsRequired = false)]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public string? Foo { get; init; }
|
||||
|
||||
[CommandParameter(1)]
|
||||
public string Bar { get; set; }
|
||||
|
||||
public required string Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -43,11 +43,11 @@ public class ParameterMustBeLastIfNonRequiredAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
[CommandParameter(1, IsRequired = false)]
|
||||
public string Bar { get; set; }
|
||||
|
||||
public string? Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -67,11 +67,11 @@ public class ParameterMustBeLastIfNonRequiredAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
|
||||
[CommandParameter(1, IsRequired = true)]
|
||||
public string Bar { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
[CommandParameter(1)]
|
||||
public required string Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -90,8 +90,8 @@ public class ParameterMustBeLastIfNonRequiredAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
public string Foo { get; set; }
|
||||
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
|
||||
@@ -19,11 +19,11 @@ public class ParameterMustBeLastIfNonScalarAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string[] Foo { get; set; }
|
||||
|
||||
public required string[] Foo { get; init; }
|
||||
|
||||
[CommandParameter(1)]
|
||||
public string Bar { get; set; }
|
||||
|
||||
public required string Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -43,11 +43,11 @@ public class ParameterMustBeLastIfNonScalarAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
[CommandParameter(1)]
|
||||
public string[] Bar { get; set; }
|
||||
|
||||
public required string[] Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -67,11 +67,11 @@ public class ParameterMustBeLastIfNonScalarAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
[CommandParameter(1)]
|
||||
public string Bar { get; set; }
|
||||
|
||||
public required string Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -90,8 +90,8 @@ public class ParameterMustBeLastIfNonScalarAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
public string Foo { get; set; }
|
||||
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
|
||||
@@ -19,7 +19,7 @@ public class ParameterMustBeRequiredIfPropertyRequiredAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0, IsRequired = false)]
|
||||
public required string Foo { get; set; }
|
||||
public required string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -39,8 +39,8 @@ public class ParameterMustBeRequiredIfPropertyRequiredAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0, IsRequired = true)]
|
||||
public required string Foo { get; set; }
|
||||
[CommandParameter(0)]
|
||||
public required string Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -61,7 +61,7 @@ public class ParameterMustBeRequiredIfPropertyRequiredAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0, IsRequired = false)]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -81,8 +81,8 @@ public class ParameterMustBeRequiredIfPropertyRequiredAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0, IsRequired = true)]
|
||||
public string Foo { get; set; }
|
||||
[CommandParameter(0)]
|
||||
public required string Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -102,7 +102,7 @@ public class ParameterMustBeRequiredIfPropertyRequiredAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
public required string Foo { get; set; }
|
||||
public required string Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
|
||||
@@ -19,11 +19,11 @@ public class ParameterMustBeSingleIfNonRequiredAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0, IsRequired = false)]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public string? Foo { get; init; }
|
||||
|
||||
[CommandParameter(1, IsRequired = false)]
|
||||
public string Bar { get; set; }
|
||||
|
||||
public string? Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -43,11 +43,11 @@ public class ParameterMustBeSingleIfNonRequiredAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
[CommandParameter(1, IsRequired = false)]
|
||||
public string Bar { get; set; }
|
||||
|
||||
public string? Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -67,11 +67,11 @@ public class ParameterMustBeSingleIfNonRequiredAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
|
||||
[CommandParameter(1, IsRequired = true)]
|
||||
public string Bar { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
[CommandParameter(1)]
|
||||
public required string Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -90,8 +90,8 @@ public class ParameterMustBeSingleIfNonRequiredAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
public string Foo { get; set; }
|
||||
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
|
||||
@@ -19,11 +19,11 @@ public class ParameterMustBeSingleIfNonScalarAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string[] Foo { get; set; }
|
||||
|
||||
public required string[] Foo { get; init; }
|
||||
|
||||
[CommandParameter(1)]
|
||||
public string[] Bar { get; set; }
|
||||
|
||||
public required string[] Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -43,11 +43,11 @@ public class ParameterMustBeSingleIfNonScalarAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
[CommandParameter(1)]
|
||||
public string[] Bar { get; set; }
|
||||
|
||||
public required string[] Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -67,11 +67,11 @@ public class ParameterMustBeSingleIfNonScalarAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
[CommandParameter(1)]
|
||||
public string Bar { get; set; }
|
||||
|
||||
public required string Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -90,8 +90,8 @@ public class ParameterMustBeSingleIfNonScalarAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
public string Foo { get; set; }
|
||||
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
|
||||
@@ -19,11 +19,11 @@ public class ParameterMustHaveUniqueNameAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0, Name = "foo")]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
[CommandParameter(1, Name = "foo")]
|
||||
public string Bar { get; set; }
|
||||
|
||||
public required string Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -43,11 +43,11 @@ public class ParameterMustHaveUniqueNameAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0, Name = "foo")]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
[CommandParameter(1, Name = "bar")]
|
||||
public string Bar { get; set; }
|
||||
|
||||
public required string Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -66,8 +66,8 @@ public class ParameterMustHaveUniqueNameAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
public string Foo { get; set; }
|
||||
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
|
||||
@@ -19,11 +19,11 @@ public class ParameterMustHaveUniqueOrderAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
[CommandParameter(0)]
|
||||
public string Bar { get; set; }
|
||||
|
||||
public required string Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -43,11 +43,11 @@ public class ParameterMustHaveUniqueOrderAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
[CommandParameter(1)]
|
||||
public string Bar { get; set; }
|
||||
|
||||
public required string Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -66,8 +66,8 @@ public class ParameterMustHaveUniqueOrderAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
public string Foo { get; set; }
|
||||
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
|
||||
@@ -17,15 +17,15 @@ public class ParameterMustHaveValidConverterAnalyzerSpecs
|
||||
"""
|
||||
public class MyConverter
|
||||
{
|
||||
public string Convert(string rawValue) => rawValue;
|
||||
public string Convert(string? rawValue) => rawValue;
|
||||
}
|
||||
|
||||
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0, Converter = typeof(MyConverter))]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -43,15 +43,15 @@ public class ParameterMustHaveValidConverterAnalyzerSpecs
|
||||
"""
|
||||
public class MyConverter : BindingConverter<int>
|
||||
{
|
||||
public override int Convert(string rawValue) => 42;
|
||||
public override int Convert(string? rawValue) => 42;
|
||||
}
|
||||
|
||||
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0, Converter = typeof(MyConverter))]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -70,15 +70,15 @@ public class ParameterMustHaveValidConverterAnalyzerSpecs
|
||||
"""
|
||||
public class MyConverter : BindingConverter<string>
|
||||
{
|
||||
public override string Convert(string rawValue) => rawValue;
|
||||
public override string Convert(string? rawValue) => rawValue;
|
||||
}
|
||||
|
||||
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0, Converter = typeof(MyConverter))]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -96,15 +96,15 @@ public class ParameterMustHaveValidConverterAnalyzerSpecs
|
||||
"""
|
||||
public class MyConverter : BindingConverter<int>
|
||||
{
|
||||
public override int Convert(string rawValue) => 42;
|
||||
public override int Convert(string? rawValue) => 42;
|
||||
}
|
||||
|
||||
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandOption("foo", Converter = typeof(MyConverter))]
|
||||
public int? Foo { get; set; }
|
||||
|
||||
public int? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -122,15 +122,15 @@ public class ParameterMustHaveValidConverterAnalyzerSpecs
|
||||
"""
|
||||
public class MyConverter : BindingConverter<string>
|
||||
{
|
||||
public override string Convert(string rawValue) => rawValue;
|
||||
public override string Convert(string? rawValue) => rawValue;
|
||||
}
|
||||
|
||||
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0, Converter = typeof(MyConverter))]
|
||||
public IReadOnlyList<string> Foo { get; set; }
|
||||
|
||||
public required IReadOnlyList<string> Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -150,8 +150,8 @@ public class ParameterMustHaveValidConverterAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -170,8 +170,8 @@ public class ParameterMustHaveValidConverterAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
public string Foo { get; set; }
|
||||
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
|
||||
@@ -19,13 +19,13 @@ public class ParameterMustHaveValidValidatorsAnalyzerSpecs
|
||||
{
|
||||
public void Validate(string value) {}
|
||||
}
|
||||
|
||||
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0, Validators = new[] {typeof(MyValidator)})]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -45,13 +45,13 @@ public class ParameterMustHaveValidValidatorsAnalyzerSpecs
|
||||
{
|
||||
public override BindingValidationError Validate(int value) => Ok();
|
||||
}
|
||||
|
||||
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0, Validators = new[] {typeof(MyValidator)})]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -71,13 +71,13 @@ public class ParameterMustHaveValidValidatorsAnalyzerSpecs
|
||||
{
|
||||
public override BindingValidationError Validate(string value) => Ok();
|
||||
}
|
||||
|
||||
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0, Validators = new[] {typeof(MyValidator)})]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -97,8 +97,8 @@ public class ParameterMustHaveValidValidatorsAnalyzerSpecs
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public required string Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
@@ -117,8 +117,8 @@ public class ParameterMustHaveValidValidatorsAnalyzerSpecs
|
||||
[Command]
|
||||
public class MyCommand : ICommand
|
||||
{
|
||||
public string Foo { get; set; }
|
||||
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
""";
|
||||
|
||||
@@ -4,9 +4,10 @@
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
|
||||
<GenerateDependencyFile>true</GenerateDependencyFile>
|
||||
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
|
||||
<NoWarn>$(NoWarn);RS1025;RS1026</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
|
||||
<PropertyGroup>
|
||||
<!--
|
||||
Because this project only has a single target framework, the condition in
|
||||
@@ -16,7 +17,10 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.4.0" PrivateAssets="all" />
|
||||
<!-- Make sure to target the lowest possible version of the compiler for wider support -->
|
||||
<PackageReference Include="Microsoft.CodeAnalysis" Version="3.0.0" PrivateAssets="all" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.0.0" PrivateAssets="all" />
|
||||
<PackageReference Include="PolyShim" Version="1.2.0" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -24,7 +24,7 @@ public class OptionMustBeRequiredIfPropertyRequiredAnalyzer : AnalyzerBase
|
||||
if (property.ContainingType is null)
|
||||
return;
|
||||
|
||||
if (!property.IsRequired)
|
||||
if (!property.IsRequired())
|
||||
return;
|
||||
|
||||
var option = CommandOptionSymbol.TryResolve(property);
|
||||
|
||||
@@ -39,7 +39,7 @@ public class OptionMustHaveUniqueNameAnalyzer : AnalyzerBase
|
||||
.ContainingType
|
||||
.GetMembers()
|
||||
.OfType<IPropertySymbol>()
|
||||
.Where(m => !m.Equals(property, SymbolEqualityComparer.Default))
|
||||
.Where(m => !m.Equals(property))
|
||||
.ToArray();
|
||||
|
||||
foreach (var otherProperty in otherProperties)
|
||||
|
||||
@@ -38,7 +38,7 @@ public class OptionMustHaveUniqueShortNameAnalyzer : AnalyzerBase
|
||||
.ContainingType
|
||||
.GetMembers()
|
||||
.OfType<IPropertySymbol>()
|
||||
.Where(m => !m.Equals(property, SymbolEqualityComparer.Default))
|
||||
.Where(m => !m.Equals(property))
|
||||
.ToArray();
|
||||
|
||||
foreach (var otherProperty in otherProperties)
|
||||
|
||||
@@ -37,7 +37,7 @@ public class ParameterMustBeLastIfNonRequiredAnalyzer : AnalyzerBase
|
||||
.ContainingType
|
||||
.GetMembers()
|
||||
.OfType<IPropertySymbol>()
|
||||
.Where(m => !m.Equals(property, SymbolEqualityComparer.Default))
|
||||
.Where(m => !m.Equals(property))
|
||||
.ToArray();
|
||||
|
||||
foreach (var otherProperty in otherProperties)
|
||||
|
||||
@@ -37,7 +37,7 @@ public class ParameterMustBeLastIfNonScalarAnalyzer : AnalyzerBase
|
||||
.ContainingType
|
||||
.GetMembers()
|
||||
.OfType<IPropertySymbol>()
|
||||
.Where(m => !m.Equals(property, SymbolEqualityComparer.Default))
|
||||
.Where(m => !m.Equals(property))
|
||||
.ToArray();
|
||||
|
||||
foreach (var otherProperty in otherProperties)
|
||||
|
||||
@@ -24,7 +24,7 @@ public class ParameterMustBeRequiredIfPropertyRequiredAnalyzer : AnalyzerBase
|
||||
if (property.ContainingType is null)
|
||||
return;
|
||||
|
||||
if (!property.IsRequired)
|
||||
if (!property.IsRequired())
|
||||
return;
|
||||
|
||||
var parameter = CommandParameterSymbol.TryResolve(property);
|
||||
|
||||
@@ -37,7 +37,7 @@ public class ParameterMustBeSingleIfNonRequiredAnalyzer : AnalyzerBase
|
||||
.ContainingType
|
||||
.GetMembers()
|
||||
.OfType<IPropertySymbol>()
|
||||
.Where(m => !m.Equals(property, SymbolEqualityComparer.Default))
|
||||
.Where(m => !m.Equals(property))
|
||||
.ToArray();
|
||||
|
||||
foreach (var otherProperty in otherProperties)
|
||||
|
||||
@@ -37,7 +37,7 @@ public class ParameterMustBeSingleIfNonScalarAnalyzer : AnalyzerBase
|
||||
.ContainingType
|
||||
.GetMembers()
|
||||
.OfType<IPropertySymbol>()
|
||||
.Where(m => !m.Equals(property, SymbolEqualityComparer.Default))
|
||||
.Where(m => !m.Equals(property))
|
||||
.ToArray();
|
||||
|
||||
foreach (var otherProperty in otherProperties)
|
||||
|
||||
@@ -39,7 +39,7 @@ public class ParameterMustHaveUniqueNameAnalyzer : AnalyzerBase
|
||||
.ContainingType
|
||||
.GetMembers()
|
||||
.OfType<IPropertySymbol>()
|
||||
.Where(m => !m.Equals(property, SymbolEqualityComparer.Default))
|
||||
.Where(m => !m.Equals(property))
|
||||
.ToArray();
|
||||
|
||||
foreach (var otherProperty in otherProperties)
|
||||
|
||||
@@ -35,7 +35,7 @@ public class ParameterMustHaveUniqueOrderAnalyzer : AnalyzerBase
|
||||
.ContainingType
|
||||
.GetMembers()
|
||||
.OfType<IPropertySymbol>()
|
||||
.Where(m => !m.Equals(property, SymbolEqualityComparer.Default))
|
||||
.Where(m => !m.Equals(property))
|
||||
.ToArray();
|
||||
|
||||
foreach (var otherProperty in otherProperties)
|
||||
|
||||
@@ -34,6 +34,17 @@ internal static class RoslynExtensions
|
||||
.FirstOrDefault(i => i.ConstructedFrom.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T)?
|
||||
.TypeArguments[0];
|
||||
|
||||
// Detect if the property is required through roundabout means so as to not have to take dependency
|
||||
// on higher versions of the C# compiler.
|
||||
public static bool IsRequired(this IPropertySymbol property) => property
|
||||
// Can't rely on the RequiredMemberAttribute because it's generated by the compiler, not added by the user,
|
||||
// so we have to check for the presence of the `required` modifier in the syntax tree instead.
|
||||
.DeclaringSyntaxReferences
|
||||
.Select(r => r.GetSyntax())
|
||||
.OfType<PropertyDeclarationSyntax>()
|
||||
.SelectMany(p => p.Modifiers)
|
||||
.Any(m => m.IsKind((SyntaxKind)8447));
|
||||
|
||||
public static bool IsAssignable(this Compilation compilation, ITypeSymbol source, ITypeSymbol destination) =>
|
||||
compilation.ClassifyConversion(source, destination).Exists;
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ internal static class StringExtensions
|
||||
StringComparison comparison = StringComparison.Ordinal)
|
||||
{
|
||||
while (str.EndsWith(sub, comparison))
|
||||
str = str.Substring(0, str.Length - sub.Length);
|
||||
str = str[..^sub.Length];
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
@@ -6,12 +6,12 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="BenchmarkDotNet" Version="0.13.2" />
|
||||
<PackageReference Include="BenchmarkDotNet" Version="0.13.5" />
|
||||
<PackageReference Include="clipr" Version="1.6.1" />
|
||||
<PackageReference Include="Cocona" Version="2.1.0" />
|
||||
<PackageReference Include="Cocona" Version="2.2.0" />
|
||||
<PackageReference Include="CommandLineParser" Version="2.9.1" />
|
||||
<PackageReference Include="McMaster.Extensions.CommandLineUtils" Version="4.0.2" />
|
||||
<PackageReference Include="PowerArgs" Version="4.0.0" />
|
||||
<PackageReference Include="PowerArgs" Version="4.0.2" />
|
||||
<PackageReference Include="System.CommandLine" Version="2.0.0-beta1.20574.7" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -16,7 +16,7 @@ public partial class BookAddCommand : ICommand
|
||||
[CommandParameter(0, Name = "title", Description = "Book title.")]
|
||||
public required string Title { get; init; }
|
||||
|
||||
[CommandOption("author", 'a', IsRequired = true, Description = "Book author.")]
|
||||
[CommandOption("author", 'a', Description = "Book author.")]
|
||||
public required string Author { get; init; }
|
||||
|
||||
[CommandOption("published", 'p', Description = "Book publish date.")]
|
||||
|
||||
@@ -2,21 +2,4 @@
|
||||
|
||||
namespace CliFx.Demo.Domain;
|
||||
|
||||
public class Book
|
||||
{
|
||||
public string Title { get; }
|
||||
|
||||
public string Author { get; }
|
||||
|
||||
public DateTimeOffset Published { get; }
|
||||
|
||||
public Isbn Isbn { get; }
|
||||
|
||||
public Book(string title, string author, DateTimeOffset published, Isbn isbn)
|
||||
{
|
||||
Title = title;
|
||||
Author = author;
|
||||
Published = published;
|
||||
Isbn = isbn;
|
||||
}
|
||||
}
|
||||
public record Book(string Title, string Author, DateTimeOffset Published, Isbn Isbn);
|
||||
@@ -2,32 +2,13 @@
|
||||
|
||||
namespace CliFx.Demo.Domain;
|
||||
|
||||
public partial class Isbn
|
||||
public partial record Isbn(int EanPrefix, int RegistrationGroup, int Registrant, int Publication, int CheckDigit)
|
||||
{
|
||||
public int EanPrefix { get; }
|
||||
|
||||
public int RegistrationGroup { get; }
|
||||
|
||||
public int Registrant { get; }
|
||||
|
||||
public int Publication { get; }
|
||||
|
||||
public int CheckDigit { get; }
|
||||
|
||||
public Isbn(int eanPrefix, int registrationGroup, int registrant, int publication, int checkDigit)
|
||||
{
|
||||
EanPrefix = eanPrefix;
|
||||
RegistrationGroup = registrationGroup;
|
||||
Registrant = registrant;
|
||||
Publication = publication;
|
||||
CheckDigit = checkDigit;
|
||||
}
|
||||
|
||||
public override string ToString() =>
|
||||
$"{EanPrefix:000}-{RegistrationGroup:00}-{Registrant:00000}-{Publication:00}-{CheckDigit:0}";
|
||||
}
|
||||
|
||||
public partial class Isbn
|
||||
public partial record Isbn
|
||||
{
|
||||
public static Isbn Parse(string value, IFormatProvider formatProvider)
|
||||
{
|
||||
|
||||
@@ -4,15 +4,8 @@ using System.Linq;
|
||||
|
||||
namespace CliFx.Demo.Domain;
|
||||
|
||||
public partial class Library
|
||||
public partial record Library(IReadOnlyList<Book> Books)
|
||||
{
|
||||
public IReadOnlyList<Book> Books { get; }
|
||||
|
||||
public Library(IReadOnlyList<Book> books)
|
||||
{
|
||||
Books = books;
|
||||
}
|
||||
|
||||
public Library WithBook(Book book)
|
||||
{
|
||||
var books = Books.ToList();
|
||||
@@ -29,7 +22,7 @@ public partial class Library
|
||||
}
|
||||
}
|
||||
|
||||
public partial class Library
|
||||
public partial record Library
|
||||
{
|
||||
public static Library Empty { get; } = new(Array.Empty<Book>());
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Newtonsoft.Json;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace CliFx.Demo.Domain;
|
||||
|
||||
@@ -10,7 +10,7 @@ public class LibraryProvider
|
||||
|
||||
private void StoreLibrary(Library library)
|
||||
{
|
||||
var data = JsonConvert.SerializeObject(library);
|
||||
var data = JsonSerializer.Serialize(library);
|
||||
File.WriteAllText(StorageFilePath, data);
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ public class LibraryProvider
|
||||
|
||||
var data = File.ReadAllText(StorageFilePath);
|
||||
|
||||
return JsonConvert.DeserializeObject<Library>(data) ?? Library.Empty;
|
||||
return JsonSerializer.Deserialize<Library>(data) ?? Library.Empty;
|
||||
}
|
||||
|
||||
public Book? TryGetBook(string title) => GetLibrary().Books.FirstOrDefault(b => b.Title == title);
|
||||
|
||||
@@ -1,25 +1,21 @@
|
||||
using CliFx;
|
||||
using CliFx.Demo.Commands;
|
||||
using CliFx.Demo.Domain;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
// We use Microsoft.Extensions.DependencyInjection for injecting dependencies in commands
|
||||
var services = new ServiceCollection();
|
||||
|
||||
// Register services
|
||||
services.AddSingleton<LibraryProvider>();
|
||||
|
||||
// Register commands
|
||||
services.AddTransient<BookCommand>();
|
||||
services.AddTransient<BookAddCommand>();
|
||||
services.AddTransient<BookRemoveCommand>();
|
||||
services.AddTransient<BookListCommand>();
|
||||
|
||||
var serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
return await new CliApplicationBuilder()
|
||||
.SetDescription("Demo application showcasing CliFx features.")
|
||||
.AddCommandsFromThisAssembly()
|
||||
.UseTypeActivator(serviceProvider.GetRequiredService)
|
||||
.UseTypeActivator(commandTypes =>
|
||||
{
|
||||
// We use Microsoft.Extensions.DependencyInjection for injecting dependencies in commands
|
||||
var services = new ServiceCollection();
|
||||
services.AddSingleton<LibraryProvider>();
|
||||
|
||||
// Register all commands as transient services
|
||||
foreach (var commandType in commandTypes)
|
||||
services.AddTransient(commandType);
|
||||
|
||||
return services.BuildServiceProvider();
|
||||
})
|
||||
.Build()
|
||||
.RunAsync();
|
||||
@@ -1,5 +1,5 @@
|
||||
# CliFx Demo Project
|
||||
|
||||
Sample command line interface for managing a library of books.
|
||||
Sample command-line interface for managing a library of books.
|
||||
|
||||
This demo project showcases basic CliFx functionality such as command routing, argument parsing, and autogenerated help text.
|
||||
This demo project showcases basic CliFx functionality such as command routing, argument parsing, and autogenerated help text.
|
||||
|
||||
30
CliFx.Tests.Dummy/Commands/CancellationTestCommand.cs
Normal file
30
CliFx.Tests.Dummy/Commands/CancellationTestCommand.cs
Normal file
@@ -0,0 +1,30 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
|
||||
namespace CliFx.Tests.Dummy.Commands;
|
||||
|
||||
[Command("cancel-test")]
|
||||
public class CancellationTestCommand : ICommand
|
||||
{
|
||||
public async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
try
|
||||
{
|
||||
console.Output.WriteLine("Started.");
|
||||
|
||||
await Task.Delay(
|
||||
TimeSpan.FromSeconds(3),
|
||||
console.RegisterCancellationHandler()
|
||||
);
|
||||
|
||||
console.Output.WriteLine("Completed.");
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
console.Output.WriteLine("Cancelled.");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ namespace CliFx.Tests.Dummy.Commands;
|
||||
public class EnvironmentTestCommand : ICommand
|
||||
{
|
||||
[CommandOption("target", EnvironmentVariable = "ENV_TARGET")]
|
||||
public string GreetingTarget { get; set; } = "World";
|
||||
public string GreetingTarget { get; init; } = "World";
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
|
||||
@@ -3,12 +3,11 @@ using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace CliFx.Tests.Dummy;
|
||||
// This dummy application is used in tests for scenarios
|
||||
// that require an external process to properly verify.
|
||||
|
||||
// This dummy application is used in tests for scenarios that require an external process to properly verify
|
||||
public static partial class Program
|
||||
{
|
||||
public static Assembly Assembly { get; } = typeof(Program).Assembly;
|
||||
public static Assembly Assembly { get; } = Assembly.GetExecutingAssembly();
|
||||
|
||||
public static string Location { get; } = Assembly.Location;
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ public class ApplicationSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Application_can_be_created_with_minimal_configuration()
|
||||
public async Task I_can_create_an_application_with_the_default_configuration()
|
||||
{
|
||||
// Act
|
||||
var app = new CliApplicationBuilder()
|
||||
@@ -34,7 +34,7 @@ public class ApplicationSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Application_can_be_created_with_a_fully_customized_configuration()
|
||||
public async Task I_can_create_an_application_with_a_custom_configuration()
|
||||
{
|
||||
// Act
|
||||
var app = new CliApplicationBuilder()
|
||||
@@ -63,7 +63,7 @@ public class ApplicationSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Application_configuration_fails_if_an_invalid_command_is_registered()
|
||||
public async Task I_cannot_add_an_invalid_command_to_the_application()
|
||||
{
|
||||
// Act
|
||||
var app = new CliApplicationBuilder()
|
||||
@@ -76,10 +76,10 @@ public class ApplicationSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Should().Contain("not a valid command");
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx.Tests.Utils;
|
||||
using CliFx.Tests.Utils.Extensions;
|
||||
using CliWrap;
|
||||
using FluentAssertions;
|
||||
using Xunit;
|
||||
using Xunit.Abstractions;
|
||||
@@ -15,8 +19,52 @@ public class CancellationSpecs : SpecsBase
|
||||
{
|
||||
}
|
||||
|
||||
[Fact(Timeout = 15000)]
|
||||
public async Task I_can_configure_the_command_to_listen_to_the_interrupt_signal()
|
||||
{
|
||||
// Arrange
|
||||
using var cts = new CancellationTokenSource();
|
||||
|
||||
// We need to send the cancellation request right after the process has registered
|
||||
// a handler for the interrupt signal, otherwise the default handler will trigger
|
||||
// and just kill the process.
|
||||
void HandleStdOut(string line)
|
||||
{
|
||||
if (string.Equals(line, "Started.", StringComparison.OrdinalIgnoreCase))
|
||||
cts.CancelAfter(TimeSpan.FromSeconds(0.2));
|
||||
}
|
||||
|
||||
var stdOutBuffer = new StringBuilder();
|
||||
|
||||
var pipeTarget = PipeTarget.Merge(
|
||||
PipeTarget.ToDelegate(HandleStdOut),
|
||||
PipeTarget.ToStringBuilder(stdOutBuffer)
|
||||
);
|
||||
|
||||
var command = Cli.Wrap("dotnet")
|
||||
.WithArguments(a => a
|
||||
.Add(Dummy.Program.Location)
|
||||
.Add("cancel-test")
|
||||
) | pipeTarget;
|
||||
|
||||
// Act & assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () =>
|
||||
await command.ExecuteAsync(
|
||||
// Forceful cancellation (not required because we have a timeout)
|
||||
CancellationToken.None,
|
||||
// Graceful cancellation
|
||||
cts.Token
|
||||
)
|
||||
);
|
||||
|
||||
stdOutBuffer.ToString().Trim().Should().ConsistOfLines(
|
||||
"Started.",
|
||||
"Cancelled."
|
||||
);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Command_can_register_to_receive_a_cancellation_signal_from_the_console()
|
||||
public async Task I_can_configure_the_command_to_listen_to_the_interrupt_signal_when_running_in_isolation()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -29,16 +77,18 @@ public class CancellationSpecs : SpecsBase
|
||||
{
|
||||
try
|
||||
{
|
||||
console.Output.WriteLine("Started.");
|
||||
|
||||
await Task.Delay(
|
||||
TimeSpan.FromSeconds(3),
|
||||
console.RegisterCancellationHandler()
|
||||
);
|
||||
|
||||
console.Output.WriteLine("Completed successfully");
|
||||
console.Output.WriteLine("Completed.");
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
console.Output.WriteLine("Cancelled");
|
||||
console.Output.WriteLine("Cancelled.");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -51,18 +101,21 @@ public class CancellationSpecs : SpecsBase
|
||||
.UseConsole(FakeConsole)
|
||||
.Build();
|
||||
|
||||
// Act
|
||||
FakeConsole.RequestCancellation(TimeSpan.FromSeconds(0.2));
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
Array.Empty<string>(),
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
stdOut.Trim().Should().Be("Cancelled");
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().ConsistOfLines(
|
||||
"Started.",
|
||||
"Cancelled."
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -9,13 +9,13 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Basic.Reference.Assemblies.Net70" Version="1.4.1" />
|
||||
<PackageReference Include="CliWrap" Version="3.5.0" />
|
||||
<PackageReference Include="FluentAssertions" Version="6.8.0" />
|
||||
<PackageReference Include="GitHubActionsTestLogger" Version="2.0.1" PrivateAssets="all" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.4.0" />
|
||||
<PackageReference Include="Basic.Reference.Assemblies.Net70" Version="1.4.2" />
|
||||
<PackageReference Include="CliWrap" Version="3.6.1" />
|
||||
<PackageReference Include="FluentAssertions" Version="6.11.0" />
|
||||
<PackageReference Include="GitHubActionsTestLogger" Version="2.2.0" PrivateAssets="all" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.6.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
|
||||
<PackageReference Include="xunit" Version="2.4.2" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5" PrivateAssets="all" />
|
||||
<PackageReference Include="coverlet.collector" Version="3.2.0" PrivateAssets="all" />
|
||||
|
||||
@@ -21,11 +21,10 @@ public class ConsoleSpecs : SpecsBase
|
||||
{
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Real_console_maps_directly_to_system_console()
|
||||
[Fact(Timeout = 15000)]
|
||||
public async Task I_can_run_the_application_with_the_default_console_implementation_to_interact_with_the_system_console()
|
||||
{
|
||||
// Can't verify our own console output, so using an
|
||||
// external process for this test.
|
||||
// Can't verify our own console output, so using an external process for this test
|
||||
|
||||
// Arrange
|
||||
var command = "Hello world" | Cli.Wrap("dotnet")
|
||||
@@ -43,7 +42,26 @@ public class ConsoleSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Fake_console_does_not_leak_to_system_console()
|
||||
public void I_can_run_the_application_on_a_system_with_a_custom_console_encoding_and_not_get_corrupted_output()
|
||||
{
|
||||
// Arrange
|
||||
using var buffer = new MemoryStream();
|
||||
using var consoleWriter = new ConsoleWriter(FakeConsole, buffer, Encoding.UTF8);
|
||||
|
||||
// Act
|
||||
consoleWriter.Write("Hello world");
|
||||
consoleWriter.Flush();
|
||||
|
||||
// Assert
|
||||
var outputBytes = buffer.ToArray();
|
||||
outputBytes.Should().NotContain(Encoding.UTF8.GetPreamble());
|
||||
|
||||
var output = consoleWriter.Encoding.GetString(outputBytes);
|
||||
output.Should().Be("Hello world");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task I_can_run_the_application_with_the_fake_console_implementation_to_isolate_console_interactions()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -104,7 +122,7 @@ public class ConsoleSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Fake_console_can_be_used_with_an_in_memory_backing_store()
|
||||
public async Task I_can_run_the_application_with_the_fake_console_implementation_and_simulate_stream_interactions()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -138,17 +156,18 @@ public class ConsoleSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().Be("Hello world");
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Trim().Should().Be("Hello world");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Fake_console_can_read_key_presses()
|
||||
public async Task I_can_run_the_application_with_the_fake_console_implementation_and_simulate_key_presses()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -184,31 +203,14 @@ public class ConsoleSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().ConsistOfLines(
|
||||
"D0",
|
||||
"A",
|
||||
"Backspace"
|
||||
);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Console_does_not_emit_preamble_when_used_with_encoding_that_has_it()
|
||||
{
|
||||
// Arrange
|
||||
using var buffer = new MemoryStream();
|
||||
using var consoleWriter = new ConsoleWriter(FakeConsole, buffer, Encoding.UTF8);
|
||||
|
||||
// Act
|
||||
consoleWriter.Write("Hello world");
|
||||
consoleWriter.Flush();
|
||||
|
||||
var output = consoleWriter.Encoding.GetString(buffer.ToArray());
|
||||
|
||||
// Assert
|
||||
output.Should().Be("Hello world");
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ public class ConversionSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_can_be_converted_to_a_string()
|
||||
public async Task I_can_bind_a_parameter_or_an_option_to_a_string_property()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -26,7 +26,7 @@ public class ConversionSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -48,15 +48,15 @@ public class ConversionSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().Be("xyz");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_can_be_converted_to_an_object()
|
||||
public async Task I_can_bind_a_parameter_or_an_option_to_an_object_property()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -66,7 +66,7 @@ public class ConversionSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public object Foo { get; set; }
|
||||
public object? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -88,15 +88,15 @@ public class ConversionSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().Be("xyz");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_can_be_converted_to_a_boolean()
|
||||
public async Task I_can_bind_a_parameter_or_an_option_to_a_boolean_property()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -106,15 +106,19 @@ public class ConversionSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public bool Foo { get; set; }
|
||||
public bool Foo { get; init; }
|
||||
|
||||
[CommandOption('b')]
|
||||
public bool Bar { get; set; }
|
||||
public bool Bar { get; init; }
|
||||
|
||||
[CommandOption('c')]
|
||||
public bool Baz { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
console.Output.WriteLine("Foo = " + Foo);
|
||||
console.Output.WriteLine("Bar = " + Bar);
|
||||
console.Output.WriteLine("Baz = " + Baz);
|
||||
|
||||
return default;
|
||||
}
|
||||
@@ -129,22 +133,28 @@ public class ConversionSpecs : SpecsBase
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
new[] {"-f", "true", "-b", "false"},
|
||||
new[]
|
||||
{
|
||||
"-f", "true",
|
||||
"-b", "false",
|
||||
"-c"
|
||||
},
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"Foo = True",
|
||||
"Bar = False"
|
||||
"Bar = False",
|
||||
"Baz = True"
|
||||
);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_can_be_converted_to_a_boolean_with_implicit_value()
|
||||
public async Task I_can_bind_a_parameter_or_an_option_to_an_integer_property()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -154,47 +164,7 @@ public class ConversionSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public bool Foo { get; set; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
console.Output.WriteLine(Foo);
|
||||
return default;
|
||||
}
|
||||
}
|
||||
"""
|
||||
);
|
||||
|
||||
var application = new CliApplicationBuilder()
|
||||
.AddCommand(commandType)
|
||||
.UseConsole(FakeConsole)
|
||||
.Build();
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
new[] {"-f"},
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
stdOut.Trim().Should().Be("True");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_can_be_converted_to_an_integer()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
// language=cs
|
||||
"""
|
||||
[Command]
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public int Foo { get; set; }
|
||||
public int Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -216,15 +186,15 @@ public class ConversionSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().Be("32");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_can_be_converted_to_a_double()
|
||||
public async Task I_can_bind_a_parameter_or_an_option_to_a_double_property()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -234,7 +204,7 @@ public class ConversionSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public double Foo { get; set; }
|
||||
public double Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -256,15 +226,15 @@ public class ConversionSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().Be("32.14");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_can_be_converted_to_DateTimeOffset()
|
||||
public async Task I_can_bind_a_parameter_or_an_option_to_a_DateTimeOffset_property()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -274,7 +244,7 @@ public class ConversionSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public DateTimeOffset Foo { get; set; }
|
||||
public DateTimeOffset Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -296,15 +266,15 @@ public class ConversionSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().Be("1995-04-28 00:00:00Z");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_can_be_converted_to_a_TimeSpan()
|
||||
public async Task I_can_bind_a_parameter_or_an_option_to_a_TimeSpan_property()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -314,7 +284,7 @@ public class ConversionSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public TimeSpan Foo { get; set; }
|
||||
public TimeSpan Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -336,15 +306,15 @@ public class ConversionSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().Be("12:34:56");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_can_be_converted_to_an_enum()
|
||||
public async Task I_can_bind_a_parameter_or_an_option_to_an_enum_property()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -356,7 +326,7 @@ public class ConversionSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public CustomEnum Foo { get; set; }
|
||||
public CustomEnum Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -378,15 +348,15 @@ public class ConversionSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().Be("2");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_can_be_converted_to_a_nullable_integer()
|
||||
public async Task I_can_bind_a_parameter_or_an_option_to_a_nullable_integer_property()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -396,10 +366,10 @@ public class ConversionSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public int? Foo { get; set; }
|
||||
public int? Foo { get; init; }
|
||||
|
||||
[CommandOption('b')]
|
||||
public int? Bar { get; set; }
|
||||
public int? Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -423,10 +393,10 @@ public class ConversionSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"Foo = ",
|
||||
"Bar = 123"
|
||||
@@ -434,7 +404,7 @@ public class ConversionSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_can_be_converted_to_a_nullable_enum()
|
||||
public async Task I_can_bind_a_parameter_or_an_option_to_a_nullable_enum_property()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -446,10 +416,10 @@ public class ConversionSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public CustomEnum? Foo { get; set; }
|
||||
public CustomEnum? Foo { get; init; }
|
||||
|
||||
[CommandOption('b')]
|
||||
public CustomEnum? Bar { get; set; }
|
||||
public CustomEnum? Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -473,10 +443,10 @@ public class ConversionSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"Foo = ",
|
||||
"Bar = 2"
|
||||
@@ -484,7 +454,7 @@ public class ConversionSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_can_be_converted_to_a_type_that_has_a_constructor_accepting_a_string()
|
||||
public async Task I_can_bind_a_parameter_or_an_option_to_a_string_constructable_object_property()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -501,7 +471,7 @@ public class ConversionSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public CustomType Foo { get; set; }
|
||||
public CustomType? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -523,15 +493,15 @@ public class ConversionSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().Be("xyz");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_can_be_converted_to_a_type_that_has_a_static_parse_method()
|
||||
public async Task I_can_bind_a_parameter_or_an_option_to_a_string_parsable_object_property()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -561,10 +531,10 @@ public class ConversionSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public CustomTypeA Foo { get; set; }
|
||||
public CustomTypeA? Foo { get; init; }
|
||||
|
||||
[CommandOption('b')]
|
||||
public CustomTypeB Bar { get; set; }
|
||||
public CustomTypeB? Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -588,10 +558,10 @@ public class ConversionSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"Foo = hello",
|
||||
"Bar = world"
|
||||
@@ -599,7 +569,7 @@ public class ConversionSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_can_be_converted_using_a_custom_converter()
|
||||
public async Task I_can_bind_a_parameter_or_an_option_to_a_property_with_a_custom_converter()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -615,7 +585,7 @@ public class ConversionSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f', Converter = typeof(CustomConverter))]
|
||||
public int Foo { get; set; }
|
||||
public int Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -637,15 +607,15 @@ public class ConversionSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().Be("11");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_can_be_converted_to_an_array_of_strings()
|
||||
public async Task I_can_bind_a_parameter_or_an_option_to_a_string_array_property()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -655,7 +625,7 @@ public class ConversionSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public string[] Foo { get; set; }
|
||||
public string[]? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -679,10 +649,10 @@ public class ConversionSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"one",
|
||||
"two",
|
||||
@@ -691,7 +661,7 @@ public class ConversionSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_can_be_converted_to_a_read_only_list_of_strings()
|
||||
public async Task I_can_bind_a_parameter_or_an_option_to_a_read_only_list_of_strings_property()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -701,7 +671,7 @@ public class ConversionSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public IReadOnlyList<string> Foo { get; set; }
|
||||
public IReadOnlyList<string>? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -725,10 +695,10 @@ public class ConversionSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"one",
|
||||
"two",
|
||||
@@ -737,7 +707,7 @@ public class ConversionSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_can_be_converted_to_a_list_of_strings()
|
||||
public async Task I_can_bind_a_parameter_or_an_option_to_a_string_list_property()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -747,7 +717,7 @@ public class ConversionSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public List<string> Foo { get; set; }
|
||||
public List<string>? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -771,10 +741,10 @@ public class ConversionSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"one",
|
||||
"two",
|
||||
@@ -783,7 +753,7 @@ public class ConversionSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_can_be_converted_to_an_array_of_integers()
|
||||
public async Task I_can_bind_a_parameter_or_an_option_to_an_integer_array_property()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -793,7 +763,7 @@ public class ConversionSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public int[] Foo { get; set; }
|
||||
public int[]? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -817,10 +787,10 @@ public class ConversionSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"1",
|
||||
"13",
|
||||
@@ -829,55 +799,21 @@ public class ConversionSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_conversion_fails_if_the_value_cannot_be_converted_to_the_target_type()
|
||||
public async Task I_cannot_bind_a_parameter_or_an_option_to_a_property_of_an_unsupported_type()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
// language=cs
|
||||
"""
|
||||
[Command]
|
||||
public class Command : ICommand
|
||||
public class CustomType
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public int Foo { get; set; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
"""
|
||||
);
|
||||
|
||||
var application = new CliApplicationBuilder()
|
||||
.AddCommand(commandType)
|
||||
.UseConsole(FakeConsole)
|
||||
.Build();
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
new[] {"-f", "12.34"},
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
stdErr.Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_conversion_fails_if_the_target_type_is_not_supported()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
// language=cs
|
||||
"""
|
||||
public class CustomType {}
|
||||
|
||||
[Command]
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public CustomType Foo { get; set; }
|
||||
public CustomType? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -895,15 +831,15 @@ public class ConversionSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Should().Contain("has an unsupported underlying property type");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_conversion_fails_if_the_target_non_scalar_type_is_not_supported()
|
||||
public async Task I_cannot_bind_a_parameter_or_an_option_to_a_non_scalar_property_of_an_unsupported_type()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -920,7 +856,7 @@ public class ConversionSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public CustomType Foo { get; set; }
|
||||
public CustomType? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -938,15 +874,51 @@ public class ConversionSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Should().Contain("has an unsupported underlying property type");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_conversion_fails_if_one_of_the_validators_fail()
|
||||
public async Task I_can_bind_a_parameter_or_an_option_to_a_property_and_get_an_error_if_the_user_provides_an_invalid_value()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
// language=cs
|
||||
"""
|
||||
[Command]
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public int Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
"""
|
||||
);
|
||||
|
||||
var application = new CliApplicationBuilder()
|
||||
.AddCommand(commandType)
|
||||
.UseConsole(FakeConsole)
|
||||
.Build();
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
new[] {"-f", "12.34"},
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task I_can_bind_a_parameter_or_an_option_to_a_property_and_get_an_error_if_a_custom_validator_fails()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -966,7 +938,7 @@ public class ConversionSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f', Validators = new[] {typeof(ValidatorA), typeof(ValidatorB)})]
|
||||
public int Foo { get; set; }
|
||||
public int Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -984,15 +956,15 @@ public class ConversionSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Should().Contain("Hello world");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_or_option_value_conversion_fails_if_the_static_parse_method_throws()
|
||||
public async Task I_can_bind_a_parameter_or_an_option_to_a_string_parsable_property_and_get_an_error_if_the_parsing_fails()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -1011,7 +983,7 @@ public class ConversionSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public CustomType Foo { get; set; }
|
||||
public CustomType? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -1029,10 +1001,10 @@ public class ConversionSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Should().Contain("Hello world");
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx.Tests.Utils;
|
||||
@@ -19,58 +18,39 @@ public class DirectivesSpecs : SpecsBase
|
||||
{
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Debug_directive_can_be_specified_to_interrupt_execution_until_a_debugger_is_attached()
|
||||
[Fact(Timeout = 15000)]
|
||||
public async Task I_can_use_the_debug_directive_to_make_the_application_wait_for_the_debugger_to_attach()
|
||||
{
|
||||
// Arrange
|
||||
var stdOutBuffer = new StringBuilder();
|
||||
using var cts = new CancellationTokenSource();
|
||||
|
||||
// We can't actually attach a debugger, but we can ensure that the process is waiting for one
|
||||
void HandleStdOut(string line)
|
||||
{
|
||||
// Kill the process once it writes the output we expect
|
||||
if (line.Contains("Attach the debugger to", StringComparison.OrdinalIgnoreCase))
|
||||
cts.Cancel();
|
||||
}
|
||||
|
||||
var command = Cli.Wrap("dotnet")
|
||||
.WithArguments(a => a
|
||||
.Add(Dummy.Program.Location)
|
||||
.Add("[debug]")
|
||||
) | stdOutBuffer;
|
||||
) | HandleStdOut;
|
||||
|
||||
// Act
|
||||
// Act & assert
|
||||
try
|
||||
{
|
||||
// This has a timeout just in case the execution hangs forever
|
||||
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||||
|
||||
var task = command.ExecuteAsync(cts.Token);
|
||||
|
||||
// We can't attach a debugger programmatically, so the application
|
||||
// will hang indefinitely.
|
||||
// To work around it, we will wait until the application writes
|
||||
// something to the standard output and then kill it.
|
||||
while (true)
|
||||
{
|
||||
if (stdOutBuffer.Length > 0)
|
||||
{
|
||||
cts.Cancel();
|
||||
break;
|
||||
}
|
||||
|
||||
await Task.Delay(100, cts.Token);
|
||||
}
|
||||
|
||||
await task;
|
||||
await command.ExecuteAsync(cts.Token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
catch (OperationCanceledException ex) when (ex.CancellationToken == cts.Token)
|
||||
{
|
||||
// This is expected
|
||||
// This means that the process was killed after it wrote the expected output
|
||||
}
|
||||
|
||||
var stdOut = stdOutBuffer.ToString();
|
||||
|
||||
// Assert
|
||||
stdOut.Should().Contain("Attach debugger to");
|
||||
|
||||
TestOutput.WriteLine(stdOut);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Preview_directive_can_be_specified_to_print_command_input()
|
||||
public async Task I_can_use_the_preview_directive_to_make_the_application_print_the_parsed_command_input()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -100,10 +80,10 @@ public class DirectivesSpecs : SpecsBase
|
||||
}
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ContainAllInOrder(
|
||||
"cmd", "<param>", "[-a]", "[-b]", "[-c]", "[--option \"foo\"]",
|
||||
"ENV_QOP", "=", "\"hello\"",
|
||||
|
||||
@@ -20,7 +20,7 @@ public class EnvironmentSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_can_fall_back_to_an_environment_variable()
|
||||
public async Task I_can_configure_an_option_to_fall_back_to_an_environment_variable_if_the_user_does_not_provide_the_corresponding_argument()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -29,12 +29,17 @@ public class EnvironmentSpecs : SpecsBase
|
||||
[Command]
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption("foo", IsRequired = true, EnvironmentVariable = "ENV_FOO")]
|
||||
public string Foo { get; set; }
|
||||
[CommandOption("foo", EnvironmentVariable = "ENV_FOO")]
|
||||
public string? Foo { get; init; }
|
||||
|
||||
[CommandOption("bar", EnvironmentVariable = "ENV_BAR")]
|
||||
public string? Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
console.Output.WriteLine(Foo);
|
||||
console.Output.WriteLine(Bar);
|
||||
|
||||
return default;
|
||||
}
|
||||
}
|
||||
@@ -48,22 +53,26 @@ public class EnvironmentSpecs : SpecsBase
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
Array.Empty<string>(),
|
||||
new[] {"--foo", "42"},
|
||||
new Dictionary<string, string>
|
||||
{
|
||||
["ENV_FOO"] = "bar"
|
||||
["ENV_FOO"] = "100",
|
||||
["ENV_BAR"] = "200"
|
||||
}
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
stdOut.Trim().Should().Be("bar");
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().ConsistOfLines(
|
||||
"42",
|
||||
"200"
|
||||
);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_does_not_fall_back_to_an_environment_variable_if_a_value_is_provided_through_arguments()
|
||||
public async Task I_can_configure_an_option_bound_to_a_non_scalar_property_to_fall_back_to_an_environment_variable_if_the_user_does_not_provide_the_corresponding_argument()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -73,50 +82,7 @@ public class EnvironmentSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption("foo", EnvironmentVariable = "ENV_FOO")]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
console.Output.WriteLine(Foo);
|
||||
return default;
|
||||
}
|
||||
}
|
||||
"""
|
||||
);
|
||||
|
||||
var application = new CliApplicationBuilder()
|
||||
.AddCommand(commandType)
|
||||
.UseConsole(FakeConsole)
|
||||
.Build();
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
new[] {"--foo", "baz"},
|
||||
new Dictionary<string, string>
|
||||
{
|
||||
["ENV_FOO"] = "bar"
|
||||
}
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
stdOut.Trim().Should().Be("baz");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_of_non_scalar_type_can_receive_multiple_values_from_an_environment_variable()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
// language=cs
|
||||
"""
|
||||
[Command]
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption("foo", EnvironmentVariable = "ENV_FOO")]
|
||||
public IReadOnlyList<string> Foo { get; set; }
|
||||
public IReadOnlyList<string>? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -143,10 +109,10 @@ public class EnvironmentSpecs : SpecsBase
|
||||
}
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"bar",
|
||||
"baz"
|
||||
@@ -154,7 +120,7 @@ public class EnvironmentSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_of_scalar_type_always_receives_a_single_value_from_an_environment_variable()
|
||||
public async Task I_can_configure_an_option_bound_to_a_scalar_property_to_fall_back_to_an_environment_variable_while_ignoring_path_separators()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -164,7 +130,7 @@ public class EnvironmentSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption("foo", EnvironmentVariable = "ENV_FOO")]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -189,60 +155,15 @@ public class EnvironmentSpecs : SpecsBase
|
||||
}
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().Be($"bar{Path.PathSeparator}baz");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Environment_variables_are_matched_case_sensitively()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
// language=cs
|
||||
"""
|
||||
[Command]
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption("foo", EnvironmentVariable = "ENV_FOO")]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
console.Output.WriteLine(Foo);
|
||||
return default;
|
||||
}
|
||||
}
|
||||
"""
|
||||
);
|
||||
|
||||
var application = new CliApplicationBuilder()
|
||||
.AddCommand(commandType)
|
||||
.UseConsole(FakeConsole)
|
||||
.Build();
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
Array.Empty<string>(),
|
||||
new Dictionary<string, string>
|
||||
{
|
||||
["ENV_foo"] = "baz",
|
||||
["ENV_FOO"] = "bar",
|
||||
["env_FOO"] = "qop"
|
||||
}
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
stdOut.Trim().Should().Be("bar");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Environment_variables_are_extracted_automatically()
|
||||
[Fact(Timeout = 15000)]
|
||||
public async Task I_can_run_the_application_and_it_will_resolve_all_required_environment_variables_automatically()
|
||||
{
|
||||
// Ensures that the environment variables are properly obtained from
|
||||
// System.Environment when they are not provided explicitly to CliApplication.
|
||||
|
||||
@@ -17,7 +17,7 @@ public class ErrorReportingSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Command_can_throw_an_exception_which_exits_with_a_stacktrace()
|
||||
public async Task I_can_throw_an_exception_in_a_command_to_report_an_error_with_a_stacktrace()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -43,12 +43,13 @@ public class ErrorReportingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().BeEmpty();
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Should().ContainAllInOrder(
|
||||
"System.Exception", "Something went wrong",
|
||||
"at", "CliFx."
|
||||
@@ -56,7 +57,7 @@ public class ErrorReportingSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Command_can_throw_an_exception_with_an_inner_exception_which_exits_with_a_stacktrace()
|
||||
public async Task I_can_throw_an_exception_with_an_inner_exception_in_a_command_to_report_an_error_with_a_stacktrace()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -82,12 +83,13 @@ public class ErrorReportingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().BeEmpty();
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Should().ContainAllInOrder(
|
||||
"System.Exception", "Something went wrong",
|
||||
"System.Exception", "Another exception",
|
||||
@@ -96,7 +98,7 @@ public class ErrorReportingSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Command_can_throw_a_special_exception_which_exits_with_specified_code_and_message()
|
||||
public async Task I_can_throw_an_exception_in_a_command_to_report_an_error_and_exit_with_the_specified_code()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -122,17 +124,18 @@ public class ErrorReportingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(69);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().BeEmpty();
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Trim().Should().Be("Something went wrong");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Command_can_throw_a_special_exception_without_message_which_exits_with_a_stacktrace()
|
||||
public async Task I_can_throw_an_exception_without_a_message_in_a_command_to_report_an_error_with_a_stacktrace()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -158,12 +161,13 @@ public class ErrorReportingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(69);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().BeEmpty();
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Should().ContainAllInOrder(
|
||||
"CliFx.Exceptions.CommandException",
|
||||
"at", "CliFx."
|
||||
@@ -171,7 +175,7 @@ public class ErrorReportingSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Command_can_throw_a_special_exception_which_prints_help_text_before_exiting()
|
||||
public async Task I_can_throw_an_exception_in_a_command_to_report_an_error_and_print_the_help_text()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -198,12 +202,13 @@ public class ErrorReportingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(69);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().Contain("This will be in help text");
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Trim().Should().Be("Something went wrong");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -17,7 +17,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_is_bound_from_an_argument_matching_its_name()
|
||||
public async Task I_can_bind_an_option_to_a_property_and_get_the_value_from_the_corresponding_argument_by_name()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -27,7 +27,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public bool Foo { get; set; }
|
||||
public bool Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -49,15 +49,15 @@ public class OptionBindingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().Be("True");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_is_bound_from_an_argument_matching_its_short_name()
|
||||
public async Task I_can_bind_an_option_to_a_property_and_get_the_value_from_the_corresponding_argument_by_short_name()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -67,7 +67,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public bool Foo { get; set; }
|
||||
public bool Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -89,15 +89,15 @@ public class OptionBindingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().Be("True");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_is_bound_from_a_set_of_arguments_matching_its_name()
|
||||
public async Task I_can_bind_an_option_to_a_property_and_get_the_value_from_the_corresponding_argument_set_by_name()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -107,10 +107,10 @@ public class OptionBindingSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
[CommandOption("bar")]
|
||||
public string Bar { get; set; }
|
||||
public string? Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -130,14 +130,18 @@ public class OptionBindingSpecs : SpecsBase
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
new[] {"--foo", "one", "--bar", "two"},
|
||||
new[]
|
||||
{
|
||||
"--foo", "one",
|
||||
"--bar", "two"
|
||||
},
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"Foo = one",
|
||||
"Bar = two"
|
||||
@@ -145,7 +149,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_is_bound_from_a_set_of_arguments_matching_its_short_name()
|
||||
public async Task I_can_bind_an_option_to_a_property_and_get_the_value_from_the_corresponding_argument_set_by_short_name()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -155,10 +159,10 @@ public class OptionBindingSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
[CommandOption('b')]
|
||||
public string Bar { get; set; }
|
||||
public string? Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -178,14 +182,18 @@ public class OptionBindingSpecs : SpecsBase
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
new[] {"-f", "one", "-b", "two"},
|
||||
new[]
|
||||
{
|
||||
"-f", "one",
|
||||
"-b", "two"
|
||||
},
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"Foo = one",
|
||||
"Bar = two"
|
||||
@@ -193,7 +201,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_is_bound_from_a_stack_of_arguments_matching_its_short_name()
|
||||
public async Task I_can_bind_an_option_to_a_property_and_get_the_value_from_the_corresponding_argument_stack_by_short_name()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -203,10 +211,10 @@ public class OptionBindingSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
[CommandOption('b')]
|
||||
public string Bar { get; set; }
|
||||
public string? Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -230,10 +238,10 @@ public class OptionBindingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"Foo = ",
|
||||
"Bar = value"
|
||||
@@ -241,7 +249,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_of_non_scalar_type_is_bound_from_a_set_of_arguments_matching_its_name()
|
||||
public async Task I_can_bind_an_option_to_a_non_scalar_property_and_get_the_values_from_the_corresponding_arguments_by_name()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -251,7 +259,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption("Foo")]
|
||||
public IReadOnlyList<string> Foo { get; set; }
|
||||
public IReadOnlyList<string>? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -275,10 +283,10 @@ public class OptionBindingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"one",
|
||||
"two",
|
||||
@@ -287,7 +295,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_of_non_scalar_type_is_bound_from_a_set_of_arguments_matching_its_short_name()
|
||||
public async Task I_can_bind_an_option_to_a_non_scalar_property_and_get_the_values_from_the_corresponding_arguments_by_short_name()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -297,7 +305,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public IReadOnlyList<string> Foo { get; set; }
|
||||
public IReadOnlyList<string>? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -321,10 +329,10 @@ public class OptionBindingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"one",
|
||||
"two",
|
||||
@@ -333,7 +341,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_of_non_scalar_type_is_bound_from_multiple_sets_of_arguments_matching_its_name()
|
||||
public async Task I_can_bind_an_option_to_a_non_scalar_property_and_get_the_values_from_the_corresponding_argument_sets_by_name()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -343,7 +351,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public IReadOnlyList<string> Foo { get; set; }
|
||||
public IReadOnlyList<string>? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -363,14 +371,19 @@ public class OptionBindingSpecs : SpecsBase
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
new[] {"--foo", "one", "--foo", "two", "--foo", "three"},
|
||||
new[]
|
||||
{
|
||||
"--foo", "one",
|
||||
"--foo", "two",
|
||||
"--foo", "three"
|
||||
},
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"one",
|
||||
"two",
|
||||
@@ -379,7 +392,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_of_non_scalar_type_is_bound_from_multiple_sets_of_arguments_matching_its_short_name()
|
||||
public async Task I_can_bind_an_option_to_a_non_scalar_property_and_get_the_values_from_the_corresponding_argument_sets_by_short_name()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -389,7 +402,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption('f')]
|
||||
public IReadOnlyList<string> Foo { get; set; }
|
||||
public IReadOnlyList<string>? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -409,14 +422,19 @@ public class OptionBindingSpecs : SpecsBase
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
new[] {"-f", "one", "-f", "two", "-f", "three"},
|
||||
new[]
|
||||
{
|
||||
"-f", "one",
|
||||
"-f", "two",
|
||||
"-f", "three"
|
||||
},
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"one",
|
||||
"two",
|
||||
@@ -425,7 +443,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_of_non_scalar_type_is_bound_from_multiple_sets_of_arguments_matching_its_name_or_short_name()
|
||||
public async Task I_can_bind_an_option_to_a_non_scalar_property_and_get_the_values_from_the_corresponding_argument_sets_by_name_or_short_name()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -435,7 +453,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption("foo", 'f')]
|
||||
public IReadOnlyList<string> Foo { get; set; }
|
||||
public IReadOnlyList<string>? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -455,14 +473,19 @@ public class OptionBindingSpecs : SpecsBase
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
new[] {"--foo", "one", "-f", "two", "--foo", "three"},
|
||||
new[]
|
||||
{
|
||||
"--foo", "one",
|
||||
"-f", "two",
|
||||
"--foo", "three"
|
||||
},
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"one",
|
||||
"two",
|
||||
@@ -471,7 +494,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_is_not_bound_if_there_are_no_arguments_matching_its_name_or_short_name()
|
||||
public async Task I_can_bind_an_option_to_a_property_and_get_no_value_if_the_user_does_not_provide_the_corresponding_argument()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -481,10 +504,10 @@ public class OptionBindingSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
[CommandOption("bar")]
|
||||
public string Bar { get; set; } = "hello";
|
||||
public string? Bar { get; init; } = "hello";
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -508,10 +531,10 @@ public class OptionBindingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"Foo = one",
|
||||
"Bar = hello"
|
||||
@@ -519,7 +542,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_binding_supports_multiple_inheritance_through_default_interface_members()
|
||||
public async Task I_can_bind_an_option_to_a_property_through_multiple_inheritance()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -538,7 +561,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
public int Foo
|
||||
{
|
||||
get => SharedContext.Foo;
|
||||
set => SharedContext.Foo = value;
|
||||
init => SharedContext.Foo = value;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -548,20 +571,20 @@ public class OptionBindingSpecs : SpecsBase
|
||||
public bool Bar
|
||||
{
|
||||
get => SharedContext.Bar;
|
||||
set => SharedContext.Bar = value;
|
||||
init => SharedContext.Bar = value;
|
||||
}
|
||||
}
|
||||
|
||||
public interface IHasBaz : ICommand
|
||||
{
|
||||
public string Baz { get; set; }
|
||||
public string? Baz { get; init; }
|
||||
}
|
||||
|
||||
[Command]
|
||||
public class Command : IHasFoo, IHasBar, IHasBaz
|
||||
{
|
||||
[CommandOption("baz")]
|
||||
public string Baz { get; set; }
|
||||
public string? Baz { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -582,13 +605,18 @@ public class OptionBindingSpecs : SpecsBase
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
new[] { "--foo", "42", "--bar", "--baz", "xyz" }
|
||||
new[]
|
||||
{
|
||||
"--foo", "42",
|
||||
"--bar",
|
||||
"--baz", "xyz"
|
||||
}
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"Foo = 42",
|
||||
"Bar = True",
|
||||
@@ -597,7 +625,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_binding_does_not_consider_a_negative_number_as_an_option_name_or_short_name()
|
||||
public async Task I_can_bind_an_option_to_a_property_and_get_the_correct_value_if_the_user_provides_an_argument_containing_a_negative_number()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -607,12 +635,11 @@ public class OptionBindingSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
console.Output.WriteLine(Foo);
|
||||
|
||||
return default;
|
||||
}
|
||||
}
|
||||
@@ -630,15 +657,15 @@ public class OptionBindingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().Be("-13");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_binding_fails_if_a_required_option_has_not_been_provided()
|
||||
public async Task I_can_bind_a_required_option_to_a_property_and_get_an_error_if_the_user_does_not_provide_the_corresponding_argument()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -647,8 +674,8 @@ public class OptionBindingSpecs : SpecsBase
|
||||
[Command]
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption("foo", IsRequired = true)]
|
||||
public string Foo { get; set; }
|
||||
[CommandOption("foo")]
|
||||
public required string Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -666,87 +693,15 @@ public class OptionBindingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Should().Contain("Missing required option(s)");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_binding_fails_if_a_required_option_has_been_provided_with_an_empty_value()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
// language=cs
|
||||
"""
|
||||
[Command]
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption("foo", IsRequired = true)]
|
||||
public string Foo { get; set; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
"""
|
||||
);
|
||||
|
||||
var application = new CliApplicationBuilder()
|
||||
.AddCommand(commandType)
|
||||
.UseConsole(FakeConsole)
|
||||
.Build();
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
new[] {"--foo"},
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
stdErr.Should().Contain("Missing required option(s)");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_binding_fails_if_a_required_option_of_non_scalar_type_has_not_been_provided_with_at_least_one_value()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
// language=cs
|
||||
"""
|
||||
[Command]
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption("foo", IsRequired = true)]
|
||||
public IReadOnlyList<string> Foo { get; set; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
"""
|
||||
);
|
||||
|
||||
var application = new CliApplicationBuilder()
|
||||
.AddCommand(commandType)
|
||||
.UseConsole(FakeConsole)
|
||||
.Build();
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
new[] {"--foo"},
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
stdErr.Should().Contain("Missing required option(s)");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_binding_fails_if_one_of_the_provided_option_names_is_not_recognized()
|
||||
public async Task I_can_bind_a_required_option_to_a_property_and_get_an_error_if_the_user_provides_an_empty_argument()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -756,7 +711,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public string Foo { get; set; }
|
||||
public required string Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -770,19 +725,95 @@ public class OptionBindingSpecs : SpecsBase
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
new[] {"--foo", "one", "--bar", "two"},
|
||||
new[] {"--foo"},
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Should().Contain("Missing required option(s)");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task I_can_bind_an_option_to_a_non_scalar_property_and_get_an_error_if_the_user_does_not_provide_at_least_one_corresponding_argument()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
// language=cs
|
||||
"""
|
||||
[Command]
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public required IReadOnlyList<string> Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
"""
|
||||
);
|
||||
|
||||
var application = new CliApplicationBuilder()
|
||||
.AddCommand(commandType)
|
||||
.UseConsole(FakeConsole)
|
||||
.Build();
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
new[] {"--foo"},
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Should().Contain("Missing required option(s)");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task I_can_bind_options_and_get_an_error_if_the_user_provides_unrecognized_arguments()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
// language=cs
|
||||
"""
|
||||
[Command]
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
"""
|
||||
);
|
||||
|
||||
var application = new CliApplicationBuilder()
|
||||
.AddCommand(commandType)
|
||||
.UseConsole(FakeConsole)
|
||||
.Build();
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
new[]
|
||||
{
|
||||
"--foo", "one",
|
||||
"--bar", "two"
|
||||
},
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Should().Contain("Unrecognized option(s)");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_binding_fails_if_an_option_of_scalar_type_has_been_provided_with_multiple_values()
|
||||
public async Task I_can_bind_an_option_to_a_scalar_property_and_get_an_error_if_the_user_provides_too_many_arguments()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -792,7 +823,7 @@ public class OptionBindingSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public string Foo { get; set; }
|
||||
public string? Foo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -810,46 +841,10 @@ public class OptionBindingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Should().Contain("expects a single argument, but provided with multiple");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Option_binding_fails_if_a_required_property_option_has_not_been_provided()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
// language=cs
|
||||
"""
|
||||
[Command]
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandOption("foo")]
|
||||
public required string Foo { get; set; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
"""
|
||||
);
|
||||
|
||||
var application = new CliApplicationBuilder()
|
||||
.AddCommand(commandType)
|
||||
.UseConsole(FakeConsole)
|
||||
.Build();
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
Array.Empty<string>(),
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
stdErr.Should().Contain("Missing required option(s)");
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ public class ParameterBindingSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_is_bound_from_an_argument_matching_its_order()
|
||||
public async Task I_can_bind_a_parameter_to_a_property_and_get_the_value_from_the_corresponding_argument()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -26,10 +26,10 @@ public class ParameterBindingSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
public required string Foo { get; init; }
|
||||
|
||||
[CommandParameter(1)]
|
||||
public string Bar { get; set; }
|
||||
public required string Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -53,10 +53,10 @@ public class ParameterBindingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"Foo = one",
|
||||
"Bar = two"
|
||||
@@ -64,7 +64,7 @@ public class ParameterBindingSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_of_non_scalar_type_is_bound_from_remaining_non_option_arguments()
|
||||
public async Task I_can_bind_a_parameter_to_a_non_scalar_property_and_get_values_from_the_remaining_non_option_arguments()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -74,16 +74,16 @@ public class ParameterBindingSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
public required string Foo { get; init; }
|
||||
|
||||
[CommandParameter(1)]
|
||||
public string Bar { get; set; }
|
||||
public required string Bar { get; init; }
|
||||
|
||||
[CommandParameter(2)]
|
||||
public IReadOnlyList<string> Baz { get; set; }
|
||||
public required IReadOnlyList<string> Baz { get; init; }
|
||||
|
||||
[CommandOption("boo")]
|
||||
public string Boo { get; set; }
|
||||
public string? Boo { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -110,10 +110,10 @@ public class ParameterBindingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"Foo = one",
|
||||
"Bar = two",
|
||||
@@ -124,7 +124,7 @@ public class ParameterBindingSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_is_not_bound_if_there_are_no_arguments_matching_its_order()
|
||||
public async Task I_can_bind_a_parameter_to_a_property_and_get_an_error_if_the_user_does_not_provide_the_corresponding_argument()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -134,10 +134,88 @@ public class ParameterBindingSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
public required string Foo { get; init; }
|
||||
|
||||
[CommandParameter(1)]
|
||||
public required string Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
"""
|
||||
);
|
||||
|
||||
var application = new CliApplicationBuilder()
|
||||
.AddCommand(commandType)
|
||||
.UseConsole(FakeConsole)
|
||||
.Build();
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
new[] {"one"},
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Should().Contain("Missing required parameter(s)");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task I_can_bind_a_parameter_to_a_non_scalar_property_and_get_an_error_if_the_user_does_not_provide_at_least_one_corresponding_argument()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
// language=cs
|
||||
"""
|
||||
[Command]
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public required string Foo { get; init; }
|
||||
|
||||
[CommandParameter(1)]
|
||||
public required IReadOnlyList<string> Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
"""
|
||||
);
|
||||
|
||||
var application = new CliApplicationBuilder()
|
||||
.AddCommand(commandType)
|
||||
.UseConsole(FakeConsole)
|
||||
.Build();
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
new[] {"one"},
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Should().Contain("Missing required parameter(s)");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task I_can_bind_a_non_required_parameter_to_a_property_and_get_no_value_if_the_user_does_not_provide_the_corresponding_argument()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
// language=cs
|
||||
"""
|
||||
[Command]
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public required string Foo { get; init; }
|
||||
|
||||
[CommandParameter(1, IsRequired = false)]
|
||||
public string Bar { get; set; } = "xyz";
|
||||
public string? Bar { get; init; } = "xyz";
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -161,10 +239,10 @@ public class ParameterBindingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Should().ConsistOfLines(
|
||||
"Foo = abc",
|
||||
"Bar = xyz"
|
||||
@@ -172,7 +250,7 @@ public class ParameterBindingSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_binding_fails_if_a_required_parameter_has_not_been_provided()
|
||||
public async Task I_can_bind_parameters_and_get_an_error_if_the_user_provides_too_many_arguments()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -182,88 +260,10 @@ public class ParameterBindingSpecs : SpecsBase
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
public required string Foo { get; init; }
|
||||
|
||||
[CommandParameter(1)]
|
||||
public string Bar { get; set; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
"""
|
||||
);
|
||||
|
||||
var application = new CliApplicationBuilder()
|
||||
.AddCommand(commandType)
|
||||
.UseConsole(FakeConsole)
|
||||
.Build();
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
new[] {"one"},
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
stdErr.Should().Contain("Missing required parameter(s)");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_binding_fails_if_a_parameter_of_non_scalar_type_has_not_been_provided_with_at_least_one_value()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
// language=cs
|
||||
"""
|
||||
[Command]
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
|
||||
[CommandParameter(1)]
|
||||
public IReadOnlyList<string> Bar { get; set; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
"""
|
||||
);
|
||||
|
||||
var application = new CliApplicationBuilder()
|
||||
.AddCommand(commandType)
|
||||
.UseConsole(FakeConsole)
|
||||
.Build();
|
||||
|
||||
// Act
|
||||
var exitCode = await application.RunAsync(
|
||||
new[] {"one"},
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
stdErr.Should().Contain("Missing required parameter(s)");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parameter_binding_fails_if_one_of_the_provided_parameters_is_unexpected()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
// language=cs
|
||||
"""
|
||||
[Command]
|
||||
public class Command : ICommand
|
||||
{
|
||||
[CommandParameter(0)]
|
||||
public string Foo { get; set; }
|
||||
|
||||
[CommandParameter(1)]
|
||||
public string Bar { get; set; }
|
||||
public required string Bar { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -281,10 +281,10 @@ public class ParameterBindingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Should().Contain("Unexpected parameter(s)");
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ public class RoutingSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Default_command_is_executed_if_provided_arguments_do_not_match_any_named_command()
|
||||
public async Task I_can_configure_a_command_to_be_executed_by_default_when_the_user_does_not_specify_a_command_name()
|
||||
{
|
||||
// Arrange
|
||||
var commandTypes = DynamicCommandBuilder.CompileMany(
|
||||
@@ -65,15 +65,15 @@ public class RoutingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().Be("default");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Specific_named_command_is_executed_if_provided_arguments_match_its_name()
|
||||
public async Task I_can_configure_a_command_to_be_executed_when_the_user_specifies_its_name()
|
||||
{
|
||||
// Arrange
|
||||
var commandTypes = DynamicCommandBuilder.CompileMany(
|
||||
@@ -122,15 +122,15 @@ public class RoutingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().Be("cmd");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Specific_named_child_command_is_executed_if_provided_arguments_match_its_name()
|
||||
public async Task I_can_configure_a_nested_command_to_be_executed_when_the_user_specifies_its_name()
|
||||
{
|
||||
// Arrange
|
||||
var commandTypes = DynamicCommandBuilder.CompileMany(
|
||||
@@ -179,10 +179,10 @@ public class RoutingSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().Be("cmd child");
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ public class TypeActivationSpecs : SpecsBase
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Default_type_activator_can_initialize_a_type_if_it_has_a_parameterless_constructor()
|
||||
public async Task I_can_configure_the_application_to_use_the_default_type_activator_to_initialize_types_through_parameterless_constructors()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -48,15 +48,15 @@ public class TypeActivationSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().Be("foo");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Default_type_activator_fails_if_the_type_does_not_have_a_parameterless_constructor()
|
||||
public async Task I_can_configure_the_application_to_use_the_default_type_activator_and_get_an_error_if_the_requested_type_does_not_have_a_parameterless_constructor()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -84,15 +84,15 @@ public class TypeActivationSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Should().Contain("Failed to create an instance of type");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Custom_type_activator_can_initialize_a_type_using_a_given_function()
|
||||
public async Task I_can_configure_the_application_to_use_a_custom_type_activator_to_initialize_types_using_a_delegate()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -126,15 +126,15 @@ public class TypeActivationSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().Be("Hello world");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Custom_type_activator_can_initialize_a_type_using_a_service_provider()
|
||||
public async Task I_can_configure_the_application_to_use_a_custom_type_activator_to_initialize_types_using_a_service_provider()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -156,14 +156,23 @@ public class TypeActivationSpecs : SpecsBase
|
||||
"""
|
||||
);
|
||||
|
||||
var serviceProvider = new ServiceCollection()
|
||||
.AddSingleton(commandType, Activator.CreateInstance(commandType, "Hello world")!)
|
||||
.BuildServiceProvider();
|
||||
|
||||
var application = new CliApplicationBuilder()
|
||||
.AddCommand(commandType)
|
||||
.UseConsole(FakeConsole)
|
||||
.UseTypeActivator(serviceProvider)
|
||||
.UseTypeActivator(commandTypes =>
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
|
||||
foreach (var serviceType in commandTypes)
|
||||
{
|
||||
services.AddSingleton(
|
||||
serviceType,
|
||||
Activator.CreateInstance(serviceType, "Hello world")!
|
||||
);
|
||||
}
|
||||
|
||||
return services.BuildServiceProvider();
|
||||
})
|
||||
.Build();
|
||||
|
||||
// Act
|
||||
@@ -172,15 +181,15 @@ public class TypeActivationSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().Be(0);
|
||||
|
||||
var stdOut = FakeConsole.ReadOutputString();
|
||||
stdOut.Trim().Should().Be("Hello world");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Custom_type_activator_fails_if_the_underlying_function_returns_null()
|
||||
public async Task I_can_configure_the_application_to_use_a_custom_type_activator_and_get_an_error_if_the_requested_type_cannot_be_initialized()
|
||||
{
|
||||
// Arrange
|
||||
var commandType = DynamicCommandBuilder.Compile(
|
||||
@@ -201,7 +210,7 @@ public class TypeActivationSpecs : SpecsBase
|
||||
var application = new CliApplicationBuilder()
|
||||
.AddCommand(commandType)
|
||||
.UseConsole(FakeConsole)
|
||||
.UseTypeActivator(_ => null!)
|
||||
.UseTypeActivator((Type _) => null!)
|
||||
.Build();
|
||||
|
||||
// Act
|
||||
@@ -210,10 +219,10 @@ public class TypeActivationSpecs : SpecsBase
|
||||
new Dictionary<string, string>()
|
||||
);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
|
||||
// Assert
|
||||
exitCode.Should().NotBe(0);
|
||||
|
||||
var stdErr = FakeConsole.ReadErrorString();
|
||||
stdErr.Should().Contain("Failed to create an instance of type");
|
||||
}
|
||||
}
|
||||
@@ -11,14 +11,9 @@ using Microsoft.CodeAnalysis.Text;
|
||||
namespace CliFx.Tests.Utils;
|
||||
|
||||
// This class uses Roslyn to compile commands dynamically.
|
||||
//
|
||||
// It allows us to collocate commands with tests more
|
||||
// easily, which helps a lot when reasoning about them.
|
||||
// Unfortunately, this comes at a cost of static typing,
|
||||
// but this is still a worthwhile trade off.
|
||||
//
|
||||
// Maybe one day C# will allow declaring classes inside
|
||||
// methods and doing this will no longer be necessary.
|
||||
// It allows us to collocate commands with tests more easily, which helps a lot when reasoning about them.
|
||||
// Unfortunately, this comes at a cost of static typing, but this is still a worthwhile trade off.
|
||||
// Maybe one day C# will allow declaring classes inside methods and doing this will no longer be necessary.
|
||||
// Language proposal: https://github.com/dotnet/csharplang/discussions/130
|
||||
internal static class DynamicCommandBuilder
|
||||
{
|
||||
@@ -124,7 +119,6 @@ internal static class DynamicCommandBuilder
|
||||
public static Type Compile(string sourceCode)
|
||||
{
|
||||
var commandTypes = CompileMany(sourceCode);
|
||||
|
||||
if (commandTypes.Count > 1)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
|
||||
@@ -41,7 +41,7 @@ internal static class AssertionExtensions
|
||||
lastIndex = index;
|
||||
}
|
||||
|
||||
return new(assertions);
|
||||
return new AndConstraint<StringAssertions>(assertions);
|
||||
}
|
||||
|
||||
public static AndConstraint<StringAssertions> ContainAllInOrder(
|
||||
|
||||
@@ -5,7 +5,7 @@ using CliFx.Infrastructure;
|
||||
namespace CliFx.Tests.Utils;
|
||||
|
||||
[Command]
|
||||
public class NoOpCommand : ICommand
|
||||
internal class NoOpCommand : ICommand
|
||||
{
|
||||
public ValueTask ExecuteAsync(IConsole console) => default;
|
||||
}
|
||||
@@ -9,17 +9,17 @@ namespace CliFx;
|
||||
public class ApplicationConfiguration
|
||||
{
|
||||
/// <summary>
|
||||
/// Command types defined in this application.
|
||||
/// Command types defined in the application.
|
||||
/// </summary>
|
||||
public IReadOnlyList<Type> CommandTypes { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether debug mode is allowed in this application.
|
||||
/// Whether debug mode is allowed in the application.
|
||||
/// </summary>
|
||||
public bool IsDebugModeAllowed { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether preview mode is allowed in this application.
|
||||
/// Whether preview mode is allowed in the application.
|
||||
/// </summary>
|
||||
public bool IsPreviewModeAllowed { get; }
|
||||
|
||||
|
||||
@@ -9,13 +9,12 @@ namespace CliFx.Attributes;
|
||||
public sealed class CommandAttribute : Attribute
|
||||
{
|
||||
/// <summary>
|
||||
/// Command's name.
|
||||
/// Command name.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Command can have no name, in which case it's treated as the default command.
|
||||
///
|
||||
/// Command can have no name, in which case it's treated as the application's default command.
|
||||
/// Only one default command is allowed in an application.
|
||||
/// All commands registered in an application must have unique names (comparison IS NOT case-sensitive).
|
||||
/// Only one command without a name is allowed in an application.
|
||||
/// </remarks>
|
||||
public string? Name { get; }
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ public sealed class CommandOptionAttribute : Attribute
|
||||
|
||||
/// <summary>
|
||||
/// Environment variable whose value will be used as a fallback if the option
|
||||
/// has not been explicitly set through command line arguments.
|
||||
/// has not been explicitly set through command-line arguments.
|
||||
/// </summary>
|
||||
public string? EnvironmentVariable { get; set; }
|
||||
|
||||
@@ -51,7 +51,7 @@ public sealed class CommandOptionAttribute : Attribute
|
||||
public string? Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Custom converter used for mapping the raw command line argument into
|
||||
/// Custom converter used for mapping the raw command-line argument into
|
||||
/// a value expected by the underlying property.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
@@ -81,7 +81,7 @@ public sealed class CommandOptionAttribute : Attribute
|
||||
/// Initializes an instance of <see cref="CommandOptionAttribute" />.
|
||||
/// </summary>
|
||||
public CommandOptionAttribute(string name, char shortName)
|
||||
: this(name, (char?) shortName)
|
||||
: this(name, (char?)shortName)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ public sealed class CommandOptionAttribute : Attribute
|
||||
/// Initializes an instance of <see cref="CommandOptionAttribute" />.
|
||||
/// </summary>
|
||||
public CommandOptionAttribute(char shortName)
|
||||
: this(null, (char?) shortName)
|
||||
: this(null, (char?)shortName)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,7 @@ public sealed class CommandParameterAttribute : Attribute
|
||||
{
|
||||
/// <summary>
|
||||
/// Parameter order.
|
||||
/// Higher order means the parameter appears later, lower order means
|
||||
/// it appears earlier.
|
||||
/// Higher order means the parameter appears later, lower order means it appears earlier.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// All parameters in a command must have unique order.
|
||||
@@ -47,7 +46,7 @@ public sealed class CommandParameterAttribute : Attribute
|
||||
public string? Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Custom converter used for mapping the raw command line argument into
|
||||
/// Custom converter used for mapping the raw command-line argument into
|
||||
/// a value expected by the underlying property.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
|
||||
@@ -2,6 +2,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx.Exceptions;
|
||||
using CliFx.Formatting;
|
||||
@@ -14,7 +15,7 @@ using CliFx.Utils.Extensions;
|
||||
namespace CliFx;
|
||||
|
||||
/// <summary>
|
||||
/// Command line application facade.
|
||||
/// Command-line application facade.
|
||||
/// </summary>
|
||||
public class CliApplication
|
||||
{
|
||||
@@ -58,12 +59,8 @@ public class CliApplication
|
||||
|
||||
private bool ShouldShowHelpText(CommandSchema commandSchema, CommandInput commandInput) =>
|
||||
commandSchema.IsHelpOptionAvailable && commandInput.IsHelpOptionSpecified ||
|
||||
// Show help text also in case the fallback default command is
|
||||
// executed without any arguments.
|
||||
commandSchema == FallbackDefaultCommand.Schema &&
|
||||
string.IsNullOrWhiteSpace(commandInput.CommandName) &&
|
||||
!commandInput.Parameters.Any() &&
|
||||
!commandInput.Options.Any();
|
||||
// Show help text also if the fallback default command is executed without any arguments
|
||||
commandSchema == FallbackDefaultCommand.Schema && !commandInput.HasArguments;
|
||||
|
||||
private bool ShouldShowVersionText(CommandSchema commandSchema, CommandInput commandInput) =>
|
||||
commandSchema.IsVersionOptionAvailable && commandInput.IsVersionOptionSpecified;
|
||||
@@ -75,28 +72,30 @@ public class CliApplication
|
||||
var processId = ProcessEx.GetCurrentProcessId();
|
||||
|
||||
_console.Output.WriteLine(
|
||||
$"Attach debugger to PID {processId} to continue."
|
||||
$"Attach the debugger to process with ID {processId} to continue."
|
||||
);
|
||||
}
|
||||
|
||||
// Try to also launch debugger ourselves (only works if VS is installed)
|
||||
// Try to also launch the debugger ourselves (only works with Visual Studio)
|
||||
Debugger.Launch();
|
||||
|
||||
while (!Debugger.IsAttached)
|
||||
{
|
||||
await Task.Delay(100);
|
||||
}
|
||||
}
|
||||
|
||||
private async ValueTask<int> RunAsync(ApplicationSchema applicationSchema, CommandInput commandInput)
|
||||
{
|
||||
// Handle debug directive
|
||||
// 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.
|
||||
_console.ResetColor();
|
||||
|
||||
// Handle the debug directive
|
||||
if (IsDebugModeEnabled(commandInput))
|
||||
{
|
||||
await PromptDebuggerAsync();
|
||||
}
|
||||
|
||||
// Handle preview directive
|
||||
// Handle the preview directive
|
||||
if (IsPreviewModeEnabled(commandInput))
|
||||
{
|
||||
_console.Output.WriteCommandInput(commandInput);
|
||||
@@ -105,16 +104,23 @@ public class CliApplication
|
||||
|
||||
// Try to get the command schema that matches the input
|
||||
var commandSchema =
|
||||
applicationSchema.TryFindCommand(commandInput.CommandName) ??
|
||||
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;
|
||||
|
||||
// Activate command instance
|
||||
// Initialize an instance of the command type
|
||||
var commandInstance = commandSchema == FallbackDefaultCommand.Schema
|
||||
? new FallbackDefaultCommand() // bypass activator
|
||||
: (ICommand)_typeActivator.CreateInstance(commandSchema.Type);
|
||||
? new FallbackDefaultCommand() // bypass the activator
|
||||
: _typeActivator.CreateInstance<ICommand>(commandSchema.Type);
|
||||
|
||||
// Assemble help context
|
||||
// Assemble the help context
|
||||
var helpContext = new HelpContext(
|
||||
Metadata,
|
||||
applicationSchema,
|
||||
@@ -122,14 +128,14 @@ public class CliApplication
|
||||
commandSchema.GetValues(commandInstance)
|
||||
);
|
||||
|
||||
// Handle help option
|
||||
// Handle the help option
|
||||
if (ShouldShowHelpText(commandSchema, commandInput))
|
||||
{
|
||||
_console.Output.WriteHelpText(helpContext);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Handle version option
|
||||
// Handle the version option
|
||||
if (ShouldShowVersionText(commandSchema, commandInput))
|
||||
{
|
||||
_console.Output.WriteLine(Metadata.Version);
|
||||
@@ -137,12 +143,12 @@ public class CliApplication
|
||||
}
|
||||
|
||||
// Starting from this point, we may produce exceptions that are meant for the
|
||||
// end user of the application (i.e. invalid input, command exception, etc).
|
||||
// end-user of the application (i.e. invalid input, command exception, etc).
|
||||
// Catch these exceptions here, print them to the console, and don't let them
|
||||
// propagate further.
|
||||
try
|
||||
{
|
||||
// Bind and execute command
|
||||
// Bind and execute the command
|
||||
_commandBinder.Bind(commandInput, commandSchema, commandInstance);
|
||||
await commandInstance.ExecuteAsync(_console);
|
||||
|
||||
@@ -163,12 +169,12 @@ public class CliApplication
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the application with the specified command line arguments and environment variables.
|
||||
/// Returns an exit code which indicates whether the application completed successfully.
|
||||
/// Runs the application with the specified command-line arguments and environment variables.
|
||||
/// Returns the exit code which indicates whether the application completed successfully.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// When running WITHOUT debugger (i.e. in production), this method swallows all exceptions and
|
||||
/// reports them to the console.
|
||||
/// When running WITHOUT the debugger attached (i.e. in production), this method swallows
|
||||
/// all exceptions and reports them to the console.
|
||||
/// </remarks>
|
||||
public async ValueTask<int> RunAsync(
|
||||
IReadOnlyList<string> commandLineArguments,
|
||||
@@ -176,10 +182,6 @@ public class CliApplication
|
||||
{
|
||||
try
|
||||
{
|
||||
// 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.
|
||||
_console.ResetColor();
|
||||
|
||||
var applicationSchema = ApplicationSchema.Resolve(Configuration.CommandTypes);
|
||||
|
||||
var commandInput = CommandInput.Parse(
|
||||
@@ -192,10 +194,8 @@ public class CliApplication
|
||||
}
|
||||
// To prevent the app from showing the annoying troubleshooting dialog on Windows,
|
||||
// we handle all exceptions ourselves and print them to the console.
|
||||
//
|
||||
// We only want to do that if the app is running in production, which we infer
|
||||
// based on whether a debugger is attached to the process.
|
||||
//
|
||||
// based on whether the debugger is attached to the process.
|
||||
// When not running in production, we want the IDE to show exceptions to the
|
||||
// developer, so we don't swallow them in that case.
|
||||
catch (Exception ex) when (!Debugger.IsAttached)
|
||||
@@ -206,31 +206,32 @@ public class CliApplication
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the application with the specified command line arguments.
|
||||
/// Environment variables are resolved automatically.
|
||||
/// Returns an exit code which indicates whether the application completed successfully.
|
||||
/// Runs the application with the specified command-line arguments.
|
||||
/// Returns the exit code which indicates whether the application completed successfully.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// When running WITHOUT debugger (i.e. in production), this method swallows all exceptions and
|
||||
/// reports them to the console.
|
||||
/// When running WITHOUT the debugger attached (i.e. in production), this method swallows
|
||||
/// all exceptions and reports them to the console.
|
||||
/// </remarks>
|
||||
public async ValueTask<int> RunAsync(IReadOnlyList<string> commandLineArguments) => await RunAsync(
|
||||
commandLineArguments,
|
||||
// Use case-sensitive comparison because environment variables are
|
||||
// case-sensitive on Linux and macOS (but not on Windows).
|
||||
Environment
|
||||
.GetEnvironmentVariables()
|
||||
.ToDictionary<string, string>(StringComparer.Ordinal)
|
||||
.ToDictionary<string, string>(
|
||||
RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
|
||||
? StringComparer.OrdinalIgnoreCase
|
||||
: StringComparer.Ordinal
|
||||
)
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Runs the application.
|
||||
/// Command line arguments and environment variables are resolved automatically.
|
||||
/// Returns an exit code which indicates whether the application completed successfully.
|
||||
/// Command-line arguments and environment variables are resolved automatically.
|
||||
/// Returns the exit code which indicates whether the application completed successfully.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// When running WITHOUT debugger (i.e. in production), this method swallows all exceptions and
|
||||
/// reports them to the console.
|
||||
/// When running WITHOUT the debugger attached (i.e. in production), this method swallows
|
||||
/// all exceptions and reports them to the console.
|
||||
/// </remarks>
|
||||
public async ValueTask<int> RunAsync() => await RunAsync(
|
||||
Environment.GetCommandLineArgs()
|
||||
|
||||
@@ -33,7 +33,6 @@ public partial class CliApplicationBuilder
|
||||
public CliApplicationBuilder AddCommand(Type commandType)
|
||||
{
|
||||
_commandTypes.Add(commandType);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -112,7 +111,7 @@ public partial class CliApplicationBuilder
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets application title, which is shown in the help text.
|
||||
/// Sets the application title, which is shown in the help text.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// By default, application title is inferred from the assembly name.
|
||||
@@ -124,11 +123,10 @@ public partial class CliApplicationBuilder
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets application executable name, which is shown in the help text.
|
||||
/// Sets the application executable name, which is shown in the help text.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// By default, application executable name is inferred from the assembly file name.
|
||||
/// The file name is also prefixed with `dotnet` if it's a DLL file.
|
||||
/// </remarks>
|
||||
public CliApplicationBuilder SetExecutableName(string executableName)
|
||||
{
|
||||
@@ -137,8 +135,7 @@ public partial class CliApplicationBuilder
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets application version, which is shown in the help text or
|
||||
/// when the user specifies the version option.
|
||||
/// Sets the application version, which is shown in the help text or when the user specifies the version option.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// By default, application version is inferred from the assembly version.
|
||||
@@ -150,7 +147,7 @@ public partial class CliApplicationBuilder
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets application description, which is shown in the help text.
|
||||
/// Sets the application description, which is shown in the help text.
|
||||
/// </summary>
|
||||
public CliApplicationBuilder SetDescription(string? description)
|
||||
{
|
||||
@@ -177,10 +174,10 @@ public partial class CliApplicationBuilder
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the application to use the specified function for activating types.
|
||||
/// Configures the application to use the specified delegate for activating types.
|
||||
/// </summary>
|
||||
public CliApplicationBuilder UseTypeActivator(Func<Type, object> typeActivator) =>
|
||||
UseTypeActivator(new DelegateTypeActivator(typeActivator));
|
||||
public CliApplicationBuilder UseTypeActivator(Func<Type, object> createInstance) =>
|
||||
UseTypeActivator(new DelegateTypeActivator(createInstance));
|
||||
|
||||
/// <summary>
|
||||
/// Configures the application to use the specified service provider for activating types.
|
||||
@@ -188,6 +185,14 @@ public partial class CliApplicationBuilder
|
||||
public CliApplicationBuilder UseTypeActivator(IServiceProvider serviceProvider) =>
|
||||
UseTypeActivator(serviceProvider.GetService);
|
||||
|
||||
/// <summary>
|
||||
/// Configures the application to use the specified service provider for activating types.
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public CliApplicationBuilder UseTypeActivator(Func<IReadOnlyList<Type>, IServiceProvider> getServiceProvider) =>
|
||||
UseTypeActivator(getServiceProvider(_commandTypes.ToArray()));
|
||||
|
||||
/// <summary>
|
||||
/// Creates a configured instance of <see cref="CliApplication" />.
|
||||
/// </summary>
|
||||
@@ -221,45 +226,58 @@ public partial class CliApplicationBuilder
|
||||
{
|
||||
var entryAssemblyName = EnvironmentEx.EntryAssembly?.GetName().Name;
|
||||
if (string.IsNullOrWhiteSpace(entryAssemblyName))
|
||||
return "App";
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Failed to infer the default application title. " +
|
||||
$"Please specify it explicitly using {nameof(SetTitle)}()."
|
||||
);
|
||||
}
|
||||
|
||||
return entryAssemblyName;
|
||||
}
|
||||
|
||||
private static string GetDefaultExecutableName()
|
||||
{
|
||||
var entryAssemblyLocation = EnvironmentEx.EntryAssembly?.Location;
|
||||
if (string.IsNullOrWhiteSpace(entryAssemblyLocation))
|
||||
return "app";
|
||||
var entryAssemblyFilePath = EnvironmentEx.EntryAssembly?.Location;
|
||||
var processFilePath = EnvironmentEx.ProcessPath;
|
||||
|
||||
// If the application was launched via matching EXE apphost, use that as the executable name
|
||||
var isLaunchedViaAppHost = string.Equals(
|
||||
EnvironmentEx.ProcessPath,
|
||||
Path.ChangeExtension(entryAssemblyLocation, ".exe"),
|
||||
StringComparison.OrdinalIgnoreCase
|
||||
);
|
||||
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)}()."
|
||||
);
|
||||
}
|
||||
|
||||
if (isLaunchedViaAppHost)
|
||||
return Path.GetFileNameWithoutExtension(entryAssemblyLocation);
|
||||
// If the process path matches the entry assembly path, it's a legacy .NET Framework app
|
||||
// or a self-contained .NET Core app.
|
||||
if (PathEx.AreEqual(entryAssemblyFilePath, processFilePath))
|
||||
{
|
||||
return Path.GetFileNameWithoutExtension(entryAssemblyFilePath);
|
||||
}
|
||||
|
||||
// Otherwise, use the entry assembly as the executable name.
|
||||
// Prefix it with `dotnet` if it's a DLL file.
|
||||
var isDll = string.Equals(
|
||||
Path.GetExtension(entryAssemblyLocation),
|
||||
".dll",
|
||||
StringComparison.OrdinalIgnoreCase
|
||||
);
|
||||
// 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))
|
||||
{
|
||||
return Path.GetFileNameWithoutExtension(entryAssemblyFilePath);
|
||||
}
|
||||
|
||||
return isDll
|
||||
? "dotnet " + Path.GetFileName(entryAssemblyLocation)
|
||||
: Path.GetFileNameWithoutExtension(entryAssemblyLocation);
|
||||
// Otherwise, it's a framework-dependent .NET Core app launched through the .NET CLI
|
||||
return "dotnet " + Path.GetFileName(entryAssemblyFilePath);
|
||||
}
|
||||
|
||||
private static string GetDefaultVersionText()
|
||||
{
|
||||
var entryAssemblyVersion = EnvironmentEx.EntryAssembly?.GetName().Version;
|
||||
if (entryAssemblyVersion is null)
|
||||
return "v1.0";
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Failed to infer the default application version. " +
|
||||
$"Please specify it explicitly using {nameof(SetVersion)}()."
|
||||
);
|
||||
}
|
||||
|
||||
return "v" + entryAssemblyVersion.ToSemanticString();
|
||||
}
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>netstandard2.1;netstandard2.0</TargetFrameworks>
|
||||
<TargetFrameworks>netstandard2.0;netstandard2.1</TargetFrameworks>
|
||||
<IsPackable>true</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<Authors>$(Company)</Authors>
|
||||
<Description>Declarative framework for building command line applications</Description>
|
||||
<Description>Class-first framework for building command-line interfaces</Description>
|
||||
<PackageTags>command line executable interface framework parser arguments cli app application net core</PackageTags>
|
||||
<PackageProjectUrl>https://github.com/Tyrrrz/CliFx</PackageProjectUrl>
|
||||
<PackageReleaseNotes>https://github.com/Tyrrrz/CliFx/blob/master/Changelog.md</PackageReleaseNotes>
|
||||
<PackageReadmeFile>Readme.md</PackageReadmeFile>
|
||||
<PackageIcon>favicon.png</PackageIcon>
|
||||
<PackageLicenseExpression>MIT</PackageLicenseExpression>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
@@ -21,17 +20,13 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="../Readme.md" Pack="true" PackagePath="" Visible="false" />
|
||||
<None Include="../favicon.png" Pack="true" PackagePath="" Visible="false" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="all" />
|
||||
<PackageReference Include="Nullable" Version="1.3.1" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
|
||||
<PackageReference Include="System.Threading.Tasks.Extensions" Version="4.5.4" />
|
||||
<PackageReference Include="PolyShim" Version="1.2.0" PrivateAssets="all" />
|
||||
<PackageReference Include="System.Threading.Tasks.Extensions" Version="4.5.4" Condition="'$(TargetFramework)' == 'netstandard2.0'" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Embed the analyzer inside the package -->
|
||||
|
||||
@@ -27,11 +27,11 @@ internal class CommandBinder
|
||||
// Custom converter
|
||||
if (memberSchema.ConverterType is not null)
|
||||
{
|
||||
var converter = (IBindingConverter)_typeActivator.CreateInstance(memberSchema.ConverterType);
|
||||
var converter = _typeActivator.CreateInstance<IBindingConverter>(memberSchema.ConverterType);
|
||||
return converter.Convert(rawValue);
|
||||
}
|
||||
|
||||
// Assignable from string (e.g. string itself, object, etc)
|
||||
// Assignable from a string (e.g. string itself, object, etc)
|
||||
if (targetType.IsAssignableFrom(typeof(string)))
|
||||
{
|
||||
return rawValue;
|
||||
@@ -77,7 +77,7 @@ internal class CommandBinder
|
||||
: null;
|
||||
}
|
||||
|
||||
// String-constructible (FileInfo, etc)
|
||||
// String-constructable (FileInfo, etc)
|
||||
var stringConstructor = targetType.GetConstructor(new[] { typeof(string) });
|
||||
if (stringConstructor is not null)
|
||||
{
|
||||
@@ -101,7 +101,7 @@ internal class CommandBinder
|
||||
throw CliFxException.InternalError(
|
||||
$"""
|
||||
{memberSchema.GetKind()} {memberSchema.GetFormattedIdentifier()} has an unsupported underlying property type.
|
||||
There is no known way to convert a string value into an instance of type `{targetType.FullName}`
|
||||
There is no known way to convert a string value into an instance of type `{targetType.FullName}`.
|
||||
To fix this, either change the property to use a supported type or configure a custom converter.
|
||||
"""
|
||||
);
|
||||
@@ -125,7 +125,7 @@ internal class CommandBinder
|
||||
return array;
|
||||
}
|
||||
|
||||
// Array-constructible (List<T>, HashSet<T>, etc)
|
||||
// Array-constructable (List<T>, HashSet<T>, etc)
|
||||
var arrayConstructor = targetEnumerableType.GetConstructor(new[] { arrayType });
|
||||
if (arrayConstructor is not null)
|
||||
{
|
||||
@@ -136,34 +136,41 @@ internal class CommandBinder
|
||||
$"""
|
||||
{memberSchema.GetKind()} {memberSchema.GetFormattedIdentifier()} has an unsupported underlying property type.
|
||||
There is no known way to convert an array of `{targetElementType.FullName}` into an instance of type `{targetEnumerableType.FullName}`.
|
||||
To fix this, change the property to use a type which can be assigned from an array or a type that has a constructor which accepts an array.
|
||||
To fix this, change the property to use a type which can be assigned from an array or a type which has a constructor that accepts an array.
|
||||
"""
|
||||
);
|
||||
}
|
||||
|
||||
private object? ConvertMember(IMemberSchema memberSchema, IReadOnlyList<string> rawValues)
|
||||
{
|
||||
var targetType = memberSchema.Property.Type;
|
||||
|
||||
try
|
||||
{
|
||||
// Non-scalar
|
||||
var enumerableUnderlyingType = targetType.TryGetEnumerableUnderlyingType();
|
||||
if (targetType != typeof(string) && enumerableUnderlyingType is not null)
|
||||
var enumerableUnderlyingType = memberSchema.Property.Type.TryGetEnumerableUnderlyingType();
|
||||
if (enumerableUnderlyingType is not null && memberSchema.Property.Type != typeof(string))
|
||||
{
|
||||
return ConvertMultiple(memberSchema, rawValues, targetType, enumerableUnderlyingType);
|
||||
return ConvertMultiple(
|
||||
memberSchema,
|
||||
rawValues,
|
||||
memberSchema.Property.Type,
|
||||
enumerableUnderlyingType
|
||||
);
|
||||
}
|
||||
|
||||
// Scalar
|
||||
if (rawValues.Count <= 1)
|
||||
{
|
||||
return ConvertSingle(memberSchema, rawValues.SingleOrDefault(), targetType);
|
||||
return ConvertSingle(
|
||||
memberSchema,
|
||||
rawValues.SingleOrDefault(),
|
||||
memberSchema.Property.Type
|
||||
);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not CliFxException) // don't wrap CliFxException
|
||||
{
|
||||
// We use reflection-based invocation which can throw TargetInvocationException.
|
||||
// Unwrap these exceptions to provide a more user-friendly error message.
|
||||
// Unwrap those exceptions to provide a more user-friendly error message.
|
||||
var errorMessage = ex is TargetInvocationException invokeEx
|
||||
? invokeEx.InnerException?.Message ?? invokeEx.Message
|
||||
: ex.Message;
|
||||
@@ -193,7 +200,7 @@ internal class CommandBinder
|
||||
|
||||
foreach (var validatorType in memberSchema.ValidatorTypes)
|
||||
{
|
||||
var validator = (IBindingValidator)_typeActivator.CreateInstance(validatorType);
|
||||
var validator = _typeActivator.CreateInstance<IBindingValidator>(validatorType);
|
||||
var error = validator.Validate(convertedValue);
|
||||
|
||||
if (error is not null)
|
||||
@@ -234,7 +241,7 @@ internal class CommandBinder
|
||||
if (position >= commandInput.Parameters.Count)
|
||||
break;
|
||||
|
||||
// Scalar - take one input at the current position
|
||||
// Scalar: take one input at the current position
|
||||
if (parameterSchema.Property.IsScalar())
|
||||
{
|
||||
var parameterInput = commandInput.Parameters[position];
|
||||
@@ -246,7 +253,7 @@ internal class CommandBinder
|
||||
|
||||
remainingParameterInputs.Remove(parameterInput);
|
||||
}
|
||||
// Non-scalar - take all remaining inputs starting from the current position
|
||||
// Non-scalar: take all remaining inputs starting from the current position
|
||||
else
|
||||
{
|
||||
var parameterInputs = commandInput.Parameters.Skip(position).ToArray();
|
||||
@@ -307,7 +314,7 @@ internal class CommandBinder
|
||||
|
||||
BindMember(optionSchema, commandInstance, rawValues);
|
||||
|
||||
// Required options require at least one value to be set
|
||||
// Required options need at least one value to be set
|
||||
if (rawValues.Any())
|
||||
remainingRequiredOptionSchemas.Remove(optionSchema);
|
||||
}
|
||||
@@ -320,11 +327,11 @@ internal class CommandBinder
|
||||
|
||||
BindMember(optionSchema, commandInstance, rawValues);
|
||||
|
||||
// Required options require at least one value to be set
|
||||
// Required options need at least one value to be set
|
||||
if (rawValues.Any())
|
||||
remainingRequiredOptionSchemas.Remove(optionSchema);
|
||||
}
|
||||
// No input - skip
|
||||
// No input, skip
|
||||
else
|
||||
{
|
||||
continue;
|
||||
|
||||
@@ -9,9 +9,11 @@ public partial class CliFxException : Exception
|
||||
{
|
||||
internal const int DefaultExitCode = 1;
|
||||
|
||||
// Regular `exception.Message` never returns null, even if
|
||||
// it hasn't been set.
|
||||
internal string? ActualMessage { get; }
|
||||
// When an exception is created without a message, the base Exception class
|
||||
// provides a default message that is not very useful.
|
||||
// This property is used to identify whether this instance was created with
|
||||
// a custom message, so that we can avoid printing the default message.
|
||||
internal bool HasCustomMessage { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Returned exit code.
|
||||
@@ -33,7 +35,7 @@ public partial class CliFxException : Exception
|
||||
Exception? innerException = null)
|
||||
: base(message, innerException)
|
||||
{
|
||||
ActualMessage = message;
|
||||
HasCustomMessage = !string.IsNullOrWhiteSpace(message);
|
||||
ExitCode = exitCode;
|
||||
ShowHelp = showHelp;
|
||||
}
|
||||
@@ -41,13 +43,13 @@ public partial class CliFxException : Exception
|
||||
|
||||
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 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);
|
||||
|
||||
// User errors are typically caused by invalid input and they're meant for
|
||||
// the end-user, so we want to show help.
|
||||
// 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);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace CliFx.Extensibility;
|
||||
|
||||
// Used internally to simplify usage from reflection
|
||||
// Used internally to simplify the usage from reflection
|
||||
internal interface IBindingConverter
|
||||
{
|
||||
object? Convert(string? rawValue);
|
||||
@@ -12,7 +12,7 @@ internal interface IBindingConverter
|
||||
public abstract class BindingConverter<T> : IBindingConverter
|
||||
{
|
||||
/// <summary>
|
||||
/// Parses value from a raw command line argument.
|
||||
/// Parses value from a raw command-line argument.
|
||||
/// </summary>
|
||||
public abstract T Convert(string? rawValue);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace CliFx.Extensibility;
|
||||
|
||||
// Used internally to simplify usage from reflection
|
||||
// Used internally to simplify the usage from reflection
|
||||
internal interface IBindingValidator
|
||||
{
|
||||
BindingValidationError? Validate(object? value);
|
||||
|
||||
@@ -13,7 +13,7 @@ internal class CommandInputConsoleFormatter : ConsoleFormatter
|
||||
|
||||
private void WriteCommandLineArguments(CommandInput commandInput)
|
||||
{
|
||||
Write("Command line:");
|
||||
Write("Command-line:");
|
||||
WriteLine();
|
||||
|
||||
WriteHorizontalMargin();
|
||||
|
||||
@@ -98,26 +98,22 @@ internal class ExceptionConsoleFormatter : ConsoleFormatter
|
||||
if (!string.IsNullOrWhiteSpace(exception.StackTrace))
|
||||
{
|
||||
// Parse and pretty-print the stacktrace
|
||||
foreach (var stackFrame in StackFrame.ParseMany(exception.StackTrace))
|
||||
{
|
||||
foreach (var stackFrame in StackFrame.ParseTrace(exception.StackTrace))
|
||||
WriteStackFrame(stackFrame, indentLevel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void WriteException(Exception exception)
|
||||
{
|
||||
// Domain exceptions should be printed with minimal information
|
||||
// because they are meant for the user of the application,
|
||||
// not the user of the library.
|
||||
if (exception is CliFxException cliFxException &&
|
||||
!string.IsNullOrWhiteSpace(cliFxException.ActualMessage))
|
||||
// Domain exceptions should be printed with minimal information because they are
|
||||
// meant for the user of the application, not the user of the library.
|
||||
if (exception is CliFxException { HasCustomMessage: true } cliFxException)
|
||||
{
|
||||
Write(ConsoleColor.Red, cliFxException.ActualMessage);
|
||||
Write(ConsoleColor.Red, cliFxException.Message);
|
||||
WriteLine();
|
||||
}
|
||||
// All other exceptions most likely indicate an actual bug
|
||||
// and should include stacktrace and other detailed information.
|
||||
// All other exceptions most likely indicate an actual bug and should include
|
||||
// the stacktrace and other detailed information.
|
||||
else
|
||||
{
|
||||
Write(ConsoleColor.White, ConsoleColor.DarkRed, "ERROR");
|
||||
|
||||
@@ -206,7 +206,7 @@ internal class HelpConsoleFormatter : ConsoleFormatter
|
||||
Write('.');
|
||||
Write(' ');
|
||||
}
|
||||
|
||||
|
||||
// Default value
|
||||
if (!parameterSchema.IsRequired)
|
||||
{
|
||||
@@ -367,7 +367,9 @@ internal class HelpConsoleFormatter : ConsoleFormatter
|
||||
{
|
||||
var childCommandSchemas = _context
|
||||
.ApplicationSchema
|
||||
.GetChildCommands(_context.CommandSchema.Name);
|
||||
.GetChildCommands(_context.CommandSchema.Name)
|
||||
.OrderBy(a => a.Name, StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
|
||||
if (!childCommandSchemas.Any())
|
||||
return;
|
||||
@@ -402,14 +404,15 @@ internal class HelpConsoleFormatter : ConsoleFormatter
|
||||
// Child commands of child command
|
||||
var grandChildCommandSchemas = _context
|
||||
.ApplicationSchema
|
||||
.GetChildCommands(childCommandSchema.Name);
|
||||
.GetChildCommands(childCommandSchema.Name)
|
||||
.OrderBy(c => c.Name, StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
|
||||
if (grandChildCommandSchemas.Any())
|
||||
{
|
||||
Write(ConsoleColor.White, "Subcommands: ");
|
||||
|
||||
var isFirst = true;
|
||||
|
||||
foreach (var grandChildCommandSchema in grandChildCommandSchemas)
|
||||
{
|
||||
if (isFirst)
|
||||
|
||||
@@ -4,7 +4,7 @@ using CliFx.Infrastructure;
|
||||
namespace CliFx;
|
||||
|
||||
/// <summary>
|
||||
/// Entry point through which the user interacts with the command line application.
|
||||
/// Entry point through which the user interacts with the command-line application.
|
||||
/// </summary>
|
||||
public interface ICommand
|
||||
{
|
||||
@@ -13,7 +13,7 @@ public interface ICommand
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If the execution of the command is not asynchronous, simply end the method with
|
||||
/// <code>return default;</code>
|
||||
/// <c>return default;</c>
|
||||
/// </remarks>
|
||||
ValueTask ExecuteAsync(IConsole console);
|
||||
}
|
||||
@@ -4,22 +4,22 @@ using CliFx.Exceptions;
|
||||
namespace CliFx.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// Implementation of <see cref="ITypeActivator" /> that instantiates an object
|
||||
/// by using a predefined function.
|
||||
/// Implementation of <see cref="ITypeActivator" /> that instantiates an object by using a predefined delegate.
|
||||
/// </summary>
|
||||
public class DelegateTypeActivator : ITypeActivator
|
||||
{
|
||||
private readonly Func<Type, object> _func;
|
||||
private readonly Func<Type, object> _createInstance;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes an instance of <see cref="DelegateTypeActivator" />.
|
||||
/// </summary>
|
||||
public DelegateTypeActivator(Func<Type, object> func) => _func = func;
|
||||
public DelegateTypeActivator(Func<Type, object> createInstance) =>
|
||||
_createInstance = createInstance;
|
||||
|
||||
/// <inheritdoc />
|
||||
public object CreateInstance(Type type)
|
||||
{
|
||||
var instance = _func(type);
|
||||
var instance = _createInstance(type);
|
||||
|
||||
if (instance is null)
|
||||
{
|
||||
|
||||
@@ -8,10 +8,8 @@ namespace CliFx.Infrastructure;
|
||||
/// <summary>
|
||||
/// Implementation of <see cref="IConsole" /> that uses the provided fake
|
||||
/// standard input, output, and error streams.
|
||||
/// Use this implementation in tests to verify command interactions with the console.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Use this implementation in tests to verify how a command interacts with the console.
|
||||
/// </remarks>
|
||||
public class FakeConsole : IConsole, IDisposable
|
||||
{
|
||||
private readonly CancellationTokenSource _cancellationTokenSource = new();
|
||||
|
||||
@@ -5,10 +5,8 @@ namespace CliFx.Infrastructure;
|
||||
/// <summary>
|
||||
/// Implementation of <see cref="IConsole" /> that uses fake
|
||||
/// standard input, output, and error streams backed by in-memory stores.
|
||||
/// Use this implementation in tests to verify command interactions with the console.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Use this implementation in tests to verify how a command interacts with the console.
|
||||
/// </remarks>
|
||||
public class FakeInMemoryConsole : FakeConsole
|
||||
{
|
||||
private readonly MemoryStream _input;
|
||||
@@ -36,17 +34,17 @@ public class FakeInMemoryConsole : FakeConsole
|
||||
/// </summary>
|
||||
public void WriteInput(byte[] data)
|
||||
{
|
||||
// We want the consumer to be able to read what we wrote
|
||||
// so we need to seek the stream back to its original
|
||||
// position after we finish writing.
|
||||
lock (_input)
|
||||
{
|
||||
var lastPosition = _input.Position;
|
||||
|
||||
// Write the data to the end of the stream
|
||||
_input.Seek(0, SeekOrigin.End);
|
||||
_input.Write(data);
|
||||
_input.Flush();
|
||||
|
||||
_input.Position = lastPosition;
|
||||
// Reset position to where it was before
|
||||
_input.Seek(lastPosition, SeekOrigin.Begin);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -86,19 +86,18 @@ public interface IConsole
|
||||
|
||||
/// <summary>
|
||||
/// Registers a handler for the interrupt signal (Ctrl+C) on the console and returns
|
||||
/// a token representing the cancellation request.
|
||||
/// the token that represents the associated cancellation request.
|
||||
/// Subsequent calls to this method have no side effects and return the same token.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Calling this method effectively makes the command cancellation-aware, which
|
||||
/// means that sending the interrupt signal won't immediately terminate the application,
|
||||
/// but will instead trigger a token that the command can use to exit more gracefully.
|
||||
/// Calling this method makes the command cancellation-aware, which means that sending
|
||||
/// the interrupt signal won't immediately terminate the application, but will instead
|
||||
/// trigger the associated token, allowing the command to exit early but on its own terms.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Note that the handler is only respected when the user sends the interrupt signal for the first time.
|
||||
/// If the user decides to issue the signal again, the application will terminate immediately
|
||||
/// regardless of whether the command is cancellation-aware.
|
||||
/// Note that if the user sends the interrupt signal a second time, the application will
|
||||
/// be forcefully terminated without triggering the token.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
CancellationToken RegisterCancellationHandler();
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
using System;
|
||||
using CliFx.Exceptions;
|
||||
using CliFx.Extensibility;
|
||||
using CliFx.Utils.Extensions;
|
||||
|
||||
namespace CliFx.Infrastructure;
|
||||
|
||||
@@ -11,4 +14,19 @@ public interface ITypeActivator
|
||||
/// Creates an instance of the specified type.
|
||||
/// </summary>
|
||||
object CreateInstance(Type type);
|
||||
}
|
||||
|
||||
internal static class TypeActivatorExtensions
|
||||
{
|
||||
public static T CreateInstance<T>(this ITypeActivator activator, Type type)
|
||||
{
|
||||
if (!typeof(T).IsAssignableFrom(type))
|
||||
{
|
||||
throw CliFxException.InternalError(
|
||||
$"Type '{type.FullName}' is not assignable to '{typeof(T).FullName}'."
|
||||
);
|
||||
}
|
||||
|
||||
return (T)activator.CreateInstance(type);
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,12 @@ internal partial class CommandInput
|
||||
|
||||
public IReadOnlyList<EnvironmentVariableInput> EnvironmentVariables { get; }
|
||||
|
||||
public bool HasArguments =>
|
||||
!string.IsNullOrWhiteSpace(CommandName) ||
|
||||
Directives.Any() ||
|
||||
Parameters.Any() ||
|
||||
Options.Any();
|
||||
|
||||
public bool IsDebugDirectiveSpecified => Directives.Any(d => d.IsDebugDirective);
|
||||
|
||||
public bool IsPreviewDirectiveSpecified => Directives.Any(d => d.IsPreviewDirective);
|
||||
@@ -74,8 +80,8 @@ internal partial class CommandInput
|
||||
|
||||
var lastIndex = index;
|
||||
|
||||
// Append arguments to a buffer until we find the longest sequence
|
||||
// that represents a valid command name.
|
||||
// Append arguments to a buffer until we find the longest sequence that represents
|
||||
// a valid command name.
|
||||
for (var i = index; i < commandLineArguments.Count; i++)
|
||||
{
|
||||
var argument = commandLineArguments[i];
|
||||
@@ -85,8 +91,8 @@ internal partial class CommandInput
|
||||
var potentialCommandName = potentialCommandNameComponents.JoinToString(" ");
|
||||
if (commandNames.Contains(potentialCommandName))
|
||||
{
|
||||
// Record the position but continue the loop in case
|
||||
// we find a longer (more specific) match.
|
||||
// Record the position but continue the loop in case we find
|
||||
// a longer (more specific) match.
|
||||
commandName = potentialCommandName;
|
||||
lastIndex = i;
|
||||
}
|
||||
@@ -105,7 +111,7 @@ internal partial class CommandInput
|
||||
{
|
||||
var result = new List<ParameterInput>();
|
||||
|
||||
// Consume all arguments until first option identifier
|
||||
// Consume all arguments until the first option identifier
|
||||
for (; index < commandLineArguments.Count; index++)
|
||||
{
|
||||
var argument = commandLineArguments[index];
|
||||
@@ -120,7 +126,7 @@ internal partial class CommandInput
|
||||
argument.Length > 1 &&
|
||||
char.IsLetter(argument[1]);
|
||||
|
||||
// Break on first option identifier
|
||||
// Break on the first option identifier
|
||||
if (isOptionIdentifier)
|
||||
break;
|
||||
|
||||
@@ -153,7 +159,7 @@ internal partial class CommandInput
|
||||
if (!string.IsNullOrWhiteSpace(lastOptionIdentifier))
|
||||
result.Add(new OptionInput(lastOptionIdentifier, lastOptionValues));
|
||||
|
||||
lastOptionIdentifier = argument.Substring(2);
|
||||
lastOptionIdentifier = argument[2..];
|
||||
lastOptionValues = new List<string>();
|
||||
}
|
||||
// Short name
|
||||
@@ -161,13 +167,13 @@ internal partial class CommandInput
|
||||
argument.Length > 1 &&
|
||||
char.IsLetter(argument[1]))
|
||||
{
|
||||
foreach (var alias in argument.Substring(1))
|
||||
foreach (var identifier in argument[1..])
|
||||
{
|
||||
// Flush previous
|
||||
if (!string.IsNullOrWhiteSpace(lastOptionIdentifier))
|
||||
result.Add(new OptionInput(lastOptionIdentifier, lastOptionValues));
|
||||
|
||||
lastOptionIdentifier = alias.AsString();
|
||||
lastOptionIdentifier = identifier.AsString();
|
||||
lastOptionValues = new List<string>();
|
||||
}
|
||||
}
|
||||
@@ -178,7 +184,7 @@ internal partial class CommandInput
|
||||
}
|
||||
}
|
||||
|
||||
// Flush last option
|
||||
// Flush the last option
|
||||
if (!string.IsNullOrWhiteSpace(lastOptionIdentifier))
|
||||
result.Add(new OptionInput(lastOptionIdentifier, lastOptionValues));
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ internal partial class ApplicationSchema
|
||||
public CommandSchema? TryFindDefaultCommand() =>
|
||||
Commands.FirstOrDefault(c => c.IsDefault);
|
||||
|
||||
public CommandSchema? TryFindCommand(string? commandName) =>
|
||||
public CommandSchema? TryFindCommand(string commandName) =>
|
||||
Commands.FirstOrDefault(c => c.MatchesName(commandName));
|
||||
|
||||
private IReadOnlyList<CommandSchema> GetDescendantCommands(
|
||||
|
||||
@@ -70,8 +70,7 @@ internal partial class CommandSchema
|
||||
public static bool IsCommandType(Type type) =>
|
||||
type.Implements(typeof(ICommand)) &&
|
||||
type.IsDefined(typeof(CommandAttribute)) &&
|
||||
!type.IsAbstract &&
|
||||
!type.IsInterface;
|
||||
type is { IsAbstract: false, IsInterface: false };
|
||||
|
||||
public static CommandSchema? TryResolve(Type type)
|
||||
{
|
||||
@@ -88,7 +87,7 @@ internal partial class CommandSchema
|
||||
: new[] {OptionSchema.HelpOption};
|
||||
|
||||
var properties = type
|
||||
// Get properties directly on command type
|
||||
// Get properties directly on the command type
|
||||
.GetProperties()
|
||||
// Get non-abstract properties on interfaces (to support default interfaces members)
|
||||
.Union(type
|
||||
@@ -125,7 +124,6 @@ internal partial class CommandSchema
|
||||
public static CommandSchema Resolve(Type type)
|
||||
{
|
||||
var schema = TryResolve(type);
|
||||
|
||||
if (schema is null)
|
||||
{
|
||||
throw CliFxException.InternalError(
|
||||
|
||||
22
CliFx/Utils/PathEx.cs
Normal file
22
CliFx/Utils/PathEx.cs
Normal file
@@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace CliFx.Utils;
|
||||
|
||||
internal static class PathEx
|
||||
{
|
||||
private static StringComparer EqualityComparer { get; } =
|
||||
RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
|
||||
? StringComparer.OrdinalIgnoreCase
|
||||
: StringComparer.Ordinal;
|
||||
|
||||
public static bool AreEqual(string path1, string path2)
|
||||
{
|
||||
static string Normalize(string path) => Path
|
||||
.GetFullPath(path)
|
||||
.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
|
||||
return EqualityComparer.Equals(Normalize(path1), Normalize(path2));
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
// ReSharper disable CheckNamespace
|
||||
|
||||
#if NETSTANDARD2_0
|
||||
using System.Collections.Generic;
|
||||
|
||||
internal static class CollectionPolyfills
|
||||
{
|
||||
public static void Deconstruct<TKey, TValue>(this KeyValuePair<TKey, TValue> pair, out TKey key, out TValue value)
|
||||
{
|
||||
key = pair.Key;
|
||||
value = pair.Value;
|
||||
}
|
||||
|
||||
public static TValue GetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dic, TKey key) =>
|
||||
dic.TryGetValue(key!, out var result) ? result! : default!;
|
||||
}
|
||||
|
||||
namespace System.Linq
|
||||
{
|
||||
internal static class LinqPolyfills
|
||||
{
|
||||
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer) =>
|
||||
new(source, comparer);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,11 +0,0 @@
|
||||
// ReSharper disable CheckNamespace
|
||||
|
||||
#if NETSTANDARD2_0
|
||||
using System.IO;
|
||||
|
||||
internal static class StreamPolyfills
|
||||
{
|
||||
public static void Write(this Stream stream, byte[] buffer) =>
|
||||
stream.Write(buffer, 0, buffer.Length);
|
||||
}
|
||||
#endif
|
||||
@@ -1,12 +0,0 @@
|
||||
// ReSharper disable CheckNamespace
|
||||
|
||||
#if NETSTANDARD2_0
|
||||
internal static class StringPolyfills
|
||||
{
|
||||
public static bool StartsWith(this string str, char c) =>
|
||||
str.Length > 0 && str[0] == c;
|
||||
|
||||
public static bool EndsWith(this string str, char c) =>
|
||||
str.Length > 0 && str[str.Length - 1] == c;
|
||||
}
|
||||
#endif
|
||||
@@ -52,33 +52,35 @@ internal partial class StackFrame
|
||||
private const string NotSpace = @"[^\x20\t]";
|
||||
|
||||
// Taken from https://github.com/atifaziz/StackTraceParser
|
||||
private static readonly Regex Pattern = new(@"
|
||||
^
|
||||
" + Space + @"*
|
||||
\w+ " + Space + @"+
|
||||
(?<frame>
|
||||
(?<type> " + NotSpace + @"+ ) \.
|
||||
(?<method> " + NotSpace + @"+? ) " + Space + @"*
|
||||
(?<params> \( ( " + Space + @"* \)
|
||||
| (?<pt> .+?) " + Space + @"+ (?<pn> .+?)
|
||||
(, " + Space + @"* (?<pt> .+?) " + Space + @"+ (?<pn> .+?) )* \) ) )
|
||||
( " + Space + @"+
|
||||
( # Microsoft .NET stack traces
|
||||
\w+ " + Space + @"+
|
||||
(?<file> ( [a-z] \: # Windows rooted path starting with a drive letter
|
||||
| / ) # *nix rooted path starting with a forward-slash
|
||||
.+? )
|
||||
\: \w+ " + Space + @"+
|
||||
(?<line> [0-9]+ ) \p{P}?
|
||||
| # Mono stack traces
|
||||
\[0x[0-9a-f]+\] " + Space + @"+ \w+ " + Space + @"+
|
||||
<(?<file> [^>]+ )>
|
||||
:(?<line> [0-9]+ )
|
||||
)
|
||||
)?
|
||||
)
|
||||
\s*
|
||||
$",
|
||||
private static readonly Regex Pattern = new(
|
||||
$$"""
|
||||
^
|
||||
{{Space}}*
|
||||
\w+ {{Space}}+
|
||||
(?<frame>
|
||||
(?<type> {{NotSpace}}+ ) \.
|
||||
(?<method> {{NotSpace}}+? ) {{Space}}*
|
||||
(?<params> \( ( {{Space}}* \)
|
||||
| (?<pt> .+?) {{Space}}+ (?<pn> .+?)
|
||||
(, {{Space}}* (?<pt> .+?) {{Space}}+ (?<pn> .+?) )* \) ) )
|
||||
( {{Space}}+
|
||||
( # Microsoft .NET stack traces
|
||||
\w+ {{Space}}+
|
||||
(?<file> ( [a-z] \: # Windows rooted path starting with a drive letter
|
||||
| / ) # Unix rooted path starting with a forward-slash
|
||||
.+? )
|
||||
\: \w+ {{Space}}+
|
||||
(?<line> [0-9]+ ) \p{P}?
|
||||
| # Mono stack traces
|
||||
\[0x[0-9a-f]+\] {{Space}}+ \w+ {{Space}}+
|
||||
<(?<file> [^>]+ )>
|
||||
:(?<line> [0-9]+ )
|
||||
)
|
||||
)?
|
||||
)
|
||||
\s*
|
||||
$
|
||||
""",
|
||||
RegexOptions.IgnoreCase |
|
||||
RegexOptions.Multiline |
|
||||
RegexOptions.ExplicitCapture |
|
||||
@@ -87,9 +89,9 @@ internal partial class StackFrame
|
||||
TimeSpan.FromSeconds(5)
|
||||
);
|
||||
|
||||
public static IEnumerable<StackFrame> ParseMany(string stackTrace)
|
||||
public static IEnumerable<StackFrame> ParseTrace(string stackTrace)
|
||||
{
|
||||
var matches = Pattern.Matches(stackTrace).Cast<Match>().ToArray();
|
||||
var matches = Pattern.Matches(stackTrace).ToArray();
|
||||
|
||||
if (matches.Length <= 0 || matches.Any(m => !m.Success))
|
||||
{
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<Project>
|
||||
|
||||
<PropertyGroup>
|
||||
<Version>2.3.1</Version>
|
||||
<Version>2.3.4</Version>
|
||||
<Company>Tyrrrz</Company>
|
||||
<Copyright>Copyright (C) Oleksii Holub</Copyright>
|
||||
<LangVersion>latest</LangVersion>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019-2022 Oleksii Holub
|
||||
Copyright (c) 2019-2023 Oleksii Holub
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
353
Readme.md
353
Readme.md
@@ -1,7 +1,7 @@
|
||||
# CliFx
|
||||
|
||||
[](https://vshymanskyy.github.io/StandWithUkraine)
|
||||
[](https://github.com/Tyrrrz/CliFx/actions)
|
||||
[](https://tyrrrz.me/ukraine)
|
||||
[](https://github.com/Tyrrrz/CliFx/actions)
|
||||
[](https://codecov.io/gh/Tyrrrz/CliFx)
|
||||
[](https://nuget.org/packages/CliFx)
|
||||
[](https://nuget.org/packages/CliFx)
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
> 🟡 **Project status**: maintenance mode<sup>[[?]](https://github.com/Tyrrrz/.github/blob/master/docs/project-status.md)</sup>
|
||||
|
||||
**CliFx** is a simple to use, yet powerful framework for building command line applications.
|
||||
**CliFx** is a simple to use, yet powerful framework for building command-line applications.
|
||||
Its primary goal is to completely take over the user input layer, allowing you to forget about infrastructural concerns and instead focus on writing your application.
|
||||
|
||||
## Terms of use<sup>[[?]](https://github.com/Tyrrrz/.github/blob/master/docs/why-so-political.md)</sup>
|
||||
@@ -23,7 +23,7 @@ By using this project or its source code, for any purpose and in any shape or fo
|
||||
- You **support Ukraine's territorial integrity, including its claims over temporarily occupied territories of Crimea and Donbas**
|
||||
- You **reject false narratives perpetuated by Russian state propaganda**
|
||||
|
||||
To learn more about the war and how you can help, [click here](https://tyrrrz.me). Glory to Ukraine! 🇺🇦
|
||||
To learn more about the war and how you can help, [click here](https://tyrrrz.me/ukraine). Glory to Ukraine! 🇺🇦
|
||||
|
||||
## Install
|
||||
|
||||
@@ -49,12 +49,14 @@ To learn more about the war and how you can help, [click here](https://tyrrrz.me
|
||||
|
||||
## Usage
|
||||
|
||||
### Application and commands
|
||||
### Quick overview
|
||||
|
||||
To turn your program into a command line interface, modify your `Main` method so that it delegates execution to `CliApplication`.
|
||||
You can use `CliApplicationBuilder` to fluently create and configure an instance of `CliApplication`:
|
||||
To turn your program into a command-line interface, modify the `Main()` method so that it delegates the execution to an instance of `CliApplication`.
|
||||
You can use `CliApplicationBuilder` to simplify the process of creating and configuring an application:
|
||||
|
||||
```csharp
|
||||
using CliFx;
|
||||
|
||||
public static class Program
|
||||
{
|
||||
public static async Task<int> Main() =>
|
||||
@@ -70,76 +72,19 @@ public static class Program
|
||||
> Exit code is used to communicate execution result to the parent process, so it's important that your program propagates it.
|
||||
|
||||
> **Note**:
|
||||
> When calling `CliApplication.RunAsync()`, **CliFx** resolves command line arguments and environment variables from `Environment.GetCommandLineArgs()` and `Environment.GetEnvironmentVariables()` respectively.
|
||||
> You can also provide them explicitly if you choose.
|
||||
> When calling `CliApplication.RunAsync()`, **CliFx** resolves command-line arguments and environment variables from `Environment.GetCommandLineArgs()` and `Environment.GetEnvironmentVariables()` respectively.
|
||||
> You can also provide them manually using one of the alternative overloads.
|
||||
|
||||
The code above uses `AddCommandsFromThisAssembly()` to detect command types defined within the current assembly.
|
||||
Commands are entry points, through which the user can interact with your application.
|
||||
The code above uses `AddCommandsFromThisAssembly()` to detect command types defined within the current project and register them on the application.
|
||||
Commands are independent entry points, through which the user can interact with your program.
|
||||
|
||||
To define a command, create a new class by implementing the `ICommand` interface and annotate it with the `[Command]` attribute:
|
||||
To define a command, create a class that implements the `ICommand` interface and annotate it with the `[Command]` attribute:
|
||||
|
||||
```csharp
|
||||
[Command]
|
||||
public class HelloWorldCommand : ICommand
|
||||
{
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
console.Output.WriteLine("Hello world!");
|
||||
using CliFx;
|
||||
using CliFx.Attributes;
|
||||
|
||||
// Return default task if the command is not asynchronous
|
||||
return default;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In order to implement `ICommand`, the class needs to define an `ExecuteAsync(...)` method.
|
||||
This is the method that gets called by the framework when the user decides to execute this command.
|
||||
|
||||
As the only parameter, this method takes an instance of `IConsole`, which is an abstraction around the system console.
|
||||
Use this abstraction in place of `System.Console` whenever you need to write output, read input, or otherwise interact with the console.
|
||||
|
||||
With the basic setup above, the user can now run the application and get a greeting in return:
|
||||
|
||||
```powershell
|
||||
> dotnet myapp.dll
|
||||
|
||||
Hello world!
|
||||
```
|
||||
|
||||
Out of the box, the application also comes with built-in `--help` and `--version` options.
|
||||
They can be used to show help text or application version respectively:
|
||||
|
||||
```powershell
|
||||
> dotnet myapp.dll --help
|
||||
|
||||
MyApp v1.0
|
||||
|
||||
USAGE
|
||||
dotnet myapp.dll [options]
|
||||
|
||||
OPTIONS
|
||||
-h|--help Shows help text.
|
||||
--version Shows version information.
|
||||
```
|
||||
|
||||
```powershell
|
||||
> dotnet myapp.dll --version
|
||||
|
||||
v1.0
|
||||
```
|
||||
|
||||
### Parameters and options
|
||||
|
||||
Commands can be configured to take input from command line arguments.
|
||||
To do that, you need to add properties to the command class and bind them using special attributes.
|
||||
|
||||
In **CliFx**, there are two types of argument bindings: **parameters** and **options**.
|
||||
Parameters are bound from arguments based on the order they appear in, while options are bound by their name.
|
||||
|
||||
As an example, here's a command that calculates logarithm of a value — it uses a parameter binding to specify the input value and an option binding for the logarithm base:
|
||||
|
||||
```csharp
|
||||
[Command]
|
||||
[Command(Description = "Calculates the logarithm of a value.")]
|
||||
public class LogCommand : ICommand
|
||||
{
|
||||
// Order: 0
|
||||
@@ -156,50 +101,61 @@ public class LogCommand : ICommand
|
||||
var result = Math.Log(Value, Base);
|
||||
console.Output.WriteLine(result);
|
||||
|
||||
// If the execution is not meant to be asynchronous,
|
||||
// return an empty task at the end of the method.
|
||||
return default;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> **Note**:
|
||||
> **CliFx** has built-in analyzers that detect common errors in command definitions.
|
||||
> Your code will not compile if the command contains duplicate options, overlapping parameters, or otherwise invalid configuration.
|
||||
In order to implement `ICommand`, the class needs to define an `ExecuteAsync(...)` method.
|
||||
This is the method that gets called by the framework when the user decides to execute the command.
|
||||
|
||||
In order to execute this command, at a minimum, the user needs to provide the input value:
|
||||
As the only parameter, this method takes an instance of `IConsole`, which is an abstraction around the system console.
|
||||
Use this abstraction in place of `System.Console` whenever you need to write output, read input, or otherwise interact with the console.
|
||||
|
||||
```powershell
|
||||
> dotnet myapp.dll 10000
|
||||
In most cases, you will also want to define input bindings, which are properties annotated by the `[CommandParameter]` and `[CommandOption]` attributes.
|
||||
These bindings provide a way to map command-line arguments into structured data that can be used by the command.
|
||||
|
||||
The command in the above example serves as a simple logarithm calculator and defines two inputs: a positional parameter for the input value and a named option for the logarithm base.
|
||||
In order to execute this command, at minimum, the user needs to provide the input value:
|
||||
|
||||
```sh
|
||||
$ dotnet myapp.dll 10000
|
||||
|
||||
4
|
||||
```
|
||||
|
||||
They can also pass the `base` option to override the default logarithm base of 10:
|
||||
They can also pass the `-b|--base` option to override the default logarithm base of `10`:
|
||||
|
||||
```powershell
|
||||
> dotnet myapp.dll 729 -b 3
|
||||
```sh
|
||||
$ dotnet myapp.dll 729 -b 3
|
||||
|
||||
6
|
||||
```
|
||||
|
||||
In case the user forgets to specify the `value` parameter, the application will exit with an error:
|
||||
In case the user forgets to specify the required `value` parameter, the application will instead exit with an error:
|
||||
|
||||
```powershell
|
||||
> dotnet myapp.dll -b 10
|
||||
```sh
|
||||
$ dotnet myapp.dll -b 10
|
||||
|
||||
Missing required parameter(s):
|
||||
<value>
|
||||
```
|
||||
|
||||
Available parameters and options are also listed in the command's help text, which can be accessed by passing the `--help` option:
|
||||
Out of the box, **CliFx** also provides a built-in `--help` option, which generates a help screen that lists all parameters and options available for the command:
|
||||
|
||||
```powershell
|
||||
> dotnet myapp.dll --help
|
||||
```sh
|
||||
$ dotnet myapp.dll --help
|
||||
|
||||
MyApp v1.0
|
||||
|
||||
USAGE
|
||||
dotnet myapp.dll <value> [options]
|
||||
|
||||
DESCRIPTION
|
||||
Calculates the logarithm of a value.
|
||||
|
||||
PARAMETERS
|
||||
* value Value whose logarithm is to be found.
|
||||
|
||||
@@ -209,21 +165,9 @@ OPTIONS
|
||||
--version Shows version information.
|
||||
```
|
||||
|
||||
Overall, parameters and options are both used to consume input from the command line, but they differ in a few important ways:
|
||||
|
||||
| | Parameter | Option |
|
||||
| ------------------ | ------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------- |
|
||||
| **Identification** | Positional (by relative order). | Nominal (by name or short name). |
|
||||
| **Requiredness** | Required by default. Only the last parameter can be configured to be optional. | Optional by default. Any option can be configured to be required without limitations. |
|
||||
| **Arity** | Only the last parameter can be bound to a non-scalar property (i.e. an array). | Any option can be bound to a non-scalar property without limitations. |
|
||||
| **Fallback** | — | Can be configured to use an environment variable as fallback if the value isn't explicitly provided. |
|
||||
|
||||
As a general guideline, use parameters for required inputs that the command can't function without.
|
||||
Use options for all other non-required inputs, or when specifying the name explicitly makes the usage clearer.
|
||||
|
||||
### Argument syntax
|
||||
|
||||
This library employs the POSIX argument syntax, which is used in most modern command line tools.
|
||||
This library employs a variation of the POSIX argument syntax, which is used in most modern command-line tools.
|
||||
Here are some examples of how it works:
|
||||
|
||||
- `myapp --foo bar` sets option `"foo"` to value `"bar"`
|
||||
@@ -243,12 +187,69 @@ The parser's context-free nature has several implications on how it consumes arg
|
||||
For example, `myapp -i file1.txt file2.txt` will always be parsed as an option with multiple values, regardless of the arity of the underlying property it's bound to.
|
||||
Similarly, unseparated arguments in the form of `myapp -ofile` will be treated as five distinct options `'o'`, `'f'`, `'i'`, `'l'`, `'e'`, instead of `'o'` being set to value `"file"`.
|
||||
|
||||
These rules also make the order of arguments important — command line string is expected to follow this pattern:
|
||||
These rules also make the order of arguments important — command-line string is expected to follow this pattern:
|
||||
|
||||
```powershell
|
||||
> myapp [...directives] [command] [...parameters] [...options]
|
||||
```sh
|
||||
$ myapp [...directives] [command] [...parameters] [...options]
|
||||
```
|
||||
|
||||
### Parameters and options
|
||||
|
||||
**CliFx** supports two types of argument bindings: **parameters** and **options**.
|
||||
Parameters are bound from arguments based on the order they appear in, while options are bound by their name.
|
||||
|
||||
Besides that, they also differ in the following ways:
|
||||
|
||||
- Parameters are required by default, while options are not.
|
||||
|
||||
- You can make an option required by setting `IsRequired = true` on the corresponding attribute or by adding the `required` keyword to the property declaration (introduced in C# 11):
|
||||
|
||||
```csharp
|
||||
// Any option can be required or optional without restrictions
|
||||
[CommandOption("foo")]
|
||||
public required string RequiredOption { get; init; }
|
||||
```
|
||||
|
||||
- To make a parameter optional, you can set `IsRequired = false`, but only the last parameter (by order) can be configured in such way:
|
||||
|
||||
```csharp
|
||||
// Only the last parameter can be optional
|
||||
[CommandParameter(0, IsRequired = false)]
|
||||
public string? OptionalParameter { get; init; }
|
||||
```
|
||||
|
||||
- Parameters are primarily used for scalar (non-enumerable) properties, while options can be used for both scalar and non-scalar properties.
|
||||
|
||||
- You can bind an option to a property of a non-scalar type, such as `IReadOnlyList<T>`:
|
||||
|
||||
```csharp
|
||||
// Any option can be non-scalar
|
||||
[CommandOption("foo")]
|
||||
public required IReadOnlyList<string> NonScalarOption { get; init; }
|
||||
```
|
||||
|
||||
- You can bind a parameter to a non-scalar property, but only if it's the last parameter in the command:
|
||||
|
||||
```csharp
|
||||
// Only the last parameter can be non-scalar
|
||||
[CommandParameter(0)]
|
||||
public required IReadOnlyList<string> NonScalarParameter { get; init; }
|
||||
```
|
||||
|
||||
- Options can rely on an environment variable for fallback, while parameters cannot:
|
||||
|
||||
```csharp
|
||||
// If the value is not provided directly, it will be read
|
||||
// from the environment variable instead.
|
||||
// This works for both scalar and non-scalar properties.
|
||||
[CommandOption("foo", EnvironmentVariable = "ENV_FOO")]
|
||||
public required string OptionWithFallback { get; init; }
|
||||
```
|
||||
|
||||
> **Note**:
|
||||
> **CliFx** has a set of built-in analyzers that detect common errors in command definitions.
|
||||
> Your code will not compile if a command contains duplicate options, overlapping parameters, or otherwise invalid configuration.
|
||||
|
||||
### Value conversion
|
||||
|
||||
Parameters and options can be bound to properties with the following underlying types:
|
||||
@@ -278,7 +279,7 @@ public class FileSizeCalculatorCommand : ICommand
|
||||
// FileInfo is string-initializable and IReadOnlyList<T> can be assigned from an array,
|
||||
// so the value of this property can be mapped from a sequence of arguments.
|
||||
[CommandParameter(0)]
|
||||
public IReadOnlyList<FileInfo> Files { get; init; }
|
||||
public required IReadOnlyList<FileInfo> Files { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -291,34 +292,8 @@ public class FileSizeCalculatorCommand : ICommand
|
||||
}
|
||||
```
|
||||
|
||||
```powershell
|
||||
> dotnet myapp.dll file1.bin file2.exe
|
||||
|
||||
Total file size: 186368 bytes
|
||||
```
|
||||
|
||||
Same command, but using an option for the list of files instead:
|
||||
|
||||
```csharp
|
||||
[Command]
|
||||
public class FileSizeCalculatorCommand : ICommand
|
||||
{
|
||||
[CommandOption("files")]
|
||||
public IReadOnlyList<FileInfo> Files { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
var totalSize = Files.Sum(f => f.Length);
|
||||
|
||||
console.Output.WriteLine($"Total file size: {totalSize} bytes");
|
||||
|
||||
return default;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```powershell
|
||||
> dotnet myapp.dll --files file1.bin file2.exe
|
||||
```sh
|
||||
$ dotnet myapp.dll file1.bin file2.exe
|
||||
|
||||
Total file size: 186368 bytes
|
||||
```
|
||||
@@ -349,13 +324,13 @@ public class SurfaceCalculatorCommand : ICommand
|
||||
{
|
||||
// Custom converter is used to map raw argument values
|
||||
[CommandParameter(0, Converter = typeof(VectorConverter))]
|
||||
public Vector2 PointA { get; init; }
|
||||
public required Vector2 PointA { get; init; }
|
||||
|
||||
[CommandParameter(1, Converter = typeof(VectorConverter))]
|
||||
public Vector2 PointB { get; init; }
|
||||
public required Vector2 PointB { get; init; }
|
||||
|
||||
[CommandParameter(2, Converter = typeof(VectorConverter))]
|
||||
public Vector2 PointC { get; init; }
|
||||
public required Vector2 PointC { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -373,41 +348,15 @@ public class SurfaceCalculatorCommand : ICommand
|
||||
}
|
||||
```
|
||||
|
||||
### Environment variables
|
||||
```sh
|
||||
$ dotnet myapp.dll 0x0 0x10 10x0
|
||||
|
||||
An option can be configured to use a specific environment variable as fallback.
|
||||
If the user does not provide value for such option through command line arguments, the current value of the environment variable will be used instead.
|
||||
|
||||
```csharp
|
||||
[Command]
|
||||
public class AuthCommand : ICommand
|
||||
{
|
||||
[CommandOption("token", EnvironmentVariable = "AUTH_TOKEN")]
|
||||
public required string AuthToken { get; init; }
|
||||
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
console.Output.WriteLine(AuthToken);
|
||||
|
||||
return default;
|
||||
}
|
||||
}
|
||||
Triangle surface area: 50
|
||||
```
|
||||
|
||||
```powershell
|
||||
> $env:AUTH_TOKEN="test"
|
||||
|
||||
> dotnet myapp.dll
|
||||
|
||||
test
|
||||
```
|
||||
|
||||
Environment variables can be configured for options of non-scalar types (arrays, lists, etc.) as well.
|
||||
In such case, the values of the environment variable will be split by `Path.PathSeparator` (`;` on Windows, `:` on Unix systems).
|
||||
|
||||
### Multiple commands
|
||||
|
||||
In order to facilitate a variety of different workflows, command line applications may provide the user with more than just a single command.
|
||||
In order to facilitate a variety of different workflows, command-line applications may provide the user with more than just a single command.
|
||||
Complex applications may also nest commands underneath each other, employing a multi-level hierarchical structure.
|
||||
|
||||
With **CliFx**, this is achieved by simply giving each command a unique name through the `[Command]` attribute.
|
||||
@@ -448,8 +397,8 @@ For example, running `dotnet myapp.dll cmd1 arg1 -p 42` will execute `FirstComma
|
||||
|
||||
Requesting help will show direct subcommands of the current command:
|
||||
|
||||
```powershell
|
||||
> dotnet myapp.dll --help
|
||||
```sh
|
||||
$ dotnet myapp.dll --help
|
||||
|
||||
MyApp v1.0
|
||||
|
||||
@@ -470,8 +419,8 @@ You can run `dotnet myapp.dll [command] --help` to show help on a specific comma
|
||||
|
||||
The user can also refine their help request by querying it on a specific command:
|
||||
|
||||
```powershell
|
||||
> dotnet myapp.dll cmd1 --help
|
||||
```sh
|
||||
$ dotnet myapp.dll cmd1 --help
|
||||
|
||||
USAGE
|
||||
dotnet myapp.dll cmd1 [options]
|
||||
@@ -487,7 +436,7 @@ You can run `dotnet myapp.dll cmd1 [command] --help` to show help on a specific
|
||||
```
|
||||
|
||||
> **Note**:
|
||||
> Defining a default (unnamed) command is not required.
|
||||
> Defining the default (unnamed) command is not required.
|
||||
> If it's absent, running the application without specifying a command will just show the root-level help text.
|
||||
|
||||
### Reporting errors
|
||||
@@ -521,13 +470,12 @@ public class DivideCommand : ICommand
|
||||
}
|
||||
```
|
||||
|
||||
```powershell
|
||||
> dotnet myapp.dll --dividend 10 --divisor 0
|
||||
```sh
|
||||
$ dotnet myapp.dll --dividend 10 --divisor 0
|
||||
|
||||
Division by zero is not supported.
|
||||
|
||||
|
||||
> $LastExitCode
|
||||
$ echo $?
|
||||
|
||||
133
|
||||
```
|
||||
@@ -541,8 +489,8 @@ Division by zero is not supported.
|
||||
Console applications support the concept of interrupt signals, which can be issued by the user to abort the currently ongoing operation.
|
||||
If your command performs critical work, you can intercept these signals to handle cancellation requests in a graceful way.
|
||||
|
||||
To make a command cancellation-aware, call `console.RegisterCancellationHandler()` to register the signal handler and obtain the corresponding `CancellationToken`.
|
||||
Once this method is called, the program will no longer terminate on an interrupt signal but will instead trigger the token, so it's important to be able to process it correctly.
|
||||
In order to make the command cancellation-aware, call `console.RegisterCancellationHandler()` to register the signal handler and obtain the corresponding `CancellationToken`.
|
||||
Once this method is called, the program will no longer terminate on an interrupt signal but will instead trigger the token, which can be used by the command to delay the termination just enough to exit in a controlled manner.
|
||||
|
||||
```csharp
|
||||
[Command]
|
||||
@@ -568,7 +516,7 @@ public class CancellableCommand : ICommand
|
||||
|
||||
> **Warning**:
|
||||
> Cancellation handler is only respected when the user sends the interrupt signal for the first time.
|
||||
> If the user decides to issue the signal again, the application will terminate immediately regardless of whether the command is cancellation-aware.
|
||||
> If the user decides to issue the signal again, the application will be forcefully terminated without triggering the cancellation token.
|
||||
|
||||
### Type activation
|
||||
|
||||
@@ -583,24 +531,24 @@ The following example shows how to configure your application to use [`Microsoft
|
||||
```csharp
|
||||
public static class Program
|
||||
{
|
||||
public static async Task<int> Main()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
|
||||
// Register services
|
||||
services.AddSingleton<MyService>();
|
||||
|
||||
// Register commands
|
||||
services.AddTransient<MyCommand>();
|
||||
|
||||
var serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
return await new CliApplicationBuilder()
|
||||
public static async Task<int> Main() =>
|
||||
await new CliApplicationBuilder()
|
||||
.AddCommandsFromThisAssembly()
|
||||
.UseTypeActivator(serviceProvider)
|
||||
.UseTypeActivator(commandTypes =>
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
|
||||
// Register services
|
||||
services.AddSingleton<MyService>();
|
||||
|
||||
// Register commands
|
||||
foreach (var commandType in commandTypes)
|
||||
services.AddTransient(commandType);
|
||||
|
||||
return services.BuildServiceProvider();
|
||||
})
|
||||
.Build()
|
||||
.RunAsync();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -673,7 +621,12 @@ public async Task ConcatCommand_executes_successfully()
|
||||
.UseConsole(console)
|
||||
.Build();
|
||||
|
||||
var args = new[] {"--left", "foo", "--right", "bar"};
|
||||
var args = new[]
|
||||
{
|
||||
"--left", "foo",
|
||||
"--right", "bar"
|
||||
};
|
||||
|
||||
var envVars = new Dictionary<string, string>();
|
||||
|
||||
// Act
|
||||
@@ -694,19 +647,19 @@ To do that, you need to pass the corresponding directive before any other argume
|
||||
In order to run the application in debug mode, use the `[debug]` directive.
|
||||
This will cause the program to launch in a suspended state, waiting for debugger to be attached to the process:
|
||||
|
||||
```powershell
|
||||
> dotnet myapp.dll [debug] cmd -o
|
||||
```sh
|
||||
$ dotnet myapp.dll [debug] cmd -o
|
||||
|
||||
Attach debugger to PID 3148 to continue.
|
||||
```
|
||||
|
||||
To run the application in preview mode, use the `[preview]` directive.
|
||||
This will short-circuit the execution and instead print the consumed command line arguments as they were parsed, along with resolved environment variables:
|
||||
This will short-circuit the execution and instead print the consumed command-line arguments as they were parsed, along with resolved environment variables:
|
||||
|
||||
```powershell
|
||||
> dotnet myapp.dll [preview] cmd arg1 arg2 -o foo --option bar1 bar2
|
||||
```sh
|
||||
$ dotnet myapp.dll [preview] cmd arg1 arg2 -o foo --option bar1 bar2
|
||||
|
||||
Command line:
|
||||
Command-line:
|
||||
cmd <arg1> <arg2> [-o foo] [--option bar1 bar2]
|
||||
|
||||
Environment:
|
||||
@@ -726,5 +679,5 @@ var app = new CliApplicationBuilder()
|
||||
|
||||
## Etymology
|
||||
|
||||
**CliFx** is made out of "Cli" for "Command Line Interface" and "Fx" for "Framework".
|
||||
**CliFx** is made out of "Cli" for "Command-line Interface" and "Fx" for "Framework".
|
||||
It's pronounced as "cliff ex".
|
||||
Reference in New Issue
Block a user