public void TryParseAsync(IEnumerable <string> args, Func <T, Task> success) { ParserResult <T> result = Parser.Default.ParseArguments <T>(args); result.WithParsedAsync(success); result.WithNotParsed((IEnumerable <Error> errors) => DisplayHelp(result, errors)); }
/// <summary> /// Main method of console application. /// </summary> /// <param name="args">Command line arguments</param> /// <returns>Return code</returns> public static int Main(string[] args) { // See https://github.com/commandlineparser/commandline/wiki/How-To#q1 Parser parser = new Parser(config => { config.AutoVersion = false; config.HelpWriter = null; }); int returnCode = 1; // default to unsuccessful return code. ParserResult <object> parserResult = parser.ParseArguments <ListSheetsVerb, GenerateVerb, VersionVerb>(args); parserResult.WithParsed <IVerb>(verb => returnCode = verb.Execute()); parserResult.WithNotParsed(errors => { HelpText helpText = HelpText.AutoBuild(parserResult, h => { h.AutoVersion = false; return(HelpText.DefaultParsingErrorsHandler(parserResult, h)); }, example => example); System.Console.WriteLine(helpText); returnCode = 1; }); return(returnCode); }
private static int ValidateArguments(IReadOnlyList <string> args, ParserResult <CmdOptions> parserResult) { var exitCode = 0; if (!args.Any() || args[0].Equals("help", StringComparison.InvariantCultureIgnoreCase)) { exitCode = 1; } switch (parserResult.Tag) { case ParserResultType.NotParsed: parserResult.WithNotParsed(HandleParseError); exitCode = 1; break; case ParserResultType.Parsed: parserResult.WithParsed(x => { if (x.ShouldRunWithDefaultParameters) { exitCode = 0; } }); break; default: throw new ArgumentOutOfRangeException(nameof(ParserResultType)); } return(exitCode); }
public async Task <int> RunAsync() { _cliArgs.WithNotParsed(HandleErrors); await _cliArgs.WithParsedAsync(ExecuteArgumentsAsync); return(0); }
public Int32 Run(String[] args) { if (args == null) { throw new ArgumentNullException(nameof(args)); } Parser parser = new Parser(config => config.HelpWriter = null); ParserResult <Options> parserResult = parser.ParseArguments <Options>(args); parserResult.WithParsed(options => { this.logger.LogInformation($"Processing arguments {JsonConvert.SerializeObject(options)}"); this.processor.Process(options); }); parserResult.WithNotParsed((errs) => { String message = HelpText.AutoBuild(parserResult).ToString(); this.logger.LogError(message); this.logger.LogError("\n"); }); return((Int32)parserResult.Tag); }
static void Main(string[] args) { CommandLineOptions cmdOptions = null; Parser parser = new Parser(); ParserResult <CommandLineOptions> parserResult = parser.ParseArguments <CommandLineOptions>(args); parserResult.WithParsed <CommandLineOptions>(opts => cmdOptions = opts); parserResult.WithNotParsed(errs => { HelpText helpText = HelpText.AutoBuild(parserResult, h => { // Configure HelpText here or create your own and return it h.AdditionalNewLineAfterOption = false; return(HelpText.DefaultParsingErrorsHandler(parserResult, h)); }, e => { return(e); }); Console.Error.Write(helpText); }); if (cmdOptions == null || cmdOptions.Origin.Length == 0 || cmdOptions.Destination.Length == 0) { } else { Initialize(); ExecuteQuery(cmdOptions); } Console.WriteLine("Press enter key to exit"); Console.Read(); }
public void PerformArgs(string[] args) { if (args.Any()) { // https://github.com/commandlineparser/commandline ParserResult <AllOptions> optsResult = Parser.Default.ParseArguments <AllOptions>(args); optsResult.WithParsed <AllOptions>(DisplayStdOptions); optsResult.WithNotParsed(DisplayErrors); ParserResult <object> parserResult = Parser.Default.ParseArguments <SyncVerb, DiffVerb, CheckVerb, FixVerb, ScrubVerb, DupVerb, StatusVerb>(args); parserResult.WithNotParsed(DisplayErrors); // Order is important as commands "Can" be chained" // See http://www.snapraid.it/manual#4.1 Scrubbing for an indication of order parserResult.WithParsed <DiffVerb>(verb => DisplayAndCall(verb, Diff_Click)); parserResult.WithParsed <CheckVerb>(verb => DisplayAndCall(verb, Check_Click)); parserResult.WithParsed <SyncVerb>(verb => DisplayAndCall(verb, Sync_Click)); parserResult.WithParsed <ScrubVerb>(verb => DisplayAndCall(verb, Scrub_Click)); parserResult.WithParsed <DupVerb>(verb => DisplayAndCall(verb, DupFinder_Click)); parserResult.WithParsed <StatusVerb>(verb => DisplayAndCall(verb, btnStatus_Click)); parserResult.WithParsed <FixVerb>(verb => DisplayAndCall(verb, Fix_Click)); // Verbs not done as they do not have buttons yet // list // smart // up // down // pool // devices // touch // rehash } }
static void Main(string[] args) { ParserResult <Options> result = Parser.Default.ParseArguments <Options>(args); result.WithParsed(Run); result.WithNotParsed(PrintError); }
/// <summary> /// </summary> private static void PollIpcServer() { if (!RespondingToIpc) { string Command; string[] Args; if (IPCServer.Recieve(out Command, out Args)) { RespondingToIpc = true; if (Command == "RunCommand") { Logger.Log(LogLevel.Warning, LogCategory.Main, "Recieved ipc command '{0} {1}'.", Command, string.Join(" ", Args)); Parser parser = new Parser(with => with.HelpWriter = new CommandIPCWriter(IPCServer)); ParserResult <object> parserResult = parser.ParseArguments <CommandLineAddOptions, CommandLineDeleteOptions, CommandLineListOptions, CommandLineConfigureOptions>(Args); parserResult.WithParsed <CommandLineAddOptions>(opts => { opts.Run(IPCServer); }); parserResult.WithParsed <CommandLineDeleteOptions>(opts => { opts.Run(IPCServer); }); parserResult.WithParsed <CommandLineListOptions>(opts => { opts.Run(IPCServer); }); parserResult.WithParsed <CommandLineConfigureOptions>(opts => { opts.Run(IPCServer); }); parserResult.WithNotParsed(errs => { }); IPCServer.EndResponse(); } else { Logger.Log(LogLevel.Warning, LogCategory.Main, "Recieved unknown ipc command '{0}'.", Command); IPCServer.Respond("Unknown Command"); } RespondingToIpc = false; } } }
/// <summary> /// Entry point for the application. /// </summary> /// <param name="args">Command-line arguments. Recognized parameters include <c>--debug</c>, /// <c>--input</c>, and <c>--output</c>.</param> public static void Main(string[] args) { ParserResult <CLIArguments> pargs = Parser.Default.ParseArguments <CLIArguments>(args); pargs.WithNotParsed <CLIArguments>(a => Environment.Exit(0)); pargs.WithParsed <CLIArguments>(a => BootstrapApp(a)); }
public override void Run(IEnumerable <string> Arguments) { ParserResult <TOptions> result = CreateParser().ParseArguments <TOptions>(Arguments); result .WithNotParsed(x => { Console.WriteLine(GetHelpText(result)); }) .WithParsed(Run); }
public void Run(string[] args) { ParserResult <Options> parseResult = Parser.Default.ParseArguments <Options>(args); parseResult .WithNotParsed(HandleNotParsedAndBootstrap) .WithParsed(FillDefaultsAndBootstrap); }
private static void Main(string[] args) { GenerationParser generationParser = new GenerationParser(); ParserResult <GenerationOptions> parserResult = Parser.Default.ParseArguments <GenerationOptions> (args); parserResult = parserResult.WithParsed(generationParser.ExecuteOptions); parserResult = parserResult.WithNotParsed(HandleParseError); }
//This program complies with the NO_COLOR standard as it uses the Pastel library. static void Main(string[] args) { Parser parser = new Parser(config => config.HelpWriter = null); ParserResult <Options> parseResult = parser.ParseArguments <Options>(args); parseResult.WithNotParsed(err => DisplayHelp(parseResult)); parseResult.WithParsed(o => { FlagLoader loader = new FlagLoader(); Dictionary <string, PrideFlag> flagDict = loader.LoadFlags("Flag JSONs"); if (!flagDict.TryGetValue(o.FlagType, out PrideFlag flagPath)) { LogError($"{o.FlagType} isn't a valid flag type!\n"); Console.WriteLine("---Flag Types---".Pastel(Color.CornflowerBlue)); foreach (KeyValuePair <string, PrideFlag> pair in flagDict) { WriteHeaders(pair.Value, false, true); } Environment.Exit(1); } WriteHeaders(flagPath); Console.WriteLine("\nMaking image...".Pastel(Color.LightGreen)); ImageProcessing processing = new ImageProcessing(); Bitmap imageFile = null; Bitmap flag = null; try { imageFile = processing.LoadAndResizeBmp(o.ImageFile, o.Size, o.Size); flag = processing.LoadAndResizeBmp("Flags/" + flagPath.FlagFile, o.Size, o.Size); } catch (Exception ex) { LogError(ex.StackTrace, true); } Bitmap croppedBmp = processing.CropPicture(ref imageFile, o.Size, false); Bitmap flagBmp = processing.CropFlag(ref flag, o.PixelMargin); Bitmap finalBmp = processing.StitchTogether(ref flagBmp, ref croppedBmp, o.InnerSize); try { finalBmp.Save(o.Output, ImageFormat.Png); } catch (Exception ex) { LogError(ex.StackTrace, true); } Console.WriteLine($"Success! Saved image \"{o.Output}\"".Pastel(Color.SpringGreen)); Console.WriteLine($"FlagPFP, by Aesthetical#9203, 2021.".Pastel(Color.PaleTurquoise)); Environment.Exit(0); }); }
static void Main(string[] args) { ParserResult <Options> result = Parser.Default.ParseArguments <Options>(args); result.WithParsed(options => Run(options).GetAwaiter().GetResult()); result.WithNotParsed(errors => { Console.Error.WriteLine("Invalid inputs"); }); }
static async Task <int> Main(string[] args) { int exitCode = Constants.SUCCESS_EXIT_CODE; ParserResult <Options> parserResult = Parser.Default.ParseArguments <Options>(args); parserResult .WithNotParsed((errors) => { exitCode = Constants.FAILURE_EXIT_CODE; }); await parserResult .WithParsedAsync(async (options) => { if (!options.Quiet) { if (Enum.TryParse(options.LogLevel, out LogLevel logLevel)) { LoggingContext.Current.SetLogLevel(logLevel); } } else { LoggingContext.Current.SetLogLevel(LogLevel.Silent); } if (!options.Hours.HasValue || options.Hours == 0) { LoggingContext.Current.Debug($"Using the default number of hours ({Constants.DEFAULT_HOURS})"); options.Hours = Constants.DEFAULT_HOURS; } // Composition root string currentDirectory = Directory.GetCurrentDirectory(); LoggingContext.Current.Debug($"The current working directory is {currentDirectory}."); IFileLoader fileLoader = new FileLoader(options, currentDirectory); IHourShifter hourShifter = new HourShifter(options, fileLoader); ProgramBootstrap bootstrap = new ProgramBootstrap(hourShifter); exitCode = await bootstrap.Run(); LoggingContext.Current.Debug($"Returning exit code {exitCode}."); if (!options.Quiet) { Console.Write("Press any key to exit..."); Console.ReadKey(); } }); LoggingContext.Current.Debug($"Returning exit code: {exitCode}"); return(exitCode); }
public static ParserResult <T> PrintErrorsWithNotParsed <T>(this ParserResult <T> parserResult) { return(parserResult.WithNotParsed(e => { var helpText = new HelpText { Copyright = "", Heading = "", AutoVersion = false, AutoHelp = false, AddDashesToOption = true }; helpText = HelpText.DefaultParsingErrorsHandler(parserResult, helpText); helpText.AddOptions(parserResult); Console.WriteLine(helpText); })); }
private static bool SingleErrorWithTag <T>(ParserResult <T> parser, ErrorType tag) { if (parser == null || parser.Tag != ParserResultType.NotParsed) { return(false); } var requestToShowHelp = false; parser.WithNotParsed(errors => { var errorList = errors.ToList(); requestToShowHelp = errorList.Count == 1 && errorList[0].Tag == tag; }); return(requestToShowHelp); }
private void ElucidateForm_Shown(object sender, EventArgs e) { LoadConfigFile(); // display any warnings from the config validation if (srConfig.HasWarnings) { MessageBoxExt.Show( this, $"There are warnings for the configuration file:{Environment.NewLine} - {string.Join(" - ", srConfig.ConfigWarnings)}", "Configuration File Warnings", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { string[] args = Environment.GetCommandLineArgs().Skip(1).ToArray(); if (args.Any()) { // https://github.com/commandlineparser/commandline ParserResult <AllOptions> optsResult = Parser.Default.ParseArguments <AllOptions>(args); optsResult.WithParsed <AllOptions>(DisplayStdOptions); optsResult.WithNotParsed(DisplayErrors); ParserResult <object> parserResult = Parser.Default.ParseArguments <SyncVerb, DiffVerb, CheckVerb, FixVerb, ScrubVerb, DupVerb, StatusVerb>(args); parserResult.WithNotParsed(DisplayErrors); // Order is important as commands "Can" be chained" // See http://www.snapraid.it/manual scrubbing for an indication of order parserResult.WithParsed <DiffVerb>(verb => DisplayAndCall(verb, Diff_Click)); parserResult.WithParsed <CheckVerb>(verb => DisplayAndCall(verb, Check_Click)); parserResult.WithParsed <SyncVerb>(verb => DisplayAndCall(verb, Sync_Click)); parserResult.WithParsed <ScrubVerb>(verb => DisplayAndCall(verb, Scrub_Click)); parserResult.WithParsed <DupVerb>(verb => DisplayAndCall(verb, DupFinder_Click)); parserResult.WithParsed <StatusVerb>(verb => DisplayAndCall(verb, btnStatus_Click)); parserResult.WithParsed <FixVerb>(verb => DisplayAndCall(verb, Fix_Click)); // Verbs not done as they do not have buttons yet // list // smart // up // down // pool // devices // touch // rehash } } }
static void Main(string[] args) { Console.Title = "NetProtect Encrypter"; bool parse_failed = false; string input_file = ""; string output_file = ""; string aes_key = ""; string upload_url = ""; //parse arguments Parser parser = Parser.Default; ParserResult <Options> result = parser.ParseArguments <Options>(args); result = result.WithParsed(options => { Verbose_Output = options.Verbose; input_file = options.File; output_file = options.Output; aes_key = options.Key; upload_url = options.Url; }); result.WithNotParsed(errors => { foreach (Error error in errors) { if (error.Tag == ErrorType.MissingRequiredOptionError) { parse_failed = true; } } }); if (parse_failed) { Environment.Exit(EXIT_INPUT_FAILED); } Console.WriteLine("Encrypting..."); Encrypter.NetProtect protector = new Encrypter.NetProtect(input_file, output_file, aes_key, upload_url); int exit_code = protector.ProtectAssembly(); Environment.Exit(exit_code); }
public static int Main(string[] args) { var writer = new StringWriter(); var parser = new CommandLine.Parser(_ => _.HelpWriter = writer); ParserResult <CommandLineOptions> result = parser.ParseArguments <CommandLineOptions>(args); result.WithNotParsed(_ => { System.Console.WriteLine(writer.ToString()); Environment.Exit(1); }) .WithParsed(options => { if (options.LogLevel >= LogLevel.Debug) { System.Console.WriteLine($"File Parameter: '{options.File}'"); System.Console.WriteLine($"File Count: {options.File?.Count ?? -1}"); System.Console.WriteLine($"File Directory: '{options.Directory}'"); } bool isFileOptionSpecified = (options.File?.Count ?? 0) != 0; bool isDirectoryOptionSpecified = !String.IsNullOrEmpty(options.Directory); if (isFileOptionSpecified ^ isDirectoryOptionSpecified) { var xamlStylerConsole = new XamlStylerConsole(options); xamlStylerConsole.Process(isFileOptionSpecified ? ProcessType.File : ProcessType.Directory); } else { string errorString = (isFileOptionSpecified && isDirectoryOptionSpecified) ? "Cannot specify both file(s) and directory" : "Must specify file(s) or directory"; System.Console.WriteLine($"\nError: {errorString}\n"); Environment.Exit(1); } }); return(0); }
public static StageResult MarshalOptionsForStage(string[] args, string explicitAssemblyName, out Stage stage, out string optionsHelp) { optionsHelp = string.Empty; Stage s = null; Parser p = new Parser(); Type[] types = GetSubTypes <Stage>(explicitAssemblyName); if ((types == null || types.Length == 0) && explicitAssemblyName.IsNotEmpty()) { stage = null; L.Error("No assemblies matching the name {0}.dll in directory {1} were found.".F(explicitAssemblyName, AssemblyExtensions.GetExecutingAssemblyDirectoryName())); optionsHelp = "You must enter an assembly name to explicitly load. Valid assembly names are : {0}." .F(string.Join(", ", AllLoadedAssemblies.Select(a => a.GetName().Name).ToArray())); return(StageResult.INVALID_OPTIONS); } else { ClassifyBotLoadedAssemblies = types.Select(t => t.Assembly).Distinct().ToList(); if (ClassifyBotLoadedAssemblies.Count == 1) { L.Information("Loaded 1 ClassifyBot assembly: {1}.", ClassifyBotLoadedAssemblies.Count(), ClassifyBotLoadedAssemblies.Select(a => a.FullName)); } else { L.Information("Loaded {0} ClassifyBot assemblies: {1}.", ClassifyBotLoadedAssemblies.Count(), ClassifyBotLoadedAssemblies.Select(a => a.FullName)); } } ParserResult <object> options = p.ParseArguments(args, types); string oh = string.Empty; StageResult sr = StageResult.INVALID_OPTIONS; options .WithNotParsed((errors) => { oh = GetHelpForInvalidOptions(options, errors); sr = StageResult.INVALID_OPTIONS; }) .WithParsed((o) => { s = (Stage)o; sr = StageResult.CREATED; }); optionsHelp = oh; stage = s; return(sr); }
public static StageResult MarshalOptionsForStage <T>(string[] args, out T stage, out string optionsHelp) { optionsHelp = string.Empty; T s = default(T); Parser p = new Parser(); ParserResult <object> options = p.ParseArguments(args, typeof(T)); string oh = string.Empty; StageResult sr = StageResult.INVALID_OPTIONS; options .WithNotParsed((errors) => { oh = GetHelpForInvalidOptions(options, errors); sr = StageResult.INVALID_OPTIONS; }) .WithParsed((o) => { s = (T)o; sr = StageResult.CREATED; }); optionsHelp = oh; stage = s; return(sr); }
public static void Main(string[] args) { ParserResult <Options> result = Parser.Default.ParseArguments <Options>(args); if (result.Tag == ParserResultType.NotParsed) { return; } result.WithNotParsed(errs => { var helpText = HelpText.AutoBuild(result, h => { return(HelpText.DefaultParsingErrorsHandler(result, h)); }, e => { return(e); }); Console.WriteLine(helpText); }); var options = result.MapResult(o => o, xs => new Options()); BenchmarkType b = (BenchmarkType)options.Benchmark; Console.WriteLine("Benchmark Arguments:"); Console.WriteLine(" Benchmark = {0}", options.Benchmark); Console.WriteLine(" Number of threads = {0}", options.ThreadCount); Console.WriteLine(" Thread NUMA mapping = {0}", options.NumaStyle); Console.WriteLine(" Read percent = {0}", options.ReadPercent); Console.WriteLine(" Distribution = {0}", options.Distribution); if (b == BenchmarkType.Ycsb) { var test = new FASTER_YcsbBenchmark(options.ThreadCount, options.NumaStyle, options.Distribution, options.ReadPercent); test.Run(); } }
private static int Main(string[] args) { #if DEBUG // short command syntax if (args?.Length > 0) { switch (args[0]) { case "f": { ReplaceArgs("find"); break; } case "r": { ReplaceArgs("replace"); break; } } void ReplaceArgs(string commandName) { Array.Resize(ref args, args.Length + 1); for (int i = args.Length - 1; i >= 2; i--) { args[i] = args[i - 1]; } args[0] = commandName; args[1] = "-c"; } } #endif try { Parser parser = CreateParser(ignoreUnknownArguments: true); if (args == null || args.Length == 0) { HelpCommand.WriteCommandsHelp(); return(ExitCodes.Match); } var success = true; var help = false; ParserResult <BaseCommandLineOptions> defaultResult = parser .ParseArguments <BaseCommandLineOptions>(args) .WithParsed(options => { if (!options.Help) { return; } string?commandName = args?.FirstOrDefault(); Command?command = (commandName != null) ? CommandLoader.LoadCommand(typeof(Program).Assembly, commandName) : null; success = ParseVerbosityAndOutput(options); if (!success) { return; } WriteArgs(args); if (command != null) { HelpCommand.WriteCommandHelp(command); } else { HelpCommand.WriteCommandsHelp(); } help = true; }) #if DEBUG .WithNotParsed(_ => { }); #else ; #endif if (!success) { return(ExitCodes.Error); } if (help) { return(ExitCodes.Match); } parser = CreateParser(); ParserResult <object> parserResult = parser.ParseArguments < CopyCommandLineOptions, DeleteCommandLineOptions, EscapeCommandLineOptions, FindCommandLineOptions, HelpCommandLineOptions, ListPatternsCommandLineOptions, MatchCommandLineOptions, MoveCommandLineOptions, SpellcheckCommandLineOptions, RenameCommandLineOptions, ReplaceCommandLineOptions, SplitCommandLineOptions, SyncCommandLineOptions >(args); parserResult.WithNotParsed(_ => { var helpText = new HelpText(SentenceBuilder.Create(), HelpCommand.GetHeadingText()); helpText = HelpText.DefaultParsingErrorsHandler(parserResult, helpText); VerbAttribute?verbAttribute = parserResult.TypeInfo.Current.GetCustomAttribute <VerbAttribute>(); if (verbAttribute != null) { helpText.AddPreOptionsText(Environment.NewLine + HelpCommand.GetFooterText(verbAttribute.Name)); } Console.Error.WriteLine(helpText); success = false; }); if (!success) { return(ExitCodes.Error); } parserResult.WithParsed <AbstractCommandLineOptions>(options => { success = ParseVerbosityAndOutput(options); if (success) { WriteArgs(args); } }); if (!success) { return(ExitCodes.Error); } return(parserResult.MapResult( (CopyCommandLineOptions options) => Copy(options), (MoveCommandLineOptions options) => Move(options), (SyncCommandLineOptions options) => Sync(options), (DeleteCommandLineOptions options) => Delete(options), (EscapeCommandLineOptions options) => Escape(options), (FindCommandLineOptions options) => Find(options), (HelpCommandLineOptions options) => Help(options), (ListPatternsCommandLineOptions options) => ListPatterns(options), (MatchCommandLineOptions options) => Match(options), (SpellcheckCommandLineOptions options) => Spellcheck(options), (RenameCommandLineOptions options) => Rename(options), (ReplaceCommandLineOptions options) => Replace(options), (SplitCommandLineOptions options) => Split(options), _ => ExitCodes.Error)); } catch (Exception ex) { WriteError(ex); } finally { Out?.Dispose(); Out = null; } return(ExitCodes.Error); }
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); } }); }
private static int Main(string[] args) { #if DEBUG if (args.LastOrDefault() == "--debug") { WriteArgs(args.Take(args.Length - 1).ToArray(), Verbosity.Quiet); return(ExitCodes.NotSuccess); } #endif Parser parser = null; try { parser = CreateParser(ignoreUnknownArguments: true); if (args == null || args.Length == 0) { HelpCommand.WriteCommandsHelp(); return(ExitCodes.Success); } bool?success = null; ParserResult <BaseCommandLineOptions> defaultResult = parser .ParseArguments <BaseCommandLineOptions>(args) .WithParsed(options => { if (!options.Help) { return; } string commandName = args?.FirstOrDefault(); Command command = (commandName != null) ? CommandLoader.LoadCommand(typeof(Program).Assembly, commandName) : null; if (!ParseVerbosityAndOutput(options)) { success = false; return; } WriteArgs(args, Verbosity.Diagnostic); if (command != null) { HelpCommand.WriteCommandHelp(command); } else { HelpCommand.WriteCommandsHelp(); } success = true; }); if (success == false) { return(ExitCodes.Error); } if (success == true) { return(ExitCodes.Success); } parser = CreateParser(); ParserResult <object> parserResult = parser.ParseArguments( args, new Type[] { typeof(AnalyzeCommandLineOptions), typeof(FixCommandLineOptions), typeof(FormatCommandLineOptions), typeof(GenerateDocCommandLineOptions), typeof(GenerateDocRootCommandLineOptions), typeof(HelpCommandLineOptions), typeof(ListSymbolsCommandLineOptions), typeof(LogicalLinesOfCodeCommandLineOptions), typeof(MigrateCommandLineOptions), typeof(PhysicalLinesOfCodeCommandLineOptions), typeof(RenameSymbolCommandLineOptions), typeof(SpellcheckCommandLineOptions), #if DEBUG typeof(AnalyzeAssemblyCommandLineOptions), typeof(FindSymbolsCommandLineOptions), typeof(GenerateSourceReferencesCommandLineOptions), typeof(ListVisualStudioCommandLineOptions), typeof(ListReferencesCommandLineOptions), typeof(SlnListCommandLineOptions), #endif }); parserResult.WithNotParsed(e => { if (e.Any(f => f.Tag == ErrorType.VersionRequestedError)) { Console.WriteLine(typeof(Program).GetTypeInfo().Assembly.GetName().Version); success = false; return; } var helpText = new HelpText(SentenceBuilder.Create(), HelpCommand.GetHeadingText()); helpText = HelpText.DefaultParsingErrorsHandler(parserResult, helpText); VerbAttribute verbAttribute = parserResult.TypeInfo.Current.GetCustomAttribute <VerbAttribute>(); if (verbAttribute != null) { helpText.AddPreOptionsText(Environment.NewLine + HelpCommand.GetFooterText(verbAttribute.Name)); } Console.Error.WriteLine(helpText); success = false; }); if (success == true) { return(ExitCodes.Success); } if (success == false) { return(ExitCodes.Error); } parserResult.WithParsed <AbstractCommandLineOptions>( options => { if (ParseVerbosityAndOutput(options)) { WriteArgs(args, Verbosity.Diagnostic); } else { success = false; } }); if (success == false) { return(ExitCodes.Error); } return(parserResult.MapResult( (MSBuildCommandLineOptions options) => { switch (options) { case AnalyzeCommandLineOptions analyzeCommandLineOptions: return AnalyzeAsync(analyzeCommandLineOptions).Result; case FixCommandLineOptions fixCommandLineOptions: return FixAsync(fixCommandLineOptions).Result; case FormatCommandLineOptions formatCommandLineOptions: return FormatAsync(formatCommandLineOptions).Result; case GenerateDocCommandLineOptions generateDocCommandLineOptions: return GenerateDocAsync(generateDocCommandLineOptions).Result; case GenerateDocRootCommandLineOptions generateDocRootCommandLineOptions: return GenerateDocRootAsync(generateDocRootCommandLineOptions).Result; case ListSymbolsCommandLineOptions listSymbolsCommandLineOptions: return ListSymbolsAsync(listSymbolsCommandLineOptions).Result; case LogicalLinesOfCodeCommandLineOptions logicalLinesOfCodeCommandLineOptions: return LogicalLinesOrCodeAsync(logicalLinesOfCodeCommandLineOptions).Result; case PhysicalLinesOfCodeCommandLineOptions physicalLinesOfCodeCommandLineOptions: return PhysicalLinesOfCodeAsync(physicalLinesOfCodeCommandLineOptions).Result; case RenameSymbolCommandLineOptions renameSymbolCommandLineOptions: return RenameSymbolAsync(renameSymbolCommandLineOptions).Result; case SpellcheckCommandLineOptions spellcheckCommandLineOptions: return SpellcheckAsync(spellcheckCommandLineOptions).Result; #if DEBUG case FindSymbolsCommandLineOptions findSymbolsCommandLineOptions: return FindSymbolsAsync(findSymbolsCommandLineOptions).Result; case GenerateSourceReferencesCommandLineOptions generateSourceReferencesCommandLineOptions: return GenerateSourceReferencesAsync(generateSourceReferencesCommandLineOptions).Result; case ListReferencesCommandLineOptions listReferencesCommandLineOptions: return ListReferencesAsync(listReferencesCommandLineOptions).Result; case SlnListCommandLineOptions slnListCommandLineOptions: return SlnListAsync(slnListCommandLineOptions).Result; #endif default: throw new InvalidOperationException(); } }, (AbstractCommandLineOptions options) => { switch (options) { case HelpCommandLineOptions helpCommandLineOptions: return Help(helpCommandLineOptions); case MigrateCommandLineOptions migrateCommandLineOptions: return Migrate(migrateCommandLineOptions); #if DEBUG case AnalyzeAssemblyCommandLineOptions analyzeAssemblyCommandLineOptions: return AnalyzeAssembly(analyzeAssemblyCommandLineOptions); case ListVisualStudioCommandLineOptions listVisualStudioCommandLineOptions: return ListVisualStudio(listVisualStudioCommandLineOptions); #endif default: throw new InvalidOperationException(); } }, _ => ExitCodes.Error)); } catch (Exception ex) when(ex is AggregateException || ex is FileNotFoundException || ex is InvalidOperationException) { WriteError(ex); } finally { parser?.Dispose(); Out?.Dispose(); Out = null; } return(ExitCodes.Error); }
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(); MethodInfo parseArgumentsMethod = typeof(ParserExtensions).GetMethods().Where(m => m.IsGenericMethod && m.Name == "ParseArguments" && m.GetGenericArguments().Count() == BenchmarkOptionTypes.Count()).First(); Parser p = new Parser(); ParserResult <object> result = (ParserResult <object>)parseArgumentsMethod.MakeGenericMethod(BenchmarkOptionTypes).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("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}") .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); }); }
private static int Main(string[] args) { //WriteLine($"Orang Command Line Tool version {typeof(Program).GetTypeInfo().Assembly.GetName().Version}"); //WriteLine("Copyright (c) Josef Pihrt. All rights reserved."); //WriteLine(); try { Parser parser = CreateParser(ignoreUnknownArguments: true); bool help = false; ParserResult <BaseCommandLineOptions> defaultResult = parser .ParseArguments <BaseCommandLineOptions>(args) .WithParsed(options => { if (!options.Help) { return; } string?commandName = args?.FirstOrDefault(); Command?command = (commandName != null) ? CommandLoader.LoadCommand(typeof(Program).Assembly, commandName) : null; ParseVerbosityAndOutput(options); WriteArgs(args); if (command != null) { HelpCommand.WriteCommandHelp(command); } else { HelpCommand.WriteCommandsHelp(); } help = true; }) #if DEBUG .WithNotParsed(_ => { }); #else ; #endif if (help) { return(0); } bool success = true; parser = CreateParser(); ParserResult <object> parserResult = parser.ParseArguments < CopyCommandLineOptions, DeleteCommandLineOptions, EscapeCommandLineOptions, FindCommandLineOptions, HelpCommandLineOptions, ListPatternsCommandLineOptions, MatchCommandLineOptions, MoveCommandLineOptions, RenameCommandLineOptions, ReplaceCommandLineOptions, SplitCommandLineOptions >(args); parserResult.WithNotParsed(_ => { var helpText = new HelpText(SentenceBuilder.Create(), HelpCommand.GetHeadingText()); helpText = HelpText.DefaultParsingErrorsHandler(parserResult, helpText); VerbAttribute?verbAttribute = parserResult.TypeInfo.Current.GetCustomAttribute <VerbAttribute>(); if (verbAttribute != null) { helpText.AddPreOptionsText(Environment.NewLine + HelpCommand.GetFooterText(verbAttribute.Name)); } Console.Error.WriteLine(helpText); success = false; }); if (!success) { return(2); } parserResult.WithParsed <AbstractCommandLineOptions>(options => { success = ParseVerbosityAndOutput(options); WriteArgs(args); }); if (!success) { return(2); } return(parserResult.MapResult( (CopyCommandLineOptions options) => Copy(options), (MoveCommandLineOptions options) => Move(options), (DeleteCommandLineOptions options) => Delete(options), (EscapeCommandLineOptions options) => Escape(options), (FindCommandLineOptions options) => Find(options), (HelpCommandLineOptions options) => Help(options), (ListPatternsCommandLineOptions options) => ListPatterns(options), (MatchCommandLineOptions options) => Match(options), (RenameCommandLineOptions options) => Rename(options), (ReplaceCommandLineOptions options) => Replace(options), (SplitCommandLineOptions options) => Split(options), _ => 2)); } catch (Exception ex) { WriteError(ex); } finally { Out?.Dispose(); Out = null; } return(2); }