mirror of
https://github.com/Tyrrrz/CliFx.git
synced 2025-10-25 15:19:17 +00:00
Compare commits
20 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59373eadc2 | ||
|
|
ed3e4f471e | ||
|
|
41cb8647b5 | ||
|
|
c7015181e1 | ||
|
|
86742755e8 | ||
|
|
33f95d941d | ||
|
|
1328592cb5 | ||
|
|
0711b863ea | ||
|
|
a2f5cd54be | ||
|
|
7836ec610f | ||
|
|
2e489927eb | ||
|
|
02e8d19e48 | ||
|
|
eb7107fb0a | ||
|
|
a396009b62 | ||
|
|
1d9c7e942c | ||
|
|
0f3abb9db4 | ||
|
|
896482821c | ||
|
|
aa3094ee54 | ||
|
|
712580e3d7 | ||
|
|
c08102f85f |
21
Changelog.md
21
Changelog.md
@@ -1,3 +1,20 @@
|
||||
### 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))
|
||||
@@ -42,7 +59,7 @@
|
||||
### v2.0 (21-Mar-2021)
|
||||
|
||||
> Note: this major release includes many breaking changes.
|
||||
Please refer to the readme to find updated instructions and usage examples.
|
||||
> Please refer to the readme to find updated instructions and usage examples.
|
||||
|
||||
- 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.
|
||||
@@ -123,4 +140,4 @@ Please refer to the readme to find updated instructions and usage examples.
|
||||
|
||||
- Changed `IConsole` interface (and as a result, `SystemConsole` and `VirtualConsole`) to support writing binary data. Instead of `TextReader`/`TextWriter` instances, the streams are now exposed as `StreamReader`/`StreamWriter` which provide the `BaseStream` property that allows raw access. Existing usages inside commands should remain the same because `StreamReader`/`StreamWriter` are compatible with their base classes `TextReader`/`TextWriter`, but if you were using `VirtualConsole` in tests, you may have to update it to the new API. Refer to the readme for more info.
|
||||
- Changed argument binding behavior so that an error is produced if the user provides an argument that doesn't match with any parameter or option. This is done in order to improve user experience, as otherwise the user may make a typo without knowing that their input wasn't taken into account.
|
||||
- Changed argument binding behavior so that options can be set to multiple argument values while specifying them with mixed naming. For example, `--option value1 -o value2 --option value3` would result in the option being set to corresponding three values, assuming `--option` and `-o` match with the same option.
|
||||
- Changed argument binding behavior so that options can be set to multiple argument values while specifying them with mixed naming. For example, `--option value1 -o value2 --option value3` would result in the option being set to corresponding three values, assuming `--option` and `-o` match with the same option.
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<CollectCoverage>true</CollectCoverage>
|
||||
<CoverletOutputFormat>opencover</CoverletOutputFormat>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -12,13 +10,13 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Basic.Reference.Assemblies" Version="1.2.4" />
|
||||
<PackageReference Include="GitHubActionsTestLogger" Version="1.2.0" />
|
||||
<PackageReference Include="FluentAssertions" Version="6.3.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.0.1" />
|
||||
<PackageReference Include="GitHubActionsTestLogger" Version="1.3.0" PrivateAssets="all" />
|
||||
<PackageReference Include="FluentAssertions" Version="6.5.1" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.1.0" />
|
||||
<PackageReference Include="xunit" Version="2.4.1" />
|
||||
<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>
|
||||
|
||||
@@ -33,7 +33,31 @@ public class MyCommand : ICommand
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Analyzer_does_not_report_an_error_if_the_specified_option_converter_derives_from_BindingConverter()
|
||||
public void Analyzer_reports_an_error_if_the_specified_option_converter_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_the_specified_option_converter_derives_from_a_compatible_BindingConverter()
|
||||
{
|
||||
// Arrange
|
||||
// language=cs
|
||||
|
||||
@@ -33,7 +33,31 @@ public class MyCommand : ICommand
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Analyzer_does_not_report_an_error_if_all_specified_option_validators_derive_from_BindingValidator()
|
||||
public void Analyzer_reports_an_error_if_one_of_the_specified_option_validators_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_each_specified_option_validator_derives_from_a_compatible_BindingValidator()
|
||||
{
|
||||
// Arrange
|
||||
// language=cs
|
||||
|
||||
@@ -33,7 +33,32 @@ public class MyCommand : ICommand
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Analyzer_does_not_report_an_error_if_the_specified_parameter_converter_derives_from_BindingConverter()
|
||||
public void Analyzer_reports_an_error_if_the_specified_parameter_converter_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_the_specified_parameter_converter_derives_from_a_compatible_BindingConverter()
|
||||
{
|
||||
// Arrange
|
||||
// language=cs
|
||||
|
||||
@@ -33,7 +33,31 @@ public class MyCommand : ICommand
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Analyzer_does_not_report_an_error_if_all_specified_parameter_validators_derive_from_BindingValidator()
|
||||
public void Analyzer_reports_an_error_if_one_of_the_specified_parameter_validators_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_each_specified_parameter_validator_derives_from_a_compatible_BindingValidator()
|
||||
{
|
||||
// Arrange
|
||||
// language=cs
|
||||
|
||||
@@ -57,7 +57,7 @@ internal class AnalyzerAssertions : ReferenceTypeAssertions<DiagnosticAnalyzer,
|
||||
// Compile the code to IL
|
||||
var compilation = CSharpCompilation.Create(
|
||||
"CliFxTests_DynamicAssembly_" + Guid.NewGuid(),
|
||||
new[] {ast},
|
||||
new[] { ast },
|
||||
ReferenceAssemblies.Net50
|
||||
.Append(MetadataReference.CreateFromFile(typeof(ICommand).Assembly.Location)),
|
||||
// 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 producedDiagnosticIds = producedDiagnostics.Select(d => d.Id).Distinct().ToArray();
|
||||
|
||||
var result =
|
||||
var isSuccessfulAssertion =
|
||||
expectedDiagnosticIds.Intersect(producedDiagnosticIds).Count() ==
|
||||
expectedDiagnosticIds.Length;
|
||||
|
||||
Execute.Assertion.ForCondition(result).FailWith(() =>
|
||||
Execute.Assertion.ForCondition(isSuccessfulAssertion).FailWith(() =>
|
||||
{
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
@@ -125,10 +125,17 @@ internal class AnalyzerAssertions : ReferenceTypeAssertions<DiagnosticAnalyzer,
|
||||
|
||||
buffer.AppendLine("Produced diagnostics:");
|
||||
|
||||
foreach (var producedDiagnostic in producedDiagnostics)
|
||||
if (producedDiagnostics.Any())
|
||||
{
|
||||
buffer.Append(" - ");
|
||||
buffer.Append(producedDiagnostic);
|
||||
foreach (var producedDiagnostic in producedDiagnostics)
|
||||
{
|
||||
buffer.Append(" - ");
|
||||
buffer.Append(producedDiagnostic);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
buffer.AppendLine(" < none >");
|
||||
}
|
||||
|
||||
return new FailReason(buffer.ToString());
|
||||
@@ -138,10 +145,9 @@ internal class AnalyzerAssertions : ReferenceTypeAssertions<DiagnosticAnalyzer,
|
||||
public void NotProduceDiagnostics(string sourceCode)
|
||||
{
|
||||
var producedDiagnostics = GetProducedDiagnostics(sourceCode);
|
||||
var isSuccessfulAssertion = !producedDiagnostics.Any();
|
||||
|
||||
var result = !producedDiagnostics.Any();
|
||||
|
||||
Execute.Assertion.ForCondition(result).FailWith(() =>
|
||||
Execute.Assertion.ForCondition(isSuccessfulAssertion).FailWith(() =>
|
||||
{
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
|
||||
@@ -28,8 +28,8 @@ public abstract class AnalyzerBase : DiagnosticAnalyzer
|
||||
SupportedDiagnostics = ImmutableArray.Create(SupportedDiagnostic);
|
||||
}
|
||||
|
||||
protected Diagnostic CreateDiagnostic(Location location) =>
|
||||
Diagnostic.Create(SupportedDiagnostic, location);
|
||||
protected Diagnostic CreateDiagnostic(Location location, params object?[]? messageArgs) =>
|
||||
Diagnostic.Create(SupportedDiagnostic, location, messageArgs);
|
||||
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
|
||||
@@ -2,12 +2,13 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
|
||||
<Nullable>annotations</Nullable>
|
||||
<NoWarn>$(NoWarn);RS1025;RS1026</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.0.1" PrivateAssets="all" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.1.0" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -30,18 +30,20 @@ public class CommandMustBeAnnotatedAnalyzer : AnalyzerBase
|
||||
|
||||
var implementsCommandInterface = type
|
||||
.AllInterfaces
|
||||
.Any(s => s.DisplayNameMatches(SymbolNames.CliFxCommandInterface));
|
||||
.Any(i => i.DisplayNameMatches(SymbolNames.CliFxCommandInterface));
|
||||
|
||||
var hasCommandAttribute = type
|
||||
.GetAttributes()
|
||||
.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,
|
||||
// then it's very likely a user error.
|
||||
if (implementsCommandInterface && !hasCommandAttribute)
|
||||
{
|
||||
context.ReportDiagnostic(CreateDiagnostic(classDeclaration.GetLocation()));
|
||||
context.ReportDiagnostic(
|
||||
CreateDiagnostic(classDeclaration.Identifier.GetLocation())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,17 +25,19 @@ public class CommandMustImplementInterfaceAnalyzer : AnalyzerBase
|
||||
var hasCommandAttribute = type
|
||||
.GetAttributes()
|
||||
.Select(a => a.AttributeClass)
|
||||
.Any(s => s.DisplayNameMatches(SymbolNames.CliFxCommandAttribute));
|
||||
.Any(c => c.DisplayNameMatches(SymbolNames.CliFxCommandAttribute));
|
||||
|
||||
var implementsCommandInterface = type
|
||||
.AllInterfaces
|
||||
.Any(s => s.DisplayNameMatches(SymbolNames.CliFxCommandInterface));
|
||||
.Any(i => i.DisplayNameMatches(SymbolNames.CliFxCommandInterface));
|
||||
|
||||
// If the attribute is present, but the interface is not implemented,
|
||||
// it's very likely a user error.
|
||||
if (hasCommandAttribute && !implementsCommandInterface)
|
||||
{
|
||||
context.ReportDiagnostic(CreateDiagnostic(classDeclaration.GetLocation()));
|
||||
context.ReportDiagnostic(
|
||||
CreateDiagnostic(classDeclaration.Identifier.GetLocation())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using CliFx.Analyzers.Utils.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace CliFx.Analyzers.ObjectModel;
|
||||
|
||||
|
||||
@@ -7,8 +7,6 @@ internal static class SymbolNames
|
||||
public const string CliFxCommandParameterAttribute = "CliFx.Attributes.CommandParameterAttribute";
|
||||
public const string CliFxCommandOptionAttribute = "CliFx.Attributes.CommandOptionAttribute";
|
||||
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 CliFxBindingValidatorInterface = "CliFx.Extensibility.IBindingValidator";
|
||||
public const string CliFxBindingValidatorClass = "CliFx.Extensibility.BindingValidator<T>";
|
||||
}
|
||||
@@ -34,11 +34,13 @@ public class OptionMustBeInsideCommandAnalyzer : AnalyzerBase
|
||||
var isInsideCommand = property
|
||||
.ContainingType
|
||||
.AllInterfaces
|
||||
.Any(s => s.DisplayNameMatches(SymbolNames.CliFxCommandInterface));
|
||||
.Any(i => i.DisplayNameMatches(SymbolNames.CliFxCommandInterface));
|
||||
|
||||
if (!isInsideCommand)
|
||||
{
|
||||
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation()));
|
||||
context.ReportDiagnostic(
|
||||
CreateDiagnostic(propertyDeclaration.Identifier.GetLocation())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,9 @@ public class OptionMustHaveNameOrShortNameAnalyzer : AnalyzerBase
|
||||
|
||||
if (string.IsNullOrWhiteSpace(option.Name) && option.ShortName is null)
|
||||
{
|
||||
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation()));
|
||||
context.ReportDiagnostic(
|
||||
CreateDiagnostic(propertyDeclaration.Identifier.GetLocation())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,8 @@ public class OptionMustHaveUniqueNameAnalyzer : AnalyzerBase
|
||||
public OptionMustHaveUniqueNameAnalyzer()
|
||||
: base(
|
||||
"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}'.")
|
||||
{
|
||||
}
|
||||
|
||||
@@ -51,7 +52,12 @@ public class OptionMustHaveUniqueNameAnalyzer : AnalyzerBase
|
||||
|
||||
if (string.Equals(option.Name, otherOption.Name, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation()));
|
||||
context.ReportDiagnostic(
|
||||
CreateDiagnostic(
|
||||
propertyDeclaration.Identifier.GetLocation(),
|
||||
option.Name
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,8 @@ public class OptionMustHaveUniqueShortNameAnalyzer : AnalyzerBase
|
||||
public OptionMustHaveUniqueShortNameAnalyzer()
|
||||
: base(
|
||||
"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}'.")
|
||||
{
|
||||
}
|
||||
|
||||
@@ -50,7 +51,12 @@ public class OptionMustHaveUniqueShortNameAnalyzer : AnalyzerBase
|
||||
|
||||
if (option.ShortName == otherOption.ShortName)
|
||||
{
|
||||
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation()));
|
||||
context.ReportDiagnostic(
|
||||
CreateDiagnostic(
|
||||
propertyDeclaration.Identifier.GetLocation(),
|
||||
option.ShortName
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ public class OptionMustHaveValidConverterAnalyzer : AnalyzerBase
|
||||
public OptionMustHaveValidConverterAnalyzer()
|
||||
: base(
|
||||
$"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,19 @@ public class OptionMustHaveValidConverterAnalyzer : AnalyzerBase
|
||||
if (option.ConverterType is null)
|
||||
return;
|
||||
|
||||
// We check against an internal interface because checking against a generic class is a pain
|
||||
var converterImplementsInterface = option
|
||||
var converterValueType = option
|
||||
.ConverterType
|
||||
.AllInterfaces
|
||||
.Any(s => s.DisplayNameMatches(SymbolNames.CliFxBindingConverterInterface));
|
||||
.GetBaseTypes()
|
||||
.FirstOrDefault(t => t.ConstructedFrom.DisplayNameMatches(SymbolNames.CliFxBindingConverterClass))?
|
||||
.TypeArguments
|
||||
.FirstOrDefault();
|
||||
|
||||
if (!converterImplementsInterface)
|
||||
// Value returned by the converter must be assignable to the property type
|
||||
if (converterValueType is null || !property.Type.IsAssignableFrom(converterValueType))
|
||||
{
|
||||
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation()));
|
||||
context.ReportDiagnostic(
|
||||
CreateDiagnostic(propertyDeclaration.Identifier.GetLocation())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,8 @@ public class OptionMustHaveValidNameAnalyzer : AnalyzerBase
|
||||
public OptionMustHaveValidNameAnalyzer()
|
||||
: base(
|
||||
"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]))
|
||||
{
|
||||
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation()));
|
||||
context.ReportDiagnostic(
|
||||
CreateDiagnostic(
|
||||
propertyDeclaration.Identifier.GetLocation(),
|
||||
option.Name
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,8 @@ public class OptionMustHaveValidShortNameAnalyzer : AnalyzerBase
|
||||
public OptionMustHaveValidShortNameAnalyzer()
|
||||
: base(
|
||||
"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))
|
||||
{
|
||||
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation()));
|
||||
context.ReportDiagnostic(
|
||||
CreateDiagnostic(
|
||||
propertyDeclaration.Identifier.GetLocation(),
|
||||
option.ShortName
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ public class OptionMustHaveValidValidatorsAnalyzer : AnalyzerBase
|
||||
public OptionMustHaveValidValidatorsAnalyzer()
|
||||
: base(
|
||||
$"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,18 @@ public class OptionMustHaveValidValidatorsAnalyzer : AnalyzerBase
|
||||
|
||||
foreach (var validatorType in option.ValidatorTypes)
|
||||
{
|
||||
// We check against an internal interface because checking against a generic class is a pain
|
||||
var validatorImplementsInterface = validatorType
|
||||
.AllInterfaces
|
||||
.Any(s => s.DisplayNameMatches(SymbolNames.CliFxBindingValidatorInterface));
|
||||
var validatorValueType = validatorType
|
||||
.GetBaseTypes()
|
||||
.FirstOrDefault(t => t.ConstructedFrom.DisplayNameMatches(SymbolNames.CliFxBindingValidatorClass))?
|
||||
.TypeArguments
|
||||
.FirstOrDefault();
|
||||
|
||||
if (!validatorImplementsInterface)
|
||||
// Value passed to the validator must be assignable from the property type
|
||||
if (validatorValueType is null || !validatorValueType.IsAssignableFrom(property.Type))
|
||||
{
|
||||
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation()));
|
||||
context.ReportDiagnostic(
|
||||
CreateDiagnostic(propertyDeclaration.Identifier.GetLocation())
|
||||
);
|
||||
|
||||
// No need to report multiple identical diagnostics on the same node
|
||||
break;
|
||||
|
||||
@@ -34,11 +34,13 @@ public class ParameterMustBeInsideCommandAnalyzer : AnalyzerBase
|
||||
var isInsideCommand = property
|
||||
.ContainingType
|
||||
.AllInterfaces
|
||||
.Any(s => s.DisplayNameMatches(SymbolNames.CliFxCommandInterface));
|
||||
.Any(i => i.DisplayNameMatches(SymbolNames.CliFxCommandInterface));
|
||||
|
||||
if (!isInsideCommand)
|
||||
{
|
||||
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation()));
|
||||
context.ReportDiagnostic(
|
||||
CreateDiagnostic(propertyDeclaration.Identifier.GetLocation())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -47,7 +47,9 @@ public class ParameterMustBeLastIfNonRequiredAnalyzer : AnalyzerBase
|
||||
|
||||
if (otherParameter.Order > parameter.Order)
|
||||
{
|
||||
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation()));
|
||||
context.ReportDiagnostic(
|
||||
CreateDiagnostic(propertyDeclaration.Identifier.GetLocation())
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ public class ParameterMustBeLastIfNonScalarAnalyzer : AnalyzerBase
|
||||
type.DisplayNameMatches("System.String") ||
|
||||
!type.AllInterfaces
|
||||
.Select(i => i.ConstructedFrom)
|
||||
.Any(s => s.DisplayNameMatches("System.Collections.Generic.IEnumerable<T>"));
|
||||
.Any(t => t.DisplayNameMatches("System.Collections.Generic.IEnumerable<T>"));
|
||||
|
||||
private void Analyze(
|
||||
SyntaxNodeAnalysisContext context,
|
||||
@@ -54,7 +54,9 @@ public class ParameterMustBeLastIfNonScalarAnalyzer : AnalyzerBase
|
||||
|
||||
if (otherParameter.Order > parameter.Order)
|
||||
{
|
||||
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation()));
|
||||
context.ReportDiagnostic(
|
||||
CreateDiagnostic(propertyDeclaration.Identifier.GetLocation())
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,7 +47,9 @@ public class ParameterMustBeSingleIfNonRequiredAnalyzer : AnalyzerBase
|
||||
|
||||
if (otherParameter.IsRequired == false)
|
||||
{
|
||||
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation()));
|
||||
context.ReportDiagnostic(
|
||||
CreateDiagnostic(propertyDeclaration.Identifier.GetLocation())
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ public class ParameterMustBeSingleIfNonScalarAnalyzer : AnalyzerBase
|
||||
type.DisplayNameMatches("System.String") ||
|
||||
!type.AllInterfaces
|
||||
.Select(i => i.ConstructedFrom)
|
||||
.Any(s => s.DisplayNameMatches("System.Collections.Generic.IEnumerable<T>"));
|
||||
.Any(t => t.DisplayNameMatches("System.Collections.Generic.IEnumerable<T>"));
|
||||
|
||||
private void Analyze(
|
||||
SyntaxNodeAnalysisContext context,
|
||||
@@ -52,7 +52,9 @@ public class ParameterMustBeSingleIfNonScalarAnalyzer : AnalyzerBase
|
||||
|
||||
if (!IsScalar(otherProperty.Type))
|
||||
{
|
||||
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation()));
|
||||
context.ReportDiagnostic(
|
||||
CreateDiagnostic(propertyDeclaration.Identifier.GetLocation())
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,8 @@ public class ParameterMustHaveUniqueNameAnalyzer : AnalyzerBase
|
||||
public ParameterMustHaveUniqueNameAnalyzer()
|
||||
: base(
|
||||
"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}'.")
|
||||
{
|
||||
}
|
||||
|
||||
@@ -51,7 +52,12 @@ public class ParameterMustHaveUniqueNameAnalyzer : AnalyzerBase
|
||||
|
||||
if (string.Equals(parameter.Name, otherParameter.Name, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation()));
|
||||
context.ReportDiagnostic(
|
||||
CreateDiagnostic(
|
||||
propertyDeclaration.Identifier.GetLocation(),
|
||||
parameter.Name
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,8 @@ public class ParameterMustHaveUniqueOrderAnalyzer : AnalyzerBase
|
||||
public ParameterMustHaveUniqueOrderAnalyzer()
|
||||
: base(
|
||||
"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}.")
|
||||
{
|
||||
}
|
||||
|
||||
@@ -44,7 +45,12 @@ public class ParameterMustHaveUniqueOrderAnalyzer : AnalyzerBase
|
||||
|
||||
if (parameter.Order == otherParameter.Order)
|
||||
{
|
||||
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation()));
|
||||
context.ReportDiagnostic(
|
||||
CreateDiagnostic(
|
||||
propertyDeclaration.Identifier.GetLocation(),
|
||||
parameter.Order
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ public class ParameterMustHaveValidConverterAnalyzer : AnalyzerBase
|
||||
public ParameterMustHaveValidConverterAnalyzer()
|
||||
: base(
|
||||
$"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,19 @@ public class ParameterMustHaveValidConverterAnalyzer : AnalyzerBase
|
||||
if (parameter.ConverterType is null)
|
||||
return;
|
||||
|
||||
// We check against an internal interface because checking against a generic class is a pain
|
||||
var converterImplementsInterface = parameter
|
||||
var converterValueType = parameter
|
||||
.ConverterType
|
||||
.AllInterfaces
|
||||
.Any(s => s.DisplayNameMatches(SymbolNames.CliFxBindingConverterInterface));
|
||||
.GetBaseTypes()
|
||||
.FirstOrDefault(t => t.ConstructedFrom.DisplayNameMatches(SymbolNames.CliFxBindingConverterClass))?
|
||||
.TypeArguments
|
||||
.FirstOrDefault();
|
||||
|
||||
if (!converterImplementsInterface)
|
||||
// Value returned by the converter must be assignable to the property type
|
||||
if (converterValueType is null || !property.Type.IsAssignableFrom(converterValueType))
|
||||
{
|
||||
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation()));
|
||||
context.ReportDiagnostic(
|
||||
CreateDiagnostic(propertyDeclaration.Identifier.GetLocation())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ public class ParameterMustHaveValidValidatorsAnalyzer : AnalyzerBase
|
||||
public ParameterMustHaveValidValidatorsAnalyzer()
|
||||
: base(
|
||||
$"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,18 @@ public class ParameterMustHaveValidValidatorsAnalyzer : AnalyzerBase
|
||||
|
||||
foreach (var validatorType in parameter.ValidatorTypes)
|
||||
{
|
||||
// We check against an internal interface because checking against a generic class is a pain
|
||||
var validatorImplementsInterface = validatorType
|
||||
.AllInterfaces
|
||||
.Any(s => s.DisplayNameMatches(SymbolNames.CliFxBindingValidatorInterface));
|
||||
var validatorValueType = validatorType
|
||||
.GetBaseTypes()
|
||||
.FirstOrDefault(t => t.ConstructedFrom.DisplayNameMatches(SymbolNames.CliFxBindingValidatorClass))?
|
||||
.TypeArguments
|
||||
.FirstOrDefault();
|
||||
|
||||
if (!validatorImplementsInterface)
|
||||
// Value passed to the validator must be assignable from the property type
|
||||
if (validatorValueType is null || !validatorValueType.IsAssignableFrom(property.Type))
|
||||
{
|
||||
context.ReportDiagnostic(CreateDiagnostic(propertyDeclaration.GetLocation()));
|
||||
context.ReportDiagnostic(
|
||||
CreateDiagnostic(propertyDeclaration.Identifier.GetLocation())
|
||||
);
|
||||
|
||||
// No need to report multiple identical diagnostics on the same node
|
||||
break;
|
||||
|
||||
@@ -65,7 +65,9 @@ public class SystemConsoleShouldBeAvoidedAnalyzer : AnalyzerBase
|
||||
|
||||
if (isConsoleInterfaceAvailable)
|
||||
{
|
||||
context.ReportDiagnostic(CreateDiagnostic(systemConsoleMemberAccess.GetLocation()));
|
||||
context.ReportDiagnostic(
|
||||
CreateDiagnostic(systemConsoleMemberAccess.GetLocation())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
@@ -16,6 +18,22 @@ internal static class RoslynExtensions
|
||||
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 bool IsAssignableFrom(this ITypeSymbol target, ITypeSymbol source) =>
|
||||
SymbolEqualityComparer.Default.Equals(target, source) ||
|
||||
source.GetBaseTypes().Contains(target, SymbolEqualityComparer.Default) ||
|
||||
source.AllInterfaces.Contains(target, SymbolEqualityComparer.Default);
|
||||
|
||||
public static void HandleClassDeclaration(
|
||||
this AnalysisContext analysisContext,
|
||||
Action<SyntaxNodeAnalysisContext, ClassDeclarationSyntax, ITypeSymbol> analyze)
|
||||
|
||||
@@ -8,9 +8,9 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="BenchmarkDotNet" Version="0.13.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="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="System.CommandLine" Version="2.0.0-beta1.20574.7" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<CollectCoverage>true</CollectCoverage>
|
||||
<CoverletOutputFormat>opencover</CoverletOutputFormat>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -12,14 +10,14 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Basic.Reference.Assemblies" Version="1.2.4" />
|
||||
<PackageReference Include="CliWrap" Version="3.4.0" />
|
||||
<PackageReference Include="FluentAssertions" Version="6.3.0" />
|
||||
<PackageReference Include="GitHubActionsTestLogger" Version="1.2.0" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.0.1" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
|
||||
<PackageReference Include="CliWrap" Version="3.4.1" />
|
||||
<PackageReference Include="FluentAssertions" Version="6.5.1" />
|
||||
<PackageReference Include="GitHubActionsTestLogger" Version="1.3.0" PrivateAssets="all" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.1.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0" />
|
||||
<PackageReference Include="xunit" Version="2.4.1" />
|
||||
<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>
|
||||
|
||||
@@ -5,6 +5,7 @@ using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx.Infrastructure;
|
||||
using CliFx.Tests.Utils;
|
||||
using CliFx.Tests.Utils.Extensions;
|
||||
using CliWrap;
|
||||
using CliWrap.Buffered;
|
||||
using FluentAssertions;
|
||||
@@ -139,6 +140,53 @@ public class Command : ICommand
|
||||
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]
|
||||
public void Console_does_not_emit_preamble_when_used_with_encoding_that_has_it()
|
||||
{
|
||||
|
||||
@@ -112,7 +112,7 @@ public class CliApplication
|
||||
// Activate command instance
|
||||
var commandInstance = commandSchema == FallbackDefaultCommand.Schema
|
||||
? new FallbackDefaultCommand() // bypass activator
|
||||
: (ICommand) _typeActivator.CreateInstance(commandSchema.Type);
|
||||
: (ICommand)_typeActivator.CreateInstance(commandSchema.Type);
|
||||
|
||||
// Assemble help context
|
||||
var helpContext = new HelpContext(
|
||||
@@ -176,7 +176,7 @@ public class CliApplication
|
||||
{
|
||||
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.
|
||||
_console.ResetColor();
|
||||
|
||||
|
||||
@@ -35,6 +35,16 @@
|
||||
<ItemGroup>
|
||||
<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/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.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>
|
||||
|
||||
</Project>
|
||||
@@ -27,7 +27,7 @@ internal class CommandBinder
|
||||
// Custom converter
|
||||
if (memberSchema.ConverterType is not null)
|
||||
{
|
||||
var converter = (IBindingConverter) _typeActivator.CreateInstance(memberSchema.ConverterType);
|
||||
var converter = (IBindingConverter)_typeActivator.CreateInstance(memberSchema.ConverterType);
|
||||
return converter.Convert(rawValue);
|
||||
}
|
||||
|
||||
@@ -78,24 +78,24 @@ internal class CommandBinder
|
||||
}
|
||||
|
||||
// String-constructible (FileInfo, etc)
|
||||
var stringConstructor = targetType.GetConstructor(new[] {typeof(string)});
|
||||
var stringConstructor = targetType.GetConstructor(new[] { typeof(string) });
|
||||
if (stringConstructor is not null)
|
||||
{
|
||||
return stringConstructor.Invoke(new object?[] {rawValue});
|
||||
return stringConstructor.Invoke(new object?[] { rawValue });
|
||||
}
|
||||
|
||||
// String-parseable (with IFormatProvider)
|
||||
var parseMethodWithFormatProvider = targetType.TryGetStaticParseMethod(true);
|
||||
if (parseMethodWithFormatProvider is not null)
|
||||
{
|
||||
return parseMethodWithFormatProvider.Invoke(null, new object?[] {rawValue, _formatProvider});
|
||||
return parseMethodWithFormatProvider.Invoke(null, new object?[] { rawValue, _formatProvider });
|
||||
}
|
||||
|
||||
// String-parseable (without IFormatProvider)
|
||||
var parseMethod = targetType.TryGetStaticParseMethod();
|
||||
if (parseMethod is not null)
|
||||
{
|
||||
return parseMethod.Invoke(null, new object?[] {rawValue});
|
||||
return parseMethod.Invoke(null, new object?[] { rawValue });
|
||||
}
|
||||
|
||||
throw CliFxException.InternalError(
|
||||
@@ -126,10 +126,10 @@ internal class CommandBinder
|
||||
}
|
||||
|
||||
// Array-constructible (List<T>, HashSet<T>, etc)
|
||||
var arrayConstructor = targetEnumerableType.GetConstructor(new[] {arrayType});
|
||||
var arrayConstructor = targetEnumerableType.GetConstructor(new[] { arrayType });
|
||||
if (arrayConstructor is not null)
|
||||
{
|
||||
return arrayConstructor.Invoke(new object?[] {array});
|
||||
return arrayConstructor.Invoke(new object?[] { array });
|
||||
}
|
||||
|
||||
throw CliFxException.InternalError(
|
||||
@@ -192,7 +192,7 @@ internal class CommandBinder
|
||||
|
||||
foreach (var validatorType in memberSchema.ValidatorTypes)
|
||||
{
|
||||
var validator = (IBindingValidator) _typeActivator.CreateInstance(validatorType);
|
||||
var validator = (IBindingValidator)_typeActivator.CreateInstance(validatorType);
|
||||
var error = validator.Validate(convertedValue);
|
||||
|
||||
if (error is not null)
|
||||
@@ -238,7 +238,7 @@ internal class CommandBinder
|
||||
{
|
||||
var parameterInput = commandInput.Parameters[position];
|
||||
|
||||
var rawValues = new[] {parameterInput.Value};
|
||||
var rawValues = new[] { parameterInput.Value };
|
||||
BindMember(parameterSchema, commandInstance, rawValues);
|
||||
|
||||
position++;
|
||||
@@ -278,7 +278,7 @@ internal class CommandBinder
|
||||
"Missing required parameter(s):" +
|
||||
Environment.NewLine +
|
||||
remainingRequiredParameterSchemas
|
||||
.Select(o => o.GetFormattedIdentifier())
|
||||
.Select(p => p.GetFormattedIdentifier())
|
||||
.JoinToString(" ")
|
||||
);
|
||||
}
|
||||
@@ -316,7 +316,7 @@ internal class CommandBinder
|
||||
else if (environmentVariableInput is not null)
|
||||
{
|
||||
var rawValues = optionSchema.Property.IsScalar()
|
||||
? new[] {environmentVariableInput.Value}
|
||||
? new[] { environmentVariableInput.Value }
|
||||
: environmentVariableInput.SplitValues();
|
||||
|
||||
BindMember(optionSchema, commandInstance, rawValues);
|
||||
|
||||
@@ -23,7 +23,7 @@ public abstract class BindingValidator<T> : IBindingValidator
|
||||
|
||||
/// <summary>
|
||||
/// 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>
|
||||
/// <remarks>
|
||||
/// 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>
|
||||
public abstract BindingValidationError? Validate(T? value);
|
||||
|
||||
BindingValidationError? IBindingValidator.Validate(object? value) => Validate((T?) value);
|
||||
BindingValidationError? IBindingValidator.Validate(object? value) => Validate((T?)value);
|
||||
}
|
||||
@@ -206,6 +206,12 @@ internal class HelpConsoleFormatter : ConsoleFormatter
|
||||
Write('.');
|
||||
Write(' ');
|
||||
}
|
||||
|
||||
// Default value
|
||||
if (!parameterSchema.IsRequired)
|
||||
{
|
||||
WriteDefaultValue(parameterSchema);
|
||||
}
|
||||
|
||||
WriteLine();
|
||||
}
|
||||
@@ -298,60 +304,65 @@ internal class HelpConsoleFormatter : ConsoleFormatter
|
||||
// Default value
|
||||
if (!optionSchema.IsRequired)
|
||||
{
|
||||
var defaultValue = _context.CommandDefaultValues.GetValueOrDefault(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('.');
|
||||
}
|
||||
}
|
||||
}
|
||||
WriteDefaultValue(optionSchema);
|
||||
}
|
||||
|
||||
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()
|
||||
{
|
||||
var childCommandSchemas = _context
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
using System.IO;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace CliFx.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// Implements a <see cref="TextReader"/> for reading characters from a console stream.
|
||||
/// </summary>
|
||||
// Both the underlying stream AND the stream reader must be synchronized!
|
||||
// https://github.com/Tyrrrz/CliFx/issues/123
|
||||
public partial class ConsoleReader : StreamReader
|
||||
{
|
||||
/// <summary>
|
||||
@@ -29,6 +34,67 @@ public partial class ConsoleReader : StreamReader
|
||||
: 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
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
using System.IO;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx.Utils;
|
||||
|
||||
namespace CliFx.Infrastructure;
|
||||
@@ -7,6 +10,8 @@ namespace CliFx.Infrastructure;
|
||||
/// <summary>
|
||||
/// Implements a <see cref="TextWriter"/> for writing characters to a console stream.
|
||||
/// </summary>
|
||||
// Both the underlying stream AND the stream writer must be synchronized!
|
||||
// https://github.com/Tyrrrz/CliFx/issues/123
|
||||
public partial class ConsoleWriter : StreamWriter
|
||||
{
|
||||
/// <summary>
|
||||
@@ -30,6 +35,239 @@ public partial class ConsoleWriter : StreamWriter
|
||||
: 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
|
||||
|
||||
@@ -16,14 +16,15 @@ public class DefaultTypeActivator : ITypeActivator
|
||||
{
|
||||
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(
|
||||
$"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 +
|
||||
"Default type activator is only capable of instantiating a type if it has a public parameterless constructor." +
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
|
||||
@@ -14,6 +15,7 @@ namespace CliFx.Infrastructure;
|
||||
public class FakeConsole : IConsole, IDisposable
|
||||
{
|
||||
private readonly CancellationTokenSource _cancellationTokenSource = new();
|
||||
private readonly ConcurrentQueue<ConsoleKeyInfo> _keys = new();
|
||||
|
||||
/// <inheritdoc />
|
||||
public ConsoleReader Input { get; }
|
||||
@@ -91,9 +93,18 @@ public class FakeConsole : IConsole, IDisposable
|
||||
}
|
||||
|
||||
/// <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 />
|
||||
public virtual void Dispose() => _cancellationTokenSource.Dispose();
|
||||
|
||||
@@ -91,7 +91,7 @@ public interface IConsole
|
||||
/// <summary>
|
||||
/// Obtains the next character or function key pressed by the user.
|
||||
/// </summary>
|
||||
void ReadKey(bool intercept = false);
|
||||
ConsoleKeyInfo ReadKey(bool intercept = false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -94,7 +94,7 @@ public class SystemConsole : IConsole, IDisposable
|
||||
public void Clear() => Console.Clear();
|
||||
|
||||
/// <inheritdoc />
|
||||
public void ReadKey(bool intercept = false) => Console.ReadKey(intercept);
|
||||
public ConsoleKeyInfo ReadKey(bool intercept = false) => Console.ReadKey(intercept);
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
|
||||
@@ -8,6 +8,8 @@ namespace CliFx.Utils;
|
||||
// https://github.com/dotnet/runtime/blob/01b7e73cd378145264a7cb7a09365b41ed42b240/src/libraries/Common/src/System/Text/ConsoleEncoding.cs
|
||||
// Also see:
|
||||
// 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
|
||||
{
|
||||
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) =>
|
||||
_underlyingEncoding.GetBytes(chars, charIndex, charCount, bytes, byteIndex);
|
||||
|
||||
[ExcludeFromCodeCoverage]
|
||||
public override byte[] GetBytes(char[] chars) => _underlyingEncoding.GetBytes(chars);
|
||||
|
||||
[ExcludeFromCodeCoverage]
|
||||
public override byte[] GetBytes(char[] chars, int index, int count) =>
|
||||
_underlyingEncoding.GetBytes(chars, index, count);
|
||||
|
||||
[ExcludeFromCodeCoverage]
|
||||
public override byte[] GetBytes(string s) => _underlyingEncoding.GetBytes(s);
|
||||
public override byte[] GetBytes(char[] chars) => _underlyingEncoding.GetBytes(chars);
|
||||
|
||||
[ExcludeFromCodeCoverage]
|
||||
public override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) =>
|
||||
_underlyingEncoding.GetBytes(s, charIndex, charCount, bytes, byteIndex);
|
||||
|
||||
[ExcludeFromCodeCoverage]
|
||||
public override byte[] GetBytes(string s) => _underlyingEncoding.GetBytes(s);
|
||||
|
||||
[ExcludeFromCodeCoverage]
|
||||
public override int GetCharCount(byte[] bytes, int index, int count) =>
|
||||
_underlyingEncoding.GetCharCount(bytes, index, count);
|
||||
|
||||
26
CliFx/Utils/Polyfills.Collections.cs
Normal file
26
CliFx/Utils/Polyfills.Collections.cs
Normal 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
|
||||
11
CliFx/Utils/Polyfills.Streams.cs
Normal file
11
CliFx/Utils/Polyfills.Streams.cs
Normal 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
|
||||
12
CliFx/Utils/Polyfills.Strings.cs
Normal file
12
CliFx/Utils/Polyfills.Strings.cs
Normal 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
|
||||
@@ -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
|
||||
@@ -1,9 +1,9 @@
|
||||
<Project>
|
||||
|
||||
<PropertyGroup>
|
||||
<Version>2.2</Version>
|
||||
<Version>2.2.3</Version>
|
||||
<Company>Tyrrrz</Company>
|
||||
<Copyright>Copyright (C) Alexey Golub</Copyright>
|
||||
<Copyright>Copyright (C) Oleksii Holub</Copyright>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<WarningsAsErrors>nullable</WarningsAsErrors>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
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
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
27
Readme.md
27
Readme.md
@@ -1,22 +1,33 @@
|
||||
# CliFx
|
||||
|
||||
[](https://github.com/Tyrrrz/CliFx/actions)
|
||||
[](https://codecov.io/gh/Tyrrrz/CliFx)
|
||||
[](https://vshymanskyy.github.io/StandWithUkraine)
|
||||
[](https://github.com/Tyrrrz/CliFx/actions)
|
||||
[](https://codecov.io/gh/Tyrrrz/CliFx)
|
||||
[](https://nuget.org/packages/CliFx)
|
||||
[](https://nuget.org/packages/CliFx)
|
||||
[](https://discord.gg/2SUWKFnHSm)
|
||||
[](https://tyrrrz.me/donate)
|
||||
[](https://tyrrrz.me/donate)
|
||||
[](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.
|
||||
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
|
||||
|
||||
@@ -705,4 +716,4 @@ In such case, the values of the environment variable will be split by `Path.Path
|
||||
|
||||
## 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".
|
||||
|
||||
Reference in New Issue
Block a user