Ejemplo n.º 1
0
        private void Execute(List <string> args)
        {
            string commandName = string.Empty;

            if (args.Count >= 1 && Regex.IsMatch(args[0], "^[a-z]+$"))
            {
                commandName = args[0];
                args.RemoveAt(0); // Remove the argument we just used
            }

            // Attempt to find the command for the name
            CommandDescriptor commandDescriptor = commandRegistry.GetDescriptor(commandName, null);

            if (commandDescriptor == null)
            {
                throw new Exception(string.Format("Command '{0}' is not recognized.", commandName));
            }

            // Determine if this is a call for a sub command
            while (args.Count >= 1 && Regex.IsMatch(args[0], "^[a-z]+$"))
            {
                commandName = args[0];
                var subCommandDescriptor = commandRegistry.GetDescriptor(commandName, commandDescriptor);
                if (subCommandDescriptor == null)
                {
                    break;
                }

                commandDescriptor = subCommandDescriptor;
                args.RemoveAt(0); // Remove the argument we just used
            }

            // Create an instance of the required command
            ICommand command = commandFactory.Create(commandDescriptor.CommandType);

            // Parse the arguments and apply them to the command
            if (args.Count > 0)
            {
                foreach (IArgumentParser argumentParser in argumentParsers)
                {
                    argumentParser.Apply(args, command, commandDescriptor);
                }

                // Ensure that all the arguments have been parsed
                if (args.Count > 0)
                {
                    throw new Exception(string.Format("Unsupported argument '{0}'.", args[0]));
                }
            }

            // Execute the code of the command
            command.Execute();
        }