private static ArgumentSyntax DefineCommand(string args) { var cmd = new AccountUpdateCommand( NoopSettings(), (u, k) => new Mock <IAcmeContext>().Object, new FileUtil()); Assert.Equal(CommandGroup.Account.Command, cmd.Group.Command); return(ArgumentSyntax.Parse(args.Split(' '), syntax => { syntax.HandleErrors = false; syntax.DefineCommand("noop"); cmd.Define(syntax); })); }
//----------------------------------------------------------------------------------------------------------------------------------------------------- private void PublishMicroservice() { var publish = new PublishCommand(); var arguments = ArgumentSyntax.Parse( new[] { publish.Name, _microserviceFolderPath, "--no-cli", "--project-config", _projectConfigurationName }, syntax => publish.BindToCommandLine(syntax) ); publish.ValidateArguments(arguments); publish.Execute(); _microserviceFolderPath = publish.PublishFolderPath; }
static void ProcessCommandLine(string[] args) { string configFile = default; // Parse command line args first. var argSyntax = ArgumentSyntax.Parse(args, syntax => { configFile = syntax.DefineOption("c|config", "configs/Manager.conf").Value; }); // Read config file.. ManagerConfig.Initialize(configFile); }
int Run(string[] args) { ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax => { syntax.DefineOption("b|bool", ref _boolOption, "Bool option"); syntax.DefineOption("s|string", ref _stringOption, "String option"); }); Console.WriteLine($"Bool option: {_boolOption}"); Console.WriteLine($"String option: {_stringOption}"); return(0); }
static int Main(string[] args) { IReadOnlyList <string> compile = Array.Empty <string>(); IReadOnlyList <string> refs = Array.Empty <string>(); IReadOnlyList <string> generatorSearchPaths = Array.Empty <string>(); string generatedCompileItemFile = null; string outputDirectory = null; ArgumentSyntax.Parse(args, syntax => { syntax.DefineOptionList("r|reference", ref refs, "Paths to assemblies being referenced"); syntax.DefineOptionList("generatorSearchPath", ref generatorSearchPaths, "Paths to folders that may contain generator assemblies"); syntax.DefineOption("out", ref outputDirectory, true, "The directory to write generated source files to"); syntax.DefineOption("generatedFilesList", ref generatedCompileItemFile, "The path to the file to create with a list of generated source files"); syntax.DefineParameterList("compile", ref compile, "Source files included in compilation"); }); if (!compile.Any()) { Console.Error.WriteLine("No source files are specified."); return(1); } if (outputDirectory == null) { Console.Error.WriteLine("The output directory must be specified."); return(2); } var generator = new CompilationGenerator { Compile = compile, ReferencePath = refs, GeneratorAssemblySearchPaths = generatorSearchPaths, IntermediateOutputDirectory = outputDirectory, }; generator.Generate(); if (generatedCompileItemFile != null) { File.WriteAllLines(generatedCompileItemFile, generator.GeneratedFiles); } foreach (var file in generator.GeneratedFiles) { Console.WriteLine(file); } return(0); }
private ArgumentSyntax ParseCommandLine(string[] args) { IReadOnlyList <string> inputFiles = Array.Empty <string>(); IReadOnlyList <string> referenceFiles = Array.Empty <string>(); bool waitForDebugger = false; AssemblyName name = typeof(Program).GetTypeInfo().Assembly.GetName(); ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax => { syntax.ApplicationName = name.Name.ToString(); // HandleHelp writes to error, fails fast with crash dialog and lacks custom formatting. syntax.HandleHelp = false; syntax.HandleErrors = true; syntax.DefineOption("h|help", ref _help, "Help message for ILC"); syntax.DefineOptionList("r|reference", ref referenceFiles, "Reference file(s) for compilation"); syntax.DefineOption("o|out", ref _options.OutputFilePath, "Output file path"); syntax.DefineOption("cpp", ref _options.IsCppCodeGen, "Compile for C++ code-generation"); syntax.DefineOption("nolinenumbers", ref _options.NoLineNumbers, "Debug line numbers for C++ code-generation"); syntax.DefineOption("dgmllog", ref _options.DgmlLog, "Save result of dependency analysis as DGML"); syntax.DefineOption("fulllog", ref _options.FullLog, "Save detailed log of dependency analysis"); syntax.DefineOption("verbose", ref _options.Verbose, "Enable verbose logging"); syntax.DefineOption("systemmodule", ref _systemModuleName, "System module name (default: System.Private.CoreLib)"); syntax.DefineOption("multifile", ref _multiFile, "Compile only input files (do not compile referenced assemblies)"); syntax.DefineOption("waitfordebugger", ref waitForDebugger, "Pause to give opportunity to attach debugger"); syntax.DefineOption("singlemethodtypename", ref _singleMethodTypeName, "Single method compilation: name of the owning type"); syntax.DefineOption("singlemethodname", ref _singleMethodName, "Single method compilation: name of the method"); syntax.DefineOptionList("singlemethodgenericarg", ref _singleMethodGenericArgs, "Single method compilation: generic arguments to the method"); syntax.DefineParameterList("in", ref inputFiles, "Input file(s) to compile"); }); if (waitForDebugger) { Console.WriteLine("Waiting for debugger to attach. Press ENTER to continue"); Console.ReadLine(); } foreach (var input in inputFiles) { Helpers.AppendExpandedPaths(_inputFilePaths, input, true); } foreach (var reference in referenceFiles) { Helpers.AppendExpandedPaths(_referenceFilePaths, reference, false); } return(argSyntax); }
public static async Task Main(string[] args) { var launchDebugger = false; string logFilePath = null; var logLevel = LogLevel.Warning; logFilePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "ShaderTools"); ArgumentSyntax.Parse(args, syntax => { syntax.DefineOption("launchdebugger", ref launchDebugger, false, "Set whether to launch the debugger or not."); //syntax.DefineOption("logfilepath", ref logFilePath, true, "Fully qualified path to the log file."); syntax.DefineOption("loglevel", ref logLevel, x => (LogLevel)Enum.Parse(typeof(LogLevel), x), false, "Logging level."); }); if (launchDebugger) { Debugger.Launch(); } LanguageServerHost languageServerHost = null; try { languageServerHost = await LanguageServerHost.Create( Console.OpenStandardInput(), Console.OpenStandardOutput(), logFilePath, logLevel); } catch (Exception ex) { languageServerHost?.Dispose(); Console.Error.WriteLine(ex); return; } try { await languageServerHost.WaitForExit; } catch (Exception ex) { Console.Error.WriteLine(ex); return; } finally { languageServerHost.Dispose(); } }
public static void Main(string[] args) { int port = 5000; int uiPort = 5001; bool runWebUi = false; string input = null; string output = null; bool verbose = false; ArgumentSyntax.Parse(args, syntax => { syntax.DefineOption("p|port", ref port, "Port to listen for incoming connections on."); syntax.DefineOption("o|output", ref output, "Path to save downloaded files to."); syntax.DefineOption("v|verbose", ref verbose, "Show detailed logging information."); var uiPortArgument = syntax.DefineOption("ui", ref uiPort, false, "Run a web UI, optionally specifying the port to listen on (default: 5001)."); runWebUi = uiPortArgument.IsSpecified; syntax.DefineParameter("input", ref input, "Path of torrent file to download."); }); if (verbose) { LogManager.Configure(factory => factory.AddConsole(LogLevel.Debug)); } else { LogManager.Configure(factory => factory.AddConsole(LogLevel.Information)); } var client = new TorrentClient(port); var extensionProtocolModule = new ExtensionProtocolModule(); //extensionProtocolModule.RegisterMessageHandler(new PeerExchangeMessageHandler(client.AdapterAddress)); extensionProtocolModule.RegisterMessageHandler(new MetadataMessageHandler()); client.Modules.Register(extensionProtocolModule); if (runWebUi) { var uri = client.EnableWebUI(uiPort); Console.WriteLine($"Web UI started at {uri}"); } var download = client.Add(input, output); download.Start(); Console.WriteLine("Downloading..."); download.WaitForDownloadCompletionAsync().Wait(); Console.ReadKey(); }
public Config(string[] args) { // Get configuration values from JIT_DASM_ROOT/asmdiff.json LoadFileConfig(); _syntaxResult = ArgumentSyntax.Parse(args, syntax => { // Diff command section. syntax.DefineCommand("diff", ref _command, Commands.Diff, "Run asm diff of base/diff."); syntax.DefineOption("b|base", ref _baseExe, "The base compiler exe or tag."); syntax.DefineOption("d|diff", ref _diffExe, "The diff compiler exe or tag."); syntax.DefineOption("o|output", ref _outputPath, "The output path."); syntax.DefineOption("a|analyze", ref _analyze, "Analyze resulting base, diff dasm directories."); syntax.DefineOption("t|tag", ref _tag, "Name of root in output directory. Allows for many sets of output."); syntax.DefineOption("m|mscorlibonly", ref _mscorlibOnly, "Disasm mscorlib only"); syntax.DefineOption("f|frameworksonly", ref _frameworksOnly, "Disasm frameworks only"); syntax.DefineOption("v|verbose", ref _verbose, "Enable verbose output"); syntax.DefineOption("core_root", ref _platformPath, "Path to test CORE_ROOT."); syntax.DefineOption("test_root", ref _testPath, "Path to test tree"); // List command section. syntax.DefineCommand("list", ref _command, Commands.List, "List defaults and available tools asmdiff.json."); syntax.DefineOption("v|verbose", ref _verbose, "Enable verbose output"); // Install command section. syntax.DefineCommand("install", ref _command, Commands.Install, "Install tool in config."); syntax.DefineOption("j|job", ref _jobName, "Name of the job."); syntax.DefineOption("n|number", ref _number, "Job number."); syntax.DefineOption("l|last_successful", ref _lastSuccessful, "Last successful build."); syntax.DefineOption("b|branch", ref _branchName, "Name of branch."); }); // Run validation code on parsed input to ensure we have a sensible scenario. SetRID(); Validate(); ExpandToolTags(); DeriveOutputTag(); // Now that output path and tag are guaranteed to be set, update // the output path to included the tag. _outputPath = Path.Combine(_outputPath, _tag); }
public void Parse(string[] args) { ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax => { IReadOnlyList <string> filters = Array.Empty <string>(); syntax.DefineOptionList( "filter", ref filters, "Filter to apply to repositories of the config json - wildcard chars * and ? supported"); Filters = filters; string configPath = null; syntax.DefineParameter( "config", ref configPath, "Path to the config json file"); ConfigPath = configPath; string gitUser = null; syntax.DefineParameter( "git-user", ref gitUser, "GitHub user used to make PR"); GitUser = gitUser; string gitEmail = null; syntax.DefineParameter( "git-email", ref gitEmail, "GitHub email used to make PR"); GitEmail = gitEmail; string gitAuthToken = null; syntax.DefineParameter( "git-auth-token", ref gitAuthToken, "GitHub authorization token used to make PR"); GitAuthToken = gitAuthToken; }); // Workaround for https://github.com/dotnet/corefxlab/issues/1689 foreach (Argument arg in argSyntax.GetActiveArguments()) { if (arg.IsParameter && !arg.IsSpecified) { Console.WriteLine($"error: `{arg.Name}` must be specified."); Environment.Exit(1); } } }
public static int Main(string[] args) { int result = 0; try { ICommand[] commands = Container.GetExportedValues <ICommand>().ToArray(); ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax => { foreach (ICommand command in commands) { command.Options.ParseCommandLine(syntax); } }); // Workaround for https://github.com/dotnet/corefxlab/issues/1689 foreach (Argument arg in argSyntax.GetActiveArguments()) { if (arg.IsParameter && !arg.IsSpecified) { Logger.WriteError($"error: `{arg.Name}` must be specified."); Environment.Exit(1); } } if (argSyntax.ActiveCommand != null) { // Capture the Docker version and info in the output. ExecuteHelper.Execute(fileName: "docker", args: "version", isDryRun: false); ExecuteHelper.Execute(fileName: "docker", args: "info", isDryRun: false); ICommand command = commands.Single(c => c.Options == argSyntax.ActiveCommand.Value); if (command is IManifestCommand manifestCommand) { manifestCommand.LoadManifest(); } command.ExecuteAsync().Wait(); } } catch (Exception e) { Logger.WriteError(e.ToString()); result = 1; } return(result); }
public static int Main(string[] args) { int result = 0; try { ICommand[] commands = { new BuildCommand(), new GenerateTagsReadmeCommand(), new PublishManifestCommand(), new UpdateReadmeCommand(), new UpdateVersionsCommand(), }; ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax => { foreach (ICommand command in commands) { command.Options.ParseCommandLine(syntax); } }); // Workaround for https://github.com/dotnet/corefxlab/issues/1689 foreach (Argument arg in argSyntax.GetActiveArguments()) { if (arg.IsParameter && !arg.IsSpecified) { Console.Error.WriteLine($"error: `{arg.Name}` must be specified."); Environment.Exit(1); } } if (argSyntax.ActiveCommand != null) { ICommand command = commands.Single(c => c.Options == argSyntax.ActiveCommand.Value); command.LoadManifest(); command.ExecuteAsync().Wait(); } } catch (Exception e) { Console.WriteLine(e); result = 1; } return(result); }
public Config(string[] args) { _syntaxResult = ArgumentSyntax.Parse(args, syntax => { // NOTE!!! - Commands and their options are ordered. Moving an option out of line // could move it to another command. Take a careful look at how they're organized // before changing. syntax.DefineCommand("list", ref _command, Command.List, "List jobs on dotnet-ci.cloudapp.net for the repo."); syntax.DefineOption("s|server", ref _server, "Url of the server. Defaults to http://ci.dot.net/"); syntax.DefineOption("j|job", ref _jobName, "Name of the job."); syntax.DefineOption("b|branch", ref _branchName, "Name of the branch (default is master)."); syntax.DefineOption("r|repo", ref _repoName, "Name of the repo (e.g. dotnet_corefx or dotnet_coreclr). Default is dotnet_coreclr."); syntax.DefineOption("m|match", ref _matchPattern, "Regex pattern used to select jobs output."); syntax.DefineOption("n|number", ref _number, "Job number."); syntax.DefineOption("l|last_successful", ref _lastSuccessful, "List last successful build."); syntax.DefineOption("c|commit", ref _commit, "List build at this commit."); syntax.DefineOption("a|artifacts", ref _artifacts, "List job artifacts on server."); syntax.DefineCommand("copy", ref _command, Command.Copy, "Copies job artifacts from dotnet-ci.cloudapp.net. " + "This command copies a zip of artifacts from a repo (defaulted to dotnet_coreclr)." + " The default location of the zips is the Product sub-directory, though " + "that can be changed using the ContentPath(p) parameter"); syntax.DefineOption("s|server", ref _server, "Url of the server. Defaults to http://ci.dot.net/"); syntax.DefineOption("j|job", ref _jobName, "Name of the job."); syntax.DefineOption("n|number", ref _number, "Job number."); syntax.DefineOption("l|last_successful", ref _lastSuccessful, "Copy last successful build."); syntax.DefineOption("c|commit", ref _commit, "Copy this commit."); syntax.DefineOption("b|branch", ref _branchName, "Name of the branch (default is master)."); syntax.DefineOption("r|repo", ref _repoName, "Name of the repo (e.g. dotnet_corefx or dotnet_coreclr). Default is dotnet_coreclr."); syntax.DefineOption("o|output", ref _outputPath, "The path where output will be placed."); syntax.DefineOption("or|output_root", ref _outputRoot, "The root directory where output will be placed. A subdirectory named by job and build number will be created within this to store the output."); syntax.DefineOption("u|unzip", ref _unzip, "Unzip copied artifacts"); syntax.DefineOption("p|ContentPath", ref _contentPath, "Relative product zip path. Default is artifact/bin/Product/*zip*/Product.zip"); }); // Run validation code on parsed input to ensure we have a sensible scenario. validate(); }
static void Main(string[] args) { string inputDir = Directory.GetCurrentDirectory(); string outputDir = Path.Combine(inputDir, "bin", "dpkg"); string overrideName = null, overrideVersion = null; ArgumentSyntax.Parse(args, syntax => { syntax.ApplicationName = "dotnet deb-tool"; syntax.DefineOption("i|input-dir", ref inputDir, "The path to the package source directory (default: current directory)"); syntax.DefineOption("o|output-dir", ref outputDir, "Where to create the final .deb files (default ./bin/dpkg)"); syntax.DefineOption("override-name", ref overrideName, "Override the package name in the debian_config.json file"); syntax.DefineOption("override-version", ref overrideVersion, "Override the package version in the debian_config.json file"); }); }
public CommandLineOptions(string[] args) { ArgumentSyntax.Parse(args, syntax => { syntax.ApplicationName = "Editor"; syntax.DefineOption("opengl", ref _preferOpenGL, "Prefer using the OpenGL rendering backend."); syntax.DefineOption("project|p", ref _project, "Specifies the project to open."); syntax.DefineOption("scene|s", ref _scene, "Specifies the scene to open."); syntax.DefineOption( "audio", ref _audioPreference, s => (AudioEnginePreference)Enum.Parse(typeof(AudioEnginePreference), s, true), "Specifies the audio engine to use."); }); }
public bool ParseArgs(string[] args, out bool hasErrors) { hasErrors = false; if (args == null || args.Length == 0) { return(true); } bool squirrelOption = false; try { ArgumentSyntax.Parse(args, syntax => { syntax.HandleHelp = false; syntax.HandleErrors = false; if (DefineSquirrelOption(syntax, "squirrel-install", CommandEnum.SquirrelInstall, true) || DefineSquirrelOption(syntax, "squirrel-updated", CommandEnum.SquirrelUpdated, true) || DefineSquirrelOption(syntax, "squirrel-obsolete", CommandEnum.SquirrelObsolete, true) || DefineSquirrelOption(syntax, "squirrel-uninstall", CommandEnum.SquirrelUninstall, true) || DefineSquirrelOption(syntax, "squirrel-firstrun", CommandEnum.SquirrelFirstRun, false)) { // If this is a Squirrel option, we don't need to continue processing args squirrelOption = true; } }); } catch (Exception) { // Don't worry about errors from the first pass } if (squirrelOption) { return(true); } // Second pass for non-Squirrel options ArgumentSyntax parsed = ArgumentSyntax.Parse(args, syntax => { syntax.DefineCommand("update", ref Command, CommandEnum.Update, "Update to the latest version."); syntax.DefineCommand("add-path", ref Command, CommandEnum.AddPath, "Add the installation path to the PATH system environment variable."); syntax.DefineCommand("remove-path", ref Command, CommandEnum.RemovePath, "Remove the installation path from the PATH system environment variable."); }); hasErrors = parsed.HasErrors; return(!(parsed.IsHelpRequested() || hasErrors)); }
private (ICliCommand Command, ArgumentSyntax Syntax)? MatchCommand( string[] args, IEnumerable <ICliCommand> groupCommands, ArgumentSyntax groupSyntax) { string helpText = null; try { var isHelpRequested = IsHelpRequested(args); ICliCommand matchCommand = null; var cmdSyntax = ArgumentSyntax.Parse(args.Skip(1).ToArray(), s => { s.HandleErrors = false; s.HandleHelp = false; s.ErrorOnUnexpectedArguments = false; s.ApplicationName = $"{groupSyntax.ApplicationName} {groupSyntax.ActiveCommand}"; foreach (var cmd in groupCommands) { var arg = cmd.Define(s); if (arg.IsActive) { matchCommand = cmd; } } if (isHelpRequested) { helpText = s.GetHelpText(); } }); if (!isHelpRequested) { return(matchCommand, cmdSyntax); } } catch (ArgumentSyntaxException) { if (!IsHelpRequested(args)) { throw; } } PrintVersion(); consoleLogger.Info(helpText); return(null); }
public void Parse(string[] args) { ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax => { string aspnetVersion = null; Argument <string> aspnetVersionArg = syntax.DefineOption( "aspnet-version", ref aspnetVersion, "ASP.NET version to update the Dockerfiles with"); AspnetVersion = aspnetVersion; string runtimeVersion = null; Argument <string> runtimeVersionArg = syntax.DefineOption( "runtime-version", ref runtimeVersion, ".NET runtime version to update the Dockerfiles with"); RuntimeVersion = runtimeVersion; string sdkVersion = null; Argument <string> sdkVersionArg = syntax.DefineOption( "sdk-version", ref sdkVersion, "SDK version to update the Dockerfiles with"); SdkVersion = sdkVersion; string gitHubEmail = null; syntax.DefineOption( "email", ref gitHubEmail, "GitHub email used to make PR (if not specified, a PR will not be created)"); GitHubEmail = gitHubEmail; string gitHubPassword = null; syntax.DefineOption( "password", ref gitHubPassword, "GitHub password used to make PR (if not specified, a PR will not be created)"); GitHubPassword = gitHubPassword; string gitHubUser = null; syntax.DefineOption( "user", ref gitHubUser, "GitHub user used to make PR (if not specified, a PR will not be created)"); GitHubUser = gitHubUser; }); }
/// <summary> /// Parse commandline options /// </summary> private ArgumentSyntax ParseCommandLine(string[] args) { bool verbose = false; ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax => { syntax.ApplicationName = "R2RDump"; syntax.HandleHelp = false; syntax.HandleErrors = true; syntax.DefineOption("h|help", ref _help, "Help message for R2RDump"); syntax.DefineOptionList("i|in", ref _inputFilenames, "Input file(s) to dump. Expects them to by ReadyToRun images"); syntax.DefineOption("o|out", ref _outputFilename, "Output file path. Dumps everything to the specified file except help message and exception messages"); syntax.DefineOption("x|xml", ref _xml, "Output in XML format"); syntax.DefineOption("raw", ref _options.Raw, "Dump the raw bytes of each section or runtime function"); syntax.DefineOption("header", ref _options.Header, "Dump R2R header"); syntax.DefineOption("d|disasm", ref _options.Disasm, "Show disassembly of methods or runtime functions"); syntax.DefineOption("naked", ref _options.Naked, "Naked dump suppresses most compilation details like placement addresses"); syntax.DefineOptionList("q|query", ref _queries, "Query method by exact name, signature, row id or token"); syntax.DefineOptionList("k|keyword", ref _keywords, "Search method by keyword"); syntax.DefineOptionList("f|runtimefunction", ref _runtimeFunctions, ArgStringToInt, "Get one runtime function by id or relative virtual address"); syntax.DefineOptionList("s|section", ref _sections, "Get section by keyword"); syntax.DefineOption("unwind", ref _options.Unwind, "Dump unwindInfo"); syntax.DefineOption("gc", ref _options.GC, "Dump gcInfo and slot table"); syntax.DefineOption("sc", ref _options.SectionContents, "Dump section contents"); syntax.DefineOption("e|entrypoints", ref _options.EntryPoints, "Dump list of method / instance entrypoints in the R2R file"); syntax.DefineOption("n|normalize", ref _options.Normalize, "Normalize dump by sorting the various tables and methods (default = unsorted i.e. file order)"); syntax.DefineOption("v|verbose", ref verbose, "Dump disassembly, unwindInfo, gcInfo and section contents"); syntax.DefineOption("diff", ref _diff, "Compare two R2R images"); syntax.DefineOption("ignoreSensitive", ref _ignoreSensitive, "Ignores sensitive properties in xml dump to avoid failing tests"); syntax.DefineOptionList("r|reference", ref _options.ReferenceAssemblies, "Explicit reference assembly files"); syntax.DefineOptionList("rp|referencepath", ref _options.ReferencePaths, "Search paths for reference assemblies"); syntax.DefineOption("isb|inlineSignatureBinary", ref _options.InlineSignatureBinary, "Embed binary signature into its textual description"); syntax.DefineOption("sb|signatureBinary", ref _options.SignatureBinary, "Append signature binary to its textual description"); }); if (verbose) { _options.Disasm = true; _options.Unwind = true; _options.GC = true; _options.SectionContents = true; _options.EntryPoints = true; } return(argSyntax); }
public static void Run(string[] args) { string input = null; IReadOnlyList <string> componentDirectories = Array.Empty <string>(); string output = null; var cliOptions = ArgumentSyntax.Parse(args, options => { options.ApplicationName = "cdcli circuit"; options.DefineOptionList("components", ref componentDirectories, "Path to components directory."); options.DefineOption("o|output", ref output, "Path to output file."); options.DefineParameter("input", ref input, "Path to input circuit."); }); if (input == null) { cliOptions.ReportError("Input file must be specified."); } if (componentDirectories == null) { cliOptions.ReportError("Components directory must be specified."); } if (output == null) { cliOptions.ReportError("Output path must be specified."); } Console.WriteLine($"{Path.GetFileName(input)} -> {Path.GetFileName(output)}"); var reader = new CircuitDiagramDocumentReader(); CircuitDiagramDocument circuit; using (var fs = File.Open(input, FileMode.Open, FileAccess.Read)) circuit = reader.ReadCircuit(fs); var descriptionLookup = new DirectoryComponentDescriptionLookup(componentDirectories.ToArray()); var renderer = new CircuitRenderer(descriptionLookup); var drawingContext = new SkiaDrawingContext((int)circuit.Size.Width, (int)circuit.Size.Height, SKColors.White); renderer.RenderCircuit(circuit, drawingContext); using (var outputFs = File.OpenWrite(output)) drawingContext.WriteAsPng(outputFs); }
public static void Main(string[] args) { var noShellMap = false; var definition = GameDefinition.FromGame(SageGame.CncGenerals); ArgumentSyntax.Parse(args, syntax => { syntax.DefineOption("noshellmap", ref noShellMap, false, "Disables loading the shell map, speeding up startup time."); string gameName = null; var availableGames = string.Join(", ", GameDefinition.All.Select(def => def.Game.ToString())); syntax.DefineOption("game", ref gameName, false, $"Chooses which game to start. Valid options: {availableGames}"); // If a game has been specified, make sure it's valid. if (gameName != null && !GameDefinition.TryGetByName(gameName, out definition)) { syntax.ReportError($"Unknown game: {gameName}"); } }); Platform.CurrentPlatform = new Sdl2Platform(); Platform.CurrentPlatform.Start(); // TODO: Support other locators. var locator = new RegistryInstallationLocator(); var game = GameFactory.CreateGame( definition, locator, // TODO: Read game version from assembly metadata or .git folder // TODO: Set window icon. () => Platform.CurrentPlatform.CreateWindow("OpenSAGE (master)", 100, 100, 1024, 768)); game.Configuration.LoadShellMap = !noShellMap; game.ShowMainMenu(); while (game.IsRunning) { game.Tick(); } Platform.CurrentPlatform.Stop(); }
private (IEnumerable <ICliCommand> Commands, ArgumentSyntax Syntax)? MatchCommandGroup( string[] args, ILookup <CommandGroup, ICliCommand> commandGroups) { string helpText = null; var isHelpRequested = IsHelpRequested(args); try { IEnumerable <ICliCommand> commands = null; var groupSyntax = ArgumentSyntax.Parse(args, s => { s.HandleErrors = false; s.HandleHelp = false; s.ErrorOnUnexpectedArguments = false; s.ApplicationName = "certes"; foreach (var cmdGroup in commandGroups) { var cmd = s.DefineCommand(cmdGroup.Key.Command, help: cmdGroup.Key.Help); if (cmd.IsActive) { commands = cmdGroup; } } if (isHelpRequested) { helpText = s.GetHelpText(); } }); return(commands, groupSyntax); } catch (ArgumentSyntaxException) { if (isHelpRequested) { PrintVersion(); consoleLogger.Info(helpText); return(null); } throw; } }
public void Parse(string[] args) { ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax => { string gitHubEmail = null; syntax.DefineOption( "email", ref gitHubEmail, "GitHub email used to make PR (if not specified, a PR will not be created)"); GitHubEmail = gitHubEmail; string gitHubPassword = null; syntax.DefineOption( "password", ref gitHubPassword, "GitHub password used to make PR (if not specified, a PR will not be created)"); GitHubPassword = gitHubPassword; string gitHubUser = null; syntax.DefineOption( "user", ref gitHubUser, "GitHub user used to make PR (if not specified, a PR will not be created)"); GitHubUser = gitHubUser; Uri buildInfoUrl = null; syntax.DefineParameter( "build-info", ref buildInfoUrl, (value) => new Uri(value), "URL of the build info to update the Dockerfiles with (http(s):// or file://)"); BuildInfoUrl = buildInfoUrl; }); // Workaround for https://github.com/dotnet/corefxlab/issues/1689 foreach (Argument arg in argSyntax.GetActiveArguments()) { if (arg.IsParameter && !arg.IsSpecified) { Console.Error.WriteLine($"error: `{arg.Name}` must be specified."); Environment.Exit(1); } } }
private static ArgumentSyntax ParseCommandLine(string[] args) { ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax => { syntax.ApplicationName = "ReadyToRun.TestHarness"; syntax.HandleHelp = false; syntax.HandleErrors = true; syntax.DefineOption("h|help", ref _help, "Help message for R2RDump"); syntax.DefineOption("c|corerun", ref _coreRunExePath, "Path to CoreRun"); syntax.DefineOption("i|in", ref _testExe, "Path to test exe"); syntax.DefineOptionList("r|ref", ref _referenceFilenames, "Paths to referenced assemblies"); syntax.DefineOption("w|whitelist", ref _whitelistFilename, "Path to method whitelist file"); syntax.DefineOptionList("testargs", ref _testargs, "Args to pass into test"); syntax.DefineOption("noetl", ref _noEtl, "Run the test without ETL enabled"); }); return(argSyntax); }
public static AnalysisOptionsBuilder Parse(string[] args) { var options = new AnalysisOptionsBuilder(); var syntax = default(ArgumentSyntax); try { if (args.Length == 0) { return(options); } ArgumentSyntax.Parse(args, arg => { arg.HandleErrors = false; arg.DefineCommand("analyze", ref options._command, AnalysisCommand.Analyze, "Analyze packages"); arg.DefineOption("packageId", ref options._packageId, true, "NuGet package to analyze"); arg.DefineOption("original", ref options._originalVersion, true, "Original package"); arg.DefineOption("updated", ref options._updatedVersion, true, "Updated packages"); arg.DefineOption("feed", ref options._feed, false, "NuGet feed to use"); arg.DefineOption("verbose", ref options._verbose, false, "Turn verbose output on"); arg.DefineOption("ref", ref options._referencePath, false, "Zip archive of reference assemblies"); arg.DefineCommand("ref", ref options._command, AnalysisCommand.CollectReferenceAssemblies, "Collect reference assemblies"); arg.DefineOption("path", ref options._referencePath, true, "Path to save reference assembly collection"); arg.DefineCommand("monitor", ref options._command, AnalysisCommand.MonitorQueue, "Monitor queue"); syntax = arg; }); options.Validate(syntax); return(options); } catch (ArgumentSyntaxException e) { throw new ArgumentParsingException(syntax, e.Message); } }
public async Task CanReadKeyFromEnv() { var args = new[] { "--opt", "1" }; var s = ArgumentSyntax.Parse(args, syntax => { syntax.HandleErrors = false; syntax.DefineOption("opt", "0"); }); var envMock = new Mock <IEnvironmentVariables>(MockBehavior.Strict); var fileMock = new Mock <IFileUtil>(MockBehavior.Strict); envMock.Setup(m => m.GetVar(It.IsAny <string>())).Returns((string)null); await Assert.ThrowsAsync <Exception>( () => s.ReadKey("key", "KEY", fileMock.Object, envMock.Object, true)); envMock.Setup(m => m.GetVar("KEY")).Returns(Convert.ToBase64String(Helper.GetKeyV2().ToDer())); var key = await s.ReadKey("key", "KEY", fileMock.Object, envMock.Object); Assert.Equal(key.ToDer(), Helper.GetKeyV2().ToDer()); }
static void Main(string[] args) { var input = string.Empty; ArgumentSyntax.Parse(args, syntax => { syntax.DefineOption("i|input", ref input, true, "Something interesting to read."); syntax.ErrorOnUnexpectedArguments = false; }); if (string.IsNullOrEmpty(input)) { NSApplication.Init(); NSApplication.Main(args); } else { Console.WriteLine($"{input.Length} - {input}"); } }
/// <summary> /// Parse commandline options /// </summary> private ArgumentSyntax ParseCommandLine(string[] args) { bool verbose = false; ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax => { syntax.ApplicationName = "R2RDump"; syntax.HandleHelp = false; syntax.HandleErrors = true; syntax.DefineOption("h|help", ref _help, "Help message for R2RDump"); syntax.DefineOptionList("i|in", ref _inputFilenames, "Input file(s) to dump. Expects them to by ReadyToRun images"); syntax.DefineOption("o|out", ref _outputFilename, "Output file path. Dumps everything to the specified file except help message and exception messages"); syntax.DefineOption("x|xml", ref _xml, "Output in XML format"); syntax.DefineOption("raw", ref _raw, "Dump the raw bytes of each section or runtime function"); syntax.DefineOption("header", ref _header, "Dump R2R header"); syntax.DefineOption("d|disasm", ref _disasm, "Show disassembly of methods or runtime functions"); syntax.DefineOptionList("q|query", ref _queries, "Query method by exact name, signature, row id or token"); syntax.DefineOptionList("k|keyword", ref _keywords, "Search method by keyword"); syntax.DefineOptionList("r|runtimefunction", ref _runtimeFunctions, ArgStringToInt, "Get one runtime function by id or relative virtual address"); syntax.DefineOptionList("s|section", ref _sections, "Get section by keyword"); syntax.DefineOption("unwind", ref _unwind, "Dump unwindInfo"); syntax.DefineOption("gc", ref _gc, "Dump gcInfo and slot table"); syntax.DefineOption("sc", ref _sectionContents, "Dump section contents"); syntax.DefineOption("v|verbose", ref verbose, "Dump raw bytes, disassembly, unwindInfo, gcInfo and section contents"); syntax.DefineOption("diff", ref _diff, "Compare two R2R images"); syntax.DefineOption("ignoreSensitive", ref _ignoreSensitive, "Ignores sensitive properties in xml dump to avoid failing tests"); }); if (verbose) { _disasm = true; _unwind = true; _gc = true; _sectionContents = true; } _disasm = false; // TODO: this requires the coredistools nuget package with the most recent changes return(argSyntax); }
internal static ArgumentSyntax ParseCommandLine(string[] args) { string projectIdDefaultValue = null; string namespaceDefaultValue = null; string outputDirDefaultValue = null; string fileNameSuffixDefaultValue = null; string baseClassDefaultValue = null; var syntax = ArgumentSyntax.Parse(args, s => { s.ErrorOnUnexpectedArguments = false; s.DefineOption("p|projectid", ref projectIdDefaultValue, "Kentico Kontent Project ID."); s.DefineOption("n|namespace", ref namespaceDefaultValue, "-n|--namespace"); s.DefineOption("o|outputdir", ref outputDirDefaultValue, "Output directory for the generated files."); s.DefineOption("f|filenamesuffix", ref fileNameSuffixDefaultValue, "Optionally add a suffix to generated filenames (e.g., News.cs becomes News.Generated.cs)."); s.DefineOption("g|generatepartials", ref CodeGeneratorOptions.DefaultGeneratePartials, "Generate partial classes for customization (if this option is set filename suffix will default to Generated)."); s.DefineOption("t|withtypeprovider", ref CodeGeneratorOptions.DefaultWithTypeProvider, "Indicates whether the CustomTypeProvider class should be generated."); s.DefineOption("s|structuredmodel", ref CodeGeneratorOptions.DefaultStructuredModel, "Indicates whether the classes should be generated with types that represent structured data model."); s.DefineOption("c|contentmanagementapi", ref CodeGeneratorOptions.DefaultContentManagementApi, "Indicates whether the classes should be generated for CM API SDK instead."); s.DefineOption("b|baseclass", ref baseClassDefaultValue, "Optionally set the name of a base type that all generated classes derive from. If not set, they will not inherit any base class."); s.ApplicationName = "content-types-generator"; }); var unexpectedArgs = new List <string>(syntax.RemainingArguments); if (unexpectedArgs.Count > 0) { StringBuilder err = new StringBuilder(); err.AppendLine("Invalid arguments!"); foreach (var unexpectedArgument in unexpectedArgs) { err.AppendLine($"Unrecognized option '{unexpectedArgument}'"); } err.AppendLine(syntax.GetHelpText()); throw new Exception(err.ToString()); } return(syntax); }
public static Options Parse(string[] args) { var options = new Options { Path = null, Analyzers = Array.Empty <string>(), AdditionalFiles = Array.Empty <string>(), Features = Array.Empty <KeyValuePair <string, string> >() }; var r = ArgumentSyntax.Parse(args, syntax => { KeyValuePair <string, string> ParseFeature(string feature) { var split = feature.Split(':'); if (split.Length != 2) { syntax.ReportError($"Invalid feature '{feature}'. Must be of form '[name]:[value]'"); } return(new KeyValuePair <string, string>(split[0], split[1])); } syntax.DefineOptionList("a|analyzer", ref options.Analyzers, "Analyzer assembly to include"); syntax.DefineOptionList("d|additionalFile", ref options.AdditionalFiles, "Additional files for compilation"); syntax.DefineOptionList("f|feature", ref options.Features, ParseFeature, "Experimental features for compilation."); syntax.DefineParameter("path", ref options.Path, "Path to project or solution"); }); if (!File.Exists(options.Path)) { Console.WriteLine("error: Project or solution path not supplied"); // Using Environment.Exit because the argument parser uses it at the momemt Environment.Exit(0); } return(options); }