diff --git a/CliFx.Analyzers.Tests/CommandMustBeAnnotatedAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/CommandMustBeAnnotatedAnalyzerSpecs.cs index f7b51ea..40ab577 100644 --- a/CliFx.Analyzers.Tests/CommandMustBeAnnotatedAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/CommandMustBeAnnotatedAnalyzerSpecs.cs @@ -69,7 +69,7 @@ public class CommandMustBeAnnotatedAnalyzerSpecs """ public class Foo { - public int Bar { get; set; } = 5; + public int Bar { get; init; } = 5; } """; diff --git a/CliFx.Analyzers.Tests/CommandMustImplementInterfaceAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/CommandMustImplementInterfaceAnalyzerSpecs.cs index 47bc3b7..7ba028d 100644 --- a/CliFx.Analyzers.Tests/CommandMustImplementInterfaceAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/CommandMustImplementInterfaceAnalyzerSpecs.cs @@ -53,7 +53,7 @@ public class CommandMustImplementInterfaceAnalyzerSpecs """ public class Foo { - public int Bar { get; set; } = 5; + public int Bar { get; init; } = 5; } """; diff --git a/CliFx.Analyzers.Tests/OptionMustBeInsideCommandAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/OptionMustBeInsideCommandAnalyzerSpecs.cs index bc249a4..b2dc7ee 100644 --- a/CliFx.Analyzers.Tests/OptionMustBeInsideCommandAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/OptionMustBeInsideCommandAnalyzerSpecs.cs @@ -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; } diff --git a/CliFx.Analyzers.Tests/OptionMustBeRequiredIfPropertyRequiredAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/OptionMustBeRequiredIfPropertyRequiredAnalyzerSpecs.cs index 63110c3..1a542a3 100644 --- a/CliFx.Analyzers.Tests/OptionMustBeRequiredIfPropertyRequiredAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/OptionMustBeRequiredIfPropertyRequiredAnalyzerSpecs.cs @@ -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; } diff --git a/CliFx.Analyzers.Tests/OptionMustHaveNameOrShortNameAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/OptionMustHaveNameOrShortNameAnalyzerSpecs.cs index 570cf6f..3f8ffd2 100644 --- a/CliFx.Analyzers.Tests/OptionMustHaveNameOrShortNameAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/OptionMustHaveNameOrShortNameAnalyzerSpecs.cs @@ -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; } diff --git a/CliFx.Analyzers.Tests/OptionMustHaveUniqueNameAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/OptionMustHaveUniqueNameAnalyzerSpecs.cs index 40d7bc3..6b9e507 100644 --- a/CliFx.Analyzers.Tests/OptionMustHaveUniqueNameAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/OptionMustHaveUniqueNameAnalyzerSpecs.cs @@ -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; } diff --git a/CliFx.Analyzers.Tests/OptionMustHaveUniqueShortNameAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/OptionMustHaveUniqueShortNameAnalyzerSpecs.cs index 0030805..ae09360 100644 --- a/CliFx.Analyzers.Tests/OptionMustHaveUniqueShortNameAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/OptionMustHaveUniqueShortNameAnalyzerSpecs.cs @@ -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; } diff --git a/CliFx.Analyzers.Tests/OptionMustHaveValidConverterAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/OptionMustHaveValidConverterAnalyzerSpecs.cs index 3a4d933..b66f3b9 100644 --- a/CliFx.Analyzers.Tests/OptionMustHaveValidConverterAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/OptionMustHaveValidConverterAnalyzerSpecs.cs @@ -17,15 +17,15 @@ 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,15 +43,15 @@ public class OptionMustHaveValidConverterAnalyzerSpecs """ public class MyConverter : BindingConverter { - 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,15 +69,15 @@ public class OptionMustHaveValidConverterAnalyzerSpecs """ public class MyConverter : BindingConverter { - 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,15 +95,15 @@ public class OptionMustHaveValidConverterAnalyzerSpecs """ public class MyConverter : BindingConverter { - 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,15 +121,15 @@ public class OptionMustHaveValidConverterAnalyzerSpecs """ public class MyConverter : BindingConverter { - 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 Foo { get; set; } - + public IReadOnlyList? Foo { get; init; } + public ValueTask ExecuteAsync(IConsole console) => default; } """; @@ -149,8 +149,8 @@ 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,8 +169,8 @@ public class OptionMustHaveValidConverterAnalyzerSpecs [Command] public class MyCommand : ICommand { - public string Foo { get; set; } - + public string? Foo { get; init; } + public ValueTask ExecuteAsync(IConsole console) => default; } """; diff --git a/CliFx.Analyzers.Tests/OptionMustHaveValidNameAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/OptionMustHaveValidNameAnalyzerSpecs.cs index a8b4ca5..cad4057 100644 --- a/CliFx.Analyzers.Tests/OptionMustHaveValidNameAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/OptionMustHaveValidNameAnalyzerSpecs.cs @@ -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; } diff --git a/CliFx.Analyzers.Tests/OptionMustHaveValidShortNameAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/OptionMustHaveValidShortNameAnalyzerSpecs.cs index 8f2fe94..09def89 100644 --- a/CliFx.Analyzers.Tests/OptionMustHaveValidShortNameAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/OptionMustHaveValidShortNameAnalyzerSpecs.cs @@ -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; } diff --git a/CliFx.Analyzers.Tests/OptionMustHaveValidValidatorsAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/OptionMustHaveValidValidatorsAnalyzerSpecs.cs index 05ea6e4..85f307c 100644 --- a/CliFx.Analyzers.Tests/OptionMustHaveValidValidatorsAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/OptionMustHaveValidValidatorsAnalyzerSpecs.cs @@ -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; } diff --git a/CliFx.Analyzers.Tests/ParameterMustBeInsideCommandAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/ParameterMustBeInsideCommandAnalyzerSpecs.cs index 6f336f9..3b34f1f 100644 --- a/CliFx.Analyzers.Tests/ParameterMustBeInsideCommandAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/ParameterMustBeInsideCommandAnalyzerSpecs.cs @@ -18,7 +18,7 @@ public class ParameterMustBeInsideCommandAnalyzerSpecs public class MyClass { [CommandParameter(0)] - public string Foo { get; set; } + public required string Foo { get; init; } } """; @@ -37,8 +37,8 @@ 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,8 +75,8 @@ public class ParameterMustBeInsideCommandAnalyzerSpecs [Command] public class MyCommand : ICommand { - public string Foo { get; set; } - + public string? Foo { get; init; } + public ValueTask ExecuteAsync(IConsole console) => default; } """; diff --git a/CliFx.Analyzers.Tests/ParameterMustBeLastIfNonRequiredAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/ParameterMustBeLastIfNonRequiredAnalyzerSpecs.cs index 388cb9e..86e40b0 100644 --- a/CliFx.Analyzers.Tests/ParameterMustBeLastIfNonRequiredAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/ParameterMustBeLastIfNonRequiredAnalyzerSpecs.cs @@ -19,11 +19,11 @@ 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,11 +43,11 @@ 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,11 +67,11 @@ public class ParameterMustBeLastIfNonRequiredAnalyzerSpecs public class MyCommand : ICommand { [CommandParameter(0)] - public string Foo { get; set; } - - [CommandParameter(1, IsRequired = true)] - public string Bar { get; set; } - + public required string Foo { get; init; } + + [CommandParameter(1)] + public required string Bar { get; init; } + public ValueTask ExecuteAsync(IConsole console) => default; } """; @@ -90,8 +90,8 @@ public class ParameterMustBeLastIfNonRequiredAnalyzerSpecs [Command] public class MyCommand : ICommand { - public string Foo { get; set; } - + public string? Foo { get; init; } + public ValueTask ExecuteAsync(IConsole console) => default; } """; diff --git a/CliFx.Analyzers.Tests/ParameterMustBeLastIfNonScalarAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/ParameterMustBeLastIfNonScalarAnalyzerSpecs.cs index 711f815..61d89bc 100644 --- a/CliFx.Analyzers.Tests/ParameterMustBeLastIfNonScalarAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/ParameterMustBeLastIfNonScalarAnalyzerSpecs.cs @@ -19,11 +19,11 @@ 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,11 +43,11 @@ 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,11 +67,11 @@ 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,8 +90,8 @@ public class ParameterMustBeLastIfNonScalarAnalyzerSpecs [Command] public class MyCommand : ICommand { - public string Foo { get; set; } - + public string? Foo { get; init; } + public ValueTask ExecuteAsync(IConsole console) => default; } """; diff --git a/CliFx.Analyzers.Tests/ParameterMustBeRequiredIfPropertyRequiredAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/ParameterMustBeRequiredIfPropertyRequiredAnalyzerSpecs.cs index 7e5e333..c613a44 100644 --- a/CliFx.Analyzers.Tests/ParameterMustBeRequiredIfPropertyRequiredAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/ParameterMustBeRequiredIfPropertyRequiredAnalyzerSpecs.cs @@ -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; } diff --git a/CliFx.Analyzers.Tests/ParameterMustBeSingleIfNonRequiredAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/ParameterMustBeSingleIfNonRequiredAnalyzerSpecs.cs index bcdaa71..50cb467 100644 --- a/CliFx.Analyzers.Tests/ParameterMustBeSingleIfNonRequiredAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/ParameterMustBeSingleIfNonRequiredAnalyzerSpecs.cs @@ -19,11 +19,11 @@ 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,11 +43,11 @@ 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,11 +67,11 @@ public class ParameterMustBeSingleIfNonRequiredAnalyzerSpecs public class MyCommand : ICommand { [CommandParameter(0)] - public string Foo { get; set; } - - [CommandParameter(1, IsRequired = true)] - public string Bar { get; set; } - + public required string Foo { get; init; } + + [CommandParameter(1)] + public required string Bar { get; init; } + public ValueTask ExecuteAsync(IConsole console) => default; } """; @@ -90,8 +90,8 @@ public class ParameterMustBeSingleIfNonRequiredAnalyzerSpecs [Command] public class MyCommand : ICommand { - public string Foo { get; set; } - + public string? Foo { get; init; } + public ValueTask ExecuteAsync(IConsole console) => default; } """; diff --git a/CliFx.Analyzers.Tests/ParameterMustBeSingleIfNonScalarAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/ParameterMustBeSingleIfNonScalarAnalyzerSpecs.cs index 053968d..9be2724 100644 --- a/CliFx.Analyzers.Tests/ParameterMustBeSingleIfNonScalarAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/ParameterMustBeSingleIfNonScalarAnalyzerSpecs.cs @@ -19,11 +19,11 @@ 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,11 +43,11 @@ 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,11 +67,11 @@ 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,8 +90,8 @@ public class ParameterMustBeSingleIfNonScalarAnalyzerSpecs [Command] public class MyCommand : ICommand { - public string Foo { get; set; } - + public string? Foo { get; init; } + public ValueTask ExecuteAsync(IConsole console) => default; } """; diff --git a/CliFx.Analyzers.Tests/ParameterMustHaveUniqueNameAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/ParameterMustHaveUniqueNameAnalyzerSpecs.cs index f9b86af..1959f90 100644 --- a/CliFx.Analyzers.Tests/ParameterMustHaveUniqueNameAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/ParameterMustHaveUniqueNameAnalyzerSpecs.cs @@ -19,11 +19,11 @@ 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,11 +43,11 @@ 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,8 +66,8 @@ public class ParameterMustHaveUniqueNameAnalyzerSpecs [Command] public class MyCommand : ICommand { - public string Foo { get; set; } - + public string? Foo { get; init; } + public ValueTask ExecuteAsync(IConsole console) => default; } """; diff --git a/CliFx.Analyzers.Tests/ParameterMustHaveUniqueOrderAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/ParameterMustHaveUniqueOrderAnalyzerSpecs.cs index 27a26cb..a53ad98 100644 --- a/CliFx.Analyzers.Tests/ParameterMustHaveUniqueOrderAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/ParameterMustHaveUniqueOrderAnalyzerSpecs.cs @@ -19,11 +19,11 @@ 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,11 +43,11 @@ 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,8 +66,8 @@ public class ParameterMustHaveUniqueOrderAnalyzerSpecs [Command] public class MyCommand : ICommand { - public string Foo { get; set; } - + public string? Foo { get; init; } + public ValueTask ExecuteAsync(IConsole console) => default; } """; diff --git a/CliFx.Analyzers.Tests/ParameterMustHaveValidConverterAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/ParameterMustHaveValidConverterAnalyzerSpecs.cs index 43471c4..db37849 100644 --- a/CliFx.Analyzers.Tests/ParameterMustHaveValidConverterAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/ParameterMustHaveValidConverterAnalyzerSpecs.cs @@ -17,15 +17,15 @@ 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,15 +43,15 @@ public class ParameterMustHaveValidConverterAnalyzerSpecs """ public class MyConverter : BindingConverter { - 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,15 +70,15 @@ public class ParameterMustHaveValidConverterAnalyzerSpecs """ public class MyConverter : BindingConverter { - 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,15 +96,15 @@ public class ParameterMustHaveValidConverterAnalyzerSpecs """ public class MyConverter : BindingConverter { - 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,15 +122,15 @@ public class ParameterMustHaveValidConverterAnalyzerSpecs """ public class MyConverter : BindingConverter { - 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 Foo { get; set; } - + public required IReadOnlyList Foo { get; init; } + public ValueTask ExecuteAsync(IConsole console) => default; } """; @@ -150,8 +150,8 @@ 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,8 +170,8 @@ public class ParameterMustHaveValidConverterAnalyzerSpecs [Command] public class MyCommand : ICommand { - public string Foo { get; set; } - + public string? Foo { get; init; } + public ValueTask ExecuteAsync(IConsole console) => default; } """; diff --git a/CliFx.Analyzers.Tests/ParameterMustHaveValidValidatorsAnalyzerSpecs.cs b/CliFx.Analyzers.Tests/ParameterMustHaveValidValidatorsAnalyzerSpecs.cs index abd9ebc..c76f201 100644 --- a/CliFx.Analyzers.Tests/ParameterMustHaveValidValidatorsAnalyzerSpecs.cs +++ b/CliFx.Analyzers.Tests/ParameterMustHaveValidValidatorsAnalyzerSpecs.cs @@ -19,13 +19,13 @@ public class ParameterMustHaveValidValidatorsAnalyzerSpecs { public void Validate(string value) {} } - + [Command] 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; } """; @@ -45,13 +45,13 @@ public class ParameterMustHaveValidValidatorsAnalyzerSpecs { public override BindingValidationError Validate(int value) => Ok(); } - + [Command] 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; } """; @@ -71,13 +71,13 @@ public class ParameterMustHaveValidValidatorsAnalyzerSpecs { public override BindingValidationError Validate(string value) => Ok(); } - + [Command] 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,8 +97,8 @@ 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,8 +117,8 @@ public class ParameterMustHaveValidValidatorsAnalyzerSpecs [Command] public class MyCommand : ICommand { - public string Foo { get; set; } - + public string? Foo { get; init; } + public ValueTask ExecuteAsync(IConsole console) => default; } """; diff --git a/CliFx.Demo/Commands/BookAddCommand.cs b/CliFx.Demo/Commands/BookAddCommand.cs index 725ef86..27f46e3 100644 --- a/CliFx.Demo/Commands/BookAddCommand.cs +++ b/CliFx.Demo/Commands/BookAddCommand.cs @@ -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.")] diff --git a/CliFx.Tests.Dummy/Commands/CancellationTestCommand.cs b/CliFx.Tests.Dummy/Commands/CancellationTestCommand.cs new file mode 100644 index 0000000..15964e3 --- /dev/null +++ b/CliFx.Tests.Dummy/Commands/CancellationTestCommand.cs @@ -0,0 +1,28 @@ +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 + { + await Task.Delay( + TimeSpan.FromSeconds(3), + console.RegisterCancellationHandler() + ); + + console.Output.WriteLine("Completed successfully"); + } + catch (OperationCanceledException) + { + console.Output.WriteLine("Cancelled"); + throw; + } + } +} \ No newline at end of file diff --git a/CliFx.Tests.Dummy/Commands/EnvironmentTestCommand.cs b/CliFx.Tests.Dummy/Commands/EnvironmentTestCommand.cs index c0a09d4..871565c 100644 --- a/CliFx.Tests.Dummy/Commands/EnvironmentTestCommand.cs +++ b/CliFx.Tests.Dummy/Commands/EnvironmentTestCommand.cs @@ -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) { diff --git a/CliFx.Tests.Dummy/Program.cs b/CliFx.Tests.Dummy/Program.cs index 8fd9bb3..04059cc 100644 --- a/CliFx.Tests.Dummy/Program.cs +++ b/CliFx.Tests.Dummy/Program.cs @@ -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(); diff --git a/CliFx.Tests/ApplicationSpecs.cs b/CliFx.Tests/ApplicationSpecs.cs index 36a7e0c..74c27f6 100644 --- a/CliFx.Tests/ApplicationSpecs.cs +++ b/CliFx.Tests/ApplicationSpecs.cs @@ -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_can_try_to_add_an_invalid_command_to_the_application_and_get_an_error() { // Act var app = new CliApplicationBuilder() @@ -76,10 +76,10 @@ public class ApplicationSpecs : SpecsBase new Dictionary() ); - var stdErr = FakeConsole.ReadErrorString(); - // Assert exitCode.Should().NotBe(0); + + var stdErr = FakeConsole.ReadErrorString(); stdErr.Should().Contain("not a valid command"); } } \ No newline at end of file diff --git a/CliFx.Tests/CancellationSpecs.cs b/CliFx.Tests/CancellationSpecs.cs index 25491e1..56c4e41 100644 --- a/CliFx.Tests/CancellationSpecs.cs +++ b/CliFx.Tests/CancellationSpecs.cs @@ -1,7 +1,10 @@ using System; using System.Collections.Generic; +using System.Text; +using System.Threading; using System.Threading.Tasks; using CliFx.Tests.Utils; +using CliWrap; using FluentAssertions; using Xunit; using Xunit.Abstractions; @@ -15,8 +18,36 @@ public class CancellationSpecs : SpecsBase { } + [Fact(Timeout = 15000)] + public async Task I_can_configure_the_command_to_listen_to_the_interrupt_signal() + { + // Arrange + var stdOutBuffer = new StringBuilder(); + + var command = Cli.Wrap("dotnet") + .WithArguments(a => a + .Add(Dummy.Program.Location) + .Add("cancel-test") + ) | stdOutBuffer; + + using var cts = new CancellationTokenSource(); + cts.CancelAfter(TimeSpan.FromSeconds(0.2)); + + // Act & assert + await Assert.ThrowsAnyAsync(async () => + await command.ExecuteAsync( + // Forceful cancellation (not required because we have a timeout) + CancellationToken.None, + // Graceful cancellation + cts.Token + ) + ); + + stdOutBuffer.ToString().Trim().Should().Be("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( @@ -51,18 +82,18 @@ public class CancellationSpecs : SpecsBase .UseConsole(FakeConsole) .Build(); - // Act FakeConsole.RequestCancellation(TimeSpan.FromSeconds(0.2)); + // Act var exitCode = await application.RunAsync( Array.Empty(), new Dictionary() ); - var stdOut = FakeConsole.ReadOutputString(); - // Assert exitCode.Should().NotBe(0); + + var stdOut = FakeConsole.ReadOutputString(); stdOut.Trim().Should().Be("Cancelled"); } } \ No newline at end of file diff --git a/CliFx.Tests/ConsoleSpecs.cs b/CliFx.Tests/ConsoleSpecs.cs index 1edbb70..6e48bc8 100644 --- a/CliFx.Tests/ConsoleSpecs.cs +++ b/CliFx.Tests/ConsoleSpecs.cs @@ -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() ); - 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() ); - 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"); - } } \ No newline at end of file diff --git a/CliFx.Tests/ConversionSpecs.cs b/CliFx.Tests/ConversionSpecs.cs index 4ccbb96..e11e65b 100644 --- a/CliFx.Tests/ConversionSpecs.cs +++ b/CliFx.Tests/ConversionSpecs.cs @@ -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() ); - 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() ); - 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() ); - 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() - ); - - 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() ); - 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() ); - 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() ); - 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() ); - 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() ); - 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() ); - 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() ); - 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() ); - 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() ); - 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() ); - 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() ); - 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 Foo { get; set; } + public IReadOnlyList? Foo { get; init; } public ValueTask ExecuteAsync(IConsole console) { @@ -725,10 +695,10 @@ public class ConversionSpecs : SpecsBase new Dictionary() ); - 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 Foo { get; set; } + public List? Foo { get; init; } public ValueTask ExecuteAsync(IConsole console) { @@ -771,10 +741,10 @@ public class ConversionSpecs : SpecsBase new Dictionary() ); - 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() ); - 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_can_try_to_bind_a_parameter_or_an_option_to_a_property_of_an_unsupported_type_and_get_an_error() { // 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() - ); - - 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() ); - 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_can_try_to_bind_a_parameter_or_an_option_to_a_non_scalar_property_of_an_unsupported_type_and_get_an_error() { // 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() ); - 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() + ); + + // 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() ); - 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() ); - var stdErr = FakeConsole.ReadErrorString(); - // Assert exitCode.Should().NotBe(0); + + var stdErr = FakeConsole.ReadErrorString(); stdErr.Should().Contain("Hello world"); } } \ No newline at end of file diff --git a/CliFx.Tests/DirectivesSpecs.cs b/CliFx.Tests/DirectivesSpecs.cs index e891e90..ec0d61b 100644 --- a/CliFx.Tests/DirectivesSpecs.cs +++ b/CliFx.Tests/DirectivesSpecs.cs @@ -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", "", "[-a]", "[-b]", "[-c]", "[--option \"foo\"]", "ENV_QOP", "=", "\"hello\"", diff --git a/CliFx.Tests/EnvironmentSpecs.cs b/CliFx.Tests/EnvironmentSpecs.cs index 3599c2b..d269955 100644 --- a/CliFx.Tests/EnvironmentSpecs.cs +++ b/CliFx.Tests/EnvironmentSpecs.cs @@ -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(), + new[] {"--foo", "42"}, new Dictionary { - ["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 - { - ["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 Foo { get; set; } + public IReadOnlyList? 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(), - new Dictionary - { - ["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. diff --git a/CliFx.Tests/ErrorReportingSpecs.cs b/CliFx.Tests/ErrorReportingSpecs.cs index 96c402a..c77079c 100644 --- a/CliFx.Tests/ErrorReportingSpecs.cs +++ b/CliFx.Tests/ErrorReportingSpecs.cs @@ -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() ); - 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() ); - 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() ); - 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() ); - 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() ); - 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"); } } \ No newline at end of file diff --git a/CliFx.Tests/HelpTextSpecs.cs b/CliFx.Tests/HelpTextSpecs.cs index dcfa852..adfa154 100644 --- a/CliFx.Tests/HelpTextSpecs.cs +++ b/CliFx.Tests/HelpTextSpecs.cs @@ -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() ); - 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() ); - 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() ); - 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() ); - 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() ); - 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() ); - 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() ); - 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; - } - - """); + [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() ); - var stdOut = FakeConsole.ReadOutputString(); - // Assert exitCode.Should().Be(0); + + var stdOut = FakeConsole.ReadOutputString(); stdOut.Should().ContainAllInOrder( "DESCRIPTION", "Description of the default command." @@ -293,26 +293,25 @@ 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 - { - public ValueTask ExecuteAsync(IConsole console) => default; - } - - [Command("cmd")] - public class NamedCommand : ICommand - { - public ValueTask ExecuteAsync(IConsole console) => default; - } + [Command] + public class DefaultCommand : ICommand + { + public ValueTask ExecuteAsync(IConsole console) => default; + } - """); + [Command("cmd")] + public class NamedCommand : ICommand + { + public ValueTask ExecuteAsync(IConsole console) => default; + } + """ + ); var application = new CliApplicationBuilder() .AddCommands(commandTypes) @@ -325,10 +324,10 @@ public class HelpTextSpecs : SpecsBase new Dictionary() ); - 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; } - - [CommandParameter(1)] - public string Bar { get; set; } - - [CommandParameter(2)] - public IReadOnlyList Baz { get; set; } - - public ValueTask ExecuteAsync(IConsole console) => default; - } + [Command] + public class Command : ICommand + { + [CommandParameter(0)] + public required string Foo { get; init; } - """); + [CommandParameter(1)] + public required string Bar { get; init; } + + [CommandParameter(2)] + public required IReadOnlyList 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() ); - var stdOut = FakeConsole.ReadOutputString(); - // Assert exitCode.Should().Be(0); + + var stdOut = FakeConsole.ReadOutputString(); stdOut.Should().ContainAllInOrder( "USAGE", "", "", "" @@ -383,35 +381,34 @@ 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 abstract ValueTask ExecuteAsync(IConsole console); - } - - [Command] - public class Command : CommandBase - { - [CommandParameter(2)] - public IReadOnlyList Baz { get; set; } - - [CommandParameter(1)] - public string Bar { get; set; } - - public override ValueTask ExecuteAsync(IConsole console) => default; - } + // Base members appear last in reflection order + public abstract class CommandBase : ICommand + { + [CommandParameter(0)] + public required string Foo { get; init; } - """); + public abstract ValueTask ExecuteAsync(IConsole console); + } + + [Command] + public class Command : CommandBase + { + [CommandParameter(2)] + public required IReadOnlyList Baz { get; init; } + + [CommandParameter(1)] + 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() ); - var stdOut = FakeConsole.ReadOutputString(); - // Assert exitCode.Should().Be(0); + + var stdOut = FakeConsole.ReadOutputString(); stdOut.Should().ContainAllInOrder( "USAGE", "", "", "" @@ -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("bar")] - public string Bar { get; set; } - - [CommandOption("baz", IsRequired = true)] - public IReadOnlyList Baz { get; set; } - - public ValueTask ExecuteAsync(IConsole console) => default; - } + [Command] + public class Command : ICommand + { + [CommandOption("foo")] + public required string Foo { get; init; } - """); + [CommandOption("bar")] + public string? Bar { get; init; } + + [CommandOption("baz")] + public required IReadOnlyList 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() ); - var stdOut = FakeConsole.ReadOutputString(); - // Assert exitCode.Should().Be(0); + + var stdOut = FakeConsole.ReadOutputString(); stdOut.Should().ContainAllInOrder( "USAGE", "--foo ", "--baz ", "[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; } - - [CommandOption("bar", Description = "Description of bar.")] - public string Bar { get; set; } - - public ValueTask ExecuteAsync(IConsole console) => default; - } + [Command] + public class Command : ICommand + { + [CommandParameter(0, Name = "foo", Description = "Description of foo.")] + public string? Foo { get; init; } - """); + [CommandOption("bar", Description = "Description of bar.")] + 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() ); - 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; - } - - """); + [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() ); - 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; - } - - """); + [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() ); - 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; } - - [CommandOption("bar")] - public CustomEnum Bar { get; set; } - - public ValueTask ExecuteAsync(IConsole console) => default; - } + public enum CustomEnum { One, Two, Three } - """); + [Command] + public class Command : ICommand + { + [CommandParameter(0)] + public CustomEnum Foo { get; init; } + + [CommandOption("bar")] + 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() ); - 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 Foo { get; set; } - - [CommandOption("bar")] - public IReadOnlyList Bar { get; set; } - - public ValueTask ExecuteAsync(IConsole console) => default; - } + public enum CustomEnum { One, Two, Three } - """); + [Command] + public class Command : ICommand + { + [CommandParameter(0)] + public required IReadOnlyList Foo { get; init; } + + [CommandOption("bar")] + public required IReadOnlyList 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() ); - 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; } - - [CommandOption("bar")] - public IReadOnlyList Bar { get; set; } - - public ValueTask ExecuteAsync(IConsole console) => default; - } + public enum CustomEnum { One, Two, Three } - """); + [Command] + public class Command : ICommand + { + [CommandParameter(0)] + public CustomEnum? Foo { get; init; } + + [CommandOption("bar")] + public IReadOnlyList? 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() ); - 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; } - - [CommandOption("bar", EnvironmentVariable = "ENV_BAR")] - public CustomEnum Bar { get; set; } - - public ValueTask ExecuteAsync(IConsole console) => default; - } + public enum CustomEnum { One, Two, Three } - """); + [Command] + public class Command : ICommand + { + [CommandOption("foo", EnvironmentVariable = "ENV_FOO")] + public CustomEnum Foo { get; init; } + + [CommandOption("bar", EnvironmentVariable = "ENV_BAR")] + 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() ); - 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; - - [CommandOption("bar")] - public string Bar { get; set; } = "hello"; - - [CommandOption("baz")] - public IReadOnlyList Baz { get; set; } = new[] {"one", "two", "three"}; - - [CommandOption("qwe")] - public bool Qwe { get; set; } = true; - - [CommandOption("qop")] - public int? Qop { get; set; } = 1337; - - [CommandOption("zor")] - public TimeSpan Zor { get; set; } = TimeSpan.FromMinutes(123); - - [CommandOption("lol")] - public CustomEnum Lol { get; set; } = CustomEnum.Two; - - [CommandOption("hmm", IsRequired = true)] - public string Hmm { get; set; } = "not printed"; - - public ValueTask ExecuteAsync(IConsole console) => default; - } + public enum CustomEnum { One, Two, Three } - """); + [Command] + public class Command : ICommand + { + [CommandOption("foo")] + public object? Foo { get; init; } = 42; + + [CommandOption("bar")] + public string? Bar { get; init; } = "hello"; + + [CommandOption("baz")] + public IReadOnlyList? Baz { get; init; } = new[] {"one", "two", "three"}; + + [CommandOption("qwe")] + public bool Qwe { get; init; } = true; + + [CommandOption("qop")] + public int? Qop { get; init; } = 1337; + + [CommandOption("zor")] + public TimeSpan Zor { get; init; } = TimeSpan.FromMinutes(123); + + [CommandOption("lol")] + public CustomEnum Lol { get; init; } = CustomEnum.Two; + + [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() ); - var stdOut = FakeConsole.ReadOutputString(); - // Assert exitCode.Should().Be(0); + + var stdOut = FakeConsole.ReadOutputString(); + stdOut.Should().ContainAllInOrder( "OPTIONS", "--foo", "Default:", "42", @@ -857,36 +848,42 @@ 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 - { - public ValueTask ExecuteAsync(IConsole console) => default; - } - - [Command("cmd2", Description = "Description of another command.")] - public class SecondCommand : ICommand - { - public ValueTask ExecuteAsync(IConsole console) => default; - } - - [Command("cmd2 child", Description = "Description of another command's child command.")] - public class SecondCommandChildCommand : ICommand - { - public ValueTask ExecuteAsync(IConsole console) => default; - } + [Command("cmd1", Description = "Description of one command.")] + public class FirstCommand : ICommand + { + public ValueTask ExecuteAsync(IConsole console) => default; + } - """); + [Command("cmd2", Description = "Description of another command.")] + public class SecondCommand : ICommand + { + public ValueTask ExecuteAsync(IConsole console) => default; + } + + [Command("cmd2 child", Description = "Description of another command's child command.")] + public class SecondCommandChildCommand : ICommand + { + 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,62 +896,65 @@ public class HelpTextSpecs : SpecsBase new Dictionary() ); - 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 - { - public ValueTask ExecuteAsync(IConsole console) => default; - } - - [Command("cmd1 child1")] - public class FirstCommandFirstChildCommand : ICommand - { - public ValueTask ExecuteAsync(IConsole console) => default; - } - - [Command("cmd2")] - public class SecondCommand : ICommand - { - public ValueTask ExecuteAsync(IConsole console) => default; - } - - [Command("cmd2 child11")] - public class SecondCommandFirstChildCommand : ICommand - { - public ValueTask ExecuteAsync(IConsole console) => default; - } - - [Command("cmd2 child2")] - public class SecondCommandSecondChildCommand : ICommand - { - public ValueTask ExecuteAsync(IConsole console) => default; - } + [Command("cmd1")] + public class FirstCommand : ICommand + { + public ValueTask ExecuteAsync(IConsole console) => default; + } - """); + [Command("cmd1 child1")] + public class FirstCommandFirstChildCommand : ICommand + { + public ValueTask ExecuteAsync(IConsole console) => default; + } + + [Command("cmd2")] + public class SecondCommand : ICommand + { + public ValueTask ExecuteAsync(IConsole console) => default; + } + + [Command("cmd2 child11")] + 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) @@ -967,10 +967,10 @@ public class HelpTextSpecs : SpecsBase new Dictionary() ); - 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() - ); - - 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() ); - var stdOut = FakeConsole.ReadOutputString(); - // Assert exitCode.Should().Be(0); + + var stdOut = FakeConsole.ReadOutputString(); stdOut.Trim().Should().Be("v6.9"); } } \ No newline at end of file diff --git a/CliFx.Tests/OptionBindingSpecs.cs b/CliFx.Tests/OptionBindingSpecs.cs index 0d1b630..4c2a6d3 100644 --- a/CliFx.Tests/OptionBindingSpecs.cs +++ b/CliFx.Tests/OptionBindingSpecs.cs @@ -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() ); - 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() ); - 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() ); - 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() ); - 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() ); - 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 Foo { get; set; } + public IReadOnlyList? Foo { get; init; } public ValueTask ExecuteAsync(IConsole console) { @@ -275,10 +283,10 @@ public class OptionBindingSpecs : SpecsBase new Dictionary() ); - 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 Foo { get; set; } + public IReadOnlyList? Foo { get; init; } public ValueTask ExecuteAsync(IConsole console) { @@ -321,10 +329,10 @@ public class OptionBindingSpecs : SpecsBase new Dictionary() ); - 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 Foo { get; set; } + public IReadOnlyList? 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() ); - 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 Foo { get; set; } + public IReadOnlyList? 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() ); - 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 Foo { get; set; } + public IReadOnlyList? 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() ); - 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() ); - 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() ); - 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() ); - 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() - ); - - 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 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() - ); - - 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() ); + // 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 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() + ); // 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() + ); + + // 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() ); - 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(), - new Dictionary() - ); - - var stdErr = FakeConsole.ReadErrorString(); - - // Assert - exitCode.Should().NotBe(0); - stdErr.Should().Contain("Missing required option(s)"); - } } \ No newline at end of file diff --git a/CliFx.Tests/ParameterBindingSpecs.cs b/CliFx.Tests/ParameterBindingSpecs.cs index 5ecbb1a..b05dd16 100644 --- a/CliFx.Tests/ParameterBindingSpecs.cs +++ b/CliFx.Tests/ParameterBindingSpecs.cs @@ -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() ); - 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 Baz { get; set; } + public required IReadOnlyList 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() ); - 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() + ); + + // 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 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() + ); + + // 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() ); - 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() - ); - - 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 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() - ); - - 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() ); - var stdErr = FakeConsole.ReadErrorString(); - // Assert exitCode.Should().NotBe(0); + + var stdErr = FakeConsole.ReadErrorString(); stdErr.Should().Contain("Unexpected parameter(s)"); } } \ No newline at end of file diff --git a/CliFx.Tests/RoutingSpecs.cs b/CliFx.Tests/RoutingSpecs.cs index 1618b19..c799554 100644 --- a/CliFx.Tests/RoutingSpecs.cs +++ b/CliFx.Tests/RoutingSpecs.cs @@ -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() ); - 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() ); - 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() ); - var stdOut = FakeConsole.ReadOutputString(); - // Assert exitCode.Should().Be(0); + + var stdOut = FakeConsole.ReadOutputString(); stdOut.Trim().Should().Be("cmd child"); } } \ No newline at end of file diff --git a/CliFx.Tests/TypeActivationSpecs.cs b/CliFx.Tests/TypeActivationSpecs.cs index b271894..34a3dcf 100644 --- a/CliFx.Tests/TypeActivationSpecs.cs +++ b/CliFx.Tests/TypeActivationSpecs.cs @@ -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() ); - 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() ); - 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() ); - 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( @@ -181,15 +181,15 @@ public class TypeActivationSpecs : SpecsBase new Dictionary() ); - 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( @@ -219,10 +219,10 @@ public class TypeActivationSpecs : SpecsBase new Dictionary() ); - var stdErr = FakeConsole.ReadErrorString(); - // Assert exitCode.Should().NotBe(0); + + var stdErr = FakeConsole.ReadErrorString(); stdErr.Should().Contain("Failed to create an instance of type"); } } \ No newline at end of file diff --git a/CliFx.Tests/Utils/DynamicCommandBuilder.cs b/CliFx.Tests/Utils/DynamicCommandBuilder.cs index 5d1591d..2cad754 100644 --- a/CliFx.Tests/Utils/DynamicCommandBuilder.cs +++ b/CliFx.Tests/Utils/DynamicCommandBuilder.cs @@ -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( diff --git a/CliFx.Tests/Utils/Extensions/AssertionExtensions.cs b/CliFx.Tests/Utils/Extensions/AssertionExtensions.cs index 8a6c0d7..7b6f893 100644 --- a/CliFx.Tests/Utils/Extensions/AssertionExtensions.cs +++ b/CliFx.Tests/Utils/Extensions/AssertionExtensions.cs @@ -41,7 +41,7 @@ internal static class AssertionExtensions lastIndex = index; } - return new(assertions); + return new AndConstraint(assertions); } public static AndConstraint ContainAllInOrder( diff --git a/CliFx.Tests/Utils/NoOpCommand.cs b/CliFx.Tests/Utils/NoOpCommand.cs index 034e393..c2b5a99 100644 --- a/CliFx.Tests/Utils/NoOpCommand.cs +++ b/CliFx.Tests/Utils/NoOpCommand.cs @@ -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; } \ No newline at end of file diff --git a/CliFx/ApplicationConfiguration.cs b/CliFx/ApplicationConfiguration.cs index 142a3e4..bb9a2d4 100644 --- a/CliFx/ApplicationConfiguration.cs +++ b/CliFx/ApplicationConfiguration.cs @@ -9,17 +9,17 @@ namespace CliFx; public class ApplicationConfiguration { /// - /// Command types defined in this application. + /// Command types defined in the application. /// public IReadOnlyList CommandTypes { get; } /// - /// Whether debug mode is allowed in this application. + /// Whether debug mode is allowed in the application. /// public bool IsDebugModeAllowed { get; } /// - /// Whether preview mode is allowed in this application. + /// Whether preview mode is allowed in the application. /// public bool IsPreviewModeAllowed { get; } diff --git a/CliFx/Attributes/CommandAttribute.cs b/CliFx/Attributes/CommandAttribute.cs index 9c8cace..87efd41 100644 --- a/CliFx/Attributes/CommandAttribute.cs +++ b/CliFx/Attributes/CommandAttribute.cs @@ -9,13 +9,12 @@ namespace CliFx.Attributes; public sealed class CommandAttribute : Attribute { /// - /// Command's name. + /// Command name. /// /// - /// 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. /// public string? Name { get; } diff --git a/CliFx/Attributes/CommandParameterAttribute.cs b/CliFx/Attributes/CommandParameterAttribute.cs index 331ccd0..54cfd31 100644 --- a/CliFx/Attributes/CommandParameterAttribute.cs +++ b/CliFx/Attributes/CommandParameterAttribute.cs @@ -11,8 +11,7 @@ public sealed class CommandParameterAttribute : Attribute { /// /// 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. /// /// /// All parameters in a command must have unique order. diff --git a/CliFx/CliApplication.cs b/CliFx/CliApplication.cs index 58201f1..94f0f1c 100644 --- a/CliFx/CliApplication.cs +++ b/CliFx/CliApplication.cs @@ -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 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(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 /// /// 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. /// /// - /// 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. /// public async ValueTask RunAsync( IReadOnlyList 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 /// /// 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. /// /// - /// 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. /// public async ValueTask RunAsync(IReadOnlyList commandLineArguments) => await RunAsync( commandLineArguments, @@ -229,11 +227,11 @@ public class CliApplication /// /// 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. /// /// - /// 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. /// public async ValueTask RunAsync() => await RunAsync( Environment.GetCommandLineArgs() diff --git a/CliFx/CliApplicationBuilder.cs b/CliFx/CliApplicationBuilder.cs index 51a7676..ccd2761 100644 --- a/CliFx/CliApplicationBuilder.cs +++ b/CliFx/CliApplicationBuilder.cs @@ -252,11 +252,13 @@ public partial class CliApplicationBuilder // 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); + } // 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) || + if (PathEx.AreEqual(Path.ChangeExtension(entryAssemblyFilePath, "exe"), processFilePath) || PathEx.AreEqual(Path.ChangeExtension(entryAssemblyFilePath, ""), processFilePath)) { return Path.GetFileNameWithoutExtension(entryAssemblyFilePath); diff --git a/CliFx/CommandBinder.cs b/CliFx/CommandBinder.cs index c3d261c..44bea96 100644 --- a/CliFx/CommandBinder.cs +++ b/CliFx/CommandBinder.cs @@ -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(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 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(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; diff --git a/CliFx/Exceptions/CliFxException.cs b/CliFx/Exceptions/CliFxException.cs index 61c779b..6661e6c 100644 --- a/CliFx/Exceptions/CliFxException.cs +++ b/CliFx/Exceptions/CliFxException.cs @@ -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; } /// /// 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); } \ No newline at end of file diff --git a/CliFx/Extensibility/BindingConverter.cs b/CliFx/Extensibility/BindingConverter.cs index d09afb1..5af0250 100644 --- a/CliFx/Extensibility/BindingConverter.cs +++ b/CliFx/Extensibility/BindingConverter.cs @@ -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); diff --git a/CliFx/Extensibility/BindingValidator.cs b/CliFx/Extensibility/BindingValidator.cs index acc3183..0856737 100644 --- a/CliFx/Extensibility/BindingValidator.cs +++ b/CliFx/Extensibility/BindingValidator.cs @@ -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); diff --git a/CliFx/Formatting/ExceptionConsoleFormatter.cs b/CliFx/Formatting/ExceptionConsoleFormatter.cs index 4ec875d..d032edd 100644 --- a/CliFx/Formatting/ExceptionConsoleFormatter.cs +++ b/CliFx/Formatting/ExceptionConsoleFormatter.cs @@ -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"); diff --git a/CliFx/Formatting/HelpConsoleFormatter.cs b/CliFx/Formatting/HelpConsoleFormatter.cs index 3b51f96..e7b0bda 100644 --- a/CliFx/Formatting/HelpConsoleFormatter.cs +++ b/CliFx/Formatting/HelpConsoleFormatter.cs @@ -413,7 +413,6 @@ internal class HelpConsoleFormatter : ConsoleFormatter Write(ConsoleColor.White, "Subcommands: "); var isFirst = true; - foreach (var grandChildCommandSchema in grandChildCommandSchemas) { if (isFirst) diff --git a/CliFx/ICommand.cs b/CliFx/ICommand.cs index feae3f2..ec2f856 100644 --- a/CliFx/ICommand.cs +++ b/CliFx/ICommand.cs @@ -13,7 +13,7 @@ public interface ICommand /// /// /// If the execution of the command is not asynchronous, simply end the method with - /// return default; + /// return default; /// ValueTask ExecuteAsync(IConsole console); } \ No newline at end of file diff --git a/CliFx/Infrastructure/FakeConsole.cs b/CliFx/Infrastructure/FakeConsole.cs index 4ab99f8..4947b5c 100644 --- a/CliFx/Infrastructure/FakeConsole.cs +++ b/CliFx/Infrastructure/FakeConsole.cs @@ -8,10 +8,8 @@ namespace CliFx.Infrastructure; /// /// Implementation of that uses the provided fake /// standard input, output, and error streams. +/// Use this implementation in tests to verify command interactions with the console. /// -/// -/// Use this implementation in tests to verify how a command interacts with the console. -/// public class FakeConsole : IConsole, IDisposable { private readonly CancellationTokenSource _cancellationTokenSource = new(); diff --git a/CliFx/Infrastructure/FakeInMemoryConsole.cs b/CliFx/Infrastructure/FakeInMemoryConsole.cs index 5ce76ab..732ca59 100644 --- a/CliFx/Infrastructure/FakeInMemoryConsole.cs +++ b/CliFx/Infrastructure/FakeInMemoryConsole.cs @@ -5,10 +5,8 @@ namespace CliFx.Infrastructure; /// /// Implementation of 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. /// -/// -/// Use this implementation in tests to verify how a command interacts with the console. -/// public class FakeInMemoryConsole : FakeConsole { private readonly MemoryStream _input; @@ -36,17 +34,17 @@ public class FakeInMemoryConsole : FakeConsole /// 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); } } diff --git a/CliFx/Infrastructure/IConsole.cs b/CliFx/Infrastructure/IConsole.cs index a261ca0..6713ea0 100644 --- a/CliFx/Infrastructure/IConsole.cs +++ b/CliFx/Infrastructure/IConsole.cs @@ -86,19 +86,18 @@ public interface IConsole /// /// 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. /// /// /// - /// 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. /// /// - /// 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. /// /// CancellationToken RegisterCancellationHandler(); diff --git a/CliFx/Infrastructure/ITypeActivator.cs b/CliFx/Infrastructure/ITypeActivator.cs index d6f70c2..6b18000 100644 --- a/CliFx/Infrastructure/ITypeActivator.cs +++ b/CliFx/Infrastructure/ITypeActivator.cs @@ -1,4 +1,7 @@ using System; +using CliFx.Exceptions; +using CliFx.Extensibility; +using CliFx.Utils.Extensions; namespace CliFx.Infrastructure; @@ -11,4 +14,19 @@ public interface ITypeActivator /// Creates an instance of the specified type. /// object CreateInstance(Type type); +} + +internal static class TypeActivatorExtensions +{ + public static T CreateInstance(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); + } } \ No newline at end of file diff --git a/CliFx/Input/CommandInput.cs b/CliFx/Input/CommandInput.cs index 9820b69..e889136 100644 --- a/CliFx/Input/CommandInput.cs +++ b/CliFx/Input/CommandInput.cs @@ -17,6 +17,12 @@ internal partial class CommandInput public IReadOnlyList 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(); - // 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(); } } @@ -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)); diff --git a/CliFx/Schema/ApplicationSchema.cs b/CliFx/Schema/ApplicationSchema.cs index 308515e..a48198b 100644 --- a/CliFx/Schema/ApplicationSchema.cs +++ b/CliFx/Schema/ApplicationSchema.cs @@ -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 GetDescendantCommands( diff --git a/CliFx/Schema/CommandSchema.cs b/CliFx/Schema/CommandSchema.cs index 14e7cdb..c2fe7c8 100644 --- a/CliFx/Schema/CommandSchema.cs +++ b/CliFx/Schema/CommandSchema.cs @@ -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( diff --git a/CliFx/Utils/StackFrame.cs b/CliFx/Utils/StackFrame.cs index e97846b..b7f9dc3 100644 --- a/CliFx/Utils/StackFrame.cs +++ b/CliFx/Utils/StackFrame.cs @@ -89,7 +89,7 @@ internal partial class StackFrame TimeSpan.FromSeconds(5) ); - public static IEnumerable ParseMany(string stackTrace) + public static IEnumerable ParseTrace(string stackTrace) { var matches = Pattern.Matches(stackTrace).ToArray(); diff --git a/Readme.md b/Readme.md index f368e34..5e409a9 100644 --- a/Readme.md +++ b/Readme.md @@ -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 @@ -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(); // Act