13 Commits
2.3.2 ... 2.3.4

Author SHA1 Message Date
Tyrrrz
99c59431c4 Update version 2023-05-18 07:30:32 +03:00
Tyrrrz
f376081489 Update NuGet packages 2023-05-18 07:20:27 +03:00
Tyrrrz
00a1e12b5c Test naming consistency 2023-05-17 23:51:21 +03:00
Tyrrrz
81f8b17451 Fix cancellation tests 2023-05-16 02:43:47 +03:00
Tyrrrz
aa8315b68d Clean up 2023-05-16 01:56:28 +03:00
Tyrrrz
e52781c25a Refactor 2023-05-16 01:36:03 +03:00
Tyrrrz
01f29a5375 Fix tests 2023-05-15 05:50:29 +03:00
Tyrrrz
013cb8f66b Add an overload of UseTypeActivator(...) that takes a list of added command types 2023-05-15 05:29:46 +03:00
Tyrrrz
9c715f458e Update version 2023-04-28 17:10:37 +03:00
Tyrrrz
90d93a57ee Remove package readme 2023-04-28 17:09:35 +03:00
Tyrrrz
8da4a61eb7 Fix warnings in local build 2023-04-28 17:07:37 +03:00
Tyrrrz
f718370642 Update NuGet packages 2023-04-28 17:03:30 +03:00
Tyrrrz
83c7af72bf Downgrade target Roslyn version in analyzers
Closes #135
2023-04-28 17:02:50 +03:00
81 changed files with 1454 additions and 1450 deletions

View File

@@ -1,5 +1,13 @@
# Changelog # Changelog
## v2.3.4 (18-May-2023)
- Added an overload of `CliApplicationBuilder.UseTypeActivator(...)` that accepts a `Func<IReadOnlyList<Type>, IServiceProvider>` delegate. The first parameter in the delegate is the list of all command types registered in the application. You can use this overload to more easily add the commands to a DI container. See the readme for an [updated example](https://github.com/Tyrrrz/CliFx/tree/2.3.4#type-activation).
## v2.3.3 (28-Apr-2023)
- Fixed an issue where the analyzers failed to load in some projects, due to targeting a Roslyn version that was too high.
## v2.3.2 (06-Apr-2023) ## v2.3.2 (06-Apr-2023)
- Added name-based ordering to subcommands when displayed in the help text. (Thanks [@CartBlanche](https://github.com/CartBlanche)) - Added name-based ordering to subcommands when displayed in the help text. (Thanks [@CartBlanche](https://github.com/CartBlanche))

View File

@@ -9,11 +9,11 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Basic.Reference.Assemblies.Net70" Version="1.4.1" /> <PackageReference Include="Basic.Reference.Assemblies.Net70" Version="1.4.2" />
<PackageReference Include="GitHubActionsTestLogger" Version="2.0.1" PrivateAssets="all" /> <PackageReference Include="GitHubActionsTestLogger" Version="2.2.0" PrivateAssets="all" />
<PackageReference Include="FluentAssertions" Version="6.10.0" /> <PackageReference Include="FluentAssertions" Version="6.11.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.5.0" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.6.0" />
<PackageReference Include="xunit" Version="2.4.2" /> <PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5" PrivateAssets="all" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.5" PrivateAssets="all" />
<PackageReference Include="coverlet.collector" Version="3.2.0" PrivateAssets="all" /> <PackageReference Include="coverlet.collector" Version="3.2.0" PrivateAssets="all" />

View File

@@ -69,7 +69,7 @@ public class CommandMustBeAnnotatedAnalyzerSpecs
""" """
public class Foo public class Foo
{ {
public int Bar { get; set; } = 5; public int Bar { get; init; } = 5;
} }
"""; """;

View File

@@ -53,7 +53,7 @@ public class CommandMustImplementInterfaceAnalyzerSpecs
""" """
public class Foo public class Foo
{ {
public int Bar { get; set; } = 5; public int Bar { get; init; } = 5;
} }
"""; """;

View File

@@ -18,7 +18,7 @@ public class OptionMustBeInsideCommandAnalyzerSpecs
public class MyClass public class MyClass
{ {
[CommandOption("foo")] [CommandOption("foo")]
public string Foo { get; set; } public string? Foo { get; init; }
} }
"""; """;
@@ -37,7 +37,7 @@ public class OptionMustBeInsideCommandAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo")] [CommandOption("foo")]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -57,7 +57,7 @@ public class OptionMustBeInsideCommandAnalyzerSpecs
public abstract class MyCommand public abstract class MyCommand
{ {
[CommandOption("foo")] [CommandOption("foo")]
public string Foo { get; set; } public string? Foo { get; init; }
} }
"""; """;
@@ -75,7 +75,7 @@ public class OptionMustBeInsideCommandAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }

View File

@@ -19,7 +19,7 @@ public class OptionMustBeRequiredIfPropertyRequiredAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption('f', IsRequired = false)] [CommandOption('f', IsRequired = false)]
public required string Foo { get; set; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -39,8 +39,8 @@ public class OptionMustBeRequiredIfPropertyRequiredAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption('f', IsRequired = true)] [CommandOption('f')]
public required string Foo { get; set; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -61,7 +61,7 @@ public class OptionMustBeRequiredIfPropertyRequiredAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption('f', IsRequired = false)] [CommandOption('f', IsRequired = false)]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -81,8 +81,8 @@ public class OptionMustBeRequiredIfPropertyRequiredAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption('f', IsRequired = true)] [CommandOption('f')]
public string Foo { get; set; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -102,7 +102,7 @@ public class OptionMustBeRequiredIfPropertyRequiredAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
public required string Foo { get; set; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }

View File

@@ -19,7 +19,7 @@ public class OptionMustHaveNameOrShortNameAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption(null)] [CommandOption(null)]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -40,7 +40,7 @@ public class OptionMustHaveNameOrShortNameAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo")] [CommandOption("foo")]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -61,7 +61,7 @@ public class OptionMustHaveNameOrShortNameAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -81,7 +81,7 @@ public class OptionMustHaveNameOrShortNameAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }

View File

@@ -19,10 +19,10 @@ public class OptionMustHaveUniqueNameAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo")] [CommandOption("foo")]
public string Foo { get; set; } public string? Foo { get; init; }
[CommandOption("foo")] [CommandOption("foo")]
public string Bar { get; set; } public string? Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -43,10 +43,10 @@ public class OptionMustHaveUniqueNameAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo")] [CommandOption("foo")]
public string Foo { get; set; } public string? Foo { get; init; }
[CommandOption("bar")] [CommandOption("bar")]
public string Bar { get; set; } public string? Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -67,7 +67,7 @@ public class OptionMustHaveUniqueNameAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -87,7 +87,7 @@ public class OptionMustHaveUniqueNameAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }

View File

@@ -19,10 +19,10 @@ public class OptionMustHaveUniqueShortNameAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string Foo { get; set; } public string? Foo { get; init; }
[CommandOption('f')] [CommandOption('f')]
public string Bar { get; set; } public string? Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -43,10 +43,10 @@ public class OptionMustHaveUniqueShortNameAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string Foo { get; set; } public string? Foo { get; init; }
[CommandOption('b')] [CommandOption('b')]
public string Bar { get; set; } public string? Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -67,10 +67,10 @@ public class OptionMustHaveUniqueShortNameAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string Foo { get; set; } public string? Foo { get; init; }
[CommandOption('F')] [CommandOption('F')]
public string Bar { get; set; } public string? Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -91,7 +91,7 @@ public class OptionMustHaveUniqueShortNameAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo")] [CommandOption("foo")]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -111,7 +111,7 @@ public class OptionMustHaveUniqueShortNameAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }

View File

@@ -17,14 +17,14 @@ public class OptionMustHaveValidConverterAnalyzerSpecs
""" """
public class MyConverter public class MyConverter
{ {
public string Convert(string rawValue) => rawValue; public string Convert(string? rawValue) => rawValue;
} }
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo", Converter = typeof(MyConverter))] [CommandOption("foo", Converter = typeof(MyConverter))]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -43,14 +43,14 @@ public class OptionMustHaveValidConverterAnalyzerSpecs
""" """
public class MyConverter : BindingConverter<int> public class MyConverter : BindingConverter<int>
{ {
public override int Convert(string rawValue) => 42; public override int Convert(string? rawValue) => 42;
} }
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo", Converter = typeof(MyConverter))] [CommandOption("foo", Converter = typeof(MyConverter))]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -69,14 +69,14 @@ public class OptionMustHaveValidConverterAnalyzerSpecs
""" """
public class MyConverter : BindingConverter<string> public class MyConverter : BindingConverter<string>
{ {
public override string Convert(string rawValue) => rawValue; public override string Convert(string? rawValue) => rawValue;
} }
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo", Converter = typeof(MyConverter))] [CommandOption("foo", Converter = typeof(MyConverter))]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -95,14 +95,14 @@ public class OptionMustHaveValidConverterAnalyzerSpecs
""" """
public class MyConverter : BindingConverter<int> public class MyConverter : BindingConverter<int>
{ {
public override int Convert(string rawValue) => 42; public override int Convert(string? rawValue) => 42;
} }
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo", Converter = typeof(MyConverter))] [CommandOption("foo", Converter = typeof(MyConverter))]
public int? Foo { get; set; } public int? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -121,14 +121,14 @@ public class OptionMustHaveValidConverterAnalyzerSpecs
""" """
public class MyConverter : BindingConverter<string> public class MyConverter : BindingConverter<string>
{ {
public override string Convert(string rawValue) => rawValue; public override string Convert(string? rawValue) => rawValue;
} }
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo", Converter = typeof(MyConverter))] [CommandOption("foo", Converter = typeof(MyConverter))]
public IReadOnlyList<string> Foo { get; set; } public IReadOnlyList<string>? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -149,7 +149,7 @@ public class OptionMustHaveValidConverterAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo")] [CommandOption("foo")]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -169,7 +169,7 @@ public class OptionMustHaveValidConverterAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }

View File

@@ -19,7 +19,7 @@ public class OptionMustHaveValidNameAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("f")] [CommandOption("f")]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -40,7 +40,7 @@ public class OptionMustHaveValidNameAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("1foo")] [CommandOption("1foo")]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -61,7 +61,7 @@ public class OptionMustHaveValidNameAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo")] [CommandOption("foo")]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -82,7 +82,7 @@ public class OptionMustHaveValidNameAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -102,7 +102,7 @@ public class OptionMustHaveValidNameAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }

View File

@@ -19,7 +19,7 @@ public class OptionMustHaveValidShortNameAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption('1')] [CommandOption('1')]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -40,7 +40,7 @@ public class OptionMustHaveValidShortNameAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -61,7 +61,7 @@ public class OptionMustHaveValidShortNameAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo")] [CommandOption("foo")]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -81,7 +81,7 @@ public class OptionMustHaveValidShortNameAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }

View File

@@ -24,7 +24,7 @@ public class OptionMustHaveValidValidatorsAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo", Validators = new[] {typeof(MyValidator)})] [CommandOption("foo", Validators = new[] {typeof(MyValidator)})]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -50,7 +50,7 @@ public class OptionMustHaveValidValidatorsAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo", Validators = new[] {typeof(MyValidator)})] [CommandOption("foo", Validators = new[] {typeof(MyValidator)})]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -76,7 +76,7 @@ public class OptionMustHaveValidValidatorsAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo", Validators = new[] {typeof(MyValidator)})] [CommandOption("foo", Validators = new[] {typeof(MyValidator)})]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -97,7 +97,7 @@ public class OptionMustHaveValidValidatorsAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo")] [CommandOption("foo")]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -117,7 +117,7 @@ public class OptionMustHaveValidValidatorsAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }

View File

@@ -18,7 +18,7 @@ public class ParameterMustBeInsideCommandAnalyzerSpecs
public class MyClass public class MyClass
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public required string Foo { get; init; }
} }
"""; """;
@@ -37,7 +37,7 @@ public class ParameterMustBeInsideCommandAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -57,7 +57,7 @@ public class ParameterMustBeInsideCommandAnalyzerSpecs
public abstract class MyCommand public abstract class MyCommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public required string Foo { get; init; }
} }
"""; """;
@@ -75,7 +75,7 @@ public class ParameterMustBeInsideCommandAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }

View File

@@ -19,10 +19,10 @@ public class ParameterMustBeLastIfNonRequiredAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0, IsRequired = false)] [CommandParameter(0, IsRequired = false)]
public string Foo { get; set; } public string? Foo { get; init; }
[CommandParameter(1)] [CommandParameter(1)]
public string Bar { get; set; } public required string Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -43,10 +43,10 @@ public class ParameterMustBeLastIfNonRequiredAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public required string Foo { get; init; }
[CommandParameter(1, IsRequired = false)] [CommandParameter(1, IsRequired = false)]
public string Bar { get; set; } public string? Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -67,10 +67,10 @@ public class ParameterMustBeLastIfNonRequiredAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public required string Foo { get; init; }
[CommandParameter(1, IsRequired = true)] [CommandParameter(1)]
public string Bar { get; set; } public required string Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -90,7 +90,7 @@ public class ParameterMustBeLastIfNonRequiredAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }

View File

@@ -19,10 +19,10 @@ public class ParameterMustBeLastIfNonScalarAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string[] Foo { get; set; } public required string[] Foo { get; init; }
[CommandParameter(1)] [CommandParameter(1)]
public string Bar { get; set; } public required string Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -43,10 +43,10 @@ public class ParameterMustBeLastIfNonScalarAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public required string Foo { get; init; }
[CommandParameter(1)] [CommandParameter(1)]
public string[] Bar { get; set; } public required string[] Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -67,10 +67,10 @@ public class ParameterMustBeLastIfNonScalarAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public required string Foo { get; init; }
[CommandParameter(1)] [CommandParameter(1)]
public string Bar { get; set; } public required string Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -90,7 +90,7 @@ public class ParameterMustBeLastIfNonScalarAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }

View File

@@ -19,7 +19,7 @@ public class ParameterMustBeRequiredIfPropertyRequiredAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0, IsRequired = false)] [CommandParameter(0, IsRequired = false)]
public required string Foo { get; set; } public required string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -39,8 +39,8 @@ public class ParameterMustBeRequiredIfPropertyRequiredAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0, IsRequired = true)] [CommandParameter(0)]
public required string Foo { get; set; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -61,7 +61,7 @@ public class ParameterMustBeRequiredIfPropertyRequiredAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0, IsRequired = false)] [CommandParameter(0, IsRequired = false)]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -81,8 +81,8 @@ public class ParameterMustBeRequiredIfPropertyRequiredAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0, IsRequired = true)] [CommandParameter(0)]
public string Foo { get; set; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -102,7 +102,7 @@ public class ParameterMustBeRequiredIfPropertyRequiredAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
public required string Foo { get; set; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }

View File

@@ -19,10 +19,10 @@ public class ParameterMustBeSingleIfNonRequiredAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0, IsRequired = false)] [CommandParameter(0, IsRequired = false)]
public string Foo { get; set; } public string? Foo { get; init; }
[CommandParameter(1, IsRequired = false)] [CommandParameter(1, IsRequired = false)]
public string Bar { get; set; } public string? Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -43,10 +43,10 @@ public class ParameterMustBeSingleIfNonRequiredAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public required string Foo { get; init; }
[CommandParameter(1, IsRequired = false)] [CommandParameter(1, IsRequired = false)]
public string Bar { get; set; } public string? Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -67,10 +67,10 @@ public class ParameterMustBeSingleIfNonRequiredAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public required string Foo { get; init; }
[CommandParameter(1, IsRequired = true)] [CommandParameter(1)]
public string Bar { get; set; } public required string Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -90,7 +90,7 @@ public class ParameterMustBeSingleIfNonRequiredAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }

View File

@@ -19,10 +19,10 @@ public class ParameterMustBeSingleIfNonScalarAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string[] Foo { get; set; } public required string[] Foo { get; init; }
[CommandParameter(1)] [CommandParameter(1)]
public string[] Bar { get; set; } public required string[] Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -43,10 +43,10 @@ public class ParameterMustBeSingleIfNonScalarAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public required string Foo { get; init; }
[CommandParameter(1)] [CommandParameter(1)]
public string[] Bar { get; set; } public required string[] Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -67,10 +67,10 @@ public class ParameterMustBeSingleIfNonScalarAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public required string Foo { get; init; }
[CommandParameter(1)] [CommandParameter(1)]
public string Bar { get; set; } public required string Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -90,7 +90,7 @@ public class ParameterMustBeSingleIfNonScalarAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }

View File

@@ -19,10 +19,10 @@ public class ParameterMustHaveUniqueNameAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0, Name = "foo")] [CommandParameter(0, Name = "foo")]
public string Foo { get; set; } public required string Foo { get; init; }
[CommandParameter(1, Name = "foo")] [CommandParameter(1, Name = "foo")]
public string Bar { get; set; } public required string Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -43,10 +43,10 @@ public class ParameterMustHaveUniqueNameAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0, Name = "foo")] [CommandParameter(0, Name = "foo")]
public string Foo { get; set; } public required string Foo { get; init; }
[CommandParameter(1, Name = "bar")] [CommandParameter(1, Name = "bar")]
public string Bar { get; set; } public required string Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -66,7 +66,7 @@ public class ParameterMustHaveUniqueNameAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }

View File

@@ -19,10 +19,10 @@ public class ParameterMustHaveUniqueOrderAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public required string Foo { get; init; }
[CommandParameter(0)] [CommandParameter(0)]
public string Bar { get; set; } public required string Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -43,10 +43,10 @@ public class ParameterMustHaveUniqueOrderAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public required string Foo { get; init; }
[CommandParameter(1)] [CommandParameter(1)]
public string Bar { get; set; } public required string Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -66,7 +66,7 @@ public class ParameterMustHaveUniqueOrderAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }

View File

@@ -17,14 +17,14 @@ public class ParameterMustHaveValidConverterAnalyzerSpecs
""" """
public class MyConverter public class MyConverter
{ {
public string Convert(string rawValue) => rawValue; public string Convert(string? rawValue) => rawValue;
} }
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0, Converter = typeof(MyConverter))] [CommandParameter(0, Converter = typeof(MyConverter))]
public string Foo { get; set; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -43,14 +43,14 @@ public class ParameterMustHaveValidConverterAnalyzerSpecs
""" """
public class MyConverter : BindingConverter<int> public class MyConverter : BindingConverter<int>
{ {
public override int Convert(string rawValue) => 42; public override int Convert(string? rawValue) => 42;
} }
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0, Converter = typeof(MyConverter))] [CommandParameter(0, Converter = typeof(MyConverter))]
public string Foo { get; set; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -70,14 +70,14 @@ public class ParameterMustHaveValidConverterAnalyzerSpecs
""" """
public class MyConverter : BindingConverter<string> public class MyConverter : BindingConverter<string>
{ {
public override string Convert(string rawValue) => rawValue; public override string Convert(string? rawValue) => rawValue;
} }
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0, Converter = typeof(MyConverter))] [CommandParameter(0, Converter = typeof(MyConverter))]
public string Foo { get; set; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -96,14 +96,14 @@ public class ParameterMustHaveValidConverterAnalyzerSpecs
""" """
public class MyConverter : BindingConverter<int> public class MyConverter : BindingConverter<int>
{ {
public override int Convert(string rawValue) => 42; public override int Convert(string? rawValue) => 42;
} }
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandOption("foo", Converter = typeof(MyConverter))] [CommandOption("foo", Converter = typeof(MyConverter))]
public int? Foo { get; set; } public int? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -122,14 +122,14 @@ public class ParameterMustHaveValidConverterAnalyzerSpecs
""" """
public class MyConverter : BindingConverter<string> public class MyConverter : BindingConverter<string>
{ {
public override string Convert(string rawValue) => rawValue; public override string Convert(string? rawValue) => rawValue;
} }
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0, Converter = typeof(MyConverter))] [CommandParameter(0, Converter = typeof(MyConverter))]
public IReadOnlyList<string> Foo { get; set; } public required IReadOnlyList<string> Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -150,7 +150,7 @@ public class ParameterMustHaveValidConverterAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -170,7 +170,7 @@ public class ParameterMustHaveValidConverterAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }

View File

@@ -24,7 +24,7 @@ public class ParameterMustHaveValidValidatorsAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0, Validators = new[] {typeof(MyValidator)})] [CommandParameter(0, Validators = new[] {typeof(MyValidator)})]
public string Foo { get; set; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -50,7 +50,7 @@ public class ParameterMustHaveValidValidatorsAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0, Validators = new[] {typeof(MyValidator)})] [CommandParameter(0, Validators = new[] {typeof(MyValidator)})]
public string Foo { get; set; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -76,7 +76,7 @@ public class ParameterMustHaveValidValidatorsAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0, Validators = new[] {typeof(MyValidator)})] [CommandParameter(0, Validators = new[] {typeof(MyValidator)})]
public string Foo { get; set; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -97,7 +97,7 @@ public class ParameterMustHaveValidValidatorsAnalyzerSpecs
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -117,7 +117,7 @@ public class ParameterMustHaveValidValidatorsAnalyzerSpecs
[Command] [Command]
public class MyCommand : ICommand public class MyCommand : ICommand
{ {
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }

View File

@@ -17,9 +17,10 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" PrivateAssets="all" /> <!-- Make sure to target the lowest possible version of the compiler for wider support -->
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.5.0" PrivateAssets="all" /> <PackageReference Include="Microsoft.CodeAnalysis" Version="3.0.0" PrivateAssets="all" />
<PackageReference Include="PolyShim" Version="1.1.0" PrivateAssets="all" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.0.0" PrivateAssets="all" />
<PackageReference Include="PolyShim" Version="1.2.0" PrivateAssets="all" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -24,7 +24,7 @@ public class OptionMustBeRequiredIfPropertyRequiredAnalyzer : AnalyzerBase
if (property.ContainingType is null) if (property.ContainingType is null)
return; return;
if (!property.IsRequired) if (!property.IsRequired())
return; return;
var option = CommandOptionSymbol.TryResolve(property); var option = CommandOptionSymbol.TryResolve(property);

View File

@@ -39,7 +39,7 @@ public class OptionMustHaveUniqueNameAnalyzer : AnalyzerBase
.ContainingType .ContainingType
.GetMembers() .GetMembers()
.OfType<IPropertySymbol>() .OfType<IPropertySymbol>()
.Where(m => !m.Equals(property, SymbolEqualityComparer.Default)) .Where(m => !m.Equals(property))
.ToArray(); .ToArray();
foreach (var otherProperty in otherProperties) foreach (var otherProperty in otherProperties)

View File

@@ -38,7 +38,7 @@ public class OptionMustHaveUniqueShortNameAnalyzer : AnalyzerBase
.ContainingType .ContainingType
.GetMembers() .GetMembers()
.OfType<IPropertySymbol>() .OfType<IPropertySymbol>()
.Where(m => !m.Equals(property, SymbolEqualityComparer.Default)) .Where(m => !m.Equals(property))
.ToArray(); .ToArray();
foreach (var otherProperty in otherProperties) foreach (var otherProperty in otherProperties)

View File

@@ -37,7 +37,7 @@ public class ParameterMustBeLastIfNonRequiredAnalyzer : AnalyzerBase
.ContainingType .ContainingType
.GetMembers() .GetMembers()
.OfType<IPropertySymbol>() .OfType<IPropertySymbol>()
.Where(m => !m.Equals(property, SymbolEqualityComparer.Default)) .Where(m => !m.Equals(property))
.ToArray(); .ToArray();
foreach (var otherProperty in otherProperties) foreach (var otherProperty in otherProperties)

View File

@@ -37,7 +37,7 @@ public class ParameterMustBeLastIfNonScalarAnalyzer : AnalyzerBase
.ContainingType .ContainingType
.GetMembers() .GetMembers()
.OfType<IPropertySymbol>() .OfType<IPropertySymbol>()
.Where(m => !m.Equals(property, SymbolEqualityComparer.Default)) .Where(m => !m.Equals(property))
.ToArray(); .ToArray();
foreach (var otherProperty in otherProperties) foreach (var otherProperty in otherProperties)

View File

@@ -24,7 +24,7 @@ public class ParameterMustBeRequiredIfPropertyRequiredAnalyzer : AnalyzerBase
if (property.ContainingType is null) if (property.ContainingType is null)
return; return;
if (!property.IsRequired) if (!property.IsRequired())
return; return;
var parameter = CommandParameterSymbol.TryResolve(property); var parameter = CommandParameterSymbol.TryResolve(property);

View File

@@ -37,7 +37,7 @@ public class ParameterMustBeSingleIfNonRequiredAnalyzer : AnalyzerBase
.ContainingType .ContainingType
.GetMembers() .GetMembers()
.OfType<IPropertySymbol>() .OfType<IPropertySymbol>()
.Where(m => !m.Equals(property, SymbolEqualityComparer.Default)) .Where(m => !m.Equals(property))
.ToArray(); .ToArray();
foreach (var otherProperty in otherProperties) foreach (var otherProperty in otherProperties)

View File

@@ -37,7 +37,7 @@ public class ParameterMustBeSingleIfNonScalarAnalyzer : AnalyzerBase
.ContainingType .ContainingType
.GetMembers() .GetMembers()
.OfType<IPropertySymbol>() .OfType<IPropertySymbol>()
.Where(m => !m.Equals(property, SymbolEqualityComparer.Default)) .Where(m => !m.Equals(property))
.ToArray(); .ToArray();
foreach (var otherProperty in otherProperties) foreach (var otherProperty in otherProperties)

View File

@@ -39,7 +39,7 @@ public class ParameterMustHaveUniqueNameAnalyzer : AnalyzerBase
.ContainingType .ContainingType
.GetMembers() .GetMembers()
.OfType<IPropertySymbol>() .OfType<IPropertySymbol>()
.Where(m => !m.Equals(property, SymbolEqualityComparer.Default)) .Where(m => !m.Equals(property))
.ToArray(); .ToArray();
foreach (var otherProperty in otherProperties) foreach (var otherProperty in otherProperties)

View File

@@ -35,7 +35,7 @@ public class ParameterMustHaveUniqueOrderAnalyzer : AnalyzerBase
.ContainingType .ContainingType
.GetMembers() .GetMembers()
.OfType<IPropertySymbol>() .OfType<IPropertySymbol>()
.Where(m => !m.Equals(property, SymbolEqualityComparer.Default)) .Where(m => !m.Equals(property))
.ToArray(); .ToArray();
foreach (var otherProperty in otherProperties) foreach (var otherProperty in otherProperties)

View File

@@ -34,6 +34,17 @@ internal static class RoslynExtensions
.FirstOrDefault(i => i.ConstructedFrom.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T)? .FirstOrDefault(i => i.ConstructedFrom.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T)?
.TypeArguments[0]; .TypeArguments[0];
// Detect if the property is required through roundabout means so as to not have to take dependency
// on higher versions of the C# compiler.
public static bool IsRequired(this IPropertySymbol property) => property
// Can't rely on the RequiredMemberAttribute because it's generated by the compiler, not added by the user,
// so we have to check for the presence of the `required` modifier in the syntax tree instead.
.DeclaringSyntaxReferences
.Select(r => r.GetSyntax())
.OfType<PropertyDeclarationSyntax>()
.SelectMany(p => p.Modifiers)
.Any(m => m.IsKind((SyntaxKind)8447));
public static bool IsAssignable(this Compilation compilation, ITypeSymbol source, ITypeSymbol destination) => public static bool IsAssignable(this Compilation compilation, ITypeSymbol source, ITypeSymbol destination) =>
compilation.ClassifyConversion(source, destination).Exists; compilation.ClassifyConversion(source, destination).Exists;

View File

@@ -16,7 +16,7 @@ public partial class BookAddCommand : ICommand
[CommandParameter(0, Name = "title", Description = "Book title.")] [CommandParameter(0, Name = "title", Description = "Book title.")]
public required string Title { get; init; } public required string Title { get; init; }
[CommandOption("author", 'a', IsRequired = true, Description = "Book author.")] [CommandOption("author", 'a', Description = "Book author.")]
public required string Author { get; init; } public required string Author { get; init; }
[CommandOption("published", 'p', Description = "Book publish date.")] [CommandOption("published", 'p', Description = "Book publish date.")]

View File

@@ -1,25 +1,21 @@
using CliFx; using CliFx;
using CliFx.Demo.Commands;
using CliFx.Demo.Domain; using CliFx.Demo.Domain;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
// We use Microsoft.Extensions.DependencyInjection for injecting dependencies in commands
var services = new ServiceCollection();
// Register services
services.AddSingleton<LibraryProvider>();
// Register commands
services.AddTransient<BookCommand>();
services.AddTransient<BookAddCommand>();
services.AddTransient<BookRemoveCommand>();
services.AddTransient<BookListCommand>();
var serviceProvider = services.BuildServiceProvider();
return await new CliApplicationBuilder() return await new CliApplicationBuilder()
.SetDescription("Demo application showcasing CliFx features.") .SetDescription("Demo application showcasing CliFx features.")
.AddCommandsFromThisAssembly() .AddCommandsFromThisAssembly()
.UseTypeActivator(serviceProvider.GetRequiredService) .UseTypeActivator(commandTypes =>
{
// We use Microsoft.Extensions.DependencyInjection for injecting dependencies in commands
var services = new ServiceCollection();
services.AddSingleton<LibraryProvider>();
// Register all commands as transient services
foreach (var commandType in commandTypes)
services.AddTransient(commandType);
return services.BuildServiceProvider();
})
.Build() .Build()
.RunAsync(); .RunAsync();

View File

@@ -0,0 +1,30 @@
using System;
using System.Threading.Tasks;
using CliFx.Attributes;
using CliFx.Infrastructure;
namespace CliFx.Tests.Dummy.Commands;
[Command("cancel-test")]
public class CancellationTestCommand : ICommand
{
public async ValueTask ExecuteAsync(IConsole console)
{
try
{
console.Output.WriteLine("Started.");
await Task.Delay(
TimeSpan.FromSeconds(3),
console.RegisterCancellationHandler()
);
console.Output.WriteLine("Completed.");
}
catch (OperationCanceledException)
{
console.Output.WriteLine("Cancelled.");
throw;
}
}
}

View File

@@ -8,7 +8,7 @@ namespace CliFx.Tests.Dummy.Commands;
public class EnvironmentTestCommand : ICommand public class EnvironmentTestCommand : ICommand
{ {
[CommandOption("target", EnvironmentVariable = "ENV_TARGET")] [CommandOption("target", EnvironmentVariable = "ENV_TARGET")]
public string GreetingTarget { get; set; } = "World"; public string GreetingTarget { get; init; } = "World";
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {

View File

@@ -4,9 +4,7 @@ using System.Threading.Tasks;
namespace CliFx.Tests.Dummy; namespace CliFx.Tests.Dummy;
// This dummy application is used in tests for scenarios // This dummy application is used in tests for scenarios that require an external process to properly verify
// that require an external process to properly verify.
public static partial class Program public static partial class Program
{ {
public static Assembly Assembly { get; } = Assembly.GetExecutingAssembly(); public static Assembly Assembly { get; } = Assembly.GetExecutingAssembly();

View File

@@ -16,7 +16,7 @@ public class ApplicationSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Application_can_be_created_with_minimal_configuration() public async Task I_can_create_an_application_with_the_default_configuration()
{ {
// Act // Act
var app = new CliApplicationBuilder() var app = new CliApplicationBuilder()
@@ -34,7 +34,7 @@ public class ApplicationSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Application_can_be_created_with_a_fully_customized_configuration() public async Task I_can_create_an_application_with_a_custom_configuration()
{ {
// Act // Act
var app = new CliApplicationBuilder() var app = new CliApplicationBuilder()
@@ -63,7 +63,7 @@ public class ApplicationSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Application_configuration_fails_if_an_invalid_command_is_registered() public async Task I_cannot_add_an_invalid_command_to_the_application()
{ {
// Act // Act
var app = new CliApplicationBuilder() var app = new CliApplicationBuilder()
@@ -76,10 +76,10 @@ public class ApplicationSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdErr = FakeConsole.ReadErrorString();
// Assert // Assert
exitCode.Should().NotBe(0); exitCode.Should().NotBe(0);
var stdErr = FakeConsole.ReadErrorString();
stdErr.Should().Contain("not a valid command"); stdErr.Should().Contain("not a valid command");
} }
} }

View File

@@ -1,7 +1,11 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using CliFx.Tests.Utils; using CliFx.Tests.Utils;
using CliFx.Tests.Utils.Extensions;
using CliWrap;
using FluentAssertions; using FluentAssertions;
using Xunit; using Xunit;
using Xunit.Abstractions; using Xunit.Abstractions;
@@ -15,8 +19,52 @@ public class CancellationSpecs : SpecsBase
{ {
} }
[Fact(Timeout = 15000)]
public async Task I_can_configure_the_command_to_listen_to_the_interrupt_signal()
{
// Arrange
using var cts = new CancellationTokenSource();
// We need to send the cancellation request right after the process has registered
// a handler for the interrupt signal, otherwise the default handler will trigger
// and just kill the process.
void HandleStdOut(string line)
{
if (string.Equals(line, "Started.", StringComparison.OrdinalIgnoreCase))
cts.CancelAfter(TimeSpan.FromSeconds(0.2));
}
var stdOutBuffer = new StringBuilder();
var pipeTarget = PipeTarget.Merge(
PipeTarget.ToDelegate(HandleStdOut),
PipeTarget.ToStringBuilder(stdOutBuffer)
);
var command = Cli.Wrap("dotnet")
.WithArguments(a => a
.Add(Dummy.Program.Location)
.Add("cancel-test")
) | pipeTarget;
// Act & assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () =>
await command.ExecuteAsync(
// Forceful cancellation (not required because we have a timeout)
CancellationToken.None,
// Graceful cancellation
cts.Token
)
);
stdOutBuffer.ToString().Trim().Should().ConsistOfLines(
"Started.",
"Cancelled."
);
}
[Fact] [Fact]
public async Task Command_can_receive_a_cancellation_signal_from_the_console() public async Task I_can_configure_the_command_to_listen_to_the_interrupt_signal_when_running_in_isolation()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -29,16 +77,18 @@ public class CancellationSpecs : SpecsBase
{ {
try try
{ {
console.Output.WriteLine("Started.");
await Task.Delay( await Task.Delay(
TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(3),
console.RegisterCancellationHandler() console.RegisterCancellationHandler()
); );
console.Output.WriteLine("Completed successfully"); console.Output.WriteLine("Completed.");
} }
catch (OperationCanceledException) catch (OperationCanceledException)
{ {
console.Output.WriteLine("Cancelled"); console.Output.WriteLine("Cancelled.");
throw; throw;
} }
} }
@@ -51,18 +101,21 @@ public class CancellationSpecs : SpecsBase
.UseConsole(FakeConsole) .UseConsole(FakeConsole)
.Build(); .Build();
// Act
FakeConsole.RequestCancellation(TimeSpan.FromSeconds(0.2)); FakeConsole.RequestCancellation(TimeSpan.FromSeconds(0.2));
// Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
Array.Empty<string>(), Array.Empty<string>(),
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().NotBe(0); exitCode.Should().NotBe(0);
stdOut.Trim().Should().Be("Cancelled");
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().ConsistOfLines(
"Started.",
"Cancelled."
);
} }
} }

View File

@@ -9,13 +9,13 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Basic.Reference.Assemblies.Net70" Version="1.4.1" /> <PackageReference Include="Basic.Reference.Assemblies.Net70" Version="1.4.2" />
<PackageReference Include="CliWrap" Version="3.6.0" /> <PackageReference Include="CliWrap" Version="3.6.1" />
<PackageReference Include="FluentAssertions" Version="6.10.0" /> <PackageReference Include="FluentAssertions" Version="6.11.0" />
<PackageReference Include="GitHubActionsTestLogger" Version="2.0.1" PrivateAssets="all" /> <PackageReference Include="GitHubActionsTestLogger" Version="2.2.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.5.0" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.6.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageReference Include="xunit" Version="2.4.2" /> <PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5" PrivateAssets="all" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.5" PrivateAssets="all" />
<PackageReference Include="coverlet.collector" Version="3.2.0" PrivateAssets="all" /> <PackageReference Include="coverlet.collector" Version="3.2.0" PrivateAssets="all" />

View File

@@ -22,10 +22,9 @@ public class ConsoleSpecs : SpecsBase
} }
[Fact(Timeout = 15000)] [Fact(Timeout = 15000)]
public async Task Real_console_maps_directly_to_system_console() public async Task I_can_run_the_application_with_the_default_console_implementation_to_interact_with_the_system_console()
{ {
// Can't verify our own console output, so using an // Can't verify our own console output, so using an external process for this test
// external process for this test.
// Arrange // Arrange
var command = "Hello world" | Cli.Wrap("dotnet") var command = "Hello world" | Cli.Wrap("dotnet")
@@ -43,7 +42,26 @@ public class ConsoleSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Fake_console_does_not_leak_to_system_console() public void I_can_run_the_application_on_a_system_with_a_custom_console_encoding_and_not_get_corrupted_output()
{
// Arrange
using var buffer = new MemoryStream();
using var consoleWriter = new ConsoleWriter(FakeConsole, buffer, Encoding.UTF8);
// Act
consoleWriter.Write("Hello world");
consoleWriter.Flush();
// Assert
var outputBytes = buffer.ToArray();
outputBytes.Should().NotContain(Encoding.UTF8.GetPreamble());
var output = consoleWriter.Encoding.GetString(outputBytes);
output.Should().Be("Hello world");
}
[Fact]
public async Task I_can_run_the_application_with_the_fake_console_implementation_to_isolate_console_interactions()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -104,7 +122,7 @@ public class ConsoleSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Fake_console_can_be_used_with_an_in_memory_backing_store() public async Task I_can_run_the_application_with_the_fake_console_implementation_and_simulate_stream_interactions()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -138,17 +156,18 @@ public class ConsoleSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
var stdErr = FakeConsole.ReadErrorString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("Hello world"); stdOut.Trim().Should().Be("Hello world");
var stdErr = FakeConsole.ReadErrorString();
stdErr.Trim().Should().Be("Hello world"); stdErr.Trim().Should().Be("Hello world");
} }
[Fact] [Fact]
public async Task Fake_console_can_read_key_presses() public async Task I_can_run_the_application_with_the_fake_console_implementation_and_simulate_key_presses()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -184,31 +203,14 @@ public class ConsoleSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().ConsistOfLines( stdOut.Trim().Should().ConsistOfLines(
"D0", "D0",
"A", "A",
"Backspace" "Backspace"
); );
} }
[Fact]
public void Console_does_not_emit_preamble_when_used_with_encoding_that_has_it()
{
// Arrange
using var buffer = new MemoryStream();
using var consoleWriter = new ConsoleWriter(FakeConsole, buffer, Encoding.UTF8);
// Act
consoleWriter.Write("Hello world");
consoleWriter.Flush();
var output = consoleWriter.Encoding.GetString(buffer.ToArray());
// Assert
output.Should().Be("Hello world");
}
} }

View File

@@ -16,7 +16,7 @@ public class ConversionSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_can_be_converted_to_a_string() public async Task I_can_bind_a_parameter_or_an_option_to_a_string_property()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -26,7 +26,7 @@ public class ConversionSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -48,15 +48,15 @@ public class ConversionSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("xyz"); stdOut.Trim().Should().Be("xyz");
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_can_be_converted_to_an_object() public async Task I_can_bind_a_parameter_or_an_option_to_an_object_property()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -66,7 +66,7 @@ public class ConversionSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public object Foo { get; set; } public object? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -88,15 +88,15 @@ public class ConversionSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("xyz"); stdOut.Trim().Should().Be("xyz");
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_can_be_converted_to_a_boolean() public async Task I_can_bind_a_parameter_or_an_option_to_a_boolean_property()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -106,15 +106,19 @@ public class ConversionSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public bool Foo { get; set; } public bool Foo { get; init; }
[CommandOption('b')] [CommandOption('b')]
public bool Bar { get; set; } public bool Bar { get; init; }
[CommandOption('c')]
public bool Baz { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine("Foo = " + Foo); console.Output.WriteLine("Foo = " + Foo);
console.Output.WriteLine("Bar = " + Bar); console.Output.WriteLine("Bar = " + Bar);
console.Output.WriteLine("Baz = " + Baz);
return default; return default;
} }
@@ -129,22 +133,28 @@ public class ConversionSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] {"-f", "true", "-b", "false"}, new[]
{
"-f", "true",
"-b", "false",
"-c"
},
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"Foo = True", "Foo = True",
"Bar = False" "Bar = False",
"Baz = True"
); );
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_can_be_converted_to_a_boolean_with_implicit_value() public async Task I_can_bind_a_parameter_or_an_option_to_an_integer_property()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -154,47 +164,7 @@ public class ConversionSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public bool Foo { get; set; } public int Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(Foo);
return default;
}
}
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.Build();
// Act
var exitCode = await application.RunAsync(
new[] {"-f"},
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
stdOut.Trim().Should().Be("True");
}
[Fact]
public async Task Parameter_or_option_value_can_be_converted_to_an_integer()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
[Command]
public class Command : ICommand
{
[CommandOption('f')]
public int Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -216,15 +186,15 @@ public class ConversionSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("32"); stdOut.Trim().Should().Be("32");
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_can_be_converted_to_a_double() public async Task I_can_bind_a_parameter_or_an_option_to_a_double_property()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -234,7 +204,7 @@ public class ConversionSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public double Foo { get; set; } public double Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -256,15 +226,15 @@ public class ConversionSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("32.14"); stdOut.Trim().Should().Be("32.14");
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_can_be_converted_to_DateTimeOffset() public async Task I_can_bind_a_parameter_or_an_option_to_a_DateTimeOffset_property()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -274,7 +244,7 @@ public class ConversionSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public DateTimeOffset Foo { get; set; } public DateTimeOffset Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -296,15 +266,15 @@ public class ConversionSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("1995-04-28 00:00:00Z"); stdOut.Trim().Should().Be("1995-04-28 00:00:00Z");
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_can_be_converted_to_a_TimeSpan() public async Task I_can_bind_a_parameter_or_an_option_to_a_TimeSpan_property()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -314,7 +284,7 @@ public class ConversionSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public TimeSpan Foo { get; set; } public TimeSpan Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -336,15 +306,15 @@ public class ConversionSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("12:34:56"); stdOut.Trim().Should().Be("12:34:56");
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_can_be_converted_to_an_enum() public async Task I_can_bind_a_parameter_or_an_option_to_an_enum_property()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -356,7 +326,7 @@ public class ConversionSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public CustomEnum Foo { get; set; } public CustomEnum Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -378,15 +348,15 @@ public class ConversionSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("2"); stdOut.Trim().Should().Be("2");
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_can_be_converted_to_a_nullable_integer() public async Task I_can_bind_a_parameter_or_an_option_to_a_nullable_integer_property()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -396,10 +366,10 @@ public class ConversionSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public int? Foo { get; set; } public int? Foo { get; init; }
[CommandOption('b')] [CommandOption('b')]
public int? Bar { get; set; } public int? Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -423,10 +393,10 @@ public class ConversionSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"Foo = ", "Foo = ",
"Bar = 123" "Bar = 123"
@@ -434,7 +404,7 @@ public class ConversionSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_can_be_converted_to_a_nullable_enum() public async Task I_can_bind_a_parameter_or_an_option_to_a_nullable_enum_property()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -446,10 +416,10 @@ public class ConversionSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public CustomEnum? Foo { get; set; } public CustomEnum? Foo { get; init; }
[CommandOption('b')] [CommandOption('b')]
public CustomEnum? Bar { get; set; } public CustomEnum? Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -473,10 +443,10 @@ public class ConversionSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"Foo = ", "Foo = ",
"Bar = 2" "Bar = 2"
@@ -484,7 +454,7 @@ public class ConversionSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_can_be_converted_to_a_type_that_has_a_constructor_accepting_a_string() public async Task I_can_bind_a_parameter_or_an_option_to_a_string_constructable_object_property()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -501,7 +471,7 @@ public class ConversionSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public CustomType Foo { get; set; } public CustomType? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -523,15 +493,15 @@ public class ConversionSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("xyz"); stdOut.Trim().Should().Be("xyz");
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_can_be_converted_to_a_type_that_has_a_static_parse_method() public async Task I_can_bind_a_parameter_or_an_option_to_a_string_parsable_object_property()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -561,10 +531,10 @@ public class ConversionSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public CustomTypeA Foo { get; set; } public CustomTypeA? Foo { get; init; }
[CommandOption('b')] [CommandOption('b')]
public CustomTypeB Bar { get; set; } public CustomTypeB? Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -588,10 +558,10 @@ public class ConversionSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"Foo = hello", "Foo = hello",
"Bar = world" "Bar = world"
@@ -599,7 +569,7 @@ public class ConversionSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_can_be_converted_using_a_custom_converter() public async Task I_can_bind_a_parameter_or_an_option_to_a_property_with_a_custom_converter()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -615,7 +585,7 @@ public class ConversionSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f', Converter = typeof(CustomConverter))] [CommandOption('f', Converter = typeof(CustomConverter))]
public int Foo { get; set; } public int Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -637,15 +607,15 @@ public class ConversionSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("11"); stdOut.Trim().Should().Be("11");
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_can_be_converted_to_an_array_of_strings() public async Task I_can_bind_a_parameter_or_an_option_to_a_string_array_property()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -655,7 +625,7 @@ public class ConversionSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string[] Foo { get; set; } public string[]? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -679,10 +649,10 @@ public class ConversionSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"one", "one",
"two", "two",
@@ -691,7 +661,7 @@ public class ConversionSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_can_be_converted_to_a_read_only_list_of_strings() public async Task I_can_bind_a_parameter_or_an_option_to_a_read_only_list_of_strings_property()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -701,7 +671,7 @@ public class ConversionSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public IReadOnlyList<string> Foo { get; set; } public IReadOnlyList<string>? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -725,10 +695,10 @@ public class ConversionSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"one", "one",
"two", "two",
@@ -737,7 +707,7 @@ public class ConversionSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_can_be_converted_to_a_list_of_strings() public async Task I_can_bind_a_parameter_or_an_option_to_a_string_list_property()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -747,7 +717,7 @@ public class ConversionSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public List<string> Foo { get; set; } public List<string>? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -771,10 +741,10 @@ public class ConversionSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"one", "one",
"two", "two",
@@ -783,7 +753,7 @@ public class ConversionSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_can_be_converted_to_an_array_of_integers() public async Task I_can_bind_a_parameter_or_an_option_to_an_integer_array_property()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -793,7 +763,7 @@ public class ConversionSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public int[] Foo { get; set; } public int[]? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -817,10 +787,10 @@ public class ConversionSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"1", "1",
"13", "13",
@@ -829,55 +799,21 @@ public class ConversionSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_conversion_fails_if_the_value_cannot_be_converted_to_the_target_type() public async Task I_cannot_bind_a_parameter_or_an_option_to_a_property_of_an_unsupported_type()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
// language=cs // language=cs
""" """
[Command] public class CustomType
public class Command : ICommand
{ {
[CommandOption('f')]
public int Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
} }
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.Build();
// Act
var exitCode = await application.RunAsync(
new[] {"-f", "12.34"},
new Dictionary<string, string>()
);
var stdErr = FakeConsole.ReadErrorString();
// Assert
exitCode.Should().NotBe(0);
stdErr.Should().NotBeNullOrWhiteSpace();
}
[Fact]
public async Task Parameter_or_option_value_conversion_fails_if_the_target_type_is_not_supported()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
public class CustomType {}
[Command] [Command]
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public CustomType Foo { get; set; } public CustomType? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -895,15 +831,15 @@ public class ConversionSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdErr = FakeConsole.ReadErrorString();
// Assert // Assert
exitCode.Should().NotBe(0); exitCode.Should().NotBe(0);
var stdErr = FakeConsole.ReadErrorString();
stdErr.Should().Contain("has an unsupported underlying property type"); stdErr.Should().Contain("has an unsupported underlying property type");
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_conversion_fails_if_the_target_non_scalar_type_is_not_supported() public async Task I_cannot_bind_a_parameter_or_an_option_to_a_non_scalar_property_of_an_unsupported_type()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -920,7 +856,7 @@ public class ConversionSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public CustomType Foo { get; set; } public CustomType? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -938,15 +874,51 @@ public class ConversionSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdErr = FakeConsole.ReadErrorString();
// Assert // Assert
exitCode.Should().NotBe(0); exitCode.Should().NotBe(0);
var stdErr = FakeConsole.ReadErrorString();
stdErr.Should().Contain("has an unsupported underlying property type"); stdErr.Should().Contain("has an unsupported underlying property type");
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_conversion_fails_if_one_of_the_validators_fail() public async Task I_can_bind_a_parameter_or_an_option_to_a_property_and_get_an_error_if_the_user_provides_an_invalid_value()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
[Command]
public class Command : ICommand
{
[CommandOption('f')]
public int Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default;
}
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.Build();
// Act
var exitCode = await application.RunAsync(
new[] {"-f", "12.34"},
new Dictionary<string, string>()
);
// Assert
exitCode.Should().NotBe(0);
var stdErr = FakeConsole.ReadErrorString();
stdErr.Should().NotBeNullOrWhiteSpace();
}
[Fact]
public async Task I_can_bind_a_parameter_or_an_option_to_a_property_and_get_an_error_if_a_custom_validator_fails()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -966,7 +938,7 @@ public class ConversionSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f', Validators = new[] {typeof(ValidatorA), typeof(ValidatorB)})] [CommandOption('f', Validators = new[] {typeof(ValidatorA), typeof(ValidatorB)})]
public int Foo { get; set; } public int Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -984,15 +956,15 @@ public class ConversionSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdErr = FakeConsole.ReadErrorString();
// Assert // Assert
exitCode.Should().NotBe(0); exitCode.Should().NotBe(0);
var stdErr = FakeConsole.ReadErrorString();
stdErr.Should().Contain("Hello world"); stdErr.Should().Contain("Hello world");
} }
[Fact] [Fact]
public async Task Parameter_or_option_value_conversion_fails_if_the_static_parse_method_throws() public async Task I_can_bind_a_parameter_or_an_option_to_a_string_parsable_property_and_get_an_error_if_the_parsing_fails()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -1011,7 +983,7 @@ public class ConversionSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public CustomType Foo { get; set; } public CustomType? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -1029,10 +1001,10 @@ public class ConversionSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdErr = FakeConsole.ReadErrorString();
// Assert // Assert
exitCode.Should().NotBe(0); exitCode.Should().NotBe(0);
var stdErr = FakeConsole.ReadErrorString();
stdErr.Should().Contain("Hello world"); stdErr.Should().Contain("Hello world");
} }
} }

View File

@@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using CliFx.Tests.Utils; using CliFx.Tests.Utils;
@@ -20,7 +19,7 @@ public class DirectivesSpecs : SpecsBase
} }
[Fact(Timeout = 15000)] [Fact(Timeout = 15000)]
public async Task Debug_directive_can_be_specified_to_interrupt_execution_until_a_debugger_is_attached() public async Task I_can_use_the_debug_directive_to_make_the_application_wait_for_the_debugger_to_attach()
{ {
// Arrange // Arrange
using var cts = new CancellationTokenSource(); using var cts = new CancellationTokenSource();
@@ -29,7 +28,7 @@ public class DirectivesSpecs : SpecsBase
void HandleStdOut(string line) void HandleStdOut(string line)
{ {
// Kill the process once it writes the output we expect // Kill the process once it writes the output we expect
if (line.Contains("Attach debugger to", StringComparison.OrdinalIgnoreCase)) if (line.Contains("Attach the debugger to", StringComparison.OrdinalIgnoreCase))
cts.Cancel(); cts.Cancel();
} }
@@ -51,7 +50,7 @@ public class DirectivesSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Preview_directive_can_be_specified_to_print_command_input() public async Task I_can_use_the_preview_directive_to_make_the_application_print_the_parsed_command_input()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -81,10 +80,10 @@ public class DirectivesSpecs : SpecsBase
} }
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ContainAllInOrder( stdOut.Should().ContainAllInOrder(
"cmd", "<param>", "[-a]", "[-b]", "[-c]", "[--option \"foo\"]", "cmd", "<param>", "[-a]", "[-b]", "[-c]", "[--option \"foo\"]",
"ENV_QOP", "=", "\"hello\"", "ENV_QOP", "=", "\"hello\"",

View File

@@ -20,7 +20,7 @@ public class EnvironmentSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Option_can_fall_back_to_an_environment_variable() public async Task I_can_configure_an_option_to_fall_back_to_an_environment_variable_if_the_user_does_not_provide_the_corresponding_argument()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -29,12 +29,17 @@ public class EnvironmentSpecs : SpecsBase
[Command] [Command]
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption("foo", IsRequired = true, EnvironmentVariable = "ENV_FOO")] [CommandOption("foo", EnvironmentVariable = "ENV_FOO")]
public string Foo { get; set; } public string? Foo { get; init; }
[CommandOption("bar", EnvironmentVariable = "ENV_BAR")]
public string? Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine(Foo); console.Output.WriteLine(Foo);
console.Output.WriteLine(Bar);
return default; return default;
} }
} }
@@ -48,22 +53,26 @@ public class EnvironmentSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
Array.Empty<string>(), new[] {"--foo", "42"},
new Dictionary<string, string> new Dictionary<string, string>
{ {
["ENV_FOO"] = "bar" ["ENV_FOO"] = "100",
["ENV_BAR"] = "200"
} }
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
stdOut.Trim().Should().Be("bar");
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().ConsistOfLines(
"42",
"200"
);
} }
[Fact] [Fact]
public async Task Option_does_not_fall_back_to_an_environment_variable_if_a_value_is_provided_through_arguments() public async Task I_can_configure_an_option_bound_to_a_non_scalar_property_to_fall_back_to_an_environment_variable_if_the_user_does_not_provide_the_corresponding_argument()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -73,50 +82,7 @@ public class EnvironmentSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption("foo", EnvironmentVariable = "ENV_FOO")] [CommandOption("foo", EnvironmentVariable = "ENV_FOO")]
public string Foo { get; set; } public IReadOnlyList<string>? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(Foo);
return default;
}
}
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.Build();
// Act
var exitCode = await application.RunAsync(
new[] {"--foo", "baz"},
new Dictionary<string, string>
{
["ENV_FOO"] = "bar"
}
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
stdOut.Trim().Should().Be("baz");
}
[Fact]
public async Task Option_of_non_scalar_type_can_receive_multiple_values_from_an_environment_variable()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
[Command]
public class Command : ICommand
{
[CommandOption("foo", EnvironmentVariable = "ENV_FOO")]
public IReadOnlyList<string> Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -143,10 +109,10 @@ public class EnvironmentSpecs : SpecsBase
} }
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"bar", "bar",
"baz" "baz"
@@ -154,7 +120,7 @@ public class EnvironmentSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Option_of_scalar_type_always_receives_a_single_value_from_an_environment_variable() public async Task I_can_configure_an_option_bound_to_a_scalar_property_to_fall_back_to_an_environment_variable_while_ignoring_path_separators()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -164,7 +130,7 @@ public class EnvironmentSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption("foo", EnvironmentVariable = "ENV_FOO")] [CommandOption("foo", EnvironmentVariable = "ENV_FOO")]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -189,60 +155,15 @@ public class EnvironmentSpecs : SpecsBase
} }
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be($"bar{Path.PathSeparator}baz"); stdOut.Trim().Should().Be($"bar{Path.PathSeparator}baz");
} }
[Fact]
public async Task Environment_variables_are_matched_case_sensitively()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
[Command]
public class Command : ICommand
{
[CommandOption("foo", EnvironmentVariable = "ENV_FOO")]
public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console)
{
console.Output.WriteLine(Foo);
return default;
}
}
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.Build();
// Act
var exitCode = await application.RunAsync(
Array.Empty<string>(),
new Dictionary<string, string>
{
["ENV_foo"] = "baz",
["ENV_FOO"] = "bar",
["env_FOO"] = "qop"
}
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
stdOut.Trim().Should().Be("bar");
}
[Fact(Timeout = 15000)] [Fact(Timeout = 15000)]
public async Task Environment_variables_are_extracted_automatically() public async Task I_can_run_the_application_and_it_will_resolve_all_required_environment_variables_automatically()
{ {
// Ensures that the environment variables are properly obtained from // Ensures that the environment variables are properly obtained from
// System.Environment when they are not provided explicitly to CliApplication. // System.Environment when they are not provided explicitly to CliApplication.

View File

@@ -17,7 +17,7 @@ public class ErrorReportingSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Command_can_throw_an_exception_which_exits_with_a_stacktrace() public async Task I_can_throw_an_exception_in_a_command_to_report_an_error_with_a_stacktrace()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -43,12 +43,13 @@ public class ErrorReportingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
var stdErr = FakeConsole.ReadErrorString();
// Assert // Assert
exitCode.Should().NotBe(0); exitCode.Should().NotBe(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().BeEmpty(); stdOut.Should().BeEmpty();
var stdErr = FakeConsole.ReadErrorString();
stdErr.Should().ContainAllInOrder( stdErr.Should().ContainAllInOrder(
"System.Exception", "Something went wrong", "System.Exception", "Something went wrong",
"at", "CliFx." "at", "CliFx."
@@ -56,7 +57,7 @@ public class ErrorReportingSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Command_can_throw_an_exception_with_an_inner_exception_which_exits_with_a_stacktrace() public async Task I_can_throw_an_exception_with_an_inner_exception_in_a_command_to_report_an_error_with_a_stacktrace()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -82,12 +83,13 @@ public class ErrorReportingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
var stdErr = FakeConsole.ReadErrorString();
// Assert // Assert
exitCode.Should().NotBe(0); exitCode.Should().NotBe(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().BeEmpty(); stdOut.Should().BeEmpty();
var stdErr = FakeConsole.ReadErrorString();
stdErr.Should().ContainAllInOrder( stdErr.Should().ContainAllInOrder(
"System.Exception", "Something went wrong", "System.Exception", "Something went wrong",
"System.Exception", "Another exception", "System.Exception", "Another exception",
@@ -96,7 +98,7 @@ public class ErrorReportingSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Command_can_throw_a_special_exception_which_exits_with_specified_code_and_message() public async Task I_can_throw_an_exception_in_a_command_to_report_an_error_and_exit_with_the_specified_code()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -122,17 +124,18 @@ public class ErrorReportingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
var stdErr = FakeConsole.ReadErrorString();
// Assert // Assert
exitCode.Should().Be(69); exitCode.Should().Be(69);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().BeEmpty(); stdOut.Should().BeEmpty();
var stdErr = FakeConsole.ReadErrorString();
stdErr.Trim().Should().Be("Something went wrong"); stdErr.Trim().Should().Be("Something went wrong");
} }
[Fact] [Fact]
public async Task Command_can_throw_a_special_exception_without_message_which_exits_with_a_stacktrace() public async Task I_can_throw_an_exception_without_a_message_in_a_command_to_report_an_error_with_a_stacktrace()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -158,12 +161,13 @@ public class ErrorReportingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
var stdErr = FakeConsole.ReadErrorString();
// Assert // Assert
exitCode.Should().Be(69); exitCode.Should().Be(69);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().BeEmpty(); stdOut.Should().BeEmpty();
var stdErr = FakeConsole.ReadErrorString();
stdErr.Should().ContainAllInOrder( stdErr.Should().ContainAllInOrder(
"CliFx.Exceptions.CommandException", "CliFx.Exceptions.CommandException",
"at", "CliFx." "at", "CliFx."
@@ -171,7 +175,7 @@ public class ErrorReportingSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Command_can_throw_a_special_exception_which_prints_help_text_before_exiting() public async Task I_can_throw_an_exception_in_a_command_to_report_an_error_and_print_the_help_text()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -198,12 +202,13 @@ public class ErrorReportingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
var stdErr = FakeConsole.ReadErrorString();
// Assert // Assert
exitCode.Should().Be(69); exitCode.Should().Be(69);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().Contain("This will be in help text"); stdOut.Should().Contain("This will be in help text");
var stdErr = FakeConsole.ReadErrorString();
stdErr.Trim().Should().Be("Something went wrong"); stdErr.Trim().Should().Be("Something went wrong");
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -17,7 +17,7 @@ public class OptionBindingSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Option_is_bound_from_an_argument_matching_its_name() public async Task I_can_bind_an_option_to_a_property_and_get_the_value_from_the_corresponding_argument_by_name()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -27,7 +27,7 @@ public class OptionBindingSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption("foo")] [CommandOption("foo")]
public bool Foo { get; set; } public bool Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -49,15 +49,15 @@ public class OptionBindingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("True"); stdOut.Trim().Should().Be("True");
} }
[Fact] [Fact]
public async Task Option_is_bound_from_an_argument_matching_its_short_name() public async Task I_can_bind_an_option_to_a_property_and_get_the_value_from_the_corresponding_argument_by_short_name()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -67,7 +67,7 @@ public class OptionBindingSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public bool Foo { get; set; } public bool Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -89,15 +89,15 @@ public class OptionBindingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("True"); stdOut.Trim().Should().Be("True");
} }
[Fact] [Fact]
public async Task Option_is_bound_from_a_set_of_arguments_matching_its_name() public async Task I_can_bind_an_option_to_a_property_and_get_the_value_from_the_corresponding_argument_set_by_name()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -107,10 +107,10 @@ public class OptionBindingSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption("foo")] [CommandOption("foo")]
public string Foo { get; set; } public string? Foo { get; init; }
[CommandOption("bar")] [CommandOption("bar")]
public string Bar { get; set; } public string? Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -130,14 +130,18 @@ public class OptionBindingSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] {"--foo", "one", "--bar", "two"}, new[]
{
"--foo", "one",
"--bar", "two"
},
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"Foo = one", "Foo = one",
"Bar = two" "Bar = two"
@@ -145,7 +149,7 @@ public class OptionBindingSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Option_is_bound_from_a_set_of_arguments_matching_its_short_name() public async Task I_can_bind_an_option_to_a_property_and_get_the_value_from_the_corresponding_argument_set_by_short_name()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -155,10 +159,10 @@ public class OptionBindingSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string Foo { get; set; } public string? Foo { get; init; }
[CommandOption('b')] [CommandOption('b')]
public string Bar { get; set; } public string? Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -178,14 +182,18 @@ public class OptionBindingSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] {"-f", "one", "-b", "two"}, new[]
{
"-f", "one",
"-b", "two"
},
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"Foo = one", "Foo = one",
"Bar = two" "Bar = two"
@@ -193,7 +201,7 @@ public class OptionBindingSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Option_is_bound_from_a_stack_of_arguments_matching_its_short_name() public async Task I_can_bind_an_option_to_a_property_and_get_the_value_from_the_corresponding_argument_stack_by_short_name()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -203,10 +211,10 @@ public class OptionBindingSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public string Foo { get; set; } public string? Foo { get; init; }
[CommandOption('b')] [CommandOption('b')]
public string Bar { get; set; } public string? Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -230,10 +238,10 @@ public class OptionBindingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"Foo = ", "Foo = ",
"Bar = value" "Bar = value"
@@ -241,7 +249,7 @@ public class OptionBindingSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Option_of_non_scalar_type_is_bound_from_a_set_of_arguments_matching_its_name() public async Task I_can_bind_an_option_to_a_non_scalar_property_and_get_the_values_from_the_corresponding_arguments_by_name()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -251,7 +259,7 @@ public class OptionBindingSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption("Foo")] [CommandOption("Foo")]
public IReadOnlyList<string> Foo { get; set; } public IReadOnlyList<string>? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -275,10 +283,10 @@ public class OptionBindingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"one", "one",
"two", "two",
@@ -287,7 +295,7 @@ public class OptionBindingSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Option_of_non_scalar_type_is_bound_from_a_set_of_arguments_matching_its_short_name() public async Task I_can_bind_an_option_to_a_non_scalar_property_and_get_the_values_from_the_corresponding_arguments_by_short_name()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -297,7 +305,7 @@ public class OptionBindingSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public IReadOnlyList<string> Foo { get; set; } public IReadOnlyList<string>? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -321,10 +329,10 @@ public class OptionBindingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"one", "one",
"two", "two",
@@ -333,7 +341,7 @@ public class OptionBindingSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Option_of_non_scalar_type_is_bound_from_multiple_sets_of_arguments_matching_its_name() public async Task I_can_bind_an_option_to_a_non_scalar_property_and_get_the_values_from_the_corresponding_argument_sets_by_name()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -343,7 +351,7 @@ public class OptionBindingSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption("foo")] [CommandOption("foo")]
public IReadOnlyList<string> Foo { get; set; } public IReadOnlyList<string>? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -363,14 +371,19 @@ public class OptionBindingSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] {"--foo", "one", "--foo", "two", "--foo", "three"}, new[]
{
"--foo", "one",
"--foo", "two",
"--foo", "three"
},
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"one", "one",
"two", "two",
@@ -379,7 +392,7 @@ public class OptionBindingSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Option_of_non_scalar_type_is_bound_from_multiple_sets_of_arguments_matching_its_short_name() public async Task I_can_bind_an_option_to_a_non_scalar_property_and_get_the_values_from_the_corresponding_argument_sets_by_short_name()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -389,7 +402,7 @@ public class OptionBindingSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption('f')] [CommandOption('f')]
public IReadOnlyList<string> Foo { get; set; } public IReadOnlyList<string>? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -409,14 +422,19 @@ public class OptionBindingSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] {"-f", "one", "-f", "two", "-f", "three"}, new[]
{
"-f", "one",
"-f", "two",
"-f", "three"
},
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"one", "one",
"two", "two",
@@ -425,7 +443,7 @@ public class OptionBindingSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Option_of_non_scalar_type_is_bound_from_multiple_sets_of_arguments_matching_its_name_or_short_name() public async Task I_can_bind_an_option_to_a_non_scalar_property_and_get_the_values_from_the_corresponding_argument_sets_by_name_or_short_name()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -435,7 +453,7 @@ public class OptionBindingSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption("foo", 'f')] [CommandOption("foo", 'f')]
public IReadOnlyList<string> Foo { get; set; } public IReadOnlyList<string>? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -455,14 +473,19 @@ public class OptionBindingSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] {"--foo", "one", "-f", "two", "--foo", "three"}, new[]
{
"--foo", "one",
"-f", "two",
"--foo", "three"
},
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"one", "one",
"two", "two",
@@ -471,7 +494,7 @@ public class OptionBindingSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Option_is_not_bound_if_there_are_no_arguments_matching_its_name_or_short_name() public async Task I_can_bind_an_option_to_a_property_and_get_no_value_if_the_user_does_not_provide_the_corresponding_argument()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -481,10 +504,10 @@ public class OptionBindingSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption("foo")] [CommandOption("foo")]
public string Foo { get; set; } public string? Foo { get; init; }
[CommandOption("bar")] [CommandOption("bar")]
public string Bar { get; set; } = "hello"; public string? Bar { get; init; } = "hello";
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -508,10 +531,10 @@ public class OptionBindingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"Foo = one", "Foo = one",
"Bar = hello" "Bar = hello"
@@ -519,7 +542,7 @@ public class OptionBindingSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Option_binding_supports_multiple_inheritance_through_default_interface_members() public async Task I_can_bind_an_option_to_a_property_through_multiple_inheritance()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -538,7 +561,7 @@ public class OptionBindingSpecs : SpecsBase
public int Foo public int Foo
{ {
get => SharedContext.Foo; get => SharedContext.Foo;
set => SharedContext.Foo = value; init => SharedContext.Foo = value;
} }
} }
@@ -548,20 +571,20 @@ public class OptionBindingSpecs : SpecsBase
public bool Bar public bool Bar
{ {
get => SharedContext.Bar; get => SharedContext.Bar;
set => SharedContext.Bar = value; init => SharedContext.Bar = value;
} }
} }
public interface IHasBaz : ICommand public interface IHasBaz : ICommand
{ {
public string Baz { get; set; } public string? Baz { get; init; }
} }
[Command] [Command]
public class Command : IHasFoo, IHasBar, IHasBaz public class Command : IHasFoo, IHasBar, IHasBaz
{ {
[CommandOption("baz")] [CommandOption("baz")]
public string Baz { get; set; } public string? Baz { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -582,13 +605,18 @@ public class OptionBindingSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] { "--foo", "42", "--bar", "--baz", "xyz" } new[]
{
"--foo", "42",
"--bar",
"--baz", "xyz"
}
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"Foo = 42", "Foo = 42",
"Bar = True", "Bar = True",
@@ -597,7 +625,7 @@ public class OptionBindingSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Option_binding_does_not_consider_a_negative_number_as_an_option_name_or_short_name() public async Task I_can_bind_an_option_to_a_property_and_get_the_correct_value_if_the_user_provides_an_argument_containing_a_negative_number()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -607,12 +635,11 @@ public class OptionBindingSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption("foo")] [CommandOption("foo")]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
console.Output.WriteLine(Foo); console.Output.WriteLine(Foo);
return default; return default;
} }
} }
@@ -630,15 +657,15 @@ public class OptionBindingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("-13"); stdOut.Trim().Should().Be("-13");
} }
[Fact] [Fact]
public async Task Option_binding_fails_if_a_required_option_has_not_been_provided() public async Task I_can_bind_a_required_option_to_a_property_and_get_an_error_if_the_user_does_not_provide_the_corresponding_argument()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -647,8 +674,8 @@ public class OptionBindingSpecs : SpecsBase
[Command] [Command]
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption("foo", IsRequired = true)] [CommandOption("foo")]
public string Foo { get; set; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -666,87 +693,15 @@ public class OptionBindingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdErr = FakeConsole.ReadErrorString();
// Assert // Assert
exitCode.Should().NotBe(0); exitCode.Should().NotBe(0);
var stdErr = FakeConsole.ReadErrorString();
stdErr.Should().Contain("Missing required option(s)"); stdErr.Should().Contain("Missing required option(s)");
} }
[Fact] [Fact]
public async Task Option_binding_fails_if_a_required_option_has_been_provided_with_an_empty_value() public async Task I_can_bind_a_required_option_to_a_property_and_get_an_error_if_the_user_provides_an_empty_argument()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
[Command]
public class Command : ICommand
{
[CommandOption("foo", IsRequired = true)]
public string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
}
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.Build();
// Act
var exitCode = await application.RunAsync(
new[] {"--foo"},
new Dictionary<string, string>()
);
var stdErr = FakeConsole.ReadErrorString();
// Assert
exitCode.Should().NotBe(0);
stdErr.Should().Contain("Missing required option(s)");
}
[Fact]
public async Task Option_binding_fails_if_a_required_option_of_non_scalar_type_has_not_been_provided_with_at_least_one_value()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
[Command]
public class Command : ICommand
{
[CommandOption("foo", IsRequired = true)]
public IReadOnlyList<string> Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
}
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.Build();
// Act
var exitCode = await application.RunAsync(
new[] {"--foo"},
new Dictionary<string, string>()
);
var stdErr = FakeConsole.ReadErrorString();
// Assert
exitCode.Should().NotBe(0);
stdErr.Should().Contain("Missing required option(s)");
}
[Fact]
public async Task Option_binding_fails_if_one_of_the_provided_option_names_is_not_recognized()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -756,7 +711,7 @@ public class OptionBindingSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption("foo")] [CommandOption("foo")]
public string Foo { get; set; } public required string Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -770,19 +725,95 @@ public class OptionBindingSpecs : SpecsBase
// Act // Act
var exitCode = await application.RunAsync( var exitCode = await application.RunAsync(
new[] {"--foo", "one", "--bar", "two"}, new[] {"--foo"},
new Dictionary<string, string>() new Dictionary<string, string>()
); );
// Assert
exitCode.Should().NotBe(0);
var stdErr = FakeConsole.ReadErrorString(); var stdErr = FakeConsole.ReadErrorString();
stdErr.Should().Contain("Missing required option(s)");
}
[Fact]
public async Task I_can_bind_an_option_to_a_non_scalar_property_and_get_an_error_if_the_user_does_not_provide_at_least_one_corresponding_argument()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
[Command]
public class Command : ICommand
{
[CommandOption("foo")]
public required IReadOnlyList<string> Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default;
}
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.Build();
// Act
var exitCode = await application.RunAsync(
new[] {"--foo"},
new Dictionary<string, string>()
);
// Assert // Assert
exitCode.Should().NotBe(0); exitCode.Should().NotBe(0);
var stdErr = FakeConsole.ReadErrorString();
stdErr.Should().Contain("Missing required option(s)");
}
[Fact]
public async Task I_can_bind_options_and_get_an_error_if_the_user_provides_unrecognized_arguments()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
[Command]
public class Command : ICommand
{
[CommandOption("foo")]
public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default;
}
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.Build();
// Act
var exitCode = await application.RunAsync(
new[]
{
"--foo", "one",
"--bar", "two"
},
new Dictionary<string, string>()
);
// Assert
exitCode.Should().NotBe(0);
var stdErr = FakeConsole.ReadErrorString();
stdErr.Should().Contain("Unrecognized option(s)"); stdErr.Should().Contain("Unrecognized option(s)");
} }
[Fact] [Fact]
public async Task Option_binding_fails_if_an_option_of_scalar_type_has_been_provided_with_multiple_values() public async Task I_can_bind_an_option_to_a_scalar_property_and_get_an_error_if_the_user_provides_too_many_arguments()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -792,7 +823,7 @@ public class OptionBindingSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandOption("foo")] [CommandOption("foo")]
public string Foo { get; set; } public string? Foo { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -810,46 +841,10 @@ public class OptionBindingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdErr = FakeConsole.ReadErrorString();
// Assert // Assert
exitCode.Should().NotBe(0); exitCode.Should().NotBe(0);
var stdErr = FakeConsole.ReadErrorString();
stdErr.Should().Contain("expects a single argument, but provided with multiple"); stdErr.Should().Contain("expects a single argument, but provided with multiple");
} }
[Fact]
public async Task Option_binding_fails_if_a_required_property_option_has_not_been_provided()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
[Command]
public class Command : ICommand
{
[CommandOption("foo")]
public required string Foo { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
}
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.Build();
// Act
var exitCode = await application.RunAsync(
Array.Empty<string>(),
new Dictionary<string, string>()
);
var stdErr = FakeConsole.ReadErrorString();
// Assert
exitCode.Should().NotBe(0);
stdErr.Should().Contain("Missing required option(s)");
}
} }

View File

@@ -16,7 +16,7 @@ public class ParameterBindingSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Parameter_is_bound_from_an_argument_matching_its_order() public async Task I_can_bind_a_parameter_to_a_property_and_get_the_value_from_the_corresponding_argument()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -26,10 +26,10 @@ public class ParameterBindingSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public required string Foo { get; init; }
[CommandParameter(1)] [CommandParameter(1)]
public string Bar { get; set; } public required string Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -53,10 +53,10 @@ public class ParameterBindingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"Foo = one", "Foo = one",
"Bar = two" "Bar = two"
@@ -64,7 +64,7 @@ public class ParameterBindingSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Parameter_of_non_scalar_type_is_bound_from_remaining_non_option_arguments() public async Task I_can_bind_a_parameter_to_a_non_scalar_property_and_get_values_from_the_remaining_non_option_arguments()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -74,16 +74,16 @@ public class ParameterBindingSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public required string Foo { get; init; }
[CommandParameter(1)] [CommandParameter(1)]
public string Bar { get; set; } public required string Bar { get; init; }
[CommandParameter(2)] [CommandParameter(2)]
public IReadOnlyList<string> Baz { get; set; } public required IReadOnlyList<string> Baz { get; init; }
[CommandOption("boo")] [CommandOption("boo")]
public string Boo { get; set; } public string? Boo { get; init; }
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -110,10 +110,10 @@ public class ParameterBindingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"Foo = one", "Foo = one",
"Bar = two", "Bar = two",
@@ -124,7 +124,7 @@ public class ParameterBindingSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Parameter_is_not_bound_if_there_are_no_arguments_matching_its_order() public async Task I_can_bind_a_parameter_to_a_property_and_get_an_error_if_the_user_does_not_provide_the_corresponding_argument()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -134,10 +134,88 @@ public class ParameterBindingSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public required string Foo { get; init; }
[CommandParameter(1)]
public required string Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default;
}
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.Build();
// Act
var exitCode = await application.RunAsync(
new[] {"one"},
new Dictionary<string, string>()
);
// Assert
exitCode.Should().NotBe(0);
var stdErr = FakeConsole.ReadErrorString();
stdErr.Should().Contain("Missing required parameter(s)");
}
[Fact]
public async Task I_can_bind_a_parameter_to_a_non_scalar_property_and_get_an_error_if_the_user_does_not_provide_at_least_one_corresponding_argument()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
[Command]
public class Command : ICommand
{
[CommandParameter(0)]
public required string Foo { get; init; }
[CommandParameter(1)]
public required IReadOnlyList<string> Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default;
}
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.Build();
// Act
var exitCode = await application.RunAsync(
new[] {"one"},
new Dictionary<string, string>()
);
// Assert
exitCode.Should().NotBe(0);
var stdErr = FakeConsole.ReadErrorString();
stdErr.Should().Contain("Missing required parameter(s)");
}
[Fact]
public async Task I_can_bind_a_non_required_parameter_to_a_property_and_get_no_value_if_the_user_does_not_provide_the_corresponding_argument()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
[Command]
public class Command : ICommand
{
[CommandParameter(0)]
public required string Foo { get; init; }
[CommandParameter(1, IsRequired = false)] [CommandParameter(1, IsRequired = false)]
public string Bar { get; set; } = "xyz"; public string? Bar { get; init; } = "xyz";
public ValueTask ExecuteAsync(IConsole console) public ValueTask ExecuteAsync(IConsole console)
{ {
@@ -161,10 +239,10 @@ public class ParameterBindingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ConsistOfLines( stdOut.Should().ConsistOfLines(
"Foo = abc", "Foo = abc",
"Bar = xyz" "Bar = xyz"
@@ -172,7 +250,7 @@ public class ParameterBindingSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Parameter_binding_fails_if_a_required_parameter_has_not_been_provided() public async Task I_can_bind_parameters_and_get_an_error_if_the_user_provides_too_many_arguments()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -182,88 +260,10 @@ public class ParameterBindingSpecs : SpecsBase
public class Command : ICommand public class Command : ICommand
{ {
[CommandParameter(0)] [CommandParameter(0)]
public string Foo { get; set; } public required string Foo { get; init; }
[CommandParameter(1)] [CommandParameter(1)]
public string Bar { get; set; } public required string Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default;
}
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.Build();
// Act
var exitCode = await application.RunAsync(
new[] {"one"},
new Dictionary<string, string>()
);
var stdErr = FakeConsole.ReadErrorString();
// Assert
exitCode.Should().NotBe(0);
stdErr.Should().Contain("Missing required parameter(s)");
}
[Fact]
public async Task Parameter_binding_fails_if_a_parameter_of_non_scalar_type_has_not_been_provided_with_at_least_one_value()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
[Command]
public class Command : ICommand
{
[CommandParameter(0)]
public string Foo { get; set; }
[CommandParameter(1)]
public IReadOnlyList<string> Bar { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default;
}
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
.UseConsole(FakeConsole)
.Build();
// Act
var exitCode = await application.RunAsync(
new[] {"one"},
new Dictionary<string, string>()
);
var stdErr = FakeConsole.ReadErrorString();
// Assert
exitCode.Should().NotBe(0);
stdErr.Should().Contain("Missing required parameter(s)");
}
[Fact]
public async Task Parameter_binding_fails_if_one_of_the_provided_parameters_is_unexpected()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
[Command]
public class Command : ICommand
{
[CommandParameter(0)]
public string Foo { get; set; }
[CommandParameter(1)]
public string Bar { get; set; }
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }
@@ -281,10 +281,10 @@ public class ParameterBindingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdErr = FakeConsole.ReadErrorString();
// Assert // Assert
exitCode.Should().NotBe(0); exitCode.Should().NotBe(0);
var stdErr = FakeConsole.ReadErrorString();
stdErr.Should().Contain("Unexpected parameter(s)"); stdErr.Should().Contain("Unexpected parameter(s)");
} }
} }

View File

@@ -16,7 +16,7 @@ public class RoutingSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Default_command_is_executed_if_provided_arguments_do_not_match_any_named_command() public async Task I_can_configure_a_command_to_be_executed_by_default_when_the_user_does_not_specify_a_command_name()
{ {
// Arrange // Arrange
var commandTypes = DynamicCommandBuilder.CompileMany( var commandTypes = DynamicCommandBuilder.CompileMany(
@@ -65,15 +65,15 @@ public class RoutingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("default"); stdOut.Trim().Should().Be("default");
} }
[Fact] [Fact]
public async Task Specific_named_command_is_executed_if_provided_arguments_match_its_name() public async Task I_can_configure_a_command_to_be_executed_when_the_user_specifies_its_name()
{ {
// Arrange // Arrange
var commandTypes = DynamicCommandBuilder.CompileMany( var commandTypes = DynamicCommandBuilder.CompileMany(
@@ -122,15 +122,15 @@ public class RoutingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("cmd"); stdOut.Trim().Should().Be("cmd");
} }
[Fact] [Fact]
public async Task Specific_named_child_command_is_executed_if_provided_arguments_match_its_name() public async Task I_can_configure_a_nested_command_to_be_executed_when_the_user_specifies_its_name()
{ {
// Arrange // Arrange
var commandTypes = DynamicCommandBuilder.CompileMany( var commandTypes = DynamicCommandBuilder.CompileMany(
@@ -179,10 +179,10 @@ public class RoutingSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("cmd child"); stdOut.Trim().Should().Be("cmd child");
} }
} }

View File

@@ -18,7 +18,7 @@ public class TypeActivationSpecs : SpecsBase
} }
[Fact] [Fact]
public async Task Default_type_activator_can_initialize_a_type_if_it_has_a_parameterless_constructor() public async Task I_can_configure_the_application_to_use_the_default_type_activator_to_initialize_types_through_parameterless_constructors()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -48,15 +48,15 @@ public class TypeActivationSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("foo"); stdOut.Trim().Should().Be("foo");
} }
[Fact] [Fact]
public async Task Default_type_activator_fails_if_the_type_does_not_have_a_parameterless_constructor() public async Task I_can_configure_the_application_to_use_the_default_type_activator_and_get_an_error_if_the_requested_type_does_not_have_a_parameterless_constructor()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -84,15 +84,15 @@ public class TypeActivationSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdErr = FakeConsole.ReadErrorString();
// Assert // Assert
exitCode.Should().NotBe(0); exitCode.Should().NotBe(0);
var stdErr = FakeConsole.ReadErrorString();
stdErr.Should().Contain("Failed to create an instance of type"); stdErr.Should().Contain("Failed to create an instance of type");
} }
[Fact] [Fact]
public async Task Custom_type_activator_can_initialize_a_type_using_a_given_function() public async Task I_can_configure_the_application_to_use_a_custom_type_activator_to_initialize_types_using_a_delegate()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -126,15 +126,15 @@ public class TypeActivationSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("Hello world"); stdOut.Trim().Should().Be("Hello world");
} }
[Fact] [Fact]
public async Task Custom_type_activator_can_initialize_a_type_using_a_service_provider() public async Task I_can_configure_the_application_to_use_a_custom_type_activator_to_initialize_types_using_a_service_provider()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -156,14 +156,23 @@ public class TypeActivationSpecs : SpecsBase
""" """
); );
var serviceProvider = new ServiceCollection()
.AddSingleton(commandType, Activator.CreateInstance(commandType, "Hello world")!)
.BuildServiceProvider();
var application = new CliApplicationBuilder() var application = new CliApplicationBuilder()
.AddCommand(commandType) .AddCommand(commandType)
.UseConsole(FakeConsole) .UseConsole(FakeConsole)
.UseTypeActivator(serviceProvider) .UseTypeActivator(commandTypes =>
{
var services = new ServiceCollection();
foreach (var serviceType in commandTypes)
{
services.AddSingleton(
serviceType,
Activator.CreateInstance(serviceType, "Hello world")!
);
}
return services.BuildServiceProvider();
})
.Build(); .Build();
// Act // Act
@@ -172,15 +181,15 @@ public class TypeActivationSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdOut = FakeConsole.ReadOutputString();
// Assert // Assert
exitCode.Should().Be(0); exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("Hello world"); stdOut.Trim().Should().Be("Hello world");
} }
[Fact] [Fact]
public async Task Custom_type_activator_fails_if_the_underlying_function_returns_null() public async Task I_can_configure_the_application_to_use_a_custom_type_activator_and_get_an_error_if_the_requested_type_cannot_be_initialized()
{ {
// Arrange // Arrange
var commandType = DynamicCommandBuilder.Compile( var commandType = DynamicCommandBuilder.Compile(
@@ -201,7 +210,7 @@ public class TypeActivationSpecs : SpecsBase
var application = new CliApplicationBuilder() var application = new CliApplicationBuilder()
.AddCommand(commandType) .AddCommand(commandType)
.UseConsole(FakeConsole) .UseConsole(FakeConsole)
.UseTypeActivator(_ => null!) .UseTypeActivator((Type _) => null!)
.Build(); .Build();
// Act // Act
@@ -210,10 +219,10 @@ public class TypeActivationSpecs : SpecsBase
new Dictionary<string, string>() new Dictionary<string, string>()
); );
var stdErr = FakeConsole.ReadErrorString();
// Assert // Assert
exitCode.Should().NotBe(0); exitCode.Should().NotBe(0);
var stdErr = FakeConsole.ReadErrorString();
stdErr.Should().Contain("Failed to create an instance of type"); stdErr.Should().Contain("Failed to create an instance of type");
} }
} }

View File

@@ -11,14 +11,9 @@ using Microsoft.CodeAnalysis.Text;
namespace CliFx.Tests.Utils; namespace CliFx.Tests.Utils;
// This class uses Roslyn to compile commands dynamically. // This class uses Roslyn to compile commands dynamically.
// // It allows us to collocate commands with tests more easily, which helps a lot when reasoning about them.
// It allows us to collocate commands with tests more // Unfortunately, this comes at a cost of static typing, but this is still a worthwhile trade off.
// easily, which helps a lot when reasoning about them. // Maybe one day C# will allow declaring classes inside methods and doing this will no longer be necessary.
// Unfortunately, this comes at a cost of static typing,
// but this is still a worthwhile trade off.
//
// Maybe one day C# will allow declaring classes inside
// methods and doing this will no longer be necessary.
// Language proposal: https://github.com/dotnet/csharplang/discussions/130 // Language proposal: https://github.com/dotnet/csharplang/discussions/130
internal static class DynamicCommandBuilder internal static class DynamicCommandBuilder
{ {
@@ -124,7 +119,6 @@ internal static class DynamicCommandBuilder
public static Type Compile(string sourceCode) public static Type Compile(string sourceCode)
{ {
var commandTypes = CompileMany(sourceCode); var commandTypes = CompileMany(sourceCode);
if (commandTypes.Count > 1) if (commandTypes.Count > 1)
{ {
throw new InvalidOperationException( throw new InvalidOperationException(

View File

@@ -41,7 +41,7 @@ internal static class AssertionExtensions
lastIndex = index; lastIndex = index;
} }
return new(assertions); return new AndConstraint<StringAssertions>(assertions);
} }
public static AndConstraint<StringAssertions> ContainAllInOrder( public static AndConstraint<StringAssertions> ContainAllInOrder(

View File

@@ -5,7 +5,7 @@ using CliFx.Infrastructure;
namespace CliFx.Tests.Utils; namespace CliFx.Tests.Utils;
[Command] [Command]
public class NoOpCommand : ICommand internal class NoOpCommand : ICommand
{ {
public ValueTask ExecuteAsync(IConsole console) => default; public ValueTask ExecuteAsync(IConsole console) => default;
} }

View File

@@ -9,17 +9,17 @@ namespace CliFx;
public class ApplicationConfiguration public class ApplicationConfiguration
{ {
/// <summary> /// <summary>
/// Command types defined in this application. /// Command types defined in the application.
/// </summary> /// </summary>
public IReadOnlyList<Type> CommandTypes { get; } public IReadOnlyList<Type> CommandTypes { get; }
/// <summary> /// <summary>
/// Whether debug mode is allowed in this application. /// Whether debug mode is allowed in the application.
/// </summary> /// </summary>
public bool IsDebugModeAllowed { get; } public bool IsDebugModeAllowed { get; }
/// <summary> /// <summary>
/// Whether preview mode is allowed in this application. /// Whether preview mode is allowed in the application.
/// </summary> /// </summary>
public bool IsPreviewModeAllowed { get; } public bool IsPreviewModeAllowed { get; }

View File

@@ -9,13 +9,12 @@ namespace CliFx.Attributes;
public sealed class CommandAttribute : Attribute public sealed class CommandAttribute : Attribute
{ {
/// <summary> /// <summary>
/// Command's name. /// Command name.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// Command can have no name, in which case it's treated as the default command. /// Command can have no name, in which case it's treated as the application's default command.
/// /// Only one default command is allowed in an application.
/// All commands registered in an application must have unique names (comparison IS NOT case-sensitive). /// All commands registered in an application must have unique names (comparison IS NOT case-sensitive).
/// Only one command without a name is allowed in an application.
/// </remarks> /// </remarks>
public string? Name { get; } public string? Name { get; }

View File

@@ -11,8 +11,7 @@ public sealed class CommandParameterAttribute : Attribute
{ {
/// <summary> /// <summary>
/// Parameter order. /// Parameter order.
/// Higher order means the parameter appears later, lower order means /// Higher order means the parameter appears later, lower order means it appears earlier.
/// it appears earlier.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// All parameters in a command must have unique order. /// All parameters in a command must have unique order.

View File

@@ -59,12 +59,8 @@ public class CliApplication
private bool ShouldShowHelpText(CommandSchema commandSchema, CommandInput commandInput) => private bool ShouldShowHelpText(CommandSchema commandSchema, CommandInput commandInput) =>
commandSchema.IsHelpOptionAvailable && commandInput.IsHelpOptionSpecified || commandSchema.IsHelpOptionAvailable && commandInput.IsHelpOptionSpecified ||
// Show help text also in case the fallback default command is // Show help text also if the fallback default command is executed without any arguments
// executed without any arguments. commandSchema == FallbackDefaultCommand.Schema && !commandInput.HasArguments;
commandSchema == FallbackDefaultCommand.Schema &&
string.IsNullOrWhiteSpace(commandInput.CommandName) &&
!commandInput.Parameters.Any() &&
!commandInput.Options.Any();
private bool ShouldShowVersionText(CommandSchema commandSchema, CommandInput commandInput) => private bool ShouldShowVersionText(CommandSchema commandSchema, CommandInput commandInput) =>
commandSchema.IsVersionOptionAvailable && commandInput.IsVersionOptionSpecified; commandSchema.IsVersionOptionAvailable && commandInput.IsVersionOptionSpecified;
@@ -76,28 +72,30 @@ public class CliApplication
var processId = ProcessEx.GetCurrentProcessId(); var processId = ProcessEx.GetCurrentProcessId();
_console.Output.WriteLine( _console.Output.WriteLine(
$"Attach debugger to PID {processId} to continue." $"Attach the debugger to process with ID {processId} to continue."
); );
} }
// Try to also launch debugger ourselves (only works if VS is installed) // Try to also launch the debugger ourselves (only works with Visual Studio)
Debugger.Launch(); Debugger.Launch();
while (!Debugger.IsAttached) while (!Debugger.IsAttached)
{
await Task.Delay(100); await Task.Delay(100);
}
} }
private async ValueTask<int> RunAsync(ApplicationSchema applicationSchema, CommandInput commandInput) private async ValueTask<int> RunAsync(ApplicationSchema applicationSchema, CommandInput commandInput)
{ {
// Handle debug directive // Console colors may have already been overridden by the parent process,
// so we need to reset it to make sure that everything we write looks properly.
_console.ResetColor();
// Handle the debug directive
if (IsDebugModeEnabled(commandInput)) if (IsDebugModeEnabled(commandInput))
{ {
await PromptDebuggerAsync(); await PromptDebuggerAsync();
} }
// Handle preview directive // Handle the preview directive
if (IsPreviewModeEnabled(commandInput)) if (IsPreviewModeEnabled(commandInput))
{ {
_console.Output.WriteCommandInput(commandInput); _console.Output.WriteCommandInput(commandInput);
@@ -106,16 +104,23 @@ public class CliApplication
// Try to get the command schema that matches the input // Try to get the command schema that matches the input
var commandSchema = var commandSchema =
applicationSchema.TryFindCommand(commandInput.CommandName) ?? (!string.IsNullOrWhiteSpace(commandInput.CommandName)
applicationSchema.TryFindDefaultCommand() ?? // If the command name is specified, try to find the command by name.
// This should always succeed, because the input parsing relies on
// the list of available command names.
? applicationSchema.TryFindCommand(commandInput.CommandName)
// Otherwise, try to find the default command
: applicationSchema.TryFindDefaultCommand()) ??
// If a valid command was not found, use the fallback default command.
// This is only used as a stub to show the help text.
FallbackDefaultCommand.Schema; FallbackDefaultCommand.Schema;
// Activate command instance // Initialize an instance of the command type
var commandInstance = commandSchema == FallbackDefaultCommand.Schema var commandInstance = commandSchema == FallbackDefaultCommand.Schema
? new FallbackDefaultCommand() // bypass activator ? new FallbackDefaultCommand() // bypass the activator
: (ICommand)_typeActivator.CreateInstance(commandSchema.Type); : _typeActivator.CreateInstance<ICommand>(commandSchema.Type);
// Assemble help context // Assemble the help context
var helpContext = new HelpContext( var helpContext = new HelpContext(
Metadata, Metadata,
applicationSchema, applicationSchema,
@@ -123,14 +128,14 @@ public class CliApplication
commandSchema.GetValues(commandInstance) commandSchema.GetValues(commandInstance)
); );
// Handle help option // Handle the help option
if (ShouldShowHelpText(commandSchema, commandInput)) if (ShouldShowHelpText(commandSchema, commandInput))
{ {
_console.Output.WriteHelpText(helpContext); _console.Output.WriteHelpText(helpContext);
return 0; return 0;
} }
// Handle version option // Handle the version option
if (ShouldShowVersionText(commandSchema, commandInput)) if (ShouldShowVersionText(commandSchema, commandInput))
{ {
_console.Output.WriteLine(Metadata.Version); _console.Output.WriteLine(Metadata.Version);
@@ -138,12 +143,12 @@ public class CliApplication
} }
// Starting from this point, we may produce exceptions that are meant for the // Starting from this point, we may produce exceptions that are meant for the
// end user of the application (i.e. invalid input, command exception, etc). // end-user of the application (i.e. invalid input, command exception, etc).
// Catch these exceptions here, print them to the console, and don't let them // Catch these exceptions here, print them to the console, and don't let them
// propagate further. // propagate further.
try try
{ {
// Bind and execute command // Bind and execute the command
_commandBinder.Bind(commandInput, commandSchema, commandInstance); _commandBinder.Bind(commandInput, commandSchema, commandInstance);
await commandInstance.ExecuteAsync(_console); await commandInstance.ExecuteAsync(_console);
@@ -165,11 +170,11 @@ public class CliApplication
/// <summary> /// <summary>
/// Runs the application with the specified command-line arguments and environment variables. /// Runs the application with the specified command-line arguments and environment variables.
/// Returns an exit code which indicates whether the application completed successfully. /// Returns the exit code which indicates whether the application completed successfully.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// When running WITHOUT debugger (i.e. in production), this method swallows all exceptions and /// When running WITHOUT the debugger attached (i.e. in production), this method swallows
/// reports them to the console. /// all exceptions and reports them to the console.
/// </remarks> /// </remarks>
public async ValueTask<int> RunAsync( public async ValueTask<int> RunAsync(
IReadOnlyList<string> commandLineArguments, IReadOnlyList<string> commandLineArguments,
@@ -177,10 +182,6 @@ public class CliApplication
{ {
try try
{ {
// Console colors may have already been overridden by the parent process,
// so we need to reset it to make sure that everything we write looks properly.
_console.ResetColor();
var applicationSchema = ApplicationSchema.Resolve(Configuration.CommandTypes); var applicationSchema = ApplicationSchema.Resolve(Configuration.CommandTypes);
var commandInput = CommandInput.Parse( var commandInput = CommandInput.Parse(
@@ -193,10 +194,8 @@ public class CliApplication
} }
// To prevent the app from showing the annoying troubleshooting dialog on Windows, // To prevent the app from showing the annoying troubleshooting dialog on Windows,
// we handle all exceptions ourselves and print them to the console. // we handle all exceptions ourselves and print them to the console.
//
// We only want to do that if the app is running in production, which we infer // We only want to do that if the app is running in production, which we infer
// based on whether a debugger is attached to the process. // based on whether the debugger is attached to the process.
//
// When not running in production, we want the IDE to show exceptions to the // When not running in production, we want the IDE to show exceptions to the
// developer, so we don't swallow them in that case. // developer, so we don't swallow them in that case.
catch (Exception ex) when (!Debugger.IsAttached) catch (Exception ex) when (!Debugger.IsAttached)
@@ -208,12 +207,11 @@ public class CliApplication
/// <summary> /// <summary>
/// Runs the application with the specified command-line arguments. /// Runs the application with the specified command-line arguments.
/// Environment variables are resolved automatically. /// Returns the exit code which indicates whether the application completed successfully.
/// Returns an exit code which indicates whether the application completed successfully.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// When running WITHOUT debugger (i.e. in production), this method swallows all exceptions and /// When running WITHOUT the debugger attached (i.e. in production), this method swallows
/// reports them to the console. /// all exceptions and reports them to the console.
/// </remarks> /// </remarks>
public async ValueTask<int> RunAsync(IReadOnlyList<string> commandLineArguments) => await RunAsync( public async ValueTask<int> RunAsync(IReadOnlyList<string> commandLineArguments) => await RunAsync(
commandLineArguments, commandLineArguments,
@@ -229,11 +227,11 @@ public class CliApplication
/// <summary> /// <summary>
/// Runs the application. /// Runs the application.
/// Command-line arguments and environment variables are resolved automatically. /// Command-line arguments and environment variables are resolved automatically.
/// Returns an exit code which indicates whether the application completed successfully. /// Returns the exit code which indicates whether the application completed successfully.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// When running WITHOUT debugger (i.e. in production), this method swallows all exceptions and /// When running WITHOUT the debugger attached (i.e. in production), this method swallows
/// reports them to the console. /// all exceptions and reports them to the console.
/// </remarks> /// </remarks>
public async ValueTask<int> RunAsync() => await RunAsync( public async ValueTask<int> RunAsync() => await RunAsync(
Environment.GetCommandLineArgs() Environment.GetCommandLineArgs()

View File

@@ -33,7 +33,6 @@ public partial class CliApplicationBuilder
public CliApplicationBuilder AddCommand(Type commandType) public CliApplicationBuilder AddCommand(Type commandType)
{ {
_commandTypes.Add(commandType); _commandTypes.Add(commandType);
return this; return this;
} }
@@ -112,7 +111,7 @@ public partial class CliApplicationBuilder
} }
/// <summary> /// <summary>
/// Sets application title, which is shown in the help text. /// Sets the application title, which is shown in the help text.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// By default, application title is inferred from the assembly name. /// By default, application title is inferred from the assembly name.
@@ -124,11 +123,10 @@ public partial class CliApplicationBuilder
} }
/// <summary> /// <summary>
/// Sets application executable name, which is shown in the help text. /// Sets the application executable name, which is shown in the help text.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// By default, application executable name is inferred from the assembly file name. /// By default, application executable name is inferred from the assembly file name.
/// The file name is also prefixed with `dotnet` if it's a DLL file.
/// </remarks> /// </remarks>
public CliApplicationBuilder SetExecutableName(string executableName) public CliApplicationBuilder SetExecutableName(string executableName)
{ {
@@ -137,8 +135,7 @@ public partial class CliApplicationBuilder
} }
/// <summary> /// <summary>
/// Sets application version, which is shown in the help text or /// Sets the application version, which is shown in the help text or when the user specifies the version option.
/// when the user specifies the version option.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// By default, application version is inferred from the assembly version. /// By default, application version is inferred from the assembly version.
@@ -150,7 +147,7 @@ public partial class CliApplicationBuilder
} }
/// <summary> /// <summary>
/// Sets application description, which is shown in the help text. /// Sets the application description, which is shown in the help text.
/// </summary> /// </summary>
public CliApplicationBuilder SetDescription(string? description) public CliApplicationBuilder SetDescription(string? description)
{ {
@@ -177,10 +174,10 @@ public partial class CliApplicationBuilder
} }
/// <summary> /// <summary>
/// Configures the application to use the specified function for activating types. /// Configures the application to use the specified delegate for activating types.
/// </summary> /// </summary>
public CliApplicationBuilder UseTypeActivator(Func<Type, object> typeActivator) => public CliApplicationBuilder UseTypeActivator(Func<Type, object> createInstance) =>
UseTypeActivator(new DelegateTypeActivator(typeActivator)); UseTypeActivator(new DelegateTypeActivator(createInstance));
/// <summary> /// <summary>
/// Configures the application to use the specified service provider for activating types. /// Configures the application to use the specified service provider for activating types.
@@ -188,6 +185,14 @@ public partial class CliApplicationBuilder
public CliApplicationBuilder UseTypeActivator(IServiceProvider serviceProvider) => public CliApplicationBuilder UseTypeActivator(IServiceProvider serviceProvider) =>
UseTypeActivator(serviceProvider.GetService); UseTypeActivator(serviceProvider.GetService);
/// <summary>
/// Configures the application to use the specified service provider for activating types.
/// This method takes a delegate that receives the list of all added command types, so that you can
/// easily register them with the service provider.
/// </summary>
public CliApplicationBuilder UseTypeActivator(Func<IReadOnlyList<Type>, IServiceProvider> getServiceProvider) =>
UseTypeActivator(getServiceProvider(_commandTypes.ToArray()));
/// <summary> /// <summary>
/// Creates a configured instance of <see cref="CliApplication" />. /// Creates a configured instance of <see cref="CliApplication" />.
/// </summary> /// </summary>
@@ -221,45 +226,58 @@ public partial class CliApplicationBuilder
{ {
var entryAssemblyName = EnvironmentEx.EntryAssembly?.GetName().Name; var entryAssemblyName = EnvironmentEx.EntryAssembly?.GetName().Name;
if (string.IsNullOrWhiteSpace(entryAssemblyName)) if (string.IsNullOrWhiteSpace(entryAssemblyName))
return "App"; {
throw new InvalidOperationException(
"Failed to infer the default application title. " +
$"Please specify it explicitly using {nameof(SetTitle)}()."
);
}
return entryAssemblyName; return entryAssemblyName;
} }
private static string GetDefaultExecutableName() private static string GetDefaultExecutableName()
{ {
var entryAssemblyLocation = EnvironmentEx.EntryAssembly?.Location; var entryAssemblyFilePath = EnvironmentEx.EntryAssembly?.Location;
if (string.IsNullOrWhiteSpace(entryAssemblyLocation)) var processFilePath = EnvironmentEx.ProcessPath;
return "app";
// If the application was launched via matching EXE apphost, use that as the executable name if (string.IsNullOrWhiteSpace(entryAssemblyFilePath) || string.IsNullOrWhiteSpace(processFilePath))
var isLaunchedViaAppHost = string.Equals( {
EnvironmentEx.ProcessPath, throw new InvalidOperationException(
Path.ChangeExtension(entryAssemblyLocation, ".exe"), "Failed to infer the default application executable name. " +
StringComparison.OrdinalIgnoreCase $"Please specify it explicitly using {nameof(SetExecutableName)}()."
); );
}
if (isLaunchedViaAppHost) // If the process path matches the entry assembly path, it's a legacy .NET Framework app
return Path.GetFileNameWithoutExtension(entryAssemblyLocation); // or a self-contained .NET Core app.
if (PathEx.AreEqual(entryAssemblyFilePath, processFilePath))
{
return Path.GetFileNameWithoutExtension(entryAssemblyFilePath);
}
// Otherwise, use the entry assembly as the executable name. // If the process path has the same name and parent directory as the entry assembly path,
// Prefix it with `dotnet` if it's a DLL file. // but different extension, it's a framework-dependent .NET Core app launched through the apphost.
var isDll = string.Equals( if (PathEx.AreEqual(Path.ChangeExtension(entryAssemblyFilePath, "exe"), processFilePath) ||
Path.GetExtension(entryAssemblyLocation), PathEx.AreEqual(Path.GetFileNameWithoutExtension(entryAssemblyFilePath), processFilePath))
".dll", {
StringComparison.OrdinalIgnoreCase return Path.GetFileNameWithoutExtension(entryAssemblyFilePath);
); }
return isDll // Otherwise, it's a framework-dependent .NET Core app launched through the .NET CLI
? "dotnet " + Path.GetFileName(entryAssemblyLocation) return "dotnet " + Path.GetFileName(entryAssemblyFilePath);
: Path.GetFileNameWithoutExtension(entryAssemblyLocation);
} }
private static string GetDefaultVersionText() private static string GetDefaultVersionText()
{ {
var entryAssemblyVersion = EnvironmentEx.EntryAssembly?.GetName().Version; var entryAssemblyVersion = EnvironmentEx.EntryAssembly?.GetName().Version;
if (entryAssemblyVersion is null) if (entryAssemblyVersion is null)
return "v1.0"; {
throw new InvalidOperationException(
"Failed to infer the default application version. " +
$"Please specify it explicitly using {nameof(SetVersion)}()."
);
}
return "v" + entryAssemblyVersion.ToSemanticString(); return "v" + entryAssemblyVersion.ToSemanticString();
} }

View File

@@ -11,7 +11,6 @@
<PackageTags>command line executable interface framework parser arguments cli app application net core</PackageTags> <PackageTags>command line executable interface framework parser arguments cli app application net core</PackageTags>
<PackageProjectUrl>https://github.com/Tyrrrz/CliFx</PackageProjectUrl> <PackageProjectUrl>https://github.com/Tyrrrz/CliFx</PackageProjectUrl>
<PackageReleaseNotes>https://github.com/Tyrrrz/CliFx/blob/master/Changelog.md</PackageReleaseNotes> <PackageReleaseNotes>https://github.com/Tyrrrz/CliFx/blob/master/Changelog.md</PackageReleaseNotes>
<PackageReadmeFile>Readme.md</PackageReadmeFile>
<PackageIcon>favicon.png</PackageIcon> <PackageIcon>favicon.png</PackageIcon>
<PackageLicenseExpression>MIT</PackageLicenseExpression> <PackageLicenseExpression>MIT</PackageLicenseExpression>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
@@ -21,13 +20,12 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<None Include="../Readme.md" Pack="true" PackagePath="" Visible="false" />
<None Include="../favicon.png" Pack="true" PackagePath="" Visible="false" /> <None Include="../favicon.png" Pack="true" PackagePath="" Visible="false" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="all" /> <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="all" />
<PackageReference Include="PolyShim" Version="1.1.0" PrivateAssets="all" /> <PackageReference Include="PolyShim" Version="1.2.0" PrivateAssets="all" />
<PackageReference Include="System.Threading.Tasks.Extensions" Version="4.5.4" Condition="'$(TargetFramework)' == 'netstandard2.0'" /> <PackageReference Include="System.Threading.Tasks.Extensions" Version="4.5.4" Condition="'$(TargetFramework)' == 'netstandard2.0'" />
</ItemGroup> </ItemGroup>

View File

@@ -27,7 +27,7 @@ internal class CommandBinder
// Custom converter // Custom converter
if (memberSchema.ConverterType is not null) if (memberSchema.ConverterType is not null)
{ {
var converter = (IBindingConverter)_typeActivator.CreateInstance(memberSchema.ConverterType); var converter = _typeActivator.CreateInstance<IBindingConverter>(memberSchema.ConverterType);
return converter.Convert(rawValue); return converter.Convert(rawValue);
} }
@@ -101,7 +101,7 @@ internal class CommandBinder
throw CliFxException.InternalError( throw CliFxException.InternalError(
$""" $"""
{memberSchema.GetKind()} {memberSchema.GetFormattedIdentifier()} has an unsupported underlying property type. {memberSchema.GetKind()} {memberSchema.GetFormattedIdentifier()} has an unsupported underlying property type.
There is no known way to convert a string value into an instance of type `{targetType.FullName}` There is no known way to convert a string value into an instance of type `{targetType.FullName}`.
To fix this, either change the property to use a supported type or configure a custom converter. To fix this, either change the property to use a supported type or configure a custom converter.
""" """
); );
@@ -136,34 +136,41 @@ internal class CommandBinder
$""" $"""
{memberSchema.GetKind()} {memberSchema.GetFormattedIdentifier()} has an unsupported underlying property type. {memberSchema.GetKind()} {memberSchema.GetFormattedIdentifier()} has an unsupported underlying property type.
There is no known way to convert an array of `{targetElementType.FullName}` into an instance of type `{targetEnumerableType.FullName}`. There is no known way to convert an array of `{targetElementType.FullName}` into an instance of type `{targetEnumerableType.FullName}`.
To fix this, change the property to use a type which can be assigned from an array or a type that has a constructor which accepts an array. To fix this, change the property to use a type which can be assigned from an array or a type which has a constructor that accepts an array.
""" """
); );
} }
private object? ConvertMember(IMemberSchema memberSchema, IReadOnlyList<string> rawValues) private object? ConvertMember(IMemberSchema memberSchema, IReadOnlyList<string> rawValues)
{ {
var targetType = memberSchema.Property.Type;
try try
{ {
// Non-scalar // Non-scalar
var enumerableUnderlyingType = targetType.TryGetEnumerableUnderlyingType(); var enumerableUnderlyingType = memberSchema.Property.Type.TryGetEnumerableUnderlyingType();
if (targetType != typeof(string) && enumerableUnderlyingType is not null) if (enumerableUnderlyingType is not null && memberSchema.Property.Type != typeof(string))
{ {
return ConvertMultiple(memberSchema, rawValues, targetType, enumerableUnderlyingType); return ConvertMultiple(
memberSchema,
rawValues,
memberSchema.Property.Type,
enumerableUnderlyingType
);
} }
// Scalar // Scalar
if (rawValues.Count <= 1) if (rawValues.Count <= 1)
{ {
return ConvertSingle(memberSchema, rawValues.SingleOrDefault(), targetType); return ConvertSingle(
memberSchema,
rawValues.SingleOrDefault(),
memberSchema.Property.Type
);
} }
} }
catch (Exception ex) when (ex is not CliFxException) // don't wrap CliFxException catch (Exception ex) when (ex is not CliFxException) // don't wrap CliFxException
{ {
// We use reflection-based invocation which can throw TargetInvocationException. // We use reflection-based invocation which can throw TargetInvocationException.
// Unwrap these exceptions to provide a more user-friendly error message. // Unwrap those exceptions to provide a more user-friendly error message.
var errorMessage = ex is TargetInvocationException invokeEx var errorMessage = ex is TargetInvocationException invokeEx
? invokeEx.InnerException?.Message ?? invokeEx.Message ? invokeEx.InnerException?.Message ?? invokeEx.Message
: ex.Message; : ex.Message;
@@ -193,7 +200,7 @@ internal class CommandBinder
foreach (var validatorType in memberSchema.ValidatorTypes) foreach (var validatorType in memberSchema.ValidatorTypes)
{ {
var validator = (IBindingValidator)_typeActivator.CreateInstance(validatorType); var validator = _typeActivator.CreateInstance<IBindingValidator>(validatorType);
var error = validator.Validate(convertedValue); var error = validator.Validate(convertedValue);
if (error is not null) if (error is not null)
@@ -234,7 +241,7 @@ internal class CommandBinder
if (position >= commandInput.Parameters.Count) if (position >= commandInput.Parameters.Count)
break; break;
// Scalar - take one input at the current position // Scalar: take one input at the current position
if (parameterSchema.Property.IsScalar()) if (parameterSchema.Property.IsScalar())
{ {
var parameterInput = commandInput.Parameters[position]; var parameterInput = commandInput.Parameters[position];
@@ -246,7 +253,7 @@ internal class CommandBinder
remainingParameterInputs.Remove(parameterInput); remainingParameterInputs.Remove(parameterInput);
} }
// Non-scalar - take all remaining inputs starting from the current position // Non-scalar: take all remaining inputs starting from the current position
else else
{ {
var parameterInputs = commandInput.Parameters.Skip(position).ToArray(); var parameterInputs = commandInput.Parameters.Skip(position).ToArray();
@@ -324,7 +331,7 @@ internal class CommandBinder
if (rawValues.Any()) if (rawValues.Any())
remainingRequiredOptionSchemas.Remove(optionSchema); remainingRequiredOptionSchemas.Remove(optionSchema);
} }
// No input - skip // No input, skip
else else
{ {
continue; continue;

View File

@@ -9,9 +9,11 @@ public partial class CliFxException : Exception
{ {
internal const int DefaultExitCode = 1; internal const int DefaultExitCode = 1;
// Regular `exception.Message` never returns null, even if // When an exception is created without a message, the base Exception class
// it hasn't been set. // provides a default message that is not very useful.
internal string? ActualMessage { get; } // This property is used to identify whether this instance was created with
// a custom message, so that we can avoid printing the default message.
internal bool HasCustomMessage { get; }
/// <summary> /// <summary>
/// Returned exit code. /// Returned exit code.
@@ -33,7 +35,7 @@ public partial class CliFxException : Exception
Exception? innerException = null) Exception? innerException = null)
: base(message, innerException) : base(message, innerException)
{ {
ActualMessage = message; HasCustomMessage = !string.IsNullOrWhiteSpace(message);
ExitCode = exitCode; ExitCode = exitCode;
ShowHelp = showHelp; ShowHelp = showHelp;
} }
@@ -41,13 +43,13 @@ public partial class CliFxException : Exception
public partial class CliFxException public partial class CliFxException
{ {
// Internal errors don't show help because they're meant for the developer // Internal errors don't show help because they're meant for the developer and
// and not the end-user of the application. // not the end-user of the application.
internal static CliFxException InternalError(string message, Exception? innerException = null) => internal static CliFxException InternalError(string message, Exception? innerException = null) =>
new(message, DefaultExitCode, false, innerException); new(message, DefaultExitCode, false, innerException);
// User errors are typically caused by invalid input and they're meant for // User errors are typically caused by invalid input and they're meant for the end-user,
// the end-user, so we want to show help. // so we want to show help.
internal static CliFxException UserError(string message, Exception? innerException = null) => internal static CliFxException UserError(string message, Exception? innerException = null) =>
new(message, DefaultExitCode, true, innerException); new(message, DefaultExitCode, true, innerException);
} }

View File

@@ -1,6 +1,6 @@
namespace CliFx.Extensibility; namespace CliFx.Extensibility;
// Used internally to simplify usage from reflection // Used internally to simplify the usage from reflection
internal interface IBindingConverter internal interface IBindingConverter
{ {
object? Convert(string? rawValue); object? Convert(string? rawValue);

View File

@@ -1,6 +1,6 @@
namespace CliFx.Extensibility; namespace CliFx.Extensibility;
// Used internally to simplify usage from reflection // Used internally to simplify the usage from reflection
internal interface IBindingValidator internal interface IBindingValidator
{ {
BindingValidationError? Validate(object? value); BindingValidationError? Validate(object? value);

View File

@@ -98,26 +98,22 @@ internal class ExceptionConsoleFormatter : ConsoleFormatter
if (!string.IsNullOrWhiteSpace(exception.StackTrace)) if (!string.IsNullOrWhiteSpace(exception.StackTrace))
{ {
// Parse and pretty-print the stacktrace // Parse and pretty-print the stacktrace
foreach (var stackFrame in StackFrame.ParseMany(exception.StackTrace)) foreach (var stackFrame in StackFrame.ParseTrace(exception.StackTrace))
{
WriteStackFrame(stackFrame, indentLevel); WriteStackFrame(stackFrame, indentLevel);
}
} }
} }
public void WriteException(Exception exception) public void WriteException(Exception exception)
{ {
// Domain exceptions should be printed with minimal information // Domain exceptions should be printed with minimal information because they are
// because they are meant for the user of the application, // meant for the user of the application, not the user of the library.
// not the user of the library. if (exception is CliFxException { HasCustomMessage: true } cliFxException)
if (exception is CliFxException cliFxException &&
!string.IsNullOrWhiteSpace(cliFxException.ActualMessage))
{ {
Write(ConsoleColor.Red, cliFxException.ActualMessage); Write(ConsoleColor.Red, cliFxException.Message);
WriteLine(); WriteLine();
} }
// All other exceptions most likely indicate an actual bug // All other exceptions most likely indicate an actual bug and should include
// and should include stacktrace and other detailed information. // the stacktrace and other detailed information.
else else
{ {
Write(ConsoleColor.White, ConsoleColor.DarkRed, "ERROR"); Write(ConsoleColor.White, ConsoleColor.DarkRed, "ERROR");

View File

@@ -413,7 +413,6 @@ internal class HelpConsoleFormatter : ConsoleFormatter
Write(ConsoleColor.White, "Subcommands: "); Write(ConsoleColor.White, "Subcommands: ");
var isFirst = true; var isFirst = true;
foreach (var grandChildCommandSchema in grandChildCommandSchemas) foreach (var grandChildCommandSchema in grandChildCommandSchemas)
{ {
if (isFirst) if (isFirst)

View File

@@ -13,7 +13,7 @@ public interface ICommand
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// If the execution of the command is not asynchronous, simply end the method with /// If the execution of the command is not asynchronous, simply end the method with
/// <code>return default;</code> /// <c>return default;</c>
/// </remarks> /// </remarks>
ValueTask ExecuteAsync(IConsole console); ValueTask ExecuteAsync(IConsole console);
} }

View File

@@ -4,22 +4,22 @@ using CliFx.Exceptions;
namespace CliFx.Infrastructure; namespace CliFx.Infrastructure;
/// <summary> /// <summary>
/// Implementation of <see cref="ITypeActivator" /> that instantiates an object /// Implementation of <see cref="ITypeActivator" /> that instantiates an object by using a predefined delegate.
/// by using a predefined function.
/// </summary> /// </summary>
public class DelegateTypeActivator : ITypeActivator public class DelegateTypeActivator : ITypeActivator
{ {
private readonly Func<Type, object> _func; private readonly Func<Type, object> _createInstance;
/// <summary> /// <summary>
/// Initializes an instance of <see cref="DelegateTypeActivator" />. /// Initializes an instance of <see cref="DelegateTypeActivator" />.
/// </summary> /// </summary>
public DelegateTypeActivator(Func<Type, object> func) => _func = func; public DelegateTypeActivator(Func<Type, object> createInstance) =>
_createInstance = createInstance;
/// <inheritdoc /> /// <inheritdoc />
public object CreateInstance(Type type) public object CreateInstance(Type type)
{ {
var instance = _func(type); var instance = _createInstance(type);
if (instance is null) if (instance is null)
{ {

View File

@@ -8,10 +8,8 @@ namespace CliFx.Infrastructure;
/// <summary> /// <summary>
/// Implementation of <see cref="IConsole" /> that uses the provided fake /// Implementation of <see cref="IConsole" /> that uses the provided fake
/// standard input, output, and error streams. /// standard input, output, and error streams.
/// Use this implementation in tests to verify command interactions with the console.
/// </summary> /// </summary>
/// <remarks>
/// Use this implementation in tests to verify how a command interacts with the console.
/// </remarks>
public class FakeConsole : IConsole, IDisposable public class FakeConsole : IConsole, IDisposable
{ {
private readonly CancellationTokenSource _cancellationTokenSource = new(); private readonly CancellationTokenSource _cancellationTokenSource = new();

View File

@@ -5,10 +5,8 @@ namespace CliFx.Infrastructure;
/// <summary> /// <summary>
/// Implementation of <see cref="IConsole" /> that uses fake /// Implementation of <see cref="IConsole" /> that uses fake
/// standard input, output, and error streams backed by in-memory stores. /// standard input, output, and error streams backed by in-memory stores.
/// Use this implementation in tests to verify command interactions with the console.
/// </summary> /// </summary>
/// <remarks>
/// Use this implementation in tests to verify how a command interacts with the console.
/// </remarks>
public class FakeInMemoryConsole : FakeConsole public class FakeInMemoryConsole : FakeConsole
{ {
private readonly MemoryStream _input; private readonly MemoryStream _input;
@@ -36,17 +34,17 @@ public class FakeInMemoryConsole : FakeConsole
/// </summary> /// </summary>
public void WriteInput(byte[] data) public void WriteInput(byte[] data)
{ {
// We want the consumer to be able to read what we wrote
// so we need to seek the stream back to its original
// position after we finish writing.
lock (_input) lock (_input)
{ {
var lastPosition = _input.Position; var lastPosition = _input.Position;
// Write the data to the end of the stream
_input.Seek(0, SeekOrigin.End);
_input.Write(data); _input.Write(data);
_input.Flush(); _input.Flush();
_input.Position = lastPosition; // Reset position to where it was before
_input.Seek(lastPosition, SeekOrigin.Begin);
} }
} }

View File

@@ -86,19 +86,18 @@ public interface IConsole
/// <summary> /// <summary>
/// Registers a handler for the interrupt signal (Ctrl+C) on the console and returns /// Registers a handler for the interrupt signal (Ctrl+C) on the console and returns
/// a token representing the cancellation request. /// the token that represents the associated cancellation request.
/// Subsequent calls to this method have no side effects and return the same token. /// Subsequent calls to this method have no side effects and return the same token.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// <para> /// <para>
/// Calling this method effectively makes the command cancellation-aware, which /// Calling this method makes the command cancellation-aware, which means that sending
/// means that sending the interrupt signal won't immediately terminate the application, /// the interrupt signal won't immediately terminate the application, but will instead
/// but will instead trigger a token that the command can use to exit more gracefully. /// trigger the associated token, allowing the command to exit early but on its own terms.
/// </para> /// </para>
/// <para> /// <para>
/// Note that the handler is only respected when the user sends the interrupt signal for the first time. /// Note that if the user sends the interrupt signal a second time, the application will
/// If the user decides to issue the signal again, the application will terminate immediately /// be forcefully terminated without triggering the token.
/// regardless of whether the command is cancellation-aware.
/// </para> /// </para>
/// </remarks> /// </remarks>
CancellationToken RegisterCancellationHandler(); CancellationToken RegisterCancellationHandler();

View File

@@ -1,4 +1,7 @@
using System; using System;
using CliFx.Exceptions;
using CliFx.Extensibility;
using CliFx.Utils.Extensions;
namespace CliFx.Infrastructure; namespace CliFx.Infrastructure;
@@ -12,3 +15,18 @@ public interface ITypeActivator
/// </summary> /// </summary>
object CreateInstance(Type type); object CreateInstance(Type type);
} }
internal static class TypeActivatorExtensions
{
public static T CreateInstance<T>(this ITypeActivator activator, Type type)
{
if (!typeof(T).IsAssignableFrom(type))
{
throw CliFxException.InternalError(
$"Type '{type.FullName}' is not assignable to '{typeof(T).FullName}'."
);
}
return (T)activator.CreateInstance(type);
}
}

View File

@@ -17,6 +17,12 @@ internal partial class CommandInput
public IReadOnlyList<EnvironmentVariableInput> EnvironmentVariables { get; } public IReadOnlyList<EnvironmentVariableInput> EnvironmentVariables { get; }
public bool HasArguments =>
!string.IsNullOrWhiteSpace(CommandName) ||
Directives.Any() ||
Parameters.Any() ||
Options.Any();
public bool IsDebugDirectiveSpecified => Directives.Any(d => d.IsDebugDirective); public bool IsDebugDirectiveSpecified => Directives.Any(d => d.IsDebugDirective);
public bool IsPreviewDirectiveSpecified => Directives.Any(d => d.IsPreviewDirective); public bool IsPreviewDirectiveSpecified => Directives.Any(d => d.IsPreviewDirective);
@@ -74,8 +80,8 @@ internal partial class CommandInput
var lastIndex = index; var lastIndex = index;
// Append arguments to a buffer until we find the longest sequence // Append arguments to a buffer until we find the longest sequence that represents
// that represents a valid command name. // a valid command name.
for (var i = index; i < commandLineArguments.Count; i++) for (var i = index; i < commandLineArguments.Count; i++)
{ {
var argument = commandLineArguments[i]; var argument = commandLineArguments[i];
@@ -85,8 +91,8 @@ internal partial class CommandInput
var potentialCommandName = potentialCommandNameComponents.JoinToString(" "); var potentialCommandName = potentialCommandNameComponents.JoinToString(" ");
if (commandNames.Contains(potentialCommandName)) if (commandNames.Contains(potentialCommandName))
{ {
// Record the position but continue the loop in case // Record the position but continue the loop in case we find
// we find a longer (more specific) match. // a longer (more specific) match.
commandName = potentialCommandName; commandName = potentialCommandName;
lastIndex = i; lastIndex = i;
} }
@@ -105,7 +111,7 @@ internal partial class CommandInput
{ {
var result = new List<ParameterInput>(); var result = new List<ParameterInput>();
// Consume all arguments until first option identifier // Consume all arguments until the first option identifier
for (; index < commandLineArguments.Count; index++) for (; index < commandLineArguments.Count; index++)
{ {
var argument = commandLineArguments[index]; var argument = commandLineArguments[index];
@@ -120,7 +126,7 @@ internal partial class CommandInput
argument.Length > 1 && argument.Length > 1 &&
char.IsLetter(argument[1]); char.IsLetter(argument[1]);
// Break on first option identifier // Break on the first option identifier
if (isOptionIdentifier) if (isOptionIdentifier)
break; break;
@@ -161,13 +167,13 @@ internal partial class CommandInput
argument.Length > 1 && argument.Length > 1 &&
char.IsLetter(argument[1])) char.IsLetter(argument[1]))
{ {
foreach (var alias in argument[1..]) foreach (var identifier in argument[1..])
{ {
// Flush previous // Flush previous
if (!string.IsNullOrWhiteSpace(lastOptionIdentifier)) if (!string.IsNullOrWhiteSpace(lastOptionIdentifier))
result.Add(new OptionInput(lastOptionIdentifier, lastOptionValues)); result.Add(new OptionInput(lastOptionIdentifier, lastOptionValues));
lastOptionIdentifier = alias.AsString(); lastOptionIdentifier = identifier.AsString();
lastOptionValues = new List<string>(); lastOptionValues = new List<string>();
} }
} }
@@ -178,7 +184,7 @@ internal partial class CommandInput
} }
} }
// Flush last option // Flush the last option
if (!string.IsNullOrWhiteSpace(lastOptionIdentifier)) if (!string.IsNullOrWhiteSpace(lastOptionIdentifier))
result.Add(new OptionInput(lastOptionIdentifier, lastOptionValues)); result.Add(new OptionInput(lastOptionIdentifier, lastOptionValues));

View File

@@ -22,7 +22,7 @@ internal partial class ApplicationSchema
public CommandSchema? TryFindDefaultCommand() => public CommandSchema? TryFindDefaultCommand() =>
Commands.FirstOrDefault(c => c.IsDefault); Commands.FirstOrDefault(c => c.IsDefault);
public CommandSchema? TryFindCommand(string? commandName) => public CommandSchema? TryFindCommand(string commandName) =>
Commands.FirstOrDefault(c => c.MatchesName(commandName)); Commands.FirstOrDefault(c => c.MatchesName(commandName));
private IReadOnlyList<CommandSchema> GetDescendantCommands( private IReadOnlyList<CommandSchema> GetDescendantCommands(

View File

@@ -124,7 +124,6 @@ internal partial class CommandSchema
public static CommandSchema Resolve(Type type) public static CommandSchema Resolve(Type type)
{ {
var schema = TryResolve(type); var schema = TryResolve(type);
if (schema is null) if (schema is null)
{ {
throw CliFxException.InternalError( throw CliFxException.InternalError(

22
CliFx/Utils/PathEx.cs Normal file
View File

@@ -0,0 +1,22 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace CliFx.Utils;
internal static class PathEx
{
private static StringComparer EqualityComparer { get; } =
RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? StringComparer.OrdinalIgnoreCase
: StringComparer.Ordinal;
public static bool AreEqual(string path1, string path2)
{
static string Normalize(string path) => Path
.GetFullPath(path)
.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
return EqualityComparer.Equals(Normalize(path1), Normalize(path2));
}
}

View File

@@ -89,7 +89,7 @@ internal partial class StackFrame
TimeSpan.FromSeconds(5) TimeSpan.FromSeconds(5)
); );
public static IEnumerable<StackFrame> ParseMany(string stackTrace) public static IEnumerable<StackFrame> ParseTrace(string stackTrace)
{ {
var matches = Pattern.Matches(stackTrace).ToArray(); var matches = Pattern.Matches(stackTrace).ToArray();

View File

@@ -1,7 +1,7 @@
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<Version>2.3.2</Version> <Version>2.3.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

@@ -436,7 +436,7 @@ You can run `dotnet myapp.dll cmd1 [command] --help` to show help on a specific
``` ```
> **Note**: > **Note**:
> Defining a default (unnamed) command is not required. > Defining the default (unnamed) command is not required.
> If it's absent, running the application without specifying a command will just show the root-level help text. > If it's absent, running the application without specifying a command will just show the root-level help text.
### Reporting errors ### Reporting errors
@@ -490,7 +490,7 @@ Console applications support the concept of interrupt signals, which can be issu
If your command performs critical work, you can intercept these signals to handle cancellation requests in a graceful way. If your command performs critical work, you can intercept these signals to handle cancellation requests in a graceful way.
In order to make the command cancellation-aware, call `console.RegisterCancellationHandler()` to register the signal handler and obtain the corresponding `CancellationToken`. In order to make the command cancellation-aware, call `console.RegisterCancellationHandler()` to register the signal handler and obtain the corresponding `CancellationToken`.
Once this method is called, the program will no longer terminate on an interrupt signal but will instead trigger the token, so it's important to be able to process it correctly. Once this method is called, the program will no longer terminate on an interrupt signal but will instead trigger the token, which can be used by the command to delay the termination just enough to exit in a controlled manner.
```csharp ```csharp
[Command] [Command]
@@ -516,7 +516,7 @@ public class CancellableCommand : ICommand
> **Warning**: > **Warning**:
> Cancellation handler is only respected when the user sends the interrupt signal for the first time. > Cancellation handler is only respected when the user sends the interrupt signal for the first time.
> If the user decides to issue the signal again, the application will terminate immediately regardless of whether the command is cancellation-aware. > If the user decides to issue the signal again, the application will be forcefully terminated without triggering the cancellation token.
### Type activation ### Type activation
@@ -531,24 +531,24 @@ The following example shows how to configure your application to use [`Microsoft
```csharp ```csharp
public static class Program public static class Program
{ {
public static async Task<int> Main() public static async Task<int> Main() =>
{ await new CliApplicationBuilder()
var services = new ServiceCollection();
// Register services
services.AddSingleton<MyService>();
// Register commands
services.AddTransient<MyCommand>();
var serviceProvider = services.BuildServiceProvider();
return await new CliApplicationBuilder()
.AddCommandsFromThisAssembly() .AddCommandsFromThisAssembly()
.UseTypeActivator(serviceProvider) .UseTypeActivator(commandTypes =>
{
var services = new ServiceCollection();
// Register services
services.AddSingleton<MyService>();
// Register commands
foreach (var commandType in commandTypes)
services.AddTransient(commandType);
return services.BuildServiceProvider();
})
.Build() .Build()
.RunAsync(); .RunAsync();
}
} }
``` ```
@@ -621,7 +621,12 @@ public async Task ConcatCommand_executes_successfully()
.UseConsole(console) .UseConsole(console)
.Build(); .Build();
var args = new[] {"--left", "foo", "--right", "bar"}; var args = new[]
{
"--left", "foo",
"--right", "bar"
};
var envVars = new Dictionary<string, string>(); var envVars = new Dictionary<string, string>();
// Act // Act