public void Commands_can_have_aliases() { var command = new Command("this"); command.AddAlias("that"); command.Aliases.Should().BeEquivalentTo("this", "that"); command.Aliases.Should().BeEquivalentTo("this", "that"); var result = command.Parse("that"); result.CommandResult.Command.Should().Be(command); result.Errors.Should().BeEmpty(); }
public static Command CreateCommand(Func <Task> action, string description, params string[] aliases) { var command = new Command(action.Method.Name.ToLower(), description) { Handler = CommandHandler.Create(action) }; foreach (var alias in aliases) { command.AddAlias(alias); } return(command); }
public static Command Create(Delegate executor = null) { var cmd = new Command("update", "Download and update local database."); cmd.AddAlias("force"); cmd.Handler = CommandHandler.Create(executor ?? new Action <DataSource, string, string, string>(Execute)); cmd.AddOption(ProviderOption.Create()); cmd.AddOption(RepoOption.Create()); cmd.AddOption(PathOption.Create()); return(cmd); }
public void When_a_command_alias_is_added_and_contains_whitespace_then_an_informative_error_is_returned( string alias ) { var command = new Command("-x"); Action addAlias = () => command.AddAlias(alias); addAlias .Should() .Throw <ArgumentException>() .Which.Message.Should() .Contain($"Command alias cannot contain whitespace: \"{alias}\""); }
private static Command who_and_whos() { var command = new Command("#!whos", "Display the names of the current top-level variables and their values.") { Handler = CommandHandler.Create((ParseResult parseResult, KernelInvocationContext context) => { var alias = parseResult.CommandResult.Token.Value; var detailed = alias == "#!whos"; Display(context, detailed); return(Task.CompletedTask); }) }; // TODO: (who_and_whos) this should be a separate command with separate help command.AddAlias("#!who"); return(command); void Display(KernelInvocationContext context, bool detailed) { if (context.Command is SubmitCode && context.HandlingKernel is CSharpKernel kernel) { var variables = kernel.ScriptState?.Variables.Select(v => new CurrentVariable(v.Name, v.Type, v.Value)) ?? Enumerable.Empty <CurrentVariable>(); var currentVariables = new CurrentVariables( variables, detailed); var html = currentVariables .ToDisplayString(HtmlFormatter.MimeType); context.Publish( new DisplayedValueProduced( html, context.Command, new[] { new FormattedValue( HtmlFormatter.MimeType, html) })); } } }
private static Command GetDisableStartupCommand() { var disableCommand = new Command("disable") { Description = "Disables one of the current startup programs", }; disableCommand.AddAlias("d"); disableCommand.AddArgument(new Argument <string>("name")); disableCommand.Handler = CommandHandler.Create <string>(DisableCommand.Run); return(disableCommand); }
public static Command CreateCommand <T1>(Func <T1, Task> action, string description, params string[] aliases) { var parameters = action.Method.GetParameters(); var command = new Command(action.Method.Name.ToLower(), description) { new Argument <T1>(parameters[0].Name.ToLower()) }; command.Handler = CommandHandler.Create <T1>(action); foreach (var alias in aliases) { command.AddAlias(alias); } return(command); }
public void Subcommands_can_have_aliases() { var subcommand = new Command("this"); subcommand.AddAlias("that"); var rootCommand = new RootCommand { subcommand }; var result = rootCommand.Parse("that"); result.CommandResult.Command.Should().Be(subcommand); result.Errors.Should().BeEmpty(); }
public static RootCommand WireUpJwtCommands(this RootCommand rootCommand) { var jwtCommand = new Command("jwt", "JSON Web Token"); var jwtDecCommand = new Command("decode", "Decode"); jwtDecCommand.AddAlias("dec"); jwtDecCommand.AddOption(new Option <string>(new string[] { "--text", "-t" }, "Input Text")); jwtDecCommand.AddOption(new Option <FileInfo>(new string[] { "--input", "-i" }, "Input file path")); jwtDecCommand.AddOption(new Option <FileInfo>(new string[] { "--output", "-o" }, "Output file path")); jwtDecCommand.Handler = CommandHandler.Create <string, FileInfo, FileInfo, IConsole>(async(text, input, output, console) => { try { string jwt = null; if (text != null) { jwt = Jwt.Decode(text); } if (input != null) { jwt = Jwt.Decode(await File.ReadAllTextAsync(input.FullName).ConfigureAwait(false)); } if (output == null) { console.Out.WriteLine(jwt); } else { await File.WriteAllTextAsync(output.FullName, jwt).ConfigureAwait(false); } } catch (Exception ex) { console.Out.WriteLine(ex.Message); return(22); } return(0); }); jwtCommand.Add(jwtDecCommand); rootCommand.AddCommand(jwtCommand); return(rootCommand); }
private static Command CreatePublicCommand() { var pcaCommand = new Command("public", "Public Client Application") { Handler = CommandLineHost.GetCommandHandler <PublicClientApplicationAppConfigExecutor>() }; pcaCommand.AddAlias("pca"); pcaCommand.AddCommand(CreateDeviceCodeAuthorizationCommand()); pcaCommand.AddCommand(CreateIntegratedWindowsAuthenticationCommand()); pcaCommand.AddCommand(CreateAccountsCommand()); pcaCommand.AddCommand(CreateSilentTokenAcquisitionCommand()); return(pcaCommand); }
public void When_command_alias_is_changed_then_GetByAlias_returns_true_for_the_new_alias() { var symbol = new Command("original"); var command = new RootCommand { symbol }; symbol.AddAlias("added"); command.Children .GetByAlias("added") .Should() .BeSameAs(symbol); }
private static Command CreateTimeEntryCommand() { var cmd = new Command("timeentry", "Time Entry listing and manipulation") { TimeEntry_Show.GetCommand(), TimeEntry_List.GetCommand(), TimeEntry_Create.GetCommand(), TimeEntry_Update.GetCommand(), TimeEntry_Interactive.GetCommand(), TimeEntry_Copy.GetCommand(), }; cmd.AddAlias("te"); return(cmd); }
/// <summary> /// Builds the specified command. /// </summary> /// <param name="instance">The instance that contains the handler.</param> /// <param name="methodInfo">The methodInfo for the handler.</param> /// <returns></returns> /// <exception cref="ArgumentNullException">Object doesn't implement CommandAttribute</exception> public Command Build(object?instance = null, MethodInfo?methodInfo = null) { if (_att is null) { throw new ArgumentNullException("Object doesn't implement CommandAttribute"); } var method = methodInfo ?? _handlerInfo; // Load default name var defName = _t.Name.PascalToKebabCase(); //Create command var cmd = new Command(_att.Name ?? defName, _att.Description) { TreatUnmatchedTokensAsErrors = _att.TreatUnmatchedTokensAsErrors }; // Add Aliases foreach (var a in _att.Aliases) { cmd.AddAlias(a); } // Add arguments and options foreach (var p in _t.GetProperties()) { var arg = new ArgumentFactory(p); if (arg.IsValid) { cmd.AddArgument(arg.Build()); continue; } var opt = new OptionFactory(p); if (opt.IsValid) { cmd.AddOption(opt.Build()); } } if (instance is not null && method is not null) { cmd.Handler = CommandHandler.Create(method, instance); } return(cmd); }
/// <summary> /// Build an obfuscated XLS Macro Document, or Deobfuscate an existing malicious XLS Macro Document. /// </summary> /// <param name="args"></param> public static void Main(string[] args) { try { Command buildCommand = new Command("b", null); buildCommand.AddAlias("build"); MethodInfo buildMethodInfo = typeof(Program).GetMethod(nameof(Build)); buildCommand.ConfigureFromMethod(buildMethodInfo); Command deobfuscateCommand = new Command("d", null); deobfuscateCommand.AddAlias("deobfuscate"); MethodInfo deobfuscateMethodInfo = typeof(Program).GetMethod(nameof(Deobfuscate)); deobfuscateCommand.ConfigureFromMethod(deobfuscateMethodInfo); Command dumpCommand = new Command("dump", null); MethodInfo dumpMethodInfo = typeof(Program).GetMethod(nameof(Dump)); dumpCommand.ConfigureFromMethod(dumpMethodInfo); RootCommand rootCommand = new RootCommand("Build an obfuscated XLS Macro Document, or Deobfuscate an existing malicious XLS Macro Document.") { deobfuscateCommand, buildCommand, dumpCommand }; CommandLineBuilder builder = new CommandLineBuilder(rootCommand); builder.ConfigureHelpFromXmlComments(buildMethodInfo, null); //Manually set this after reading the XML for descriptions builder.Command.Description = "Build an obfuscated XLS Macro Document or Deobfuscate an existing malicious XLS Macro Document."; Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); builder .UseDefaults() .Build() .Invoke(args); } catch (Exception e) { Console.WriteLine("Unexpected Exception Occurred:\n"); Console.WriteLine(e); } }
private static Command GetStartupListCommand() { var listCommand = new Command("list") { Description = "Lists the current startup programs" }; listCommand.AddAlias("l"); var detailedOption = new Option("--detailed", "Shows additional output about the startup programs"); detailedOption.AddAlias("-d"); listCommand.AddOption(detailedOption); listCommand.Handler = CommandHandler.Create <bool>(ListCommand.Run); return(listCommand); }
public override async Task <int> Run() { var filenameArgument = new Argument <string>("filename"); filenameArgument.LegalFilePathsOnly(); var projectTimeCommand = new Command("projecttime", "Import project times"); projectTimeCommand.AddAlias("pt"); projectTimeCommand.AddArgument(filenameArgument); projectTimeCommand.Handler = CommandHandler.Create <string>(ImportProjectTime); var updateTasks = new Option("--update", "Update existing tasks with same externalId"); updateTasks.AddAlias("-u"); updateTasks.Argument.SetDefaultValue(true); updateTasks.Argument.ArgumentType = typeof(bool); var taskCommand = new Command("task", "Import tasks"); taskCommand.AddAlias("t"); taskCommand.AddArgument(filenameArgument); taskCommand.AddOption(updateTasks); taskCommand.Handler = CommandHandler.Create <string, bool>(ImportTasks); var exportProjectTimeCommand = new Command("export-projecttime", "Export Project times"); exportProjectTimeCommand.AddOption(new Option <string>("connectionstring")); exportProjectTimeCommand.Handler = CommandHandler.Create <string>(ExportProjectTime); var rootCommand = new RootCommand("timrlink command line interface") { projectTimeCommand, taskCommand, exportProjectTimeCommand, }; rootCommand.Name = "timrlink"; rootCommand.TreatUnmatchedTokensAsErrors = true; return(await rootCommand.InvokeAsync(args)); }
public Command GetCommand() { var view = new Command("view", "Views the weather") { new Option <bool>(new string[] { "--all", "-a" }, "Displays today's weather and the hourly forecast") }; view.Handler = CommandHandler.Create(async(bool all) => await Execute(all)); var configure = new Command("configure", "Configures the weather provider"); configure.AddAlias("config"); configure.Handler = CommandHandler.Create(async() => await Configure()); return(new Command(Command, "Displays today's weather") { view, configure }); }
public static RootCommand UseAddItemCommand(this RootCommand rootCommand, IShoppingList shoppingList) { var addCommmand = new Command("add-item", "Adds a grocery item to the list") { new Option <int>(new string[] { "--quantity", "-q" }, () => 1, "The number of items to add (between 1 and 999)") .WithinRange(1, 999), new Argument <string>("name") { Description = "The name of the grocery item" } }; addCommmand.AddAlias("add"); addCommmand.Handler = CommandHandler.Create <IConsole, string, int>(async(console, name, quantity) => await shoppingList.AddItemsAsync(console, name, quantity)); rootCommand.AddCommand(addCommmand); return(rootCommand); }
public void Directives_may_not_have_aliases_that_begin_with_(string value) { using var kernel = new CompositeKernel(); var command = new Command("#!this-is-fine"); command.AddAlias($"{value}hello"); kernel .Invoking(k => { kernel.AddDirective(command); }) .Should() .Throw <ArgumentException>() .Which .Message .Should() .Be($"Invalid directive name \"{value}hello\". Directives must begin with \"#\"."); }
private static Command GetRemoveStartupCommand() { var removeCommand = new Command("remove") { Description = "Removes the specified program from startup" }; removeCommand.AddAlias("r"); removeCommand.AddArgument(new Argument <string>("name")); var skipConfirmation = new Option("--confirm", "Skips the confirmation prompt"); skipConfirmation.AddAlias("-c"); removeCommand.AddOption(skipConfirmation); removeCommand.Handler = CommandHandler.Create <string, bool>(RemoveCommand.Run); return(removeCommand); }
public XenialRootCommand(IServiceProvider serviceProvider) { Command = new XenialDefaultCommand(); RootCommand = new RootCommand(); foreach (var option in Command.CreateOptions()) { RootCommand.AddOption(option); } var commandHandlerTypes = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(assembly => assembly.GetTypes()) .Where(type => !type.IsAbstract && typeof(IXenialCommandHandler).IsAssignableFrom(type)); foreach (var commandHandlerType in commandHandlerTypes.Select(type => { var attribute = type.GetCustomAttribute <XenialCommandHandlerAttribute>(); return(type, attribute); }).Where(t => t.attribute != null)) { var commandType = FindCommandType(commandHandlerType); var subCommand = new Command(commandHandlerType.attribute.CommandName, commandHandlerType.attribute.Description); if (!string.IsNullOrEmpty(commandHandlerType.attribute.ShortCut)) { subCommand.AddAlias(commandHandlerType.attribute.ShortCut); } var command = (IXenialCommand)Activator.CreateInstance(commandType); foreach (var option in command.CreateOptions()) { subCommand.AddOption(option); } subCommand.Handler = new XenialCommandHandler(serviceProvider, command, commandHandlerType.type); RootCommand.Add(subCommand); } RootCommand.Handler = this;
public Command GetCommand() { var add = new Command("add", "Adds a new day to my Advent of Code solution") { new Option <int>(new string[] { "--year", "-y" }, () => DateTime.Now.Year, "Adds a day to the given year. Defaults to this year."), }; add.Handler = CommandHandler.Create(async(int year) => await AddDayTo(year)); var test = new Command("test", "Runs tests in my Advent of Code solution") { new Option <int>(new string[] { "--year", "-y" }, () => DateTime.Now.Year, "Runs tests for the given year. Defaults to this year."), new Option <int>(new string[] { "--day", "-d" }, () => 0, "Runs tests for the given day. If not set, runs all tests for the year."), }; test.Handler = CommandHandler.Create(async(int year, int day) => await RunTests(year, day)); var view = new Command("view", "Views the Advent of Code leaderboard") { new Option <int>(new string[] { "--year", "-y" }, () => DateTime.Now.Year, "Displays the leaderboard for the given year. Defaults to this year."), new Option <int>(new string[] { "--board", "-b" }, () => 274125, "The id of the leaderboard you want to view. Defaults to the CoderCamp leaderboard") }; view.Handler = CommandHandler.Create(async(int year, int board) => await ViewLeaderboard(year, board)); var configure = new Command("configure", "Configures the AdventOfCode provider"); configure.AddAlias("config"); configure.Handler = CommandHandler.Create(async() => await Configure()); var command = new Command("aoc", "Work with Advent of Code (AoC)") { add, test, view, configure }; command.AddAlias("advent"); return(command); }
public static void Add(RootCommand command) { var rd = new Command("readdesc", "X. (本地)读取剪切板更新日志生成一行数据复制到剪切板中"); rd.AddAlias("rd"); rd.Handler = CommandHandler.Create(() => { var text = ClipboardService.GetText(); if (string.IsNullOrWhiteSpace(text)) { Console.WriteLine("错误:读取剪切板值无效!"); return; } var array = text.Split(Environment.NewLine); text = string.Join(';', array); text = $"\"{text}\""; ClipboardService.SetText(text); Console.WriteLine("OK"); }); command.AddCommand(rd); }
public static Command GetCommand() { var timerange = new Option <string>(new string[] { "--timerange", "-t" }, "Time range to use (today, thisweek, lastweek, thismonth, lastmonth)"); var includeIds = new Option <bool>(new string[] { "--include-ids", "-iid" }, () => false, "Include IDs in printout"); var search = new Option <string>(new string[] { "--search", "-s" }, "Search for substring in client/project/task/notes"); var summary = new Option <bool>(new string[] { "--summary" }, "Summarize the hours for listed entries"); var cmd = new Command("list", "List (search) time entries") { timerange, includeIds, search, summary, }; cmd.AddAlias("ls"); cmd.Handler = CommandHandler.Create <string, bool, bool, bool, string>(Execute); return(cmd); }
public static void Add(RootCommand command) { var pau = new Command("packasfui", "X. (本地)打包 ASF-UI 到嵌入的资源中"); pau.AddAlias("pau"); //pau.AddOption(new Option<string>("-ver", () => string.Empty, "通过命令行将版本号传入,如果不填则自动读取")); pau.Handler = CommandHandler.Create((/*string ver*/) => { var packDiaPath = Path.Combine(projPath, "..", "ASF-UI"); var packFilePath = Path.Combine(projPath, "src", "ST.Client", "Resources", "asf-ui" + FileEx.TAR_BR); if (File.Exists(packFilePath)) { File.Delete(packFilePath); } var files = new List <PublishFileInfo>(); ScanPath(packDiaPath, files); CreateBrotliPack(packFilePath, files); Console.WriteLine("OK"); }); command.AddCommand(pau); }
private static void ListNotes(this Command command) { var c = new Command("list", "List all registered notes"); c.AddAlias("ls"); c.Handler = CommandHandler.Create(async(IConsole console) => { var store = new NoteStore(); var notes = await store.GetAllAsync(); var view = new ListView <Note>(notes); if (view.IsEmpty) { return; } console.Append(view); }); command.Add(c); }
public Command GetCommand() { var view = new Command("view", "Views upcoming calendar events") { new Option <bool>(new string[] { "--agenda", "-a" }, "Displays today's agenda") }; view.Handler = CommandHandler.Create(async(bool agenda) => await Execute(agenda)); var logout = new Command("logout", "Logs out of the current Google account"); logout.Handler = CommandHandler.Create(async() => await Logout()); var cmd = new Command("calendar", "Display's today's calendar events") { view, logout }; cmd.AddAlias("cal"); return(cmd); }
public Command GetCommand() { var view = new Command("view", "Views activities from the past week") { new Option <int>(new string[] { "--days", "-d" }, () => 7, "Number of days to view up to 90. Defaults to 7.") }; view.Handler = CommandHandler.Create(async(int days) => await View(days)); var configure = new Command("configure", "Configures the Strava provider"); configure.AddAlias("config"); configure.Handler = CommandHandler.Create(async() => await Configure()); var command = new Command("strava", "Displays Strava fitness activities") { view, configure }; command.AddAlias("fitness"); return(command); }
public static Command GetCommand() { var id = new Option <long>(new string[] { "-id" }, "ID of time entry"); var timerange = new Option <string>(new string[] { "--timerange", "-t" }, "Time range to use (today, thisweek, lastweek, thismonth, lastmonth)"); var search = new Option <string>(new string[] { "--search", "-s" }, "Search for substring in client/project/task/notes"); var hour = new Option <decimal>(new string[] { "--hours", "-h" }, "Override duration (hours) of copied entry"); var notes = new Option <string>(new string[] { "--notes", "-n" }, "Override notes of copied time entry"); var cmd = new Command("copy", "Copy time entries") { id, timerange, hour, search, notes, }; cmd.AddAlias("cp"); cmd.Handler = CommandHandler.Create <long?, decimal?, string, string, string>(Execute); return(cmd); }
private static Command CreateConfidentialCommand() { var ccaCommand = new Command("confidential", "Confidential Client Application") { Handler = CommandLineHost.GetCommandHandler <ConfidentialClientApplicationAppConfigExecutor>() }; ccaCommand.AddAlias("cca"); var ccaClientSecretOption = new Option <string>("--secret") { Name = nameof(ConfidentialClientApplicationOptions.ClientSecret), Description = "Client Secret", Argument = { Name = "SECRET" } }; ccaClientSecretOption.AddAlias("-s"); ccaCommand.AddOption(ccaClientSecretOption); ccaCommand.AddCommand(CreateAccountsCommand()); ccaCommand.AddCommand(CreateSilentTokenAcquisitionCommand()); return(ccaCommand); }