63 Commits
2.1 ... 2.3

Author SHA1 Message Date
Oleksii Holub
5e97ebe7f0 Update version 2022-07-12 13:31:07 +03:00
Oleksii Holub
64cbdaaeab Add console dimension properties to IConsole
Closes #90
2022-06-28 15:38:10 +03:00
Oleksii Holub
ae1f03914c Update version 2022-06-14 22:34:55 +03:00
Oleksii Holub
ff25dccf8a Add overload of UseTypeActivator(...) that accepts an instance of IServiceProvider 2022-06-07 20:08:34 +03:00
Oleksii Holub
6e0d881682 Use new alerts in readme 2022-05-31 12:41:32 +03:00
Oleksii Holub
89fd42888a Update readme 2022-05-31 12:25:18 +03:00
Oleksii Holub
eeac82a6e7 Update nuget packages 2022-05-29 22:33:54 +03:00
Oleksii Holub
c641c6fbe2 Improve grammar in error messages 2022-05-26 22:21:31 +03:00
Oleksii Holub
5ec732fe9a Update version 2022-05-09 23:27:55 +03:00
Oleksii Holub
6d87411dbf Update NuGet packages 2022-05-09 23:27:33 +03:00
Oleksii Holub
ed3054c855 More consistent code style 2022-04-25 19:07:18 +03:00
Oleksii Holub
5d00de4dfe Update CliWrap 2022-04-25 19:05:23 +03:00
Oleksii Holub
016ec8b186 Make default executable name resolution smarter 2022-04-24 23:45:10 +03:00
Oleksii Holub
9141092919 Merge branch 'master' of github.com:Tyrrrz/CliFx 2022-04-24 22:59:49 +03:00
Oleksii Holub
1fe97b0140 Typo in docs 2022-04-24 22:59:38 +03:00
Oleksii Holub
6ad5989c25 Update readme 2022-04-24 19:54:37 +00:00
Oleksii Holub
7e1db916fc Update readme 2022-04-23 21:26:54 +00:00
Oleksii Holub
1c69d5c80d Update readme 2022-04-23 23:44:22 +03:00
Oleksii Holub
ab87225f1f Cleanup 2022-04-22 22:33:55 +03:00
Oleksii Holub
6d33c5cdad Update version 2022-04-22 19:15:44 +03:00
Oleksii Holub
e4c899c6c2 Reduce version of Microsoft.CodeAnalysis.CSharp further 2022-04-22 18:55:47 +03:00
Oleksii Holub
35b3ad0d63 Don't use Fody but also don't bundle Microsoft.CodeAnalysis.CSharp 2022-04-22 18:45:46 +03:00
Oleksii Holub
4e70557b47 Reorganize assets 2022-04-22 17:16:51 +03:00
Oleksii Holub
0a8d58255a Update NuGet.config 2022-04-22 16:58:21 +03:00
Oleksii Holub
d3fbc9c643 Merge analyzer project dependencies using Fody.Costura
Closes #127
2022-04-22 16:41:24 +03:00
Oleksii Holub
1cbf8776be Don't produce color codes in tests 2022-04-21 22:57:14 +03:00
Oleksii Holub
16e33f7b8f Update workflow 2022-04-21 22:51:11 +03:00
Oleksii Holub
5c848056c5 Add more contextual information to diagnostics 2022-04-20 20:27:53 +03:00
Oleksii Holub
864efd3179 Fix converter analyzer false positive when handling non-scalars or nullable types 2022-04-20 20:09:14 +03:00
Oleksii Holub
7f206a0c77 Update test logger 2022-04-19 01:31:40 +00:00
Oleksii Holub
22c15f8ec6 Update test logger 2022-04-18 19:53:52 +00:00
Oleksii Holub
59373eadc2 Update version 2022-04-17 00:20:26 +00:00
Oleksii Holub
ed3e4f471e Improve analyzer diagnostics 2022-04-17 00:01:34 +00:00
Oleksii Holub
41cb8647b5 Produce analyzer errors for invalid generic arguments in converters and validators
Closes #103
2022-04-16 22:54:57 +00:00
Oleksii Holub
c7015181e1 Update documentation 2022-04-16 15:34:58 +00:00
Oleksii Holub
86742755e8 Don't wrap default type activator exception if it's not related to constructor 2022-04-16 13:54:44 +00:00
Oleksii Holub
33f95d941d Use coverlet collector 2022-04-06 21:06:05 +00:00
Oleksii Holub
1328592cb5 Update Readme.md 2022-03-22 10:41:12 -07:00
Oleksii Holub
0711b863ea Update Readme.md 2022-03-21 10:12:22 -07:00
Oleksii Holub
a2f5cd54be Add terms of use 2022-03-05 09:46:14 -08:00
Oleksii Holub
7836ec610f Fuck Russia 2022-02-23 18:23:37 +02:00
Oleksii Holub
2e489927eb Update NuGet packages 2022-02-21 22:37:10 +02:00
Oleksii Holub
02e8d19e48 Refactor polyfills 2022-02-21 22:35:23 +02:00
Oleksii Holub
eb7107fb0a Return key in IConsole.ReadKey(...)
Closes #124
2022-02-19 01:32:58 +02:00
Oleksii Holub
a396009b62 Use expression bodied methods in more places 2022-01-30 19:11:23 +02:00
Oleksii Holub
1d9c7e942c Update version 2022-01-30 19:09:22 +02:00
Oleksii Holub
0f3abb9db4 Fix thread-safety of ConsoleWriter and ConsoleReader
Fixes #123
2022-01-30 19:07:22 +02:00
Oleksii Holub
896482821c Copy all analyzer dependencies to package 2022-01-21 01:16:59 +02:00
Oleksii Holub
aa3094ee54 Update version 2022-01-16 19:29:50 +02:00
Tyrrrz
712580e3d7 Update my name to match correct spelling 2022-01-15 03:24:06 +02:00
AliReZa Sabouri
c08102f85f Show default values for optional parameters (#122) 2022-01-11 05:22:13 -08:00
Tyrrrz
5e684c8b36 Update version 2022-01-11 00:40:30 +02:00
Tyrrrz
300ae70564 Update NuGet packages 2022-01-11 00:39:19 +02:00
Tyrrrz
76f0c77f1e Update readme 2022-01-11 00:32:56 +02:00
Tyrrrz
0f7cea4ed1 Add some more analyzer tests 2022-01-10 23:56:54 +02:00
Tyrrrz
32ee0b2bd6 Add test for optional parameters 2022-01-10 23:48:38 +02:00
Tyrrrz
4ff1e1d3e1 Cleanup 2022-01-10 23:41:28 +02:00
AliReZa Sabouri
8e96d2701d Add support for optional parameters (#119) 2022-01-10 13:11:04 -08:00
Tyrrrz
8e307df231 More cleanup 2022-01-10 16:55:43 +02:00
Tyrrrz
ff38f4916a Cleanup 2022-01-10 16:45:41 +02:00
AliReZa Sabouri
7cbbb220b4 Fix tests for default interface members (#121) 2022-01-09 20:29:57 -08:00
AliReZa Sabouri
ae2d4299f0 Add multiple inheritance support through interfaces (#120) 2022-01-09 08:11:42 -08:00
Tyrrrz
21bc69d116 Make projects not packable by default 2022-01-04 22:48:33 +02:00
89 changed files with 2013 additions and 644 deletions

View File

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 14 KiB

View File

@@ -4,7 +4,9 @@ on: [push, pull_request]
jobs: jobs:
main: main:
uses: Tyrrrz/.github/.github/workflows/NuGet.yml@master uses: Tyrrrz/.github/.github/workflows/nuget.yml@master
with:
dotnet-version: 6.0.x
secrets: secrets:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
NUGET_TOKEN: ${{ secrets.NUGET_TOKEN }} NUGET_TOKEN: ${{ secrets.NUGET_TOKEN }}

View File

@@ -1,3 +1,45 @@
### 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)
- 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)
- 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)
- 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)
- 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.
- Extended analyzers that verify the correctness of specified converters and validators. They now also ensure that the specified types are compatible with the type of the underlying property.
- 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)
- 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)
- 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)
- 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.Clear()` with corresponding implementations in `SystemConsole`, `FakeConsole`, and `FakeInMemoryConsole`. (Thanks [@Alex Rosenfeld](https://github.com/alexrosenfeld10))
@@ -37,7 +79,7 @@
### v2.0 (21-Mar-2021) ### v2.0 (21-Mar-2021)
> Note: this major release includes many breaking changes. > Note: this major release includes many breaking changes.
Please refer to the readme to find updated instructions and usage examples. > Please refer to the readme to find updated instructions and usage examples.
- Renamed property `EnvironmentVariableName` to `EnvironmentVariable` on `CommandOption` attribute. - Renamed property `EnvironmentVariableName` to `EnvironmentVariable` on `CommandOption` attribute.
- Removed most of schema validation checks that used to take place during application startup. Going forward, CliFx will be relying solely on its built-in set of Roslyn analyzers to catch common errors in command configuration. - Removed most of schema validation checks that used to take place during application startup. Going forward, CliFx will be relying solely on its built-in set of Roslyn analyzers to catch common errors in command configuration.

View File

@@ -2,10 +2,6 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>net6.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
<CollectCoverage>true</CollectCoverage>
<CoverletOutputFormat>opencover</CoverletOutputFormat>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -14,13 +10,13 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Basic.Reference.Assemblies" Version="1.2.4" /> <PackageReference Include="Basic.Reference.Assemblies" Version="1.2.4" />
<PackageReference Include="GitHubActionsTestLogger" Version="1.2.0" /> <PackageReference Include="GitHubActionsTestLogger" Version="2.0.0" PrivateAssets="all" />
<PackageReference Include="FluentAssertions" Version="6.2.0" /> <PackageReference Include="FluentAssertions" Version="6.7.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.2.0" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.0.1" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.2.0" />
<PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" PrivateAssets="all" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.5" PrivateAssets="all" />
<PackageReference Include="coverlet.msbuild" Version="3.1.0" PrivateAssets="all" /> <PackageReference Include="coverlet.collector" Version="3.1.2" PrivateAssets="all" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -19,7 +19,7 @@ public class MyCommand : ICommand
{ {
[CommandOption(null)] [CommandOption(null)]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";
@@ -38,7 +38,7 @@ public class MyCommand : ICommand
{ {
[CommandOption(""foo"")] [CommandOption(""foo"")]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";
@@ -57,7 +57,7 @@ public class MyCommand : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";

View File

@@ -19,7 +19,7 @@ public class MyCommand : ICommand
{ {
[CommandOption(""foo"")] [CommandOption(""foo"")]
public string Foo { get; set; } public string Foo { get; set; }
[CommandOption(""foo"")] [CommandOption(""foo"")]
public string Bar { get; set; } public string Bar { get; set; }
@@ -41,7 +41,7 @@ public class MyCommand : ICommand
{ {
[CommandOption(""foo"")] [CommandOption(""foo"")]
public string Foo { get; set; } public string Foo { get; set; }
[CommandOption(""bar"")] [CommandOption(""bar"")]
public string Bar { get; set; } public string Bar { get; set; }
@@ -63,7 +63,7 @@ public class MyCommand : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";

View File

@@ -19,7 +19,7 @@ public class MyCommand : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string Foo { get; set; } public string Foo { get; set; }
[CommandOption('f')] [CommandOption('f')]
public string Bar { get; set; } public string Bar { get; set; }
@@ -41,7 +41,7 @@ public class MyCommand : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string Foo { get; set; } public string Foo { get; set; }
[CommandOption('b')] [CommandOption('b')]
public string Bar { get; set; } public string Bar { get; set; }
@@ -63,7 +63,7 @@ public class MyCommand : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string Foo { get; set; } public string Foo { get; set; }
[CommandOption('F')] [CommandOption('F')]
public string Bar { get; set; } public string Bar { get; set; }
@@ -85,7 +85,7 @@ public class MyCommand : ICommand
{ {
[CommandOption(""foo"")] [CommandOption(""foo"")]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";

View File

@@ -9,7 +9,7 @@ public class OptionMustHaveValidConverterAnalyzerSpecs
private static DiagnosticAnalyzer Analyzer { get; } = new OptionMustHaveValidConverterAnalyzer(); private static DiagnosticAnalyzer Analyzer { get; } = new OptionMustHaveValidConverterAnalyzer();
[Fact] [Fact]
public void Analyzer_reports_an_error_if_the_specified_option_converter_does_not_derive_from_BindingConverter() public void Analyzer_reports_an_error_if_an_option_has_a_converter_that_does_not_derive_from_BindingConverter()
{ {
// Arrange // Arrange
// language=cs // language=cs
@@ -24,7 +24,7 @@ public class MyCommand : ICommand
{ {
[CommandOption(""foo"", Converter = typeof(MyConverter))] [CommandOption(""foo"", Converter = typeof(MyConverter))]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";
@@ -33,7 +33,31 @@ public class MyCommand : ICommand
} }
[Fact] [Fact]
public void Analyzer_does_not_report_an_error_if_the_specified_option_converter_derives_from_BindingConverter() public void Analyzer_reports_an_error_if_an_option_has_a_converter_that_does_not_derive_from_a_compatible_BindingConverter()
{
// Arrange
// language=cs
const string code = @"
public class MyConverter : BindingConverter<int>
{
public override int Convert(string rawValue) => 42;
}
[Command]
public class MyCommand : ICommand
{
[CommandOption(""foo"", Converter = typeof(MyConverter))]
public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
}";
// Act & assert
Analyzer.Should().ProduceDiagnostics(code);
}
[Fact]
public void Analyzer_does_not_report_an_error_if_an_option_has_a_converter_that_derives_from_a_compatible_BindingConverter()
{ {
// Arrange // Arrange
// language=cs // language=cs
@@ -48,7 +72,55 @@ public class MyCommand : ICommand
{ {
[CommandOption(""foo"", Converter = typeof(MyConverter))] [CommandOption(""foo"", Converter = typeof(MyConverter))]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
}";
// Act & assert
Analyzer.Should().NotProduceDiagnostics(code);
}
[Fact]
public void Analyzer_does_not_report_an_error_if_a_nullable_option_has_a_converter_that_derives_from_a_compatible_BindingConverter()
{
// Arrange
// language=cs
const string code = @"
public class MyConverter : BindingConverter<int>
{
public override int Convert(string rawValue) => 42;
}
[Command]
public class MyCommand : ICommand
{
[CommandOption(""foo"", Converter = typeof(MyConverter))]
public int? Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
}";
// Act & assert
Analyzer.Should().NotProduceDiagnostics(code);
}
[Fact]
public void Analyzer_does_not_report_an_error_if_a_non_scalar_option_has_a_converter_that_derives_from_a_compatible_BindingConverter()
{
// Arrange
// language=cs
const string code = @"
public class MyConverter : BindingConverter<string>
{
public override string Convert(string rawValue) => rawValue;
}
[Command]
public class MyCommand : ICommand
{
[CommandOption(""foo"", Converter = typeof(MyConverter))]
public IReadOnlyList<string> Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";
@@ -67,7 +139,7 @@ public class MyCommand : ICommand
{ {
[CommandOption(""foo"")] [CommandOption(""foo"")]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";

View File

@@ -19,7 +19,7 @@ public class MyCommand : ICommand
{ {
[CommandOption(""f"")] [CommandOption(""f"")]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";
@@ -38,7 +38,7 @@ public class MyCommand : ICommand
{ {
[CommandOption(""1foo"")] [CommandOption(""1foo"")]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";
@@ -57,7 +57,7 @@ public class MyCommand : ICommand
{ {
[CommandOption(""foo"")] [CommandOption(""foo"")]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";
@@ -76,7 +76,7 @@ public class MyCommand : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";

View File

@@ -19,7 +19,7 @@ public class MyCommand : ICommand
{ {
[CommandOption('1')] [CommandOption('1')]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";
@@ -38,7 +38,7 @@ public class MyCommand : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";
@@ -57,7 +57,7 @@ public class MyCommand : ICommand
{ {
[CommandOption(""foo"")] [CommandOption(""foo"")]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";

View File

@@ -9,7 +9,7 @@ public class OptionMustHaveValidValidatorsAnalyzerSpecs
private static DiagnosticAnalyzer Analyzer { get; } = new OptionMustHaveValidValidatorsAnalyzer(); private static DiagnosticAnalyzer Analyzer { get; } = new OptionMustHaveValidValidatorsAnalyzer();
[Fact] [Fact]
public void Analyzer_reports_an_error_if_one_of_the_specified_option_validators_does_not_derive_from_BindingValidator() public void Analyzer_reports_an_error_if_an_option_has_a_validator_that_does_not_derive_from_BindingValidator()
{ {
// Arrange // Arrange
// language=cs // language=cs
@@ -24,7 +24,7 @@ public class MyCommand : ICommand
{ {
[CommandOption(""foo"", Validators = new[] {typeof(MyValidator)})] [CommandOption(""foo"", Validators = new[] {typeof(MyValidator)})]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";
@@ -33,7 +33,31 @@ public class MyCommand : ICommand
} }
[Fact] [Fact]
public void Analyzer_does_not_report_an_error_if_all_specified_option_validators_derive_from_BindingValidator() public void Analyzer_reports_an_error_if_an_option_has_a_validator_that_does_not_derive_from_a_compatible_BindingValidator()
{
// Arrange
// language=cs
const string code = @"
public class MyValidator : BindingValidator<int>
{
public override BindingValidationError Validate(int value) => Ok();
}
[Command]
public class MyCommand : ICommand
{
[CommandOption(""foo"", Validators = new[] {typeof(MyValidator)})]
public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
}";
// Act & assert
Analyzer.Should().ProduceDiagnostics(code);
}
[Fact]
public void Analyzer_does_not_report_an_error_if_an_option_has_validators_that_all_derive_from_compatible_BindingValidators()
{ {
// Arrange // Arrange
// language=cs // language=cs
@@ -48,7 +72,7 @@ public class MyCommand : ICommand
{ {
[CommandOption(""foo"", Validators = new[] {typeof(MyValidator)})] [CommandOption(""foo"", Validators = new[] {typeof(MyValidator)})]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";
@@ -67,7 +91,7 @@ public class MyCommand : ICommand
{ {
[CommandOption(""foo"")] [CommandOption(""foo"")]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";

View File

@@ -0,0 +1,94 @@
using CliFx.Analyzers.Tests.Utils;
using Microsoft.CodeAnalysis.Diagnostics;
using Xunit;
namespace CliFx.Analyzers.Tests;
public class ParameterMustBeLastIfNonRequiredAnalyzerSpecs
{
private static DiagnosticAnalyzer Analyzer { get; } = new ParameterMustBeLastIfNonRequiredAnalyzer();
[Fact]
public void Analyzer_reports_an_error_if_a_non_required_parameter_is_not_the_last_in_order()
{
// Arrange
// language=cs
const string code = @"
[Command]
public class MyCommand : ICommand
{
[CommandParameter(0, Name = ""foo"", IsRequired = false)]
public string Foo { get; set; }
[CommandParameter(1, Name = ""bar"")]
public string Bar { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
}";
// Act & assert
Analyzer.Should().ProduceDiagnostics(code);
}
[Fact]
public void Analyzer_does_not_report_an_error_if_a_non_required_parameter_is_the_last_in_order()
{
// Arrange
// language=cs
const string code = @"
[Command]
public class MyCommand : ICommand
{
[CommandParameter(0, Name = ""foo"")]
public string Foo { get; set; }
[CommandParameter(1, Name = ""bar"", IsRequired = false)]
public string Bar { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
}";
// Act & assert
Analyzer.Should().NotProduceDiagnostics(code);
}
[Fact]
public void Analyzer_does_not_report_an_error_if_no_non_required_parameters_are_defined()
{
// Arrange
// language=cs
const string code = @"
[Command]
public class MyCommand : ICommand
{
[CommandParameter(0, Name = ""foo"")]
public string Foo { get; set; }
[CommandParameter(1, Name = ""bar"", IsRequired = true)]
public string Bar { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
}";
// Act & assert
Analyzer.Should().NotProduceDiagnostics(code);
}
[Fact]
public void Analyzer_does_not_report_an_error_on_a_property_that_is_not_a_parameter()
{
// Arrange
// language=cs
const string code = @"
[Command]
public class MyCommand : ICommand
{
public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
}";
// Act & assert
Analyzer.Should().NotProduceDiagnostics(code);
}
}

View File

@@ -9,7 +9,7 @@ public class ParameterMustBeLastIfNonScalarAnalyzerSpecs
private static DiagnosticAnalyzer Analyzer { get; } = new ParameterMustBeLastIfNonScalarAnalyzer(); private static DiagnosticAnalyzer Analyzer { get; } = new ParameterMustBeLastIfNonScalarAnalyzer();
[Fact] [Fact]
public void Analyzer_reports_an_error_if_a_non_scalar_parameter_is_not_last_in_order() public void Analyzer_reports_an_error_if_a_non_scalar_parameter_is_not_the_last_in_order()
{ {
// Arrange // Arrange
// language=cs // language=cs
@@ -19,7 +19,7 @@ public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string[] Foo { get; set; } public string[] Foo { get; set; }
[CommandParameter(1)] [CommandParameter(1)]
public string Bar { get; set; } public string Bar { get; set; }
@@ -31,7 +31,7 @@ public class MyCommand : ICommand
} }
[Fact] [Fact]
public void Analyzer_does_not_report_an_error_if_a_non_scalar_parameter_is_last_in_order() public void Analyzer_does_not_report_an_error_if_a_non_scalar_parameter_is_the_last_in_order()
{ {
// Arrange // Arrange
// language=cs // language=cs
@@ -41,7 +41,7 @@ public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public string Foo { get; set; }
[CommandParameter(1)] [CommandParameter(1)]
public string[] Bar { get; set; } public string[] Bar { get; set; }
@@ -63,7 +63,7 @@ public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public string Foo { get; set; }
[CommandParameter(1)] [CommandParameter(1)]
public string Bar { get; set; } public string Bar { get; set; }

View File

@@ -0,0 +1,94 @@
using CliFx.Analyzers.Tests.Utils;
using Microsoft.CodeAnalysis.Diagnostics;
using Xunit;
namespace CliFx.Analyzers.Tests;
public class ParameterMustBeSingleIfNonRequiredAnalyzerSpecs
{
private static DiagnosticAnalyzer Analyzer { get; } = new ParameterMustBeSingleIfNonRequiredAnalyzer();
[Fact]
public void Analyzer_reports_an_error_if_more_than_one_non_required_parameters_are_defined()
{
// Arrange
// language=cs
const string code = @"
[Command]
public class MyCommand : ICommand
{
[CommandParameter(0, IsRequired = false)]
public string Foo { get; set; }
[CommandParameter(1, IsRequired = false)]
public string Bar { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
}";
// Act & assert
Analyzer.Should().ProduceDiagnostics(code);
}
[Fact]
public void Analyzer_does_not_report_an_error_if_only_one_non_required_parameter_is_defined()
{
// Arrange
// language=cs
const string code = @"
[Command]
public class MyCommand : ICommand
{
[CommandParameter(0)]
public string Foo { get; set; }
[CommandParameter(1, IsRequired = false)]
public string Bar { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
}";
// Act & assert
Analyzer.Should().NotProduceDiagnostics(code);
}
[Fact]
public void Analyzer_does_not_report_an_error_if_no_non_required_parameters_are_defined()
{
// Arrange
// language=cs
const string code = @"
[Command]
public class MyCommand : ICommand
{
[CommandParameter(0)]
public string Foo { get; set; }
[CommandParameter(1, IsRequired = true)]
public string Bar { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
}";
// Act & assert
Analyzer.Should().NotProduceDiagnostics(code);
}
[Fact]
public void Analyzer_does_not_report_an_error_on_a_property_that_is_not_a_parameter()
{
// Arrange
// language=cs
const string code = @"
[Command]
public class MyCommand : ICommand
{
public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
}";
// Act & assert
Analyzer.Should().NotProduceDiagnostics(code);
}
}

View File

@@ -19,7 +19,7 @@ public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string[] Foo { get; set; } public string[] Foo { get; set; }
[CommandParameter(1)] [CommandParameter(1)]
public string[] Bar { get; set; } public string[] Bar { get; set; }
@@ -41,7 +41,7 @@ public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public string Foo { get; set; }
[CommandParameter(1)] [CommandParameter(1)]
public string[] Bar { get; set; } public string[] Bar { get; set; }
@@ -63,7 +63,7 @@ public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public string Foo { get; set; }
[CommandParameter(1)] [CommandParameter(1)]
public string Bar { get; set; } public string Bar { get; set; }

View File

@@ -19,7 +19,7 @@ public class MyCommand : ICommand
{ {
[CommandParameter(0, Name = ""foo"")] [CommandParameter(0, Name = ""foo"")]
public string Foo { get; set; } public string Foo { get; set; }
[CommandParameter(1, Name = ""foo"")] [CommandParameter(1, Name = ""foo"")]
public string Bar { get; set; } public string Bar { get; set; }
@@ -41,7 +41,7 @@ public class MyCommand : ICommand
{ {
[CommandParameter(0, Name = ""foo"")] [CommandParameter(0, Name = ""foo"")]
public string Foo { get; set; } public string Foo { get; set; }
[CommandParameter(1, Name = ""bar"")] [CommandParameter(1, Name = ""bar"")]
public string Bar { get; set; } public string Bar { get; set; }

View File

@@ -19,7 +19,7 @@ public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public string Foo { get; set; }
[CommandParameter(0)] [CommandParameter(0)]
public string Bar { get; set; } public string Bar { get; set; }
@@ -41,7 +41,7 @@ public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public string Foo { get; set; }
[CommandParameter(1)] [CommandParameter(1)]
public string Bar { get; set; } public string Bar { get; set; }

View File

@@ -9,7 +9,7 @@ public class ParameterMustHaveValidConverterAnalyzerSpecs
private static DiagnosticAnalyzer Analyzer { get; } = new ParameterMustHaveValidConverterAnalyzer(); private static DiagnosticAnalyzer Analyzer { get; } = new ParameterMustHaveValidConverterAnalyzer();
[Fact] [Fact]
public void Analyzer_reports_an_error_if_the_specified_parameter_converter_does_not_derive_from_BindingConverter() public void Analyzer_reports_an_error_if_a_parameter_has_a_converter_that_does_not_derive_from_BindingConverter()
{ {
// Arrange // Arrange
// language=cs // language=cs
@@ -24,7 +24,7 @@ public class MyCommand : ICommand
{ {
[CommandParameter(0, Converter = typeof(MyConverter))] [CommandParameter(0, Converter = typeof(MyConverter))]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";
@@ -33,7 +33,32 @@ public class MyCommand : ICommand
} }
[Fact] [Fact]
public void Analyzer_does_not_report_an_error_if_the_specified_parameter_converter_derives_from_BindingConverter() public void Analyzer_reports_an_error_if_a_parameter_has_a_converter_that_does_not_derive_from_a_compatible_BindingConverter()
{
// Arrange
// language=cs
const string code = @"
public class MyConverter : BindingConverter<int>
{
public override int Convert(string rawValue) => 42;
}
[Command]
public class MyCommand : ICommand
{
[CommandParameter(0, Converter = typeof(MyConverter))]
public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
}";
// Act & assert
Analyzer.Should().ProduceDiagnostics(code);
}
[Fact]
public void Analyzer_does_not_report_an_error_if_a_parameter_has_a_converter_that_derives_from_a_compatible_BindingConverter()
{ {
// Arrange // Arrange
// language=cs // language=cs
@@ -48,7 +73,55 @@ public class MyCommand : ICommand
{ {
[CommandParameter(0, Converter = typeof(MyConverter))] [CommandParameter(0, Converter = typeof(MyConverter))]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
}";
// Act & assert
Analyzer.Should().NotProduceDiagnostics(code);
}
[Fact]
public void Analyzer_does_not_report_an_error_if_a_nullable_parameter_has_a_converter_that_derives_from_a_compatible_BindingConverter()
{
// Arrange
// language=cs
const string code = @"
public class MyConverter : BindingConverter<int>
{
public override int Convert(string rawValue) => 42;
}
[Command]
public class MyCommand : ICommand
{
[CommandOption(""foo"", Converter = typeof(MyConverter))]
public int? Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
}";
// Act & assert
Analyzer.Should().NotProduceDiagnostics(code);
}
[Fact]
public void Analyzer_does_not_report_an_error_if_a_non_scalar_parameter_has_a_converter_that_derives_from_a_compatible_BindingConverter()
{
// Arrange
// language=cs
const string code = @"
public class MyConverter : BindingConverter<string>
{
public override string Convert(string rawValue) => rawValue;
}
[Command]
public class MyCommand : ICommand
{
[CommandParameter(0, Converter = typeof(MyConverter))]
public IReadOnlyList<string> Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";
@@ -67,7 +140,7 @@ public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";

View File

@@ -9,7 +9,7 @@ public class ParameterMustHaveValidValidatorsAnalyzerSpecs
private static DiagnosticAnalyzer Analyzer { get; } = new ParameterMustHaveValidValidatorsAnalyzer(); private static DiagnosticAnalyzer Analyzer { get; } = new ParameterMustHaveValidValidatorsAnalyzer();
[Fact] [Fact]
public void Analyzer_reports_an_error_if_one_of_the_specified_parameter_validators_does_not_derive_from_BindingValidator() public void Analyzer_reports_an_error_a_parameter_has_a_validator_that_does_not_derive_from_BindingValidator()
{ {
// Arrange // Arrange
// language=cs // language=cs
@@ -24,7 +24,7 @@ public class MyCommand : ICommand
{ {
[CommandParameter(0, Validators = new[] {typeof(MyValidator)})] [CommandParameter(0, Validators = new[] {typeof(MyValidator)})]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";
@@ -33,7 +33,31 @@ public class MyCommand : ICommand
} }
[Fact] [Fact]
public void Analyzer_does_not_report_an_error_if_all_specified_parameter_validators_derive_from_BindingValidator() public void Analyzer_reports_an_error_if_a_parameter_has_a_validator_that_does_not_derive_from_a_compatible_BindingValidator()
{
// Arrange
// language=cs
const string code = @"
public class MyValidator : BindingValidator<int>
{
public override BindingValidationError Validate(int value) => Ok();
}
[Command]
public class MyCommand : ICommand
{
[CommandParameter(0, Validators = new[] {typeof(MyValidator)})]
public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
}";
// Act & assert
Analyzer.Should().ProduceDiagnostics(code);
}
[Fact]
public void Analyzer_does_not_report_an_error_if_a_parameter_has_validators_that_all_derive_from_compatible_BindingValidators()
{ {
// Arrange // Arrange
// language=cs // language=cs
@@ -48,7 +72,7 @@ public class MyCommand : ICommand
{ {
[CommandParameter(0, Validators = new[] {typeof(MyValidator)})] [CommandParameter(0, Validators = new[] {typeof(MyValidator)})]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";
@@ -67,7 +91,7 @@ public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"; }";

View File

@@ -57,7 +57,7 @@ internal class AnalyzerAssertions : ReferenceTypeAssertions<DiagnosticAnalyzer,
// Compile the code to IL // Compile the code to IL
var compilation = CSharpCompilation.Create( var compilation = CSharpCompilation.Create(
"CliFxTests_DynamicAssembly_" + Guid.NewGuid(), "CliFxTests_DynamicAssembly_" + Guid.NewGuid(),
new[] {ast}, new[] { ast },
ReferenceAssemblies.Net50 ReferenceAssemblies.Net50
.Append(MetadataReference.CreateFromFile(typeof(ICommand).Assembly.Location)), .Append(MetadataReference.CreateFromFile(typeof(ICommand).Assembly.Location)),
// DLL to avoid having to define the Main() method // DLL to avoid having to define the Main() method
@@ -101,11 +101,11 @@ internal class AnalyzerAssertions : ReferenceTypeAssertions<DiagnosticAnalyzer,
var expectedDiagnosticIds = expectedDiagnostics.Select(d => d.Id).Distinct().ToArray(); var expectedDiagnosticIds = expectedDiagnostics.Select(d => d.Id).Distinct().ToArray();
var producedDiagnosticIds = producedDiagnostics.Select(d => d.Id).Distinct().ToArray(); var producedDiagnosticIds = producedDiagnostics.Select(d => d.Id).Distinct().ToArray();
var result = var isSuccessfulAssertion =
expectedDiagnosticIds.Intersect(producedDiagnosticIds).Count() == expectedDiagnosticIds.Intersect(producedDiagnosticIds).Count() ==
expectedDiagnosticIds.Length; expectedDiagnosticIds.Length;
Execute.Assertion.ForCondition(result).FailWith(() => Execute.Assertion.ForCondition(isSuccessfulAssertion).FailWith(() =>
{ {
var buffer = new StringBuilder(); var buffer = new StringBuilder();
@@ -125,10 +125,17 @@ internal class AnalyzerAssertions : ReferenceTypeAssertions<DiagnosticAnalyzer,
buffer.AppendLine("Produced diagnostics:"); buffer.AppendLine("Produced diagnostics:");
foreach (var producedDiagnostic in producedDiagnostics) if (producedDiagnostics.Any())
{ {
buffer.Append(" - "); foreach (var producedDiagnostic in producedDiagnostics)
buffer.Append(producedDiagnostic); {
buffer.Append(" - ");
buffer.Append(producedDiagnostic);
}
}
else
{
buffer.AppendLine(" < none >");
} }
return new FailReason(buffer.ToString()); return new FailReason(buffer.ToString());
@@ -138,10 +145,9 @@ internal class AnalyzerAssertions : ReferenceTypeAssertions<DiagnosticAnalyzer,
public void NotProduceDiagnostics(string sourceCode) public void NotProduceDiagnostics(string sourceCode)
{ {
var producedDiagnostics = GetProducedDiagnostics(sourceCode); var producedDiagnostics = GetProducedDiagnostics(sourceCode);
var isSuccessfulAssertion = !producedDiagnostics.Any();
var result = !producedDiagnostics.Any(); Execute.Assertion.ForCondition(isSuccessfulAssertion).FailWith(() =>
Execute.Assertion.ForCondition(result).FailWith(() =>
{ {
var buffer = new StringBuilder(); var buffer = new StringBuilder();

View File

@@ -28,8 +28,8 @@ public abstract class AnalyzerBase : DiagnosticAnalyzer
SupportedDiagnostics = ImmutableArray.Create(SupportedDiagnostic); SupportedDiagnostics = ImmutableArray.Create(SupportedDiagnostic);
} }
protected Diagnostic CreateDiagnostic(Location location) => protected Diagnostic CreateDiagnostic(Location location, params object?[]? messageArgs) =>
Diagnostic.Create(SupportedDiagnostic, location); Diagnostic.Create(SupportedDiagnostic, location, messageArgs);
public override void Initialize(AnalysisContext context) public override void Initialize(AnalysisContext context)
{ {

View File

@@ -2,12 +2,15 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework> <TargetFramework>netstandard2.0</TargetFramework>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
<Nullable>annotations</Nullable> <Nullable>annotations</Nullable>
<NoWarn>$(NoWarn);RS1025;RS1026</NoWarn> <NoWarn>$(NoWarn);RS1025;RS1026</NoWarn>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.4.0" PrivateAssets="all" /> <!-- Keep this dependency as low as possible since we can't bundle it -->
<!-- https://github.com/Tyrrrz/CliFx/issues/127 -->
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.8.0" PrivateAssets="all" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -30,18 +30,20 @@ public class CommandMustBeAnnotatedAnalyzer : AnalyzerBase
var implementsCommandInterface = type var implementsCommandInterface = type
.AllInterfaces .AllInterfaces
.Any(s => s.DisplayNameMatches(SymbolNames.CliFxCommandInterface)); .Any(i => i.DisplayNameMatches(SymbolNames.CliFxCommandInterface));
var hasCommandAttribute = type var hasCommandAttribute = type
.GetAttributes() .GetAttributes()
.Select(a => a.AttributeClass) .Select(a => a.AttributeClass)
.Any(s => s.DisplayNameMatches(SymbolNames.CliFxCommandAttribute)); .Any(c => c.DisplayNameMatches(SymbolNames.CliFxCommandAttribute));
// If the interface is implemented, but the attribute is missing, // If the interface is implemented, but the attribute is missing,
// then it's very likely a user error. // then it's very likely a user error.
if (implementsCommandInterface && !hasCommandAttribute) if (implementsCommandInterface && !hasCommandAttribute)
{ {
context.ReportDiagnostic(CreateDiagnostic(classDeclaration.GetLocation())); context.ReportDiagnostic(
CreateDiagnostic(classDeclaration.Identifier.GetLocation())
);
} }
} }

View File

@@ -25,17 +25,19 @@ public class CommandMustImplementInterfaceAnalyzer : AnalyzerBase
var hasCommandAttribute = type var hasCommandAttribute = type
.GetAttributes() .GetAttributes()
.Select(a => a.AttributeClass) .Select(a => a.AttributeClass)
.Any(s => s.DisplayNameMatches(SymbolNames.CliFxCommandAttribute)); .Any(c => c.DisplayNameMatches(SymbolNames.CliFxCommandAttribute));
var implementsCommandInterface = type var implementsCommandInterface = type
.AllInterfaces .AllInterfaces
.Any(s => s.DisplayNameMatches(SymbolNames.CliFxCommandInterface)); .Any(i => i.DisplayNameMatches(SymbolNames.CliFxCommandInterface));
// If the attribute is present, but the interface is not implemented, // If the attribute is present, but the interface is not implemented,
// it's very likely a user error. // it's very likely a user error.
if (hasCommandAttribute && !implementsCommandInterface) if (hasCommandAttribute && !implementsCommandInterface)
{ {
context.ReportDiagnostic(CreateDiagnostic(classDeclaration.GetLocation())); context.ReportDiagnostic(
CreateDiagnostic(classDeclaration.Identifier.GetLocation())
);
} }
} }

View File

@@ -1,12 +1,14 @@
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using System.Linq; using System.Linq;
using CliFx.Analyzers.Utils.Extensions; using CliFx.Analyzers.Utils.Extensions;
using Microsoft.CodeAnalysis;
namespace CliFx.Analyzers.ObjectModel; namespace CliFx.Analyzers.ObjectModel;
internal partial class CommandOptionSymbol internal partial class CommandOptionSymbol : ICommandMemberSymbol
{ {
public IPropertySymbol Property { get; }
public string? Name { get; } public string? Name { get; }
public char? ShortName { get; } public char? ShortName { get; }
@@ -16,11 +18,13 @@ internal partial class CommandOptionSymbol
public IReadOnlyList<ITypeSymbol> ValidatorTypes { get; } public IReadOnlyList<ITypeSymbol> ValidatorTypes { get; }
public CommandOptionSymbol( public CommandOptionSymbol(
IPropertySymbol property,
string? name, string? name,
char? shortName, char? shortName,
ITypeSymbol? converterType, ITypeSymbol? converterType,
IReadOnlyList<ITypeSymbol> validatorTypes) IReadOnlyList<ITypeSymbol> validatorTypes)
{ {
Property = property;
Name = name; Name = name;
ShortName = shortName; ShortName = shortName;
ConverterType = converterType; ConverterType = converterType;
@@ -30,22 +34,25 @@ internal partial class CommandOptionSymbol
internal partial class CommandOptionSymbol internal partial class CommandOptionSymbol
{ {
private static AttributeData? TryGetOptionAttribute(IPropertySymbol property) => private static AttributeData? TryGetOptionAttribute(IPropertySymbol property) => property
property .GetAttributes()
.GetAttributes() .FirstOrDefault(a => a.AttributeClass?.DisplayNameMatches(SymbolNames.CliFxCommandOptionAttribute) == true);
.FirstOrDefault(a => a.AttributeClass.DisplayNameMatches(SymbolNames.CliFxCommandOptionAttribute));
private static CommandOptionSymbol FromAttribute(AttributeData attribute) public static CommandOptionSymbol? TryResolve(IPropertySymbol property)
{ {
var attribute = TryGetOptionAttribute(property);
if (attribute is null)
return null;
var name = attribute var name = attribute
.ConstructorArguments .ConstructorArguments
.Where(a => a.Type.DisplayNameMatches("string") || a.Type.DisplayNameMatches("System.String")) .Where(a => a.Type?.SpecialType == SpecialType.System_String)
.Select(a => a.Value) .Select(a => a.Value)
.FirstOrDefault() as string; .FirstOrDefault() as string;
var shortName = attribute var shortName = attribute
.ConstructorArguments .ConstructorArguments
.Where(a => a.Type.DisplayNameMatches("char") || a.Type.DisplayNameMatches("System.Char")) .Where(a => a.Type?.SpecialType == SpecialType.System_Char)
.Select(a => a.Value) .Select(a => a.Value)
.FirstOrDefault() as char?; .FirstOrDefault() as char?;
@@ -64,17 +71,7 @@ internal partial class CommandOptionSymbol
.Cast<ITypeSymbol>() .Cast<ITypeSymbol>()
.ToArray(); .ToArray();
return new CommandOptionSymbol(name, shortName, converter, validators); return new CommandOptionSymbol(property, name, shortName, converter, validators);
}
public static CommandOptionSymbol? TryResolve(IPropertySymbol property)
{
var attribute = TryGetOptionAttribute(property);
if (attribute is null)
return null;
return FromAttribute(attribute);
} }
public static bool IsOptionProperty(IPropertySymbol property) => public static bool IsOptionProperty(IPropertySymbol property) =>

View File

@@ -5,24 +5,32 @@ using Microsoft.CodeAnalysis;
namespace CliFx.Analyzers.ObjectModel; namespace CliFx.Analyzers.ObjectModel;
internal partial class CommandParameterSymbol internal partial class CommandParameterSymbol : ICommandMemberSymbol
{ {
public IPropertySymbol Property { get; }
public int Order { get; } public int Order { get; }
public string? Name { get; } public string? Name { get; }
public bool? IsRequired { get; }
public ITypeSymbol? ConverterType { get; } public ITypeSymbol? ConverterType { get; }
public IReadOnlyList<ITypeSymbol> ValidatorTypes { get; } public IReadOnlyList<ITypeSymbol> ValidatorTypes { get; }
public CommandParameterSymbol( public CommandParameterSymbol(
IPropertySymbol property,
int order, int order,
string? name, string? name,
bool? isRequired,
ITypeSymbol? converterType, ITypeSymbol? converterType,
IReadOnlyList<ITypeSymbol> validatorTypes) IReadOnlyList<ITypeSymbol> validatorTypes)
{ {
Property = property;
Order = order; Order = order;
Name = name; Name = name;
IsRequired = isRequired;
ConverterType = converterType; ConverterType = converterType;
ValidatorTypes = validatorTypes; ValidatorTypes = validatorTypes;
} }
@@ -30,14 +38,17 @@ internal partial class CommandParameterSymbol
internal partial class CommandParameterSymbol internal partial class CommandParameterSymbol
{ {
private static AttributeData? TryGetParameterAttribute(IPropertySymbol property) => private static AttributeData? TryGetParameterAttribute(IPropertySymbol property) => property
property .GetAttributes()
.GetAttributes() .FirstOrDefault(a => a.AttributeClass?.DisplayNameMatches(SymbolNames.CliFxCommandParameterAttribute) == true);
.FirstOrDefault(a => a.AttributeClass.DisplayNameMatches(SymbolNames.CliFxCommandParameterAttribute));
private static CommandParameterSymbol FromAttribute(AttributeData attribute) public static CommandParameterSymbol? TryResolve(IPropertySymbol property)
{ {
var order = (int) attribute var attribute = TryGetParameterAttribute(property);
if (attribute is null)
return null;
var order = (int)attribute
.ConstructorArguments .ConstructorArguments
.Select(a => a.Value) .Select(a => a.Value)
.First()!; .First()!;
@@ -48,6 +59,12 @@ internal partial class CommandParameterSymbol
.Select(a => a.Value.Value) .Select(a => a.Value.Value)
.FirstOrDefault() as string; .FirstOrDefault() as string;
var isRequired = attribute
.NamedArguments
.Where(a => a.Key == "IsRequired")
.Select(a => a.Value.Value)
.FirstOrDefault() as bool?;
var converter = attribute var converter = attribute
.NamedArguments .NamedArguments
.Where(a => a.Key == "Converter") .Where(a => a.Key == "Converter")
@@ -63,17 +80,7 @@ internal partial class CommandParameterSymbol
.Cast<ITypeSymbol>() .Cast<ITypeSymbol>()
.ToArray(); .ToArray();
return new CommandParameterSymbol(order, name, converter, validators); return new CommandParameterSymbol(property, order, name, isRequired, converter, validators);
}
public static CommandParameterSymbol? TryResolve(IPropertySymbol property)
{
var attribute = TryGetParameterAttribute(property);
if (attribute is null)
return null;
return FromAttribute(attribute);
} }
public static bool IsParameterProperty(IPropertySymbol property) => public static bool IsParameterProperty(IPropertySymbol property) =>

View File

@@ -0,0 +1,21 @@
using System.Collections.Generic;
using CliFx.Analyzers.Utils.Extensions;
using Microsoft.CodeAnalysis;
namespace CliFx.Analyzers.ObjectModel;
internal interface ICommandMemberSymbol
{
IPropertySymbol Property { get; }
ITypeSymbol? ConverterType { get; }
IReadOnlyList<ITypeSymbol> ValidatorTypes { get; }
}
internal static class CommandMemberSymbolExtensions
{
public static bool IsScalar(this ICommandMemberSymbol member) =>
member.Property.Type.SpecialType == SpecialType.System_String ||
member.Property.Type.TryGetEnumerableUnderlyingType() is null;
}

View File

@@ -7,8 +7,6 @@ internal static class SymbolNames
public const string CliFxCommandParameterAttribute = "CliFx.Attributes.CommandParameterAttribute"; public const string CliFxCommandParameterAttribute = "CliFx.Attributes.CommandParameterAttribute";
public const string CliFxCommandOptionAttribute = "CliFx.Attributes.CommandOptionAttribute"; public const string CliFxCommandOptionAttribute = "CliFx.Attributes.CommandOptionAttribute";
public const string CliFxConsoleInterface = "CliFx.Infrastructure.IConsole"; public const string CliFxConsoleInterface = "CliFx.Infrastructure.IConsole";
public const string CliFxBindingConverterInterface = "CliFx.Extensibility.IBindingConverter";
public const string CliFxBindingConverterClass = "CliFx.Extensibility.BindingConverter<T>"; public const string CliFxBindingConverterClass = "CliFx.Extensibility.BindingConverter<T>";
public const string CliFxBindingValidatorInterface = "CliFx.Extensibility.IBindingValidator";
public const string CliFxBindingValidatorClass = "CliFx.Extensibility.BindingValidator<T>"; public const string CliFxBindingValidatorClass = "CliFx.Extensibility.BindingValidator<T>";
} }

View File

@@ -34,11 +34,13 @@ public class OptionMustBeInsideCommandAnalyzer : AnalyzerBase
var isInsideCommand = property var isInsideCommand = property
.ContainingType .ContainingType
.AllInterfaces .AllInterfaces
.Any(s => s.DisplayNameMatches(SymbolNames.CliFxCommandInterface)); .Any(i => i.DisplayNameMatches(SymbolNames.CliFxCommandInterface));
if (!isInsideCommand) if (!isInsideCommand)
{ {
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation())); context.ReportDiagnostic(
CreateDiagnostic(propertyDeclaration.Identifier.GetLocation())
);
} }
} }

View File

@@ -27,7 +27,9 @@ public class OptionMustHaveNameOrShortNameAnalyzer : AnalyzerBase
if (string.IsNullOrWhiteSpace(option.Name) && option.ShortName is null) if (string.IsNullOrWhiteSpace(option.Name) && option.ShortName is null)
{ {
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation())); context.ReportDiagnostic(
CreateDiagnostic(propertyDeclaration.Identifier.GetLocation())
);
} }
} }

View File

@@ -14,7 +14,9 @@ public class OptionMustHaveUniqueNameAnalyzer : AnalyzerBase
public OptionMustHaveUniqueNameAnalyzer() public OptionMustHaveUniqueNameAnalyzer()
: base( : base(
"Options must have unique names", "Options must have unique names",
"This option's name must be unique within the command (comparison IS NOT case sensitive).") "This option's name must be unique within the command (comparison IS NOT case sensitive). " +
"Specified name: `{0}`. " +
"Property bound to another option with the same name: `{1}`.")
{ {
} }
@@ -51,7 +53,13 @@ public class OptionMustHaveUniqueNameAnalyzer : AnalyzerBase
if (string.Equals(option.Name, otherOption.Name, StringComparison.OrdinalIgnoreCase)) if (string.Equals(option.Name, otherOption.Name, StringComparison.OrdinalIgnoreCase))
{ {
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation())); context.ReportDiagnostic(
CreateDiagnostic(
propertyDeclaration.Identifier.GetLocation(),
option.Name,
otherProperty.Name
)
);
} }
} }
} }

View File

@@ -13,7 +13,9 @@ public class OptionMustHaveUniqueShortNameAnalyzer : AnalyzerBase
public OptionMustHaveUniqueShortNameAnalyzer() public OptionMustHaveUniqueShortNameAnalyzer()
: base( : base(
"Options must have unique short names", "Options must have unique short names",
"This option's short name must be unique within the command (comparison IS case sensitive).") "This option's short name must be unique within the command (comparison IS case sensitive). " +
"Specified short name: `{0}` " +
"Property bound to another option with the same short name: `{1}`.")
{ {
} }
@@ -50,7 +52,13 @@ public class OptionMustHaveUniqueShortNameAnalyzer : AnalyzerBase
if (option.ShortName == otherOption.ShortName) if (option.ShortName == otherOption.ShortName)
{ {
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation())); context.ReportDiagnostic(
CreateDiagnostic(
propertyDeclaration.Identifier.GetLocation(),
option.ShortName,
otherProperty.Name
)
);
} }
} }
} }

View File

@@ -13,7 +13,7 @@ public class OptionMustHaveValidConverterAnalyzer : AnalyzerBase
public OptionMustHaveValidConverterAnalyzer() public OptionMustHaveValidConverterAnalyzer()
: base( : base(
$"Option converters must derive from `{SymbolNames.CliFxBindingConverterClass}`", $"Option converters must derive from `{SymbolNames.CliFxBindingConverterClass}`",
$"Converter specified for this option must derive from `{SymbolNames.CliFxBindingConverterClass}`.") $"Converter specified for this option must derive from a compatible `{SymbolNames.CliFxBindingConverterClass}`.")
{ {
} }
@@ -29,15 +29,28 @@ public class OptionMustHaveValidConverterAnalyzer : AnalyzerBase
if (option.ConverterType is null) if (option.ConverterType is null)
return; return;
// We check against an internal interface because checking against a generic class is a pain var converterValueType = option
var converterImplementsInterface = option
.ConverterType .ConverterType
.AllInterfaces .GetBaseTypes()
.Any(s => s.DisplayNameMatches(SymbolNames.CliFxBindingConverterInterface)); .FirstOrDefault(t => t.ConstructedFrom.DisplayNameMatches(SymbolNames.CliFxBindingConverterClass))?
.TypeArguments
.FirstOrDefault();
if (!converterImplementsInterface) // Value returned by the converter must be assignable to the property type
var isCompatible =
converterValueType is not null && (option.IsScalar()
// Scalar
? context.Compilation.IsAssignable(converterValueType, property.Type)
// Non-scalar (assume we can handle all IEnumerable types for simplicity)
: property.Type.TryGetEnumerableUnderlyingType() is { } enumerableUnderlyingType &&
context.Compilation.IsAssignable(converterValueType, enumerableUnderlyingType)
);
if (!isCompatible)
{ {
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation())); context.ReportDiagnostic(
CreateDiagnostic(propertyDeclaration.Identifier.GetLocation())
);
} }
} }

View File

@@ -12,7 +12,8 @@ public class OptionMustHaveValidNameAnalyzer : AnalyzerBase
public OptionMustHaveValidNameAnalyzer() public OptionMustHaveValidNameAnalyzer()
: base( : base(
"Options must have valid names", "Options must have valid names",
"This option's name must be at least 2 characters long and must start with a letter.") "This option's name must be at least 2 characters long and must start with a letter. " +
"Specified name: `{0}`.")
{ {
} }
@@ -30,7 +31,12 @@ public class OptionMustHaveValidNameAnalyzer : AnalyzerBase
if (option.Name.Length < 2 || !char.IsLetter(option.Name[0])) if (option.Name.Length < 2 || !char.IsLetter(option.Name[0]))
{ {
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation())); context.ReportDiagnostic(
CreateDiagnostic(
propertyDeclaration.Identifier.GetLocation(),
option.Name
)
);
} }
} }

View File

@@ -12,7 +12,8 @@ public class OptionMustHaveValidShortNameAnalyzer : AnalyzerBase
public OptionMustHaveValidShortNameAnalyzer() public OptionMustHaveValidShortNameAnalyzer()
: base( : base(
"Option short names must be letter characters", "Option short names must be letter characters",
"This option's short name must be a single letter character.") "This option's short name must be a single letter character. " +
"Specified short name: `{0}`.")
{ {
} }
@@ -30,7 +31,12 @@ public class OptionMustHaveValidShortNameAnalyzer : AnalyzerBase
if (!char.IsLetter(option.ShortName.Value)) if (!char.IsLetter(option.ShortName.Value))
{ {
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation())); context.ReportDiagnostic(
CreateDiagnostic(
propertyDeclaration.Identifier.GetLocation(),
option.ShortName
)
);
} }
} }

View File

@@ -13,7 +13,7 @@ public class OptionMustHaveValidValidatorsAnalyzer : AnalyzerBase
public OptionMustHaveValidValidatorsAnalyzer() public OptionMustHaveValidValidatorsAnalyzer()
: base( : base(
$"Option validators must derive from `{SymbolNames.CliFxBindingValidatorClass}`", $"Option validators must derive from `{SymbolNames.CliFxBindingValidatorClass}`",
$"All validators specified for this option must derive from `{SymbolNames.CliFxBindingValidatorClass}`.") $"Each validator specified for this option must derive from a compatible `{SymbolNames.CliFxBindingValidatorClass}`.")
{ {
} }
@@ -28,14 +28,22 @@ public class OptionMustHaveValidValidatorsAnalyzer : AnalyzerBase
foreach (var validatorType in option.ValidatorTypes) foreach (var validatorType in option.ValidatorTypes)
{ {
// We check against an internal interface because checking against a generic class is a pain var validatorValueType = validatorType
var validatorImplementsInterface = validatorType .GetBaseTypes()
.AllInterfaces .FirstOrDefault(t => t.ConstructedFrom.DisplayNameMatches(SymbolNames.CliFxBindingValidatorClass))?
.Any(s => s.DisplayNameMatches(SymbolNames.CliFxBindingValidatorInterface)); .TypeArguments
.FirstOrDefault();
if (!validatorImplementsInterface) // Value passed to the validator must be assignable from the property type
var isCompatible =
validatorValueType is not null &&
context.Compilation.IsAssignable(property.Type, validatorValueType);
if (!isCompatible)
{ {
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation())); context.ReportDiagnostic(
CreateDiagnostic(propertyDeclaration.Identifier.GetLocation())
);
// No need to report multiple identical diagnostics on the same node // No need to report multiple identical diagnostics on the same node
break; break;

View File

@@ -34,11 +34,13 @@ public class ParameterMustBeInsideCommandAnalyzer : AnalyzerBase
var isInsideCommand = property var isInsideCommand = property
.ContainingType .ContainingType
.AllInterfaces .AllInterfaces
.Any(s => s.DisplayNameMatches(SymbolNames.CliFxCommandInterface)); .Any(i => i.DisplayNameMatches(SymbolNames.CliFxCommandInterface));
if (!isInsideCommand) if (!isInsideCommand)
{ {
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation())); context.ReportDiagnostic(
CreateDiagnostic(propertyDeclaration.Identifier.GetLocation())
);
} }
} }

View File

@@ -0,0 +1,66 @@
using System.Linq;
using CliFx.Analyzers.ObjectModel;
using CliFx.Analyzers.Utils.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ParameterMustBeLastIfNonRequiredAnalyzer : AnalyzerBase
{
public ParameterMustBeLastIfNonRequiredAnalyzer()
: base(
"Parameters marked as non-required must be the last in order",
"This parameter is non-required so it must be the last in order (its order must be highest within the command). " +
"Property bound to another non-required parameter: `{0}`.")
{
}
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,
IPropertySymbol property)
{
if (property.ContainingType is null)
return;
var parameter = CommandParameterSymbol.TryResolve(property);
if (parameter is null)
return;
if (parameter.IsRequired != false)
return;
var otherProperties = property
.ContainingType
.GetMembers()
.OfType<IPropertySymbol>()
.Where(m => !m.Equals(property, SymbolEqualityComparer.Default))
.ToArray();
foreach (var otherProperty in otherProperties)
{
var otherParameter = CommandParameterSymbol.TryResolve(otherProperty);
if (otherParameter is null)
continue;
if (otherParameter.Order > parameter.Order)
{
context.ReportDiagnostic(
CreateDiagnostic(
propertyDeclaration.Identifier.GetLocation(),
otherProperty.Name
)
);
}
}
}
public override void Initialize(AnalysisContext context)
{
base.Initialize(context);
context.HandlePropertyDeclaration(Analyze);
}
}

View File

@@ -12,18 +12,12 @@ public class ParameterMustBeLastIfNonScalarAnalyzer : AnalyzerBase
{ {
public ParameterMustBeLastIfNonScalarAnalyzer() public ParameterMustBeLastIfNonScalarAnalyzer()
: base( : base(
"Parameters of non-scalar types must be last in order", "Parameters of non-scalar types must be the last in order",
"This parameter has a non-scalar type so it must be last in order (its order must be highest within the command).") "This parameter has a non-scalar type so it must be the last in order (its order must be highest within the command). " +
"Property bound to another non-scalar parameter: `{0}`.")
{ {
} }
private static bool IsScalar(ITypeSymbol type) =>
type.DisplayNameMatches("string") ||
type.DisplayNameMatches("System.String") ||
!type.AllInterfaces
.Select(i => i.ConstructedFrom)
.Any(s => s.DisplayNameMatches("System.Collections.Generic.IEnumerable<T>"));
private void Analyze( private void Analyze(
SyntaxNodeAnalysisContext context, SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration, PropertyDeclarationSyntax propertyDeclaration,
@@ -32,13 +26,13 @@ public class ParameterMustBeLastIfNonScalarAnalyzer : AnalyzerBase
if (property.ContainingType is null) if (property.ContainingType is null)
return; return;
if (IsScalar(property.Type))
return;
var parameter = CommandParameterSymbol.TryResolve(property); var parameter = CommandParameterSymbol.TryResolve(property);
if (parameter is null) if (parameter is null)
return; return;
if (parameter.IsScalar())
return;
var otherProperties = property var otherProperties = property
.ContainingType .ContainingType
.GetMembers() .GetMembers()
@@ -54,7 +48,12 @@ public class ParameterMustBeLastIfNonScalarAnalyzer : AnalyzerBase
if (otherParameter.Order > parameter.Order) if (otherParameter.Order > parameter.Order)
{ {
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation())); context.ReportDiagnostic(
CreateDiagnostic(
propertyDeclaration.Identifier.GetLocation(),
otherProperty.Name
)
);
} }
} }
} }

View File

@@ -0,0 +1,66 @@
using System.Linq;
using CliFx.Analyzers.ObjectModel;
using CliFx.Analyzers.Utils.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace CliFx.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ParameterMustBeSingleIfNonRequiredAnalyzer : AnalyzerBase
{
public ParameterMustBeSingleIfNonRequiredAnalyzer()
: base(
"Parameters marked as non-required are limited to one per command",
"This parameter is non-required so it must be the only such parameter in the command. " +
"Property bound to another non-required parameter: `{0}`.")
{
}
private void Analyze(
SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration,
IPropertySymbol property)
{
if (property.ContainingType is null)
return;
var parameter = CommandParameterSymbol.TryResolve(property);
if (parameter is null)
return;
if (parameter.IsRequired != false)
return;
var otherProperties = property
.ContainingType
.GetMembers()
.OfType<IPropertySymbol>()
.Where(m => !m.Equals(property, SymbolEqualityComparer.Default))
.ToArray();
foreach (var otherProperty in otherProperties)
{
var otherParameter = CommandParameterSymbol.TryResolve(otherProperty);
if (otherParameter is null)
continue;
if (otherParameter.IsRequired == false)
{
context.ReportDiagnostic(
CreateDiagnostic(
propertyDeclaration.Identifier.GetLocation(),
otherProperty.Name
)
);
}
}
}
public override void Initialize(AnalysisContext context)
{
base.Initialize(context);
context.HandlePropertyDeclaration(Analyze);
}
}

View File

@@ -13,17 +13,11 @@ public class ParameterMustBeSingleIfNonScalarAnalyzer : AnalyzerBase
public ParameterMustBeSingleIfNonScalarAnalyzer() public ParameterMustBeSingleIfNonScalarAnalyzer()
: base( : base(
"Parameters of non-scalar types are limited to one per command", "Parameters of non-scalar types are limited to one per command",
"This parameter has a non-scalar type so it must be the only such parameter in the command.") "This parameter has a non-scalar type so it must be the only such parameter in the command. " +
"Property bound to another non-scalar parameter: `{0}`.")
{ {
} }
private static bool IsScalar(ITypeSymbol type) =>
type.DisplayNameMatches("string") ||
type.DisplayNameMatches("System.String") ||
!type.AllInterfaces
.Select(i => i.ConstructedFrom)
.Any(s => s.DisplayNameMatches("System.Collections.Generic.IEnumerable<T>"));
private void Analyze( private void Analyze(
SyntaxNodeAnalysisContext context, SyntaxNodeAnalysisContext context,
PropertyDeclarationSyntax propertyDeclaration, PropertyDeclarationSyntax propertyDeclaration,
@@ -32,10 +26,11 @@ public class ParameterMustBeSingleIfNonScalarAnalyzer : AnalyzerBase
if (property.ContainingType is null) if (property.ContainingType is null)
return; return;
if (!CommandParameterSymbol.IsParameterProperty(property)) var parameter = CommandParameterSymbol.TryResolve(property);
if (parameter is null)
return; return;
if (IsScalar(property.Type)) if (parameter.IsScalar())
return; return;
var otherProperties = property var otherProperties = property
@@ -47,12 +42,18 @@ public class ParameterMustBeSingleIfNonScalarAnalyzer : AnalyzerBase
foreach (var otherProperty in otherProperties) foreach (var otherProperty in otherProperties)
{ {
if (!CommandParameterSymbol.IsParameterProperty(otherProperty)) var otherParameter = CommandParameterSymbol.TryResolve(otherProperty);
if (otherParameter is null)
continue; continue;
if (!IsScalar(otherProperty.Type)) if (!otherParameter.IsScalar())
{ {
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation())); context.ReportDiagnostic(
CreateDiagnostic(
propertyDeclaration.Identifier.GetLocation(),
otherProperty.Name
)
);
} }
} }
} }

View File

@@ -14,7 +14,9 @@ public class ParameterMustHaveUniqueNameAnalyzer : AnalyzerBase
public ParameterMustHaveUniqueNameAnalyzer() public ParameterMustHaveUniqueNameAnalyzer()
: base( : base(
"Parameters must have unique names", "Parameters must have unique names",
"This parameter's name must be unique within the command (comparison IS NOT case sensitive).") "This parameter's name must be unique within the command (comparison IS NOT case sensitive). " +
"Specified name: `{0}`. " +
"Property bound to another parameter with the same name: `{1}`.")
{ {
} }
@@ -51,7 +53,13 @@ public class ParameterMustHaveUniqueNameAnalyzer : AnalyzerBase
if (string.Equals(parameter.Name, otherParameter.Name, StringComparison.OrdinalIgnoreCase)) if (string.Equals(parameter.Name, otherParameter.Name, StringComparison.OrdinalIgnoreCase))
{ {
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation())); context.ReportDiagnostic(
CreateDiagnostic(
propertyDeclaration.Identifier.GetLocation(),
parameter.Name,
otherProperty.Name
)
);
} }
} }
} }

View File

@@ -13,7 +13,9 @@ public class ParameterMustHaveUniqueOrderAnalyzer : AnalyzerBase
public ParameterMustHaveUniqueOrderAnalyzer() public ParameterMustHaveUniqueOrderAnalyzer()
: base( : base(
"Parameters must have unique order", "Parameters must have unique order",
"This parameter's order must be unique within the command.") "This parameter's order must be unique within the command. " +
"Specified order: {0}. " +
"Property bound to another parameter with the same order: `{1}`.")
{ {
} }
@@ -44,7 +46,13 @@ public class ParameterMustHaveUniqueOrderAnalyzer : AnalyzerBase
if (parameter.Order == otherParameter.Order) if (parameter.Order == otherParameter.Order)
{ {
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation())); context.ReportDiagnostic(
CreateDiagnostic(
propertyDeclaration.Identifier.GetLocation(),
parameter.Order,
otherProperty.Name
)
);
} }
} }
} }

View File

@@ -13,7 +13,7 @@ public class ParameterMustHaveValidConverterAnalyzer : AnalyzerBase
public ParameterMustHaveValidConverterAnalyzer() public ParameterMustHaveValidConverterAnalyzer()
: base( : base(
$"Parameter converters must derive from `{SymbolNames.CliFxBindingConverterClass}`", $"Parameter converters must derive from `{SymbolNames.CliFxBindingConverterClass}`",
$"Converter specified for this parameter must derive from `{SymbolNames.CliFxBindingConverterClass}`.") $"Converter specified for this parameter must derive from a compatible `{SymbolNames.CliFxBindingConverterClass}`.")
{ {
} }
@@ -29,15 +29,28 @@ public class ParameterMustHaveValidConverterAnalyzer : AnalyzerBase
if (parameter.ConverterType is null) if (parameter.ConverterType is null)
return; return;
// We check against an internal interface because checking against a generic class is a pain var converterValueType = parameter
var converterImplementsInterface = parameter
.ConverterType .ConverterType
.AllInterfaces .GetBaseTypes()
.Any(s => s.DisplayNameMatches(SymbolNames.CliFxBindingConverterInterface)); .FirstOrDefault(t => t.ConstructedFrom.DisplayNameMatches(SymbolNames.CliFxBindingConverterClass))?
.TypeArguments
.FirstOrDefault();
if (!converterImplementsInterface) // Value returned by the converter must be assignable to the property type
var isCompatible =
converterValueType is not null && (parameter.IsScalar()
// Scalar
? context.Compilation.IsAssignable(converterValueType, property.Type)
// Non-scalar (assume we can handle all IEnumerable types for simplicity)
: property.Type.TryGetEnumerableUnderlyingType() is { } enumerableUnderlyingType &&
context.Compilation.IsAssignable(converterValueType, enumerableUnderlyingType)
);
if (!isCompatible)
{ {
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation())); context.ReportDiagnostic(
CreateDiagnostic(propertyDeclaration.Identifier.GetLocation())
);
} }
} }

View File

@@ -13,7 +13,7 @@ public class ParameterMustHaveValidValidatorsAnalyzer : AnalyzerBase
public ParameterMustHaveValidValidatorsAnalyzer() public ParameterMustHaveValidValidatorsAnalyzer()
: base( : base(
$"Parameter validators must derive from `{SymbolNames.CliFxBindingValidatorClass}`", $"Parameter validators must derive from `{SymbolNames.CliFxBindingValidatorClass}`",
$"All validators specified for this parameter must derive from `{SymbolNames.CliFxBindingValidatorClass}`.") $"Each validator specified for this parameter must derive from a compatible `{SymbolNames.CliFxBindingValidatorClass}`.")
{ {
} }
@@ -28,14 +28,22 @@ public class ParameterMustHaveValidValidatorsAnalyzer : AnalyzerBase
foreach (var validatorType in parameter.ValidatorTypes) foreach (var validatorType in parameter.ValidatorTypes)
{ {
// We check against an internal interface because checking against a generic class is a pain var validatorValueType = validatorType
var validatorImplementsInterface = validatorType .GetBaseTypes()
.AllInterfaces .FirstOrDefault(t => t.ConstructedFrom.DisplayNameMatches(SymbolNames.CliFxBindingValidatorClass))?
.Any(s => s.DisplayNameMatches(SymbolNames.CliFxBindingValidatorInterface)); .TypeArguments
.FirstOrDefault();
if (!validatorImplementsInterface) // Value passed to the validator must be assignable from the property type
var isCompatible =
validatorValueType is not null &&
context.Compilation.IsAssignable(property.Type, validatorValueType);
if (!isCompatible)
{ {
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation())); context.ReportDiagnostic(
CreateDiagnostic(propertyDeclaration.Identifier.GetLocation())
);
// No need to report multiple identical diagnostics on the same node // No need to report multiple identical diagnostics on the same node
break; break;

View File

@@ -65,7 +65,9 @@ public class SystemConsoleShouldBeAvoidedAnalyzer : AnalyzerBase
if (isConsoleInterfaceAvailable) if (isConsoleInterfaceAvailable)
{ {
context.ReportDiagnostic(CreateDiagnostic(systemConsoleMemberAccess.GetLocation())); context.ReportDiagnostic(
CreateDiagnostic(systemConsoleMemberAccess.GetLocation())
);
} }
} }

View File

@@ -1,4 +1,6 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -16,6 +18,25 @@ internal static class RoslynExtensions
StringComparison.Ordinal StringComparison.Ordinal
); );
public static IEnumerable<INamedTypeSymbol> GetBaseTypes(this ITypeSymbol type)
{
var current = type.BaseType;
while (current is not null)
{
yield return current;
current = current.BaseType;
}
}
public static ITypeSymbol? TryGetEnumerableUnderlyingType(this ITypeSymbol type) => type
.AllInterfaces
.FirstOrDefault(i => i.ConstructedFrom.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T)?
.TypeArguments[0];
public static bool IsAssignable(this Compilation compilation, ITypeSymbol source, ITypeSymbol destination) =>
compilation.ClassifyConversion(source, destination).Exists;
public static void HandleClassDeclaration( public static void HandleClassDeclaration(
this AnalysisContext analysisContext, this AnalysisContext analysisContext,
Action<SyntaxNodeAnalysisContext, ClassDeclarationSyntax, ITypeSymbol> analyze) Action<SyntaxNodeAnalysisContext, ClassDeclarationSyntax, ITypeSymbol> analyze)

View File

@@ -8,9 +8,9 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.13.1" /> <PackageReference Include="BenchmarkDotNet" Version="0.13.1" />
<PackageReference Include="clipr" Version="1.6.1" /> <PackageReference Include="clipr" Version="1.6.1" />
<PackageReference Include="Cocona" Version="1.6.0" /> <PackageReference Include="Cocona" Version="2.0.3" />
<PackageReference Include="CommandLineParser" Version="2.8.0" /> <PackageReference Include="CommandLineParser" Version="2.9.1" />
<PackageReference Include="McMaster.Extensions.CommandLineUtils" Version="3.1.0" /> <PackageReference Include="McMaster.Extensions.CommandLineUtils" Version="4.0.1" />
<PackageReference Include="PowerArgs" Version="3.6.0" /> <PackageReference Include="PowerArgs" Version="3.6.0" />
<PackageReference Include="System.CommandLine" Version="2.0.0-beta1.20574.7" /> <PackageReference Include="System.CommandLine" Version="2.0.0-beta1.20574.7" />
</ItemGroup> </ItemGroup>

View File

@@ -12,7 +12,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\CliFx\CliFx.csproj" /> <ProjectReference Include="..\CliFx\CliFx.csproj" />
<ProjectReference Include="..\CliFx.Analyzers\CliFx.Analyzers.csproj" ReferenceOutputAssembly="false" OutputItemType="Analyzer" /> <ProjectReference Include="..\CliFx.Analyzers\CliFx.Analyzers.csproj" ReferenceOutputAssembly="false" OutputItemType="analyzer" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -7,7 +7,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\CliFx\CliFx.csproj" /> <ProjectReference Include="..\CliFx\CliFx.csproj" />
<ProjectReference Include="..\CliFx.Analyzers\CliFx.Analyzers.csproj" ReferenceOutputAssembly="false" OutputItemType="Analyzer" /> <ProjectReference Include="..\CliFx.Analyzers\CliFx.Analyzers.csproj" ReferenceOutputAssembly="false" OutputItemType="analyzer" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -1,4 +1,5 @@
using System.Reflection; using System;
using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace CliFx.Tests.Dummy; namespace CliFx.Tests.Dummy;
@@ -14,9 +15,17 @@ public static partial class Program
public static partial class Program public static partial class Program
{ {
public static async Task Main() => public static async Task Main()
{
// Make sure color codes are not produced because we rely on the output in tests
Environment.SetEnvironmentVariable(
"DOTNET_SYSTEM_CONSOLE_ALLOW_ANSI_COLOR_REDIRECTION",
"false"
);
await new CliApplicationBuilder() await new CliApplicationBuilder()
.AddCommandsFromThisAssembly() .AddCommandsFromThisAssembly()
.Build() .Build()
.RunAsync(); .RunAsync();
}
} }

View File

@@ -2,10 +2,6 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>net6.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
<CollectCoverage>true</CollectCoverage>
<CoverletOutputFormat>opencover</CoverletOutputFormat>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -14,14 +10,15 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Basic.Reference.Assemblies" Version="1.2.4" /> <PackageReference Include="Basic.Reference.Assemblies" Version="1.2.4" />
<PackageReference Include="CliWrap" Version="3.3.3" /> <PackageReference Include="CliWrap" Version="3.4.4" />
<PackageReference Include="FluentAssertions" Version="6.2.0" /> <PackageReference Include="FluentAssertions" Version="6.7.0" />
<PackageReference Include="GitHubActionsTestLogger" Version="1.2.0" /> <PackageReference Include="GitHubActionsTestLogger" Version="2.0.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.0.1" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.2.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.2.0" />
<PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" PrivateAssets="all" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.5" PrivateAssets="all" />
<PackageReference Include="coverlet.msbuild" Version="3.1.0" PrivateAssets="all" /> <PackageReference Include="coverlet.collector" Version="3.1.2" PrivateAssets="all" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -5,6 +5,7 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using CliFx.Infrastructure; using CliFx.Infrastructure;
using CliFx.Tests.Utils; using CliFx.Tests.Utils;
using CliFx.Tests.Utils.Extensions;
using CliWrap; using CliWrap;
using CliWrap.Buffered; using CliWrap.Buffered;
using FluentAssertions; using FluentAssertions;
@@ -30,7 +31,8 @@ public class ConsoleSpecs : SpecsBase
var command = "Hello world" | Cli.Wrap("dotnet") var command = "Hello world" | Cli.Wrap("dotnet")
.WithArguments(a => a .WithArguments(a => a
.Add(Dummy.Program.Location) .Add(Dummy.Program.Location)
.Add("console-test")); .Add("console-test")
);
// Act // Act
var result = await command.ExecuteBufferedAsync(); var result = await command.ExecuteBufferedAsync();
@@ -55,6 +57,8 @@ public class Command : ICommand
console.ResetColor(); console.ResetColor();
console.ForegroundColor = ConsoleColor.DarkMagenta; console.ForegroundColor = ConsoleColor.DarkMagenta;
console.BackgroundColor = ConsoleColor.DarkMagenta; console.BackgroundColor = ConsoleColor.DarkMagenta;
console.WindowWidth = 100;
console.WindowHeight = 25;
console.CursorLeft = 42; console.CursorLeft = 42;
console.CursorTop = 24; console.CursorTop = 24;
@@ -88,6 +92,8 @@ public class Command : ICommand
Console.BackgroundColor.Should().NotBe(ConsoleColor.DarkMagenta); Console.BackgroundColor.Should().NotBe(ConsoleColor.DarkMagenta);
// This fails because tests don't spawn a console window // This fails because tests don't spawn a console window
//Console.WindowWidth.Should().Be(100);
//Console.WindowHeight.Should().Be(25);
//Console.CursorLeft.Should().NotBe(42); //Console.CursorLeft.Should().NotBe(42);
//Console.CursorTop.Should().NotBe(24); //Console.CursorTop.Should().NotBe(24);
@@ -139,6 +145,53 @@ public class Command : ICommand
stdErr.Trim().Should().Be("Hello world"); stdErr.Trim().Should().Be("Hello world");
} }
[Fact]
public async Task Fake_console_can_read_key_presses()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
@"
[Command]
public class Command : ICommand
{
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(console.ReadKey().Key);
console.Output.WriteLine(console.ReadKey().Key);
console.Output.WriteLine(console.ReadKey().Key);
return default;
}
}
");
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.Build();
// Act
FakeConsole.EnqueueKey(new ConsoleKeyInfo('0', ConsoleKey.D0, false, false, false));
FakeConsole.EnqueueKey(new ConsoleKeyInfo('a', ConsoleKey.A, false, false, false));
FakeConsole.EnqueueKey(new ConsoleKeyInfo('\0', ConsoleKey.Backspace, false, false, false));
var exitCode = await application.RunAsync(
Array.Empty<string>(),
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
stdOut.Trim().Should().ConsistOfLines(
"D0",
"A",
"Backspace"
);
}
[Fact] [Fact]
public void Console_does_not_emit_preamble_when_used_with_encoding_that_has_it() public void Console_does_not_emit_preamble_when_used_with_encoding_that_has_it()
{ {

View File

@@ -103,7 +103,7 @@ public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public bool Foo { get; set; } public bool Foo { get; set; }
[CommandOption('b')] [CommandOption('b')]
public bool Bar { get; set; } public bool Bar { get; set; }
@@ -379,7 +379,7 @@ public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public int? Foo { get; set; } public int? Foo { get; set; }
[CommandOption('b')] [CommandOption('b')]
public int? Bar { get; set; } public int? Bar { get; set; }
@@ -427,7 +427,7 @@ public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public CustomEnum? Foo { get; set; } public CustomEnum? Foo { get; set; }
[CommandOption('b')] [CommandOption('b')]
public CustomEnum? Bar { get; set; } public CustomEnum? Bar { get; set; }
@@ -471,7 +471,7 @@ public class Command : ICommand
public class CustomType public class CustomType
{ {
public string Value { get; } public string Value { get; }
public CustomType(string value) => Value = value; public CustomType(string value) => Value = value;
} }
@@ -480,7 +480,7 @@ public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public CustomType Foo { get; set; } public CustomType Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine(Foo.Value); console.Output.WriteLine(Foo.Value);
@@ -516,9 +516,9 @@ public class Command : ICommand
public class CustomTypeA public class CustomTypeA
{ {
public string Value { get; } public string Value { get; }
private CustomTypeA(string value) => Value = value; private CustomTypeA(string value) => Value = value;
public static CustomTypeA Parse(string value) => public static CustomTypeA Parse(string value) =>
new CustomTypeA(value); new CustomTypeA(value);
} }
@@ -526,9 +526,9 @@ public class CustomTypeA
public class CustomTypeB public class CustomTypeB
{ {
public string Value { get; } public string Value { get; }
private CustomTypeB(string value) => Value = value; private CustomTypeB(string value) => Value = value;
public static CustomTypeB Parse(string value, IFormatProvider formatProvider) => public static CustomTypeB Parse(string value, IFormatProvider formatProvider) =>
new CustomTypeB(value); new CustomTypeB(value);
} }
@@ -538,10 +538,10 @@ public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public CustomTypeA Foo { get; set; } public CustomTypeA Foo { get; set; }
[CommandOption('b')] [CommandOption('b')]
public CustomTypeB Bar { get; set; } public CustomTypeB Bar { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine(""Foo = "" + Foo.Value); console.Output.WriteLine(""Foo = "" + Foo.Value);
@@ -590,7 +590,7 @@ public class Command : ICommand
{ {
[CommandOption('f', Converter = typeof(CustomConverter))] [CommandOption('f', Converter = typeof(CustomConverter))]
public int Foo { get; set; } public int Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine(Foo); console.Output.WriteLine(Foo);
@@ -628,7 +628,7 @@ public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string[] Foo { get; set; } public string[] Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
foreach (var i in Foo) foreach (var i in Foo)
@@ -672,7 +672,7 @@ public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public IReadOnlyList<string> Foo { get; set; } public IReadOnlyList<string> Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
foreach (var i in Foo) foreach (var i in Foo)
@@ -716,7 +716,7 @@ public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public List<string> Foo { get; set; } public List<string> Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
foreach (var i in Foo) foreach (var i in Foo)
@@ -760,7 +760,7 @@ public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public int[] Foo { get; set; } public int[] Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
foreach (var i in Foo) foreach (var i in Foo)
@@ -804,7 +804,7 @@ public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public int Foo { get; set; } public int Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
"); ");
@@ -840,7 +840,7 @@ public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public CustomType Foo { get; set; } public CustomType Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
"); ");
@@ -872,7 +872,7 @@ public class Command : ICommand
public class CustomType : IEnumerable<object> public class CustomType : IEnumerable<object>
{ {
public IEnumerator<object> GetEnumerator() => Enumerable.Empty<object>().GetEnumerator(); public IEnumerator<object> GetEnumerator() => Enumerable.Empty<object>().GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
} }
@@ -881,7 +881,7 @@ public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public CustomType Foo { get; set; } public CustomType Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
"); ");
@@ -925,7 +925,7 @@ public class Command : ICommand
{ {
[CommandOption('f', Validators = new[] {typeof(ValidatorA), typeof(ValidatorB)})] [CommandOption('f', Validators = new[] {typeof(ValidatorA), typeof(ValidatorB)})]
public int Foo { get; set; } public int Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
"); ");
@@ -957,9 +957,9 @@ public class Command : ICommand
public class CustomType public class CustomType
{ {
public string Value { get; } public string Value { get; }
private CustomType(string value) => Value = value; private CustomType(string value) => Value = value;
public static CustomType Parse(string value) => throw new Exception(""Hello world""); public static CustomType Parse(string value) => throw new Exception(""Hello world"");
} }
@@ -968,7 +968,7 @@ public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public CustomType Foo { get; set; } public CustomType Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
"); ");

View File

@@ -28,7 +28,8 @@ public class DirectivesSpecs : SpecsBase
var command = Cli.Wrap("dotnet") var command = Cli.Wrap("dotnet")
.WithArguments(a => a .WithArguments(a => a
.Add(Dummy.Program.Location) .Add(Dummy.Program.Location)
.Add("[debug]")) | stdOutBuffer; .Add("[debug]")
) | stdOutBuffer;
// Act // Act
try try
@@ -57,7 +58,7 @@ public class DirectivesSpecs : SpecsBase
} }
catch (OperationCanceledException) catch (OperationCanceledException)
{ {
// It's expected to fail // This is expected
} }
var stdOut = stdOutBuffer.ToString(); var stdOut = stdOutBuffer.ToString();

View File

@@ -31,7 +31,7 @@ public class Command : ICommand
{ {
[CommandOption(""foo"", IsRequired = true, EnvironmentVariable = ""ENV_FOO"")] [CommandOption(""foo"", IsRequired = true, EnvironmentVariable = ""ENV_FOO"")]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine(Foo); console.Output.WriteLine(Foo);
@@ -73,7 +73,7 @@ public class Command : ICommand
{ {
[CommandOption(""foo"", EnvironmentVariable = ""ENV_FOO"")] [CommandOption(""foo"", EnvironmentVariable = ""ENV_FOO"")]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine(Foo); console.Output.WriteLine(Foo);
@@ -115,12 +115,12 @@ public class Command : ICommand
{ {
[CommandOption(""foo"", EnvironmentVariable = ""ENV_FOO"")] [CommandOption(""foo"", EnvironmentVariable = ""ENV_FOO"")]
public IReadOnlyList<string> Foo { get; set; } public IReadOnlyList<string> Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
foreach (var i in Foo) foreach (var i in Foo)
console.Output.WriteLine(i); console.Output.WriteLine(i);
return default; return default;
} }
} }
@@ -162,7 +162,7 @@ public class Command : ICommand
{ {
[CommandOption(""foo"", EnvironmentVariable = ""ENV_FOO"")] [CommandOption(""foo"", EnvironmentVariable = ""ENV_FOO"")]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine(Foo); console.Output.WriteLine(Foo);
@@ -204,7 +204,7 @@ public class Command : ICommand
{ {
[CommandOption(""foo"", EnvironmentVariable = ""ENV_FOO"")] [CommandOption(""foo"", EnvironmentVariable = ""ENV_FOO"")]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine(Foo); console.Output.WriteLine(Foo);
@@ -246,9 +246,11 @@ public class Command : ICommand
var command = Cli.Wrap("dotnet") var command = Cli.Wrap("dotnet")
.WithArguments(a => a .WithArguments(a => a
.Add(Dummy.Program.Location) .Add(Dummy.Program.Location)
.Add("env-test")) .Add("env-test")
)
.WithEnvironmentVariables(e => e .WithEnvironmentVariables(e => e
.Set("ENV_TARGET", "Mars")); .Set("ENV_TARGET", "Mars")
);
// Act // Act
var result = await command.ExecuteBufferedAsync(); var result = await command.ExecuteBufferedAsync();

View File

@@ -339,13 +339,13 @@ public class Command : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public string Foo { get; set; }
[CommandParameter(1)] [CommandParameter(1)]
public string Bar { get; set; } public string Bar { get; set; }
[CommandParameter(2)] [CommandParameter(2)]
public IReadOnlyList<string> Baz { get; set; } public IReadOnlyList<string> Baz { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
"); ");
@@ -396,7 +396,7 @@ public class Command : CommandBase
[CommandParameter(1)] [CommandParameter(1)]
public string Bar { get; set; } public string Bar { get; set; }
public override ValueTask ExecuteAsync(IConsole console) => default; public override ValueTask ExecuteAsync(IConsole console) => default;
} }
"); ");
@@ -434,13 +434,13 @@ public class Command : ICommand
{ {
[CommandOption(""foo"", IsRequired = true)] [CommandOption(""foo"", IsRequired = true)]
public string Foo { get; set; } public string Foo { get; set; }
[CommandOption(""bar"")] [CommandOption(""bar"")]
public string Bar { get; set; } public string Bar { get; set; }
[CommandOption(""baz"", IsRequired = true)] [CommandOption(""baz"", IsRequired = true)]
public IReadOnlyList<string> Baz { get; set; } public IReadOnlyList<string> Baz { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
"); ");
@@ -478,10 +478,10 @@ public class Command : ICommand
{ {
[CommandParameter(0, Name = ""foo"", Description = ""Description of foo."")] [CommandParameter(0, Name = ""foo"", Description = ""Description of foo."")]
public string Foo { get; set; } public string Foo { get; set; }
[CommandOption(""bar"", Description = ""Description of bar."")] [CommandOption(""bar"", Description = ""Description of bar."")]
public string Bar { get; set; } public string Bar { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
"); ");
@@ -597,10 +597,10 @@ public class Command : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public CustomEnum Foo { get; set; } public CustomEnum Foo { get; set; }
[CommandOption(""bar"")] [CommandOption(""bar"")]
public CustomEnum Bar { get; set; } public CustomEnum Bar { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
"); ");
@@ -732,10 +732,10 @@ public class Command : ICommand
{ {
[CommandOption(""foo"", EnvironmentVariable = ""ENV_FOO"")] [CommandOption(""foo"", EnvironmentVariable = ""ENV_FOO"")]
public CustomEnum Foo { get; set; } public CustomEnum Foo { get; set; }
[CommandOption(""bar"", EnvironmentVariable = ""ENV_BAR"")] [CommandOption(""bar"", EnvironmentVariable = ""ENV_BAR"")]
public CustomEnum Bar { get; set; } public CustomEnum Bar { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
"); ");
@@ -794,10 +794,10 @@ public class Command : ICommand
[CommandOption(""lol"")] [CommandOption(""lol"")]
public CustomEnum Lol { get; set; } = CustomEnum.Two; public CustomEnum Lol { get; set; } = CustomEnum.Two;
[CommandOption(""hmm"", IsRequired = true)] [CommandOption(""hmm"", IsRequired = true)]
public string Hmm { get; set; } = ""not printed""; public string Hmm { get; set; } = ""not printed"";
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
"); ");

View File

@@ -28,7 +28,7 @@ public class Command : ICommand
{ {
[CommandOption(""foo"")] [CommandOption(""foo"")]
public bool Foo { get; set; } public bool Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine(Foo); console.Output.WriteLine(Foo);
@@ -66,7 +66,7 @@ public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public bool Foo { get; set; } public bool Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine(Foo); console.Output.WriteLine(Foo);
@@ -104,10 +104,10 @@ public class Command : ICommand
{ {
[CommandOption(""foo"")] [CommandOption(""foo"")]
public string Foo { get; set; } public string Foo { get; set; }
[CommandOption(""bar"")] [CommandOption(""bar"")]
public string Bar { get; set; } public string Bar { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine(""Foo = "" + Foo); console.Output.WriteLine(""Foo = "" + Foo);
@@ -150,10 +150,10 @@ public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string Foo { get; set; } public string Foo { get; set; }
[CommandOption('b')] [CommandOption('b')]
public string Bar { get; set; } public string Bar { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine(""Foo = "" + Foo); console.Output.WriteLine(""Foo = "" + Foo);
@@ -196,10 +196,10 @@ public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string Foo { get; set; } public string Foo { get; set; }
[CommandOption('b')] [CommandOption('b')]
public string Bar { get; set; } public string Bar { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine(""Foo = "" + Foo); console.Output.WriteLine(""Foo = "" + Foo);
@@ -242,7 +242,7 @@ public class Command : ICommand
{ {
[CommandOption(""Foo"")] [CommandOption(""Foo"")]
public IReadOnlyList<string> Foo { get; set; } public IReadOnlyList<string> Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
foreach (var i in Foo) foreach (var i in Foo)
@@ -286,7 +286,7 @@ public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public IReadOnlyList<string> Foo { get; set; } public IReadOnlyList<string> Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
foreach (var i in Foo) foreach (var i in Foo)
@@ -330,7 +330,7 @@ public class Command : ICommand
{ {
[CommandOption(""foo"")] [CommandOption(""foo"")]
public IReadOnlyList<string> Foo { get; set; } public IReadOnlyList<string> Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
foreach (var i in Foo) foreach (var i in Foo)
@@ -374,7 +374,7 @@ public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public IReadOnlyList<string> Foo { get; set; } public IReadOnlyList<string> Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
foreach (var i in Foo) foreach (var i in Foo)
@@ -418,7 +418,7 @@ public class Command : ICommand
{ {
[CommandOption(""foo"", 'f')] [CommandOption(""foo"", 'f')]
public IReadOnlyList<string> Foo { get; set; } public IReadOnlyList<string> Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
foreach (var i in Foo) foreach (var i in Foo)
@@ -462,10 +462,10 @@ public class Command : ICommand
{ {
[CommandOption(""foo"")] [CommandOption(""foo"")]
public string Foo { get; set; } public string Foo { get; set; }
[CommandOption(""bar"")] [CommandOption(""bar"")]
public string Bar { get; set; } = ""hello""; public string Bar { get; set; } = ""hello"";
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine(""Foo = "" + Foo); console.Output.WriteLine(""Foo = "" + Foo);
@@ -496,6 +496,83 @@ public class Command : ICommand
); );
} }
[Fact]
public async Task Option_binding_supports_multiple_inheritance_through_default_interface_members()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
@"
public static class SharedContext
{
public static int Foo { get; set; }
public static bool Bar { get; set; }
}
public interface IHasFoo : ICommand
{
[CommandOption(""foo"")]
public int Foo
{
get => SharedContext.Foo;
set => SharedContext.Foo = value;
}
}
public interface IHasBar : ICommand
{
[CommandOption(""bar"")]
public bool Bar
{
get => SharedContext.Bar;
set => SharedContext.Bar = value;
}
}
public interface IHasBaz : ICommand
{
public string Baz { get; set; }
}
[Command]
public class Command : IHasFoo, IHasBar, IHasBaz
{
[CommandOption(""baz"")]
public string Baz { get; set; }
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(""Foo = "" + SharedContext.Foo);
console.Output.WriteLine(""Bar = "" + SharedContext.Bar);
console.Output.WriteLine(""Baz = "" + Baz);
return default;
}
}
");
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.Build();
// Act
var exitCode = await application.RunAsync(
new[] { "--foo", "42", "--bar", "--baz", "xyz" }
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
stdOut.Should().ConsistOfLines(
"Foo = 42",
"Bar = True",
"Baz = xyz"
);
}
[Fact] [Fact]
public async Task Option_binding_does_not_consider_a_negative_number_as_an_option_name_or_short_name() public async Task Option_binding_does_not_consider_a_negative_number_as_an_option_name_or_short_name()
{ {
@@ -508,7 +585,7 @@ public class Command : ICommand
{ {
[CommandOption(""foo"")] [CommandOption(""foo"")]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine(Foo); console.Output.WriteLine(Foo);
@@ -547,7 +624,7 @@ public class Command : ICommand
{ {
[CommandOption(""foo"", IsRequired = true)] [CommandOption(""foo"", IsRequired = true)]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"); }");
@@ -581,7 +658,7 @@ public class Command : ICommand
{ {
[CommandOption(""foo"", IsRequired = true)] [CommandOption(""foo"", IsRequired = true)]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"); }");
@@ -615,7 +692,7 @@ public class Command : ICommand
{ {
[CommandOption(""foo"", IsRequired = true)] [CommandOption(""foo"", IsRequired = true)]
public IReadOnlyList<string> Foo { get; set; } public IReadOnlyList<string> Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"); }");
@@ -649,7 +726,7 @@ public class Command : ICommand
{ {
[CommandOption(""foo"")] [CommandOption(""foo"")]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"); }");
@@ -683,7 +760,7 @@ public class Command : ICommand
{ {
[CommandOption(""foo"")] [CommandOption(""foo"")]
public string Foo { get; set; } public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"); }");

View File

@@ -27,7 +27,7 @@ public class Command : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public string Foo { get; set; }
[CommandParameter(1)] [CommandParameter(1)]
public string Bar { get; set; } public string Bar { get; set; }
@@ -35,7 +35,7 @@ public class Command : ICommand
{ {
console.Output.WriteLine(""Foo = "" + Foo); console.Output.WriteLine(""Foo = "" + Foo);
console.Output.WriteLine(""Bar = "" + Bar); console.Output.WriteLine(""Bar = "" + Bar);
return default; return default;
} }
}"); }");
@@ -73,13 +73,13 @@ public class Command : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public string Foo { get; set; }
[CommandParameter(1)] [CommandParameter(1)]
public string Bar { get; set; } public string Bar { get; set; }
[CommandParameter(2)] [CommandParameter(2)]
public IReadOnlyList<string> Baz { get; set; } public IReadOnlyList<string> Baz { get; set; }
[CommandOption(""boo"")] [CommandOption(""boo"")]
public string Boo { get; set; } public string Boo { get; set; }
@@ -87,10 +87,10 @@ public class Command : ICommand
{ {
console.Output.WriteLine(""Foo = "" + Foo); console.Output.WriteLine(""Foo = "" + Foo);
console.Output.WriteLine(""Bar = "" + Bar); console.Output.WriteLine(""Bar = "" + Bar);
foreach (var i in Baz) foreach (var i in Baz)
console.Output.WriteLine(""Baz = "" + i); console.Output.WriteLine(""Baz = "" + i);
return default; return default;
} }
}"); }");
@@ -120,7 +120,7 @@ public class Command : ICommand
} }
[Fact] [Fact]
public async Task Parameter_binding_fails_if_one_of_the_parameters_has_not_been_provided() public async Task Parameter_is_not_bound_if_there_are_no_arguments_matching_its_order()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -131,7 +131,53 @@ public class Command : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public string Foo { get; set; }
[CommandParameter(1, IsRequired = false)]
public string Bar { get; set; } = ""xyz"";
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(""Foo = "" + Foo);
console.Output.WriteLine(""Bar = "" + Bar);
return default;
}
}");
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.Build();
// Act
var exitCode = await application.RunAsync(
new[] {"abc"},
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
stdOut.Should().ConsistOfLines(
"Foo = abc",
"Bar = xyz"
);
}
[Fact]
public async Task Parameter_binding_fails_if_a_required_parameter_has_not_been_provided()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
@"
[Command]
public class Command : ICommand
{
[CommandParameter(0)]
public string Foo { get; set; }
[CommandParameter(1)] [CommandParameter(1)]
public string Bar { get; set; } public string Bar { get; set; }
@@ -153,7 +199,7 @@ public class Command : ICommand
// Assert // Assert
exitCode.Should().NotBe(0); exitCode.Should().NotBe(0);
stdErr.Should().Contain("Missing parameter(s)"); stdErr.Should().Contain("Missing required parameter(s)");
} }
[Fact] [Fact]
@@ -168,10 +214,10 @@ public class Command : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public string Foo { get; set; }
[CommandParameter(1)] [CommandParameter(1)]
public IReadOnlyList<string> Bar { get; set; } public IReadOnlyList<string> Bar { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
}"); }");
@@ -190,7 +236,7 @@ public class Command : ICommand
// Assert // Assert
exitCode.Should().NotBe(0); exitCode.Should().NotBe(0);
stdErr.Should().Contain("Missing parameter(s)"); stdErr.Should().Contain("Missing required parameter(s)");
} }
[Fact] [Fact]
@@ -205,7 +251,7 @@ public class Command : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public string Foo { get; set; }
[CommandParameter(1)] [CommandParameter(1)]
public string Bar { get; set; } public string Bar { get; set; }

View File

@@ -4,6 +4,7 @@ using System.Threading.Tasks;
using CliFx.Infrastructure; using CliFx.Infrastructure;
using CliFx.Tests.Utils; using CliFx.Tests.Utils;
using FluentAssertions; using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using Xunit; using Xunit;
using Xunit.Abstractions; using Xunit.Abstractions;
@@ -87,7 +88,7 @@ public class Command : ICommand
} }
[Fact] [Fact]
public async Task Delegate_type_activator_can_initialize_a_type_using_a_custom_function() public async Task Custom_type_activator_can_initialize_a_type_using_a_given_function()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -110,7 +111,7 @@ public class Command : ICommand
var application = new CliApplicationBuilder() var application = new CliApplicationBuilder()
.AddCommand(commandType) .AddCommand(commandType)
.UseConsole(FakeConsole) .UseConsole(FakeConsole)
.UseTypeActivator(type => Activator.CreateInstance(type, "hello world")!) .UseTypeActivator(type => Activator.CreateInstance(type, "Hello world")!)
.Build(); .Build();
// Act // Act
@@ -123,11 +124,55 @@ public class Command : ICommand
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
stdOut.Trim().Should().Be("hello world"); stdOut.Trim().Should().Be("Hello world");
} }
[Fact] [Fact]
public async Task Delegate_type_activator_fails_if_the_underlying_function_returns_null() public async Task Custom_type_activator_can_initialize_a_type_using_a_service_provider()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
@"
[Command]
public class Command : ICommand
{
private readonly string _foo;
public Command(string foo) => _foo = foo;
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(_foo);
return default;
}
}");
var serviceProvider = new ServiceCollection()
.AddSingleton(commandType, Activator.CreateInstance(commandType, "Hello world")!)
.BuildServiceProvider();
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.UseTypeActivator(serviceProvider)
.Build();
// Act
var exitCode = await application.RunAsync(
Array.Empty<string>(),
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
stdOut.Trim().Should().Be("Hello world");
}
[Fact]
public async Task Custom_type_activator_fails_if_the_underlying_function_returns_null()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(

View File

@@ -29,7 +29,7 @@ public sealed class CommandOptionAttribute : Attribute
public char? ShortName { get; } public char? ShortName { get; }
/// <summary> /// <summary>
/// Whether this option is required. /// Whether this option is required (default: <c>false</c>).
/// If an option is required, the user will get an error if they don't set it. /// If an option is required, the user will get an error if they don't set it.
/// </summary> /// </summary>
public bool IsRequired { get; set; } public bool IsRequired { get; set; }

View File

@@ -11,18 +11,26 @@ public sealed class CommandParameterAttribute : Attribute
{ {
/// <summary> /// <summary>
/// Parameter order. /// Parameter order.
/// </summary>
/// <remarks>
/// Higher order means the parameter appears later, lower order means /// Higher order means the parameter appears later, lower order means
/// it appears earlier. /// it appears earlier.
/// /// </summary>
/// <remarks>
/// All parameters in a command must have unique order. /// All parameters in a command must have unique order.
///
/// Parameter whose type is a non-scalar (e.g. array), must always be the last in order. /// Parameter whose type is a non-scalar (e.g. array), must always be the last in order.
/// Only one non-scalar parameter is allowed in a command. /// Only one non-scalar parameter is allowed in a command.
/// </remarks> /// </remarks>
public int Order { get; } public int Order { get; }
/// <summary>
/// Whether this parameter is required (default: <c>true</c>).
/// If a parameter is required, the user will get an error if they don't set it.
/// </summary>
/// <remarks>
/// Parameter marked as non-required must always be the last in order.
/// Only one non-required parameter is allowed in a command.
/// </remarks>
public bool IsRequired { get; set; } = true;
/// <summary> /// <summary>
/// Parameter name. /// Parameter name.
/// This is shown to the user in the help text. /// This is shown to the user in the help text.

View File

@@ -112,7 +112,7 @@ public class CliApplication
// Activate command instance // Activate command instance
var commandInstance = commandSchema == FallbackDefaultCommand.Schema var commandInstance = commandSchema == FallbackDefaultCommand.Schema
? new FallbackDefaultCommand() // bypass activator ? new FallbackDefaultCommand() // bypass activator
: (ICommand) _typeActivator.CreateInstance(commandSchema.Type); : (ICommand)_typeActivator.CreateInstance(commandSchema.Type);
// Assemble help context // Assemble help context
var helpContext = new HelpContext( var helpContext = new HelpContext(
@@ -176,7 +176,7 @@ public class CliApplication
{ {
try try
{ {
// Console colors may have already been overriden by the parent process, // 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. // so we need to reset it to make sure that everything we write looks properly.
_console.ResetColor(); _console.ResetColor();

View File

@@ -6,6 +6,7 @@ using System.Reflection;
using CliFx.Attributes; using CliFx.Attributes;
using CliFx.Infrastructure; using CliFx.Infrastructure;
using CliFx.Schema; using CliFx.Schema;
using CliFx.Utils;
using CliFx.Utils.Extensions; using CliFx.Utils.Extensions;
namespace CliFx; namespace CliFx;
@@ -21,7 +22,7 @@ public partial class CliApplicationBuilder
private bool _isPreviewModeAllowed = true; private bool _isPreviewModeAllowed = true;
private string? _title; private string? _title;
private string? _executableName; private string? _executableName;
private string? _versionText; private string? _version;
private string? _description; private string? _description;
private IConsole? _console; private IConsole? _console;
private ITypeActivator? _typeActivator; private ITypeActivator? _typeActivator;
@@ -144,7 +145,7 @@ public partial class CliApplicationBuilder
/// </remarks> /// </remarks>
public CliApplicationBuilder SetVersion(string version) public CliApplicationBuilder SetVersion(string version)
{ {
_versionText = version; _version = version;
return this; return this;
} }
@@ -181,6 +182,12 @@ public partial class CliApplicationBuilder
public CliApplicationBuilder UseTypeActivator(Func<Type, object> typeActivator) => public CliApplicationBuilder UseTypeActivator(Func<Type, object> typeActivator) =>
UseTypeActivator(new DelegateTypeActivator(typeActivator)); UseTypeActivator(new DelegateTypeActivator(typeActivator));
/// <summary>
/// Configures the application to use the specified service provider for activating types.
/// </summary>
public CliApplicationBuilder UseTypeActivator(IServiceProvider serviceProvider) =>
UseTypeActivator(serviceProvider.GetService);
/// <summary> /// <summary>
/// Creates a configured instance of <see cref="CliApplication"/>. /// Creates a configured instance of <see cref="CliApplication"/>.
/// </summary> /// </summary>
@@ -189,7 +196,7 @@ public partial class CliApplicationBuilder
var metadata = new ApplicationMetadata( var metadata = new ApplicationMetadata(
_title ?? GetDefaultTitle(), _title ?? GetDefaultTitle(),
_executableName ?? GetDefaultExecutableName(), _executableName ?? GetDefaultExecutableName(),
_versionText ?? GetDefaultVersionText(), _version ?? GetDefaultVersionText(),
_description _description
); );
@@ -210,14 +217,9 @@ public partial class CliApplicationBuilder
public partial class CliApplicationBuilder public partial class CliApplicationBuilder
{ {
private static readonly Lazy<Assembly?> EntryAssemblyLazy = new(Assembly.GetEntryAssembly);
// Entry assembly can be null, for example in tests
private static Assembly? EntryAssembly => EntryAssemblyLazy.Value;
private static string GetDefaultTitle() private static string GetDefaultTitle()
{ {
var entryAssemblyName = EntryAssembly?.GetName().Name; var entryAssemblyName = EnvironmentEx.EntryAssembly?.GetName().Name;
if (string.IsNullOrWhiteSpace(entryAssemblyName)) if (string.IsNullOrWhiteSpace(entryAssemblyName))
return "App"; return "App";
@@ -226,26 +228,39 @@ public partial class CliApplicationBuilder
private static string GetDefaultExecutableName() private static string GetDefaultExecutableName()
{ {
var entryAssemblyLocation = EntryAssembly?.Location; var entryAssemblyLocation = EnvironmentEx.EntryAssembly?.Location;
if (string.IsNullOrWhiteSpace(entryAssemblyLocation)) if (string.IsNullOrWhiteSpace(entryAssemblyLocation))
return "app"; return "app";
// The assembly can be an .exe or a .dll, depending on how it was packaged // 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 (isLaunchedViaAppHost)
return Path.GetFileNameWithoutExtension(entryAssemblyLocation);
// Otherwise, use the entry assembly as the executable name.
// Prefix it with `dotnet` if it's a DLL file.
var isDll = string.Equals( var isDll = string.Equals(
Path.GetExtension(entryAssemblyLocation), Path.GetExtension(entryAssemblyLocation),
".dll", ".dll",
StringComparison.OrdinalIgnoreCase StringComparison.OrdinalIgnoreCase
); );
var name = isDll return isDll
? "dotnet " + Path.GetFileName(entryAssemblyLocation) ? "dotnet " + Path.GetFileName(entryAssemblyLocation)
: Path.GetFileNameWithoutExtension(entryAssemblyLocation); : Path.GetFileNameWithoutExtension(entryAssemblyLocation);
return name;
} }
private static string GetDefaultVersionText() => private static string GetDefaultVersionText()
EntryAssembly is not null {
? "v" + EntryAssembly.GetName().Version.ToSemanticString() var entryAssemblyVersion = EnvironmentEx.EntryAssembly?.GetName().Version;
: "v1.0"; if (entryAssemblyVersion is null)
return "v1.0";
return "v" + entryAssemblyVersion.ToSemanticString();
}
} }

View File

@@ -4,6 +4,7 @@
<TargetFrameworks>netstandard2.1;netstandard2.0</TargetFrameworks> <TargetFrameworks>netstandard2.1;netstandard2.0</TargetFrameworks>
<Authors>$(Company)</Authors> <Authors>$(Company)</Authors>
<Description>Declarative framework for building command line applications</Description> <Description>Declarative framework for building command line applications</Description>
<IsPackable>true</IsPackable>
<PackageTags>command line executable interface framework parser arguments cli app application net core</PackageTags> <PackageTags>command line executable interface framework parser arguments cli app application net core</PackageTags>
<PackageProjectUrl>https://github.com/Tyrrrz/CliFx</PackageProjectUrl> <PackageProjectUrl>https://github.com/Tyrrrz/CliFx</PackageProjectUrl>
<PackageReleaseNotes>https://github.com/Tyrrrz/CliFx/blob/master/Changelog.md</PackageReleaseNotes> <PackageReleaseNotes>https://github.com/Tyrrrz/CliFx/blob/master/Changelog.md</PackageReleaseNotes>
@@ -32,8 +33,16 @@
<!-- Pack the analyzer assembly inside the package --> <!-- Pack the analyzer assembly inside the package -->
<ItemGroup> <ItemGroup>
<ProjectReference Include="../CliFx.Analyzers/CliFx.Analyzers.csproj" ReferenceOutputAssembly="false" OutputItemType="Analyzer" /> <ProjectReference Include="../CliFx.Analyzers/CliFx.Analyzers.csproj" ReferenceOutputAssembly="false" OutputItemType="analyzer" />
<None Include="../CliFx.Analyzers/bin/$(Configuration)/netstandard2.0/CliFx.Analyzers.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" /> <None Include="../CliFx.Analyzers/bin/$(Configuration)/netstandard2.0/CliFx.Analyzers.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<None Include="../CliFx.Analyzers/bin/$(Configuration)/netstandard2.0/System.Buffers.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<None Include="../CliFx.Analyzers/bin/$(Configuration)/netstandard2.0/System.Collections.Immutable.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<None Include="../CliFx.Analyzers/bin/$(Configuration)/netstandard2.0/System.Memory.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<None Include="../CliFx.Analyzers/bin/$(Configuration)/netstandard2.0/System.Numerics.Vectors.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<None Include="../CliFx.Analyzers/bin/$(Configuration)/netstandard2.0/System.Reflection.Metadata.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<None Include="../CliFx.Analyzers/bin/$(Configuration)/netstandard2.0/System.Runtime.CompilerServices.Unsafe.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<None Include="../CliFx.Analyzers/bin/$(Configuration)/netstandard2.0/System.Text.Encoding.CodePages.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<None Include="../CliFx.Analyzers/bin/$(Configuration)/netstandard2.0/System.Threading.Tasks.Extensions.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -27,7 +27,7 @@ internal class CommandBinder
// Custom converter // Custom converter
if (memberSchema.ConverterType is not null) if (memberSchema.ConverterType is not null)
{ {
var converter = (IBindingConverter) _typeActivator.CreateInstance(memberSchema.ConverterType); var converter = (IBindingConverter)_typeActivator.CreateInstance(memberSchema.ConverterType);
return converter.Convert(rawValue); return converter.Convert(rawValue);
} }
@@ -43,12 +43,6 @@ internal class CommandBinder
return string.IsNullOrWhiteSpace(rawValue) || bool.Parse(rawValue); return string.IsNullOrWhiteSpace(rawValue) || bool.Parse(rawValue);
} }
// IConvertible primitives (int, double, char, etc)
if (targetType.IsConvertible())
{
return Convert.ChangeType(rawValue, targetType, _formatProvider);
}
// Special case for DateTimeOffset // Special case for DateTimeOffset
if (targetType == typeof(DateTimeOffset)) if (targetType == typeof(DateTimeOffset))
{ {
@@ -68,6 +62,12 @@ internal class CommandBinder
return Enum.Parse(targetType, rawValue!, true); return Enum.Parse(targetType, rawValue!, true);
} }
// Convertible primitives (int, double, char, etc)
if (targetType.Implements(typeof(IConvertible)))
{
return Convert.ChangeType(rawValue, targetType, _formatProvider);
}
// Nullable<T> // Nullable<T>
var nullableUnderlyingType = targetType.TryGetNullableUnderlyingType(); var nullableUnderlyingType = targetType.TryGetNullableUnderlyingType();
if (nullableUnderlyingType is not null) if (nullableUnderlyingType is not null)
@@ -78,24 +78,24 @@ internal class CommandBinder
} }
// String-constructible (FileInfo, etc) // String-constructible (FileInfo, etc)
var stringConstructor = targetType.GetConstructor(new[] {typeof(string)}); var stringConstructor = targetType.GetConstructor(new[] { typeof(string) });
if (stringConstructor is not null) if (stringConstructor is not null)
{ {
return stringConstructor.Invoke(new object?[] {rawValue}); return stringConstructor.Invoke(new object?[] { rawValue });
} }
// String-parseable (with IFormatProvider) // String-parseable (with IFormatProvider)
var parseMethodWithFormatProvider = targetType.TryGetStaticParseMethod(true); var parseMethodWithFormatProvider = targetType.TryGetStaticParseMethod(true);
if (parseMethodWithFormatProvider is not null) if (parseMethodWithFormatProvider is not null)
{ {
return parseMethodWithFormatProvider.Invoke(null, new object?[] {rawValue, _formatProvider}); return parseMethodWithFormatProvider.Invoke(null, new object?[] { rawValue, _formatProvider });
} }
// String-parseable (without IFormatProvider) // String-parseable (without IFormatProvider)
var parseMethod = targetType.TryGetStaticParseMethod(); var parseMethod = targetType.TryGetStaticParseMethod();
if (parseMethod is not null) if (parseMethod is not null)
{ {
return parseMethod.Invoke(null, new object?[] {rawValue}); return parseMethod.Invoke(null, new object?[] { rawValue });
} }
throw CliFxException.InternalError( throw CliFxException.InternalError(
@@ -126,10 +126,10 @@ internal class CommandBinder
} }
// Array-constructible (List<T>, HashSet<T>, etc) // Array-constructible (List<T>, HashSet<T>, etc)
var arrayConstructor = targetEnumerableType.GetConstructor(new[] {arrayType}); var arrayConstructor = targetEnumerableType.GetConstructor(new[] { arrayType });
if (arrayConstructor is not null) if (arrayConstructor is not null)
{ {
return arrayConstructor.Invoke(new object?[] {array}); return arrayConstructor.Invoke(new object?[] { array });
} }
throw CliFxException.InternalError( throw CliFxException.InternalError(
@@ -169,7 +169,7 @@ internal class CommandBinder
: ex.Message; : ex.Message;
throw CliFxException.UserError( throw CliFxException.UserError(
$"{memberSchema.GetKind()} {memberSchema.GetFormattedIdentifier()} cannot be set from provided argument(s):" + $"{memberSchema.GetKind()} {memberSchema.GetFormattedIdentifier()} cannot be set from the provided argument(s):" +
Environment.NewLine + Environment.NewLine +
rawValues.Select(v => '<' + v + '>').JoinToString(" ") + rawValues.Select(v => '<' + v + '>').JoinToString(" ") +
Environment.NewLine + Environment.NewLine +
@@ -192,7 +192,7 @@ internal class CommandBinder
foreach (var validatorType in memberSchema.ValidatorTypes) foreach (var validatorType in memberSchema.ValidatorTypes)
{ {
var validator = (IBindingValidator) _typeActivator.CreateInstance(validatorType); var validator = (IBindingValidator)_typeActivator.CreateInstance(validatorType);
var error = validator.Validate(convertedValue); var error = validator.Validate(convertedValue);
if (error is not null) if (error is not null)
@@ -223,7 +223,7 @@ internal class CommandBinder
{ {
// Ensure there are no unexpected parameters and that all parameters are provided // Ensure there are no unexpected parameters and that all parameters are provided
var remainingParameterInputs = commandInput.Parameters.ToList(); var remainingParameterInputs = commandInput.Parameters.ToList();
var remainingParameterSchemas = commandSchema.Parameters.ToList(); var remainingRequiredParameterSchemas = commandSchema.Parameters.Where(p => p.IsRequired).ToList();
var position = 0; var position = 0;
@@ -238,7 +238,7 @@ internal class CommandBinder
{ {
var parameterInput = commandInput.Parameters[position]; var parameterInput = commandInput.Parameters[position];
var rawValues = new[] {parameterInput.Value}; var rawValues = new[] { parameterInput.Value };
BindMember(parameterSchema, commandInstance, rawValues); BindMember(parameterSchema, commandInstance, rawValues);
position++; position++;
@@ -258,7 +258,7 @@ internal class CommandBinder
remainingParameterInputs.RemoveRange(parameterInputs); remainingParameterInputs.RemoveRange(parameterInputs);
} }
remainingParameterSchemas.Remove(parameterSchema); remainingRequiredParameterSchemas.Remove(parameterSchema);
} }
if (remainingParameterInputs.Any()) if (remainingParameterInputs.Any())
@@ -272,13 +272,13 @@ internal class CommandBinder
); );
} }
if (remainingParameterSchemas.Any()) if (remainingRequiredParameterSchemas.Any())
{ {
throw CliFxException.UserError( throw CliFxException.UserError(
"Missing parameter(s):" + "Missing required parameter(s):" +
Environment.NewLine + Environment.NewLine +
remainingParameterSchemas remainingRequiredParameterSchemas
.Select(o => o.GetFormattedIdentifier()) .Select(p => p.GetFormattedIdentifier())
.JoinToString(" ") .JoinToString(" ")
); );
} }
@@ -316,7 +316,7 @@ internal class CommandBinder
else if (environmentVariableInput is not null) else if (environmentVariableInput is not null)
{ {
var rawValues = optionSchema.Property.IsScalar() var rawValues = optionSchema.Property.IsScalar()
? new[] {environmentVariableInput.Value} ? new[] { environmentVariableInput.Value }
: environmentVariableInput.SplitValues(); : environmentVariableInput.SplitValues();
BindMember(optionSchema, commandInstance, rawValues); BindMember(optionSchema, commandInstance, rawValues);

View File

@@ -23,7 +23,7 @@ public abstract class BindingValidator<T> : IBindingValidator
/// <summary> /// <summary>
/// Validates the value bound to a parameter or an option. /// Validates the value bound to a parameter or an option.
/// Returns <code>null</code> if validation is successful, or an error in case of failure. /// Returns null if validation is successful, or an error in case of failure.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// You can use the utility methods <see cref="Ok"/> and <see cref="Error"/> to /// You can use the utility methods <see cref="Ok"/> and <see cref="Error"/> to
@@ -31,5 +31,5 @@ public abstract class BindingValidator<T> : IBindingValidator
/// </remarks> /// </remarks>
public abstract BindingValidationError? Validate(T? value); public abstract BindingValidationError? Validate(T? value);
BindingValidationError? IBindingValidator.Validate(object? value) => Validate((T?) value); BindingValidationError? IBindingValidator.Validate(object? value) => Validate((T?)value);
} }

View File

@@ -157,7 +157,15 @@ internal class HelpConsoleFormatter : ConsoleFormatter
foreach (var parameterSchema in _context.CommandSchema.Parameters.OrderBy(p => p.Order)) foreach (var parameterSchema in _context.CommandSchema.Parameters.OrderBy(p => p.Order))
{ {
Write(ConsoleColor.Red, "* "); if (parameterSchema.IsRequired)
{
Write(ConsoleColor.Red, "* ");
}
else
{
WriteHorizontalMargin();
}
Write(ConsoleColor.DarkCyan, $"{parameterSchema.Name}"); Write(ConsoleColor.DarkCyan, $"{parameterSchema.Name}");
WriteColumnMargin(); WriteColumnMargin();
@@ -198,6 +206,12 @@ internal class HelpConsoleFormatter : ConsoleFormatter
Write('.'); Write('.');
Write(' '); Write(' ');
} }
// Default value
if (!parameterSchema.IsRequired)
{
WriteDefaultValue(parameterSchema);
}
WriteLine(); WriteLine();
} }
@@ -290,60 +304,65 @@ internal class HelpConsoleFormatter : ConsoleFormatter
// Default value // Default value
if (!optionSchema.IsRequired) if (!optionSchema.IsRequired)
{ {
var defaultValue = _context.CommandDefaultValues.GetValueOrDefault(optionSchema); WriteDefaultValue(optionSchema);
if (defaultValue is not null)
{
// Non-Scalar
if (defaultValue is not string && defaultValue is IEnumerable defaultValues)
{
var elementType =
defaultValues.GetType().TryGetEnumerableUnderlyingType() ??
typeof(object);
if (elementType.IsToStringOverriden())
{
Write(ConsoleColor.White, "Default: ");
var isFirst = true;
foreach (var element in defaultValues)
{
if (isFirst)
{
isFirst = false;
}
else
{
Write(", ");
}
Write('"');
Write(element.ToString(CultureInfo.InvariantCulture));
Write('"');
}
Write('.');
}
}
else
{
if (defaultValue.GetType().IsToStringOverriden())
{
Write(ConsoleColor.White, "Default: ");
Write('"');
Write(defaultValue.ToString(CultureInfo.InvariantCulture));
Write('"');
Write('.');
}
}
}
} }
WriteLine(); WriteLine();
} }
} }
private void WriteDefaultValue(IMemberSchema schema)
{
var defaultValue = _context.CommandDefaultValues.GetValueOrDefault(schema);
if (defaultValue is not null)
{
// Non-Scalar
if (defaultValue is not string && defaultValue is IEnumerable defaultValues)
{
var elementType =
defaultValues.GetType().TryGetEnumerableUnderlyingType() ??
typeof(object);
if (elementType.IsToStringOverriden())
{
Write(ConsoleColor.White, "Default: ");
var isFirst = true;
foreach (var element in defaultValues)
{
if (isFirst)
{
isFirst = false;
}
else
{
Write(", ");
}
Write('"');
Write(element.ToString(CultureInfo.InvariantCulture));
Write('"');
}
Write('.');
}
}
else
{
if (defaultValue.GetType().IsToStringOverriden())
{
Write(ConsoleColor.White, "Default: ");
Write('"');
Write(defaultValue.ToString(CultureInfo.InvariantCulture));
Write('"');
Write('.');
}
}
}
}
private void WriteCommandChildren() private void WriteCommandChildren()
{ {
var childCommandSchemas = _context var childCommandSchemas = _context

View File

@@ -1,11 +1,16 @@
using System.IO; using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text; using System.Text;
using System.Threading.Tasks;
namespace CliFx.Infrastructure; namespace CliFx.Infrastructure;
/// <summary> /// <summary>
/// Implements a <see cref="TextReader"/> for reading characters from a console stream. /// Implements a <see cref="TextReader"/> for reading characters from a console stream.
/// </summary> /// </summary>
// Both the underlying stream AND the stream reader must be synchronized!
// https://github.com/Tyrrrz/CliFx/issues/123
public partial class ConsoleReader : StreamReader public partial class ConsoleReader : StreamReader
{ {
/// <summary> /// <summary>
@@ -29,14 +34,73 @@ public partial class ConsoleReader : StreamReader
: this(console, stream, System.Console.InputEncoding) : this(console, stream, System.Console.InputEncoding)
{ {
} }
// The following overrides are required to establish thread-safe behavior
// in methods deriving from StreamReader.
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override int Peek() => base.Peek();
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override int Read() => base.Read();
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override int Read(char[] buffer, int index, int count) =>
base.Read(buffer, index, count);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override int ReadBlock(char[] buffer, int index, int count) =>
base.ReadBlock(buffer, index, count);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override string? ReadLine() => base.ReadLine();
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override string ReadToEnd() => base.ReadToEnd();
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override Task<int> ReadAsync(char[] buffer, int index, int count) =>
// Must be non-async to work with locks
Task.FromResult(Read(buffer, index, count));
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count) =>
// Must be non-async to work with locks
Task.FromResult(ReadBlock(buffer, index, count));
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override Task<string?> ReadLineAsync() =>
// Must be non-async to work with locks
Task.FromResult(ReadLine());
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override Task<string> ReadToEndAsync() =>
// Must be non-async to work with locks
Task.FromResult(ReadToEnd());
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Close() => base.Close();
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
protected override void Dispose(bool disposing) => base.Dispose(disposing);
} }
public partial class ConsoleReader public partial class ConsoleReader
{ {
internal static ConsoleReader Create(IConsole console, Stream? stream) => new( internal static ConsoleReader Create(IConsole console, Stream stream) => new(
console, console,
stream is not null Stream.Synchronized(stream)
? Stream.Synchronized(stream)
: Stream.Null
); );
} }

View File

@@ -1,5 +1,8 @@
using System.IO; using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text; using System.Text;
using System.Threading.Tasks;
using CliFx.Utils; using CliFx.Utils;
namespace CliFx.Infrastructure; namespace CliFx.Infrastructure;
@@ -7,6 +10,8 @@ namespace CliFx.Infrastructure;
/// <summary> /// <summary>
/// Implements a <see cref="TextWriter"/> for writing characters to a console stream. /// Implements a <see cref="TextWriter"/> for writing characters to a console stream.
/// </summary> /// </summary>
// Both the underlying stream AND the stream writer must be synchronized!
// https://github.com/Tyrrrz/CliFx/issues/123
public partial class ConsoleWriter : StreamWriter public partial class ConsoleWriter : StreamWriter
{ {
/// <summary> /// <summary>
@@ -30,14 +35,245 @@ public partial class ConsoleWriter : StreamWriter
: this(console, stream, System.Console.OutputEncoding) : this(console, stream, System.Console.OutputEncoding)
{ {
} }
// The following overrides are required to establish thread-safe behavior
// in methods deriving from StreamWriter.
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Write(char[] buffer, int index, int count) => base.Write(buffer, index, count);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Write(char[] buffer) => base.Write(buffer);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Write(char value) => base.Write(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Write(string? value) => base.Write(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Write(string format, object? arg0) => base.Write(format, arg0);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Write(string format, object? arg0, object? arg1) =>
base.Write(format, arg0, arg1);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Write(string format, object? arg0, object? arg1, object? arg2) =>
base.Write(format, arg0, arg1, arg2);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Write(string format, params object?[] arg) => base.Write(format, arg);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Write(bool value) => base.Write(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Write(int value) => base.Write(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Write(long value) => base.Write(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Write(uint value) => base.Write(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Write(ulong value) => base.Write(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Write(float value) => base.Write(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Write(double value) => base.Write(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Write(decimal value) => base.Write(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Write(object? value) => base.Write(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override Task WriteAsync(char[] buffer, int index, int count)
{
// Must be non-async to work with locks
Write(buffer, index, count);
return Task.CompletedTask;
}
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override Task WriteAsync(char value)
{
// Must be non-async to work with locks
Write(value);
return Task.CompletedTask;
}
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override Task WriteAsync(string? value)
{
// Must be non-async to work with locks
Write(value);
return Task.CompletedTask;
}
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void WriteLine() => base.WriteLine();
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void WriteLine(char[] buffer, int index, int count) =>
base.WriteLine(buffer, index, count);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void WriteLine(char[] buffer) => base.WriteLine(buffer);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void WriteLine(char value) => base.WriteLine(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void WriteLine(string? value) => base.WriteLine(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void WriteLine(string format, object? arg0) => base.WriteLine(format, arg0);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void WriteLine(string format, object? arg0, object? arg1) =>
base.WriteLine(format, arg0, arg1);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void WriteLine(string format, object? arg0, object? arg1, object? arg2) =>
base.WriteLine(format, arg0, arg1, arg2);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void WriteLine(string format, params object?[] arg) =>
base.WriteLine(format, arg);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void WriteLine(bool value) => base.WriteLine(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void WriteLine(int value) => base.WriteLine(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void WriteLine(long value) => base.WriteLine(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void WriteLine(uint value) => base.WriteLine(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void WriteLine(ulong value) => base.WriteLine(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void WriteLine(float value) => base.WriteLine(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void WriteLine(double value) => base.WriteLine(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void WriteLine(decimal value) => base.WriteLine(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void WriteLine(object? value) => base.WriteLine(value);
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override Task WriteLineAsync()
{
// Must be non-async to work with locks
WriteLine();
return Task.CompletedTask;
}
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override Task WriteLineAsync(char value)
{
// Must be non-async to work with locks
WriteLine(value);
return Task.CompletedTask;
}
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override Task WriteLineAsync(char[] buffer, int index, int count)
{
// Must be non-async to work with locks
WriteLine(buffer, index, count);
return Task.CompletedTask;
}
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override Task WriteLineAsync(string? value)
{
// Must be non-async to work with locks
WriteLine(value);
return Task.CompletedTask;
}
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Flush() => base.Flush();
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override Task FlushAsync()
{
// Must be non-async to work with locks
Flush();
return Task.CompletedTask;
}
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override void Close() => base.Close();
/// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
protected override void Dispose(bool disposing) => base.Dispose(disposing);
} }
public partial class ConsoleWriter public partial class ConsoleWriter
{ {
internal static ConsoleWriter Create(IConsole console, Stream? stream) => new( internal static ConsoleWriter Create(IConsole console, Stream stream) => new(
console, console,
stream is not null Stream.Synchronized(stream)
? Stream.Synchronized(stream)
: Stream.Null
) {AutoFlush = true}; ) {AutoFlush = true};
} }

View File

@@ -16,14 +16,15 @@ public class DefaultTypeActivator : ITypeActivator
{ {
return Activator.CreateInstance(type); return Activator.CreateInstance(type);
} }
catch (Exception ex) // Only catch MemberAccessException because the constructor can throw for its own reasons too
catch (MemberAccessException ex)
{ {
throw CliFxException.InternalError( throw CliFxException.InternalError(
$"Failed to create an instance of type `{type.FullName}`." + $"Failed to create an instance of type `{type.FullName}`, could not access the constructor." +
Environment.NewLine + Environment.NewLine +
"Default type activator is only capable of instantiating a type if it has a public parameterless constructor." + "Default type activator is only capable of instantiating a type if it has a public parameterless constructor." +
Environment.NewLine + Environment.NewLine +
"To fix this, either add a parameterless constructor to the type or configure a custom activator on the application.", "To fix this, either add a parameterless constructor to the type or configure a custom activator for the application.",
ex ex
); );
} }

View File

@@ -1,4 +1,5 @@
using System; using System;
using System.Collections.Concurrent;
using System.IO; using System.IO;
using System.Threading; using System.Threading;
@@ -14,6 +15,7 @@ namespace CliFx.Infrastructure;
public class FakeConsole : IConsole, IDisposable public class FakeConsole : IConsole, IDisposable
{ {
private readonly CancellationTokenSource _cancellationTokenSource = new(); private readonly CancellationTokenSource _cancellationTokenSource = new();
private readonly ConcurrentQueue<ConsoleKeyInfo> _keys = new();
/// <inheritdoc /> /// <inheritdoc />
public ConsoleReader Input { get; } public ConsoleReader Input { get; }
@@ -40,11 +42,10 @@ public class FakeConsole : IConsole, IDisposable
public ConsoleColor BackgroundColor { get; set; } = ConsoleColor.Black; public ConsoleColor BackgroundColor { get; set; } = ConsoleColor.Black;
/// <inheritdoc /> /// <inheritdoc />
public void ResetColor() public int WindowWidth { get; set; } = 232; // Windows defaults
{
ForegroundColor = ConsoleColor.Gray; /// <inheritdoc />
BackgroundColor = ConsoleColor.Black; public int WindowHeight { get; set; } = 14; // Windows defaults
}
/// <inheritdoc /> /// <inheritdoc />
public int CursorLeft { get; set; } public int CursorLeft { get; set; }
@@ -57,9 +58,35 @@ public class FakeConsole : IConsole, IDisposable
/// </summary> /// </summary>
public FakeConsole(Stream? input = null, Stream? output = null, Stream? error = null) public FakeConsole(Stream? input = null, Stream? output = null, Stream? error = null)
{ {
Input = ConsoleReader.Create(this, input); Input = ConsoleReader.Create(this, input ?? Stream.Null);
Output = ConsoleWriter.Create(this, output); Output = ConsoleWriter.Create(this, output ?? Stream.Null);
Error = ConsoleWriter.Create(this, error); Error = ConsoleWriter.Create(this, error ?? Stream.Null);
}
/// <inheritdoc />
public ConsoleKeyInfo ReadKey(bool intercept = false) =>
_keys.TryDequeue(out var key)
? key
: throw new InvalidOperationException(
"Cannot read key because there are no key presses enqueued. " +
$"Use the `{nameof(EnqueueKey)}(...)` method to simulate a key press."
);
/// <summary>
/// Enqueues a simulated key press, which can then be read by calling <see cref="ReadKey"/>.
/// </summary>
public void EnqueueKey(ConsoleKeyInfo key) => _keys.Enqueue(key);
/// <inheritdoc />
public void ResetColor()
{
ForegroundColor = ConsoleColor.Gray;
BackgroundColor = ConsoleColor.Black;
}
/// <inheritdoc />
public void Clear()
{
} }
/// <inheritdoc /> /// <inheritdoc />
@@ -85,16 +112,6 @@ public class FakeConsole : IConsole, IDisposable
} }
} }
/// <inheritdoc />
public void Clear()
{
}
/// <inheritdoc />
public void ReadKey(bool intercept = false)
{
}
/// <inheritdoc /> /// <inheritdoc />
public virtual void Dispose() => _cancellationTokenSource.Dispose(); public virtual void Dispose() => _cancellationTokenSource.Dispose();
} }

View File

@@ -15,7 +15,7 @@ public interface IConsole
ConsoleReader Input { get; } ConsoleReader Input { get; }
/// <summary> /// <summary>
/// Whether the input stream is redirected. /// Gets a value that indicates whether input has been redirected from the standard input stream.
/// </summary> /// </summary>
bool IsInputRedirected { get; } bool IsInputRedirected { get; }
@@ -25,7 +25,7 @@ public interface IConsole
ConsoleWriter Output { get; } ConsoleWriter Output { get; }
/// <summary> /// <summary>
/// Whether the output stream is redirected. /// Gets a value that indicates whether output has been redirected from the standard output stream.
/// </summary> /// </summary>
bool IsOutputRedirected { get; } bool IsOutputRedirected { get; }
@@ -35,39 +35,59 @@ public interface IConsole
ConsoleWriter Error { get; } ConsoleWriter Error { get; }
/// <summary> /// <summary>
/// Whether the error stream is redirected. /// Gets a value that indicates whether error output has been redirected from the standard error stream.
/// </summary> /// </summary>
bool IsErrorRedirected { get; } bool IsErrorRedirected { get; }
/// <summary> /// <summary>
/// Current foreground color. /// Gets or sets the foreground color of the console
/// </summary> /// </summary>
ConsoleColor ForegroundColor { get; set; } ConsoleColor ForegroundColor { get; set; }
/// <summary> /// <summary>
/// Current background color. /// Gets or sets the background color of the console.
/// </summary> /// </summary>
ConsoleColor BackgroundColor { get; set; } ConsoleColor BackgroundColor { get; set; }
/// <summary> /// <summary>
/// Resets foreground and background colors to their default values. /// Gets or sets the width of the console window.
/// </summary> /// </summary>
void ResetColor(); int WindowWidth { get; set; }
/// <summary> /// <summary>
/// Cursor left offset. /// Gets or sets the height of the console window.
/// </summary>
int WindowHeight { get; set; }
/// <summary>
/// Gets or sets the column position of the cursor within the buffer area.
/// </summary> /// </summary>
int CursorLeft { get; set; } int CursorLeft { get; set; }
/// <summary> /// <summary>
/// Cursor top offset. /// Gets or sets the row position of the cursor within the buffer area.
/// </summary> /// </summary>
int CursorTop { get; set; } int CursorTop { get; set; }
/// <summary>
/// Obtains the next character or function key pressed by the user.
/// </summary>
ConsoleKeyInfo ReadKey(bool intercept = false);
/// <summary>
/// Sets the foreground and background console colors to their defaults.
/// </summary>
void ResetColor();
/// <summary>
/// Clears the console buffer and corresponding console window of display information.
/// </summary>
void Clear();
/// <summary> /// <summary>
/// Registers a handler for the interrupt signal (Ctrl+C) on the console and returns /// Registers a handler for the interrupt signal (Ctrl+C) on the console and returns
/// a token representing the cancellation request. /// a token representing the cancellation request.
/// Subsequent calls to this method have no side-effects and return the same token. /// Subsequent calls to this method have no side effects and return the same token.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// <para> /// <para>
@@ -82,16 +102,6 @@ public interface IConsole
/// </para> /// </para>
/// </remarks> /// </remarks>
CancellationToken RegisterCancellationHandler(); CancellationToken RegisterCancellationHandler();
/// <summary>
/// Clears the console buffer and corresponding console window of display information.
/// </summary>
void Clear();
/// <summary>
/// Obtains the next character or function key pressed by the user.
/// </summary>
void ReadKey(bool intercept = false);
} }
/// <summary> /// <summary>

View File

@@ -42,18 +42,19 @@ public class SystemConsole : IConsole, IDisposable
set => Console.BackgroundColor = value; set => Console.BackgroundColor = value;
} }
/// <summary> /// <inheritdoc />
/// Initializes an instance of <see cref="SystemConsole"/>. public int WindowWidth
/// </summary>
public SystemConsole()
{ {
Input = ConsoleReader.Create(this, Console.OpenStandardInput()); get => Console.WindowWidth;
Output = ConsoleWriter.Create(this, Console.OpenStandardOutput()); set => Console.WindowWidth = value;
Error = ConsoleWriter.Create(this, Console.OpenStandardError());
} }
/// <inheritdoc /> /// <inheritdoc />
public void ResetColor() => Console.ResetColor(); public int WindowHeight
{
get => Console.WindowHeight;
set => Console.WindowHeight = value;
}
/// <inheritdoc /> /// <inheritdoc />
public int CursorLeft public int CursorLeft
@@ -69,6 +70,25 @@ public class SystemConsole : IConsole, IDisposable
set => Console.CursorTop = value; set => Console.CursorTop = value;
} }
/// <summary>
/// Initializes an instance of <see cref="SystemConsole"/>.
/// </summary>
public SystemConsole()
{
Input = ConsoleReader.Create(this, Console.OpenStandardInput());
Output = ConsoleWriter.Create(this, Console.OpenStandardOutput());
Error = ConsoleWriter.Create(this, Console.OpenStandardError());
}
/// <inheritdoc />
public ConsoleKeyInfo ReadKey(bool intercept = false) => Console.ReadKey(intercept);
/// <inheritdoc />
public void ResetColor() => Console.ResetColor();
/// <inheritdoc />
public void Clear() => Console.Clear();
/// <inheritdoc /> /// <inheritdoc />
public CancellationToken RegisterCancellationHandler() public CancellationToken RegisterCancellationHandler()
{ {
@@ -90,12 +110,6 @@ public class SystemConsole : IConsole, IDisposable
return (_cancellationTokenSource = cts).Token; return (_cancellationTokenSource = cts).Token;
} }
/// <inheritdoc />
public void Clear() => Console.Clear();
/// <inheritdoc />
public void ReadKey(bool intercept = false) => Console.ReadKey(intercept);
/// <inheritdoc /> /// <inheritdoc />
public void Dispose() public void Dispose()
{ {

View File

@@ -33,7 +33,7 @@ internal class BindablePropertyDescriptor : IPropertyDescriptor
return type; return type;
} }
var underlyingType = GetUnderlyingType(Type); var underlyingType = GetUnderlyingType(Type);
// We can only get valid values for enums // We can only get valid values for enums

View File

@@ -87,12 +87,27 @@ internal partial class CommandSchema
? new[] {OptionSchema.HelpOption, OptionSchema.VersionOption} ? new[] {OptionSchema.HelpOption, OptionSchema.VersionOption}
: new[] {OptionSchema.HelpOption}; : new[] {OptionSchema.HelpOption};
var parameterSchemas = type.GetProperties() var properties = type
// Get properties directly on command type
.GetProperties()
// Get non-abstract properties on interfaces (to support default interfaces members)
.Union(type
.GetInterfaces()
// Only interfaces implementing ICommand for explicitness
.Where(i => typeof(ICommand).IsAssignableFrom(i) && i != typeof(ICommand))
.SelectMany(i => i
.GetProperties()
.Where(p => !p.GetMethod.IsAbstract && !p.SetMethod.IsAbstract)
)
)
.ToArray();
var parameterSchemas = properties
.Select(ParameterSchema.TryResolve) .Select(ParameterSchema.TryResolve)
.WhereNotNull() .WhereNotNull()
.ToArray(); .ToArray();
var optionSchemas = type.GetProperties() var optionSchemas = properties
.Select(OptionSchema.TryResolve) .Select(OptionSchema.TryResolve)
.WhereNotNull() .WhereNotNull()
.Concat(implicitOptionSchemas) .Concat(implicitOptionSchemas)

View File

@@ -13,6 +13,8 @@ internal partial class ParameterSchema : IMemberSchema
public string Name { get; } public string Name { get; }
public bool IsRequired { get; }
public string? Description { get; } public string? Description { get; }
public Type? ConverterType { get; } public Type? ConverterType { get; }
@@ -23,6 +25,7 @@ internal partial class ParameterSchema : IMemberSchema
IPropertyDescriptor property, IPropertyDescriptor property,
int order, int order,
string name, string name,
bool isRequired,
string? description, string? description,
Type? converterType, Type? converterType,
IReadOnlyList<Type> validatorTypes) IReadOnlyList<Type> validatorTypes)
@@ -30,6 +33,7 @@ internal partial class ParameterSchema : IMemberSchema
Property = property; Property = property;
Order = order; Order = order;
Name = name; Name = name;
IsRequired = isRequired;
Description = description; Description = description;
ConverterType = converterType; ConverterType = converterType;
ValidatorTypes = validatorTypes; ValidatorTypes = validatorTypes;
@@ -55,6 +59,7 @@ internal partial class ParameterSchema
new BindablePropertyDescriptor(property), new BindablePropertyDescriptor(property),
attribute.Order, attribute.Order,
name, name,
attribute.IsRequired,
description, description,
attribute.Converter, attribute.Converter,
attribute.Validators attribute.Validators

View File

@@ -0,0 +1,20 @@
using System;
using System.Diagnostics;
using System.Reflection;
namespace CliFx.Utils;
internal static class EnvironmentEx
{
private static readonly Lazy<string?> ProcessPathLazy = new(() =>
{
using var process = Process.GetCurrentProcess();
return process.MainModule?.FileName;
});
public static string? ProcessPath => ProcessPathLazy.Value;
private static readonly Lazy<Assembly?> EntryAssemblyLazy = new(Assembly.GetEntryAssembly);
public static Assembly? EntryAssembly => EntryAssemblyLazy.Value;
}

View File

@@ -59,27 +59,4 @@ internal static class TypeExtensions
var toStringMethod = type.GetMethod(nameof(ToString), Type.EmptyTypes); var toStringMethod = type.GetMethod(nameof(ToString), Type.EmptyTypes);
return toStringMethod?.GetBaseDefinition()?.DeclaringType != toStringMethod?.DeclaringType; return toStringMethod?.GetBaseDefinition()?.DeclaringType != toStringMethod?.DeclaringType;
} }
// Types supported by `Convert.ChangeType(...)`
private static readonly HashSet<Type> ConvertibleTypes = new()
{
typeof(bool),
typeof(char),
typeof(sbyte),
typeof(byte),
typeof(short),
typeof(ushort),
typeof(int),
typeof(uint),
typeof(long),
typeof(ulong),
typeof(float),
typeof(double),
typeof(decimal),
typeof(DateTime),
typeof(string),
typeof(object)
};
public static bool IsConvertible(this Type type) => ConvertibleTypes.Contains(type);
} }

View File

@@ -8,6 +8,8 @@ namespace CliFx.Utils;
// https://github.com/dotnet/runtime/blob/01b7e73cd378145264a7cb7a09365b41ed42b240/src/libraries/Common/src/System/Text/ConsoleEncoding.cs // https://github.com/dotnet/runtime/blob/01b7e73cd378145264a7cb7a09365b41ed42b240/src/libraries/Common/src/System/Text/ConsoleEncoding.cs
// Also see: // Also see:
// https://source.dot.net/#System.Console/ConsoleEncoding.cs,5eedd083a4a4f4a2 // https://source.dot.net/#System.Console/ConsoleEncoding.cs,5eedd083a4a4f4a2
// Majority of overrides are just proxy calls to avoid potentially more expensive base behavior.
// The important part is the GetPreamble() method that has been overriden to return an empty array.
internal class NoPreambleEncoding : Encoding internal class NoPreambleEncoding : Encoding
{ {
private readonly Encoding _underlyingEncoding; private readonly Encoding _underlyingEncoding;
@@ -72,20 +74,20 @@ internal class NoPreambleEncoding : Encoding
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) => public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) =>
_underlyingEncoding.GetBytes(chars, charIndex, charCount, bytes, byteIndex); _underlyingEncoding.GetBytes(chars, charIndex, charCount, bytes, byteIndex);
[ExcludeFromCodeCoverage]
public override byte[] GetBytes(char[] chars) => _underlyingEncoding.GetBytes(chars);
[ExcludeFromCodeCoverage] [ExcludeFromCodeCoverage]
public override byte[] GetBytes(char[] chars, int index, int count) => public override byte[] GetBytes(char[] chars, int index, int count) =>
_underlyingEncoding.GetBytes(chars, index, count); _underlyingEncoding.GetBytes(chars, index, count);
[ExcludeFromCodeCoverage] [ExcludeFromCodeCoverage]
public override byte[] GetBytes(string s) => _underlyingEncoding.GetBytes(s); public override byte[] GetBytes(char[] chars) => _underlyingEncoding.GetBytes(chars);
[ExcludeFromCodeCoverage] [ExcludeFromCodeCoverage]
public override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) => public override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) =>
_underlyingEncoding.GetBytes(s, charIndex, charCount, bytes, byteIndex); _underlyingEncoding.GetBytes(s, charIndex, charCount, bytes, byteIndex);
[ExcludeFromCodeCoverage]
public override byte[] GetBytes(string s) => _underlyingEncoding.GetBytes(s);
[ExcludeFromCodeCoverage] [ExcludeFromCodeCoverage]
public override int GetCharCount(byte[] bytes, int index, int count) => public override int GetCharCount(byte[] bytes, int index, int count) =>
_underlyingEncoding.GetCharCount(bytes, index, count); _underlyingEncoding.GetCharCount(bytes, index, count);

View File

@@ -0,0 +1,26 @@
// 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

View File

@@ -0,0 +1,11 @@
// 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

View File

@@ -0,0 +1,12 @@
// 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

View File

@@ -1,53 +0,0 @@
// ReSharper disable CheckNamespace
#if NETSTANDARD2_0
using System;
using System.Collections.Generic;
using System.IO;
internal static partial class PolyfillExtensions
{
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;
public static string[] Split(this string str, char separator, StringSplitOptions splitOptions) =>
str.Split(new[] {separator}, splitOptions);
}
internal static partial class PolyfillExtensions
{
public static void Deconstruct<TKey, TValue>(this KeyValuePair<TKey, TValue> pair, out TKey key, out TValue value)
{
key = pair.Key;
value = pair.Value;
}
}
internal static partial class PolyfillExtensions
{
public static void Write(this Stream stream, byte[] buffer) =>
stream.Write(buffer, 0, buffer.Length);
}
namespace System.Linq
{
internal static class PolyfillExtensions
{
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer) =>
new(source, comparer);
}
}
namespace System.Collections.Generic
{
internal static class PolyfillExtensions
{
public static TValue GetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dic, TKey key) =>
dic.TryGetValue(key!, out var result) ? result! : default!;
}
}
#endif

View File

@@ -1,12 +1,13 @@
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<Version>2.1</Version> <Version>2.3</Version>
<Company>Tyrrrz</Company> <Company>Tyrrrz</Company>
<Copyright>Copyright (C) Alexey Golub</Copyright> <Copyright>Copyright (C) Oleksii Holub</Copyright>
<LangVersion>latest</LangVersion> <LangVersion>latest</LangVersion>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<WarningsAsErrors>nullable</WarningsAsErrors> <WarningsAsErrors>nullable</WarningsAsErrors>
<IsPackable>false</IsPackable>
</PropertyGroup> </PropertyGroup>
<!-- Disable nullability warnings on older frameworks because there is no nullability info for BCL --> <!-- Disable nullability warnings on older frameworks because there is no nullability info for BCL -->

View File

@@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2019-2022 Alexey Golub Copyright (c) 2019-2022 Oleksii Holub
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@@ -2,6 +2,9 @@
<configuration> <configuration>
<packageSources> <packageSources>
<clear /> <clear />
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" /> <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
</packageSources> </packageSources>
<config>
<add key="defaultPushSource" value="https://api.nuget.org/v3/index.json" />
</config>
</configuration> </configuration>

211
Readme.md
View File

@@ -1,29 +1,40 @@
# CliFx # CliFx
[![Build](https://github.com/Tyrrrz/CliFx/workflows/main/badge.svg?branch=master)](https://github.com/Tyrrrz/CliFx/actions) [![Made in Ukraine](https://img.shields.io/badge/made_in-ukraine-ffd700.svg?labelColor=0057b7)](https://vshymanskyy.github.io/StandWithUkraine)
[![Coverage](https://codecov.io/gh/Tyrrrz/CliFx/branch/master/graph/badge.svg)](https://codecov.io/gh/Tyrrrz/CliFx) [![Build](https://img.shields.io/github/workflow/status/Tyrrrz/CliFx/CI/master)](https://github.com/Tyrrrz/CliFx/actions)
[![Coverage](https://img.shields.io/codecov/c/github/Tyrrrz/CliFx/master)](https://codecov.io/gh/Tyrrrz/CliFx)
[![Version](https://img.shields.io/nuget/v/CliFx.svg)](https://nuget.org/packages/CliFx) [![Version](https://img.shields.io/nuget/v/CliFx.svg)](https://nuget.org/packages/CliFx)
[![Downloads](https://img.shields.io/nuget/dt/CliFx.svg)](https://nuget.org/packages/CliFx) [![Downloads](https://img.shields.io/nuget/dt/CliFx.svg)](https://nuget.org/packages/CliFx)
[![Discord](https://img.shields.io/discord/869237470565392384?label=discord)](https://discord.gg/2SUWKFnHSm) [![Discord](https://img.shields.io/discord/869237470565392384?label=discord)](https://discord.gg/2SUWKFnHSm)
[![Donate](https://img.shields.io/badge/donate-$$$-purple.svg)](https://tyrrrz.me/donate) [![Donate](https://img.shields.io/badge/donate-$$$-8a2be2.svg)](https://tyrrrz.me/donate)
[![Fuck Russia](https://img.shields.io/badge/fuck-russia-e4181c.svg?labelColor=000000)](https://twitter.com/tyrrrz/status/1495972128977571848)
**Project status: active**. [What does it mean?](https://github.com/Tyrrrz/.github/blob/master/docs/project-status.md) > 🟢 **Project status**: active<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. 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.
💬 **If you want to chat, join my [Discord server](https://discord.gg/2SUWKFnHSm)**. ## Terms of use<sup>[[?]](https://github.com/Tyrrrz/.github/blob/master/docs/why-so-political.md)</sup>
## Download By using this project or its source code, for any purpose and in any shape or form, you grant your **implicit agreement** to all the following statements:
📦 [NuGet](https://nuget.org/packages/CliFx): `dotnet add package CliFx` - You **condemn Russia and its military aggression against Ukraine**
- You **recognize that Russia is an occupant that unlawfully invaded a sovereign state**
- 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! 🇺🇦
## Install
- 📦 [NuGet](https://nuget.org/packages/CliFx): `dotnet add package CliFx`
## Features ## Features
- Complete application framework, not just an argument parser - Complete application framework, not just an argument parser
- Minimum boilerplate and easy to get started - Minimum boilerplate and easy to get started
- Class-first configuration via attributes - Class-first configuration via attributes
- Comprehensive autogenerated help text - Comprehensive auto-generated help text
- Support for deeply nested command hierarchies - Support for deeply nested command hierarchies
- Graceful cancellation via interrupt signals - Graceful cancellation via interrupt signals
- Support for reading and writing binary data - Support for reading and writing binary data
@@ -34,13 +45,11 @@ Its primary goal is to completely take over the user input layer, allowing you t
## Screenshots ## Screenshots
![help screen](.screenshots/help.png) ![help screen](.assets/help-screen.png)
## Usage ## Usage
### Quick start ### Application and commands
![quick start animated](https://i.imgur.com/uouNh2u.gif)
To turn your program into a command line interface, modify your `Main` method so that it delegates execution to `CliApplication`. 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`: You can use `CliApplicationBuilder` to fluently create and configure an instance of `CliApplication`:
@@ -56,10 +65,15 @@ public static class Program
} }
``` ```
> ⚠️ Ensure that your `Main()` method returns the integer exit code provided by `CliApplication.RunAsync()`, as shown in the above example. > **Warning**:
Exit code is used to communicate execution result to the parent process, so it's important that your program returns it. > Ensure that your `Main()` method returns the integer exit code provided by `CliApplication.RunAsync()`, as shown in the above example.
> Exit code is used to communicate execution result to the parent process, so it's important that your program propagates it.
The code above calls `AddCommandsFromThisAssembly()` to scan and resolve command types defined within the current assembly. > **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.
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. Commands are entry points, through which the user can interact with your application.
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 new class by implementing the `ICommand` interface and annotate it with the `[Command]` attribute:
@@ -81,12 +95,12 @@ public class HelloWorldCommand : ICommand
In order to implement `ICommand`, the class needs to define an `ExecuteAsync(...)` method. 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. This is the method that gets called by the framework when the user decides to execute this command.
As a parameter, this method takes an instance of `IConsole`, which is an abstraction around the system console. 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. 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: With the basic setup above, the user can now run the application and get a greeting in return:
```sh ```powershell
> dotnet myapp.dll > dotnet myapp.dll
Hello world! Hello world!
@@ -95,7 +109,7 @@ Hello world!
Out of the box, the application also comes with built-in `--help` and `--version` options. 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: They can be used to show help text or application version respectively:
```sh ```powershell
> dotnet myapp.dll --help > dotnet myapp.dll --help
MyApp v1.0 MyApp v1.0
@@ -108,7 +122,7 @@ OPTIONS
--version Shows version information. --version Shows version information.
``` ```
```sh ```powershell
> dotnet myapp.dll --version > dotnet myapp.dll --version
v1.0 v1.0
@@ -117,12 +131,12 @@ v1.0
### Parameters and options ### Parameters and options
Commands can be configured to take input from command line arguments. Commands can be configured to take input from command line arguments.
To do that, you need to add properties to the command class and annotate them with special attributes. 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**. In **CliFx**, there are two types of argument bindings: **parameters** and **options**.
Parameters are positional arguments identified by the order they appear in, while options represent sets of arguments identified by their name. 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 the logarithm of a value, using a parameter binding to specify the input and an option binding to configure the logarithm base: 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 ```csharp
[Command] [Command]
@@ -147,9 +161,13 @@ public class LogCommand : ICommand
} }
``` ```
> **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 execute this command, at a minimum, the user needs to provide the input value: In order to execute this command, at a minimum, the user needs to provide the input value:
```sh ```powershell
> dotnet myapp.dll 10000 > dotnet myapp.dll 10000
4 4
@@ -157,7 +175,7 @@ In order to execute this command, at a minimum, the user needs to provide the in
They can also pass the `base` option to override the default logarithm base of 10: They can also pass the `base` option to override the default logarithm base of 10:
```sh ```powershell
> dotnet myapp.dll 729 -b 3 > dotnet myapp.dll 729 -b 3
6 6
@@ -165,16 +183,16 @@ They can also pass the `base` option to override the default logarithm base of 1
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 `value` parameter, the application will exit with an error:
```sh ```powershell
> dotnet myapp.dll -b 10 > dotnet myapp.dll -b 10
Missing parameter(s): Missing required parameter(s):
<value> <value>
``` ```
Available parameters and options are also listed in the command's help text, which can be accessed by passing the `--help` option: Available parameters and options are also listed in the command's help text, which can be accessed by passing the `--help` option:
```sh ```powershell
> dotnet myapp.dll --help > dotnet myapp.dll --help
MyApp v1.0 MyApp v1.0
@@ -193,13 +211,14 @@ OPTIONS
Overall, parameters and options are both used to consume input from the command line, but they differ in a few important ways: Overall, parameters and options are both used to consume input from the command line, but they differ in a few important ways:
- Parameters are identified by their relative order. Options are identified by their name or a single-character short name. | | Parameter | Option |
- Parameters technically also have a name, but it's only used in the help text. |--------------------|--------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------|
- Parameters are always required. Options are normally optional, but can also be configured to require a value. | **Identification** | Positional (by relative order). | Nominal (by name or short name). |
- Options can be configured to use an environment variable as a fallback. | **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. |
- Both parameters and options can take multiple values, but there can only be one such parameter in a command and it must be the last in order. Options are not limited in this regard. | **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, it's recommended to use parameters for required inputs that the command can't function without. 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. Use options for all other non-required inputs or when specifying the name explicitly makes the usage clearer.
### Argument syntax ### Argument syntax
@@ -215,26 +234,26 @@ Here are some examples of how it works:
- `myapp -xqf bar` sets options `'x'` and `'q'` without value, and option `'f'` to value `"bar"` - `myapp -xqf bar` sets options `'x'` and `'q'` without value, and option `'f'` to value `"bar"`
- `myapp -i file1.txt file2.txt` sets option `'i'` to a sequence of values `"file1.txt"` and `"file2.txt"` - `myapp -i file1.txt file2.txt` sets option `'i'` to a sequence of values `"file1.txt"` and `"file2.txt"`
- `myapp -i file1.txt -i file2.txt` sets option `'i'` to a sequence of values `"file1.txt"` and `"file2.txt"` - `myapp -i file1.txt -i file2.txt` sets option `'i'` to a sequence of values `"file1.txt"` and `"file2.txt"`
- `myapp cmd abc -o` routes to command `cmd` (assuming it's an existing command) with parameter `abc` and sets option `'o'` without value - `myapp cmd abc -o` routes to command `cmd` (assuming it's a command) with parameter `abc` and sets option `'o'` without value
Additionally, argument parsing in **CliFx** aims to be as deterministic as possible, ideally yielding the same result regardless of the application configuration. Additionally, argument parsing in **CliFx** aims to be as deterministic as possible, ideally yielding the same result regardless of the application configuration.
In fact, the only context-sensitive part in the parser is the command name resolution, which needs to know the list of available commands in order to discern between arguments that correspond to command name and arguments which map as parameters. In fact, the only context-sensitive part in the parser is the command name resolution, which needs to know the list of available commands in order to discern them from parameters.
The parser's context-free nature has several implications on how it consumes arguments. The parser's context-free nature has several implications on how it consumes arguments.
For example, passing `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. 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"`. 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"`.
Because of these rules, order of arguments is semantically important and must always follow this pattern: These rules also make the order of arguments important — command line string is expected to follow this pattern:
```ini ```powershell
[directives] [command name] [parameters] [options] > myapp [...directives] [command] [...parameters] [...options]
``` ```
### Value conversion ### Value conversion
Parameters and options can have the following underlying types: Parameters and options can be bound to properties with the following underlying types:
- Standard types - Basic types
- Primitive types (`int`, `bool`, `double`, `ulong`, `char`, etc.) - Primitive types (`int`, `bool`, `double`, `ulong`, `char`, etc.)
- Date and time types (`DateTime`, `DateTimeOffset`, `TimeSpan`) - Date and time types (`DateTime`, `DateTimeOffset`, `TimeSpan`)
- Enum types (converted from either name or numeric value) - Enum types (converted from either name or numeric value)
@@ -272,7 +291,7 @@ public class FileSizeCalculatorCommand : ICommand
} }
``` ```
```sh ```powershell
> dotnet myapp.dll file1.bin file2.exe > dotnet myapp.dll file1.bin file2.exe
Total file size: 186368 bytes Total file size: 186368 bytes
@@ -298,7 +317,7 @@ public class FileSizeCalculatorCommand : ICommand
} }
``` ```
```sh ```powershell
> dotnet myapp.dll --files file1.bin file2.exe > dotnet myapp.dll --files file1.bin file2.exe
Total file size: 186368 bytes Total file size: 186368 bytes
@@ -354,10 +373,42 @@ public class SurfaceCalculatorCommand : ICommand
} }
``` ```
### Environment variables
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", IsRequired = true, EnvironmentVariable = "AUTH_TOKEN")]
public string AuthToken { get; init; }
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(AuthToken);
return default;
}
}
```
```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 Linux).
### Multiple commands ### 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 within each other, employing a multi-level hierarchical structure. 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. With **CliFx**, this is achieved by simply giving each command a unique name through the `[Command]` attribute.
Commands that have common name segments are considered to be hierarchically related, which affects how they're listed in the help text. Commands that have common name segments are considered to be hierarchically related, which affects how they're listed in the help text.
@@ -392,12 +443,12 @@ public class SubCommand : ICommand
} }
``` ```
Once configured, the user can execute a specific command by including its name in the passed arguments. Once configured, the user can execute a specific command by pre-pending its name to the passed arguments.
For example, running `dotnet myapp.dll cmd1 arg1 -p 42` will execute `FirstCommand` in the above example. For example, running `dotnet myapp.dll cmd1 arg1 -p 42` will execute `FirstCommand` in the above example.
Requesting help will show direct subcommands of the current command: Requesting help will show direct subcommands of the current command:
```sh ```powershell
> dotnet myapp.dll --help > dotnet myapp.dll --help
MyApp v1.0 MyApp v1.0
@@ -419,7 +470,7 @@ 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: The user can also refine their help request by querying it on a specific command:
```sh ```powershell
> dotnet myapp.dll cmd1 --help > dotnet myapp.dll cmd1 --help
USAGE USAGE
@@ -435,8 +486,9 @@ COMMANDS
You can run `dotnet myapp.dll cmd1 [command] --help` to show help on a specific command. You can run `dotnet myapp.dll cmd1 [command] --help` to show help on a specific command.
``` ```
> 💡 Defining a default (unnamed) command is not required. > **Note**:
If it's absent, running the application without specifying a command will just show the root level help text. > Defining a 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 ### Reporting errors
@@ -469,7 +521,7 @@ public class DivideCommand : ICommand
} }
``` ```
```sh ```powershell
> dotnet myapp.dll --dividend 10 --divisor 0 > dotnet myapp.dll --dividend 10 --divisor 0
Division by zero is not supported. Division by zero is not supported.
@@ -480,8 +532,9 @@ Division by zero is not supported.
133 133
``` ```
> ⚠️ Even though exit codes are represented by 32-bit integers in .NET, using values outside of 8-bit unsigned range will cause an overflow on Unix systems. > **Warning**:
To avoid unexpected results, use numbers between 1 and 255 for exit codes that indicate failure. > Even though exit codes are represented by 32-bit integers in .NET, using values outside 8-bit unsigned range will cause an overflow on Unix systems.
> To avoid unexpected results, use numbers between 1 and 255 for exit codes that indicate failure.
### Graceful cancellation ### Graceful cancellation
@@ -513,15 +566,16 @@ public class CancellableCommand : ICommand
} }
``` ```
> ⚠️ Forceful termination of a command can only be delayed once. > **Warning**:
If the user issues a second interrupt signal, the process will be killed immediately without waiting for graceful cancellation. > Forceful termination of a command can only be delayed once.
> If the user issues a second interrupt signal, the process will be killed immediately without waiting for graceful cancellation.
### Type activation ### Type activation
Because **CliFx** takes responsibility for the application's entire lifecycle, it needs to be capable of instantiating various user-defined types at runtime. Because **CliFx** takes responsibility for the application's entire lifecycle, it needs to be capable of instantiating various user-defined types at runtime.
To facilitate that, it uses an interface called `ITypeActivator` that determines how to create a new instance of a given type. To facilitate that, it uses an interface called `ITypeActivator` that determines how to create a new instance of a given type.
The default implementation of `ITypeActivator` only supports types that have public parameterless constructors, which is sufficient for majority of scenarios. The default implementation of `ITypeActivator` only supports types that have public parameterless constructors, which is sufficient for the majority of scenarios.
However, in some cases you may also want to define a custom initializer, for example when integrating with an external dependency container. However, in some cases you may also want to define a custom initializer, for example when integrating with an external dependency container.
The following example shows how to configure your application to use [`Microsoft.Extensions.DependencyInjection`](https://nuget.org/packages/Microsoft.Extensions.DependencyInjection) as the type activator in **CliFx**: The following example shows how to configure your application to use [`Microsoft.Extensions.DependencyInjection`](https://nuget.org/packages/Microsoft.Extensions.DependencyInjection) as the type activator in **CliFx**:
@@ -543,7 +597,7 @@ public static class Program
return await new CliApplicationBuilder() return await new CliApplicationBuilder()
.AddCommandsFromThisAssembly() .AddCommandsFromThisAssembly()
.UseTypeActivator(serviceProvider.GetService) .UseTypeActivator(serviceProvider)
.Build() .Build()
.RunAsync(); .RunAsync();
} }
@@ -596,7 +650,7 @@ public async Task ConcatCommand_executes_successfully()
// Act // Act
await command.ExecuteAsync(console); await command.ExecuteAsync(console);
var stdOut = console.ReadOutputString(); var stdOut = console.ReadOutputString();
// Assert // Assert
@@ -624,7 +678,7 @@ public async Task ConcatCommand_executes_successfully()
// Act // Act
await app.RunAsync(args, envVars); await app.RunAsync(args, envVars);
var stdOut = console.ReadOutputString(); var stdOut = console.ReadOutputString();
// Assert // Assert
@@ -640,7 +694,7 @@ 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. 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: This will cause the program to launch in a suspended state, waiting for debugger to be attached to the process:
```sh ```powershell
> dotnet myapp.dll [debug] cmd -o > dotnet myapp.dll [debug] cmd -o
Attach debugger to PID 3148 to continue. Attach debugger to PID 3148 to continue.
@@ -649,12 +703,12 @@ Attach debugger to PID 3148 to continue.
To run the application in preview mode, use the `[preview]` directive. 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:
```sh ```powershell
> dotnet myapp.dll [preview] cmd arg1 arg2 -o foo --option bar1 bar2 > dotnet myapp.dll [preview] cmd arg1 arg2 -o foo --option bar1 bar2
Command line: Command line:
cmd <arg1> <arg2> [-o foo] [--option bar1 bar2] cmd <arg1> <arg2> [-o foo] [--option bar1 bar2]
Environment: Environment:
FOO="123" FOO="123"
BAR="xyz" BAR="xyz"
@@ -670,38 +724,7 @@ var app = new CliApplicationBuilder()
.Build(); .Build();
``` ```
### Environment variables
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", IsRequired = true, EnvironmentVariable = "AUTH_TOKEN")]
public string AuthToken { get; init; }
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(AuthToken);
return default;
}
}
```
```sh
> $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 Linux).
## Etymology ## Etymology
**CliFx** is made out of "Cli" for "Command Line Interface" and "Fx" for "Framework". It's pronounced as "cliff ex". **CliFx** is made out of "Cli" for "Command Line Interface" and "Fx" for "Framework".
It's pronounced as "cliff ex".

BIN
logo.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB