public static int FindFirstUknownArg <T>(string[] args) { Parser parser = new Parser((parserSettings) => { parserSettings.HelpWriter = null; }); ParserResult <T> parserResult = parser.ParseArguments <T>(args); if (parserResult.Tag == ParserResultType.NotParsed) { List <int> unknownArgsIndexes = new List <int>(); NotParsed <T> info = parserResult as NotParsed <T>; foreach (var error in info.Errors) { if (error.Tag == ErrorType.UnknownOptionError) { UnknownOptionError unknownOptionError = error as UnknownOptionError; int uknownArgIndex = Array.FindIndex(args, (arg) => { if (unknownOptionError.Token.Length == 1) { return(arg.StartsWith("-" + unknownOptionError.Token)); } else { return(arg.Equals("--" + unknownOptionError.Token)); } }); unknownArgsIndexes.Add(uknownArgIndex); } } if (unknownArgsIndexes.Count == 0) { return(-1); } int min = int.MaxValue; foreach (int index in unknownArgsIndexes) { if (index < min) { min = index; } } return(min); } return(-1); }
public void Errors_ErrorsExist_ShouldReturnErrors() { var result = new ParseResult(); var optionMissingError = new OptionMissingError("optionA"); result.AddError(optionMissingError); var unknownOptionError = new UnknownOptionError("optionB"); result.AddError(unknownOptionError); result.Errors.Should().BeEquivalentTo(optionMissingError, unknownOptionError); }
static void Main(string[] args) { Args = args; if (Args.Contains("fn") || Args.Contains("pm") || Args.Contains("cr")) { SetLogger(new SerilogLogger(console: false, debug: true)); } else if (Args.Contains("--debug")) { SetLogger(new SerilogLogger(console: true, debug: true)); } else { SetLogger(new SerilogLogger(console: true, debug: false)); } AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Console.CancelKeyPress += Console_CancelKeyPress; WebServer = new WebServer(); WebServer.ProcessRequest += WebServer_ProcessRequest; WebServer.EndPoint = new IPEndPoint(IPAddress.Loopback, 5001); WebServer.IsStarted = true; if (!args.Contains("fn") && !args.Contains("pm") && !args.Contains("cr")) { PrintLogo(); } if (args.Contains("--debug")) { Info("Debug mode set."); } ParserResult <object> result = new Parser().ParseArguments <Options, SpeechRecognitionOptions, TTSOptions, FNOptions, PMOptions>(args); result.WithNotParsed((IEnumerable <Error> errors) => { HelpText help = GetAutoBuiltHelpText(result); help.Copyright = string.Empty; help.AddPreOptionsLine(string.Empty); if (errors.Any(e => e.Tag == ErrorType.VersionRequestedError)) { Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.HelpVerbRequestedError)) { HelpVerbRequestedError error = (HelpVerbRequestedError)errors.First(e => e.Tag == ErrorType.HelpVerbRequestedError); if (error.Type != null) { help.AddVerbs(error.Type); } else { help.AddVerbs(typeof(SpeechRecognitionOptions), typeof(TTSOptions), typeof(FNOptions), typeof(PMOptions)); } Info(help); Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.HelpRequestedError)) { HelpRequestedError error = (HelpRequestedError)errors.First(e => e.Tag == ErrorType.HelpRequestedError); help.AddVerbs(typeof(SpeechRecognitionOptions), typeof(TTSOptions), typeof(FNOptions), typeof(PMOptions)); Info(help); Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.NoVerbSelectedError)) { help.AddVerbs(typeof(SpeechRecognitionOptions), typeof(TTSOptions), typeof(FNOptions), typeof(PMOptions)); Info(help); Exit(ExitResult.INVALID_OPTIONS); } else if (errors.Any(e => e.Tag == ErrorType.MissingRequiredOptionError)) { MissingRequiredOptionError error = (MissingRequiredOptionError)errors.First(e => e.Tag == ErrorType.MissingRequiredOptionError); Error("A required option is missing: {0}.", error.NameInfo.NameText); Info(help); Exit(ExitResult.INVALID_OPTIONS); } else if (errors.Any(e => e.Tag == ErrorType.UnknownOptionError)) { UnknownOptionError error = (UnknownOptionError)errors.First(e => e.Tag == ErrorType.UnknownOptionError); help.AddVerbs(typeof(SpeechRecognitionOptions), typeof(TTSOptions)); Error("Unknown option: {error}.", error.Token); Info(help); Exit(ExitResult.INVALID_OPTIONS); } else { Error("An error occurred parsing the program options: {errors}.", errors); help.AddVerbs(typeof(SpeechRecognitionOptions), typeof(TTSOptions)); Info(help); Exit(ExitResult.INVALID_OPTIONS); } }) .WithParsed <SpeechRecognitionOptions>(o => { ASR(); Exit(ExitResult.SUCCESS); }) .WithParsed <TTSOptions>(o => { TTS(o.Text); Exit(ExitResult.SUCCESS); }) .WithParsed <FNOptions>(o => { FNController.Options = o; new FNController(o).Start(); Exit(ExitResult.SUCCESS); }) .WithParsed <PMOptions>(o => { PMController.Options = o; new PMController(o).Start(); Exit(ExitResult.SUCCESS); }); }
static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; LConfig = new LoggerConfiguration() .Enrich.FromLogContext() .MinimumLevel.Debug() .WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss}<{ThreadId:d2}> [{Level:u3}] {Message}{NewLine}{Exception}") .WriteTo.File("OpGen.log"); L = Log.Logger = LConfig.CreateLogger(); Parser p = new Parser(); ParserResult <Options> result = p.ParseArguments <Options>(args); result.WithNotParsed((IEnumerable <Error> errors) => { HelpText help = GetAutoBuiltHelpText(result); help.MaximumDisplayWidth = Console.WindowWidth; help.Copyright = string.Empty; help.Heading = new HeadingInfo("Sylvester.tf OpGen CLI", Version.ToString(3)); help.AddPreOptionsLine(string.Empty); if (errors.Any(e => e.Tag == ErrorType.VersionRequestedError)) { Log.Information(help); Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.HelpVerbRequestedError)) { HelpVerbRequestedError error = (HelpVerbRequestedError)errors.First(e => e.Tag == ErrorType.HelpVerbRequestedError); if (error.Type != null) { help.AddVerbs(error.Type); } else { help.AddVerbs(typeof(Options)); } Log.Information(help); Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.HelpRequestedError)) { help.AddOptions(result); L.Information(help); Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.MissingRequiredOptionError)) { MissingRequiredOptionError error = (MissingRequiredOptionError)errors.First(e => e is MissingRequiredOptionError); help.AddOptions(result); help.AddPreOptionsLine($"A required option or value is missing: {error.NameInfo.NameText} The options and values for this benchmark category are: "); L.Information(help); Exit(ExitResult.INVALID_OPTIONS); } else if (errors.Any(e => e.Tag == ErrorType.MissingValueOptionError)) { MissingValueOptionError error = (MissingValueOptionError)errors.First(e => e.Tag == ErrorType.MissingValueOptionError); help.AddOptions(result); help.AddPreOptionsLine($"A required option or value is missing. The options and values for this category are: "); L.Information(help); Exit(ExitResult.INVALID_OPTIONS); } else if (errors.Any(e => e.Tag == ErrorType.UnknownOptionError)) { UnknownOptionError error = (UnknownOptionError)errors.First(e => e.Tag == ErrorType.UnknownOptionError); help.AddOptions(result); help.AddPreOptionsLine($"Unknown option: {error.Token}."); L.Information(help); Exit(ExitResult.INVALID_OPTIONS); } else { help.AddPreOptionsLine($"An error occurred parsing the program options: {string.Join(" ", errors.Select(e => e.Tag.ToString()).ToArray())}"); help.AddVerbs(typeof(Options)); L.Information(help); Exit(ExitResult.INVALID_OPTIONS); } }) .WithParsed(o => { Generator = new Generator(o.OutputFileName); var dirs = !string.IsNullOrEmpty(o.Dirs) ? o.Dirs.Split(',') : Array.Empty <string>(); if (dirs.Length == 1) { L.Information("Using {0} TensorFlow op def directory.", 1); } else { L.Information("Using {0} TensorFlow op def directories.", dirs.Length); } Generator.Run(dirs, o.Op); Exit(ExitResult.SUCCESS); }); }
static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += Program_UnhandledException; Console.CancelKeyPress += Console_CancelKeyPress; LConfig = new LoggerConfiguration() .Enrich.FromLogContext() .Enrich.WithThreadId(); if (args.Contains("-v") || args.Contains("--verbose")) { LConfig = LConfig.MinimumLevel.Verbose() .WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss}<{ThreadId:d2}> [{Level:u3}] [{SourceContext}] {Message}{NewLine}{Exception}"); } else { LConfig = LConfig .MinimumLevel.Debug() .WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss}<{ThreadId:d2}> [{Level:u3}] {Message}{NewLine}{Exception}"); } IConfigurationBuilder builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); AppConfig = builder.Build(); Log.Logger = LConfig.CreateLogger(); L = new Logger <Program>(); ParserResult <object> result = new Parser().ParseArguments <Options, GenerateOptions, CopyOptions, SyncOptions>(args); result.WithNotParsed((IEnumerable <Error> errors) => { HelpText help = GetAutoBuiltHelpText(result); help.Heading = new HeadingInfo("AzSync", Version.ToString(3)); help.Copyright = string.Empty; help.AddPreOptionsLine(string.Empty); if (errors.Any(e => e.Tag == ErrorType.VersionRequestedError)) { Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.HelpVerbRequestedError)) { HelpVerbRequestedError error = (HelpVerbRequestedError)errors.First(e => e.Tag == ErrorType.HelpVerbRequestedError); if (error.Type != null) { help.AddVerbs(error.Type); } L.Info(help); Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.HelpRequestedError)) { help.AddVerbs(typeof(SyncOptions), typeof(CopyOptions), typeof(GenerateOptions)); L.Info(help); Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.NoVerbSelectedError)) { help.AddVerbs(typeof(SyncOptions), typeof(CopyOptions), typeof(GenerateOptions)); L.Error("No operation selected. Specify one of: copy, sync, gen."); L.Info(help); Exit(ExitResult.INVALID_OPTIONS); } else if (errors.Any(e => e.Tag == ErrorType.MissingRequiredOptionError)) { MissingRequiredOptionError error = (MissingRequiredOptionError)errors.First(e => e.Tag == ErrorType.MissingRequiredOptionError); L.Error("A required option is missing: {0}.", error.NameInfo.NameText); L.Info(help); Exit(ExitResult.INVALID_OPTIONS); } else if (errors.Any(e => e.Tag == ErrorType.UnknownOptionError)) { UnknownOptionError error = (UnknownOptionError)errors.First(e => e.Tag == ErrorType.UnknownOptionError); help.AddVerbs(typeof(SyncOptions), typeof(CopyOptions), typeof(GenerateOptions)); L.Error("Unknown option: {error}.", error.Token); L.Info(help); Exit(ExitResult.INVALID_OPTIONS); } else { L.Error("An error occurred parsing the program options: {errors}.", errors); help.AddVerbs(typeof(SyncOptions), typeof(CopyOptions), typeof(GenerateOptions)); L.Info(help); Exit(ExitResult.INVALID_OPTIONS); } }) .WithParsed((TransferOptions o) => { o.Source = string.IsNullOrEmpty(AppConfig["Source"]) ? o.Source : AppConfig["Source"]; o.SourceKey = string.IsNullOrEmpty(AppConfig["SourceKey"]) ? o.SourceKey : AppConfig["SourceKey"]; o.Destination = string.IsNullOrEmpty(AppConfig["Destination"]) ? o.Destination : AppConfig["Destination"]; o.DestinationKey = string.IsNullOrEmpty(AppConfig["DestKey"]) ? o.DestinationKey : AppConfig["DestKey"]; o.Pattern = string.IsNullOrEmpty(AppConfig["Pattern"]) ? o.Pattern : AppConfig["Pattern"]; if (o.UseStorageEmulator) { o.DestinationKey = @"Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="; } foreach (PropertyInfo prop in o.GetType().GetProperties()) { EngineOptions.Add(prop.Name, prop.GetValue(o)); } if (!string.IsNullOrEmpty(o.Source) && (o.Source.StartsWith("http://") || o.Source.StartsWith("https://")) && Uri.TryCreate(o.Source, UriKind.Absolute, out Uri sourceUri)) { if (sourceUri.Segments.Length < 3) { L.Error("The Azure endpoint Url for the sync source must be in the format http(s)://{account_name}.blob.core.windows.net/{container_name}"); Exit(ExitResult.INVALID_OPTIONS); } else { EngineOptions.Add("SourceUri", sourceUri); EngineOptions.Add("SourceAccountName", sourceUri.Segments[1].TrimEnd('/')); EngineOptions.Add("SourceContainerName", sourceUri.Segments[2]); if (sourceUri.Segments.Length == 4) { EngineOptions.Add("SourceBlobName", sourceUri.Segments[3]); } } } else if (!string.IsNullOrEmpty(o.Source)) { try { if (Directory.Exists(o.Source)) { EngineOptions.Add("SourceDirectory", new DirectoryInfo(o.Source)); string[] files = Directory.GetFiles(o.Source, o.Pattern, o.Recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); L.Info("Matched {0} file(s) to pattern {1} in directory {2}.", files.Length, o.Pattern, o.Source); if (files.Length > 0) { EngineOptions.Add("SourceFiles", files); } else { L.Warn("Nothing to do, exiting."); Exit(ExitResult.SUCCESS); } } else { L.Error("Could not find local directory {0}.", o.Source); Exit(ExitResult.FILE_OR_DIRECTORY_NOT_FOUND); } } catch (IOException ioe) { L.Error(ioe, "A storage error occurred attempting to find or access local directory {d}.", o.Source); Exit(ExitResult.FILE_OR_DIRECTORY_NOT_FOUND); } } if (!string.IsNullOrEmpty(o.Destination) && (o.Destination.StartsWith("http://") || o.Destination.StartsWith("https://")) && Uri.TryCreate(o.Destination, UriKind.Absolute, out Uri destinationUri)) { if (destinationUri.Segments.Length != 3) { L.Error("The Azure endpoint Url for the sync destination must be in the format http(s)://{account_name}.blob.core.windows.net/{container_name}"); Exit(ExitResult.INVALID_OPTIONS); } else { EngineOptions.Add("DestinationUri", destinationUri); EngineOptions.Add("DestinationAccountName", destinationUri.Segments[1].TrimEnd('/')); EngineOptions.Add("DestinationContainerName", destinationUri.Segments[2]); if (destinationUri.Segments.Length == 4) { EngineOptions.Add("DestinationBlobName", destinationUri.Segments[3]); } } } else if (!string.IsNullOrEmpty(o.Destination)) { try { if (Directory.Exists(o.Destination)) { EngineOptions.Add("DestinationDirectory", new DirectoryInfo(o.Destination)); } else { L.Error("Could not find local directory {0}.", o.Destination); Exit(ExitResult.FILE_OR_DIRECTORY_NOT_FOUND); } } catch (IOException ioe) { L.Error(ioe, "A storage exception was thrown attempting to find local directory {d}.", o.Destination); Exit(ExitResult.FILE_OR_DIRECTORY_NOT_FOUND); } } }) .WithParsed((CopyOptions o) => { EngineOptions.Add("Operation", TransferEngine.OperationType.COPY); ExecuteTransferTasks(); }) .WithParsed((SyncOptions o) => { EngineOptions.Add("Operation", TransferEngine.OperationType.SYNC); ExecuteTransferTasks(); }) .WithParsed((GenerateOptions o) => { GenerateOptions = o; ExecuteGenerateTasks(); }); }
static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; LConfig = new LoggerConfiguration() .Enrich.FromLogContext() .Enrich.WithThreadId() .Enrich.WithProcessId() .MinimumLevel.Debug() .WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss}<{ThreadId:d2}> [{Level:u3}] {Message}{NewLine}{Exception}"); L = Log.Logger = LConfig.CreateLogger(); Type[] BenchmarkOptionTypes = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.IsSubclassOf(typeof(Options))).ToArray(); ParserResult <object> result = new Parser().ParseArguments <Options, MallocBenchmarkOptions, NativeArrayBenchmarkOptions, HugeNativeArrayBenchmarkOptions>(args); result.WithNotParsed((IEnumerable <Error> errors) => { HelpText help = GetAutoBuiltHelpText(result); help.MaximumDisplayWidth = Console.WindowWidth; help.Copyright = string.Empty; help.Heading = new HeadingInfo("jemalloc.NET", Version.ToString(3)); help.AddPreOptionsLine(string.Empty); if (errors.Any(e => e.Tag == ErrorType.VersionRequestedError)) { Log.Information(help); Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.HelpVerbRequestedError)) { HelpVerbRequestedError error = (HelpVerbRequestedError)errors.First(e => e.Tag == ErrorType.HelpVerbRequestedError); if (error.Type != null) { help.AddVerbs(error.Type); } Log.Information(help); Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.HelpRequestedError)) { help.AddVerbs(BenchmarkOptionTypes); L.Information(help); Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.NoVerbSelectedError)) { help.AddVerbs(BenchmarkOptionTypes); help.AddPreOptionsLine("No category selected. Select a category from the options below:"); L.Information(help); Exit(ExitResult.INVALID_OPTIONS); } else if (errors.Any(e => e.Tag == ErrorType.MissingRequiredOptionError)) { MissingRequiredOptionError error = (MissingRequiredOptionError)errors.First(e => e is MissingRequiredOptionError); help.AddOptions(result); help.AddPreOptionsLine($"A required option or value is missing. The options and values for this benchmark category are: "); L.Information(help); Exit(ExitResult.INVALID_OPTIONS); } else if (errors.Any(e => e.Tag == ErrorType.MissingValueOptionError)) { MissingValueOptionError error = (MissingValueOptionError)errors.First(e => e.Tag == ErrorType.MissingValueOptionError); help.AddOptions(result); help.AddPreOptionsLine($"A required option or value is missing. The options and values for this benchmark category are: "); L.Information(help); Exit(ExitResult.INVALID_OPTIONS); } else if (errors.Any(e => e.Tag == ErrorType.UnknownOptionError)) { UnknownOptionError error = (UnknownOptionError)errors.First(e => e.Tag == ErrorType.UnknownOptionError); help.AddOptions(result); help.AddPreOptionsLine($"Unknown option: {error.Token}."); L.Information(help); Exit(ExitResult.INVALID_OPTIONS); } else { help.AddPreOptionsLine($"An error occurred parsing the program options: {string.Join(' ', errors.Select(e => e.Tag.ToString()).ToArray())}"); help.AddVerbs(BenchmarkOptionTypes); L.Information(help); Exit(ExitResult.INVALID_OPTIONS); } }) .WithParsed((Options o) => { foreach (PropertyInfo prop in o.GetType().GetProperties()) { BenchmarkOptions.Add(prop.Name, prop.GetValue(o)); } if (o.ColdStart) { JemBenchmarkJobAttribute.ColdStartOverride = true; } if (o.TargetCount > 0) { JemBenchmarkJobAttribute.TargetCountOverride = o.TargetCount; } }) .WithParsed <MallocBenchmarkOptions>(o => { BenchmarkOptions.Add("Category", Category.MALLOC); if (o.Create) { BenchmarkOptions.Add("Operation", Operation.CREATE); } else if (o.Fill) { BenchmarkOptions.Add("Operation", Operation.FILL); } if (!BenchmarkOptions.ContainsKey("Operation")) { Log.Error("You must select an operation to benchmark with --fill."); Exit(ExitResult.SUCCESS); } else { Benchmark(o); } }) .WithParsed <NativeArrayBenchmarkOptions>(o => { BenchmarkOptions.Add("Category", Category.NARRAY); if (o.Create) { BenchmarkOptions.Add("Operation", Operation.CREATE); } else if (o.Fill) { BenchmarkOptions.Add("Operation", Operation.FILL); } else if (o.Math) { BenchmarkOptions.Add("Operation", Operation.MATH); } if (!BenchmarkOptions.ContainsKey("Operation")) { Log.Error("You must select an operation to benchmark with --create or --fill."); Exit(ExitResult.SUCCESS); } else { Benchmark(o); } }) .WithParsed <HugeNativeArrayBenchmarkOptions>(o => { BenchmarkOptions.Add("Category", Category.HUGEARRAY); if (o.Create) { BenchmarkOptions.Add("Operation", Operation.CREATE); } else if (o.Fill) { BenchmarkOptions.Add("Operation", Operation.FILL); } else if (o.Math) { BenchmarkOptions.Add("Operation", Operation.MATH); } if (!BenchmarkOptions.ContainsKey("Operation")) { Log.Error("You must select an operation to benchmark with --create or --fill or --math."); Exit(ExitResult.SUCCESS); } else { Benchmark(o); } }); }
static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; LConfig = new LoggerConfiguration() .Enrich.FromLogContext() .MinimumLevel.Debug() .WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss}<{ThreadId:d2}> [{Level:u3}] {Message}{NewLine}{Exception}"); L = Log.Logger = LConfig.CreateLogger(); Type[] BindOptionTypes = Assembly.GetExecutingAssembly().GetTypes().Where(t => t == typeof(Options) || t.IsSubclassOf(typeof(Options))).ToArray(); MethodInfo parseArgumentsMethod = typeof(ParserExtensions).GetMethods().Where(m => m.IsGenericMethod && m.Name == "ParseArguments" && m.GetGenericArguments().Count() == BindOptionTypes.Count()).First(); Parser p = new Parser(); ParserResult <object> result = (ParserResult <object>)parseArgumentsMethod.MakeGenericMethod(BindOptionTypes).Invoke(p, new object[] { p, args }); result.WithNotParsed((IEnumerable <Error> errors) => { HelpText help = GetAutoBuiltHelpText(result); help.MaximumDisplayWidth = Console.WindowWidth; help.Copyright = string.Empty; help.Heading = new HeadingInfo("Sylvester Bindings CLI", Version.ToString(3)); help.AddPreOptionsLine(string.Empty); if (errors.Any(e => e.Tag == ErrorType.VersionRequestedError)) { Log.Information(help); Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.HelpVerbRequestedError)) { HelpVerbRequestedError error = (HelpVerbRequestedError)errors.First(e => e.Tag == ErrorType.HelpVerbRequestedError); if (error.Type != null) { help.AddVerbs(error.Type); } else { help.AddVerbs(BindOptionTypes); } Log.Information(help); Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.HelpRequestedError)) { help.AddOptions(result); L.Information(help); Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.NoVerbSelectedError)) { help.AddVerbs(BindOptionTypes); help.AddPreOptionsLine("No library selected. Select a library or verb from the options below:"); L.Information(help); Exit(ExitResult.INVALID_OPTIONS); } else if (errors.Any(e => e.Tag == ErrorType.MissingRequiredOptionError)) { MissingRequiredOptionError error = (MissingRequiredOptionError)errors.First(e => e is MissingRequiredOptionError); help.AddOptions(result); help.AddPreOptionsLine($"A required option or value is missing: {error.NameInfo.NameText} The options and values for this benchmark category are: "); L.Information(help); Exit(ExitResult.INVALID_OPTIONS); } else if (errors.Any(e => e.Tag == ErrorType.MissingValueOptionError)) { MissingValueOptionError error = (MissingValueOptionError)errors.First(e => e.Tag == ErrorType.MissingValueOptionError); help.AddOptions(result); help.AddPreOptionsLine($"A required option or value is missing. The options and values for this category are: "); L.Information(help); Exit(ExitResult.INVALID_OPTIONS); } else if (errors.Any(e => e.Tag == ErrorType.UnknownOptionError)) { UnknownOptionError error = (UnknownOptionError)errors.First(e => e.Tag == ErrorType.UnknownOptionError); help.AddOptions(result); help.AddPreOptionsLine($"Unknown option: {error.Token}."); L.Information(help); Exit(ExitResult.INVALID_OPTIONS); } else { help.AddPreOptionsLine($"An error occurred parsing the program options: {string.Join(" ", errors.Select(e => e.Tag.ToString()).ToArray())}"); help.AddVerbs(BindOptionTypes); L.Information(help); Exit(ExitResult.INVALID_OPTIONS); } }) .WithParsed <Options>(o => { if (string.IsNullOrEmpty(o.ModuleName)) { Log.Error($"You must select a module to create bindings for. Use the --help option to get the list of available modules."); Exit(ExitResult.INVALID_OPTIONS); } if (!string.IsNullOrEmpty(o.Root) && !Directory.Exists(o.Root)) { Log.Error($"The library root directory specified {o.Root} does not exist."); Exit(ExitResult.INVALID_OPTIONS); } else if (!string.IsNullOrEmpty(o.Root)) { ProgramOptions.Add("RootDirectory", new DirectoryInfo(o.Root)); } foreach (PropertyInfo prop in o.GetType().GetProperties()) { ProgramOptions.Add(prop.Name, prop.GetValue(o)); } }) .WithParsed <PlaidMLOptions>(o => { if (!File.Exists(Path.Combine(AssemblyDirectory.FullName, "plaidml", "base.h"))) { L.Error($"The PlaidML header file {Path.Combine(AssemblyDirectory.FullName, "plaidml", "base.h")} was not found."); Exit(ExitResult.FILE_MISSING); } else if (!File.Exists(Path.Combine(AssemblyDirectory.FullName, "plaidml", "plaidml.h"))) { L.Error($"The PlaidML header file {Path.Combine(AssemblyDirectory.FullName, "plaidml", "plaidml.h")} was not found."); Exit(ExitResult.FILE_MISSING); } ProgramLibrary = new PlaidML(ProgramOptions); ConsoleDriver.Run(ProgramLibrary); if (ProgramLibrary.CleanAndFixup()) { Exit(ExitResult.SUCCESS); } else { Exit(ExitResult.ERROR_DURING_CLEANUP); } }) .WithParsed <TensorFlowOptions>(o => { if (!File.Exists(Path.Combine(AssemblyDirectory.FullName, "tf", "c_api.h"))) { L.Error($"The TensorFlow header file {Path.Combine(AssemblyDirectory.FullName, "tf", "c_api.h")} was not found."); Exit(ExitResult.FILE_MISSING); } ProgramLibrary = new TensorFlow(ProgramOptions); ConsoleDriver.Run(ProgramLibrary); if (ProgramLibrary.CleanAndFixup()) { Exit(ExitResult.SUCCESS); } else { Exit(ExitResult.ERROR_DURING_CLEANUP); } }); }
static void Main(string[] args) { if (args.Contains("--debug")) { SetLogger(new SerilogLogger(console: true, debug: true)); Info("Debug mode set."); } else { AppDomain.CurrentDomain.UnhandledException += Program_UnhandledException; SetLogger(new SerilogLogger(console: true, debug: false)); } PrintLogo(); #if WINDOWS && NET461 ParserResult <object> result = new Parser().ParseArguments <Options, ApiOptions, PingOptions, EndpointsOptions, SchemaOptions, VerticesOptions, EdgesOptions, UpsertOptions, QueryOptions, BuiltinOptions, ExecOptions, WinEvtOptions>(args); #else ParserResult <object> result = new Parser().ParseArguments <Options, ApiOptions, PingOptions, EndpointsOptions, SchemaOptions, VerticesOptions, EdgesOptions, UpsertOptions, QueryOptions, BuiltinOptions, ExecOptions>(args); #endif result.WithParsed <ApiOptions>(o => { ApiClient = new ApiClient(GetToken(o), GetRestServerUrl(o), GetGsqlServerUrl(o), GetUser(o), GetPass(o)); if (!ApiClient.Initialized) { Error("The API client did not initialize."); Exit(ExitResult.INVALID_OPTIONS); } }) .WithParsed <PingOptions>(o => { Exit(Echo(o).Result); }) .WithParsed <EndpointsOptions>(o => { Exit(Endpoints(o).Result); }) .WithParsed <SchemaOptions>(o => { Exit(Schema(o).Result); }) .WithParsed <VerticesOptions>(o => { Exit(Vertices(o).Result); }) .WithParsed <EdgesOptions>(o => { Exit(Edges(o).Result); }) .WithParsed <ExecOptions>(o => { Exit(Exec(o).Result); }) #if WINDOWS && NET461 .WithParsed <WinEvtOptions>(o => { Exit(WinEvt(o).Result); }) #endif .WithParsed <UpsertOptions>(o => { Exit(Upsert(o).Result); }) .WithParsed <QueryOptions>(o => { Exit(Query(o).Result); }) .WithParsed <BuiltinOptions>(o => { Exit(Builtin(o).Result); }) #region Print options help .WithNotParsed((IEnumerable <Error> errors) => { HelpText help = GetAutoBuiltHelpText(result); help.Heading = new HeadingInfo("TigerGraph.NET", ApiClient.AssemblyVersion.ToString(3)); help.Copyright = ""; if (errors.Any(e => e.Tag == ErrorType.VersionRequestedError)) { help.Heading = new HeadingInfo("TigerGraph.NET", ApiClient.AssemblyVersion.ToString(3)); help.Copyright = new CopyrightInfo("Allister Beharry", new int[] { 2020 }); Info(help); Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.HelpVerbRequestedError)) { HelpVerbRequestedError error = (HelpVerbRequestedError)errors.First(e => e.Tag == ErrorType.HelpVerbRequestedError); if (error.Type != null) { help.AddVerbs(error.Type); } else { help.AddVerbs(OptionTypes); } Info(help.ToString().Replace("--", "")); Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.HelpRequestedError)) { HelpRequestedError error = (HelpRequestedError)errors.First(e => e.Tag == ErrorType.HelpRequestedError); help.AddVerbs(result.TypeInfo.Current); help.AddOptions(result); help.AddPreOptionsLine($"{result.TypeInfo.Current.Name.Replace("Options", "").ToLower()} options:"); Info(help); Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.NoVerbSelectedError)) { help.AddVerbs(OptionTypes); Info(help); Exit(ExitResult.INVALID_OPTIONS); } else if (errors.Any(e => e.Tag == ErrorType.MissingRequiredOptionError)) { MissingRequiredOptionError error = (MissingRequiredOptionError)errors.First(e => e.Tag == ErrorType.MissingRequiredOptionError); Error("A required option is missing: {0}.", error.NameInfo.NameText); Info(help); Exit(ExitResult.INVALID_OPTIONS); } else if (errors.Any(e => e.Tag == ErrorType.UnknownOptionError)) { UnknownOptionError error = (UnknownOptionError)errors.First(e => e.Tag == ErrorType.UnknownOptionError); help.AddVerbs(OptionTypes); Error("Unknown option: {error}.", error.Token); Info(help); Exit(ExitResult.INVALID_OPTIONS); } else { Error("An error occurred parsing the program options: {errors}.", errors); help.AddVerbs(OptionTypes); Info(help); Exit(ExitResult.INVALID_OPTIONS); } }); #endregion }
public static string GetHelpForInvalidOptions(ParserResult <object> result, IEnumerable <Error> errors) { Type[] stageTypes = GetSubTypes <Stage>(ExplicitAssemblyName); HelpText help = HelpText.AutoBuild(result, h => { h.AddOptions(result); return(h); }, e => { return(e); }, true); help.MaximumDisplayWidth = Console.WindowWidth; help.Copyright = string.Empty; help.Heading = new HeadingInfo("ClassifyBot", Assembly.GetExecutingAssembly().GetName().Version.ToString(3)); help.AddPreOptionsLine(string.Empty); if (errors.Any(e => e.Tag == ErrorType.VersionRequestedError)) { help.Heading = string.Empty; return("{2}{0}v{1}".F(FiggleFonts.Chunky.Render("ClassifyBot"), Assembly.GetExecutingAssembly().GetName().Version.ToString(4), Environment.NewLine)); } else if (errors.Any(e => e.Tag == ErrorType.HelpVerbRequestedError)) { HelpVerbRequestedError error = (HelpVerbRequestedError)errors.First(e => e.Tag == ErrorType.HelpVerbRequestedError); if (error.Type != null) { help.AddVerbs(error.Type); } else { help.AddVerbs(stageTypes); } return(help); } else if (errors.Any(e => e.Tag == ErrorType.HelpRequestedError)) { HelpRequestedError error = (HelpRequestedError)errors.First(e => e.Tag == ErrorType.HelpRequestedError); help.AddOptions(result); return(help); } else if (errors.Any(e => e.Tag == ErrorType.NoVerbSelectedError)) { help.AddVerbs(stageTypes); help.AddPreOptionsLine("No stage selected. Select a stage or verb from the ones listed below:"); return(help); } else if (errors.Any(e => e.Tag == ErrorType.BadVerbSelectedError)) { BadVerbSelectedError error = (BadVerbSelectedError)errors.First(e => e.Tag == ErrorType.BadVerbSelectedError); help.AddVerbs(stageTypes); help.AddPreOptionsLine($"Unknown stage: {error.Token}. Valid stages and verbs are:"); return(help); } else if (errors.Any(e => e.Tag == ErrorType.MissingRequiredOptionError)) { MissingRequiredOptionError error = (MissingRequiredOptionError)errors.First(e => e is MissingRequiredOptionError); help.AddOptions(result); help.AddPreOptionsLine($"A required option or value is missing. The options and values for this stage are: "); return(help); } else if (errors.Any(e => e.Tag == ErrorType.MissingValueOptionError)) { MissingValueOptionError error = (MissingValueOptionError)errors.First(e => e.Tag == ErrorType.MissingValueOptionError); help.AddOptions(result); help.AddPreOptionsLine($"A required option or value is missing. The options and values for this stage are: "); return(help); } else if (errors.Any(e => e.Tag == ErrorType.UnknownOptionError)) { UnknownOptionError error = (UnknownOptionError)errors.First(e => e.Tag == ErrorType.UnknownOptionError); help.AddOptions(result); help.AddPreOptionsLine($"Unknown option: {error.Token}."); return(help); } else { help.AddPreOptionsLine($"An error occurred parsing the program options: {string.Join(" ", errors.Select(e => e.Tag.ToString()).ToArray())}"); help.AddVerbs(stageTypes); return(help); } }
static void Main(string[] args) { SetLogger(new SerilogLogger("NewsAlpha-CLI.log")); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; CO.WriteLine(FiggleFonts.Chunky.Render("News Alpha"), Color.Blue); CO.WriteLine("v{0}", AssemblyVersion.ToString(3), Color.Blue); ParserResult <object> result = new Parser().ParseArguments <SocialNewsOptions, GabOptions, FourChanPolOptions, ArticleOptions>(args); result.WithNotParsed((IEnumerable <Error> errors) => { HelpText help = GetAutoBuiltHelpText(result); help.Copyright = string.Empty; help.AddPreOptionsLine(string.Empty); if (errors.Any(e => e.Tag == ErrorType.VersionRequestedError)) { Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.HelpVerbRequestedError)) { HelpVerbRequestedError error = (HelpVerbRequestedError)errors.First(e => e.Tag == ErrorType.HelpVerbRequestedError); if (error.Type != null) { help.AddVerbs(error.Type); } else { help.AddVerbs(typeof(GabOptions), typeof(FourChanPolOptions), typeof(ArticleOptions)); } Info(help); Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.HelpRequestedError)) { help.AddVerbs(typeof(GabOptions), typeof(FourChanPolOptions), typeof(ArticleOptions)); Info(help); Exit(ExitResult.SUCCESS); } else if (errors.Any(e => e.Tag == ErrorType.NoVerbSelectedError)) { help.AddVerbs(typeof(GabOptions), typeof(FourChanPolOptions), typeof(ArticleOptions)); Error("No index selected. Specify one of: gab, pol."); Info(help); Exit(ExitResult.INVALID_OPTIONS); } else if (errors.Any(e => e.Tag == ErrorType.MissingRequiredOptionError)) { MissingRequiredOptionError error = (MissingRequiredOptionError)errors.First(e => e.Tag == ErrorType.MissingRequiredOptionError); Error("A required option is missing: {0}.", error.NameInfo.NameText); Info(help); Exit(ExitResult.INVALID_OPTIONS); } else if (errors.Any(e => e.Tag == ErrorType.UnknownOptionError)) { UnknownOptionError error = (UnknownOptionError)errors.First(e => e.Tag == ErrorType.UnknownOptionError); help.AddVerbs(typeof(GabOptions), typeof(FourChanPolOptions), typeof(ArticleOptions)); Error("Unknown option: {error}.", error.Token); Info(help); Exit(ExitResult.INVALID_OPTIONS); } else { Error("An error occurred parsing the program options: {errors}.", errors); help.AddVerbs(typeof(GabOptions), typeof(FourChanPolOptions), typeof(ArticleOptions)); Info(help); Exit(ExitResult.INVALID_OPTIONS); } }) .WithParsed <GabOptions>(o => { Search("gab", o.Search, o.ThreatIntent, o.IdentityHate, o.Links, o.Count).Wait(); Exit(ExitResult.SUCCESS); }) .WithParsed <FourChanPolOptions>(o => { Search("4chpol", o.Search, o.ThreatIntent, o.IdentityHate, o.Links, o.Count).Wait(); Exit(ExitResult.SUCCESS); }) .WithParsed <ArticleOptions>(o => { if (!string.IsNullOrEmpty(o.AddTopic)) { AddNewsTopic(o.AddTopic, o.Count).Wait(); Exit(ExitResult.SUCCESS); } else if (!string.IsNullOrEmpty(o.RetrieveTopic)) { RetrieveNewsTopic(o.RetrieveTopic, o.Count).Wait(); Exit(ExitResult.SUCCESS); } }); }
public static void FilterArguments <T>(string[] args, out string[] knownArgs, out string[] unknownArgs) { Parser parser = new Parser((parserSettings) => { parserSettings.HelpWriter = null; }); ParserResult <T> parserResult = parser.ParseArguments <T>(args); if (parserResult.Tag == ParserResultType.NotParsed) { List <int> unknownArgsIndexes = new List <int>(); List <string> unknownArgsList = new List <string>(); NotParsed <T> info = parserResult as NotParsed <T>; foreach (var error in info.Errors) { if (error.Tag == ErrorType.UnknownOptionError) { UnknownOptionError unknownOptionError = error as UnknownOptionError; int uknownArgIndex = Array.FindIndex(args, (arg) => { return(arg.Equals("--" + unknownOptionError.Token) || arg.Equals("-" + unknownOptionError.Token)); }); unknownArgsIndexes.Add(uknownArgIndex); unknownArgsList.Add(args[uknownArgIndex]); for (int argIndex = uknownArgIndex + 1; argIndex < args.Length; argIndex++) { if (IsValueArgument(args, argIndex)) { unknownArgsIndexes.Add(argIndex); unknownArgsList.Add(args[argIndex]); } else { break; } } } } unknownArgs = unknownArgsList.ToArray(); if (unknownArgsIndexes.Count < args.Length) { // if there is some argument left string[] filteredArguments = new string[args.Length - unknownArgsIndexes.Count]; int lastAddedArgIndex = 0; for (int i = 0; i < args.Length; i++) { if (!unknownArgsIndexes.Contains(i)) { filteredArguments[lastAddedArgIndex++] = args[i]; } } knownArgs = filteredArguments; return; } else { knownArgs = new string[0]; return; } } unknownArgs = new string[0]; knownArgs = args; }