public static void Main(string[] args) { ParserResult <object> result = Parser.Default.ParseArguments <ScaffoldTestOptions, IdentifyMissingTestsOptions>(args); result.WithParsed <ScaffoldTestOptions>(ScaffoldTest.Run); result.WithParsed <IdentifyMissingTestsOptions>(IdentifyMissingTests.Run); }
/// <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; } } }
internal static async Task Main(string[] args) { ParserResult <object> result = Parser.Default.ParseArguments <ScaffoldTestOptions, IdentifyMissingTestsOptions, DownloadDriversOptions, ApiCheckerOptions>(args); result.WithParsed <ScaffoldTestOptions>(ScaffoldTest.Run); result.WithParsed <IdentifyMissingTestsOptions>(IdentifyMissingTests.Run); await result.WithParsedAsync <DownloadDriversOptions>(DriverDownloader.RunAsync).ConfigureAwait(false); await result.WithParsedAsync <ApiCheckerOptions>(ApiChecker.RunAsync).ConfigureAwait(false); }
private static void GetCommandLineOptions(ParserResult <Options> options) { options.WithParsed <Options>(opts => { if (!String.IsNullOrWhiteSpace(opts.Brokers)) { kafkaBroker = opts.Brokers; } if (!String.IsNullOrWhiteSpace(opts.JobTopic)) { SetTopicsFromStringList(opts.JobTopic); } if (!String.IsNullOrWhiteSpace(opts.AnswerTopic)) { kafkaAnswerTopic = opts.AnswerTopic; } if (!String.IsNullOrWhiteSpace(opts.CaFile)) { WriteSSLValue("CA_FILE_LOCATION", opts.CaFile); } if (!String.IsNullOrWhiteSpace(opts.CertFile)) { WriteSSLValue("CERT_FILE_LOCATION", opts.CertFile); } if (!String.IsNullOrWhiteSpace(opts.KeyFile)) { WriteSSLValue("KEY_FILE_LOCATION", opts.KeyFile); } }); }
/// <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); }
static void Main(string[] args) { ParserResult <Options> parserResult = Parser.Default.ParseArguments <Options>(args); parserResult .WithParsed(options => { var task = Task.Run(async() => { try { var fileName = "NuGet-" + options.Release + (string.IsNullOrEmpty(options.RequiredLabel) ? "" : options.RequiredLabel) + ".md"; File.WriteAllText(fileName, await new ChangelogGenerator(options).GenerateChangelog()); Console.WriteLine($"{fileName} creation complete"); Environment.Exit(0); Console.ReadLine(); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); Environment.Exit(1); } }); task.Wait(); }) .WithNotParsed(errors => { Environment.Exit(1); Console.ReadLine(); }); }
static int Main(string[] args) { #if DEBUG if (Debugger.IsAttached) { args = "-l Fine".Split(' '); } #endif Parser parser = new Parser(with => { with.HelpWriter = null; with.CaseInsensitiveEnumValues = true; }); ParserResult <Options> result = parser.ParseArguments <Options>(args); int exitCode = 0; Program program = new Program(); result .WithParsed(options => { program.Init(options); exitCode = program.Start(options); }) .WithNotParsed(errs => { DisplayHelp(result, errs); exitCode = -1; }); #if DEBUG if (Debugger.IsAttached) { Console.Write("Press any key to continue..."); Console.ReadLine(); } #endif return(exitCode); }
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 Command MakeResult(ParserResult <Command> result) { Command ret = new Command(); result.WithParsed(x => ret = x); return(ret); }
static void Main(string[] args) { //try //{ Parser parser = new Parser(ps => ps.ParsingCulture = CultureInfo.CurrentCulture); ParserResult <Options> parserResult = parser.ParseArguments <Options>(args); parserResult .WithParsed(options => { Pipeline pipeline = new ServiceCollection() .AddEDMinorFactionSupport(options.Date, "EDA Kunti League", options.Verbose) .BuildServiceProvider() .GetService <Pipeline>(); pipeline.Run(Console.Out); }) .WithNotParsed(errors => Console.Error.Write(HelpText.AutoBuild(parserResult))); //} //catch(Exception ex) //{ // Console.Error.Write(ex.ToString()); //} }
private static void Main(string[] args) { // dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true try { var parser = new Parser(with => with.HelpWriter = null); parserResult = parser.ParseArguments <InjectorOptions>(args); parserResult .WithParsed( opts => { Options = opts; logger.Debug($"args: {string.Join(' ', args)}"); opts.UpdateFromFile(); opts.Log(); opts.Validate(); var injector = new Injector(opts); injector.Inject(); } ) .WithNotParsed(errs => DisplayHelp(parserResult, errs)); } catch (Exception ex) { HandleException("An unknown error occurred. See log for details", ex); } WaitForUserInput(); }
public static IHostBuilder CreateHostBuilder(string[] args) { return(new HostBuilder() .ConfigureAppConfiguration((appConfig) => appConfig.AddConfiguration(_configuration)) .ConfigureServices((hostContext, services) => { _parserResult.WithParsed(cmdOptions => services.AddSingleton(cmdOptions)); services.AddOptions(); services.AddHostedService <DbImporterHostedService>(); services.AddTransient <IDataReader <EdSystem> >((_) => new DefaultDataReader <EdSystem>( _.GetService <CmdOptions>().EdsmStarDataPath, _.GetService <ILogger <DefaultDataReader <EdSystem> > >(), _.GetService <CmdOptions>().SkipSystems)); services.AddTransient <IDataReader <CelestialBody> >((_) => new DefaultDataReader <CelestialBody>( _.GetService <CmdOptions>().EdsmBodiesDataPath, _.GetService <ILogger <DefaultDataReader <CelestialBody> > >(), _.GetService <CmdOptions>().SkipBodies)); services.AddDbContext <EdsmDbContext>(dbOptions => { dbOptions.UseLazyLoadingProxies(); dbOptions.UseNpgsql(hostContext.Configuration.GetConnectionString("Postgre"), sqlOptions => sqlOptions.CommandTimeout(1800)); }); services.AddTransient <IDbImporter, DefaultDbImporter>(); services.AddTransient <IImportActionFactory, DefaultImportActionFactory>(); }) .ConfigureLogging((hostContext, logConfig) => { logConfig .AddFilter("Microsoft", LogLevel.Error) .AddConsole(); })); }
/// /************************************************************************ /// * Initial configuration from TyrenDe's streamdeck-client-csharp example: /// * https://github.com/TyrenDe/streamdeck-client-csharp /// * and SaviorXTanren's MixItUp.StreamDeckPlugin: /// * https://github.com/SaviorXTanren/mixer-mixitup/ /// *************************************************************************/ /// <summary> /// Obsolete! Use the new Run(string[]) overload /// Library's main initialization point. /// Pass the args from your Main function and a list of supported PluginActionIds, the framework will handle the rest. /// </summary> /// <param name="args"></param> /// <param name="supportedActionIds"></param> public static void Run(string[] args, PluginActionId[] supportedActionIds) { Logger.Instance.LogMessage(TracingLevel.INFO, $"Plugin [{GetExeName()}] Loading - {supportedActionIds.Length} Actions Found"); System.AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper; #if DEBUG Logger.Instance.LogMessage(TracingLevel.DEBUG, $"Plugin Loading - Args: {String.Join(" ", args)}"); #endif // The command line args parser expects all args to use `--`, so, let's append for (int count = 0; count < args.Length; count++) { if (args[count].StartsWith("-") && !args[count].StartsWith("--")) { args[count] = $"-{args[count]}"; } } Parser parser = new Parser((with) => { with.EnableDashDash = true; with.CaseInsensitiveEnumValues = true; with.CaseSensitive = false; with.IgnoreUnknownArguments = true; with.HelpWriter = Console.Error; }); ParserResult <StreamDeckOptions> options = parser.ParseArguments <StreamDeckOptions>(args); options.WithParsed <StreamDeckOptions>(o => RunPlugin(o, supportedActionIds)); }
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) { 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(); }
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); }
static void Main(string[] args) { ParserResult <Options> result = Parser.Default.ParseArguments <Options>(args); result.WithParsed(Run); result.WithNotParsed(PrintError); }
/// <summary> /// Main entry point of the program /// </summary> /// <param name="args">Command line arguments to be parsed</param> static void Main(string[] args) { // We create your own command line parser to setup wanted options using (CommandLine.Parser parser = new CommandLine.Parser( with => { //with.HelpWriter = Console.Error; with.HelpWriter = null; // To display myself the help with.IgnoreUnknownArguments = false; with.CaseSensitive = false; } )) { // Make the parsing ParserResult <CommandLineArguments> result = parser.ParseArguments <CommandLineArguments>(args); // In function of parser result, we run the program of we handle the errors result.WithParsed <CommandLineArguments>(opts => Run(opts)) .WithNotParsed <CommandLineArguments>((errs) => HandleParseError(errs, result) ); } // Only for debug, when the program is launch under Visual Studio. if (Debugger.IsAttached) { Console.WriteLine("Press any key to exit"); Console.ReadKey(); } }
// StreamDeck launches the plugin with these details // -port [number] -pluginUUID [GUID] -registerEvent [string?] -info [json] static void Main(string[] args) { // Uncomment this line of code to allow for debugging // while (!System.Diagnostics.Debugger.IsAttached) { System.Threading.Thread.Sleep(100); } // The command line args parser expects all args to use `--`, so, let's append for (int count = 0; count < args.Length; count++) { if (args[count].StartsWith("-") && !args[count].StartsWith("--")) { args[count] = $"-{args[count]}"; } } Parser parser = new Parser((with) => { with.EnableDashDash = true; with.CaseInsensitiveEnumValues = true; with.CaseSensitive = false; with.IgnoreUnknownArguments = true; with.HelpWriter = Console.Error; }); ParserResult <Options> options = parser.ParseArguments <Options>(args); options.WithParsed <Options>(o => RunPlugin(o)); }
static void Main(string[] args) { ParserResult <Options> parserResult = Parser.Default.ParseArguments <Options>(args); parserResult.WithParsed(options => { var task = Task.Run(async() => { try { await new LabelUpdateHelper(options).UpdateLabel(); Console.WriteLine("Update label complete"); Environment.Exit(0); } catch (Exception) { throw; } }); task.Wait(); }) .WithNotParsed(errors => { Environment.Exit(1); Console.ReadLine(); }); }
/// <summary> /// /// </summary> /// <param name="args"></param> static protected void Run(string[] args) { Thread.CurrentThread.Name = "NativeHost::Main"; try { SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlHandler), true); regService = new RegistryService(endpoint.Properties); BrowserType caller = endpoint.CheckBrowserCall(args); if (caller == BrowserType.Unknown) { Log.Debug("Native host started with args {0} ", args); Parser parser = new CommandLine.Parser(with => with.HelpWriter = null); parserResult = parser.ParseArguments <Options>(args); parser.Dispose(); parserResult .WithParsed(options => RunAndReturnExitCode(options)) .WithNotParsed(errors => DisplayHelp(errors)); } else { Log.Debug("Native host called by {1} with args {0} ", args, caller); DoHostListen(caller); } } catch (Exception e) { Log.Fatal(e.Message); } Log.CloseAndFlush(); Log.Debug("Native host will now exit"); }
private static int Init(ParserResult <CmdOptions> result) { try { result .WithParsed(opt => { var serviceProvider = new ServiceCollection() .AddSingleton(options => new ControllerOptions { Mode = opt.Mode }) .AddScoped <IDispatcher, Dispatcher>() .AddScoped <IController, Controller>() .BuildServiceProvider(); var dispatcher = serviceProvider.GetRequiredService <IDispatcher>(); new App(dispatcher).Run(opt); }); return(0); } // Even though its not ok to catch a generic exception, // This is our only way to catch ANY exception from the app and return a failed exitCode catch (Exception ex) { Console.WriteLine(ex); return(1); } }
private static void Main(string[] args) { using var parser = new Parser(with => with.HelpWriter = null); ParserResult <object> parserResult = parser.ParseArguments <Options.List, Options.Extract, Options.Create, Options.Remove, Options.Add>(args); parserResult .WithParsed <Options.List>(List) .WithParsed <Options.Extract>(Extract) .WithParsed <Options.Create>(Create) .WithParsed <Options.Remove>(Remove) .WithParsed <Options.Add>(Add) .WithNotParsed(x => { if (args.Length == 1) { if (File.Exists(args[0])) { var opts = new Options.Extract { ParArchivePath = args[0], OutputDirectory = string.Concat(args[0], ".unpack"), Recursive = false, }; Extract(opts); return; } if (Directory.Exists(args[0])) { var opts = new Options.Create { InputDirectory = args[0], ParArchivePath = args[0].EndsWith(".unpack", StringComparison.InvariantCultureIgnoreCase) ? args[0].Substring(0, args[0].Length - 7) : string.Concat(args[0], ".par"), AlternativeMode = false, Compression = 1, }; Create(opts); return; } } var helpText = HelpText.AutoBuild( parserResult, h => { h.AutoHelp = false; // hide --help h.AutoVersion = false; // hide --version return(HelpText.DefaultParsingErrorsHandler(parserResult, h)); }, e => e); Console.WriteLine(helpText); }); }
public TWorkflowResult Process(string[] args) { CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture; TWorkflowResult result = null; if (Parameters != null) { result = ProcessJsonConfig(args); } else { var paramsNormalizer = new CliParametersNormalizer <TParameters>(); bool success = paramsNormalizer.Normalize(args, out string[] outArgs); var parser = new Parser(config => { config.IgnoreUnknownArguments = ContinueWithInvalidArgs; config.CaseInsensitiveEnumValues = true; }); ParserResult <TParameters> parserResult = parser.ParseArguments <TParameters>(outArgs); if (success || ContinueWithInvalidArgs) { parserResult.WithParsed( parameters => { Parameters = parameters; FillLoggerSettings(parameters); Logger.LogErrors(paramsNormalizer.Errors); result = ProcessJsonConfig(outArgs); }) .WithNotParsed(errors => { Logger.LogErrors(paramsNormalizer.Errors); if (ContinueWithInvalidArgs) { result = ProcessJsonConfig(outArgs, errors); } else { LogInfoAndErrors(outArgs, errors); } }); } } #if DEBUG if (StopIfDebuggerAttached && Debugger.IsAttached) { Console.WriteLine("Press Enter to exit"); Console.ReadLine(); } #endif return(result); }
/// <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)); }
static void Main(string[] args) { ParserResult <CommandLineOptions> options = Parser.Default.ParseArguments <CommandLineOptions>(args); if (options != null) { options.WithParsed(t => ProcessData(t)); } }
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); }
private static void Main(string[] args) { Console.Title = Title; parserResult = Parser.Default.ParseArguments <Parameters>(args); parserResult.WithParsed(ParameterOk); log.Info("Finished!"); Console.ReadLine(); }
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 void Main(string[] args) { // Start bot with command line options Parser parser = new Parser(with => with.HelpWriter = null); ParserResult <CommandLineOptions> result = parser.ParseArguments <CommandLineOptions>(args); result.WithParsed(options => new SpinTheWheelBot(options).Start().GetAwaiter().GetResult() ) .WithNotParsed(errs => DisplayHelp(result, errs)); }