26 Commits
2.2.2 ... 2.2.4

Author SHA1 Message Date
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
59 changed files with 696 additions and 269 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,17 @@
### 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) ### v2.2.2 (30-Jan-2022)
- Fixed an issue where `ConsoleWriter` and `ConsoleReader` were not properly thread-safe. - Fixed an issue where `ConsoleWriter` and `ConsoleReader` were not properly thread-safe.
@@ -51,7 +65,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,8 +2,6 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>net6.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
<CollectCoverage>true</CollectCoverage>
<CoverletOutputFormat>opencover</CoverletOutputFormat>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -12,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="1.4.1" PrivateAssets="all" />
<PackageReference Include="FluentAssertions" Version="6.3.0" /> <PackageReference Include="FluentAssertions" Version="6.6.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.0.1" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.1.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.3" 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

@@ -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
@@ -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
@@ -56,6 +80,54 @@ public class MyCommand : ICommand
Analyzer.Should().NotProduceDiagnostics(code); 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;
}";
// Act & assert
Analyzer.Should().NotProduceDiagnostics(code);
}
[Fact] [Fact]
public void Analyzer_does_not_report_an_error_if_an_option_does_not_have_a_converter() public void Analyzer_does_not_report_an_error_if_an_option_does_not_have_a_converter()
{ {

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
@@ -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

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
@@ -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
@@ -56,6 +81,54 @@ public class MyCommand : ICommand
Analyzer.Should().NotProduceDiagnostics(code); 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;
}";
// Act & assert
Analyzer.Should().NotProduceDiagnostics(code);
}
[Fact] [Fact]
public void Analyzer_does_not_report_an_error_if_a_parameter_does_not_have_a_converter() public void Analyzer_does_not_report_an_error_if_a_parameter_does_not_have_a_converter()
{ {

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
@@ -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

View File

@@ -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,11 +125,18 @@ internal class AnalyzerAssertions : ReferenceTypeAssertions<DiagnosticAnalyzer,
buffer.AppendLine("Produced diagnostics:"); buffer.AppendLine("Produced diagnostics:");
if (producedDiagnostics.Any())
{
foreach (var producedDiagnostic in producedDiagnostics) foreach (var producedDiagnostic in producedDiagnostics)
{ {
buffer.Append(" - "); buffer.Append(" - ");
buffer.Append(producedDiagnostic); 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

@@ -8,7 +8,9 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.0.1" 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)); .FirstOrDefault(a => a.AttributeClass?.DisplayNameMatches(SymbolNames.CliFxCommandOptionAttribute) == true);
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,16 +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);
return attribute is not null
? FromAttribute(attribute)
: null;
} }
public static bool IsOptionProperty(IPropertySymbol property) => public static bool IsOptionProperty(IPropertySymbol property) =>

View File

@@ -5,8 +5,10 @@ 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; }
@@ -18,12 +20,14 @@ internal partial class CommandParameterSymbol
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, bool? isRequired,
ITypeSymbol? converterType, ITypeSymbol? converterType,
IReadOnlyList<ITypeSymbol> validatorTypes) IReadOnlyList<ITypeSymbol> validatorTypes)
{ {
Property = property;
Order = order; Order = order;
Name = name; Name = name;
IsRequired = isRequired; IsRequired = isRequired;
@@ -34,13 +38,16 @@ 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)); .FirstOrDefault(a => a.AttributeClass?.DisplayNameMatches(SymbolNames.CliFxCommandParameterAttribute) == true);
private static CommandParameterSymbol FromAttribute(AttributeData attribute) public static CommandParameterSymbol? TryResolve(IPropertySymbol property)
{ {
var attribute = TryGetParameterAttribute(property);
if (attribute is null)
return null;
var order = (int)attribute var order = (int)attribute
.ConstructorArguments .ConstructorArguments
.Select(a => a.Value) .Select(a => a.Value)
@@ -73,16 +80,7 @@ internal partial class CommandParameterSymbol
.Cast<ITypeSymbol>() .Cast<ITypeSymbol>()
.ToArray(); .ToArray();
return new CommandParameterSymbol(order, name, isRequired, converter, validators); return new CommandParameterSymbol(property, order, name, isRequired, converter, validators);
}
public static CommandParameterSymbol? TryResolve(IPropertySymbol property)
{
var attribute = TryGetParameterAttribute(property);
return attribute is not null
? FromAttribute(attribute)
: null;
} }
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

@@ -13,7 +13,8 @@ public class ParameterMustBeLastIfNonRequiredAnalyzer : AnalyzerBase
public ParameterMustBeLastIfNonRequiredAnalyzer() public ParameterMustBeLastIfNonRequiredAnalyzer()
: base( : base(
"Parameters marked as non-required must be the last in order", "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).") "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}`.")
{ {
} }
@@ -47,7 +48,12 @@ public class ParameterMustBeLastIfNonRequiredAnalyzer : 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

@@ -13,17 +13,11 @@ public class ParameterMustBeLastIfNonScalarAnalyzer : AnalyzerBase
public ParameterMustBeLastIfNonScalarAnalyzer() public ParameterMustBeLastIfNonScalarAnalyzer()
: base( : base(
"Parameters of non-scalar types must be the 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 the 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

@@ -13,7 +13,8 @@ public class ParameterMustBeSingleIfNonRequiredAnalyzer : AnalyzerBase
public ParameterMustBeSingleIfNonRequiredAnalyzer() public ParameterMustBeSingleIfNonRequiredAnalyzer()
: base( : base(
"Parameters marked as non-required are limited to one per command", "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.") "This parameter is non-required so it must be the only such parameter in the command. " +
"Property bound to another non-required parameter: `{0}`.")
{ {
} }
@@ -47,7 +48,12 @@ public class ParameterMustBeSingleIfNonRequiredAnalyzer : AnalyzerBase
if (otherParameter.IsRequired == false) if (otherParameter.IsRequired == false)
{ {
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation())); context.ReportDiagnostic(
CreateDiagnostic(
propertyDeclaration.Identifier.GetLocation(),
otherProperty.Name
)
);
} }
} }
} }

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.8.0" />
<PackageReference Include="McMaster.Extensions.CommandLineUtils" Version="4.0.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,8 +2,6 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>net6.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
<CollectCoverage>true</CollectCoverage>
<CoverletOutputFormat>opencover</CoverletOutputFormat>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -12,14 +10,14 @@
<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.4.0" /> <PackageReference Include="CliWrap" Version="3.4.3" />
<PackageReference Include="FluentAssertions" Version="6.3.0" /> <PackageReference Include="FluentAssertions" Version="6.6.0" />
<PackageReference Include="GitHubActionsTestLogger" Version="1.2.0" /> <PackageReference Include="GitHubActionsTestLogger" Version="1.4.1" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.0.1" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.1.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.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.3" 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;
@@ -139,6 +140,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

@@ -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

@@ -33,10 +33,8 @@
<!-- 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/Microsoft.CodeAnalysis.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<None Include="../CliFx.Analyzers/bin/$(Configuration)/netstandard2.0/Microsoft.CodeAnalysis.CSharp.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.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.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.Memory.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />

View File

@@ -278,7 +278,7 @@ internal class CommandBinder
"Missing required parameter(s):" + "Missing required parameter(s):" +
Environment.NewLine + Environment.NewLine +
remainingRequiredParameterSchemas remainingRequiredParameterSchemas
.Select(o => o.GetFormattedIdentifier()) .Select(p => p.GetFormattedIdentifier())
.JoinToString(" ") .JoinToString(" ")
); );
} }

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

View File

@@ -53,10 +53,8 @@ public partial class ConsoleReader : StreamReader
/// <inheritdoc /> /// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)] [ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override int ReadBlock(char[] buffer, int index, int count) public override int ReadBlock(char[] buffer, int index, int count) =>
{ base.ReadBlock(buffer, index, count);
return base.ReadBlock(buffer, index, count);
}
/// <inheritdoc /> /// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)] [ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
@@ -68,35 +66,27 @@ public partial class ConsoleReader : StreamReader
/// <inheritdoc /> /// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)] [ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override Task<int> ReadAsync(char[] buffer, int index, int count) public override Task<int> ReadAsync(char[] buffer, int index, int count) =>
{
// Must be non-async to work with locks // Must be non-async to work with locks
return Task.FromResult(Read(buffer, index, count)); Task.FromResult(Read(buffer, index, count));
}
/// <inheritdoc /> /// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)] [ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count) public override Task<int> ReadBlockAsync(char[] buffer, int index, int count) =>
{
// Must be non-async to work with locks // Must be non-async to work with locks
return Task.FromResult(ReadBlock(buffer, index, count)); Task.FromResult(ReadBlock(buffer, index, count));
}
/// <inheritdoc /> /// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)] [ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override Task<string?> ReadLineAsync() public override Task<string?> ReadLineAsync() =>
{
// Must be non-async to work with locks // Must be non-async to work with locks
return Task.FromResult(ReadLine()); Task.FromResult(ReadLine());
}
/// <inheritdoc /> /// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)] [ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]
public override Task<string> ReadToEndAsync() public override Task<string> ReadToEndAsync() =>
{
// Must be non-async to work with locks // Must be non-async to work with locks
return Task.FromResult(ReadToEnd()); Task.FromResult(ReadToEnd());
}
/// <inheritdoc /> /// <inheritdoc />
[ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)] [ExcludeFromCodeCoverage, MethodImpl(MethodImplOptions.Synchronized)]

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; }
@@ -91,9 +93,18 @@ public class FakeConsole : IConsole, IDisposable
} }
/// <inheritdoc /> /// <inheritdoc />
public void ReadKey(bool intercept = false) 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 /> /// <inheritdoc />
public virtual void Dispose() => _cancellationTokenSource.Dispose(); public virtual void Dispose() => _cancellationTokenSource.Dispose();

View File

@@ -91,7 +91,7 @@ public interface IConsole
/// <summary> /// <summary>
/// Obtains the next character or function key pressed by the user. /// Obtains the next character or function key pressed by the user.
/// </summary> /// </summary>
void ReadKey(bool intercept = false); ConsoleKeyInfo ReadKey(bool intercept = false);
} }
/// <summary> /// <summary>

View File

@@ -94,7 +94,7 @@ public class SystemConsole : IConsole, IDisposable
public void Clear() => Console.Clear(); public void Clear() => Console.Clear();
/// <inheritdoc /> /// <inheritdoc />
public void ReadKey(bool intercept = false) => Console.ReadKey(intercept); public ConsoleKeyInfo ReadKey(bool intercept = false) => Console.ReadKey(intercept);
/// <inheritdoc /> /// <inheritdoc />
public void Dispose() public void Dispose()

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,52 +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,7 +1,7 @@
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<Version>2.2.2</Version> <Version>2.2.4</Version>
<Company>Tyrrrz</Company> <Company>Tyrrrz</Company>
<Copyright>Copyright (C) Oleksii Holub</Copyright> <Copyright>Copyright (C) Oleksii Holub</Copyright>
<LangVersion>latest</LangVersion> <LangVersion>latest</LangVersion>

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>

View File

@@ -1,22 +1,33 @@
# 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
## 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
@@ -34,7 +45,7 @@ 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

BIN
logo.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB