// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= static bool Execute(string command, ClassDefinition cd, IReadOnlyDictionary <string, string> inputArgs, CmdLineConfig config, out object result) { if (config == null) { throw new ArgumentNullException("config"); } var cl = new CmdLineExecutor(cd, new InstanceProvider(Instance)); try { return(cl.Execute(command, inputArgs, out result)); } catch (CmdLineArgException ex) { con.wl(ConsoleColor.Red, "{0}", ex.Message); result = null; return(false); } }
static public int Execute(string[] args, T instance, CmdLineConfig config = null) { if (config == null) { config = new CmdLineConfig(); } Instance = instance; CmdLineParser parser; var cd = new ClassDefinition(typeof(T), config); try { parser = new CmdLineParser(args, config); } catch (CmdLineArgException ex) { con.WriteAppHeader(cd); con.wl(ConsoleColor.Red, "{0}", ex.Message); con.WriteHelp(cd); return(-1); } if (parser.IsHelpCommand) { con.WriteAppHeader(cd); if (parser.IsHelpCommand && parser.Command != null) { con.WriteHelp(cd, parser.Command); } else { con.WriteHelp(cd); } return(0); } var executor = new CmdLineExecutor(cd, new InstanceProvider(Instance)); if (config.RequiresCommand) { if (parser.Command != null) { CmdLineException exception = null; try { if (executor.Execute(parser.Command, parser.Args, out object result)) { return(result != null && result.GetType().IsAssignableFrom(typeof(int)) ? (int)result : 0); } } catch (CmdLineException ex) { exception = ex; } con.WriteAppHeader(cd); if (exception != null) { con.wl(ConsoleColor.Red, "{0}", exception.Message); con.WriteHelp(cd, parser.Command); } else { con.w("Command ").w(ConsoleColor.Red, "{0}", parser.Command).wl(" not found"); con.WriteHelp(cd); } return(-1); // help on command. parser.Args contain unknown parameters } else { // general help } } else if (parser.Command == null) { if (Execute(null, cd, parser.Args, config, out object result)) { return(result != null && result.GetType().IsAssignableFrom(typeof(int)) ? (int)result : 0); } else { // help on command. parser.Args contain unknown parameters } } else { // unknown parameter, no command expected } con.WriteAppHeader(cd); if (parser.IsHelpCommand && parser.Command != null) { con.WriteHelp(cd, parser.Command); } else { con.WriteHelp(cd); } return(0); }