private CommandRunData GetCommandRunData(ConsoleCommandInfo info, string[] args, OptionSet options) { IConsoleCommand command; try { command = info.Instance ?? (IConsoleCommand)info.CommandType.Resolve(); } catch (Exception e) { e.SetContext("commandInfo", info); throw; } var errors = new List <string>(); var commandArgs = new Dictionary <Arg, object>(); var validators = new List <IValidatable> { command }; var setterUppers = new List <ISetupAndCleanup>(); command.As <ISetupAndCleanup>(setterUppers.Add); LoadArgs(options, validators, setterUppers, command, commandArgs); bool showHelp = false; if (options != null) { options.Add(HelpCommand.Prototype, "show this message and exit", a => showHelp = true); try { command.ExtraArgs = options.Parse(args.Skip(1)); if (showHelp) { return(new CommandRunData { Command = HelpCommand.ForCommand(info, command) }); } } catch (Exception e) { Log.Error(e.Dump()); errors = new List <string> { e.Message }; } } errors.AddRange(validators.OrderBy(v => v is IConsoleCommand) .SelectMany(v => v.GetArgValidationErrors())); errors.AddRange(from arg in commandArgs where arg.Key.ArgAttribute.Required let value = arg.Key.PropertyInfo.GetValue(arg.Value, null) where value == null select arg.Key.ArgAttribute.FirstPrototype + " is required"); if (errors.Count > 0) { return(new CommandRunData { Command = HelpCommand.ForCommand(info, command), Errors = errors }); } return(new CommandRunData { Command = command, SetterUppers = setterUppers }); }
public CommandRunData LoadCommand(string[] args) { var optionPrefixes = new[] { '/', '-' }; ConsoleCommandInfo info = null; if (args.IsNullOrEmpty() || string.IsNullOrEmpty(args[0])) { CommandsByType.TryGetValue(Config.DefaultCommand, out info); if (info != null) { args = new[] { info.Attribute.FirstPrototype }.Union(args).ToArray(); } } var commandName = args[0].Trim(); if (optionPrefixes.Any(p => p == commandName[0])) { //did the user type /help first? if (CommandsByName.TryGetValue(commandName.Substring(1), out info) && info == CommandsByType[typeof(HelpCommand)]) { commandName = commandName.TrimStart(optionPrefixes); } else { CommandsByType.TryGetValue(Config.DefaultCommand, out info); if (info != null) { args = new[] { info.Attribute.FirstPrototype }.Union(args).ToArray(); } } } var options = new OptionSet(); if (info != null || CommandsByName.TryGetValue(commandName, out info)) { if (info.CommandType == typeof(HelpCommand)) { ConsoleCommandInfo infoForHelp; if (args.Length > 1 && CommandsByName.TryGetValue(args[1].TrimStart(optionPrefixes), out infoForHelp)) { var instance = (IConsoleCommand)infoForHelp.CommandType.Resolve(); return(new CommandRunData { Command = HelpCommand.ForCommand(infoForHelp, instance) }); } return(new CommandRunData { Command = HelpCommand.ForCommands(Commands) }); } return(GetCommandRunData(info, args, options)); } Writer.WriteLine("Unknown command: " + commandName); return(new CommandRunData { Command = HelpCommand.ForCommands(Commands) }); }