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

View File

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

View File

@@ -69,7 +69,7 @@ public class CommandMustBeAnnotatedAnalyzerSpecs
"""
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 int Bar { get; set; } = 5;
public int Bar { get; init; } = 5;
}
""";

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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
{
[CommandOption("target", EnvironmentVariable = "ENV_TARGET")]
public string GreetingTarget { get; set; } = "World";
public string GreetingTarget { get; init; } = "World";
public ValueTask ExecuteAsync(IConsole console)
{

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using CliFx.Tests.Utils;
@@ -20,7 +19,7 @@ public class DirectivesSpecs : SpecsBase
}
[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
using var cts = new CancellationTokenSource();
@@ -29,7 +28,7 @@ public class DirectivesSpecs : SpecsBase
void HandleStdOut(string line)
{
// 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();
}
@@ -51,7 +50,7 @@ public class DirectivesSpecs : SpecsBase
}
[Fact]
public async Task Preview_directive_can_be_specified_to_print_command_input()
public async Task I_can_use_the_preview_directive_to_make_the_application_print_the_parsed_command_input()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
@@ -81,10 +80,10 @@ public class DirectivesSpecs : SpecsBase
}
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ContainAllInOrder(
"cmd", "<param>", "[-a]", "[-b]", "[-c]", "[--option \"foo\"]",
"ENV_QOP", "=", "\"hello\"",

View File

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

View File

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

View File

@@ -17,7 +17,7 @@ public class HelpTextSpecs : SpecsBase
}
[Fact]
public async Task Help_text_is_printed_if_no_arguments_are_provided_and_the_default_command_is_not_defined()
public async Task I_can_request_the_help_text_by_running_the_application_without_arguments_if_the_default_command_is_not_defined()
{
// Arrange
var application = new CliApplicationBuilder()
@@ -31,15 +31,15 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().Contain("This will be in help text");
}
[Fact]
public async Task Help_text_is_printed_if_provided_arguments_contain_the_help_option()
public async Task I_can_request_the_help_text_by_running_the_application_with_the_help_option()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
@@ -65,15 +65,15 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().Contain("This will be in help text");
}
[Fact]
public async Task Help_text_is_printed_if_provided_arguments_contain_the_help_option_even_if_the_default_command_is_not_defined()
public async Task I_can_request_the_help_text_by_running_the_application_with_the_help_option_even_if_the_default_command_is_not_defined()
{
// Arrange
var commandTypes = DynamicCommandBuilder.CompileMany(
@@ -105,15 +105,15 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().Contain("This will be in help text");
}
[Fact]
public async Task Help_text_for_a_specific_named_command_is_printed_if_provided_arguments_match_its_name_and_contain_the_help_option()
public async Task I_can_request_the_help_text_for_a_specific_command_by_running_the_application_and_specifying_its_name_with_the_help_option()
{
// Arrange
var commandTypes = DynamicCommandBuilder.CompileMany(
@@ -150,15 +150,15 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().Contain("Description of a named command.");
}
[Fact]
public async Task Help_text_for_a_specific_named_child_command_is_printed_if_provided_arguments_match_its_name_and_contain_the_help_option()
public async Task I_can_request_the_help_text_for_a_specific_nested_command_by_running_the_application_and_specifying_its_name_with_the_help_option()
{
// Arrange
var commandTypes = DynamicCommandBuilder.CompileMany(
@@ -195,15 +195,15 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().Contain("Description of a named child command.");
}
[Fact]
public async Task Help_text_is_printed_on_invalid_user_input()
public async Task I_can_request_the_help_text_by_running_the_application_with_invalid_arguments()
{
// Arrange
var application = new CliApplicationBuilder()
@@ -218,17 +218,18 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
var stdErr = FakeConsole.ReadErrorString();
// Assert
exitCode.Should().NotBe(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().Contain("This will be in help text");
var stdErr = FakeConsole.ReadErrorString();
stdErr.Should().NotBeNullOrWhiteSpace();
}
[Fact]
public async Task Help_text_shows_application_metadata()
public async Task I_can_request_the_help_text_to_see_the_application_title_description_and_version()
{
// Arrange
var application = new CliApplicationBuilder()
@@ -244,10 +245,10 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ContainAll(
"App title",
"App description",
@@ -256,20 +257,19 @@ public class HelpTextSpecs : SpecsBase
}
[Fact]
public async Task Help_text_shows_command_description()
public async Task I_can_request_the_help_text_to_see_the_command_description()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
[Command(Description = "Description of the default command.")]
public class DefaultCommand : ICommand
{
public ValueTask ExecuteAsync(IConsole console) => default;
}
""");
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
@@ -282,10 +282,10 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ContainAllInOrder(
"DESCRIPTION",
"Description of the default command."
@@ -293,13 +293,12 @@ public class HelpTextSpecs : SpecsBase
}
[Fact]
public async Task Help_text_shows_usage_format_which_indicates_how_to_execute_a_named_command()
public async Task I_can_request_the_help_text_to_see_the_usage_format_for_a_named_command()
{
// Arrange
var commandTypes = DynamicCommandBuilder.CompileMany(
// language=cs
"""
[Command]
public class DefaultCommand : ICommand
{
@@ -311,8 +310,8 @@ public class HelpTextSpecs : SpecsBase
{
public ValueTask ExecuteAsync(IConsole console) => default;
}
""");
"""
);
var application = new CliApplicationBuilder()
.AddCommands(commandTypes)
@@ -325,10 +324,10 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ContainAllInOrder(
"USAGE",
"[command]", "[...]"
@@ -336,29 +335,28 @@ public class HelpTextSpecs : SpecsBase
}
[Fact]
public async Task Help_text_shows_usage_format_which_lists_all_parameters()
public async Task I_can_request_the_help_text_to_see_the_usage_format_for_all_parameters()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
[Command]
public class Command : ICommand
{
[CommandParameter(0)]
public string Foo { get; set; }
public required string Foo { get; init; }
[CommandParameter(1)]
public string Bar { get; set; }
public required string Bar { get; init; }
[CommandParameter(2)]
public IReadOnlyList<string> Baz { get; set; }
public required IReadOnlyList<string> Baz { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default;
}
""");
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
@@ -371,10 +369,10 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ContainAllInOrder(
"USAGE",
"<foo>", "<bar>", "<baz...>"
@@ -383,18 +381,17 @@ public class HelpTextSpecs : SpecsBase
// https://github.com/Tyrrrz/CliFx/issues/117
[Fact]
public async Task Help_text_shows_usage_format_which_lists_all_parameters_in_specified_order()
public async Task I_can_request_the_help_text_to_see_the_usage_format_for_all_parameters_in_the_correct_order()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
// Base members appear last in reflection order
public abstract class CommandBase : ICommand
{
[CommandParameter(0)]
public string Foo { get; set; }
public required string Foo { get; init; }
public abstract ValueTask ExecuteAsync(IConsole console);
}
@@ -403,15 +400,15 @@ public class HelpTextSpecs : SpecsBase
public class Command : CommandBase
{
[CommandParameter(2)]
public IReadOnlyList<string> Baz { get; set; }
public required IReadOnlyList<string> Baz { get; init; }
[CommandParameter(1)]
public string Bar { get; set; }
public required string Bar { get; init; }
public override ValueTask ExecuteAsync(IConsole console) => default;
}
""");
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
@@ -424,10 +421,10 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ContainAllInOrder(
"USAGE",
"<foo>", "<bar>", "<baz...>"
@@ -435,29 +432,28 @@ public class HelpTextSpecs : SpecsBase
}
[Fact]
public async Task Help_text_shows_usage_format_which_lists_all_required_options()
public async Task I_can_request_the_help_text_to_see_the_usage_format_for_all_required_options()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
[Command]
public class Command : ICommand
{
[CommandOption("foo", IsRequired = true)]
public string Foo { get; set; }
[CommandOption("foo")]
public required string Foo { get; init; }
[CommandOption("bar")]
public string Bar { get; set; }
public string? Bar { get; init; }
[CommandOption("baz", IsRequired = true)]
public IReadOnlyList<string> Baz { get; set; }
[CommandOption("baz")]
public required IReadOnlyList<string> Baz { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default;
}
""");
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
@@ -470,10 +466,10 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ContainAllInOrder(
"USAGE",
"--foo <value>", "--baz <values...>", "[options]"
@@ -481,26 +477,25 @@ public class HelpTextSpecs : SpecsBase
}
[Fact]
public async Task Help_text_shows_all_parameters_and_options()
public async Task I_can_request_the_help_text_to_see_the_list_of_all_parameters_and_options()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
[Command]
public class Command : ICommand
{
[CommandParameter(0, Name = "foo", Description = "Description of foo.")]
public string Foo { get; set; }
public string? Foo { get; init; }
[CommandOption("bar", Description = "Description of bar.")]
public string Bar { get; set; }
public string? Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default;
}
""");
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
@@ -513,10 +508,10 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ContainAllInOrder(
"PARAMETERS",
"foo", "Description of foo.",
@@ -526,20 +521,19 @@ public class HelpTextSpecs : SpecsBase
}
[Fact]
public async Task Help_text_shows_the_implicit_help_and_version_options_on_the_default_command()
public async Task I_can_request_the_help_text_to_see_the_help_and_version_options()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
[Command]
public class Command : ICommand
{
public ValueTask ExecuteAsync(IConsole console) => default;
}
""");
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
@@ -552,10 +546,10 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ContainAllInOrder(
"OPTIONS",
"-h", "--help", "Shows help text",
@@ -564,20 +558,19 @@ public class HelpTextSpecs : SpecsBase
}
[Fact]
public async Task Help_text_shows_the_implicit_help_option_but_not_the_version_option_on_a_named_command()
public async Task I_can_request_the_help_text_on_a_named_command_to_see_the_help_option()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
[Command("cmd")]
public class Command : ICommand
{
public ValueTask ExecuteAsync(IConsole console) => default;
}
""");
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
@@ -590,42 +583,43 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ContainAllInOrder(
"OPTIONS",
"-h", "--help", "Shows help text"
);
stdOut.Should().NotContainAny(
"--version", "Shows version information"
);
}
[Fact]
public async Task Help_text_shows_all_valid_values_for_enum_parameters_and_options()
public async Task I_can_request_the_help_text_to_see_the_list_of_valid_values_for_all_parameters_and_options_bound_to_enum_properties()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
public enum CustomEnum { One, Two, Three }
[Command]
public class Command : ICommand
{
[CommandParameter(0)]
public CustomEnum Foo { get; set; }
public CustomEnum Foo { get; init; }
[CommandOption("bar")]
public CustomEnum Bar { get; set; }
public CustomEnum Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default;
}
""");
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
@@ -638,10 +632,10 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ContainAllInOrder(
"PARAMETERS",
"foo", "Choices:", "One", "Two", "Three",
@@ -651,28 +645,27 @@ public class HelpTextSpecs : SpecsBase
}
[Fact]
public async Task Help_text_shows_all_valid_values_for_non_scalar_enum_parameters_and_options()
public async Task I_can_request_the_help_text_to_see_the_list_of_valid_values_for_all_parameters_and_options_bound_to_non_scalar_enum_properties()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
public enum CustomEnum { One, Two, Three }
[Command]
public class Command : ICommand
{
[CommandParameter(0)]
public IReadOnlyList<CustomEnum> Foo { get; set; }
public required IReadOnlyList<CustomEnum> Foo { get; init; }
[CommandOption("bar")]
public IReadOnlyList<CustomEnum> Bar { get; set; }
public required IReadOnlyList<CustomEnum> Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default;
}
""");
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
@@ -685,10 +678,10 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ContainAllInOrder(
"PARAMETERS",
"foo", "Choices:", "One", "Two", "Three",
@@ -698,28 +691,27 @@ public class HelpTextSpecs : SpecsBase
}
[Fact]
public async Task Help_text_shows_all_valid_values_for_nullable_enum_parameters_and_options()
public async Task I_can_request_the_help_text_to_see_the_list_of_valid_values_for_all_parameters_and_options_bound_to_nullable_enum_properties()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
public enum CustomEnum { One, Two, Three }
[Command]
public class Command : ICommand
{
[CommandParameter(0)]
public CustomEnum? Foo { get; set; }
public CustomEnum? Foo { get; init; }
[CommandOption("bar")]
public IReadOnlyList<CustomEnum?> Bar { get; set; }
public IReadOnlyList<CustomEnum?>? Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default;
}
""");
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
@@ -732,10 +724,10 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ContainAllInOrder(
"PARAMETERS",
"foo", "Choices:", "One", "Two", "Three",
@@ -745,28 +737,27 @@ public class HelpTextSpecs : SpecsBase
}
[Fact]
public async Task Help_text_shows_environment_variables_for_options_that_have_them_configured_as_fallback()
public async Task I_can_request_the_help_text_to_see_the_environment_variables_of_options_that_use_them_as_fallback()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
public enum CustomEnum { One, Two, Three }
[Command]
public class Command : ICommand
{
[CommandOption("foo", EnvironmentVariable = "ENV_FOO")]
public CustomEnum Foo { get; set; }
public CustomEnum Foo { get; init; }
[CommandOption("bar", EnvironmentVariable = "ENV_BAR")]
public CustomEnum Bar { get; set; }
public CustomEnum Bar { get; init; }
public ValueTask ExecuteAsync(IConsole console) => default;
}
""");
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
@@ -779,10 +770,10 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ContainAllInOrder(
"OPTIONS",
"--foo", "Environment variable:", "ENV_FOO",
@@ -791,46 +782,45 @@ public class HelpTextSpecs : SpecsBase
}
[Fact]
public async Task Help_text_shows_default_values_for_non_required_options()
public async Task I_can_request_the_help_text_to_see_the_default_values_of_non_required_options()
{
// Arrange
var commandType = DynamicCommandBuilder.Compile(
// language=cs
"""
public enum CustomEnum { One, Two, Three }
[Command]
public class Command : ICommand
{
[CommandOption("foo")]
public object Foo { get; set; } = 42;
public object? Foo { get; init; } = 42;
[CommandOption("bar")]
public string Bar { get; set; } = "hello";
public string? Bar { get; init; } = "hello";
[CommandOption("baz")]
public IReadOnlyList<string> Baz { get; set; } = new[] {"one", "two", "three"};
public IReadOnlyList<string>? Baz { get; init; } = new[] {"one", "two", "three"};
[CommandOption("qwe")]
public bool Qwe { get; set; } = true;
public bool Qwe { get; init; } = true;
[CommandOption("qop")]
public int? Qop { get; set; } = 1337;
public int? Qop { get; init; } = 1337;
[CommandOption("zor")]
public TimeSpan Zor { get; set; } = TimeSpan.FromMinutes(123);
public TimeSpan Zor { get; init; } = TimeSpan.FromMinutes(123);
[CommandOption("lol")]
public CustomEnum Lol { get; set; } = CustomEnum.Two;
public CustomEnum Lol { get; init; } = CustomEnum.Two;
[CommandOption("hmm", IsRequired = true)]
public string Hmm { get; set; } = "not printed";
[CommandOption("hmm")]
public required string Hmm { get; init; } = "not printed";
public ValueTask ExecuteAsync(IConsole console) => default;
}
""");
"""
);
var application = new CliApplicationBuilder()
.AddCommand(commandType)
@@ -843,10 +833,11 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ContainAllInOrder(
"OPTIONS",
"--foo", "Default:", "42",
@@ -857,17 +848,17 @@ public class HelpTextSpecs : SpecsBase
"--zor", "Default:", "02:03:00",
"--lol", "Default:", "Two"
);
stdOut.Should().NotContain("not printed");
}
[Fact]
public async Task Help_text_shows_all_immediate_child_commands()
public async Task I_can_request_the_help_text_to_see_the_list_of_all_immediate_child_commands()
{
// Arrange
var commandTypes = DynamicCommandBuilder.CompileMany(
// language=cs
"""
[Command("cmd1", Description = "Description of one command.")]
public class FirstCommand : ICommand
{
@@ -886,7 +877,13 @@ public class HelpTextSpecs : SpecsBase
public ValueTask ExecuteAsync(IConsole console) => default;
}
""");
[Command("cmd3 child", Description = "Description of an orphaned command.")]
public class ThirdCommandChildCommand : ICommand
{
public ValueTask ExecuteAsync(IConsole console) => default;
}
"""
);
var application = new CliApplicationBuilder()
.AddCommands(commandTypes)
@@ -899,31 +896,34 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ContainAllInOrder(
"COMMANDS",
"cmd1", "Description of one command.",
"cmd2", "Description of another command."
"cmd2", "Description of another command.",
// `cmd2 child` will appear as an immediate command because it does not
// have a more specific parent.
"cmd3 child", "Description of an orphaned command."
);
// `cmd2 child` will still appear in the list of `cmd2` subcommands,
// but its description will not be seen.
// but its description will not be visible.
stdOut.Should().NotContain(
"Description of another command's child command."
);
}
[Fact]
public async Task Help_text_shows_all_immediate_child_commands_of_each_child_command()
public async Task I_can_request_the_help_text_to_see_the_list_of_all_immediate_grand_child_commands()
{
// Arrange
var commandTypes = DynamicCommandBuilder.CompileMany(
// language=cs
"""
[Command("cmd1")]
public class FirstCommand : ICommand
{
@@ -953,8 +953,8 @@ public class HelpTextSpecs : SpecsBase
{
public ValueTask ExecuteAsync(IConsole console) => default;
}
""");
"""
);
var application = new CliApplicationBuilder()
.AddCommands(commandTypes)
@@ -967,10 +967,10 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Should().ContainAllInOrder(
"COMMANDS",
"cmd1", "Subcommands:", "cmd1 child1",
@@ -979,58 +979,7 @@ public class HelpTextSpecs : SpecsBase
}
[Fact]
public async Task Help_text_shows_non_immediate_child_commands_if_they_do_not_have_a_more_specific_parent()
{
// Arrange
var commandTypes = DynamicCommandBuilder.CompileMany(
// language=cs
"""
[Command("cmd1")]
public class FirstCommand : ICommand
{
public ValueTask ExecuteAsync(IConsole console) => default;
}
[Command("cmd2 child1")]
public class SecondCommandFirstChildCommand : ICommand
{
public ValueTask ExecuteAsync(IConsole console) => default;
}
[Command("cmd2 child2")]
public class SecondCommandSecondChildCommand : ICommand
{
public ValueTask ExecuteAsync(IConsole console) => default;
}
""");
var application = new CliApplicationBuilder()
.AddCommands(commandTypes)
.UseConsole(FakeConsole)
.Build();
// Act
var exitCode = await application.RunAsync(
new[] {"--help"},
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
stdOut.Should().ContainAllInOrder(
"COMMANDS",
"cmd1",
"cmd2 child1",
"cmd2 child2"
);
}
[Fact]
public async Task Version_text_is_printed_if_provided_arguments_contain_the_version_option()
public async Task I_can_request_the_version_text_by_running_the_application_with_the_version_option()
{
// Arrange
var application = new CliApplicationBuilder()
@@ -1045,10 +994,10 @@ public class HelpTextSpecs : SpecsBase
new Dictionary<string, string>()
);
var stdOut = FakeConsole.ReadOutputString();
// Assert
exitCode.Should().Be(0);
var stdOut = FakeConsole.ReadOutputString();
stdOut.Trim().Should().Be("v6.9");
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -11,7 +11,6 @@
<PackageTags>command line executable interface framework parser arguments cli app application net core</PackageTags>
<PackageProjectUrl>https://github.com/Tyrrrz/CliFx</PackageProjectUrl>
<PackageReleaseNotes>https://github.com/Tyrrrz/CliFx/blob/master/Changelog.md</PackageReleaseNotes>
<PackageReadmeFile>Readme.md</PackageReadmeFile>
<PackageIcon>favicon.png</PackageIcon>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
@@ -21,13 +20,12 @@
</PropertyGroup>
<ItemGroup>
<None Include="../Readme.md" Pack="true" PackagePath="" Visible="false" />
<None Include="../favicon.png" Pack="true" PackagePath="" Visible="false" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="all" />
<PackageReference Include="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'" />
</ItemGroup>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

22
CliFx/Utils/PathEx.cs Normal file
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)
);
public static IEnumerable<StackFrame> ParseMany(string stackTrace)
public static IEnumerable<StackFrame> ParseTrace(string stackTrace)
{
var matches = Pattern.Matches(stackTrace).ToArray();

View File

@@ -1,7 +1,7 @@
<Project>
<PropertyGroup>
<Version>2.3.2</Version>
<Version>2.3.4</Version>
<Company>Tyrrrz</Company>
<Copyright>Copyright (C) Oleksii Holub</Copyright>
<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**:
> Defining a default (unnamed) command is not required.
> Defining the default (unnamed) command is not required.
> If it's absent, running the application without specifying a command will just show the root-level help text.
### Reporting errors
@@ -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.
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
[Command]
@@ -516,7 +516,7 @@ public class CancellableCommand : ICommand
> **Warning**:
> Cancellation handler is only respected when the user sends the interrupt signal for the first time.
> If the user decides to issue the signal again, the application will terminate immediately regardless of whether the command is cancellation-aware.
> If the user decides to issue the signal again, the application will be forcefully terminated without triggering the cancellation token.
### Type activation
@@ -531,7 +531,10 @@ The following example shows how to configure your application to use [`Microsoft
```csharp
public static class Program
{
public static async Task<int> Main()
public static async Task<int> Main() =>
await new CliApplicationBuilder()
.AddCommandsFromThisAssembly()
.UseTypeActivator(commandTypes =>
{
var services = new ServiceCollection();
@@ -539,17 +542,14 @@ public static class Program
services.AddSingleton<MyService>();
// Register commands
services.AddTransient<MyCommand>();
foreach (var commandType in commandTypes)
services.AddTransient(commandType);
var serviceProvider = services.BuildServiceProvider();
return await new CliApplicationBuilder()
.AddCommandsFromThisAssembly()
.UseTypeActivator(serviceProvider)
return services.BuildServiceProvider();
})
.Build()
.RunAsync();
}
}
```
### Testing
@@ -621,7 +621,12 @@ public async Task ConcatCommand_executes_successfully()
.UseConsole(console)
.Build();
var args = new[] {"--left", "foo", "--right", "bar"};
var args = new[]
{
"--left", "foo",
"--right", "bar"
};
var envVars = new Dictionary<string, string>();
// Act