Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add TypeResolver to ExceptionHandler #1325

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions src/Spectre.Console.Cli/CommandApp.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Spectre.Console.Cli.Internal;
using Spectre.Console.Cli.Internal.Configuration;

namespace Spectre.Console.Cli;
Expand All @@ -8,7 +9,7 @@ namespace Spectre.Console.Cli;
public sealed class CommandApp : ICommandApp
{
private readonly Configurator _configurator;
private readonly CommandExecutor _executor;
private readonly CommandExecutorFactory _executorFactory;
private bool _executed;

/// <summary>
Expand All @@ -20,7 +21,7 @@ public CommandApp(ITypeRegistrar? registrar = null)
registrar ??= new DefaultTypeRegistrar();

_configurator = new Configurator(registrar);
_executor = new CommandExecutor(registrar);
_executorFactory = new CommandExecutorFactory(registrar);
}

/// <summary>
Expand Down Expand Up @@ -81,8 +82,9 @@ public async Task<int> RunAsync(IEnumerable<string> args)
_executed = true;
}

return await _executor
.Execute(_configurator, args)
return await _executorFactory
.CreateCommandExecutor(_configurator, args)
.Execute()
.ConfigureAwait(false);
}
catch (Exception ex)
Expand All @@ -102,7 +104,11 @@ public async Task<int> RunAsync(IEnumerable<string> args)

if (_configurator.Settings.ExceptionHandler != null)
{
return _configurator.Settings.ExceptionHandler(ex);
using var resolver = _executorFactory
.CreateCommandExecutor(_configurator, args)
.BuildTypeResolver();

return _configurator.Settings.ExceptionHandler(ex, resolver);
}

// Render the exception.
Expand Down
13 changes: 12 additions & 1 deletion src/Spectre.Console.Cli/ConfiguratorExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ public static IConfigurator SetExceptionHandler(this IConfigurator configurator,
/// <param name="configurator">The configurator.</param>
/// <param name="exceptionHandler">The Action that handles the exception.</param>
/// <returns>A configurator that can be used to configure the application further.</returns>
public static IConfigurator SetExceptionHandler(this IConfigurator configurator, Func<Exception, int>? exceptionHandler)
public static IConfigurator SetExceptionHandler(this IConfigurator configurator, Func<Exception, ITypeResolver, int>? exceptionHandler)
{
if (configurator == null)
{
Expand All @@ -369,4 +369,15 @@ public static IConfigurator SetExceptionHandler(this IConfigurator configurator,
configurator.Settings.ExceptionHandler = exceptionHandler;
return configurator;
}

/// <summary>
/// Sets the ExceptionsHandler.
/// </summary>
/// <param name="configurator">The configurator.</param>
/// <param name="exceptionHandler">The Action that handles the exception.</param>
/// <returns>A configurator that can be used to configure the application further.</returns>
public static IConfigurator SetExceptionHandler(this IConfigurator configurator, Func<Exception, int>? exceptionHandler)
{
return configurator.SetExceptionHandler(exceptionHandler == null ? null : (ex, _) => exceptionHandler(ex));
}
}
2 changes: 1 addition & 1 deletion src/Spectre.Console.Cli/ICommandAppSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,5 +80,5 @@ public interface ICommandAppSettings
/// Gets or sets a handler for Exceptions.
/// <para>This handler will not be called, if <see cref="PropagateExceptions"/> is set to <c>true</c>.</para>
/// </summary>
public Func<Exception, int>? ExceptionHandler { get; set; }
public Func<Exception, ITypeResolver, int>? ExceptionHandler { get; set; }
}
172 changes: 73 additions & 99 deletions src/Spectre.Console.Cli/Internal/CommandExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,119 +4,93 @@ internal sealed class CommandExecutor
{
private readonly ITypeRegistrar _registrar;

public CommandExecutor(ITypeRegistrar registrar)
public IConfiguration Configuration { get; }
public IEnumerable<string> Args { get; }
public bool RequiresVersion { get; internal set; }
public HelpProvider DefaultHelpProvider { get; internal set; }
public CommandTreeParserResult ParsedResult { get; internal set; }
public CommandModel Model { get; internal set; }

public CommandExecutor(
ITypeRegistrar registrar,
IConfiguration configuration,
IEnumerable<string> args,
bool requiresVersion,
HelpProvider? defaultHelpProvider,
CommandTreeParserResult? parsedResult,
CommandModel? model)
{
_registrar = registrar ?? throw new ArgumentNullException(nameof(registrar));
Configuration = configuration;
Args = args;
_registrar.Register(typeof(DefaultPairDeconstructor), typeof(DefaultPairDeconstructor));
}

public async Task<int> Execute(IConfiguration configuration, IEnumerable<string> args)
{
if (configuration == null)
RequiresVersion = requiresVersion;

if (requiresVersion)
{
throw new ArgumentNullException(nameof(configuration));
}

args ??= new List<string>();

_registrar.RegisterInstance(typeof(IConfiguration), configuration);
_registrar.RegisterLazy(typeof(IAnsiConsole), () => configuration.Settings.Console.GetConsole());

// Register the help provider
var defaultHelpProvider = new HelpProvider(configuration.Settings);
_registrar.RegisterInstance(typeof(IHelpProvider), defaultHelpProvider);

// Create the command model.
var model = CommandModelBuilder.Build(configuration);
_registrar.RegisterInstance(typeof(CommandModel), model);
_registrar.RegisterDependencies(model);

return;
}

DefaultHelpProvider = defaultHelpProvider ?? throw new ArgumentNullException(nameof(defaultHelpProvider));
ParsedResult = parsedResult ?? throw new ArgumentNullException(nameof(parsedResult));
Model = model ?? throw new ArgumentNullException(nameof(model));
}

public async Task<int> Execute()
{
// Asking for version? Kind of a hack, but it's alright.
// We should probably make this a bit better in the future.
if (args.Contains("-v") || args.Contains("--version"))
if (RequiresVersion)
{
var console = configuration.Settings.Console.GetConsole();
console.WriteLine(ResolveApplicationVersion(configuration));
var console = Configuration.Settings.Console.GetConsole();
console.WriteLine(ResolveApplicationVersion(Configuration));
return 0;
}

// Parse and map the model against the arguments.
var parsedResult = ParseCommandLineArguments(model, configuration.Settings, args);

// Register the arguments with the container.
_registrar.RegisterInstance(typeof(CommandTreeParserResult), parsedResult);
_registrar.RegisterInstance(typeof(IRemainingArguments), parsedResult.Remaining);

// Create the resolver.
using (var resolver = new TypeResolverAdapter(_registrar.Build()))
{
// Get the registered help provider, falling back to the default provider
// registered above if no custom implementations have been registered.
var helpProvider = resolver.Resolve(typeof(IHelpProvider)) as IHelpProvider ?? defaultHelpProvider;

// Currently the root?
if (parsedResult?.Tree == null)
{
// Display help.
configuration.Settings.Console.SafeRender(helpProvider.Write(model, null));
return 0;
}

// Get the command to execute.
var leaf = parsedResult.Tree.GetLeafCommand();
if (leaf.Command.IsBranch || leaf.ShowHelp)
{
// Branches can't be executed. Show help.
configuration.Settings.Console.SafeRender(helpProvider.Write(model, leaf.Command));
return leaf.ShowHelp ? 0 : 1;
}

// Is this the default and is it called without arguments when there are required arguments?
if (leaf.Command.IsDefaultCommand && args.Count() == 0 && leaf.Command.Parameters.Any(p => p.Required))
{
// Display help for default command.
configuration.Settings.Console.SafeRender(helpProvider.Write(model, leaf.Command));
return 1;
}

// Create the content.
var context = new CommandContext(parsedResult.Remaining, leaf.Command.Name, leaf.Command.Data);

// Execute the command tree.
return await Execute(leaf, parsedResult.Tree, context, resolver, configuration).ConfigureAwait(false);
using var resolver = new TypeResolverAdapter(_registrar.Build());

// Get the registered help provider, falling back to the default provider
// registered above if no custom implementations have been registered.
var helpProvider = resolver.Resolve(typeof(IHelpProvider)) as IHelpProvider ?? DefaultHelpProvider;

// Currently the root?
if (ParsedResult?.Tree == null)
{
// Display help.
Configuration.Settings.Console.SafeRender(helpProvider.Write(Model, null));
return 0;
}

// Get the command to execute.
var leaf = ParsedResult.Tree.GetLeafCommand();
if (leaf.Command.IsBranch || leaf.ShowHelp)
{
// Branches can't be executed. Show help.
Configuration.Settings.Console.SafeRender(helpProvider.Write(Model, leaf.Command));
return leaf.ShowHelp ? 0 : 1;
}

// Is this the default and is it called without arguments when there are required arguments?
if (leaf.Command.IsDefaultCommand && Args.Count() == 0 && leaf.Command.Parameters.Any(p => p.Required))
{
// Display help for default command.
Configuration.Settings.Console.SafeRender(helpProvider.Write(Model, leaf.Command));
return 1;
}

// Create the content.
var context = new CommandContext(ParsedResult.Remaining, leaf.Command.Name, leaf.Command.Data);

// Execute the command tree.
return await Execute(leaf, ParsedResult.Tree, context, resolver, Configuration).ConfigureAwait(false);
}

public TypeResolverAdapter BuildTypeResolver()
{
return new TypeResolverAdapter(_registrar.Build());
}

#pragma warning disable CS8603 // Possible null reference return.
private CommandTreeParserResult ParseCommandLineArguments(CommandModel model, CommandAppSettings settings, IEnumerable<string> args)
{
var parser = new CommandTreeParser(model, settings.CaseSensitivity, settings.ParsingMode, settings.ConvertFlagsToRemainingArguments);

var parserContext = new CommandTreeParserContext(args, settings.ParsingMode);
var tokenizerResult = CommandTreeTokenizer.Tokenize(args);
var parsedResult = parser.Parse(parserContext, tokenizerResult);

var lastParsedLeaf = parsedResult?.Tree?.GetLeafCommand();
var lastParsedCommand = lastParsedLeaf?.Command;
if (lastParsedLeaf != null && lastParsedCommand != null &&
lastParsedCommand.IsBranch && !lastParsedLeaf.ShowHelp &&
lastParsedCommand.DefaultCommand != null)
{
// Insert this branch's default command into the command line
// arguments and try again to see if it will parse.
var argsWithDefaultCommand = new List<string>(args);

argsWithDefaultCommand.Insert(tokenizerResult.Tokens.Position, lastParsedCommand.DefaultCommand.Name);

parserContext = new CommandTreeParserContext(argsWithDefaultCommand, settings.ParsingMode);
tokenizerResult = CommandTreeTokenizer.Tokenize(argsWithDefaultCommand);
parsedResult = parser.Parse(parserContext, tokenizerResult);
}

return parsedResult;
}
#pragma warning restore CS8603 // Possible null reference return.

private static string ResolveApplicationVersion(IConfiguration configuration)
{
return
Expand Down
97 changes: 97 additions & 0 deletions src/Spectre.Console.Cli/Internal/CommandExecutorFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
namespace Spectre.Console.Cli.Internal;

internal class CommandExecutorFactory
{
private ITypeRegistrar _registrar;

public CommandExecutorFactory(ITypeRegistrar registrar)
{
_registrar = registrar ?? throw new ArgumentNullException(nameof(registrar));
}

public CommandExecutor CreateCommandExecutor(IConfiguration configuration, IEnumerable<string> args)
{
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}

args ??= new List<string>();

// Asking for version? Kind of a hack, but it's alright.
// We should probably make this a bit better in the future.
if (args.Contains("-v") || args.Contains("--version"))
{
return new CommandExecutor(
registrar: _registrar,
configuration: configuration,
args: args,
requiresVersion: true,
defaultHelpProvider: null,
parsedResult: null,
model: null);
}

_registrar.Register(typeof(DefaultPairDeconstructor), typeof(DefaultPairDeconstructor));
_registrar.RegisterInstance(typeof(IConfiguration), configuration);
_registrar.RegisterLazy(typeof(IAnsiConsole), () => configuration.Settings.Console.GetConsole());

// Register the help provider
var defaultHelpProvider = new HelpProvider(configuration.Settings);
_registrar.RegisterInstance(typeof(IHelpProvider), defaultHelpProvider);

// Create the command model.
var model = CommandModelBuilder.Build(configuration);
_registrar.RegisterInstance(typeof(CommandModel), model);
_registrar.RegisterDependencies(model);

// Parse and map the model against the arguments.
var parsedResult = ParseCommandLineArguments(model, configuration.Settings, args);

// Register the arguments with the container.
_registrar.RegisterInstance(typeof(CommandTreeParserResult), parsedResult);
_registrar.RegisterInstance(typeof(IRemainingArguments), parsedResult.Remaining);

return new CommandExecutor(
registrar: _registrar,
configuration: configuration,
args: args,
requiresVersion: false,
defaultHelpProvider: defaultHelpProvider,
parsedResult: parsedResult,
model: model
);
}

#pragma warning disable CS8603 // Possible null reference return.

private CommandTreeParserResult ParseCommandLineArguments(CommandModel model, CommandAppSettings settings, IEnumerable<string> args)
{
var parser = new CommandTreeParser(model, settings.CaseSensitivity, settings.ParsingMode, settings.ConvertFlagsToRemainingArguments);

var parserContext = new CommandTreeParserContext(args, settings.ParsingMode);
var tokenizerResult = CommandTreeTokenizer.Tokenize(args);
var parsedResult = parser.Parse(parserContext, tokenizerResult);

var lastParsedLeaf = parsedResult?.Tree?.GetLeafCommand();
var lastParsedCommand = lastParsedLeaf?.Command;
if (lastParsedLeaf != null && lastParsedCommand != null &&
lastParsedCommand.IsBranch && !lastParsedLeaf.ShowHelp &&
lastParsedCommand.DefaultCommand != null)
{
// Insert this branch's default command into the command line
// arguments and try again to see if it will parse.
var argsWithDefaultCommand = new List<string>(args);

argsWithDefaultCommand.Insert(tokenizerResult.Tokens.Position, lastParsedCommand.DefaultCommand.Name);

parserContext = new CommandTreeParserContext(argsWithDefaultCommand, settings.ParsingMode);
tokenizerResult = CommandTreeTokenizer.Tokenize(argsWithDefaultCommand);
parsedResult = parser.Parse(parserContext, tokenizerResult);
}

return parsedResult;
}

#pragma warning restore CS8603 // Possible null reference return.
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ internal sealed class CommandAppSettings : ICommandAppSettings
public ParsingMode ParsingMode =>
StrictParsing ? ParsingMode.Strict : ParsingMode.Relaxed;

public Func<Exception, int>? ExceptionHandler { get; set; }
public Func<Exception, ITypeResolver, int>? ExceptionHandler { get; set; }

public CommandAppSettings(ITypeRegistrar registrar)
{
Expand Down