コード例 #1
0
        public async Task Invoke()
        {
            SubCommandAttribute cmdAttr = this.GetSubCommandAttribute(out TCommandExecutor commandExecutor, out IEnumerator <string> argumentEnumerator);

            if (cmdAttr == null && this.IsHelp())
            {
                this.ShowHelp();
                return;
            }

            //if (cmdAttr == null) {
            //    IEnumerable<string> args = Environment.GetCommandLineArgs().Skip(1);
            //    string strCmd = args.FirstOrDefault();
            //    throw new CommandLineException($"Invalid command: {strCmd}");
            //}

            if (this.IsHelp(cmdAttr))
            {
                this.ShowHelp(cmdAttr);
                return;
            }

            if (cmdAttr != null)
            {
                SubCommand cmd = this.GetSubCommand(commandExecutor, cmdAttr.Type, argumentEnumerator);
                await cmd.Run();
            }
        }
コード例 #2
0
        /// <summary>
        /// Parse options from current command line
        /// </summary>
        /// <returns></returns>
        public SubCommand GetSubCommand(TCommandExecutor parent, Type subCmdType, IEnumerator <string> argumentEnumerator)
        {
            SubCommand cmd = (SubCommand)System.Activator.CreateInstance(subCmdType);

            SubCommand <TCommandExecutor> strongTypedCmd = cmd as SubCommand <TCommandExecutor>;

            if (strongTypedCmd != null)
            {
                strongTypedCmd.Parent = parent;
            }

            //Validate command options class
            this.ValidateArguments();

            var attrs = subCmdType.GetProperties().Where(p => p.GetCustomAttribute <CommandAbstractAttribute>(true) != null)
                        .ToDictionary(p => p, p => p.GetCustomAttribute <CommandAbstractAttribute>(true));

            while (argumentEnumerator.MoveNext())
            {
                if (!attrs.Any(kvp => kvp.Value.TryConsumeArgs(cmd, kvp.Key, argumentEnumerator)))
                {
                    throw new ArgumentException($"Invalid argument '{argumentEnumerator.Current}'");
                }
            }

            return(cmd);
        }