public static ScryptCommandLineArgs Parse(string[] args, out string verb) { if (args.Length == 0) { // Work around a bug in CommandLineParser that doesn't correctly support a custom 'help' verb. Console.WriteLine(HelpText.AutoBuild(new ScryptCommandLineArgs(), _ => { }, true)); Environment.Exit(Parser.DefaultExitCodeFail); } string verbForClosure = null; var arguments = new ScryptCommandLineArgs(); var parser = new Parser(settings => { settings.HelpWriter = null; }); var parseSucceed = parser.ParseArguments(args, arguments, (foundVerb, subOptions) => { verbForClosure = foundVerb; }); if (!parseSucceed) { Console.WriteLine(HelpText.AutoBuild(arguments, _ => { }, true)); Environment.Exit(Parser.DefaultExitCodeFail); } verb = verbForClosure; return arguments; }
/// <summary> /// Main method that runs the install program. /// </summary> /// <param name="args">Command line arguments.</param> private static void Main(string[] args) { InstallOptions installOptions = new InstallOptions(); Environment.CurrentDirectory = Directory.GetParent(Assembly.GetExecutingAssembly().Location).FullName; if (args.Contains("--help")) { Console.Write(installOptions.GetUsage()); Environment.Exit(0); } installLogger = new InstallLogger(installOptions.Quiet); Parser parser = new Parser(settings => { settings.MutuallyExclusive = true; }); if (!parser.ParseArguments(args, installOptions)) { installLogger.LogErrorLine("Invalid command line parameters"); Environment.Exit(1); } JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.None, ContractResolver = new DiscretionalContractResolver(), Converters = new JsonConverter[] { new JsonKnownTypeConverter() } }; new Program().Run(installOptions); }
static int Main(string[] args) { log.Info("Start."); var parser = new Parser(with => { with.HelpWriter = Console.Out; with.EnableDashDash = true; }); try { objWS_S = new EArchiveClient("EArchiveDefaultTest"); var isRunning = objWS_S.IsRunning(); if (!isRunning) { log.Error("Connection to webservice failed. Service is not running."); return 2; } } catch (Exception ex) { log.Error(ex, "Connection to webservice failed. Is certificate configured properly?"); return 1; } var result = parser.ParseArguments<SendLDocOptions, GetLDocOptions, SendLDocCSVOptions, GetSendLDocSchemaOptions>(args); var exitCode = result.MapResult( (SendLDocOptions opts) => RunSendAndReturnExitCode(opts), (GetLDocOptions opts) => RunGetAndReturnExitCode(opts), (SendLDocCSVOptions opts) => RunSendFromCsvAndReturnExitCode(opts), (GetSendLDocSchemaOptions opts) => RunGetSchemaAndReturnExitCode(opts), errs => 1 ); objWS_S.Close(); log.Info("All done."); return exitCode; }
static int Main( string[] args ) { var options = new Options(); var parser = new CommandLine.Parser( with => with.HelpWriter = Console.Error ); if ( parser.ParseArgumentsStrict( args, options, () => Environment.Exit( -2 ) ) ) { if ( string.IsNullOrEmpty( options.PathToRockWeb ) ) { string removeString = "Dev Tools\\Applications"; string currentDirectory = System.Reflection.Assembly.GetExecutingAssembly().Location; int index = currentDirectory.IndexOf( removeString ); string rockDirectory = ( index < 0 ) ? currentDirectory : currentDirectory.Substring( 0, index ); options.PathToRockWeb = Path.Combine( rockDirectory, "RockWeb" ); } if ( !Directory.Exists( options.PathToRockWeb ) ) { Console.WriteLine( "Error: unable to find directory: " + options.PathToRockWeb ); return -1; } Run( options ); } return 0; }
static void Main(string[] args) { //(1)コマンドラインパーサーの初期化 ParserSettings setting = new ParserSettings(); setting.HelpWriter = Console.Error; var parser = new Parser(setting); //(2)オプション用クラスに引数を展開 var option = new ConsoleOption(); if (!parser.ParseArguments(args, option)) { //パラメータに問題がある場合は、失敗ステータスで終了 Environment.Exit(1); } var filePath = System.IO.Path.GetFullPath(option.OutputDirPath); var createYoutubeQRCode = new CreateYoutubeQRCodeLib.CreateYoutubeQRCode(); createYoutubeQRCode.TargetContentType = CreateYoutubeQRCodeLib.contentType.User; createYoutubeQRCode.ConsumerKey = option.ClientID; createYoutubeQRCode.ConsumerSecret = option.ClientSeacret; createYoutubeQRCode.TargetFolderPath = filePath; var t = createYoutubeQRCode.CreateQR(); t.Wait(); }
private static void Main(string[] args) { var parser = new Parser(config => config.HelpWriter = Console.Out); if (args.Length == 0) { parser.ParseArguments<Options>(new[] { "--help" }); return; } Options options = null; parser.ParseArguments<Options>(args) .WithParsed(r => { options = r; }); if (string.IsNullOrEmpty(options.Job)) { Console.WriteLine("Job required!"); return; } Console.WriteLine(options.Job); switch (options.Job.ToLower()) { case "sqlread": SqlBenchmark.ReadAsync(options.Parallel).Wait(); break; case "migrate": Sql2MongoMigrator.MigrateAsync().Wait(); break; case "read": MongoDbBenchmark.ReadAsync(options.Parallel).Wait(); break; case "duplicate": MongoDbBenchmark.DuplicateAsync(options.Parallel).Wait(); break; case "replace": MongoDbBenchmark.ReplaceAsync(options.Parallel).Wait(); break; case "savesimple": MongoDbBenchmark.SaveSimpleAsync(options.Parallel).Wait(); break; case "savecomplex": MongoDbBenchmark.SaveComplexAsync(options.Parallel, false).Wait(); break; case "savecomplexfull": MongoDbBenchmark.SaveComplexAsync(options.Parallel, true).Wait(); break; default: Console.WriteLine("Invalid job!"); break; } }
public static int Main(string[] args) { Options options = new Options(); using (Parser cmdParser = new Parser()) { cmdParser.ParseArguments(args, options); } List<string> files = Directory.EnumerateFiles(Environment.CurrentDirectory, options.Input, SearchOption.TopDirectoryOnly).ToList(); if (files.Count == 0) { Console.Error.WriteLine("File {0} not found", options.Input); return -1; } StreamWriter streamWriter; IParser parser; int result = AssertConditions(options, out streamWriter, out parser); if (result != 0) { string usage = options.GetUsage(); Console.WriteLine(usage); return result; } using (CSVWriter csvWriter = new CSVWriter(',', streamWriter)) { foreach(string file in files) { using (StreamReader reader = new StreamReader(file)) { if (options.Header) { string[] header = parser.GetHeader(); csvWriter.Append(header); } IEnumerable<string[]> rows = parser.Read(reader); foreach (string[] row in rows) { csvWriter.Append(row); } } } } return 0; }
public OptionsParser(OptionsParserSettings settings) { _settings = settings; _parser = new Parser(parserSettings => { parserSettings.IgnoreUnknownArguments = false; parserSettings.HelpWriter = _settings.HelpWriter; parserSettings.EnableDashDash = true; }); }
/// <summary> /// CommandLine Main /// </summary> /// <param name="args">Input parameters</param> static void Main(string[] args) { var options = new Options(); var parser = new CommandLine.Parser(with => with.HelpWriter = Console.Error); if (parser.ParseArgumentsStrict(args, options, () => Environment.Exit(-2))) { Run(options); } }
public static Arguments Parse(string[] args) { var parameters = new Arguments(); var parser = new Parser(with => with.HelpWriter = Console.Error); parser.ParseArgumentsStrict(args, parameters, () => { throw new ArgumentOutOfRangeException("args", args, "Command line arguments are invalid."); }); return parameters; }
/// <summary> /// Console entry point /// </summary> /// <param name="args">command line arguments</param> /// <returns>0 if all extractions are successful.</returns> private static int Main(string[] args) { var options = new Options(); var parser = new Parser(settings => { settings.CaseSensitive = false; settings.HelpWriter = Console.Error; settings.ParsingCulture = CultureInfo.InvariantCulture; }); var result = parser.ParseArguments(args, options); if (!result) { Fail(); return -1; } TfsTeamProjectCollection tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(options.Collection)); try { tfs.EnsureAuthenticated(); } catch (Exception) { Fail("Connection to TFS failed"); return -1; } // Getting Identity Service var ims = tfs.GetService<IIdentityManagementService>(); var someExtractionFail = false; foreach (var userName in options.Users) { Console.WriteLine("===== Extracting Permissions for User {0} ======", userName); var fileName = Helpers.GenerateFileName(userName, options.OutputFile); var extractionStatus = ExtractPermissionForUserName(ims, userName, options, fileName, tfs); if (!extractionStatus) { someExtractionFail = true; } } if (someExtractionFail) { Fail("An error occured during the extraction"); return -1; } return 0; }
private static void InitializeOptions(string[] args) { s_options = new Options(); var parser = new Parser( x => { x.MutuallyExclusive = true; x.HelpWriter = System.Console.Error; }); parser.ParseArgumentsStrict(args, s_options); }
private static void ParseOptions(string[] args, Options options) { var parser = new Parser(delegate(ParserSettings settings) { settings.CaseSensitive = false; settings.HelpWriter = Console.Error; }); if (parser.ParseArguments(args, options) == false) throw new ArgumentException("Invalid command line"); }
public static void Main([NotNull] string[] args) { Assert.ArgumentNotNull(args, "args"); CoreApp.InitializeLogging(); CoreApp.LogMainInfo(); Analytics.Start(); var filteredArgs = args.ToList(); var query = GetQueryAndFilterArgs(filteredArgs); var wait = GetWaitAndFilterArgs(filteredArgs); var parser = new Parser(with => with.HelpWriter = Console.Error); Assert.IsNotNull(parser, "parser"); var options = new MainCommandGroup(); EnsureAutoCompeteForCommands(options); if (!parser.ParseArguments(filteredArgs.ToArray(), options, delegate { })) { Console.WriteLine("Note, commands provide output when work is done i.e. without any progress indication."); Console.WriteLine("\r\n --query\t When specified, allows returning only part of any command's output"); Console.WriteLine("\r\n --data\t When specified, allows returning only 'data' part of any command's output"); Console.WriteLine("\r\n --wait\t When specified, waits for keyboard input before terminating"); Environment.Exit(Parser.DefaultExitCodeFail); } var result = options.SelectedCommand.Execute(); result = QueryResult(result, query); if (result == null) { return; } var serializer = new JsonSerializer { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented, }; serializer.Converters.Add(new DirectoryInfoConverter()); var writer = Console.Out; serializer.Serialize(writer, result); if (wait) { Console.ReadKey(); } }
private static void Main(string[] args) { try { var parser = new Parser(config => config.HelpWriter = Console.Out); parser.ParseArguments<Options>(args).WithParsed(Remap); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public void Main(string[] args) { Parser parser = new Parser(config => { config.EnableDashDash = true; config.CaseSensitive = true; config.IgnoreUnknownArguments = false; config.HelpWriter = Out; }); parser.ParseArguments<Options>(args) .WithNotParsed(ArgumentsError) .WithParsed(Execute); }
/// <summary> /// Application's Entry Point. /// </summary> /// <param name="args">Command line arguments splitted by the system.</param> private static void Main(string[] args) { #if EXEC_TESTS RunATestForDebugging(); #endif var options = new Options(); var parser = new CommandLine.Parser(with => with.HelpWriter = Console.Error); if (parser.ParseArgumentsStrict(args, options, () => Environment.Exit(-2))) { Run(options); } }
static int Main(string[] arguments) { CoreSettings settings = new CoreSettings(); Parser parser = new Parser(s => { s.IgnoreUnknownArguments = true; s.CaseSensitive = true; }); if(!parser.ParseArguments(arguments, settings)) { return 1; } else { return Launch(settings, arguments); } }
public static void Main(string[] args) { var options = new Options(); if (HasNoArguments(args)) { Console.Write(options.GetUsage()); Environment.Exit(1); } var parser = new Parser(); if (parser.ParseArguments(args, options)) { if (ShouldShowVersion(options)) { OutputVersion(); return; } try { var config = ConfigFactory.Create(options); var requester = new Requester(); var logger = LoggerFactory.Create(options); var warmer = WarmerFactory.Create(options, config, requester, logger); warmer.Warm(); } catch (XmlException e) { Console.WriteLine(""); Console.WriteLine("Invalid XML Config File"); Console.WriteLine("-----------------------"); Console.WriteLine(e.Message); } catch (FileNotFoundException e) { Console.WriteLine(""); Console.WriteLine("Could not find the file specifed. {0}", options.Inputfiles); Console.WriteLine("-----------------------"); Console.WriteLine(e.Message); } } else { Environment.Exit(1); } }
static IProgramOptions ParseCommandLine(string[] args) { var options = new CommandLineOptions.CommandLineOptions(); var parser = new Parser(settings => { settings.IgnoreUnknownArguments = true; settings.CaseSensitive = false; }); if (!parser.ParseArguments(args, options)) { Environment.Exit(1); } return options; }
private static void Main(string[] args) { StringWriter writer = new StringWriter(); Parser p = new Parser(with => with.HelpWriter = writer); TapCheckerOptions opts = new TapCheckerOptions(); if (!p.ParseArguments(args, opts)) { Console.WriteLine(writer.ToString()); return; } List<string> files = new List<string>(); if ((opts.Files.Length == 1) && (opts.Files[0] == "*")) { files.AddRange(Directory.GetFiles(".", "*.tap")); } else { files.AddRange(opts.Files.ToArray()); } ConsoleColor currentColor = Console.ForegroundColor; TapChecker checker = new TapChecker(); foreach (var fileToCheck in files) { List<ReportLine> report = checker.Check(fileToCheck, opts); foreach (var reportLine in report) { switch (reportLine.Status) { case ReportLineStatus.Info: Console.ForegroundColor = currentColor; break; case ReportLineStatus.Error: Console.ForegroundColor = ConsoleColor.Red; break; case ReportLineStatus.Warning: Console.ForegroundColor = ConsoleColor.Yellow; break; } Console.WriteLine(reportLine.Message); } Console.WriteLine(); } Console.ForegroundColor = currentColor; Console.WriteLine("Press enter to exit"); Console.ReadLine(); }
private static int Main(string[] args) { var parser = new Parser( (settings) => { settings.EnableDashDash = true; settings.HelpWriter = Console.Error; }); var orchestrator = new Orchestrator(parser); var parserResult = parser.ParseArguments<RunasOptions, ElevateOptions, BootstrapOptions>(args); var exitCode = parserResult.MapResult( (RunasOptions opts) => { // Split username from domain if given var domainUserName = Utils.SplitUsernameAndDomain(opts.Username); var domain = domainUserName.Key; var userName = domainUserName.Value; // Get password from command line if not given SecureString passwordSecured; if (opts.Password == null) { Console.Write("Password: "); passwordSecured = Utils.GetConsoleSecurePassword(); } else { passwordSecured = opts.Password.ConvertToSecureString(); } // Exec return orchestrator.RunAs(opts.Command, opts.Arguments, domain, userName, passwordSecured, opts.Elevated); }, (ElevateOptions opts) => { // Exec return orchestrator.Elevate(opts.Command, opts.Arguments, opts.LogFilePath, opts.InitVerb); }, (BootstrapOptions opts) => { // Exec return orchestrator.Bootstrap(opts.Command, opts.Arguments, opts.LogFilePath, opts.InitVerb); }, errs => 1); return exitCode; }
public static void Main(string[] args) { Options = new AutomatrOptions(); Parser parser = new Parser(new Action<ParserSettings>((ParserSettings p) => { p.CaseSensitive = false; p.IgnoreUnknownArguments = false; p.MutuallyExclusive = true; })); bool parse = parser.ParseArguments(args, Options); if (Options.Version) { AutomatrLog.Log("Automatr " + Version, AutomatrLog.LogLevel.Info); return; } AutomatrConfig config = AutomatrConfig.Load(Options.ConfigPath); Automatr automatr = new Automatr(config); automatr.Run(); }
static void Main(string[] args) { var options = new Options(); var parser = new Parser(); //If parsing was successful verify either a server is given or the file and receivers are given if (parser.ParseArguments(args, options) && (!string.IsNullOrWhiteSpace(options.Server) || (!string.IsNullOrWhiteSpace(options.File) && options.Clients != null && options.Clients.Any()))) { //If No Server is Given assume Current Box is the Server otherwise process act as if you are a client if (string.IsNullOrWhiteSpace(options.Server)) { var server = new CommandExecutionServer(options.Port, options.Timeout, options.File, options.Arguments, options.Clients, options.UseServer); var result = server.Start(); Console.WriteLine(result ? "Execution Successful! Processes Running." : "An Error Occured while attempting to execute the processes!"); } else { var client = new CommandExecutionClient(options.Port, options.Server); var process = client.Start(); if (process != null) { Console.WriteLine("Process Started!"); process.WaitForExit(); Console.WriteLine("Process Complete!"); } else { Console.WriteLine("Error occured when attempting to execute process!"); } } } else { Console.WriteLine(options.GetUsage()); return; } Console.WriteLine("Press Enter To Close The Console!"); Console.ReadLine(); }
public static int Main(string[] args) { int retval = -1; var options = new Options(); var parser = new CommandLine.Parser(with => with.HelpWriter = Console.Error); if (parser.ParseArgumentsStrict(args, options, () => Environment.Exit(-2))) { log.InfoFormat("Started:\t{0}", !String.IsNullOrEmpty(options.Job) ? options.Job : options.InputFile); Bits.Wcf.BitsWcfServiceClient cl = new Bits.Wcf.BitsWcfServiceClient(); switch(options.Mode) { case TriggerMode.FolderWatcher: retval = cl.RunJobFromClient(options.Job, options.InputFile); break; case TriggerMode.Timer: //see if there is a [full] set of geneva parms if (options.PS != null || options.PE != null || options.K != null || options.PK != null) { if (options.PS == null || options.PE == null || options.K == null || options.PK == null) { log.Warn("If providing Geneva parameters, all parameters must be provided (PS, PE, K, PK)"); return 0; } else { log.InfoFormat("Geneva Dates:\tps{0} pe{1} k{2} ps{3} ", options.PS, options.PE, options.K, options.PK); retval = cl.RunJobFromClient(options.Job, String.Empty); } } else retval = cl.RunJobFromClient(options.Job, String.Empty); break; } } log.InfoFormat("Completed:\t{0}", options.Job); log.InfoFormat("Return Value:\t{0}", retval); return retval; }
static void Main(string[] args) { if (args.Length == 0) // check for null array { Console.WriteLine("There are no arguments present on the command line."); Console.WriteLine("Press any key to exit."); Console.ReadKey(); Environment.Exit(0); } else { Options options = new Options(); CommandLine.Parser parser = new Parser(); Console.WriteLine(options.InputHost); Console.WriteLine(options.InputFile); Console.Write("Hostname : "); Console.WriteLine(args[0]); // Write array length try { IPAddress[] addresslist = Dns.GetHostAddresses(args[0]); foreach (IPAddress theaddress in addresslist) { if (theaddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { Console.WriteLine(theaddress.ToString()); } } } catch (System.Net.Sockets.SocketException sockEx) { Console.WriteLine("Socket Error: " + sockEx.NativeErrorCode + " " + sockEx.Message); } } // Keep the console window open Console.WriteLine("Press any key to exit."); Console.ReadKey(); }
public static void Run(string[] args) { var options = new Options(); var parser = new CommandLine.Parser(s => { s.CaseSensitive = false; s.MutuallyExclusive = true; s.HelpWriter = Console.Out; s.ParsingCulture = System.Globalization.CultureInfo.InvariantCulture; }); if (!parser.ParseArguments(args, options)) { return; } if (options.Folders.Count > 0) { var firstFolder = options.Folders.First(); var collection = new MediaCollection<ConsoleFilm>(firstFolder).Items; if (options.List) { foreach (var film in collection) { Console.WriteLine(String.Format("{0,-3} {1,-9} {2}", film.Rating, film.ImdbId, film.FolderName)); } } if(options.Decorate) { new IconService().ProcessValidFilms(collection, validFilms => Console.WriteLine("Complete! " + validFilms.Count() + " folders have been decorated with icons.")); } if(options.Watch) { new ConsoleFilmProcessingWatcher(firstFolder).InfiniteWait(); } } if (options.RunGui) { GuiApp.Run(); } }
public IConfig GetConfig() { var args = Environment.GetCommandLineArgs(); var options = new CommandLineOptions(); using (var parser = new CommandLine.Parser((settings) => { settings.HelpWriter = null; })) { parser.ParseArguments <CommandLineOptions>(args) .WithParsed(opts => { options = opts; }) .WithNotParsed(errors => { }); } var configFileConfig = (string.IsNullOrEmpty(options.ConfigFileName) ? null : _fileConfigProvider.GetConfig(options.ConfigFileName)); var commandLineConfig = _commandLineArgsConfigProvider.GetConfig(args); return(_mergeConfigProvider.GetConfig(configFileConfig, commandLineConfig)); }
static public T Parse <T>(Logging.ILogger logging, string[] arguments) where T : CoreCommandlineOptions { var parser = new CommandLine.Parser(config => config.HelpWriter = Console.Out); T options = null; IEnumerable <Error> errors = null; var result = parser.ParseArguments <T>(arguments) .WithParsed <T>(opts => options = opts) .WithNotParsed <T>(errs => errors = errs); if (errors != null) { options = System.Activator.CreateInstance <T>(); options.ParsingErrors = errors; } return(options); }
static void Main(string[] args) { Pauser pauser = new Pauser(); try { var parser = new CommandLine.Parser(with => with.HelpWriter = null); var parserResult = parser.ParseArguments <Options>(args); parserResult .WithParsed <Options>(options => pauser.Run(options)) .WithNotParsed(errors => DisplayHelp(parserResult, errors)); parserResult.WithParsed(options => pauser.Run(options)); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
static void Main(string[] args) { var options = new Options(); var parser = new Parser(config => config.HelpWriter = Console.Out); var result = parser.ParseArguments(args, options); if (options.Timeout > 0) { timeout = TimeSpan.FromMilliseconds(options.Timeout); } if (options.MaxRetries > 0) { maxRetries = options.MaxRetries; } RunPackageInstall(options.PackagePath, options.SitecoreUrl); }
static void Main(string[] args) { Parser parser = new CommandLine.Parser(); hyptoolargs parsedArgs = new hyptoolargs(); if (parser.ParseArgumentsStrict(args, parsedArgs, () => { Console.Write(HelpText.AutoBuild(parsedArgs).ToString()); })) { _Main(parsedArgs); } else { Console.WriteLine("Valid action values:"); foreach (string actionName in Enum.GetNames(typeof(hypervisorAction))) { Console.WriteLine(" * '" + actionName + "'"); } } }
public static void Main(string[] args) { try { if (args.Any(a => a.Contains("help", StringComparison.InvariantCultureIgnoreCase))) { var parser = new CommandLine.Parser(with => with.HelpWriter = null); var result = parser.ParseArguments <KongoOptions>(args); var helpText = HelpText.AutoBuild(result, h => { //configure HelpText h.AddPreOptionsLine(""); h.AddPreOptionsLine("----------------------------------"); h.AdditionalNewLineAfterOption = false; //remove newline between options h.Heading = "Kongo 1.0.2"; //change header h.Copyright = "Brought to you by Stakeyourada.com"; return(h); }, e => e); Console.WriteLine(); Console.WriteLine(helpText); } else { // Parse command line and execute var config = new Program().ReadKongoConfiguration(args); CommandLine.Parser.Default.ParseArguments <KongoOptions>(config) .MapResult( (KongoOptions opts) => LoadKongoOptions(opts), HandleParseError); var host = CreateHostBuilder(args).Build(); CreateDbIfNotExists(host); host.Run(); } } catch (ArgumentNullException) { // just ignore this exception and let app close, cmd line help was already displayed } }
/// <summary> /// Called when the command line tool starts. /// </summary> /// <param name="args">Arguments for the application.</param> static void Main(string[] args) { // Parse the command line options var exitCode = 0; var options = new GlobalOptions(); using (var parser = new Parser(settings => { settings.MutuallyExclusive = true; settings.HelpWriter = Console.Error; })) { if (!parser.ParseArguments(args, options, ExecuteVerb)) { exitCode = Parser.DefaultExitCodeFail; } } // Command line arguments not succesfully parsed #if DEBUG Console.ReadLine(); #endif Environment.Exit(exitCode); }
public void TaskWithTagAndTagIntersectThrowAnExcption() { var commandLineParser = new CommandLine.Parser(); CommandLineParser parserObj = new CommandLineParser(new OptionConverter(new JsonDeserializer()), commandLineParser, new ParserUsage(), new VerbFormater()); string[] argv = new string[] { "task info", "--tags", "t1", "t2", "--exclusive-tags", "t3", "t4" }; ParseException ex = null; var converter = new OptionConverter(null); var usage = new ParserUsage(); var parser = commandLineParser.ParseArguments <Options.InfoTaskOptions>(argv); ex = Assert.Throws <ParseException>(() => parser.MapResult( (Options.InfoTaskOptions o) => converter.ConvertGenericGetterOption(ConfigType.Task, CommandApi.Info, o), err => throw new ParseException(usage.PrintHelp(parser, err, argv)))); Assert.IsNotNull(ex); commandLineParser.Dispose(); }
public IApplication Build(string[] args, Func <object, IApplication> appResolver) { var parser = new CommandLine.Parser(with => { with.HelpWriter = null; }); var verbTypes = Verbs.Select(x => x.GetType()).OrderBy(x => x.GetCustomAttribute <VerbAttribute>().Name).ToArray(); var parserResult = parser.ParseArguments(args, verbTypes); IApplication application = null; parserResult .WithParsed(x => { application = appResolver(x); }) .WithNotParsed(x => HandleErrors(parserResult, x)); return(application); }
/// <summary> /// Tries to parse the command line arguments. /// Returns false if parsing fails or no compilation is to be done. /// </summary> /// <param name="args">The command line arguments passed to the executable.</param> /// <param name="output">A writer for any output such as help.</param> /// <param name="options">The parsed compilation options, if successful.</param> public static bool TryParseArguments( IEnumerable <string> args, TextWriter output, [NotNullWhen(true)] out CompilationOptions?options) { var parser = new CommandLine.Parser(config => { config.HelpWriter = output; }); var result = parser.ParseArguments <CommandLineOptions>(args); if (result is Parsed <CommandLineOptions> parsed) { // Handle the case where multiple main modules are specified by ourselves. // We could also set an Value attribute property Max=1, but the error message would be: // "A sequence value not bound to option name is defined with few items than required." // So yeah, maybe it is better to handle that by ourselves. Debug.Assert(parsed.Value.MainModule != null); var mainModules = new List <string>(parsed.Value.MainModule); if (mainModules.Count > 1) { output.WriteLine("ERROR(S):"); output.WriteLine("More than one main module specified."); options = null; return(false); } // Convert the options into compilation options options = new CompilationOptions( mainModules.Count == 0 ? "." : mainModules[0], debugPattern: parsed.Value.DumpRegex, emitDisassembly: parsed.Value.Disassembly); return(true); } else { options = null; return(false); } }
public static void Main(string[] cmdLineArgs) { try { var args = new Args(); var parser = new Parser(); if (!parser.ParseArguments(cmdLineArgs, args)) { log.Fatal("Command line args could not be parsed. Exiting the application."); Environment.ExitCode = 1; } else { if (args.ConfigCheck) { VerifyConfiguration(); } else { if (!VerifyConfiguration()) { log.Fatal("The configuration validation failed, exiting the application."); Environment.ExitCode = 2; return; } if (args.RunInConsole) { RunInConsole(); } else { RunAsService(); } } } } catch (Exception ex) { log.Fatal(ex); } }
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); }
/// <summary> /// Initializes a new instance of the <see cref="StartBacktestCommand"/> class. /// </summary> /// <param name="inputs">inputs.</param> public StartBacktestCommand(string[] inputs) : base(inputs) { Parser parser = new Parser(x => x.HelpWriter = null); parser.ParseArguments <StartBacktestCommandArguments>(inputs) .WithNotParsed(_ => throw new InvalidCommandException("invalid arguments, use help to get more info")) .WithParsed(x => _args = x); // Check if the input type is a valid algorithm _algo = Reflections.GetAllImplementations(typeof(IBaseAlgorithm)) .FirstOrDefault(x => x.Name == _args.AlgorithmName) ?? throw new InvalidCommandException($"{_args.AlgorithmName} is not a known algorithm"); // Retrieve the settings type var settingsType = Reflections.GetAllSubtypes(typeof(AlgorithmConfiguration)) .FirstOrDefault(s => Reflections.AlgorithmMatchesConfiguration(_algo, s)) ?? throw new InvalidCommandException( $"{_args.AlgorithmName} does not have a configuration object and cannot be started."); // Optionally load with custom path. if (!_args.Inline) { _args.ConfigurationPath = _args.ConfigurationPath ?? _args.AlgorithmName + ".yaml"; try { _configuration = ConfigurationLoader.LoadConfiguration(settingsType, _args.ConfigurationPath); } catch (Exception e) { throw new InvalidCommandException(e.Message); } } else { _configuration = BacktestDaemonService.GetConfigurationFromUser(settingsType); } DatabaseUtilities.Instance.ValidateCandleWidth(_configuration.TradingPairs, Configuration.Configuration.Instance.CandleWidth); ConfigureTimestampEdges(BacktestDaemonService.Instance.State, _args); Program.CommandLineArgs.BacktestOutputPath = _args.OutputPath; }
private static IServiceCollection ConfigureServices(string[] args) { IServiceCollection services = new ServiceCollection(); var parser = new CommandLine.Parser(with => with.HelpWriter = null); var parserResult = parser.ParseArguments <RunOptions, UpdateOptions>(args); services.AddSingleton(parserResult); services.AddTransient <IDnsServerParser, DnsServerParser>(); services.AddTransient <IDnsServerService, DnsServerService>(); services.AddTransient <IDnsQueryService, DnsQueryService>(); services.AddTransient <IConsoleTableService, ConsoleTableService>(); services.AddTransient <IConsoleTemplateService, ConsoleTemplateService>(); services.AddSingleton <IPercentageAnimator>(new PercentageAnimator()); // required to run the application services.AddTransient <App>(); return(services); }
public void Execute(string command) { var args = splitArgs(command); var options = new Options(); var optionParser = new CommandLine.Parser(with => { with.MutuallyExclusive = true; with.HelpWriter = Console.Out; }); //if (!CommandLine.Parser.Default.ParseArguments(args, options,(verd,verbOptions)=> if (!optionParser.ParseArguments(args, options, (verd, verbOptions) => { var commandOption = verbOptions as ICliCommand; if (commandOption != null) { commandOption.Execute(this); } })) { //we have a error here Console.WriteLine("Wrong command, please read the help."); } }
public static void Main(string[] args) { var parser = new CommandLine.Parser(with => with.HelpWriter = null); var parserResult = parser.ParseArguments <Options>(args); var helpText = HelpText.AutoBuild(parserResult, h => { h.AdditionalNewLineAfterOption = false; h.Copyright = ""; return(h); }, e => e); parserResult .WithParsed <Options>(options => { PingResponse ping = PingUtils.PingServer(options.MumbleHostname, options.MumblePort); Statsd.SendGauge(options.StatsdHostname, options.StatsdPort, ping.ConnectedUsers); }) .WithNotParsed(errs => { Console.Error.WriteLine(helpText); }); }
static int Main(string[] args) { int code = 0; var parser = new CommandLine.Parser(c => { c.CaseInsensitiveEnumValues = true; }); parser .ParseArguments <Options>(args) .WithParsed <Options>(opts => code = Main(opts).Result) .WithNotParsed <Options>(errs => { foreach (var e in errs) { code = ReportError(e.ToString()); } }); return(code); }
static void Main(string[] args) { var options = new Options(); var parser = new CommandLine.Parser(with => with.HelpWriter = System.Console.Error); if (parser.ParseArguments(args, options)) { if (options.Debug) { utils.Logger.Instance.BasicConfig(); } else { utils.Logger.Instance.XmlConfig(); } utils.Logger.Instance.Log.Info("Program Start"); utils.Logger.Instance.Log.Info("Arg RequestUri: " + options.RequestUri); Run(options); } }
public static void CreateConfig() { if (!File.Exists(ConfigPath)) { System.Text.StringBuilder oStringBuilder = new StringBuilder(); oStringBuilder.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"); oStringBuilder.AppendLine("<configuration>"); var oParser = new CommandLine.Parser(with => with.HelpWriter = null); var oParserResult = oParser.ParseArguments <Options>("--help".Split()); string sHelpText = HelpText.AutoBuild(oParserResult, HelpTextInstance => { HelpTextInstance.AdditionalNewLineAfterOption = false; //remove the extra newline between options HelpTextInstance.Heading = ""; HelpTextInstance.Copyright = ""; HelpTextInstance.MaximumDisplayWidth = 50000; HelpTextInstance.AddDashesToOption = false; HelpTextInstance.AutoVersion = false; HelpTextInstance.AutoHelp = false; return(HelpText.DefaultParsingErrorsHandler(oParserResult, HelpTextInstance)); }, e => e); sHelpText = Regex.Replace(sHelpText, @"\n ., ", " "); sHelpText = Regex.Replace(sHelpText, @" \[-. ", " [Default: "); oStringBuilder.AppendLine(" <!--" + sHelpText.Replace("<br/>", "\n".PadRight(37)) + "\n\n"); oStringBuilder.AppendLine(" To override a Key/Value pair, remove the leading and trailing HTML style comment tags surrounding the line (<!–– ––>)\n -->\n"); oParserResult = oParser.ParseArguments <Options>("".Split()); oParserResult.WithParsed <Options>(options => CreateConfigSection(options, ref oStringBuilder)); oStringBuilder.AppendLine("</configuration>"); var oOptions = new Options(); System.IO.File.WriteAllText(ConfigPath, oStringBuilder.ToString()); } }
public static T ParseAndHandleArguments <T>(string Message, string[] args, bool ignoreError = false) where T : new() { if (args.Length == 1 && args.First() == "--build") { TaskBuilder.BuildSelf(); Environment.Exit(0); } if (args.Length > 1 && args.First() == "--publish") { TaskBuilder.PublishSelf(args).Wait(); Environment.Exit(0); } Console.WriteLine(string.Join(" ", args)); args = MoveBoolsLast(args); Console.WriteLine(Message); if (Environment.GetEnvironmentVariable("SYSTEM_DEBUG") == "true") { Console.WriteLine(string.Join(" ", args)); } // var options = new T(); var b = new CommandLine.Parser((s) => { s.IgnoreUnknownArguments = true; }); var result = RunParseAndHandleArguments <T>(b, args); if (result != null || ignoreError) { return(result); } throw new ArgumentException("Arguments not working " + string.Join(" ", args)); }
// Command line arguments sample: "harvestAll --environment=dev --parseDBEnvironment=prod" // // Some presets that you might copy and paste in: // harvestAll --environment=dev --parseDBEnvironment=local --suppressLogs --count=2 // harvestWarnings --environment=dev --parseDBEnvironment=local --suppressLogs // harvestAll --environment=dev --parseDBEnvironment=local --suppressLogs "--queryWhere={ \"objectId\":\"38WdeYJ0yF\"}" // harvestAll --environment=dev --parseDBEnvironment=dev --suppressLogs "--queryWhere={ \"objectId\":\"JUCL9OMOza\"}" // harvestAll --environment=dev --parseDBEnvironment=dev --suppressLogs "--queryWhere={ \"title\":{\"$in\":[\"Vaccinations\",\"Fox and Frog\",\"The Moon and the Cap\"]}}" public static void Main(string[] args) { // See https://github.com/commandlineparser/commandline for documentation about CommandLine.Parser var parser = new CommandLine.Parser((settings) => { settings.CaseInsensitiveEnumValues = true; settings.CaseSensitive = false; settings.HelpWriter = Console.Error; }); try { parser.ParseArguments <HarvestAllOptions, HarvestHighPriorityOptions, HarvestLowPriorityOptions, HarvestWarningsOptions>(args) .WithParsed <HarvestAllOptions>(options => { Harvester.RunHarvestAll(options); }) .WithParsed <HarvestWarningsOptions>(options => { Harvester.RunHarvestWarnings(options); }) // TODO: Replace placeholders .WithParsed <HarvestHighPriorityOptions>(options => { throw new NotImplementedException("HarvestHighPriority"); }) .WithParsed <HarvestLowPriorityOptions>(options => { throw new NotImplementedException("HarvestLowPriority"); }) .WithNotParsed(errors => { Console.Out.WriteLine("Error parsing command line arguments."); Environment.Exit(1); }); } catch (Exception e) { YouTrackIssueConnector.SubmitToYouTrack(e, "An exception was thrown which was not handled by the program."); throw; } }
public void Execute(string[] args, IContext context) { var parser = new CommandLine.Parser(configuration => configuration.HelpWriter = null); parser.ParseArguments <TOptions>(args) .WithParsed <TOptions>(options => Execute(options, context)) .WithNotParsed(errors => { var error = errors.First(); if (error is CommandLine.MissingRequiredOptionError) { ConsoleHelper.PrintError($"Missing required argument."); } else if (error is CommandLine.UnknownOptionError e) { ConsoleHelper.PrintError($"Unknown argument: {e.Token}"); } else { ConsoleHelper.PrintError(error.ToString()); } }); }
private void Application_Startup(object sender, StartupEventArgs e) { Auxiliary.Logger.Init(); var options = new Options(); foreach (var arg in e.Args) { //_log.Info("Input param " + arg); } AttachConsole(-1); var parser = new CommandLine.Parser(with => { with.MutuallyExclusive = true; with.CaseSensitive = true; with.HelpWriter = Console.Error; }); if (parser.ParseArguments(e.Args, options)) { options.AfterParse(); try{ var cd = new CollectorDialog(options); cd.Show(); } catch (Exception ex) { Auxiliary.Logger._log.Error("Error: " + ex.Message); } } FreeConsole(); }
static void Main(string[] args) { //-- 分析命令行参数 var options = new Options(); var parser = new CommandLine.Parser(with => with.HelpWriter = Console.Error); if (!parser.ParseArgumentsStrict(args, options, () => Environment.Exit(-1))) { //-- 执行导出操作 return; } string outputcsfile = options.OutPutCSFile; //@"../../../../HotFixProto/proto.cs"; string outputswcfile = options.OutPutCSWC; //@"../../../../AS3ProtoBuf_Unity/Assets/StreamingAssets/proto.cswc"; ASTool.Grammar grammar = ASCompiler.Grammar.getGrammar(); string teststring = "package{}"; Dictionary <string, string> srcFiles = new Dictionary <string, string>(); string[] protofiles = null; { string path = options.ProtoAS3; if (path.EndsWith(".as")) { path = System.IO.Path.GetDirectoryName(path); } if (string.IsNullOrEmpty(path)) { path = ".\\"; } string[] ps = path.Split(System.IO.Path.DirectorySeparatorChar); if (ps.Length == 2 && string.IsNullOrEmpty(ps[1]) && ps[0].IndexOf(System.IO.Path.VolumeSeparatorChar) > 0) { Console.WriteLine("无法在根目录下搜索.请将as源代码放到一个文件夹内"); return; } else if (System.IO.Directory.Exists(path)) { //Console.WriteLine(path); //teststring = System.IO.File.ReadAllText(args[0]); //files = System.IO.Directory.GetFiles(path, "*.as", System.IO.SearchOption.AllDirectories); AddSrcFiles(path, srcFiles); protofiles = new string[srcFiles.Count]; srcFiles.Keys.CopyTo(protofiles, 0); //(string[])files.Clone(); } } if (srcFiles.Count == 0) { Console.Write("输入as文件所在路径"); return; } //*********加入ProtoBuf API***** //string apidir = @"../../../../as3protobuflib"; //if (System.IO.Directory.Exists(apidir)) //{ // AddSrcFiles(apidir, srcFiles); //} //********************* var proj = new ASTool.AS3.AS3Proj(); var srcout = new ASTool.ConSrcOut(); foreach (var src in srcFiles) { grammar.hasError = false; teststring = System.IO.File.ReadAllText(src.Key); if (string.IsNullOrEmpty(teststring)) { continue; } teststring = teststring.Replace("override com.netease.protobuf.used_by_generated_code final function", "override protected final function"); var tree = grammar.ParseTree(teststring, ASTool.AS3LexKeywords.LEXKEYWORDS, ASTool.AS3LexKeywords.LEXSKIPBLANKWORDS, src.Value); if (grammar.hasError) { Console.WriteLine(src.Key); Console.WriteLine("解析语法树失败!"); Console.ReadLine(); return; } var analyser = new ASTool.AS3FileGrammarAnalyser(proj, src.Value); if (!analyser.Analyse(tree)) //生成项目的语法树 { Console.WriteLine(analyser.err.ToString()); Console.WriteLine("语义分析失败!"); Console.ReadLine(); return; } #if DEBUG //Console.Clear(); #endif } #if DEBUG Console.WriteLine(); Console.WriteLine("====语法树翻译===="); //runtimeCompiler rtLoader = new runtimeCompiler(); foreach (var p in proj.SrcFiles) { p.Write(0, srcout); } #endif //Console.Read(); //return; ASCompiler.compiler.Builder builder = new ASCompiler.compiler.Builder(); builder.LoadLibrary(System.IO.File.ReadAllBytes("as3protobuf.swc")); //builder.LoadLibrary( System.IO.File.ReadAllBytes("astoolglobal.swc")); builder.Build(proj, null); if (builder.buildErrors.Count == 0) { ASBinCode.CSWC swc = builder.getBuildOutSWC(); //System.IO.File.WriteAllBytes("astoolglobal.swc", swc.toBytes()); //System.IO.File.WriteAllBytes("as3protobuf.swc", swc.toBytes()); System.IO.File.WriteAllBytes(outputswcfile, swc.toBytes()); if (swc != null) { ASRuntime.Player player = new ASRuntime.Player(); player.loadCode(swc); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("using System;"); foreach (var cls in swc.classes) { if (cls.staticClass != null) { //判断是否在编译路径中 string fullname = cls.package + (string.IsNullOrEmpty(cls.package)?"": ".") + cls.name + ".as"; foreach (var f in protofiles) { string ff = f.Replace("\\", ".").Replace("/", "."); if (ff.EndsWith(fullname)) { CodeGen codeGen = new CodeGen(cls, swc, player); string cs = codeGen.GetCode(); Console.Write(cs); stringBuilder.AppendLine(cs); break; } } } } System.IO.File.WriteAllText(outputcsfile, stringBuilder.ToString()); } } }
static void Main(string[] args) { try { var settings = new Settings(); // ReSharper disable once RedundantNameQualifier using (var parser = new CommandLine.Parser(x => { x.CaseSensitive = false; x.IgnoreUnknownArguments = true; })) { if (!parser.ParseArguments(args, settings)) { Console.Error.WriteLine(settings.GetUsage()); return; } } if (!settings.YouTubeOnly) { if (settings.InputFiles == null) { RunMultiDumper(ref settings); } else { // We want to expand any wildcards in the input file list (and also fully qualify them) var inputs = new List <string>(); foreach (var inputFile in settings.InputFiles) { if (File.Exists(inputFile)) { inputs.Add(Path.GetFullPath(inputFile)); continue; } var pattern = Path.GetFileName(inputFile); if (pattern == null) { throw new Exception($"Failed to match {inputFile}"); } var pathPart = inputFile.Substring(0, inputFile.Length - pattern.Length); var directory = pathPart.Length > 0 ? Path.GetFullPath(pathPart) : Directory.GetCurrentDirectory(); var files = Directory.EnumerateFiles(directory, pattern).ToList(); if (files.Count == 0) { throw new Exception($"Failed to match {inputFile}"); } inputs.AddRange(files.OrderByAlphaNumeric(x => x)); } settings.InputFiles = inputs; } if (settings.InputFiles == null || !settings.InputFiles.Any()) { Console.Error.WriteLine(settings.GetUsage()); throw new Exception("No inputs specified"); } var channels = settings.InputFiles .AsParallel() .Select(filename => { var channel = new Channel { Filename = filename, LineColor = ParseColor(settings.LineColor), LineWidth = settings.LineWidth, FillColor = ParseColor(settings.FillColor), Label = Channel.GuessNameFromMultidumperFilename(filename), Algorithm = CreateTriggerAlgorithm(settings.TriggerAlgorithm), TriggerLookaheadFrames = settings.TriggerLookahead, ZeroLineWidth = settings.ZeroLineWidth, ZeroLineColor = ParseColor(settings.ZeroLineColor), LabelFont = settings.ChannelLabelsFont == null ? null : new Font(settings.ChannelLabelsFont, settings.ChannelLabelsSize), LabelColor = ParseColor(settings.ChannelLabelsColor), HighPassFilter = settings.HighPass }; channel.LoadDataAsync().Wait(); channel.ViewWidthInMilliseconds = settings.ViewWidthMs; return(channel); }).Where(ch => ch.SampleCount > 0).ToList(); if (settings.AutoScalePercentage > 0) { float max; bool IsYm2413Percussion(Channel ch) => ch.Label.StartsWith("YM2413 ") && !ch.Label.StartsWith("YM2413 Tone"); if (settings.AutoScaleIgnoreYM2413Percussion) { var channelsToUse = channels.Where(channel => !IsYm2413Percussion(channel)).ToList(); if (channelsToUse.Count == 0) { // Fall back on overall max if all channels are percussion max = channels.Max(ch => ch.Max); } else { max = channelsToUse.Max(ch => ch.Max); } } else { max = channels.Max(ch => ch.Max); } var scale = settings.AutoScalePercentage / 100 / max; foreach (var channel in channels) { channel.Scale = scale; } } if (settings.ChannelLabelsFromVgm && settings.VgmFile != null) { TryGuessLabelsFromVgm(channels, settings.VgmFile); } if (settings.OutputFile != null) { // Emit normalized data to a WAV file for later mixing if (settings.MasterAudioFile == null && !settings.NoMasterMix) { settings.MasterAudioFile = settings.OutputFile + ".wav"; Mixer.MixToFile(channels, settings.MasterAudioFile, !settings.NoMasterMixReplayGain); } } Render(settings, channels); foreach (var channel in channels) { channel.Dispose(); } } if (settings.YouTubeTitle != null) { UploadToYouTube(settings).Wait(); } } catch (Exception e) { Console.Error.WriteLine($"Fatal: {e}"); } }
// ReSharper disable once MethodTooLong private static void Main(string[] args) { try { LoadApplicationSettings(); //Console.BackgroundColor = _Settings.EditorBackgroundColor; //Console.ForegroundColor = _Settings.EditorTextColor; //FillCurrentLineBackground(); var parser = new Parser(with => with.HelpWriter = null); var parserResult = parser.ParseArguments <Options>(args); parserResult .WithParsed(o => { var options = Grammar.ParseOption.None; var loadGui = false; var showParseTree = false; var writeSvg = false; ISyntaxHighlightingGuide guide = null; if (o.Tokens) { options |= Grammar.ParseOption.Tokens; } if (o.Diagnostics) { options |= Grammar.ParseOption.Diagnostics; } if (o.Trace) { options |= Grammar.ParseOption.Trace; } if (o.Tree) { options |= Grammar.ParseOption.Tree; showParseTree = true; } if (!string.IsNullOrEmpty(o.SvgFileName)) { writeSvg = true; options |= Grammar.ParseOption.Tree; } if (o.Sll) { options |= Grammar.ParseOption.Sll; } if (o.Gui) { loadGui = true; options |= Grammar.ParseOption.Tree; } var workingDirectory = Environment.CurrentDirectory; var scanner = new Grammar.Scanner(); var grammar = scanner.LocateGrammar(workingDirectory, o.GrammarName); if (grammar == null) { Console.WriteLine(Resources.GrammarNotFoundErrorMessage, o.GrammarName); return; } // To be used later once syntax highlighting for the console is enabled. //var guideResult = grammar.LoadSyntaxHighlightingGuide(); //guide = guideResult != null ? guideResult.Item2 : new HeuristicSyntaxHighlightingGuide(_Settings); string data; if (!string.IsNullOrEmpty(o.FileName)) { if (!File.Exists(o.FileName)) { Console.WriteLine(Resources.FileNotFoundErrorMessage, o.FileName); return; } var encodingToUse = !string.IsNullOrEmpty(o.EncodingName) ? Encoding.GetEncoding(o.EncodingName) : Encoding.Default; using (var reader = new StreamReader(o.FileName, encodingToUse)) data = reader.ReadToEnd(); } else { //var analyzer = new Analyzer(); var builder = new StringBuilder(); Console.WriteLine(Resources.ReadingFromStandardInputPromptMessage); var currentLine = Console.CursorTop; var keepReading = true; while (keepReading) { if (Console.KeyAvailable) { while (Console.KeyAvailable) { var typed = Console.ReadKey(true); if ((typed.Modifiers & ConsoleModifiers.Control) == ConsoleModifiers.Control && typed.Key == ConsoleKey.Z) { Console.Write("^Z"); keepReading = false; break; } if (typed.Key == ConsoleKey.Enter) { if (Console.CursorTop == Console.BufferHeight - 1) { _ScrollFadeCount++; } Console.WriteLine(); FillCurrentLineBackground(); builder.Append("\r\n"); } else if (typed.Key == ConsoleKey.Tab) { var spaces = new string(' ', _Settings.EditorTabLength); Console.Write(spaces); builder.Append(spaces); } else if (typed.Key == ConsoleKey.Backspace) { if (Console.CursorLeft > 0) { Console.Write(typed.KeyChar); Console.Write(' '); Console.Write(typed.KeyChar); builder.Remove(builder.Length - 1, 1); _Cache.FlushTokensForLine(currentLine - (_ScrollFadeCount + 1)); } } else { Console.Write(typed.KeyChar); builder.Append(typed.KeyChar); } } //analyzer.Tokenize(grammar, builder.ToString()); //HighlightSyntaxInConsole(currentLine - (_ScrollFadeCount + 1), analyzer, guide); } } Console.WriteLine(); data = builder.ToString(); } // If tokens are the only option we've received, we don't need to parse if (options == Grammar.ParseOption.Tokens) { DisplayTokens(grammar, data); return; } // Now we attempt to parse, but still handle a lexer-only grammar. if (grammar.Parser != null) { var analyzer = new Analyzer(); var grammarParser = analyzer.BuildParserWithOptions(grammar, data, options); analyzer.ExecuteParsing(grammarParser, o.RuleName); if (showParseTree) { Console.WriteLine(analyzer.ParserContext.ToStringTree(grammarParser)); } if (writeSvg) { var rules = scanner.GetParserRulesForGrammarParser(grammar.Parser); var grapher = new ParseTreeGrapher() { BackgroundColor = _Settings.GraphNodeBackgroundColor.GetMsAglColor(), BorderColor = _Settings.GraphNodeBorderColor.GetMsAglColor(), TextColor = _Settings.GraphNodeTextColor.GetMsAglColor() }; var graph = grapher.CreateGraph(analyzer.ParserContext, rules.ToList()); graph.LayoutAlgorithmSettings = new SugiyamaLayoutSettings(); GraphRenderer renderer = new GraphRenderer(graph); renderer.CalculateLayout(); graph.EscapeNodesForSvg(); SvgGraphWriter.Write(graph, o.SvgFileName, null, null, 4); } } else { if (options.HasFlag(ParseOption.Tokens)) { DisplayTokens(grammar, data); } if (showParseTree || writeSvg) { Console.WriteLine(Resources.GrammarHasNoParserErrorMessage, grammar.GrammarName); } if (showParseTree) { Console.WriteLine(Resources.UnableToDisplayParseTree); } if (writeSvg) { Console.WriteLine(Resources.SvgWritingAbortedErrorMessage); } } if (loadGui) { LoadGui(data, grammar, o.RuleName); } }) .WithNotParsed(errs => DisplayHelp(parserResult, errs)); #if DEBUG Console.WriteLine(Resources.PressAnyKeyMessage); Console.ReadKey(); #endif } // ReSharper disable once CatchAllClause catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); #if DEBUG Console.WriteLine(Resources.PressAnyKeyMessage); Console.ReadKey(); #endif } }
static void Main(string[] args) { /******************************************************/ SetConsoleCtrlHandler(cancelHandler, true); ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate; ServicePointManager.DefaultConnectionLimit = 1024; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | (SecurityProtocolType)0x300 //Tls11 | (SecurityProtocolType)0xC00; //Tls12 /******************************************************/ try { string loc = "en-US"; string currLoc = Thread.CurrentThread.CurrentUICulture.Name; if (currLoc == "zh-TW" || currLoc == "zh-HK" || currLoc == "zh-MO") { loc = "zh-TW"; } else if (currLoc == "zh-CN" || currLoc == "zh-SG") { loc = "zh-CN"; } //设置语言 CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(loc); Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(loc); } catch (Exception) {; } // 处理m3u8dl URL协议 if (args.Length == 1) { if (args[0].ToLower().StartsWith("m3u8dl:")) { var base64 = args[0].Replace("m3u8dl://", "").Replace("m3u8dl:", ""); var cmd = ""; try { cmd = Encoding.UTF8.GetString(Convert.FromBase64String(base64)); } catch (FormatException) { cmd = Encoding.UTF8.GetString(Convert.FromBase64String(base64.TrimEnd('/'))); } //修正工作目录 Environment.CurrentDirectory = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); args = Global.ParseArguments(cmd).ToArray(); //解析命令行 } else if (args[0] == "--registerUrlProtocol") { RequireElevated(string.Join(" ", args)); bool result = RegisterUriScheme("m3u8dl", Assembly.GetExecutingAssembly().Location); Console.WriteLine(result ? strings.registerUrlProtocolSuccessful : strings.registerUrlProtocolFailed); Environment.Exit(0); } else if (args[0] == "--unregisterUrlProtocol") { RequireElevated(string.Join(" ", args)); bool result = UnregisterUriScheme("m3u8dl"); Console.WriteLine(result ? strings.unregisterUrlProtocolSuccessful : strings.unregisterUrlProtocolFailed); Environment.Exit(0); } } //寻找ffmpeg.exe if (File.Exists("ffmpeg.exe")) { FFmpeg.FFMPEG_PATH = Path.Combine(Environment.CurrentDirectory, "ffmpeg.exe"); } else if (File.Exists(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "ffmpeg.exe"))) { FFmpeg.FFMPEG_PATH = Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "ffmpeg.exe"); } else { try { string[] EnvironmentPath = Environment.GetEnvironmentVariable("Path").Split(';'); foreach (var de in EnvironmentPath) { if (File.Exists(Path.Combine(de.Trim('\"').Trim(), "ffmpeg.exe"))) { FFmpeg.FFMPEG_PATH = Path.Combine(de.Trim('\"').Trim(), "ffmpeg.exe"); goto HasFFmpeg; } } } catch (Exception) { ; } Console.BackgroundColor = ConsoleColor.Red; //设置背景色 Console.ForegroundColor = ConsoleColor.White; //设置前景色,即字体颜色 Console.WriteLine(strings.ffmpegLost); Console.ResetColor(); //将控制台的前景色和背景色设为默认值 Console.WriteLine(strings.ffmpegTip); Console.WriteLine(); Console.WriteLine("http://ffmpeg.org/download.html#build-windows"); Console.WriteLine(); Console.WriteLine(strings.pressAnyKeyExit); Console.ReadKey(); Environment.Exit(-1); } HasFFmpeg: if (!File.Exists(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "NO_UPDATE"))) { Thread checkUpdate = new Thread(() => { Global.CheckUpdate(); }); checkUpdate.IsBackground = true; checkUpdate.Start(); } //ReadLine字数上限 Stream steam = Console.OpenStandardInput(); Console.SetIn(new StreamReader(steam, Encoding.Default, false, 5000)); if (args.Length == 0) { Global.WriteInit(); Console.ForegroundColor = ConsoleColor.Cyan; Console.Write("N_m3u8DL-CLI"); Console.ResetColor(); Console.Write(" > "); var cmd = Console.ReadLine(); if (string.IsNullOrEmpty(cmd)) { Environment.Exit(0); } args = Global.ParseArguments(cmd).ToArray(); //解析命令行 Console.Clear(); } //如果只有URL,没有附加参数,则尝试解析配置文件 else if (args.Length == 1 || (args.Length == 3 && args[1].ToLower() == "--savename")) { if (File.Exists(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "N_m3u8DL-CLI.args.txt"))) { if (args.Length == 3) { args = Global.ParseArguments($"\"{args[0]}\" {args[1]} {args[2]} " + File.ReadAllText(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "N_m3u8DL-CLI.args.txt"))).ToArray(); //解析命令行 } else { args = Global.ParseArguments($"\"{args[0]}\" " + File.ReadAllText(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "N_m3u8DL-CLI.args.txt"))).ToArray(); //解析命令行 } } } var cmdParser = new CommandLine.Parser(with => with.HelpWriter = null); var parserResult = cmdParser.ParseArguments <MyOptions>(args); //解析命令行 parserResult .WithParsed(o => DoWork(o)) .WithNotParsed(errs => DisplayHelp(parserResult, errs)); }
static void Main(string[] args) { if (args != null && args.Length > 0) { IVLVariables.isCommandLineArgsPresent = true; var options = new Options(); var parser = new CommandLine.Parser(with => with.HelpWriter = Console.Error); if (parser.ParseArgumentsStrict(args, options, () => Environment.Exit(-2))) { string path = string.Empty; Common.Validators.FileNameFolderPathValidator f = Common.Validators.FileNameFolderPathValidator.GetInstance(); switch (f.CheckFolderPath(options.ImageSavePath, ref path)) { case Common.Validators.FolderPathErrorCode.Success: { Directory.SetCurrentDirectory(new FileInfo(Application.ExecutablePath).Directory.FullName); IVLVariables.isCommandLineAppLaunch = true; IVLVariables.CmdImageSavePath = path; break; } case Common.Validators.FolderPathErrorCode.FolderPath_Empty: { Directory.SetCurrentDirectory(new FileInfo(Application.ExecutablePath).Directory.FullName); IVLVariables.isCommandLineAppLaunch = true; break; } case Common.Validators.FolderPathErrorCode.InvalidDirectory: { MessageBox.Show("Please enter a valid path for the application to run"); return; } case Common.Validators.FolderPathErrorCode.DirectoryDoesnotExist: { if (!Directory.Exists(options.ImageSavePath)) { Directory.CreateDirectory(options.ImageSavePath); IVLVariables.isCommandLineAppLaunch = true; Directory.SetCurrentDirectory(new FileInfo(Application.ExecutablePath).Directory.FullName); IVLVariables.CmdImageSavePath = options.ImageSavePath; } break; } } if (options.ReportBatchFilePath == null && options.ImageSavePath == null)//this has been added to run the old batchfile and to get the batchfile path. { options.ReportBatchFilePath = options.DefinitionFiles[0]; } if (!string.IsNullOrEmpty(options.ReportBatchFilePath)) { IVLVariables.isCommandLineAppLaunch = false; IVLVariables.batchFilePath = options.ReportBatchFilePath; } } } if (registryKey != null) { IVLVariables.appDirPathName = (string)registryKey.GetValue("AppDataPath"); } bool createdNew = false; using (Mutex mutex = new Mutex(true, "IntuSoft", out createdNew)) { if (createdNew) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); try { if (string.IsNullOrEmpty(IVLVariables.appDirPathName)) { IVLVariables.appDirPathName = new FileInfo(Application.ExecutablePath).Directory.FullName + Path.DirectorySeparatorChar; } else if (Directory.Exists(IVLVariables.appDirPathName)) { IVLVariables.appDirPathName = IVLVariables.appDirPathName + Path.DirectorySeparatorChar; // new FileInfo(Application.ExecutablePath).Directory.FullName + Path.DirectorySeparatorChar; } else { IVLVariables.appDirPathName = new FileInfo(Application.ExecutablePath).Directory.FullName + Path.DirectorySeparatorChar; } LogManager.Configuration.Variables["dir"] = IVLVariables.appDirPathName; LogManager.Configuration.Variables["dir2"] = DateTime.Now.ToString("yyyy-MM-dd"); #region Previous Log Codes Commented //string filePath = new FileInfo(Application.ExecutablePath).Directory.FullName + Path.DirectorySeparatorChar // + "Logs" + Path.DirectorySeparatorChar + DateTime.Now.ToString("dd-MM-yyyy") + Path.DirectorySeparatorChar; //log file path //if (!Directory.Exists(filePath)) // Directory.CreateDirectory(filePath); //log4net.GlobalContext.Properties["LogFileName"] = filePath + "Camera"; //log4net.Config.XmlConfigurator.Configure(); //log4net.GlobalContext.Properties["UIFileName"] = filePath + "UI"; //log4net.Config.XmlConfigurator.Configure(); //log4net.GlobalContext.Properties["FrameEventFileName"] = filePath + "Frames"; //log4net.Config.XmlConfigurator.Configure(); //// Configure log file for capture sequence// //log4net.GlobalContext.Properties["CaptureFileName"] = filePath + "CaptureLog"; //log4net.Config.XmlConfigurator.Configure(); //log4net.GlobalContext.Properties["CaptureSettingsFileName"] = filePath + "CaptureSettingsLog"; //log4net.Config.XmlConfigurator.Configure(); #endregion _currentInstance = new IvlMainWindow(); // code to create logs folder during start of the application Application.Run(_currentInstance); } catch (Exception ex) { Common.ExceptionLogWriter.WriteLog(ex, exceptionLog); // exceptionLog.Info(ex.StackTrace); } } else { //STRING_Program_062 //Common.CustomMessageBox.Show(Resources.Program_01 ,Resources.Software_Name, Common.Common.CustomMessageBoxButtons.OK, Common.CustomMessageBoxIcon.Information); try { #region Region of Commented Code //string filePath = new FileInfo(Application.ExecutablePath).Directory.FullName + Path.DirectorySeparatorChar // + "Logs" + Path.DirectorySeparatorChar + DateTime.Now.ToString("dd-MM-yyyy") + Path.DirectorySeparatorChar; //log file path //if (!Directory.Exists(filePath)) // Directory.CreateDirectory(filePath); //log4net.GlobalContext.Properties["LogFileName"] = filePath + "Camera"; //log4net.Config.XmlConfigurator.Configure(); //log4net.GlobalContext.Properties["UIFileName"] = filePath + "UI"; //log4net.Config.XmlConfigurator.Configure(); //log4net.GlobalContext.Properties["FrameEventFileName"] = filePath + "Frames"; //log4net.Config.XmlConfigurator.Configure(); //// Configure log file for capture sequence// //log4net.GlobalContext.Properties["CaptureFileName"] = filePath + "CaptureLog"; //log4net.Config.XmlConfigurator.Configure(); #endregion if (IVLVariables.LangResourceManager == null) { IVLVariables.LangResourceManager = new ResourceManager("INTUSOFT.Desktop.LanguageResources.Res", typeof(IvlMainWindow).Assembly); } System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(IVLVariables.LangResourceManager.GetString("Software_Name", IVLVariables.LangResourceCultureInfo)); foreach (System.Diagnostics.Process item in processes) { ShowWindow(item.MainWindowHandle, SW_RESTORE); ShowWindow(item.MainWindowHandle, SW_SHOWMAXIMIZED); SetForegroundWindow(item.MainWindowHandle); } } catch (Exception ex) { Common.ExceptionLogWriter.WriteLog(ex, exceptionLog); } } } }
} // proc AddToProcessEnvironment /// <summary>Eintrittspunkt in die Anwendung.</summary> /// <param name="args">Parameter die übergeben werden. Ungenutzt.</param> public static void Main(string[] args) { #if DEBUG var readlineAtTheEnd = false; #endif var printHeader = new Action(() => { Console.WriteLine(HeadingInfo.Default.ToString()); Console.WriteLine(CopyrightInfo.Default.ToString()); #if DEBUG readlineAtTheEnd = true; #endif }); try { var parser = new CommandLine.Parser(s => { s.CaseSensitive = false; s.IgnoreUnknownArguments = false; s.HelpWriter = null; s.ParsingCulture = CultureInfo.InvariantCulture; }); // work with arguments var r = parser.ParseArguments(args, new Type[] { typeof(RunOptions), typeof(RegisterOptions), typeof(UnregisterOptions) }); r.MapResult <RunOptions, RegisterOptions, UnregisterOptions, bool>( opts => // run { // print heading if (opts.Verbose) { printHeader(); } // validate arguments opts.Validate(); // execute the service var app = new DEServer(opts.ConfigurationFile, opts.Properties); if (opts.Verbose) // Run the console version of the service { app.ServiceLog = new ConsoleLog(); app.OnStart(); Console.WriteLine("Service is started."); Console.ReadLine(); app.OnStop(); } else { ServiceBase.Run(new Service(ServicePrefix + opts.ServiceName, app)); // Start as a windows service } return(true); }, opts => // register { // print heading printHeader(); // validate arguments opts.Validate(); // form the run command line var runOpts = new RunOptions(opts); var serviceCommandLine = parser.FormatCommandLine(runOpts, o => { o.PreferShortName = true; }); // register the service RegisterService(opts.ServiceName, serviceCommandLine); Console.WriteLine("Service '{0}{1}' created/modified.", ServicePrefix, opts.ServiceName); return(true); }, opts => // unregister { // print heading printHeader(); UnregisterService(opts.ServiceName); Console.WriteLine("Service '{0}{1}' removed.", ServicePrefix, opts.ServiceName); return(true); }, errors => { // print help var help = CommandLine.Text.HelpText.AutoBuild(r); if (errors.FirstOrDefault(e => e is HelpVerbRequestedError) != null) { help.AddPreOptionsLine(Environment.NewLine + "Usage:"); help.AddPreOptionsLine(" DEServer.exe run -v -c [configuration file] -n [name] {properties}"); help.AddPreOptionsLine(" DEServer.exe register -c [configuration file] -n [name] {properties}"); help.AddPreOptionsLine(" DEServer.exe unregister --name [name] "); } if (errors.FirstOrDefault(e => e is VersionRequestedError) != null) { // todo: add detailed version info help.AddPostOptionsLine("Assembly version: todo"); } Console.WriteLine(help.ToString()); return(false); } ); } catch (Exception e) { Console.WriteLine(e.GetMessageString()); #if DEBUG if (readlineAtTheEnd) { Console.ReadLine(); } #endif } } // proc Main
static void Main(string[] args) { var config = new Config(); var settings = new CommandLine.ParserSettings(true, true, false, Console.Error); var parser = new CommandLine.Parser(settings); string inputPath = null, outputPath = null; bool isExtract = false, isRawExtract = false, isCreate = false; if (args.Length == 0) { // Don't try to parse zero arguments or else it results in an exception Console.WriteLine(config.GetUsage()); Environment.Exit(-1); } if (parser.ParseArguments(args, config)) { if (!String.IsNullOrWhiteSpace(config.InputFileRaw)) { inputPath = config.InputFileRaw; isRawExtract = true; isExtract = true; } else if (!String.IsNullOrWhiteSpace(config.InputFile)) { inputPath = config.InputFile; isExtract = true; } else if (!String.IsNullOrWhiteSpace(config.InputFolder)) { inputPath = config.InputFolder; isCreate = true; } if (!String.IsNullOrWhiteSpace(config.OutputPath)) { outputPath = config.OutputPath; } else { if (isCreate) { outputPath = inputPath + ".ctpk"; } else { string basePath = Path.GetDirectoryName(inputPath); string baseFilename = Path.GetFileNameWithoutExtension(inputPath); if (!String.IsNullOrWhiteSpace(basePath)) { baseFilename = Path.Combine(basePath, baseFilename); } outputPath = baseFilename; } } } if (isCreate) { Ctpk.Create(inputPath, outputPath); } else if (isExtract) { Ctpk.Read(inputPath, outputPath, isRawExtract); } else { Console.WriteLine("Could not find path or file '{0}'", args[0]); } }
static void Main(string[] args) { Versionr.Utilities.Misc.StartTimer(); try { string workingDirectoryPath = Environment.CurrentDirectory; var printerStream = new Printer.PrinterStream(); var nullstream = new System.IO.MemoryStream(); VersionOptions initalOpts = new VersionOptions(); CommandLine.Parser silentparser = new CommandLine.Parser(new Action <ParserSettings>( (ParserSettings p) => { p.CaseSensitive = true; p.IgnoreUnknownArguments = false; p.HelpWriter = new System.IO.StreamWriter(nullstream); p.MutuallyExclusive = true; })); CommandLine.Parser parser = new CommandLine.Parser(new Action <ParserSettings>( (ParserSettings p) => { p.CaseSensitive = true; p.IgnoreUnknownArguments = false; p.HelpWriter = printerStream; p.MutuallyExclusive = true; })); if (args.Length >= 1 && args[0] == "--version" && parser.ParseArguments(args, initalOpts) && initalOpts.Version) { Printer.WriteLineMessage("#b#Versionr## v{0} #q#{1}{2}", System.Reflection.Assembly.GetCallingAssembly().GetName().Version, Utilities.MultiArchPInvoke.IsX64 ? "x64" : "x86", Utilities.MultiArchPInvoke.IsRunningOnMono ? " (using Mono runtime)" : ""); Printer.WriteLineMessage("#q#- A less hateful version control system."); Printer.PushIndent(); Printer.WriteLineMessage("\n#b#Core version: {0}\n", Area.CoreVersion); foreach (var x in Area.ComponentVersions) { Printer.WriteLineMessage("{0}: #b#{1}", x.Item1, x.Item2); } Printer.PopIndent(); Printer.WriteLineMessage("\n#b#Plugins:\n"); Printer.PushIndent(); foreach (var plugin in PluginCache.Plugins) { Printer.WriteLineMessage("#b#{1}## ({2}) #q#{0}", Path.GetFileName(plugin.Assembly.Location), plugin.Attributes.Name, plugin.Assembly.GetName().Version); } Printer.PopIndent(); Printer.RestoreDefaults(); return; } if (args.Length == 0) { PrintAllOptions(args, parser, printerStream); printerStream.Flush(); Printer.PrintMessage("\n#e#Error## - missing command."); Printer.RestoreDefaults(); Environment.Exit(CommandLine.Parser.DefaultExitCodeFail); } // We will attempt to parse the commandline first object options = null; string invokedVerb = string.Empty; object invokedVerbInstance = null; object activatedPlugin = null; foreach (object pluginOptions in PluginOptions) { if (silentparser.ParseArguments(args, pluginOptions, (verb, success, subOptions) => { if (subOptions != null) { invokedVerb = verb; activatedPlugin = pluginOptions; } invokedVerbInstance = subOptions; })) { options = pluginOptions; break; } if (invokedVerb != string.Empty) { break; } } if (options == null) { if (invokedVerb != string.Empty && activatedPlugin != null) { // First, does the option object even support help? System.Reflection.MethodInfo helpOptionVerb = GetVerbHelpMethod(activatedPlugin); if (helpOptionVerb != null) { // We hit a verb, but the commandline parser is unhappy at us, re-run the parse parser.ParseArguments(args, activatedPlugin, (verb, success, subOptions) => { }); } else { if (invokedVerbInstance is VerbOptionBase) { printerStream.WriteLine(((VerbOptionBase)invokedVerbInstance).GetUsage()); } else { Printer.PrintMessage("Warning - verb #b#{0}##: command is malformed and cannot be parsed.", invokedVerb); Printer.PrintMessage("No help method defined on verb object.", invokedVerb); } } } else { PrintAllOptions(args, parser, printerStream); } printerStream.Flush(); Printer.RestoreDefaults(); Environment.Exit(CommandLine.Parser.DefaultExitCodeFail); } if (!string.IsNullOrEmpty((invokedVerbInstance as VerbOptionBase).Logfile)) { Printer.OpenLog((invokedVerbInstance as VerbOptionBase).Logfile); } Console.CancelKeyPress += Console_CancelKeyPress; try { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); // because lewis broke 'lg' on purpose if (args.Count() > 0 && args[0] == "lg" && invokedVerbInstance is Commands.LogVerbOptions) { ((Commands.LogVerbOptions)invokedVerbInstance).Jrunting = true; } int bmc = 1; bool bm = false; if (invokedVerbInstance is VerbOptionBase) { bm = ((VerbOptionBase)invokedVerbInstance).Benchmark; bmc = ((VerbOptionBase)invokedVerbInstance).BMC; } for (int i = 0; i < (bm ? bmc : 1); i++) { Commands.BaseCommand command = ((VerbOptionBase)invokedVerbInstance).GetCommand(); VerbOptionBase baseOptions = invokedVerbInstance as VerbOptionBase; if (baseOptions != null) { Printer.NoColours = baseOptions.NoColours; } bool result = command.Run(new System.IO.DirectoryInfo(workingDirectoryPath), invokedVerbInstance); if (!result) { printerStream.Flush(); Printer.RestoreDefaults(); Environment.Exit(2); } } if (bm) { Printer.PrintMessage("\nOperation took #b#{0}## ms.", sw.ElapsedMilliseconds); } printerStream.Flush(); Printer.RestoreDefaults(); return; } catch (Exception e) { printerStream.Flush(); System.Console.WriteLine("Error processing action:\n{0}", e.ToString()); Printer.RestoreDefaults(); Environment.Exit(20); } Printer.RestoreDefaults(); } catch { Environment.Exit(100); } return; }
private static int Main(string[] args) { //Disable default help text. var parser = new CommandLine.Parser(with => with.HelpWriter = null); var program = new Program(); return(Parser.Default.ParseArguments <CLIOptions, K8sOptions>(args) .MapResult( (CLIOptions options) => { var analyzerConfig = program.ParseCLI(options); //Initialize metrics collectors var collectorConfig = new MetricsCollectorConfig() { RunLength = TimeSpan.FromSeconds(options.ServerMetricsDuration), UpdateFrequency = analyzerConfig.UpdateFrequency, }; var metricsCollectorServerOnly = new MetricsCollector(collectorConfig); var metricsCollectorModel = new MetricsCollector(collectorConfig); Console.CancelKeyPress += delegate { ExportMetrics(options, metricsCollectorServerOnly, metricsCollectorModel); }; try { foreach (var model in options.ModelNames) { try { while (ModelAnalyzer.IsServerRunning()) { Thread.Sleep(TimeSpan.FromSeconds(1)); } analyzerConfig.ModelName = model; var analyzer = new ModelAnalyzer(analyzerConfig, metricsCollectorServerOnly, metricsCollectorModel); analyzer.RunLocal(); } catch (ModelLoadException) { Console.WriteLine($"Failed to load {model} on inference server: skipping model"); } catch (Exception exception) { Console.WriteLine(exception.ToString()); } } } finally { ExportMetrics(options, metricsCollectorServerOnly, metricsCollectorModel); } return 0; }, (K8sOptions options) => { var analyzerConfig = program.ParseK8s(options); //Initialize metrics collectors var collectorConfig = new MetricsCollectorConfig() { RunLength = TimeSpan.FromSeconds(options.ServerMetricsDuration), UpdateFrequency = analyzerConfig.UpdateFrequency, }; var metricsCollectorServerOnly = new MetricsCollector(collectorConfig); var metricsCollectorModel = new MetricsCollector(collectorConfig); Console.CancelKeyPress += delegate { ExportMetrics(options, metricsCollectorServerOnly, metricsCollectorModel); }; try { foreach (var model in options.ModelNames) { try { analyzerConfig.ModelName = model; var analyzer = new ModelAnalyzer(analyzerConfig, metricsCollectorServerOnly, metricsCollectorModel); analyzer.RunK8s(); } catch (ModelLoadException) { Console.WriteLine($"Failed to load {model} on inference server: skipping model"); } catch (Exception exception) { Console.WriteLine(exception.ToString()); } } } finally { ExportMetrics(options, metricsCollectorServerOnly, metricsCollectorModel); } return 0; }, errs => { return -1; } )); }
static int Main(string[] args) { var options = new Options(); string verb = ""; object subOptions = null; var ps = new CommandLine.ParserSettings(); IUserCredentialApplication credential = new Auth.UserCredentialApplicationFromFile(); CommandLine.Parser parser = new CommandLine.Parser(new CommandLine.ParserSettings { MutuallyExclusive = true, CaseSensitive = false, HelpWriter = Console.Error }); parser = CommandLine.Parser.Default; if (parser.ParseArguments(args, options, (_verb, _subOptions) => { verb = _verb; subOptions = _subOptions; })) { (subOptions as BaseOptions).CommandLine = string.Join(" ", args); switch (verb) { case "upload": { var uploadOptions = subOptions as UploadOptions; if (!uploadOptions.Batch && string.IsNullOrWhiteSpace(uploadOptions.ModuleName)) { Console.Error.Write(options.GetUsage("upload")); return(-1); } var drive = new IO.Google.Drive(credential); var uploader = new Uploader(drive); uploader.Upload(uploadOptions); } break; case "download": { var drive = new IO.Google.Drive(credential); var downloader = new Downloader(drive); downloader.Download(subOptions as DownloadOptions); } break; case "diff": { var diffOptions = subOptions as DiffOptions; var drive = new IO.Google.Drive(credential); var folder = drive.FindFolder(diffOptions.GDriveFolder); ITranslationModule localModule = IO.ResX.FromResX(diffOptions.ResXDir, diffOptions.ModuleName, "en"); var downloader = new Downloader(drive); var xlsx = downloader.DownloadXlsx(diffOptions); var _remoteModule = IO.XlsX.FromXLSX(diffOptions.FileName, "en", xlsx); _remoteModule.Name = diffOptions.ModuleName; ITranslationModule remoteModule = _remoteModule.FilterByTags(diffOptions.Tags); TranslationModuleDiff diff = localModule.Diff(remoteModule); var diffJson = Newtonsoft.Json.JsonConvert.SerializeObject(diff, Newtonsoft.Json.Formatting.Indented); Console.OutputEncoding = System.Text.Encoding.UTF8; Console.Write(diffJson); if (diffOptions.HTML) { var htmlLogger = new HTMLConcatLogger(); diff.Print(htmlLogger); var fileName = System.IO.Path.GetTempFileName() + ".html"; System.IO.File.WriteAllText(fileName, htmlLogger.HTML); System.Diagnostics.Process.Start(fileName); } } break; case "patch": { var patchOptions = subOptions as PatchOptions; //read patch data from stdin Console.InputEncoding = System.Text.Encoding.UTF8; var jsonReader = new System.Text.StringBuilder(); string s; while ((s = Console.ReadLine()) != null) { jsonReader.AppendLine(s); } string json = jsonReader.ToString(); //string json = System.IO.File.ReadAllText(@".\diff"); var diff = Newtonsoft.Json.JsonConvert.DeserializeObject <TranslationModuleDiff>(json); TranslationModule localModule = IO.ResX.FromResX(patchOptions.ResXDir, patchOptions.ModuleName, "en"); localModule.Patch(diff); IO.ResX.ToResX(localModule, patchOptions.ResXDir); } break; } } return(0); }