void PopulateKeyValue(string key, string value) { var parameter = key.ToLower(); switch (parameter) { case "search": ParsedOptions.SetSearchQuery(value); break; case "endpointname": ParsedOptions.SetEndpointName(value); break; case "autorefresh": ParsedOptions.SetAutoRefresh(value); break; case "resetlayout": ParsedOptions.SetResetLayout(bool.Parse(value)); break; default: AddUnsupportedKey(key); break; } }
/// <summary> /// Adds parsed option to a ParseResult object. This method is called by Parser. /// </summary> /// <param name="parsedOption">ParsedOption object to be added to a ParseResult object.</param> internal void addOption(ParsedOption parsedOption) { ParsedOptions.Add(parsedOption); foreach (var name in parsedOption.Names) { parsedOptions.Add(name, parsedOption); } }
private static async Task Main(string[] args) { #region Parse arguments ParsedOptions opts; try { var options = new CommandLineParser().Parse(args, KnownOptions.Options); opts = new ParsedOptions(options); } catch (Exception ex) { PrintHelp(); Environment.Exit(ex.HResult); return; } #endregion #region Resolve IP addresses IPAddress[] addresses; try { Console.Write("Resolving addresses..."); addresses = await Utils.ParseAddressesAsync(opts.TcpingTarget, opts.ResolveMultipleIPs); Utils.EraseLine(); } catch (Exception ex) { Utils.EraseLine(); WriteErrorLine($"Supplied hostname ({opts.TcpingTarget}) cannot be resolved: {ex}"); Environment.Exit(ex.HResult); return; } #endregion #region Print header Console.Write($"TCPING {opts.TcpingTarget}:{opts.Port} "); if (addresses.Length > 1) { Console.WriteLine($"({addresses.Length} IP{addresses.Length.S()}: {addresses.SpreadToString()})"); if (opts.Animate) { opts.Animate = false; Console.WriteLine("warning: animation disabled for multiple IPs."); } } else { var addr = addresses[0]; Console.WriteLine( $"({addr}): {addr.AddressFamily switch {AddressFamily.InterNetwork => "IPv4, connect", AddressFamily.InterNetworkV6 => "IPv6, connect", _ => "?"}}");
public string RecreateUnparsedArguments() { var escapeMarkerDetected = false; var bldr = new StringBuilder(); for (int i = 0; i < parsedArgs.Length; i++) { var arg = parsedArgs[i]; if (!escapeMarkerDetected && arg == Tokenizer.EscapeMarker) { escapeMarkerDetected = true; continue; } var shift = 0; var pOpts = ParsedOptions .Cast <IParsedArgument>() .Union(Values.Where(y => y.IsSet)) .Where(x => x.Descriptor.Index == i) .OrderBy(y => y.Descriptor.LocalPosition) .ToList(); foreach (var pOpt in pOpts) { arg = arg.Remove(pOpt.Descriptor.LocalPosition - shift, pOpt.Descriptor.Length); shift += pOpt.Descriptor.Length; if (pOpt.IsSeparated) { // skip next argument as it was parsed by this option i++; } } if (arg != "-" && arg.Length > 0) { arg = arg.Replace(@"""", @"\"""); if (arg.Contains(" ")) { arg = string.Format("\"{0}\"", arg); } bldr.Append(arg).Append(' '); } } // trim last space if (bldr.Length > 0 && bldr[bldr.Length - 1] == ' ') { bldr.Remove(bldr.Length - 1, 1); } return(bldr.ToString()); }
public static ParsedOptions ParseArgsToFactory(params string[] args) { var opts = new ParsedOptions(); var parser = new CommandLineParser(new CommandLineParserSettings(true, true)); if (!parser.ParseArguments(args, opts)) { Console.WriteLine(opts.GetUsage()); return(null); } return(opts); }
public InjectorSettings(string[] args) { Breakpoints = new List<BreakpointMethod>() { new BreakpointMethod("MS.Internal.JoltHelper", "FireEvent"), }; _options = ParseOptions(args); IsValid = (_options.Mode == PidSelectionMode.Args && _options.Pid != null) || (_options.Mode != PidSelectionMode.Args && _options.Pid == null) || (_options.Install != null && args.Length == 1) || (_options.Uninstall != null && args.Length == 1); }
/// <summary> /// Report process time to console and append to log file. /// </summary> /// <param name="options">Parsed CLI options with process file and arguments.</param> /// <param name="pTimes">Measured process times.</param> static void ReportProcessTimes(ParsedOptions options, ProcessTimes pTimes, string measuredProcessName) { string times = pTimes.FormatProcessTimes(); StringBuilder logBuilder = new StringBuilder(); logBuilder.Append(DateTime.Now.ToString("dd.MM.yyyy hh:mm:ss")) .Append('\n') .Append("Measured process: ").Append(measuredProcessName).Append('\n') .Append("Command: ").Append(options.ProcessFile).Append(' ').Append(options.ProcessArguments) .Append('\n') .Append(times); string report = logBuilder.ToString(); AppendToLogFile(report); ColoredPrint(report, ConsoleColor.DarkGreen); }
static ParsedOptions ParseOptions(string[] args) { InspectionOptions options = null; try { CommandLineRunOptionsParser parser = new CommandLineRunOptionsParser(); RunOptions parsedOptions = parser.ParseArguments(args); if (parsedOptions == null) { return(ParsedOptions.Failed()); } if (!string.IsNullOrWhiteSpace(parsedOptions.AppSettingsFile)) { RunOptions appOptions = parser.LoadAppSettings(parsedOptions.AppSettingsFile); parsedOptions.Override(appOptions); } if (string.IsNullOrWhiteSpace(parsedOptions.TargetPath)) { parsedOptions.TargetPath = Directory.GetCurrentDirectory(); } options = new InspectionOptions() { ExcludedModules = parsedOptions.ExcludedModules, IncludedModules = parsedOptions.IncludedModules, IgnoreFailure = parsedOptions.IgnoreFailures == "true", OutputDirectory = parsedOptions.OutputDirectory, PackagesRepoUrl = parsedOptions.PackagesRepoUrl, NugetConfigPath = parsedOptions.NugetConfigPath, TargetPath = parsedOptions.TargetPath, Verbose = parsedOptions.Verbose }; return(ParsedOptions.Succeeded(options)); } catch (Exception e) { Console.WriteLine("Failed to parse options."); Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); return(ParsedOptions.Failed()); } }
void PrintLoop(QueueingBasicConsumer consumer, ParsedOptions opts) { while (!_stopping) { object tmp; if (!consumer.Queue.Dequeue(200, out tmp)) { continue; } var msg = (BasicDeliverEventArgs)tmp; if (opts.BasicProps) { DebugUtil.DumpProperties(msg.BasicProperties, Console.Out, 1); } string output, formatted, input = msg.Body.AsUtf8String(); if (opts.PrettyJSON) { if (!LevelFilter.ShouldPrint(input, LogLevel.FromString(opts.Level), out formatted)) { continue; } output = formatted; } else { output = input; } Console.WriteLine(output); if (opts.WriteToFile) { WriteToFile(output); } } }
public void Parse() { var args = _environment.GetCommandLineArgs(); Logger.DebugFormat("Application invoked with following arguments: {0}", string.Join(" ", args)); if (args.Length != 2) { return; } var uri = args[1].Split(UriSeparator); if (uri.Length == 0) { return; } if (uri.Length > 0) { ParsedOptions.SetEndpointUri(uri[0]); } if (uri.Length > 1) { var parameters = uri[1]; var tokens = parameters.Split(TokenSeparator); foreach (var token in tokens) { var keyValue = token.Split(KeyValueSeparator); if (keyValue.Length == 2) { PopulateKeyValue(keyValue[0], keyValue[1]); } } } }
void PrintLoop(QueueingBasicConsumer consumer, ParsedOptions opts) { while (!_stopping) { object tmp; if (!consumer.Queue.Dequeue(200, out tmp)) continue; var msg = (BasicDeliverEventArgs) tmp; if (opts.BasicProps) DebugUtil.DumpProperties(msg.BasicProperties, Console.Out, 1); string output, formatted, input = msg.Body.AsUtf8String(); if (opts.PrettyJSON) { if (!LevelFilter.ShouldPrint(input, LogLevel.FromString(opts.Level), out formatted)) continue; output = formatted; } else output = input; Console.WriteLine(output); if (opts.WriteToFile) WriteToFile(output); } }
void ReceiveLoop(ParsedOptions opts) { while (!_stopping) { try { while (!_stopping) { try { Console.WriteLine("Setting up connection..."); using (var c = opts.Factory.CreateConnection()) using (var m = c.CreateModel()) { m.BasicQos(0u, 100, false); // http://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.qos.prefetch-size var consumer = new QueueingBasicConsumer(m); m.ExchangeDeclarePassive(opts.Exchange); var turnOff = true; var q = opts.WithQueue( () => { turnOff = false; // does itself after - below - seconds return m.QueueDeclare("", false, false, false, new Dictionary<string, object> { {"x-expires", 10*60000} // expire queue after 30 minutes, see http://www.rabbitmq.com/extensions.html }); }, qn => { Console.WriteLine("Declaring queue for this program's life-time. If this computer crashes, you need to manually delete it."); m.QueueDeclare(qn, true, false, false, null); }, qn => { Console.WriteLine("Declaring permanent queue. (WARNING - read the help unless you know what you do)"); m.QueueDeclare(qn, true, false, false, null); turnOff = false; }); m.QueueBind(q, opts.Exchange, opts.RoutingKey); m.BasicConsume(q, true, consumer); Console.WriteLine("Entering print loop..."); PrintLoop(consumer, opts); if (turnOff) { Console.WriteLine("Deleting queue..."); m.QueueDelete(q); } Console.WriteLine("Shutting down connection..."); } } catch (BrokerUnreachableException) { Console.WriteLine("Could not connect, retrying..."); Thread.Sleep(1000); } } } // sometimes this happens if rabbit is shut down catch (EndOfStreamException) { Console.WriteLine("RabbitMQ went down, re-connecting..."); } // this happens most of the time catch (IOException) { Console.WriteLine("RabbitMQ went down ungracefully, re-connecting..."); } // this happens when one kills erlang (killall -9 erl) catch (OperationInterruptedException) { Console.WriteLine(String.Format("Yet another one of RabbitMQ's failure modes - re-connecting... (you might not have the {0} exchange in your broker)", opts.Exchange)); } } }
public static ParsedOptions ParseArgsToFactory(params string[] args) { var opts = new ParsedOptions(); var parser = new CommandLineParser(new CommandLineParserSettings(true, true)); if (!parser.ParseArguments(args, opts)) { Console.WriteLine(opts.GetUsage()); return null; } return opts; }
static void Main(string[] args) { // Define cli options. SimpleArgParser simpleArgParser = new SimpleArgParser(new CliFlag[] { new CliFlag(CliFlag.SilentFlag) { HasValue = false, Description = "Silent mode" }, new CliFlag(CliFlag.ProcessNameFlag) { HasValue = true, Description = "Measured process name" }, new CliFlag(CliFlag.VerboseFlag) { HasValue = false, Description = "Report all subprocesses" }, new CliFlag(CliFlag.HelpFlag) { HasValue = false, Description = "Print help" } }); if (!simpleArgParser.Parse(args)) { return; } // Check that we have received the process filename. if (args.Length < 1 || simpleArgParser.HasMatched(CliFlag.HelpFlag)) { const string HelpText = "TimeIt.exe [options] command [command options]\n" + "\nOptions:\n" + "\t-s Silent mode (stdout and stderr aren't redirected.)\n" + "\t-v Verbose mode (Print execution time of all processes.)\n" + "\t-n Measured process name (Report execution time of this process.)\n" + "\t-h Print help"; Console.WriteLine(HelpText); return; } // Parse cli options. ParsedOptions options = simpleArgParser.GetParsedOptions(); // Dont create new window and redirect outputs if silent is not defined. ProcessStartInfo startInfo = new ProcessStartInfo(options.ProcessFile, options.ProcessArguments) { CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = !options.Silent, RedirectStandardError = !options.Silent }; // Create child process. Process rootProcess = new Process() { StartInfo = startInfo }; // Handle cancelation, kill the child process. Console.CancelKeyPress += KillMeasuredProcess; // Handle stdout and stderr streams. rootProcess.OutputDataReceived += PrintMeasuredProcessStdout; rootProcess.ErrorDataReceived += PrintMeasuredProcessStderr; // Start the measured process and begin reading of stdout, stderr. try { rootProcess.Start(); } catch (Exception) { ColoredPrint($"Failed to start requested process. Process file: ({options.ProcessFile}) | Arguments: ({options.ProcessArguments})", ConsoleColor.Red, error: true); return; } if (!options.Silent) { rootProcess.BeginOutputReadLine(); rootProcess.BeginErrorReadLine(); } // Create process tree from root process. m_processTree = new ProcessTree(rootProcess); // Wait until measured process exits. rootProcess.WaitForExit(); if (!m_processTree.IsValid) { ColoredPrint("Unable to query child processes.", ConsoleColor.Red, true); return; } // Measure execution time of all processes in the tree. m_processTree.MeasureExecutionTimeOfTree(); if (options.Verbose) { foreach (SubProcess subProcess in m_processTree) { string times = $"{subProcess.Name}\n{subProcess.Times.FormatProcessTimes()}"; ColoredPrint(times, ConsoleColor.DarkGreen); } } else if (options.HasMeasuredProcessName) { // If user defined -n option report that process time. if (m_processTree.TryGetMeasuredProcess(options.MeasuredProcessName, out ProcessTimes times)) { ReportProcessTimes(options, times, options.MeasuredProcessName); return; } else { ColoredPrint($"Unable to find requested process with name '{options.MeasuredProcessName}'", ConsoleColor.Red, true); return; } } ReportProcessTimes(options, m_processTree.GetOverallTreeTime(), "TotalProcessTree"); }
void ReceiveLoop(ParsedOptions opts) { while (!_stopping) { try { while (!_stopping) { try { Console.WriteLine("Setting up connection..."); using (var c = opts.Factory.CreateConnection()) using (var m = c.CreateModel()) { m.BasicQos(0u, 100, false); // http://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.qos.prefetch-size var consumer = new QueueingBasicConsumer(m); m.ExchangeDeclarePassive(opts.Exchange); var turnOff = true; var q = opts.WithQueue( () => { turnOff = false; // does itself after - below - seconds return(m.QueueDeclare("", false, false, false, new Dictionary <string, object> { { "x-expires", 10 * 60000 } // expire queue after 30 minutes, see http://www.rabbitmq.com/extensions.html })); }, qn => { Console.WriteLine( "Declaring queue for this program's life-time. If this computer crashes, you need to manually delete it."); m.QueueDeclare(qn, true, false, false, null); }, qn => { Console.WriteLine( "Declaring permanent queue. (WARNING - read the help unless you know what you do)"); m.QueueDeclare(qn, true, false, false, null); turnOff = false; }); m.QueueBind(q, opts.Exchange, opts.RoutingKey); m.BasicConsume(q, true, consumer); Console.WriteLine("Entering print loop..."); PrintLoop(consumer, opts); if (turnOff) { Console.WriteLine("Deleting queue..."); m.QueueDelete(q); } Console.WriteLine("Shutting down connection..."); } } catch (BrokerUnreachableException) { Console.WriteLine("Could not connect, retrying..."); Thread.Sleep(1000); } } } // sometimes this happens if rabbit is shut down catch (EndOfStreamException) { Console.WriteLine("RabbitMQ went down, re-connecting..."); } // this happens most of the time catch (IOException) { Console.WriteLine("RabbitMQ went down ungracefully, re-connecting..."); } // this happens when one kills erlang (killall -9 erl) catch (OperationInterruptedException) { Console.WriteLine( String.Format( "Yet another one of RabbitMQ's failure modes - re-connecting... (you might not have the {0} exchange in your broker)", opts.Exchange)); } } }
static async Task <int> Run(string[] args) { Log.SetContext(Context.Instance); var optionErrors = new List <string> (); ParsedOptions parsedOptions = new ParsedOptions { AutoProvision = ParseBoolean(Context.Instance.Properties.GetValue(KnownProperties.AutoProvision)), AutoProvisionUsesSudo = ParseBoolean(Context.Instance.Properties.GetValue(KnownProperties.AutoProvisionUsesSudo)), IgnoreMaxMonoVersion = ParseBoolean(Context.Instance.Properties.GetValue(KnownProperties.IgnoreMaxMonoVersion)), }; var opts = new OptionSet { "Usage: xaprepare [OPTIONS]", $"Xamarin.Android v{BuildInfo.XAVersion} preparation utility", "", { "p|property={=}", "Set a {PROPERTY} to a {VALUE}", (string p, string v) => Context.Instance.Properties.Set(p, v) }, { "d|dump-properties", "Dump values of all the defined properties to the screen", v => parsedOptions.DumpProps = true }, { "j|make-concurrency=", "Number of concurrent jobs for make to run. A positive integer or 0 for the default. Defaults to the number of CPUs/cores", v => parsedOptions.MakeConcurrency = EnsureUInt(v, "Invalid Make concurrency value") }, { "no-emoji", "Do not use any emoji characters in the output", v => parsedOptions.NoEmoji = true }, { "r|run-mode=", $"Specify the execution mode: {GetExecutionModes()}. See documentation for mode descriptions. Default: {Configurables.Defaults.ExecutionMode}", v => parsedOptions.ExecutionMode = ParseExecutionMode(v) }, { "f|build-runtimes", $"Build runtimes even if the bundle/archives are available.", v => parsedOptions.ForceRuntimesBuild = true }, { "H|hash-algorithm=", "Use the specified hash algorithm instead of the default {Configurables.Defaults.HashAlgorithm}", v => parsedOptions.HashAlgorithm = v?.Trim() }, { "D|debug-ext=", $"Extension of files with debug information for managed DLLs and executables. Default: {parsedOptions.DebugFileExtension}", v => parsedOptions.DebugFileExtension = v?.Trim() }, { "v|verbosity=", $"Set console log verbosity to {{LEVEL}}. Level name may be abbreviated to the smallest unique part (one of: {GetVerbosityLevels ()}). Default: {Context.Instance.LoggingVerbosity.ToString().ToLowerInvariant ()}", v => parsedOptions.Verbosity = ParseLogVerbosity(v) }, { "s|scenario=", "Run the specified scenario (use --ls to list all known scenarios) instead of the default one", v => parsedOptions.ScenarioName = v }, { "ls", "List names of all known scenarios", v => parsedOptions.ListScenarios = true }, { "cf=", $"{{NAME}} of the compression format to use for some archives (e.g. the XA bundle). One of: {GetCompressionFormatNames ()}; Default: {parsedOptions.CompressionFormat}", v => parsedOptions.CompressionFormat = v?.Trim() }, { "c|configuration=", $"Build {{CONFIGURATION}}. Default: {Context.Instance.Configuration}", v => parsedOptions.Configuration = v?.Trim() }, { "a|enable-all", "Enable preparation of all the supported targets, ABIs etc", v => parsedOptions.EnableAll = true }, { "refresh:", "[sdk,ndk] Comma separated list of components which should be reinstalled. Defaults to all supported components if no value is provided.", v => parsedOptions.RefreshList = ParseRefreshableComponents(v?.Trim()) }, "", { "auto-provision=", $"Automatically install software required by Xamarin.Android", v => parsedOptions.AutoProvision = ParseBoolean(v) }, { "auto-provision-uses-sudo=", $"Allow use of sudo(1) when provisioning", v => parsedOptions.AutoProvisionUsesSudo = ParseBoolean(v) }, { "ignore-max-mono-version=", $"Ignore the maximum supported Mono version restriction", v => parsedOptions.IgnoreMaxMonoVersion = ParseBoolean(v) }, { "ignore-min-mono-version=", $"Ignore the minimum supported Mono version restriction", v => parsedOptions.IgnoreMinMonoVersion = ParseBoolean(v) }, "", { "h|help", "Show this help message", v => parsedOptions.ShowHelp = true }, }; opts.Parse(args); if (parsedOptions.ShowHelp) { opts.WriteOptionDescriptions(Console.Out); return(0); } if (optionErrors.Count > 0) { Log.Instance.ErrorLine("Invalid arguments passed, please run with --help to see option documentation:"); Log.Instance.ErrorLine(); foreach (string errorLine in optionErrors) { Log.Instance.ErrorLine($" {errorLine}"); } } // If we're running without a terminal or the output is redirected we must enforce the dull mode. if (!Context.Instance.InteractiveSession) { parsedOptions.ExecutionMode = ExecutionMode.CI; } Context.Instance.MakeConcurrency = parsedOptions.MakeConcurrency; Context.Instance.NoEmoji = parsedOptions.NoEmoji; Context.Instance.ExecutionMode = parsedOptions.ExecutionMode; Context.Instance.ForceRuntimesBuild = parsedOptions.ForceRuntimesBuild; Context.Instance.LoggingVerbosity = parsedOptions.Verbosity; Context.Instance.DebugFileExtension = parsedOptions.DebugFileExtension; Context.Instance.AutoProvision = parsedOptions.AutoProvision; Context.Instance.AutoProvisionUsesSudo = parsedOptions.AutoProvisionUsesSudo; Context.Instance.IgnoreMaxMonoVersion = parsedOptions.IgnoreMaxMonoVersion; Context.Instance.IgnoreMinMonoVersion = parsedOptions.IgnoreMinMonoVersion; Context.Instance.EnableAllTargets = parsedOptions.EnableAll; Context.Instance.ComponentsToRefresh = parsedOptions.RefreshList; if (!String.IsNullOrEmpty(parsedOptions.Configuration)) { Context.Instance.Configuration = parsedOptions.Configuration; } if (!String.IsNullOrEmpty(parsedOptions.HashAlgorithm)) { Context.Instance.HashAlgorithm = parsedOptions.HashAlgorithm; } SetCompressionFormat(parsedOptions.CompressionFormat); if (!await Context.Instance.Init(parsedOptions.ScenarioName)) { return(1); } if (parsedOptions.DumpProps) { DumpProperties(Context.Instance); } if (parsedOptions.ListScenarios) { ListScenarios(Context.Instance); return(0); } return(await Context.Instance.Execute() ? 0 : 1); uint EnsureUInt(string v, string errorText) { if (UInt32.TryParse(v, out uint ret)) { return(ret); } optionErrors.Add(errorText); return(0); } }
private ParsedOptions ParseOptions(string[] args) { var options = new ParsedOptions(); _optionsSet = new OptionSet() { {"m|mode=", Messages.ModeHelp, (PidSelectionMode mode) => options.Mode = mode}, {"p|pid=", Messages.PidHelp, (int pid) => options.Pid = pid}, {"i|install", Messages.InstallHelp, v => options.Install = true}, {"u|uninstall", Messages.UninstallHelp, v => options.Uninstall = true}, }; try { _optionsSet.Parse(args); } catch (OptionException) { return new ParsedOptions(); // Should be invalid. } return options; }