static async Task Main(string[] args) { using (var instance = new Instance("OpenTabletDriver.Daemon")) { if (instance.AlreadyExists) { Console.WriteLine("OpenTabletDriver Daemon is already running."); Thread.Sleep(1000); return; } AppDomain.CurrentDomain.UnhandledException += (sender, e) => { var exception = (Exception)e.ExceptionObject; File.WriteAllLines(Path.Join(AppInfo.Current.AppDataDirectory, "daemon.log"), new string[] { DateTime.Now.ToString(), exception.GetType().FullName, exception.Message, exception.Source, exception.StackTrace, exception.TargetSite.Name } ); }; var rootCommand = new RootCommand("OpenTabletDriver") { new Option(new string[] { "--appdata", "-a" }, "Application data directory") { Argument = new Argument <DirectoryInfo>("appdata") }, new Option(new string[] { "--config", "-c" }, "Configuration directory") { Argument = new Argument <DirectoryInfo> ("config") } }; rootCommand.Handler = CommandHandler.Create <DirectoryInfo, DirectoryInfo>((appdata, config) => { if (!string.IsNullOrWhiteSpace(appdata?.FullName)) { AppInfo.Current.AppDataDirectory = appdata.FullName; } if (!string.IsNullOrWhiteSpace(config?.FullName)) { AppInfo.Current.ConfigurationDirectory = config.FullName; } }); rootCommand.Invoke(args); var host = new RpcHost <DriverDaemon>("OpenTabletDriver.Daemon"); host.ConnectionStateChanged += (sender, state) => Log.Write("IPC", $"{(state ? "Connected to" : "Disconnected from")} a client.", LogLevel.Debug); await host.Run(BuildDaemon()); } }
static void Main(string[] args) { var filesArg = new Argument <FileInfo[]>("files", "NEDF files to process").ExistingOnly(); filesArg.Arity = ArgumentArity.OneOrMore; var rootCommand = new RootCommand("Export header / marker data for NEDF files") { new Option <StreamWriter>(new string[] { "--statsfile", "-o" }, "File to save stats to instead of stdout"), new Option <StreamWriter>("--errlog", "File to log errors to instead of stderr"), new Option <uint>("--maxsamples", () => int.MaxValue, "Quit after this many samples, useful for sanity checks"), new Option <bool>("--markercsv", "Write a CSV file with markers for each supplied nedf file"), filesArg }; rootCommand.Handler = CommandHandler.Create((StreamWriter statsfile, StreamWriter errlog, uint maxsamples, bool markercsv, FileInfo[] files) => { var stderr = errlog ?? Console.Error; var statsout = statsfile ?? Console.Out; statsout.WriteLine("File;NEDFversion;nchan;nacc;nsample;nstim;StartDate_firstEEGTimestamp"); foreach (var file in files) { try { using var r = new NedfFile(file.FullName, (str) => errlog.WriteLine(str)); string basename = Path.GetFileNameWithoutExtension(file.Name); int markercount = 0; if (markercsv) { var outfile = markercsv ? new StreamWriter(file.DirectoryName + '/' + basename + "_markers.csv") : null; outfile?.WriteLine("sample;marker"); foreach ((uint pos, uint value) in r.GetMarkerPairs(maxsamples)) { outfile?.WriteLine($"{pos};{value}"); markercount++; } outfile?.Dispose(); } CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; statsout.WriteLine(string.Join(";", new object[] { Path.GetFileName(file.Name), r.NEDFversion, r.NChan, r.NAcc, r.NSample, markercount, r.hdr.StepDetails.StartDate_firstEEGTimestamp }.Select(obj => obj.ToString()))); } catch (Exception e) { Console.Error.WriteLine($"{file}: Error: {e.Message}"); } } }); rootCommand.Invoke(args); }
static void Main(string[] args) { ConfigureServices(); ConfigureCommands(); rootCommand.Invoke(args); DisposeServices(); }
static int Main(string[] args) { var command = new RootCommand { new Argument <FileInfo>("output", () => new FileInfo(Path.Join(Environment.CurrentDirectory, "output.png")), "Path to the output file, default is `output.png`.") }; command.Description = "Takes words on input and generates word cloud as PNG from them."; command.Handler = CommandHandler.Create <FileInfo>(output => { // Process words on input. var freqs = new Dictionary <string, int>(); var whitespaces = new Regex(@"\s+"); while (Console.ReadLine() is string line) { foreach (var word in whitespaces.Split(line)) { if (!freqs.TryGetValue(word, out var freq)) { freq = 0; } freqs[word] = freq + 1; } } // Generate topic cloud. var wordCloud = new WordCloudInput( freqs.Select(p => new WordCloudEntry(p.Key, p.Value))) { Width = 1024, Height = 256, MinFontSize = 8, MaxFontSize = 32 }; var sizer = new LogSizer(wordCloud); using var engine = new SkGraphicEngine(sizer, wordCloud); var layout = new SpiralLayout(wordCloud); var wcg = new WordCloudGenerator <SKBitmap>(wordCloud, engine, layout); // Draw the bitmap on white background. using var final = new SKBitmap(wordCloud.Width, wordCloud.Height); using var canvas = new SKCanvas(final); canvas.Clear(SKColors.White); canvas.DrawBitmap(wcg.Draw(), 0, 0); // Save to PNG. using var data = final.Encode(SKEncodedImageFormat.Png, 100); using var writer = output.Create(); data.SaveTo(writer); }); return(command.Invoke(args)); }
private static CommandLineBuilder CreateCommandLineBuilder() { var rootCommand = new RootCommand("Bicep registry module tool") .AddSubcommand(new ValidateCommand()) .AddSubcommand(new GenerateCommand()); rootCommand.Handler = CommandHandler.Create(() => rootCommand.Invoke("-h")); return(new(rootCommand)); }
public void Command_Invoke_can_be_called_more_than_once_for_the_same_command() { var command = new RootCommand("Root command description") { new Command("inner") }; var console1 = new TestConsole(); command.Invoke("-h", console1); console1.Out.ToString().Should().Contain(command.Description); var console2 = new TestConsole(); command.Invoke("-h", console2); console2.Out.ToString().Should().Contain(command.Description); }
static int Main(string[] args) { var cmd = new RootCommand { LsDevicesCmd(), StreamCmd(), DownloadCmd(), }; return(cmd.Invoke(args)); }
private static int Main(string[] args) { var rootCommand = new RootCommand(ThisAssembly.AppName) { new Option <string>(new[] { "--connection-string", "-cs" }, "Contains the connection string to connect to the database"), new Option <string>(new[] { "--view-name", "-vn" }, "The name of the view to inline"), new Option <FileInfo>(new[] { "--view-path", "-vp" }, "The path of the view as a .sql file (including create statement)"), new Option <bool>(new[] { "--strip-unused-columns", "-suc" }, () => true), new Option <bool>(new[] { "--strip-unused-joins", "-suj" }), new Option <bool>("--generate-create-or-alter", () => true), // TODO: DatabaseView.parser (hardcoded to TSql150Parser) }; rootCommand.Handler = CommandHandler.Create <string, string?, FileInfo?, bool, bool, bool>((connectionString, viewName, viewPath, stripUnusedColumns, stripUnusedJoins, generateCreateOrAlter) => { var cs = new SqlConnectionStringBuilder(connectionString); if (!cs.ContainsKey(nameof(cs.ApplicationName))) { cs.ApplicationName = ThisAssembly.AppName; connectionString = cs.ToString(); } var connection = new DatabaseConnection(new SqlConnection(connectionString)); string viewSql; if (!string.IsNullOrEmpty(viewName)) { viewSql = connection.GetViewDefinition(viewName); } else if (viewPath != null) { viewSql = File.ReadAllText(viewPath.FullName); } else { throw new InvalidOperationException("At least --view-name or --view-path is required."); } if (generateCreateOrAlter) { viewSql = DatabaseView.CreateOrAlter(viewSql); } var inliner = new DatabaseViewInliner(connection, viewSql, new() { StripUnusedColumns = stripUnusedColumns, StripUnusedJoins = stripUnusedJoins, }); Console.WriteLine(inliner.Sql); return(inliner.Errors.Count > 0 ? -1 : 0); }); return(rootCommand.Invoke(args)); }
private static int Main(string[] args) { var workingDirectory = new DirectoryInfo(CurrentPath); var exifTool = new ExifTool(new ExifToolOptions { ExifToolPath = "/usr/bin/vendor_perl/exiftool" }); var exifWrapper = new ExifWrapper(exifTool); var rootImageHandler = new RootImageHandler(exifWrapper); var fromIPhoneOld = CommandExtensions.Create( "from-iphone-old", "Converts a dump from iPhone into a date-based directory structure", dryRun => FromIPhoneOld.Run(workingDirectory, dryRun)); var fromIPhone = CommandExtensions.CreateWithOutput( "from-iphone", "Converts a dump from iPhone into a date-based directory structure", (dryRun, output) => { new FromIPhone(exifWrapper) .Run(workingDirectory, output, dryRun); }); var fixExif = CommandExtensions.Create( "fix-exif", "Set all the missing Exif dates in Exif in a directory, inferring the missing dates from directory names", dryRun => { new FixExif(rootImageHandler).Run(workingDirectory, dryRun); }); var removeDuplicateJpg = CommandExtensions.Create( "remove-duplicate-jpg", "Remove the JPG files that duplicate equivalent HEIC images", dryRun => RemoveDuplicateJpg.Run(workingDirectory, dryRun) ); var separateIPhone5 = CommandExtensions.CreateWithOutput( "identify-iphone5", "Identify which photos have been taken with iPhone 5", (dryRun, output) => { new IdentifyIPhone5(exifWrapper) .Run(workingDirectory, dryRun); }); var rootCommand = new RootCommand { new Option("--version", "The current version of this tool"), fromIPhoneOld, fromIPhone, fixExif, removeDuplicateJpg, separateIPhone5 }; rootCommand.Handler = CommandHandler.Create(Version.VersionHandler); return(rootCommand.Invoke(args)); }
public static int Main(string[] args) { var rootCommand = new RootCommand("Convert ClangSharp-generated code into metadata") { new Option <string>(new[] { "--sourceDir", "-s" }, "The location of the source files.") { IsRequired = true }, new Option <string>(new[] { "--interopFileName", "-i" }, "The path to Windows.Win32.Interop.dll") { IsRequired = true }, new Option <string>(new[] { "--outputFileName", "-o" }, "The path to the .winmd to create") { IsRequired = true }, new Option <string>(new[] { "--version", "-v" }, description: "The version to use on the .winmd", getDefaultValue: () => "1.0.0.0"), new Option(new string[] { "--remap", "-r" }, "A declaration name to be remapped to another name during binding generation.") { Argument = new Argument("<name>=<value>") { ArgumentType = typeof(string), Arity = ArgumentArity.OneOrMore, } }, new Option(new string[] { "--typeImport", "-t" }, "A type to be imported from another assembly.") { Argument = new Argument("<name>=<value>") { ArgumentType = typeof(string), Arity = ArgumentArity.OneOrMore, } }, new Option(new string[] { "--requiredNamespaceForName", "-n" }, "The required namespace for a named item.") { Argument = new Argument("<name>=<value>") { ArgumentType = typeof(string), Arity = ArgumentArity.OneOrMore, } }, new Option(new string[] { "--autoTypes", "-a" }, "An auto-type to add to the metadata.") { Argument = new Argument("<value>") { ArgumentType = typeof(string), Arity = ArgumentArity.OneOrMore, } } }; rootCommand.Handler = CommandHandler.Create(typeof(Program).GetMethod(nameof(Run))); return(rootCommand.Invoke(args)); }
public void Instances_from_service_provider_can_be_injected_at_any_position_relative_to_symbol_parameters_with_Func_overloads(int @case) { var option = new Option <bool>("-o"); var argument = new Argument <string>("value"); var command = new RootCommand { option, argument }; ParseResult boundParseResult = default; bool boundBoolValue = default; string boundStringValue = default; switch (@case) { case 1: command.SetHandler((ParseResult parseResult, bool boolValue, string stringValue) => { boundParseResult = parseResult; boundBoolValue = boolValue; boundStringValue = stringValue; return(Task.FromResult(123)); }, option, argument); break; case 2: command.SetHandler((bool boolValue, ParseResult parseResult, string stringValue) => { boundParseResult = parseResult; boundBoolValue = boolValue; boundStringValue = stringValue; return(Task.FromResult(123)); }, option, argument); break; case 3: command.SetHandler((bool boolValue, string stringValue, ParseResult parseResult) => { boundParseResult = parseResult; boundBoolValue = boolValue; boundStringValue = stringValue; return(Task.FromResult(123)); }, option, argument); break; } command.Invoke("-o hi"); boundParseResult.Should().NotBeNull(); boundBoolValue.Should().BeTrue(); boundStringValue.Should().Be("hi"); }
public static int Main(string[] args) { var rootCommand = new RootCommand { new Option <int>("--compId", description: "Competition id from liveresultat.orienteering.se") { IsRequired = true, ArgumentHelpName = "id" }, new Option <DateTime>("--zeroTime", description: "Start 0 time") { IsRequired = true, ArgumentHelpName = "hh:mm" }, new Option <string>("--startFile", description: "path to startlist file") { IsRequired = true, ArgumentHelpName = "path" }, new Option <string>("--finishFile", description: "path to finish/race file") { IsRequired = true, ArgumentHelpName = "path" }, new Option <string>("--rawSplitsFile", description: "path to raw splits file") { ArgumentHelpName = "path" }, new Option <string>("--dsqFile", description: "path to disqualified file") { ArgumentHelpName = "path" }, new Option <string>("--radioFile", description: "path to radio controls file") { ArgumentHelpName = "path" }, new Option <bool>( "--isRelay", description: "set if race is relay" ) }; rootCommand.Name = "EmmaClient"; rootCommand.Description = "A linux fork of EmmaClient for uploading live results to liveresultat.orienteering.se"; rootCommand.Handler = CommandHandler.Create <int, DateTime, string, string, string, string, string, bool>((compId, zeroTime, startFile, finishFile, rawSplitsFile, dsqFile, radioFile, isRelay) => { FrmMonitor monForm = new FrmMonitor(); monForm.SetParser(new RacomFileSetParser(startFile, rawSplitsFile, finishFile, dsqFile, radioFile, zeroTime, isRelay)); monForm.CompetitionID = compId; monForm.Run(); }); return(rootCommand.Invoke(args)); }
private static void Main(string[] args) { RootCommand command = new RootCommand("A bunch of cli commands using code I copied from www.stackoverflow.com") { ResizeImageCommand(), MyConsole.GetVerbosityOption() }; command.Invoke(args); }
public void Mulitple_invocations_() { // FIX: (Mulitple_invocations_) delete var command = new RootCommand("Root command description") { new Command("inner") }; var console1 = new TestConsole(); command.Invoke("-h", console1); console1.Out.ToString().Should().Contain(command.Description); var console2 = new TestConsole(); command.Invoke("-h", console2); console2.Out.ToString().Should().Contain(command.Description); }
public static int Main(string[] args) { var root = new RootCommand { ListCommand(), PlayCommand(), TrainCommand() }; return(root.Invoke(args)); }
public static void Main(string[] args) { try { if (Debugger.IsAttached || args.Length == 0) { Console.Write("Specify input file path: "); var inputPath = Console.ReadLine(); Console.Write("Specify the block size in bytes: "); var blockSizeString = Console.ReadLine(); var isValidInt = int.TryParse(blockSizeString, out var blockSize); ValidateParamsAndExecute(inputPath, null, isValidInt ? blockSize : -1, false, "SHA256"); } else { var rootCommand = new RootCommand { new Option <string>( alias: "--input-path", description: "Specify input file path"), new Option <string>( alias: "--output-path", description: "Specify output file path if you want it to be in file"), new Option <int>( alias: "--block-size", description: "Specify the block size in bytes"), new Option <bool>( alias: "--single-thread", description: "Computes hash in single thread"), new Option <string>( alias: "--hash-algorithm-name", defaultValue: "SHA256", description: "Hash algorithm that will be used to calculate hash"), }; rootCommand.Description = "Console App to chunk file and calculate its' hashes"; rootCommand.Handler = CommandHandler.Create <string, string, int, bool, string>(ValidateParamsAndExecute); rootCommand.Invoke(args); } } catch (Exception e) { Console.WriteLine(e); } #if DEBUG Console.Write("Press Enter to continue: "); Console.ReadLine(); #endif }
public void RootCommand_Invoke_returns_0_when_handler_is_successful() { var wasCalled = false; var rootCommand = new RootCommand(); rootCommand.Handler = CommandHandler.Create(() => wasCalled = true); int result = rootCommand.Invoke(""); wasCalled.Should().BeTrue(); result.Should().Be(0); }
public int Run(string[] args) { var cmd = new RootCommand { new Option <string>(new[] { "--url", "-u" }, description: "url to download", getDefaultValue: () => "https://github.com/xudifsd/WinUtils/releases/latest/download/WinUtils.zip"), }; cmd.Handler = CommandHandler.Create <string>(Download); return(cmd.Invoke(args)); }
static void Main(string[] args) { var rootCommand = new RootCommand { new Option <string>(new [] { "-c", "--configuration" }, "Name of build configuration"), new Option <bool>(new [] { "-p", "--publish" }, "Publish after build"), }; rootCommand.Description = $"Test appliacation to learn basics of System.CommandLine"; rootCommand.Handler = CommandHandler.Create <Arguments>(Run); rootCommand.Invoke(args); }
static void Main(string[] args) { var root = new RootCommand("OpenTabletDriver udev rule tool") { new Argument <DirectoryInfo>("directory"), new Argument <FileInfo>("output"), new Option(new string[] { "--verbose", "-v" }, "Verbose output") }; root.Handler = CommandHandler.Create <DirectoryInfo, FileInfo, bool>(WriteRules); root.Invoke(args); }
private static int Main(string[] args) { var rootCmd = new RootCommand("Language server for ScriptLang (.sc).") { new Argument <int>("port", "Port to use."), new Option <bool>("--wait-for-debugger", () => false) }; rootCmd.Handler = CommandHandler.Create <int, bool>(Run); return(rootCmd.Invoke(args)); }
private static int Main(string[] args) { var rootCommand = new RootCommand("The Coyote documentation generator."); var generateCommand = CreateGenerateCommand(); var mergeCommand = CreateMergeCommand(); rootCommand.AddCommand(generateCommand); rootCommand.AddCommand(mergeCommand); rootCommand.TreatUnmatchedTokensAsErrors = true; return(rootCommand.Invoke(args)); }
static void Main(string[] args) { var root = new RootCommand("Device Debugger CLI") { new Argument <string>("vendor"), new Argument <string>("product"), new Argument <uint>("reportlength") }; root.Handler = CommandHandler.Create <string, string, uint>(MainHandler); root.Invoke(args); }
public static void Main(string[] args) { var rootCommand = new RootCommand { Demos.CreateCommand(), CreateCommand("import", nameof(Import)), CreateCommand("export", nameof(Export)), CreateCommand("tokenize", nameof(Tokenize)), }; rootCommand.Invoke(args); }
public static int Run(string[] args) { var rootCommand = new RootCommand(); rootCommand.Add(new Option <VerbosityLevel>("--verbosity", VerbosityLevel.Normal, "Output verbosity level. Allowed values are normal and diagnostic.")); rootCommand.Add(new Option <string[]>("--trace", Array.Empty <string>(), "Output additional trace loggers specified by name.")); var buildCommand = new Command("build", "Generates C# code, database model file and other project assets."); // CurrentDirectory by default, because rhetos.exe on *build* is expected to be located in NuGet package cache. buildCommand.Add(new Argument <DirectoryInfo>("project-root-folder", () => new DirectoryInfo(Environment.CurrentDirectory)) { Description = "Project folder where csproj file is located. If not specified, current working directory is used by default." }); buildCommand.Add(new Option <bool>("--msbuild-format", false, "Adjust error output format for MSBuild integration.")); buildCommand.Handler = CommandHandler.Create((DirectoryInfo projectRootFolder, bool msbuildFormat, VerbosityLevel verbosity, string[] trace) => { var program = new Program(verbosity, trace); program.SafeExecuteCommand(() => program.Build(projectRootFolder.FullName), "Build", msbuildFormat); }); rootCommand.AddCommand(buildCommand); var dbUpdateCommand = new Command("dbupdate", "Updates the database structure and initializes the application data in the database."); dbUpdateCommand.Add(new Argument <FileInfo>("startup-assembly") { Description = "Startup assembly of the host application." }); dbUpdateCommand.Add(new Option <bool>("--short-transactions", "Commit transaction after creating or dropping each database object.")); dbUpdateCommand.Add(new Option <bool>("--skip-recompute", "Skip automatic update of computed data with KeepSynchronized. See output log for data that needs updating.")); //Lack of this switch means that the dbupdate command should start the command rhetos.exe dbupdate //in another process with the host applications runtimeconfig.json and deps.json files var executeCommandInCurrentProcessOption = new Option <bool>(ExecuteCommandInCurrentProcessOptionName); executeCommandInCurrentProcessOption.IsHidden = true; dbUpdateCommand.Add(executeCommandInCurrentProcessOption); dbUpdateCommand.Handler = CommandHandler.Create((FileInfo startupAssembly, bool shortTransactions, bool skipRecompute, bool executeCommandInCurrentProcess, VerbosityLevel verbosity, string[] trace) => { var program = new Program(verbosity, trace); if (executeCommandInCurrentProcess) { return(program.SafeExecuteCommand(() => program.DbUpdate(startupAssembly.FullName, shortTransactions, skipRecompute), "DbUpdate", msBuildErrorFormat: false)); } else { return(program.InvokeDbUpdateAsExternalProcess(startupAssembly.FullName, args)); } }); rootCommand.AddCommand(dbUpdateCommand); return(rootCommand.Invoke(args)); }
static int Main(string[] args) { if (args.Length > 0) { AttachConsole(AttachParentProcess); } var command = new RootCommand { Handler = CommandHandler.Create(() => { Run(new SdkWrapperProxy(new SdkWrapper(), record: false)); }) }; Command record = new Command( name: "record", description: "Record session updates and telemetry.") { Handler = CommandHandler.Create(() => { Run(new SdkWrapperProxy(new SdkWrapper(), record: true)); }) }; command.AddCommand(record); Command playback = new Command( name: "playback", description: "Play back only events from the indexed session within the session log.") { new Argument <string>( name: "logfile", description: "The RaceAdmin session log file to play back."), new Option( aliases: new[] { "--session", "-s" }, description: "Play back only events from the indexed session within the session log.") { Argument = new Argument <int>(getDefaultValue: () => - 1) } }; playback.Handler = CommandHandler.Create((string logfile, int session) => { // for now assume just a filename and look for file in documents folder string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); BinaryReader reader = new BinaryReader(File.Open(documentsPath + "\\" + logfile, FileMode.Open)); Run(new SdkReplayProxy(reader, session)); }); command.AddCommand(playback); return(command.Invoke(args)); }
public static void Main(string[] args) { var rootCommand = new RootCommand("voicekit"); var recognitionCommand = CommandLineInterface.CreateRecognitionCommand(); var streamingRecognitionCommand = CommandLineInterface.CreateStreamingRecognitionCommand(); var streamingSynthesisCommand = CommandLineInterface.CreateStreamingSynthesisCommand(); rootCommand.AddCommand(recognitionCommand); rootCommand.AddCommand(streamingRecognitionCommand); rootCommand.AddCommand(streamingSynthesisCommand); rootCommand.Invoke(args); }
public static void Main(string[] args) { var cmd = new RootCommand { new Argument <string>("filename", "URI of the file to analyze.\nRelative paths are supported only for the file system."), new Option <bool>(new string[] { "--verbose", "-v" }, "Output logs"), new Option <bool>(new string[] { "--log-to-file", "-l" }, "Write logs to a file of the format 'logs/html-parser-yyyymmddhhmmss'") }; cmd.Handler = CommandHandler.Create <string, bool, bool>(new Startup().Start); cmd.Invoke(args); }
public void If_service_is_not_found_then_an_error_results() { var command = new RootCommand(); var wasCalled = false; command.SetHandler((ClassWithMultipleCtor instance) => wasCalled = true); var exitCode = command.Invoke(""); wasCalled.Should().BeFalse(); exitCode.Should().Be(1); }
public void RootCommand_Invoke_can_set_custom_result_code() { var rootCommand = new RootCommand(); rootCommand.Handler = CommandHandler.Create <InvocationContext>(context => { context.ResultCode = 123; }); int resultCode = rootCommand.Invoke(""); resultCode.Should().Be(123); }