예제 #1
0
        /// <summary>
        /// Executes a command based on the parameters passed in by the user
        /// </summary>
        /// <param name="args">String array that is passed in by the user from the command line (exactly the same as args[] passed into the Main function).</param>
        /// <returns>True if the command was executed successfully. Successful execution is defined in your command functions.</returns>
        public int ExecuteCommand(string[] args)
        {
            try
            {
                int CRESULT;
                if (args.Contains("-h") || args.Contains("-?"))
                {
                    return(HelpFunction.Invoke());
                }

                // check if there's a default command
                // and if there is, check if we use the default or another command
                // by checking if there is either:
                // A) There are no args, in which case the default is the only option.
                // B) There are args, but the first one is a switch
                if (hasDefaultCommand && UseDefaultCommand(args))
                {
                    CRESULT = DefaultCommand.ExecuteCommand(args);
                }
                else
                {
                    if (args.Length == 0)
                    {
                        ConsoleLogger.PrintError("No command found.");
                        return(HelpFunction.Invoke());
                    }
                    string cmd = args[0].ToLower();

                    if (!_commands.ContainsKey(cmd))
                    {
                        ConsoleLogger.PrintError("Unknown command \"" + cmd + "\".");
                        return(HelpFunction.Invoke());
                    }

                    string[] switches = new string[args.Length - 1];
                    Array.Copy(args, 1, switches, 0, args.Length - 1);

                    // Cmd is guaranteed to only contain 1 element at this point
                    // Get the first element in cmd where the Command invocation string equals cmd, and execute that command, passing in switches.
                    CRESULT = _commands[cmd].ExecuteCommand(switches);
                }

                if (CRESULT != 0)
                {
                    if (ErrorCodes.ContainsKey(CRESULT))
                    {
                        ConsoleLogger.PrintError(ErrorCodes[CRESULT]);
                    }
                    else
                    {
                        ConsoleLogger.PrintDebug("WARNING: Returning an error code not defined in CommandManager.ErrorCodes: " + CRESULT);
                    }
                }

                return(CRESULT);
            }
            catch (Exception e)
            {
                ConsoleLogger.PrintDebug("FATAL ERROR: " + e.ToString());
                ConsoleLogger.PrintDebug(e.StackTrace);
                return(1);
            }
        }