public static void Main(string[] args) { ParserResult <Options> result = Parser.Default.ParseArguments <Options>(args); if (result.Tag == ParserResultType.NotParsed) { return; } var options = result.MapResult(o => o, xs => new Options()); BenchmarkType b = (BenchmarkType)options.Benchmark; if (b == BenchmarkType.Ycsb) { var test = new FASTER_YcsbBenchmark(options.ThreadCount, options.NumaStyle, options.Distribution, options.ReadPercent, options.Backup); test.Run(); } else if (b == BenchmarkType.SpanByte) { var test = new FasterSpanByteYcsbBenchmark(options.ThreadCount, options.NumaStyle, options.Distribution, options.ReadPercent, options.Backup); test.Run(); } else if (b == BenchmarkType.ConcurrentDictionaryYcsb) { var test = new ConcurrentDictionary_YcsbBenchmark(options.ThreadCount, options.NumaStyle, options.Distribution, options.ReadPercent); test.Run(); } }
static void Main(string[] args) { Console.WriteLine("LYRA Command Line Client"); Console.WriteLine("Version: " + "0.5.3"); ParserResult <Options> result = Parser.Default.ParseArguments <Options>(args); using (var host = CreateHost()) { host.Start(); var client = host.Services.GetService <IHostedService>(); // activate api serivce grain // debug test var c = client; //var gf = host.Services.GetService<IGrainFactory>(); //var nodeApi = c.Node; var wm = new WalletManager(); int mapresult = result.MapResult((Options options) => wm.RunWallet(options).Result, _ => CommandLineError()); if (mapresult != 0) { if (mapresult == -2) { Console.WriteLine("Unsupported parameters"); } } } }
static async Task Main(string[] args) { IConfiguration configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .Build(); CosmosClient client = new CosmosClientBuilder(configuration.GetConnectionString("Cosmos")) .WithApplicationName("OnDotNetRocks") .Build(); await Program.InitializeContainersAsync(client); // Parse command line arguments ParserResult <CommandLineOptions> result = Parser.Default.ParseArguments <CommandLineOptions>(args); try { await result.MapResult(async options => await Program.ParseOptionsAndRunAsync(options, client), _ => Task.CompletedTask); Console.WriteLine("Job's done."); } catch (ArgumentException exception) { Console.WriteLine(exception.Message); Console.WriteLine("Options: --processor \"<name>\": Starts a processor instance with a particular name."); Console.WriteLine(" --estimator: Starts an estimator to watch for changes."); Console.WriteLine(" --writer <number>: Starts a writer for a fixed number of documents."); } }
private static CommandOptions ParseArguments(string[] args) { // Parse command line options ParserResult <object> parserResult = Parser.Default.ParseArguments < ProjectCommandOptions, RepositoryCommandOptions, PullRequestCommandOptions, BuildDefinitionCommandOptions>(args); // Map results after parsing CommandOptions commandOptions = null; parserResult.MapResult <ProjectCommandOptions, RepositoryCommandOptions, PullRequestCommandOptions, BuildDefinitionCommandOptions, object>( (ProjectCommandOptions opts) => commandOptions = opts, (RepositoryCommandOptions opts) => commandOptions = opts, (PullRequestCommandOptions opts) => commandOptions = opts, (BuildDefinitionCommandOptions opts) => commandOptions = opts, (errs) => 1); // Return null if not able to parse if (parserResult.Tag == ParserResultType.NotParsed) { HelpText helpText = HelpText.AutoBuild(parserResult); helpText.AddEnumValuesToHelpText = true; helpText.AddOptions(parserResult); commandOptions = null; } // Return list of parsed commands return(commandOptions); }
static void VarLenServer(string[] args) { Console.WriteLine("FASTER variable-length KV server"); ParserResult <Options> result = Parser.Default.ParseArguments <Options>(args); if (result.Tag == ParserResultType.NotParsed) { return; } var opts = result.MapResult(o => o, xs => new Options()); opts.GetSettings(out var logSettings, out var checkpointSettings, out var indexSize); // Create a new instance of the FasterKV, customized for variable-length blittable data (represented by SpanByte) // With SpanByte, keys and values are stored inline in the FASTER log as [ 4 byte length | payload ] var store = new FasterKV <SpanByte, SpanByte>(indexSize, logSettings, checkpointSettings); if (opts.Recover) { store.Recover(); } // Create a new server based on above store. You specify additional details such as the serializer (to read and write // from and to the wire) and functions (to communicate with FASTER via IFunctions) var server = new FasterKVServer <SpanByte, SpanByte, SpanByte, SpanByteAndMemory, SpanByteFunctionsForServer <long>, SpanByteSerializer> (store, wp => new SpanByteFunctionsForServer <long>(wp), opts.Address, opts.Port, new SpanByteSerializer(), default); server.Start(); Console.WriteLine("Started server"); Thread.Sleep(Timeout.Infinite); }
static void FixedLenServer(string[] args) { Console.WriteLine("FASTER fixed-length (binary) KV server"); ParserResult <Options> result = Parser.Default.ParseArguments <Options>(args); if (result.Tag == ParserResultType.NotParsed) { return; } var opts = result.MapResult(o => o, xs => new Options()); opts.GetSettings(out var logSettings, out var checkpointSettings, out var indexSize); // We use blittable structs Key and Value to construct a costomized server for fixed-length types var store = new FasterKV <Key, Value>(indexSize, logSettings, checkpointSettings); if (opts.Recover) { store.Recover(); } // We specify FixedLenSerializer as our in-built serializer for blittable (fixed length) types // This server can be used with compatible clients such as FixedLenClient and FASTER.benchmark var server = new FasterKVServer <Key, Value, Input, Output, Functions, FixedLenSerializer <Key, Value, Input, Output> > (store, e => new Functions(), opts.Address, opts.Port); server.Start(); Thread.Sleep(Timeout.Infinite); }
private static int ParseFirstArgNotVerb(string[] p_Args, Parser p_Parser) { // if no verb specified print help message if (p_Args.Length == 1) { List <string> _args = new(p_Args) { "help" }; p_Args = _args.ToArray(); } // Just make verb firts lol if (!new List <string>() { "help", "--help", "version", "--version" }.Contains(p_Args[0])) { string temp = p_Args[0]; p_Args[0] = p_Args[1]; p_Args[1] = temp; } ParserResult <object> result = p_Parser.ParseArguments <BaseOptions, AddOptions, RemoveOptions, RenameOptions, ExtractOptions, ListOptions, CatOptions>(p_Args); return(result.MapResult( (AddOptions p_Options) => RunAdd(p_Options), (RemoveOptions p_Options) => RunRemove(p_Options), (RenameOptions p_Options) => RunRename(p_Options), (ExtractOptions p_Options) => RunExtract(p_Options), (ListOptions p_Options) => RunList(p_Options), (CatOptions p_Options) => RunCat(p_Options), p_Errors => DisplayHelp(result) )); }
static int Main(string[] args) { ParserResult <object> parserResult = Parser.Default.ParseArguments(args, ValidVerbs); ReturnCode retcode = parserResult.MapResult((VerbBase opts) => opts.RunAsPipe(), errs => ReturnCode.InputError); return((int)retcode); }
public static int Run(string[] p_Args) { Parser parser = new(p_With => { p_With.HelpWriter = null; p_With.CaseInsensitiveEnumValues = true; p_With.CaseSensitive = false; }); // Default parsing with verb as first arg ParserResult <object> result = parser.ParseArguments <BaseOptions, AddOptions, RemoveOptions, RenameOptions, ExtractOptions, ListOptions, CatOptions>(p_Args); return(result.MapResult( (AddOptions p_Options) => RunAdd(p_Options), (RemoveOptions p_Options) => RunRemove(p_Options), (RenameOptions p_Options) => RunRename(p_Options), (ExtractOptions p_Options) => RunExtract(p_Options), (ListOptions p_Options) => RunList(p_Options), (CatOptions p_Options) => RunCat(p_Options), p_Errors => { foreach (Error error in p_Errors) { if (error.Tag == ErrorType.BadVerbSelectedError) { return ParseFirstArgNotVerb(p_Args, parser); // if first arg is not verb it is must be PackedPath } } return DisplayHelp(result); } )); }
/// <summary> /// Entry point for the application /// </summary> /// <param name="args">application arguments</param> /// <returns>a task that represents the asynchronous operation</returns> private static async Task <int> Main(string[] args) { ParserResult <object> result = Parser.Default.ParseArguments <SubmitOptions, GetOptions, GetFileBySha256Options>(args); try { await result.MapResult( async (SubmitOptions options) => await SubmitAsync(options), async (GetOptions options) => await GetAsync(options), async (GetFileBySha256Options options) => await GetFileBySha256Async(options), async (IEnumerable <Error> errors) => await HandleErrorsAsync(errors)); } catch (CLIENT.EvaluationServiceException ex) { await Console.Error.WriteLineAsync($"An error has occurred while calling the Evaluation Service: {ex}"); return((int)ProgramExitCodes.EvaluationServiceError); } catch (Exception ex) { await Console.Error.WriteLineAsync($"An unhandled error has occurred: {ex}"); return((int)ProgramExitCodes.GenericError); } return((int)ProgramExitCodes.Ok); }
private static int ParseArgumentsAndExecute(string[] args) { ParserResult <SynchronizerArguments> parseResult = Parser.Default.ParseArguments <SynchronizerArguments>(args); _log.Info($"Parsing program arguments: {String.Join(" ", args)}"); return(parseResult.MapResult ( synchronizerArguments => { synchronizerArguments.Validate(); _log.Info("Initializing injection container"); Container container = SynchronizerContainerRegistrator.Register(); container.GetInstance <IServerUri>().Uri = synchronizerArguments.EtcdEndpoint; _engine = container.GetInstance <IEngine>(); _mainTask = Task.Run(() => { _engine.Start(); return 0; }); Console.CancelKeyPress += OnExit; _closing.WaitOne(); return _mainTask.Result; }, notParsedErrors => { HandleParseErrors(notParsedErrors.GetEnumerator()); return -1; } )); }
private static void Main(string[] args) { Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; ParserResult <Options> result = Parser.Default.ParseArguments <Options>(args); result.MapResult(options => Run(options), _ => 1); }
public static async Task Either <T>(this ParserResult <T> result, Func <T, Task> parsedFunc, Func <IEnumerable <Error>, Task> notParsedFunc) { await result.MapResult( async result => await parsedFunc(result), async errors => await notParsedFunc(errors)); }
static void Main(string[] args) { Console.CancelKeyPress += (sender, eventArgs) => { eventArgs.Cancel = true; tokenSource.Cancel(); }; ParserResult <Options> parseResults = Parser.Default.ParseArguments <Options>(args); options = parseResults.MapResult( parsed => parsed, notParsed => { return(default(Options)); }); if (options == default(Options)) { return; } if (options.csvoutput != null) { //Create CSV file and write header row. csvFile = new CSVFile(options.csvoutput); var columnlist = new List <string> { "Message#", "Date Time", "Routing Key", "Exchange", "Body" }; csvFile.WriteRow(columnlist); var connectionString = options.AMQP; Console.WriteLine("Trace is running. Ctrl-C to exit"); HandleDelivery(); try { using (ConnectAndSubscribe(connectionString)) { tokenSource.Token.WaitHandle.WaitOne(); } Console.WriteLine("Shutdown"); } catch (Exception e) { Console.Out.WriteLine(e.Message); } } }
public static JObject MapOk <T1>(ParserResult <T1> result) { return(result.MapResult(variablesObj => JObject.FromObject(variablesObj, JsonSerializer.Create(new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })), errors => { Console.WriteLine($"Failed to read parameterObj: {string.Join(",", errors)} "); return null; })); }
private static int Main(string[] args) { ParserResult <object> result = Parser.Default.ParseArguments <ParseOptions, ShellOptions>(args); return(result.MapResult( (ParseOptions opts) => RunMain(opts), (ShellOptions opts) => RunShell(opts), errs => 1)); }
internal bool Parse(string[] args) { ParserResult <Options> result = Parser.Default.ParseArguments <Options>(args); if (result.Tag == ParserResultType.NotParsed) { return(false); } Options = result.MapResult(o => o, xs => new Options());
private static async Task <int> Main(string[] args) { result = Parser.Default.ParseArguments <DeployWithSlotOptions, DeployInplaceOptions>(args); return(await result.MapResult( async (DeployWithSlotOptions opts) => await Run(opts), async (DeployInplaceOptions opts) => await Run(opts), async errs => await HandleParseErrorAsync(errs))); }
public string Process(string[] args) { ParserResult <PredictOption> parsedResult = Parser.Default.ParseArguments <PredictOption>(args); string result = parsedResult.MapResult( opts => HandlePredictCommand(opts), errors => ShowError(errors) ); return(result); }
internal TestLoader(string[] args) { error = true; ParserResult <Options> result = Parser.Default.ParseArguments <Options>(args); if (result.Tag == ParserResultType.NotParsed) { return; } Options = result.MapResult(o => o, xs => new Options());
// Using EF Core - for interfacing with data // with: Npgsql - for default data storage // with: InMemoryDatabase - for unit testing // with: FileContextCore - for feature parity // Using MSTest - for unit testing // Using CommandLine - for parsing command line args static int Main(string[] args) { // Valid contexts are: Remote (PostgreSQL) or Local (local JSON file) DbContextOptions <BordsContext> options = DataContexts.Local; using BordsContext db = new BordsContext(options); BoardLib lib = new BoardLib(db); // Parse and perform command ParserResult <object> parsedArguments = Parser.Default.ParseArguments < ListOptions, NewTaskOptions, DeleteTaskOptions, CheckTaskOptions, MoveTaskOptions, EditTaskOptions, PrioritizeTaskOptions>(args); try { bool GracefullyExecuted = parsedArguments .MapResult( (ListOptions opts) => true, (NewTaskOptions opts) => ( (opts.Boardname == null) ? lib.CreateTask(opts.Description, opts.Priority) : lib.CreateTask(opts.Boardname, opts.Description, opts.Priority) ) is Task ? true : false, (DeleteTaskOptions opts) => lib.DeleteTask(opts.TaskId) is Task ? true : false, (CheckTaskOptions opts) => lib.ToggleTaskComplete(opts.TaskId) is Task ? true : false, (MoveTaskOptions opts) => lib.MoveTask(opts.TaskId, opts.DestinationBoard) is Task ? true : false, (EditTaskOptions opts) => lib.DescribeTask(opts.TaskId, opts.NewDescription) is Task ? true : false, (PrioritizeTaskOptions opts) => lib.PrioritizeTask(opts.TaskId, opts.NewPriority) is Task ? true : false, errs => false); lib.CleanupEmptyBoards(); lib.PrintAll(); return(GracefullyExecuted ? 0 : 1); } catch (Exception ex) { if (ex is BadTaskIdException) { Console.WriteLine("A Task with that ID was not found"); } else if (ex is PriorityOutOfBoundsException) { Console.WriteLine("Priority must be an integer of 1, 2, or 3"); } else { throw ex; } return(1); } }
public static IndexerParameters ParseCommandLine(IEnumerable <string> args) { ParserResult <IndexerParameters> res = Parser.Default.ParseArguments <IndexerParameters>(args); IndexerParameters result = res.MapResult(options => { return(options); }, errors => { return(null); }); return(result); }
public async static Task Main(string[] args) { Parser parser = new Parser(config => { config.CaseInsensitiveEnumValues = true; }); ParserResult <CommandLineOptions> parserResult = parser.ParseArguments <CommandLineOptions>(args); await parserResult.MapResult( options => { Generate(options); return(Task.CompletedTask); }, (_) => Task.CompletedTask) .ConfigureAwait(true); }
public static async Task <int> MapResult( this ParserResult <object> result, Func <SyncOpts, Task <int> > parsedSync, Func <PrintOpts, Task <int> > parsedPrint, Func <ReadOpts, Task <int> > parsedRead, Func <ListOpts, Task <int> > parsedList, Func <NotParsed <object>, Task <int> > notParsed) => await result.MapResult( parsedSync, parsedPrint, parsedRead, parsedList, notParsedFunc : _ => notParsed((NotParsed <object>)result));
static int Main(string[] args) { ParserResult <object> operation = Parser.Default .ParseArguments <ExtractWikiDbOperation, GenerateDictionaryOperation, QueryDictionaryOperation, SummarizeDictionaryOperation, CleanDictionaryOperation>(args); return(operation.MapResult( (ExtractWikiDbOperation op) => op.Extract(), (GenerateDictionaryOperation op) => op.Generate(), (QueryDictionaryOperation op) => op.Query(), (SummarizeDictionaryOperation op) => op.Summarize(), (CleanDictionaryOperation op) => op.Clean(), _ => 1)); }
public string GetParseResult(params string[] args) { using (Parser parser = CreateParser()) { ParserResult <object> result = parser.ParseVerbs( args, dynamicVerbFactory, typeof(BuildVerb), typeof(GenerateVerb), typeof(GetVerb), typeof(SetVerb), typeof(UpdateVerb), typeof(InstallVerb), typeof(ScanSdksVerb), typeof(ShowLogVerb), typeof(MigrateCliVerb)); return(result .MapResult((object verb) => ConvertToString(verb), (errors) => ConvertError(result))); } }
private static void Main(string[] args) { // Initializing string executablePath = (Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly()).Location; string location = executablePath; if (string.IsNullOrEmpty(location)) { location = Environment.GetCommandLineArgs().FirstOrDefault(); } RunnerFolder = Path.GetDirectoryName(location); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Platform = Platform.Windows; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Platform = Platform.Linux; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { Platform = Platform.MacOS; } else { Console.Error.WriteLine("The current platform is not supported. Supported platforms are: Windows, Linux and MacOS."); Environment.Exit(-1); return; } // *** Console.CancelKeyPress += Console_CancelKeyPress; AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; AppDomain.CurrentDomain.DomainUnload += CurrentDomain_ProcessExit; Parser parser = new Parser(settings => { settings.AutoHelp = true; settings.AutoVersion = true; settings.EnableDashDash = true; settings.HelpWriter = null; }); ParserResult <Options> result = parser.ParseArguments <Options>(args); result.MapResult(ParsedOptions, errors => ParsedErrors(result, errors)); }
public static async Task <int> Run(this Parser parser, string[] args, params Type[] jobTypes) { Dictionary <Type, Type> dict = new Dictionary <Type, Type>(); foreach (var jobType in jobTypes) { if (jobType.TryGetClosedGenericType(typeof(IUtility <>), out Type genericType)) { Type optionType = genericType.GetGenericArguments().First(); dict.Add(optionType, jobType); } } ParserResult <Object> parserResult = parser.ParseArguments(args, dict.Keys.ToArray()); return(await parserResult.MapResult <object, Task <int> >(async opt => await RunAsync(opt, dict), err => Task.FromResult(1))); }
public static T Parse <T>(T defaults, string[] args, out int exitCode) where T : CommandLineOptions { T options = defaults; // parse command line: we can't use the simple form of this because we need to display // help ourselves as the library just prints help to the console which we don't see ParserResult <T> result = Parser.Default.ParseArguments <T>(args); exitCode = result.MapResult(success => { options = success; return(0); }, errors => HandleCommandLineErrors(result, errors)); return(options); }
public static int Execute(this ParserResult <object> options, IServiceProvider provider) { int Execute <T1, T2>(T2 o) where T1 : ICommand <T2> { return(provider.GetRequiredService <T1>().Execute(o)); }; // #3: Execute the correct command based on the arguments return(options.MapResult( (GetDocumentsCommand.Options o) => Execute <GetDocumentsCommand, GetDocumentsCommand.Options>(o), (CreateIndexCommand.Options o) => Execute <CreateIndexCommand, CreateIndexCommand.Options>(o), (DeleteIndexCommand.Options o) => Execute <DeleteIndexCommand, DeleteIndexCommand.Options>(o), (IndexExistsCommand.Options o) => Execute <IndexExistsCommand, IndexExistsCommand.Options>(o), (UpdateDocumentsCommand.Options o) => Execute <UpdateDocumentsCommand, UpdateDocumentsCommand.Options>(o), errs => 1 )); }