コード例 #1
0
        private async Task ExecuteMiddlewareAsync(CommandContext context, IArgumentParser argumentParser, Action <MariCommandsOptions> config = null)
        {
            var services = new ServiceCollection();

            services.AddLogging();

            services.AddOptions <MariCommandsOptions>();

            if (config.HasContent())
            {
                services.Configure(config);
            }

            services.AddSingleton <IArgumentParser>(argumentParser);

            var provider = services.BuildServiceProvider(true);

            context.ServiceScopeFactory = provider.GetRequiredService <IServiceScopeFactory>();

            var app = new TestCommandApplicationBuilder(provider);

            app.UseParser();

            var commandDelegate = app.Build();

            await commandDelegate(context);
        }
コード例 #2
0
ファイル: AdminProcessing.cs プロジェクト: ImVogl/PRGTrainer
        /// <summary>
        /// Инициализирует новый экземпляр <see cref="AdminProcessing"/>
        /// </summary>
        /// <param name="telegramBotClient">Клиент телеграмма.</param>
        /// <param name="adminController">Контроллер состояния пользователя.</param>
        /// <param name="adminHandler">Обработчик действий администратора.</param>
        /// <param name="argumentParser">Парсер аргументов.</param>
        public AdminProcessing(
            ITelegramBotClient telegramBotClient,
            IAdminController adminController,
            IAdminHandler adminHandler,
            IArgumentParser argumentParser)
        {
            _telegramBotClient   = telegramBotClient;
            _testStateController = adminController;
            _adminHandler        = adminHandler;
            _argumentParser      = argumentParser;
            _outputFileTypes     = new Dictionary <int, StatisticOutputFileType>();

            _defaultMessage = string.Format(
                @"{0} - Получение статистики по вопросам.{1}{2} - Получение статистики по пользователям.{1}" +
                @"Вспомогательный ключ:{1}" +
                @"{5} - тип файла со статистикой (txt - текстовый, {7} - изображение, по-умолчанию txt).{1}{1}" +
                @"Для статистики по пользователям существуют дополнительные ключи:{1}" +
                @"{3}{4} - пользователи, для которых нужно отобразить статистику (по-умолчанию все пользователи).{1}" +
                @"{3}{6} - дата, начиная с которой стоит выдать статистику (по-умолчанию за все время.){1}{1}" +
                @"Пример: {2} {4}:User1, @User2 {5}:{7} {6}:20.01.2018",
                QuestionStatisticKey,
                Environment.NewLine,
                UserStatisticKey,
                "\t\t",
                UsersKey.TrimEnd(':'),
                OutTypeKey.TrimEnd(':'),
                StartDateKey.TrimEnd(':'),
                OutTypeImg);
        }
コード例 #3
0
 public InputConverter(IArgumentParser argumentParser, ArabicToRomanConverter arabicToRomanConverter,
                       RomanToArabicConverter romanToArabicConverter)
 {
     _argumentParser         = argumentParser;
     _arabicToRomanConverter = arabicToRomanConverter;
     _romanToArabicConverter = romanToArabicConverter;
 }
コード例 #4
0
        protected void ShouldHandle(string value, IArgumentParser parser)
        {
            var symbol = A.Fake <IArgumentSymbol>();

            A.CallTo(() => symbol.Source).Returns(value);
            Assert.IsTrue(parser.ShouldHandle(symbol));
        }
コード例 #5
0
ファイル: Dispatcher.cs プロジェクト: developernotes/nu
 public Dispatcher(IArgumentParser argumentParser, IArgumentMapFactory argumentMapFactory,
     IConsole console)
 {
     _argumentParser = argumentParser;
     _console = console;
     _argumentMapFactory = argumentMapFactory;
 }
コード例 #6
0
ファイル: Program.cs プロジェクト: codingkids/sievo
 /// <summary>
 /// App Initialization.
 /// </summary>
 private static void ApplicationIntialization()
 {
     StartupHandler.AddConsolelogging();
     _logger          = _serviceProvider.GetLogger <Program>();
     _argumentsParser = _serviceProvider.GetService <IArgumentParser>();
     _dataProvider    = _serviceProvider.GetService <IDataProvider>();
 }
コード例 #7
0
        protected byte[] GetBytes(string value, IArgumentParser parser)
        {
            var symbol = A.Fake <IArgumentSymbol>();

            A.CallTo(() => symbol.Source).Returns(value);
            return(parser.GetBytes(symbol));
        }
コード例 #8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CakeApplication"/> class.
        /// </summary>
        /// <param name="log">The log.</param>
        /// <param name="commandFactory">The command factory.</param>
        /// <param name="argumentParser">The argument parser.</param>
        /// <param name="console">The console.</param>
        public CakeApplication(
            IVerbosityAwareLog log,
            ICommandFactory commandFactory,
            IArgumentParser argumentParser,
            IConsole console)
        {
            if (log == null)
            {
                throw new ArgumentNullException("log");
            }
            if (commandFactory == null)
            {
                throw new ArgumentNullException("commandFactory");
            }
            if (argumentParser == null)
            {
                throw new ArgumentNullException("argumentParser");
            }
            if (console == null)
            {
                throw new ArgumentNullException("console");
            }

            _log            = log;
            _commandFactory = commandFactory;
            _argumentParser = argumentParser;
            _console        = console;
        }
コード例 #9
0
        private void ReflectCommandLineType()
        {
            // get fields
            foreach (FieldInfo field in typeof(T).GetFields())
            {
                ArgumentAttribute attribute = GetAttribute(field);
                if (attribute == null)
                {
                    continue;
                }
                IArgumentParser parser = ArgumentParserFactory.Create(field, attribute);
                if (parser == null)
                {
                    throw new ArgumentException("Could not reflect " + field.Name);
                }
                this.ArgumentParsers.Add(parser);
            }

            foreach (PropertyInfo property in typeof(T).GetProperties())
            {
                ArgumentAttribute attribute = GetAttribute(property);
                if (attribute == null)
                {
                    continue;
                }
                IArgumentParser parser = ArgumentParserFactory.Create(property, attribute);
                if (parser == null)
                {
                    throw new ArgumentException("Could not reflect " + property.Name);
                }
                this.ArgumentParsers.Add(parser);
            }
        }
コード例 #10
0
 public ProximitySearchService(IArgumentParser argumentParser,
                               IFileParser fileParser,
                               IProximitySearchCalculator proximitySearchCalculator)
 {
     _argumentParser            = argumentParser;
     _fileParser                = fileParser;
     _proximitySearchCalculator = proximitySearchCalculator;
 }
コード例 #11
0
ファイル: Program.cs プロジェクト: watermelonpizza/argparse
 static void SetupConfigCommand(IArgumentParser argParser)
 {
     argParser
     .CreateArgumentCatagory <ConfigCommands>()
     .Name("Options")
     .WithArgument(x => x.Basic)
     .Help("THis is sub help for this command");
 }
コード例 #12
0
ファイル: Program_UT.cs プロジェクト: haled/XSqlClient
 public ProgramTests()
 {
     _mockArgParser = new MockArgumentParser();
       _mockRunner = new MockRunner();
       _mockSqlResult = new MockSqlResult();
       ((MockSqlResult)_mockSqlResult).ExpectedTextOutput = "formatted text";
       _testProgram = new Program(_mockArgParser, _mockRunner);
 }
コード例 #13
0
ファイル: CommandExecutor.cs プロジェクト: ArildF/linqtwit
        public CommandExecutor(IServiceLocator locator, IArgumentParser parser, ICommandUIService commandUIService)
        {
            this._locator = locator;
            _parser = parser;
            _commandUIService = commandUIService;

            this._commands = this._locator.GetAllInstances<ICommand>().ToDictionary(
                c => c.GetType().FullName.ToLowerInvariant());
        }
コード例 #14
0
 /// <summary>
 /// use customized <see cref="IArgumentParser"/>.
 /// lifetime of parser should be <see cref="ServiceLifetime.Transient"/>.
 /// </summary>
 /// <param name="parser"></param>
 /// <returns></returns>
 public EngineBuilder Use([NotNull] IArgumentParser parser)
 {
     if (parser == null)
     {
         throw new ArgumentNullException(nameof(parser));
     }
     this._services.AddSingleton(parser);
     return(this);
 }
コード例 #15
0
 public Processor(
     IArgumentParser parser,
     IOutputFormatter formatter,
     IOutput output)
 {
     _parser    = parser;
     _formatter = formatter;
     _output    = output;
 }
コード例 #16
0
        public void SetUp()
        {
            var sp = ConfigureServices(services =>
            {
                services.AddSingleton <IArgumentParser, ArgumentParser>();
            });

            argumentParser = sp.GetService <IArgumentParser>();
        }
コード例 #17
0
        public ArgumentHandler(IArgumentParser argumentParser, IConfigFileParser configFileParser, IFileSystem fileSystem)
        {
            Guard.AgainstNullArgument("argumentParser", argumentParser);
            Guard.AgainstNullArgument("configFileParser", configFileParser);
            Guard.AgainstNullArgument("fileSystem", fileSystem);

            _fileSystem       = fileSystem;
            _argumentParser   = argumentParser;
            _configFileParser = configFileParser;
        }
コード例 #18
0
 public CommandExecutor(IConsole console, IConfigHandler configHandler, IFileSystem fileSystem, IConfig defaultConfig, IArgumentParser argumentHandler, ILinker linker, IPathResolver pathResolver)
 {
     this.console         = console;
     this.configHandler   = configHandler;
     this.fileSystem      = fileSystem;
     this.defaultConfig   = defaultConfig;
     this.argumentHandler = argumentHandler;
     this.linker          = linker;
     this.pathResolver    = pathResolver;
 }
コード例 #19
0
        public ArgumentHandler(IArgumentParser argumentParser, IConfigFileParser configFileParser, IFileSystem fileSystem)
        {
            Guard.AgainstNullArgument("argumentParser", argumentParser);
            Guard.AgainstNullArgument("configFileParser", configFileParser);
            Guard.AgainstNullArgument("fileSystem", fileSystem);

            _fileSystem = fileSystem;
            _argumentParser = argumentParser;
            _configFileParser = configFileParser;
        }
コード例 #20
0
        public void SetUp()
        {
            var sp = ConfigureServices(services =>
            {
                services.AddSingleton <IArgumentParser, ArgumentParser>();
                services.AddSingleton <IGlobbingResolver, GlobbingResolver>();
            });

            environment    = sp.GetService <IEnvironment>();
            argumentParser = sp.GetService <IArgumentParser>();
        }
コード例 #21
0
        public void SetUp()
        {
            var sp = ConfigureServices(services =>
            {
                services.AddSingleton <IArgumentParser, ArgumentParser>();
                services.AddSingleton <IGlobbingResolver, GlobbingResolver>();
                services.AddSingleton <ICurrentBuildAgent, MockBuildAgent>();
            });

            argumentParser = sp.GetService <IArgumentParser>();
        }
コード例 #22
0
        public CommandLineProcessor(ILogger logger, IArgumentParser parser, string[] args)
        {
            _logger = logger;
            _logger.Info("Assigning Parser");
            _parser    = parser;
            _arguments = args;

            _logger.Info("Validations");
            Validate(_logger, "logger");
            Validate(_parser, "parser");
        }
コード例 #23
0
ファイル: ArgumentParser_UT.cs プロジェクト: haled/XSqlClient
 public ArgumentParserTests()
 {
     _desiredArgs = new Dictionary<string,string>
       {
     {"-s", "server"},
     {"-d", "database"},
     {"-u", "user"},
     {"-p", "password"},
     {"-q", "query"},
       };
       _testArgs = CreateTestArgs();
       _testArgParser = new ArgumentParser(_desiredArgs);
 }
コード例 #24
0
 public PicklerApplication(
     IArgumentParser argumentParser,
     IFileLoader fileLoader,
     IFeatureExtractor featureExtractor,
     ITrxResultsParser trxResultsParser,
     IResultRenderer resultRenderer)
 {
     _argumentParser   = argumentParser;
     _fileLoader       = fileLoader;
     _featureExtractor = featureExtractor;
     _trxResultsParser = trxResultsParser;
     _resultRenderer   = resultRenderer;
 }
コード例 #25
0
 public CommandLineInterface(
     IArgumentParser argumentParser,
     IConsoleReader consoleReader,
     IPackageManager packageManager,
     IEnvironment environment,
     IHelpScreenGenerator helpScreenGenerator)
 {
     _argumentParser      = argumentParser ?? throw new ArgumentNullException(nameof(argumentParser));
     _consoleReader       = consoleReader ?? throw new ArgumentNullException(nameof(consoleReader));
     _packageManager      = packageManager ?? throw new ArgumentNullException(nameof(packageManager));
     _environment         = environment ?? throw new ArgumentNullException(nameof(environment));
     _helpScreenGenerator = helpScreenGenerator ?? throw new ArgumentNullException(nameof(helpScreenGenerator));
 }
コード例 #26
0
 public CommandLineExecutor(IArgumentParser argumentParser, ITempestRunner runner)
 {
     if (argumentParser == null)
     {
         throw new ArgumentNullException(nameof(argumentParser));
     }
     if (runner == null)
     {
         throw new ArgumentNullException(nameof(runner));
     }
     _argumentParser = argumentParser;
     _runner         = runner;
 }
コード例 #27
0
        public void SeedAssembly(Assembly a)
        {
            if (parsers.Count != 0)
            {
                return;
            }

            Type[] types = a.GetTypes()
                           .Where(x => x.IsClass && typeof(IArgumentParser).IsAssignableFrom(x))
                           .ToArray();

            foreach (var t in types)
            {
                IArgumentParser p = (IArgumentParser)Activator.CreateInstance(t);
                parsers.Add(p);
            }
        }
コード例 #28
0
        // Invokes the parser on the context arguments
        private static ContextResult InvokeParser(TOptions options,
                                                  ParseContext parseContext,
                                                  ContextResult result,
                                                  IArgumentParser <TOptions> parser)
        {
            while (parseContext.Ready)
            {
                var state = parseContext.Count;
                result |= parser.ProcessContext(options, parseContext);

                if (state != parseContext.Count && !parser.MultiValued)
                {
                    break;
                }
            }

            return(result);
        }
コード例 #29
0
        internal void Execute(IConsole console, IArgumentParser argumentHandler, ICommandExecutor commandExecutor)
        {
            bool finished = false;

            while (!finished)
            {
                console.Write("> ");
                string input = console.ReadLine().Trim();

                if (input.ToLower().Equals("exit"))
                {
                    finished = true;
                }
                else
                {
                    commandExecutor.Execute(argumentHandler.ParseStringToArguments(input));
                }
            }
        }
コード例 #30
0
ファイル: Runner_UT.cs プロジェクト: haled/XSqlClient
 public RunnerTests()
 {
     _mockArgParser = new MockArgumentParser();
       _testRunner = new Runner();
 }
コード例 #31
0
 public void SetUp()
 {
     argumentParser = new ArgumentParser(new TestEnvironment());
 }
コード例 #32
0
 public void SetUp()
 {
     _argumentValueMapper = MockRepository.GenerateMock <IArgumentValueMapper>();
     _testObject          = new ArgumentParser(_argumentValueMapper);
 }
コード例 #33
0
 public void SetUp()
 {
     argumentParser = new ArgumentParser();
 }
コード例 #34
0
 /// <summary>
 /// Adds an argument parser instance capable of parsing a specific type.
 /// </summary>
 /// <param name="argumentParser"></param>
 /// <typeparam name="T"></typeparam>
 public void AddArgumentParser <T>(IArgumentParser <T> argumentParser)
 {
     _parsers.Add(typeof(T), argumentParser);
 }
コード例 #35
0
 public CommandLineArgumentParser(ICommandLineInputProvider inputProvider, IArgumentParser argumentParser)
 {
     this.inputProvider  = inputProvider;
     this.argumentParser = argumentParser;
 }
コード例 #36
0
 public CommandDispatcher(IArgumentParser argumentParser)
 {
     ArgumentParser = argumentParser;
 }
コード例 #37
0
ファイル: Program.cs プロジェクト: haled/XSqlClient
 public Program(IArgumentParser argParser, IRunner runner)
 {
     _argumentParser = argParser;
       _runner = runner;
 }
コード例 #38
0
 public void SetUp()
 {
     _argumentValueMapper = MockRepository.GenerateMock<IArgumentValueMapper>();
     _testObject = new ArgumentParser(_argumentValueMapper);
 }
コード例 #39
0
 protected ArgumentDrivenAppflow(IArgumentParser argumentParser, string[] arguments)
     : base(arguments)
 {
 }