public void OptionAndOptionWithArgument()
        {
            String[] args = new String[] {
                "-p",
                "-attr",
                "p"
            };

            ICommandLine cl = parser.Parse(options, args);

            Assert.IsTrue(cl.HasOption("p"), "Confirm -p is set");
            Assert.IsTrue(cl.HasOption("attr"), "Confirm -attr is set");
            Assert.IsTrue(cl.GetOptionValue("attr").Value.Equals("p"), "Confirm arg of -attr");
            Assert.IsTrue(!cl.Arguments.Any(), "Confirm all arguments recognized");
        }
Example #2
0
        public bool Run(string[] args)
        {
            try
            {
                var result = _commandLineParser.Parse(args);
                if (result != null)
                {
                    _buildLogProcessor.Proces(
                        result.InputFile,
                        result.OutputFile,
                        result.CloneRoot,
                        result.Owner,
                        result.Repo,
                        result.Hash,
                        result.ConfigurationFile);
                    return(true);
                }

                return(false);
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.ToString());
                return(false);
            }
        }
Example #3
0
        public IReadOnlyList <StyledSpan <TextStyle> > Highlight(string commandLine)
        {
            if (commandLine == null)
            {
                throw new ArgumentNullException(nameof(commandLine));
            }

            if (commandLine.Length == 0)
            {
                return(Array.Empty <StyledSpan <TextStyle> >());
            }

            if (String.IsNullOrWhiteSpace(commandLine))
            {
                return(GetDefaultForAll(commandLine));
            }

            var syntax = _parser.Parse(commandLine);

            var highlights    = new List <StyledSpan <TextStyle> >();
            var visitorParams = new CommandLineHighlightingVisitorParams <TextStyle>(
                highlights, _highlightingOptions.Palette);

            syntax.Accept(_highlightingVisitor, visitorParams);

            return(highlights);
        }
Example #4
0
        public static object ParseObject(this ICommandLineParser parser, Type type, Options options, string[] args, bool stopAtNotOption)
        {
            var commandLine = parser.Parse(options, args, stopAtNotOption);
            var obj         = Activator.CreateInstance(type, true);

            ReflectedOptions.SetToObject(options, commandLine, obj);
            return(obj);
        }
        public Task <string> GetInitialProjectLocationAsync()
        {
            var commandLineContext = new CommandLineContext();

            _commandLineParser.Parse(_commandLineService.GetCommandLine(), commandLineContext);

            return(Task.FromResult(commandLineContext.InitialFile));
        }
        public async Task <string> GetInitialProjectLocationAsync()
        {
            var commandLineContext = new CommandLineContext();

            _commandLineParser.Parse(_startUpInfoProvider.Arguments, commandLineContext);

            return(commandLineContext.InitialFile);
        }
Example #7
0
        public static IValidationContext Parse(this ICommandLineParser commandLineParser, string commandLineArguments, IContext targetContext)
        {
            Argument.IsNotNull(() => commandLineParser);

            var splitted = _regex.Matches(commandLineArguments).Cast <Match>()
                           .Select(m => m.Value)
                           .ToList();

            return(commandLineParser.Parse(splitted, targetContext));
        }
Example #8
0
        public async Task ExecuteAsync <TContext>(string commandLineString, TContext context, CancellationToken cancellationToken)
        {
            if (commandLineString.IsNullOrEmpty())
            {
                throw DynamicException.Create("CommandLineNullOrEmpty", "You need to specify at least one command.");
            }

            var commandLines = _commandLineParser.Parse(commandLineString);

            await ExecuteAsync(commandLines, context, cancellationToken);
        }
Example #9
0
        public void HandleCommandLine(string [] args, ICommandLineParser parser)
        {
            if (parser == null)
            {
                throw new ArgumentNullException("parser");
            }

            Initialize();

            parser.Options = appOptions;
            CommandLine commandLine = parser.Parse(args);

            if (commandLine.HasParsed)
            {
                HandleCommandLine(commandLine);
            }
        }
Example #10
0
        public bool Run(string[] args)
        {
            try
            {
                var result = _commandLineParser.Parse(args);
                if (result != null)
                {
                    return(_submissionService.SubmitAsync(result.InputFile, result.Token, result.HeadSha).Result);
                }

                return(false);
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.ToString());
                return(false);
            }
        }
Example #11
0
        public void Run()
        {
            var result = parser.Parse(options);

            if (!result.Valid)
            {
                Console.WriteLine(result.InputValue);
                Console.WriteLine(result.HelpText);
                return;
            }

            Console.CancelKeyPress += Console_CancelKeyPress;

            KillProcesses();//first run check and kill process according to the params

            var timer = new Timer(TimeSpan.FromMinutes(options.Frequency).TotalMilliseconds);

            timer.AutoReset = true;
            timer.Elapsed  += Timer_Elapsed;
            try
            {
                timer.Start();
                while (true)
                {
                    if (_cancelled)
                    {
                        log.Info("The app was canceled");
                        timer.Dispose();
                        Console.CancelKeyPress -= Console_CancelKeyPress;
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                log.Error(e.StackTrace);
            }
            finally
            {
                timer.Dispose();
                Console.CancelKeyPress -= Console_CancelKeyPress;
            }
        }
Example #12
0
        private int RunInternal(string[] args)
        {
            _log.Trace("Application starting.");

            // Parses command line without sanity checks.
            CommandLineParseResult parseResult = _parser.Parse(args);

            if (!parseResult.IsCorrect || !parseResult.Verb.HasValue)
            {
                _log.Error("Command line arguments incorrect.");
                return(1);
            }

            IVerbRunner verbRunner = CreateVerbRunner(parseResult.Verb.Value, parseResult.VerbOptions);

            verbRunner.Run();

            return(0);
        }
Example #13
0
        public async Task <int> Parse(params string[] args)
        {
            if (!args.Contains("--verbose"))
            {
                args = args.Concat(new[] { "--verbose" }).ToArray();
            }
            try
            {
                return(await commandLineParserImplementation.Parse(args));
            }catch (Exception e)
            {
                if (!exceptionHandler.HandleException(e))
                {
                    throw;
                }

                return(-1);
            }
        }
Example #14
0
        public async Task <IReadOnlyList <SoftKeySet> > ExecuteAsync(string commandLineString, CancellationToken cancellationToken)
        {
            if (commandLineString.IsNullOrEmpty())
            {
                return(NoCommandsExecuted);
            }

            var commandLines = _commandLineParser.Parse(commandLineString).ToList();

            var executables =
                (from commandLine in commandLines
                 let commandName = commandLine.CommandName()
                                   let command = _commandFactory.CreateCommand(commandName, commandLine)
                                                 select(commandName, command)).ToList();

            var notFoundCommands = executables.Where(exe => exe.command is null).ToList();

            if (notFoundCommands.Any())
            {
                // From each command get only a single name but take the longest one as this is most likely the full-name.
                var notFoundCommandNames = notFoundCommands.Select(exe => exe.commandName.OrderByDescending(name => name.Length).First().ToString());
                throw DynamicException.Factory.CreateDynamicException(
                          $"CommandNotFound{nameof(Exception)}",
                          $"Could not find one or more commands: {notFoundCommandNames.Join(", ").EncloseWith("[]")}.",
                          null);
            }

            var executedCommands = new List <SoftKeySet>();

            foreach (var executable in executables)
            {
                await executable.command.ExecuteAsync(cancellationToken);

                executedCommands.Add(executable.commandName);
            }

            return(executedCommands);
        }
Example #15
0
        public IActionResult Post([FromBody] ConvertModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(
                           new ConvertResult <ConvertModel>(
                               ModelState.SelectMany(r => r.Value.Errors.Select(e => e.ErrorMessage))
                               .ToArray())));
            }

            var parseResult = _commandLineParser.Parse(new Span <char>(model.Curl.ToCharArray()));

            if (!parseResult.Success)
            {
                return(BadRequest(parseResult));
            }

            var csharp = _converterService.ToCsharp(parseResult.Data);

            csharp.AddWarnings(parseResult.Warnings);

            return(Ok(csharp));
        }
Example #16
0
 public Task <int> Parse(params string[] args)
 {
     return(parser.Parse(args));
 }
Example #17
0
 public static ICommandLine Parse(this ICommandLineParser parser, object options, string[] args, bool stopAtNotOption)
 {
     return(parser.Parse(ReflectedOptions.CreateFromObject(options), args, stopAtNotOption));
 }
Example #18
0
        public void Parse_Empty_EmptyCollection()
        {
            var commandLines = Parser.Parse(string.Empty).ToList();

            Assert.True(commandLines.Empty());
        }
Example #19
0
 public static ICommandLine ParseConsole(this ICommandLineParser parser, Options options, bool stopAtNotOption)
 {
     return(parser.Parse(options, Environment.GetCommandLineArgs(), stopAtNotOption));
 }
Example #20
0
        public ICommand Create(string cmd)
        {
            var cmdElements = _parser.Parse(cmd);
            var argument    = cmdElements.OfType <ArgumentElement>().First();
            var definitions = cmdElements.OfType <DefinitionElement>().ToArray();

            switch (argument.Id)
            {
            case "register":
                return(new RegisterAccountCommand(_userAgent, new RegisterAccountArguments
                {
                    Domain = definitions.First(x => x.Key == "d").Value,
                    Extension = definitions.First(x => x.Key == "e").Value,
                    Password = definitions.First(x => x.Key == "p").Value,
                    Port = definitions.First(x => x.Key == "Port").Value,
                    Transport = definitions.First(x => x.Key == "t").Value
                }));

            case "accounts":
                return(new ShowAccountsCommand(_userAgent));

            case "unregister":
                return(new UnregisterAccountCommand(_userAgent,
                                                    new IdArguments {
                    Id = definitions.First(x => x.Key == "i").Value
                }));

            case "codecs":
                return(new ShowCodecsCommand(_userAgent));

            case "setcodec":
                return(new SetCodecCommand(_userAgent, new CodecArguments
                {
                    Channels = definitions.First(x => x.Key == "Channels").Value,
                    CodecId = definitions.First(x => x.Key == "c").Value,
                    Frequency = definitions.First(x => x.Key == "f").Value,
                    Priority = definitions.First(x => x.Key == "p").Value,
                }));

            case "devices":
                return(new ShowDevicesCommand(_userAgent));

            case "setdevice":
                return(new SetDeviceCommand(_userAgent, new DeviceArguments
                {
                    CaptureId = definitions.First(x => x.Key == "c").Value,
                    PlaybackId = definitions.First(x => x.Key == "p").Value,
                }));

            case "calls":
                return(new ShowCallsCommand(_userAgent));

            case "makecall":
                return(new MakeCallCommand(_userAgent, new CallArguments
                {
                    At = definitions.First(x => x.Key == "a").Value,
                    From = definitions.First(x => x.Key == "f").Value,
                    Through = definitions.First(x => x.Key == "Through").Value,
                    To = definitions.First(x => x.Key == "t").Value,
                }));

            case "hangupcall":
                return(new HangupCallCommand(_userAgent,
                                             new IdArguments {
                    Id = definitions.First(x => x.Key == "i").Value
                }));

            case "dtmf":
                return(new SendDtmfCommand(_userAgent, new DtmfArguments
                {
                    CallId = definitions.First(x => x.Key == "c").Value,
                    Digits = definitions.First(x => x.Key == "d").Value,
                }));

            case "xfer":
                return(new TransferCommand(_userAgent, new TransferArguments
                {
                    CallId = definitions.First(x => x.Key == "c").Value,
                    Destination = definitions.First(x => x.Key == "d").Value,
                }));

            case "buddies":
                return(new ShowAllBuddiesCommand(_userAgent));

            case "registerbuddy":
                return(new RegisterBuddyCommand(_userAgent, new RegisterBuddyArguments
                {
                    Domain = definitions.First(x => x.Key == "d").Value,
                    Extension = definitions.First(x => x.Key == "e").Value,
                    Port = definitions.First(x => x.Key == "Port").Value,
                    Subscribe = definitions.First(x => x.Key == "s").Value,
                    Transport = definitions.First(x => x.Key == "t").Value,
                }));

            case "unregisterbuddy":
                return(new UnregisterBuddyCommand(_userAgent,
                                                  new IdArguments {
                    Id = definitions.First(x => x.Key == "i").Value
                }));

            case "dumpsub":
                return(new DumpSubscriptionCommand(_userAgent, new DumpSubscriptionArguments
                {
                    Verbose = definitions.First(x => x.Key == "v").Value
                }));

            case "im":
                return(new SendImCommand(_userAgent, new ImArguments
                {
                    At = definitions.First(x => x.Key == "a").Value,
                    Body = definitions.First(x => x.Key == "b").Value,
                    From = definitions.First(x => x.Key == "f").Value,
                    InDialog = definitions.First(x => x.Key == "i").Value,
                    Through = definitions.First(x => x.Key == "Through").Value,
                    To = definitions.First(x => x.Key == "t").Value,
                }, _container.Get <IMessageBuilder>()));

            case "playertest":
                return(new PlayFileCommand(_userAgent, _container));

            case "?":
            case "help":
            case "print":
                return(new PrintUsageCommand());

            default:
                return(new NoOpCommand());
            }
        }
Example #21
0
 public static ICommandLine Parse(this ICommandLineParser parser, Options options, string[] args, bool stopAtNotOption)
 {
     return(parser.Parse(options, args, null, stopAtNotOption));
 }
Example #22
0
        private async Task CommandLineLoop(CommandDelegate application, CancellationToken loopToken)
        {
            await Task.Yield();

            var consoleTokenSource = new ConsoleCancelEventTokenSource(_console);

            loopToken.Register(consoleTokenSource.Cancel);
            IsRunning = true;

            bool   isFirstCancel = true;
            string commandLine   = null;

            try
            {
                while (!loopToken.IsCancellationRequested)
                {
                    try
                    {
                        _outputLock.Lock();
                        _prompt?.Write(_coloredTextWriter);
                        commandLine = await _lineReader.ReadLineAsync(consoleTokenSource.Token)
                                      .ConfigureAwait(false);
                    }
                    catch (OperationCanceledException ex)
                    {
                        // Do not throw because this is a normal loop ending.
                        if (loopToken.IsCancellationRequested)
                        {
                            break;
                        }

                        consoleTokenSource.Reset();
                        _console.WriteLine();

                        if (ex is ReadingLineCanceledException rex && rex.HadUserInput)
                        {
                            // Do not count this as a first cancellation if there was a user input
                            // and reset the flag if it was not the first one.
                            isFirstCancel = true;
                            continue;
                        }

                        // Exit on double Ctrl+C hotkey.
                        if (!isFirstCancel)
                        {
                            break;
                        }

                        isFirstCancel = false;
                        _console.WriteLine("Press Ctrl+C again to close application");
                        continue;
                    }
                    finally
                    {
                        _outputLock.Unlock();
                    }

                    // Reset the flag after a succesfull reading.
                    isFirstCancel = true;

                    if (String.IsNullOrWhiteSpace(commandLine))
                    {
                        continue;
                    }

                    try
                    {
                        var parsedCommandLine = _parser.Parse(commandLine, consoleTokenSource.Token);

                        if (parsedCommandLine.HasErrors)
                        {
                            PrintParseErrors(parsedCommandLine);
                            continue;
                        }

                        var context = _contextBuilder
                                      .SetCancelToken(consoleTokenSource.Token)
                                      .SetRawCommandLine(commandLine)
                                      .SetParsedCommandLine(parsedCommandLine)
                                      .Build();

                        // End command-line loop.
                        if (loopToken.IsCancellationRequested)
                        {
                            break;
                        }

                        await application(context).ConfigureAwait(false);
                    }
                    catch (OperationCanceledException)
                    {
                        // Do not throw because this is a normal loop ending.
                        if (loopToken.IsCancellationRequested)
                        {
                            break;
                        }

                        consoleTokenSource.Reset();
                        _console.WriteLine();
                    }
                    catch (Exception ex)
                    {
                        PrintErrorMessage(ex, verbose: false);
                    }
                }
            }
            finally
            {
                consoleTokenSource.Dispose();
                IsRunning = false;
            }
        }
Example #23
0
        private static async Task <int> MainAsync(string[] args)
        {
            if (args.Any() &&
                args[0].Equals(CommandLineConstants.MigrateCliVerb, StringComparison.OrdinalIgnoreCase) &&
                !args.Any(a => a.TrimEnd().EndsWith("help", StringComparison.OrdinalIgnoreCase)))
            {
                return(Migrate() ? 0 : 1);
            }

            Agents.Net.CommunityAnalysis.Analyse(Array.Empty <Assembly>());
#if DEBUG
            Stopwatch stopwatch = Stopwatch.StartNew();
#endif
            try
            {
                bool             noSdkExploration = args.Any(a => a.Contains("--no-sdk-exploration", StringComparison.Ordinal));
                ILog             log     = CreateLog();
                ContainerBuilder builder = new ContainerBuilder();
                builder.RegisterInstance(log);
                builder.RegisterModule(new DiModule(noSdkExploration));

                using (IContainer container = builder.Build())
                {
                    try
                    {
                        ICommandLineParser commandLineParser = container.Resolve <ICommandLineParser>();
#if DEBUG
                        Console.WriteLine($@"Startup timer {stopwatch.Elapsed}");
                        Console.WriteLine($@"Arguments: {args.Aggregate(string.Empty, (s, s1) => s + "_" + s1)}");
#endif
                        int result = await commandLineParser.Parse(args).ConfigureAwait(false);

                        return(result);
                    }
                    catch (Exception e)
                    {
                        IExceptionHandler exceptionHandler = container.Resolve <IExceptionHandler>();
                        if (!exceptionHandler.HandleException(e))
                        {
                            throw;
                        }

                        return(-1);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($@"Unexpected exception during execution{Environment.NewLine}{e}");
                Trace.TraceError(e.ToString());
                return(-1);
            }

            ILog CreateLog()
            {
                string path   = LogHelper.GetLogCatalogLocation();
                ILog   result = LogCatalog.CreateNewLog(path, string.Join(" ", args));

                result.AddInitialLog(args);
                return(result);
            }

            bool Migrate()
            {
                ILog log = LogHelper.GetMigrationLog();

                try
                {
                    log.AddInitialLog(args);
                    //Not implemented feature: Old version has caches and settings in same location as current version.
                    //How to identify the version? Probably create a .version file.
                    return(MigrationChain.Start(m =>
                    {
                        Console.WriteLine(m);
                        log.LogInformation(m);
                    })
                           .AddPotentialLocation(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                                                              "plcncli.Common"), new Version(19, 0))
                           .AddMigrationFile("settings.xml")
                           .AddMigrationFile("sdk-properties.xml")
                           .SetMigrationDestination(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                                                                 (Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly()).GetName().Name))
                           .AddConversionStep <ConversionFrom190>()
                           .Execute());
                }
                finally
                {
                    (log as IDisposable)?.Dispose();
                }
            }
        }
Example #24
0
        public void Parse_Empty_EmptyCollection()
        {
            var arguments = Parser.Parse("").ToList();

            Assert.That.Collection().IsEmpty(arguments);
        }
Example #25
0
        public void Parse_Empty_EmptyCollection()
        {
            var commandLines = Parser.Parse(string.Empty).ToList();

            Assert.That.Collection().IsEmpty(commandLines);
        }
 public CommandLineSyntax CommandNameOnly()
 {
     return(_parser.Parse(Command_NameOnly));
 }
Example #27
0
        public void HandleCommandLine(string [] args, ICommandLineParser parser)
        {
            if (parser == null)
                throw new ArgumentNullException("parser");

            Initialize();

            parser.Options = appOptions;
            CommandLine commandLine = parser.Parse(args);
            if (commandLine.HasParsed)
                HandleCommandLine(commandLine);
        }