Beispiel #1
0
        public string[] Parse(string[] args)
        {
            var stack = new Stack<string>(args.Reverse());
            while (stack.Count > 0)
            {
                var option = stack.Pop();
            
                //the rest should be passed back.
                if (option == "--")
                    break;

                //not an option so push it back onto the stack and give up
                if ((option[0] != '/') && (option[0] != '-'))
                {
                    stack.Push(option);
                    break;
                }

                //remove extra dash for long form
                option = option.Substring(1);
                if (option[0] == '-')
                    option = option.Substring(1);

                //if we have an equals sign, break it up
                if (option.Contains('='))
                {
                    var values = option.Split(new[] {'='}, 2);
                    option = values[0];
                    stack.Push(values[1]);
                }

                var match = this.Where(o => o.LongForm == option || o.ShortForm == option).FirstOrDefault();
                if (match == null)
                {
                    //cant execute the option so put it back.
                    stack.Push(option);
                    break;
                }

                //we are going to execute it
                if (match.RequiresParam)
                {
                    //cant execute the option because we dont have a param supplied
                    if (stack.Count == 0)
                        throw new MissingOptionParameterException(match);

                    match.ActionWithParam(stack.Pop());
                }
                else
                {
                    match.Action();
                }

                match.Found = true;
            }

            var notFound = this.FirstOrDefault(o => o.Required && !o.Found);
            if(notFound != null)
                throw new MissingOptionException(notFound);

            return stack.Reverse().ToArray();
        }