Skip to content

Commit

Permalink
Merge pull request #505 from bilal-fazlani/nullable-class-constraint
Browse files Browse the repository at this point in the history
breaK with ExitCodes Async rename. change to `T:class?` constraint for nulls
  • Loading branch information
drewburlingame authored Jan 8, 2025
2 parents 8953415 + b19b7fd commit 2565c1d
Show file tree
Hide file tree
Showing 42 changed files with 100 additions and 102 deletions.
2 changes: 1 addition & 1 deletion CommandDotNet.DataAnnotations/DataAnnotationsMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ private static Task<int> DataAnnotationsValidation(CommandContext ctx, Execution
console.Error.WriteLine();
}

return ExitCodes.ValidationError;
return ExitCodes.ValidationErrorAsync;
}

return next(ctx);
Expand Down
8 changes: 4 additions & 4 deletions CommandDotNet.DocExamples/Diagnostics/Exceptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ private static int ErrorHandler(CommandContext? ctx, Exception exception)
// if the exception occurred before a command could be parsed
ctx?.PrintHelp();

return ExitCodes.Error.Result;
return ExitCodes.ErrorAsync.Result;
}

public void Throw(string message)
Expand Down Expand Up @@ -64,7 +64,7 @@ static int Main(string[] args)
.UseErrorHandler((ctx, ex) =>
{
(ctx?.Console.Error ?? Console.Error).WriteLine(ex.Message);
return ExitCodes.Error.Result;
return ExitCodes.ErrorAsync.Result;
})
.Run(args);
}
Expand Down Expand Up @@ -97,7 +97,7 @@ static int Main(string[] args)
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
return ExitCodes.Error.Result;
return ExitCodes.ErrorAsync.Result;
}
}
// end-snippet
Expand Down Expand Up @@ -146,7 +146,7 @@ private static int ErrorHandler(CommandContext? ctx, Exception exception)
// if the exception occurred before a command could be parsed
ctx?.PrintHelp();

return ExitCodes.Error.Result;
return ExitCodes.ErrorAsync.Result;
}

public void Throw(string message)
Expand Down
4 changes: 2 additions & 2 deletions CommandDotNet.Example/Commands/Prompts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,14 @@ public Task<int> Intercept(InterceptorExecutionDelegate next,
if (username == null)
{
console.Out.WriteLine("username not provided");
return ExitCodes.Error;
return ExitCodes.ErrorAsync;
}

var pwd = password?.GetPassword();
if (string.IsNullOrWhiteSpace(pwd))
{
console.Out.WriteLine("password not provided");
return ExitCodes.Error;
return ExitCodes.ErrorAsync;
}

console.Out.WriteLine($"authenticated as user:{username} with password:{password} (actual password:{pwd})");
Expand Down
4 changes: 2 additions & 2 deletions CommandDotNet.FluentValidation/FluentValidationMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,13 +99,13 @@ private static Task<int> FluentValidationForModels(CommandContext ctx, Execution
console.Error.WriteLine();
}

return ExitCodes.ValidationError;
return ExitCodes.ValidationErrorAsync;
}
}
catch (InvalidValidatorException e)
{
ctx.Console.Error.WriteLine(e.ToString());
return ExitCodes.Error;
return ExitCodes.ErrorAsync;
}

return next(ctx);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http;
using System.Threading.Tasks;
using CommandDotNet.Builders;
Expand Down Expand Up @@ -99,10 +100,8 @@ private static Task<int> AlertOnNewVersion(CommandContext context, ExecutionDele
return next(context);
}

private static bool TryGetCurrentVersion(out SemVersion semVersion)
{
return SemVersion.TryParse(AppInfo.Instance.Version, out semVersion);
}
private static bool TryGetCurrentVersion([NotNullWhen(true)] out SemVersion? semVersion) =>
SemVersion.TryParse(AppInfo.Instance.Version, out semVersion);

private static bool TryGetLatestReleaseVersion(CommandContext context, NewerReleaseConfig config, out SemVersion? semVersion)
{
Expand Down
2 changes: 1 addition & 1 deletion CommandDotNet.TestTools/AppRunnerTestExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public static AppRunner CaptureState(this AppRunner runner, Action<CommandContex
{
capture(context);
return exitAfterCapture
? ExitCodes.Success
? ExitCodes.SuccessAsync
: next(context);
}, middlewareStage, orderWithinStage));
}
Expand Down
13 changes: 1 addition & 12 deletions CommandDotNet.TestTools/AssertFailedException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,5 @@
namespace CommandDotNet.TestTools
{
[Serializable]
public class AssertFailedException : Exception
{
public AssertFailedException(string message)
: base(message)
{
}

protected AssertFailedException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
public class AssertFailedException(string message) : Exception(message);
}
9 changes: 3 additions & 6 deletions CommandDotNet.TestTools/InvocationInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,11 @@

namespace CommandDotNet.TestTools
{
public class InvocationInfo<T> : InvocationInfo where T: class
public class InvocationInfo<T>(CommandContext commandContext, InvocationStep invocationStep)
: InvocationInfo(commandContext, invocationStep)
where T : class
{
public new T? Instance => (T?)base.Instance;

public InvocationInfo(CommandContext commandContext, InvocationStep invocationStep)
: base(commandContext, invocationStep)
{
}
}

public class InvocationInfo
Expand Down
4 changes: 2 additions & 2 deletions CommandDotNet.TestTools/TestDependencyResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@ public void Add(object service)
_services.Add(service.GetType(), service);
}

public void Add<T>(T? service) where T: class
public void Add<T>(T? service) where T: class?
{
_services.Add(typeof(T), service);
}

public void AddOrUpdate<T>(T? service) where T : class
public void AddOrUpdate<T>(T? service) where T : class?
{
_services[typeof(T)] = service;
}
Expand Down
11 changes: 3 additions & 8 deletions CommandDotNet.TestTools/TrackingInvocation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,21 @@

namespace CommandDotNet.TestTools
{
internal class TrackingInvocation : IInvocation
internal class TrackingInvocation(IInvocation backingInvocation) : IInvocation
{
private readonly IInvocation _backingInvocation;
private readonly IInvocation _backingInvocation = backingInvocation ?? throw new ArgumentNullException(nameof(backingInvocation));

public bool WasInvoked { get; private set; }
public bool Errored => InvocationError != null;
public Exception? InvocationError { get; private set; }

public IReadOnlyCollection<IArgument> Arguments => _backingInvocation.Arguments;
public IReadOnlyCollection<ParameterInfo> Parameters => _backingInvocation.Parameters;
public object[] ParameterValues => _backingInvocation.ParameterValues;
public object?[] ParameterValues => _backingInvocation.ParameterValues;
public MethodInfo MethodInfo => _backingInvocation.MethodInfo;
public bool IsInterceptor => _backingInvocation.IsInterceptor;
public IReadOnlyCollection<IArgumentModel> FlattenedArgumentModels => _backingInvocation.FlattenedArgumentModels;

public TrackingInvocation(IInvocation backingInvocation)
{
_backingInvocation = backingInvocation ?? throw new ArgumentNullException(nameof(backingInvocation));
}

public object? Invoke(CommandContext commandContext, object instance, ExecutionDelegate next)
{
WasInvoked = true;
Expand Down
2 changes: 1 addition & 1 deletion CommandDotNet.Tests/AppRunnerScenarioExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace CommandDotNet.Tests
public static class AppRunnerScenarioExtensions
{
public static AppRunner StopAfter(this AppRunner runner, MiddlewareStep step)
=> runner.Configure(cfg => cfg.UseMiddleware((_, _) => ExitCodes.Success, step+1));
=> runner.Configure(cfg => cfg.UseMiddleware((_, _) => ExitCodes.SuccessAsync, step+1));

public static AppRunner StopAfter(this AppRunner runner, MiddlewareStages stage)
=> runner.StopAfter(new MiddlewareStep(stage));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ public void CommandLogger_Log_CanBeCalled_BeforeParseResults()
.Configure(c => c.UseMiddleware((context, next) =>
{
Diag.CommandLogger.Log(context, context.Console.Out.WriteLine);
return ExitCodes.Success;
return ExitCodes.SuccessAsync;
}, MiddlewareStages.PostTokenizePreParseInput))
.Verify(new Scenario
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public void ShortNameShouldBe(string propertyName, char? shortName)
[InlineData(LongNameNull, null)]
[InlineData(LongNameEmpty, null)]
[Theory]
public void LongNameShouldBe(string propertyName, string longName)
public void LongNameShouldBe(string propertyName, string? longName)
{
var option = _options[propertyName];
option.LongName.Should().Be(longName);
Expand Down
2 changes: 1 addition & 1 deletion CommandDotNet.Tests/FeatureTests/AsyncTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ private class App
[Command("get2", Description = "Invokes an async method and exits with return code 2")]
public async Task<int> Get2Async()
{
return await ExitCodes.ValidationError;
return await ExitCodes.ValidationErrorAsync;
}

[Command("get00", Description = "Invokes an async method and exits with return code 0")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ public Task<int> Intercept(InterceptorExecutionDelegate next,
{
if (interceptOptions.skipCmd)
{
return ExitCodes.Success;
return ExitCodes.SuccessAsync;
}

var returnCode = next();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ public Task<int> Intercept(InterceptorExecutionDelegate next,
{
if (interceptOptions.skipCmd)
{
return ExitCodes.Success;
return ExitCodes.SuccessAsync;
}

var returnCode = next();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public void Help_NoArgs_Includes_1stLevelCommands_And_2ndLevelApp(Type type)
When = { Args = null },
Then =
{
ExitCode = ExitCodes.Error.Result,
ExitCode = ExitCodes.Error,
Output = @"Required command was not provided
Usage: testhost.dll [command]
Expand Down
4 changes: 2 additions & 2 deletions CommandDotNet.Tests/FeatureTests/CommandInvocatorTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ Task<int> BeforeInvocation(CommandContext context, ExecutionDelegate next)
{
var values = context.InvocationPipeline.TargetCommand!.Invocation.ParameterValues;
values.Length.Should().Be(2);
var invokedCar = (Car) values[0];
var invokedOwner = (string)values[1];
var invokedCar = (Car) values[0]!;
var invokedOwner = (string)values[1]!;

invokedCar.Number.Should().Be(1);
invokedCar.Number = 2;
Expand Down
8 changes: 4 additions & 4 deletions CommandDotNet.Tests/FeatureTests/ExceptionHandlingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public void CanHandleErrors(string? commandName, string? exceptionMessage = null
{
context = ctx;
exception = ex;
return ExitCodes.Error.Result;
return ExitCodes.ErrorAsync.Result;
})
.Run(args);
exitCode.Should().Be(1);
Expand All @@ -69,7 +69,7 @@ public void CanHandleErrorsFromConstructor()
{
context = ctx;
exception = ex;
return ExitCodes.Error.Result;
return ExitCodes.ErrorAsync.Result;
})
.Run("Process");

Expand All @@ -86,7 +86,7 @@ public void ErrorHandlerIsNotTriggeredForValueParsingException()
.UseErrorHandler((ctx, ex) =>
{
exception = ex;
return ExitCodes.Error.Result;
return ExitCodes.ErrorAsync.Result;
})
.Run("Process -o");

Expand All @@ -102,7 +102,7 @@ public void ErrorHandlerIsNotTriggeredForInvalidConfigurationException()
.UseErrorHandler((ctx, ex) =>
{
exception = ex;
return ExitCodes.Error.Result;
return ExitCodes.ErrorAsync.Result;
})
.Run("Do");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ void ContainsIf(bool yes, string value)
if (exitBeforeBind)
{
appRunner.Configure(c =>
c.UseMiddleware((ctx, next) => ExitCodes.Success,
c.UseMiddleware((ctx, next) => ExitCodes.SuccessAsync,
MiddlewareStages.PostParseInputPreBindValues));
}

Expand All @@ -94,7 +94,7 @@ void ContainsIf(bool yes, string value)

var result = appRunner
.UseParseDirective()
.UseErrorHandler((ctx, ex) => ExitCodes.Error.Result)
.UseErrorHandler((ctx, ex) => ExitCodes.ErrorAsync.Result)
.Verify(new Scenario
{
When = {Args = $"{parse} {args}"},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ public void SwitchAct_ForNullArg_Should_ThrowNullRef()
{
Assert.Throws<ArgumentNullException>(() =>
((IArgument) null!).SwitchAct(
o => Assert.True(false, "operandAction should not be called for operand"),
o => Assert.True(false, "optionAction should not be called for operand"))
o => Assert.Fail("operandAction should not be called for operand"),
o => Assert.Fail("optionAction should not be called for operand"))
);
}

Expand All @@ -34,7 +34,7 @@ public void SwitchAct_ForOperand_Should_ExecuteOnlyOperandAction()

AnOperand.SwitchAct(
o => actionCalled = true,
o => Assert.True(false, "optionAction should not be called for operand"));
o => Assert.Fail("optionAction should not be called for operand"));

actionCalled.Should().BeTrue();
}
Expand All @@ -45,7 +45,7 @@ public void SwitchAct_ForOption_Should_ExecuteOnlyOptionAction()
bool actionCalled = false;

AnOption.SwitchAct(
o => Assert.True(false, "operandAction should not be called for option"),
o => Assert.Fail("operandAction should not be called for option"),
o => actionCalled = true);

actionCalled.Should().BeTrue();
Expand Down
6 changes: 3 additions & 3 deletions CommandDotNet/AppConfigBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public class AppConfigBuilder

private readonly SingleRegistrationGuard<Type> _parameterResolverSingleRegistrationGuard =
new("parameter resolver", type => type.FullName);
private readonly Dictionary<Type, Func<CommandContext, object>> _parameterResolversByType = new()
private readonly Dictionary<Type, Func<CommandContext, object?>> _parameterResolversByType = new()
{
[typeof(CommandContext)] = ctx => ctx,
[typeof(IConsole)] = ctx => ctx.Console,
Expand Down Expand Up @@ -93,9 +93,9 @@ public AppConfigBuilder(AppSettings appSettings)
/// Types must be resolvable from the <see cref="CommandContext"/><br/>
/// Default types: <see cref="CommandContext"/>, <see cref="IConsole"/>, <see cref="CancellationToken"/>
/// </summary>
public AppConfigBuilder UseParameterResolver<T>(Func<CommandContext,T> resolver) where T: class
public AppConfigBuilder UseParameterResolver<T>(Func<CommandContext,T> resolver) where T: class?
{
if (resolver == null) throw new ArgumentNullException(nameof(resolver));
ArgumentNullException.ThrowIfNull(resolver);

_parameterResolverSingleRegistrationGuard.Register(typeof(T));
_parameterResolversByType.Add(typeof(T), resolver);
Expand Down
6 changes: 3 additions & 3 deletions CommandDotNet/AppRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -172,12 +172,12 @@ private int HandleException(Exception ex, CommandContext? commandContext)
if (ex.IsFor<ValueParsingException>(out var vpe))
{
console.Error.WriteLine(vpe!.Print(excludeTypeName: true));
return ExitCodes.Error.Result;
return ExitCodes.ErrorAsync.Result;
}
if (ex.IsFor<InvalidConfigurationException>(out var ice))
{
console.Error.WriteLine(ice!.Print());
return ExitCodes.Error.Result;
return ExitCodes.ErrorAsync.Result;
}
if (_handleErrorDelegate != null)
{
Expand All @@ -192,7 +192,7 @@ private int HandleException(Exception ex, CommandContext? commandContext)

// code not reached but required to compile
// compiler does not realize previous line throws an exception
return ExitCodes.Error.Result;
return ExitCodes.ErrorAsync.Result;
}

public override string ToString()
Expand Down
Loading

0 comments on commit 2565c1d

Please sign in to comment.