예제 #1
0
        public int Execute(params string[] args)
        {
            CommandLineApplication    command   = this;
            CommandArgumentEnumerator arguments = null;

            if (HandleResponseFiles)
            {
                args = ExpandResponseFiles(args).ToArray();
            }

            for (var index = 0; index < args.Length; index++)
            {
                var arg = args[index];

                bool isLongOption = arg.StartsWith("--");
                if (arg == "-?" || arg == "/?")
                {
                    command.ShowHelp();
                    return(0);
                }
                else if (isLongOption || arg.StartsWith("-"))
                {
                    CommandOption option;

                    var result = ParseOption(isLongOption, command, args, ref index, out option);


                    if (result == ParseOptionResult.ShowHelp)
                    {
                        command.ShowHelp();
                        return(0);
                    }
                    else if (result == ParseOptionResult.ShowVersion)
                    {
                        command.ShowVersion();
                        return(0);
                    }
                    else if (result == ParseOptionResult.UnexpectedArgs)
                    {
                        break;
                    }
                }
                else
                {
                    var subcommand = ParseSubCommand(arg, command);
                    if (subcommand != null)
                    {
                        command = subcommand;
                    }
                    else
                    {
                        if (arguments == null || arguments.CommandName != command.Name)
                        {
                            arguments = new CommandArgumentEnumerator(command.Arguments.GetEnumerator(), command.Name);
                        }

                        if (arguments.MoveNext())
                        {
                            arguments.Current.Values.Add(arg);
                        }
                        else
                        {
                            HandleUnexpectedArg(command, args, index, argTypeName: "command or argument");
                            break;
                        }
                    }
                }
            }

            if (Commands.Count > 0 && command == this)
            {
                throw new CommandParsingException(
                          command,
                          "Required command missing",
                          isRequiredSubCommandMissing: true);
            }

            return(command.Invoke());
        }