Ejemplo n.º 1
0
        private ParseRun CreateRun(IReadOnlyList<string> tokens)
        {
            var run = new ParseRun();

            Command currentCommand = RootCommand;

            //Go through the tokens and find all the subcommands and their arguments and options.
            for (int i = 0; i < tokens.Count; i++)
            {
                string token = tokens[i];

                run.Options.AddRange(currentCommand.Options.Select(o => new OptionRun(o, currentCommand)));

                //Check if subcommand exists under the current command with the token as a name.
                Command subcommand = currentCommand.Commands[token];

                if (subcommand != null)
                {
                    //Add the command and move to the next command level.
                    run.Commands.Add(subcommand);
                    currentCommand = subcommand;
                } else
                {
                    //Only add the arguments from the current command to the run if a subcommand is not specified.
                    //Arguments from the innermost command can only be used for a run. If arguments
                    //from different levels of commands are used, then the correct order of the commands is ambiguous.
                    foreach (Argument argument in currentCommand.Arguments)
                        run.Arguments.Add(new ArgumentRun(argument));

                    //All tokens from the current token are considered the args for the command.
                    run.Tokens = new List<string>(tokens.Count - i + 1);
                    for (int j = i; j < tokens.Count; j++)
                        run.Tokens.Add(tokens[j]);

                    //We're done with subcommands. Break out of this look.
                    break;
                }
            }

            if (run.Tokens == null)
                run.Tokens = new List<string>(0);
            return run;
        }
Ejemplo n.º 2
0
        private static ParseResult CreateParseResult(ParseRun run)
        {
            Command finalCommand = run.Commands.Count > 0 ? run.Commands[run.Commands.Count - 1] : null;
            List<string> arguments = run.Arguments
                .Select(ar => ar.Value)
                .ToList();
            Dictionary<string, object> options = run.Options
                .Where(option => option.Command.Name == null)
                .ToDictionary(rootOptionRun => rootOptionRun.Option.Name, rootOptionRun => rootOptionRun.ResolvedValue);
            foreach (Command command in run.Commands)
            {
                IEnumerable<OptionRun> commandOptionRuns = run.Options.Where(option => option.Command == command);
                foreach (OptionRun commandOptionRun in commandOptionRuns)
                    options.Add(commandOptionRun.Option.Name, commandOptionRun.ResolvedValue);
            }

            return new ParseResult(finalCommand, arguments, options);
        }