public override void Specify() { given("exactly one command is loaded", () => { var exampleCommand = new ExampleCommand(); var commands = new ConsoleCommand[] { exampleCommand }; when("no parameters are specified", () => { var output = new StringWriter(); var exitCode = arrange(() => ConsoleCommandDispatcher.DispatchCommand(commands, new string[0], output)); then_the_command_runs_without_tracing_parameter_information(output, exitCode); then("the command's property is not set", () => { expect(() => exampleCommand.Foo == null); }); }); when("the only parameter specified is the command", () => { var output = new StringWriter(); var exitCode = arrange(() => ConsoleCommandDispatcher.DispatchCommand(commands, new[] { "Example" }, output)); then_the_command_runs_without_tracing_parameter_information(output, exitCode); then("the command's property is not set", () => { expect(() => exampleCommand.Foo == null); }); }); when("the only parameter specified is not the command", () => { var output = new StringWriter(); var exitCode = arrange(() => ConsoleCommandDispatcher.DispatchCommand(commands, new[] { "/f=bar" }, output)); then_the_command_runs_without_tracing_parameter_information(output, exitCode); then("the command's property is set", () => { expect(() => exampleCommand.Foo == "bar"); }); }); when("both the command and an extra parameter are specified", () => { var output = new StringWriter(); var exitCode = arrange(() => ConsoleCommandDispatcher.DispatchCommand(commands, new[] { "Example", "/f=bar" }, output)); then_the_command_runs_without_tracing_parameter_information(output, exitCode); then("the command's property is set", () => { expect(() => exampleCommand.Foo == "bar"); }); }); }); }
public Func<int> RunConsoleModeCommand(string[] lines, bool inputIsFromUser, ConsoleCommand command, TextWriter outputWriter = null) { var injectedInputStream = new MemoryStream(); var fakeConsoleWriter = outputWriter ?? new StringWriter(); var fakeConsoleReader = new StreamReader(injectedInputStream); var consoleModeCommand = new ConsoleModeCommand( () => new ConsoleCommand[] {command}, fakeConsoleWriter, fakeConsoleReader); arrange(delegate { var injectedInput = new StreamWriter(injectedInputStream); foreach (var line in lines) injectedInput.WriteLine(line); injectedInput.Flush(); injectedInputStream.Seek(0, SeekOrigin.Begin); }); IConsoleRedirectionDetection redirectionDetection = A.Fake<IConsoleRedirectionDetection>(); arrange(() => consoleModeCommand.SetConsoleRedirectionDetection(redirectionDetection)); arrange(() => A.CallTo(() => redirectionDetection.IsInputRedirected()).Returns(!inputIsFromUser)); return () => ConsoleCommandDispatcher.DispatchCommand(new ConsoleCommand[] {consoleModeCommand}, new string[0], fakeConsoleWriter); }
public static void ShowCommandHelp(ConsoleCommand selectedCommand, TextWriter console, bool skipExeInExpectedUsage = false) { var haveOptions = selectedCommand.GetActualOptions().Count > 0; console.WriteLine(); console.WriteLine("'" + selectedCommand.Command + "' - " + selectedCommand.OneLineDescription); console.WriteLine(); console.Write("Expected usage:"); if (!skipExeInExpectedUsage) { console.Write(" " + AppDomain.CurrentDomain.FriendlyName); } console.Write(" " + selectedCommand.Command); if (haveOptions) console.Write(" <options> "); console.WriteLine(selectedCommand.RemainingArgumentsHelpText); if (haveOptions) { console.WriteLine("<options> available:"); selectedCommand.GetActualOptions().WriteOptionDescriptions(console); } console.WriteLine(); }
public static string Help(string command = "") { var result = String.Empty; if (String.IsNullOrWhiteSpace(command)) { var allCommands = new StringBuilder(); allCommands.Append("Available commands (help [command name] to see parameter info):\n"); foreach (var availableNamespace in Library.Commands) { foreach (var availableCommand in availableNamespace.Value) { var commandName = availableNamespace.Key == "DefaultCommands" ? availableCommand.Key : String.Format("{0}.{1}", availableNamespace.Key, availableCommand.Key); allCommands.AppendFormat("\t{0}\n", commandName); } } result = allCommands.ToString(); } else { var cmd = new ConsoleCommand(command); var validCommand = Library.Commands.ContainsKey(cmd.LibraryClassName); var methodDictionary = Library.Commands[cmd.LibraryClassName]; if (methodDictionary.ContainsKey(cmd.Name) == false) { validCommand = false; } if (validCommand) { var parameterList = methodDictionary[cmd.Name]; var allParameters = new StringBuilder(); allParameters.AppendFormat("Available parameters for {0}\n", command); foreach (var parameterInfo in parameterList) { allParameters.AppendFormat("\t{0} {1}\n", parameterInfo.ParameterType, parameterInfo.Name); } result = allParameters.ToString(); } else { var badCommandMessage = String.Format("Unrecognized command \'{0}.{1}\'. Please type a valid command.", cmd.LibraryClassName, cmd.Name); result = badCommandMessage; } } return result; }
public override void Specify() { given("we have some commands", delegate { var firstcommand = new TestCommand().IsCommand("command-a", "oneline description a"); var secondCommand = new TestCommand().IsCommand("command-b", "oneline description b"); var commands = new ConsoleCommand[] { firstcommand, secondCommand }.ToList(); var writer = new StringWriter(); when("we dispatch the commands with no arguments", delegate { arrange(() => ConsoleCommandDispatcher.DispatchCommand(commands, new string[0], writer)); then("the output contains a list of available commands", delegate { var output = writer.ToString(); Expect.That(output).ContainsInOrder( firstcommand.Command, firstcommand.OneLineDescription, secondCommand.Command, secondCommand.OneLineDescription); }); }); when("we call a command, asking for help", delegate { var commandC = new TestCommand() .IsCommand("command-c", "one line description for C") .HasAdditionalArguments(0, "<remaining> <args>") .HasOption("o|option=", "option description", v => { }); commands.Add(commandC); arrange(() => ConsoleCommandDispatcher.DispatchCommand(commands, new string[] { commandC.Command, "/?" }, writer)); then("the output contains a all help available for that command", delegate { var output = writer.ToString(); Expect.That(output).ContainsInOrder( commandC.Command, commandC.OneLineDescription, commandC.RemainingArgumentsHelpText, "-o", "--option", "option description"); }); }); }); }
void RequestAdmin(ConsoleCommand command, string[] args) { if (args.Length == 1) { Client.Messenger.RequestAdmin(args[0]); } else { Controller.PrintError(command); } }
void RequestRooms(ConsoleCommand command, string[] args) { if (args.Length > 0) { Controller.PrintError(command); } else { Debug.Log("Request rooms"); Client.Messenger.RequestRooms(); } }
public static void ShowParsedCommand(ConsoleCommand consoleCommand, TextWriter consoleOut) { if (!consoleCommand.TraceCommandAfterParse) { return; } string[] skippedProperties = new []{ "Command", "OneLineDescription", "LongDescription", "Options", "TraceCommandAfterParse", "RemainingArgumentsCount", "RemainingArgumentsHelpText", "RequiredOptions" }; var properties = consoleCommand.GetType().GetTypeInfo().GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => !skippedProperties.Contains(p.Name)); var fields = consoleCommand.GetType().GetTypeInfo().GetFields(BindingFlags.Public | BindingFlags.Instance) .Where(p => !skippedProperties.Contains(p.Name)); Dictionary<string,string> allValuesToTrace = new Dictionary<string, string>(); foreach (var property in properties) { object value = property.GetValue(consoleCommand, new object[0]); allValuesToTrace[property.Name] = value != null ? value.ToString() : "null"; } foreach (var field in fields) { allValuesToTrace[field.Name] = MakeObjectReadable(field.GetValue(consoleCommand)); } consoleOut.WriteLine(); string introLine = String.Format("Executing {0}", consoleCommand.Command); if (string.IsNullOrEmpty(consoleCommand.OneLineDescription)) introLine = introLine + ":"; else introLine = introLine + " (" + consoleCommand.OneLineDescription + "):"; consoleOut.WriteLine(introLine); foreach(var value in allValuesToTrace.OrderBy(k => k.Key)) consoleOut.WriteLine(" " + value.Key + " : " + value.Value); consoleOut.WriteLine(); }
//string public void AssignCommand(string commandName, Action <string> command, string helpText = "") { string cmd = commandName; if (_allCommands.ContainsKey(cmd)) { Debug.Log("command already contained: " + cmd); } else { _allCommands[cmd] = new ConsoleCommand(command, helpText); } }
/// <summary> /// Simply create a new ConsoleCommand object using the single argument string. /// </summary> /// <param name="argList">The list of command line arguments.</param> /// <returns>A ConsoleCommand object.</returns> /// <remarks> /// Will throw an exception on error, which will be caught in the caller. /// </remarks> private static ConsoleCommand ParseCommandLine(IReadOnlyList <string> argList) { // The object returned to the method caller. ConsoleCommand consoleCommand = null; // Create a new ConsoleCommand using the current command line argument. if (argList != null) { // create and populate a ConsoleCommand object. consoleCommand = new ConsoleCommand(argList[0]); } return(consoleCommand); }
/// <summary> /// Adds a command to the console which can then be used if it doesn't already exist. /// </summary> /// <param name="cmd">A console command object which should be added.</param> /// <returns></returns> public bool RegisterCommand(ConsoleCommand cmd) { if (_commands.Exists(c => c.command.ToLower() == cmd.command.ToLower())) { return(false); } else { _commands.Add(cmd); _commands = (List <ConsoleCommand>)_commands.OrderBy(c => c.command).ToList(); return(true); } }
//no params public void AssignCommand(string commandName, Action command, string helpText = "") { string cn = commandName.ToUpper(); if (_allCommands.ContainsKey(cn)) { Debug.Log("command already contained: " + cn); } else { _allCommands[cn] = new ConsoleCommand(param => command(), helpText); } }
/// <summary> Registers a callback to a command that is executable in the GameConsole. </summary> /// <remarks> Multiple callbacks can be registered to the same command. All will be executed, in the order in which they /// were registered. </remarks> /// <exception cref="ArgumentNullException"> <paramref name="command" /> or <paramref name="callback" /> is null. </exception> /// <param name="command"> the command string to use </param> /// <param name="callback"> the handler that is to be registered </param> public static void RegisterCommand(string command, ConsoleCommand callback) { Argument.NotNull(callback); Argument.NotNull(command); if (!_commands.ContainsKey(command)) { _commands[command] = callback; } else { _commands[command] += callback; } }
public void ConsoleCommandSimilarParameters() { var cmd = new ConsoleCommand("foo bar=\"baz\" bar=\"boo\""); Assert.AreEqual("foo", cmd.Name); Assert.AreEqual(2, cmd.Arguments.Count()); Assert.AreEqual("bar", cmd.Arguments.First().Key); Assert.AreEqual("baz", cmd.Arguments.First().Value); Assert.AreEqual("bar", cmd.Arguments.Skip(1).First().Key); Assert.AreEqual("boo", cmd.Arguments.Skip(1).First().Value); }
public void CommandWillReturnOutputAsString() { var command = new ConsoleCommand { CommandFullLocation = "CommandLineUnitTester" }; var runner = new ConsoleRunner(command); runner.Execute(); Assert.That(runner.Output.Contains("This is echo base."), Is.True); }
/// <summary> /// </summary> /// <param name="consoleCommand"></param> /// <param name="files"></param> /// <returns>Returns files filtered by Inclusion/Exclusion type parameters</returns> private static List <string> GetFilteredFiles(ConsoleCommand consoleCommand, List <string> files) { bool FileTypeInclusionFlag = consoleCommand.CommandArgs.ContainsKey(ConsoleFlag.FileTypeInclusions); bool FileTypeExclusionFlag = consoleCommand.CommandArgs.ContainsKey(ConsoleFlag.FileTypeExclusions); var FileTypeInclusions = FileTypeInclusionFlag ? consoleCommand.CommandArgs[ConsoleFlag.FileTypeInclusions].Split(new char[] { ',', ';' }).Select(x => x.Trim('.')) : null; var FileTypeExclusions = FileTypeExclusionFlag ? consoleCommand.CommandArgs[ConsoleFlag.FileTypeExclusions].Split(new char[] { ',', ';' }).Select(x => x.Trim('.')) : null; files = FileTypeInclusions == null ? files : files.Where(file => FileTypeInclusions.Contains(Path.GetExtension(file).Trim('.'))).ToList(); files = FileTypeExclusions == null ? files : files.Where(file => !FileTypeExclusions.Contains(Path.GetExtension(file).Trim('.'))).ToList(); return(files); }
static FormHelper() { AvailableForms = new List <FormInfo>(); ConsoleCommand.Register("mono_extensions", (args) => { if (instance == null) { instance = new FormLoader(); } instance.Show(); }); }
public ConsoleCommandRepository() { //these commands should never be created by the ResolveTypeDelegate. They're internal only AddCommand(BuildCommandInfo(new HelpCommand())); if (Config.ConsoleMode.Enabled) { AddCommand(BuildCommandInfo(ConsoleCommand = new ConsoleCommand())); } if (Config.ShowViewArgsCommand) { AddCommand(BuildCommandInfo(new ViewArgsCommand())); } }
public ConsoleCommand ParseCommand(CommandFileReader reader, CommandsFile commandsFile, Type targetClass, out int skip) { ConsoleCommand result = new ConsoleCommand(); string line = reader.NextLine(); if (Regex.IsMatch(line, RegexCommand)) { result.Names = Regex.Match(line, @"\(" + CreateMulitpleRegex(RegexVariable) + @"\)").Value .Trim('(', ')').Split(',').Select(s => s.Trim()).ToArray(); } while (!reader.IsDone) { line = reader.NextLine(); if (Regex.IsMatch(line, RegexParameter)) { result.Add(ParseParameter(reader.Copy(), commandsFile, out int _skip)); reader.Skip(_skip); if (!reader.IsDone) { reader.Back(); } } else if (Regex.IsMatch(line, RegexExample)) { result.Add(ParseExample(reader.Copy(), commandsFile, out int _skip)); reader.Skip(_skip); if (!reader.IsDone) { reader.Back(); } } else if (Regex.IsMatch(line, RegexCommandContents)) { string value = line.Substring(line.IndexOf(':') + 1).Trim(); result.SetCallback(targetClass.GetMethod(value)); } else if (EndsBlock(line)) { break; } else { throw new Exception(); } } skip = reader.Position - reader.Start - 1; return(result); }
public void CommandRunnerWillHaveErrorOutput() { var command = new ConsoleCommand { CommandFullLocation = "CommandLineUnitTester", Arguments = "We read you red 5" }; var runner = new ConsoleRunner(command); runner.Execute(); Assert.That(runner.ErrorOutput.Contains("This is on the Error Stream")); }
public void CommandWithArguments() { var command = new ConsoleCommand { CommandFullLocation = "CommandLineUnitTester", Arguments = "We read you red 5", }; var runner = new ConsoleRunner(command); runner.Execute(); Assert.That(runner.Output.Contains("Wereadyoured5"), Is.True); }
void when_the_command_is_ran_without_the_parameter_then_the_console_gives_error_output(ConsoleCommand command, string parameterName) { when("that command is ran without the parameter", delegate() { StringWriter output = new StringWriter(); var exitCode = arrange(() => ConsoleCommandDispatcher.DispatchCommand(command,new[] {command.Command}, output)); then("the output indicates the parameter wasn't specified", delegate() { expect(() => output.ToString().Contains("Missing option: " + parameterName)); }); then("the exit code indicates the call failed", delegate() { expect(() => exitCode == -1); }); }); }
/// <summary> /// The constructor of the base class, from which Mako Runners should be derived, /// will store various bits of data relating to the service being created. These /// bits of data will be similar for all Mako Runners. /// </summary> /// <param name="keyServer"></param> /// <param name="consoleCommand"></param> public BaseMakoRunner(Guid keyServer, ConsoleCommand consoleCommand) { // Info = new RunnerInfo(consoleCommand); // MyRunnerId = keyServer; // Create the log provider to log progress. MakoLogger = new DelegateLogProvider(); // MakoLogger._onProgressUpdate += MakoLogger__onProgressUpdate; }
private static string BuildSearchPattern(ConsoleCommand consoleCommand) { bool FixedStringsFlag = consoleCommand.CommandArgs.ContainsKey(ConsoleFlag.FixedStrings); bool IgnoreCaseFlag = consoleCommand.CommandArgs.ContainsKey(ConsoleFlag.IgnoreCase); string SearchPattern = string.Empty; string SearchTerm = consoleCommand.CommandArgs[ConsoleFlag.SearchTerm]; string IgnoreCaseModifier = IgnoreCaseFlag ? @"(?i)" : string.Empty; SearchTerm = FixedStringsFlag ? Regex.Escape(SearchTerm) : SearchTerm; SearchPattern = @"(?<MatchedString>" + IgnoreCaseModifier + SearchTerm + @")"; return(SearchPattern); }
// Called when the mod is loaded public override void OnLoad() { // Do your initialization here Keybind.Add(this, tptocar); Keybind.Add(this, tptomuscle); Keybind.Add(this, tptotruck); Keybind.Add(this, tptorepairshop); Keybind.Add(this, tptohome); Keybind.Add(this, tptostore); Keybind.Add(this, tptosatsuna); ConsoleCommand.Add(new TeleportPluginCommand()); ModConsole.Print("First Plugin has been loaded!"); }
void Say(ConsoleCommand command, string[] args) { // lmao hack. string str = ""; foreach (var arg in args) { str += arg + " "; } str.TrimEnd(' '); Client.Messenger.Say(str); }
private ConsoleCommand CreateConsoleCommand(ConsoleAttribute attribute, ConsoleCommandHandler handler) { ConsoleCommand scommand = new ConsoleCommand(); if (attribute != null) { scommand.description = attribute.Description; scommand.syntax = attribute.Syntax; scommand.mingmlevel = attribute.GmLevel; scommand.handler = handler; } return(scommand); }
private bool Redo(ConsoleCommand cc) { var result = false; if (String.IsNullOrEmpty(cc.Argument)) { invoker.Logger.Redo(); result = true; } else if (cc.Argument == "all") { invoker.Logger.RedoAll(); result = true; } else if (cc.HasNumberArgument) { int level = 0; if (Int32.TryParse(cc.Operand.ToString(), out level)) { if (level >= 0) { if (level <= invoker.Logger.RedoLevels) { invoker.Logger.RedoTo(level); result = true; } else { Console.WriteLine("Invalid level. Level must be between 0 and {0}", invoker.Logger.RedoLevels); } } else { Console.WriteLine("Invalid level. Level must be between 0 and {0}", invoker.Logger.RedoLevels); } } else { Console.WriteLine("Invalid level"); } } else if (cc.Argument == "/?") { Console.WriteLine("Syntax: redo ['level' | all]"); Console.WriteLine("\twhere 'level' is a redo level to which the operations must be repeated."); Console.WriteLine("\twhere 'redo' performs a single redo level"); Console.WriteLine("\t'redo all' redos all the operations"); } return(result); }
public void ApplyTo(ConsoleCommand command) { FindAndLoadCredentialsIfAvailable(); if (string.IsNullOrEmpty(Username)) { ApplyWithoutCheckingFile(command); } else { command.HasOption("u=", string.Format("Username (default is {0})", Username), v => Username = v); command.HasOption("s=", string.Format("Secret key (default is for {0})", Username), v => Secret = v); } }
static void Main(string[] args) { string currentFolder = System.IO.Directory.GetCurrentDirectory(); Console.WriteLine(currentFolder); string[] arguments = System.Environment.GetCommandLineArgs(); // 1st check for <current_project>.dproj // use --dproj to force // extract dependencies Runnable command = new ConsoleCommand(); Console.WriteLine(command.run(arguments)); }
// // This is bound to the UI thread // private void NotifyCommand(ConsoleCommand command) { foreach (var listener in commandListeners) { try { listener.Callback(command); } catch (Exception ex) { _logger.Error("Exception in command listener: {0}\n{1}", ex.Message, ex.StackTrace); } } }
public override void OnLoad() { try { // Load assets AssetBundle ab = LoadAssets.LoadBundle(this, "floodlight.unity3d"); GameObject origLight = ab.LoadAsset <GameObject>("floodlight.prefab"); _light = GameObject.Instantiate <GameObject>(origLight); _light.name = "floodlight(Clone)"; _light.layer = LayerMask.NameToLayer("Parts"); _light.tag = "PART"; FloodlightBehaviour comp = _light.AddComponent <FloodlightBehaviour>(); comp.UseBattery = UseBattery; comp.Flicker = EnableFlicker; comp.Unbreakable = Unbreakable; GameObject origBox = ab.LoadAsset <GameObject>("lightbulb_box.prefab"); _box = GameObject.Instantiate <GameObject>(origBox); GameObject.Destroy(origLight); GameObject.Destroy(origBox); ab.Unload(false); // Initialize objects InitShop(); // Load save FloodlightSaveData data = FloodlightSaveData.Deserialize <FloodlightSaveData>(FloodlightSaveData.SavePath); _light.GetComponent <FloodlightBehaviour>().Load(data); for (int i = 0; i < data.BulbPos.Count; ++i) { GameObject box = GameObject.Instantiate <GameObject>(_box); box.transform.position = data.BulbPos[i]; box.transform.rotation = data.BulbRot[i]; LightbulbBoxBehaviour c = box.AddComponent <LightbulbBoxBehaviour>(); c.ShopList = _list; c.Activate(); c.SetBought(); } // Set up command ConsoleCommand.Add(new FloodlightCommand(_light)); } catch (Exception ex) { ModConsole.Error(ex.ToString()); } }
public override void Specify() { given("a no-op command that requires a parameter", delegate() { var noopCommand = new CommandWithRequiredParameter(); var commands = new ConsoleCommand[] { noopCommand }; when("that command is ran without the parameter", delegate() { StringWriter output = new StringWriter(); var exitCode = arrange(() => ConsoleCommandDispatcher.DispatchCommand(commands, new[] { "required" }, output)); then("the output indicates the parameter wasn't specified", delegate() { expect(() => output.ToString().Contains("Missing option: foo")); }); then("the exit code indicates the call failed", delegate() { expect(() => exitCode == -1); }); }); when("that command is ran with the parameter", delegate() { StringWriter output = new StringWriter(); var exitCode = arrange(() => ConsoleCommandDispatcher.DispatchCommand(commands, new[] { "required", "-foo", "bar" }, output)); then("the output is empty", delegate() { expect(() => string.IsNullOrEmpty(output.ToString().Trim())); }); then("the exit code indicates the call succeeded", delegate() { expect(() => exitCode == 0); }); then("the option is actually received", delegate() { expect(() => noopCommand.Foo == "bar"); }); }); }); }
private bool ProcessInput(ConsoleCommand command) { try { if (!command.suppressCommand) { LogEvent(LogEventType.All, command.rawCommand); } var args = command.rawCommand.Split(argsSplitChars, 2); command.command = args[0]; if (args.Length > 1) { command.args = args[1]; } string result = String.Empty; result = SendCommand(command.rawCommand); var lines = result.Split(lineSplitChars, StringSplitOptions.RemoveEmptyEntries).Select(l => l.Trim()).ToArray(); if (!command.suppressOutput) { foreach (var line in lines) { LogEvent(LogEventType.All, line); } } if (lines.Length == 1 && lines[0].StartsWith(NoResponseMatch)) { lines[0] = NoResponseOutput; } command.status = ConsoleStatus.Connected; command.lines = lines; this.outputProcessor.PostAction(() => ProcessOutput(command)); return(true); } catch (Exception ex) { _logger.Debug("Failed to send command '{0}'. {1}\n{2}", command.rawCommand, ex.Message, ex.ToString()); command.status = ConsoleStatus.Disconnected; this.outputProcessor.PostAction(() => ProcessOutput(command)); return(false); } }
public void AddCommand(string command, string help, ConsoleCommand func) { command = command.ToLower(); if (!_commands.ContainsKey(command)) { cCommand com = new cCommand(); com._help = help; com._func = func; _commands.Add(command, com); } else { Console.WriteLine("COMMAND " + command + "ALREADY EXISTS!"); } }
public void CommandWillRunInGivenDirectory() { var command = new ConsoleCommand { CommandFullLocation = "CommandLineUnitTester", Arguments = "We read you red 5", WorkingDirectory = @"C:\Program Files" }; var runner = new ConsoleRunner(command); runner.Execute(); Assert.That(runner.Output.Contains(@"C:\Program Files"), Is.True); }
public override void Bind(Entity entity, Main main, bool creating = false) { entity.CannotSuspend = true; Transform transform = entity.GetOrCreate <Transform>("Transform"); ConsoleCommand cmd = entity.GetOrCreate <ConsoleCommand>("ConsoleCommand"); base.Bind(entity, main, creating); entity.Add("Execute", cmd.Execute, description: "Execute console command"); entity.Add("Name", cmd.Name, description: "Name of the console command"); entity.Add("Description", cmd.Description, description: "Description to display in console help"); #if DEVELOPMENT entity.Add("EnabledInRelease", cmd.EnabledInRelease); #endif }
public static void RegisterCommand(ConsoleCommand command) { if (commands == null) { commands = new Dictionary <string, ConsoleCommand>(); } if (command == null) { return; } if (!commands.ContainsKey(command.command)) { commands.Add(command.command, command); } }
/// <summary> /// Registers a callback to a command that is executable in the GameConsole. /// </summary> /// <remarks> /// Multiple callbacks can be registered to the same command. All will be executed, in the order in which /// they were registered. /// </remarks> /// <exception cref="ArgumentNullException">thrown if <paramref name="command"/> or <paramref name="callback"/> is null.</exception> /// <param name="command">the command string to use</param> /// <param name="callback">the handler that is to be registered</param> public static void RegisterCommand(string command, ConsoleCommand callback) { if (callback == null || command == null) { throw new ArgumentNullException(); } if (!_commands.ContainsKey(command)) { _commands[command] = callback; } else { _commands[command] += callback; } }
void CreateRoom(ConsoleCommand command, string[] args) { if (args.Length > 1) { Controller.PrintError(command); } else { // Check if password was provided. Kinda shitty? Eh! if (args.Length == 0) { Client.Messenger.CreateRoom(); } else { Client.Messenger.CreateRoom(args[0]); } } }
private void WhenTheUserDoesNotSpecifyACommandThenShowAvailableCommands(List<ConsoleCommand> commands, StringWriter writer, ConsoleCommand firstcommand, ConsoleCommand secondCommand, string[] arguments) { when("the user does not specify a command", delegate { arrange(() => ConsoleCommandDispatcher.DispatchCommand(commands, arguments, writer)); then("the output contains a list of available commands", delegate { var output = writer.ToString(); Expect.That(output).ContainsInOrder( firstcommand.Command, firstcommand.OneLineDescription, secondCommand.Command, secondCommand.OneLineDescription); }); }); }
public static void ShowCommandHelp(ConsoleCommand selectedCommand, TextWriter console) { var haveOptions = selectedCommand.Options.Count > 0; console.WriteLine("'" + selectedCommand.Command + "' - " + selectedCommand.OneLineDescription); console.WriteLine(); console.Write("Expected usage: {0} {1} ", AppDomain.CurrentDomain.FriendlyName, selectedCommand.Command); if (haveOptions) console.Write("<options> "); console.WriteLine(selectedCommand.RemainingArgumentsHelpText); if (haveOptions) { console.WriteLine("<options> available:"); selectedCommand.Options.WriteOptionDescriptions(console); } console.WriteLine(); }
public override void Specify() { given("we have some commands", delegate { var firstcommand = new TestCommand().IsCommand("command-a", "oneline description a"); var secondCommand = new TestCommand().IsCommand("command-b", "oneline description b"); var commands = new ConsoleCommand[] { firstcommand, secondCommand }.ToList(); var writer = new StringWriter(); WhenTheUserDoesNotSpecifyACommandThenShowAvailableCommands(commands, writer, firstcommand, secondCommand, new string[0]); WhenTheUserDoesNotSpecifyACommandThenShowAvailableCommands(commands, writer, firstcommand, secondCommand, new [] { "help"}); ShouldShowHelpWhenRequested(commands, new string[] { "command-c", "/?" }); ShouldShowHelpWhenRequested(commands, new string[] { "help", "command-c" }); }); }
// Use this for initialization void Start(){ t = new EnterFrameTimer(200); t.OnTimer = onTimer; t.Start(); ConsoleCommand command; CompositeCommand cc = new CompositeCommand(CompositeCommandMode.SEQUENCE); cc.OnCommandItemComplete = delegate(AbstractCommand _command) { Debug.Log("Item Complete" + " " + (_command as ConsoleCommand).index.ToString()); }; cc.OnCommandComplete = delegate(AbstractCommand _command) { Debug.Log("All Complete"); }; int max = 10; for (int i = 0; i < max; i++) { command = new ConsoleCommand(); command.index = i; cc.AddCommand(command); } cc.Execute(); }
public static void ShowParsedCommand(ConsoleCommand consoleCommand, TextWriter consoleOut) { if (!consoleCommand.TraceCommandAfterParse) { return; } var deserializeRootElementName = consoleCommand.Command; var properties = consoleCommand.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => !consoleCommand._skippedProperties.Contains(p.Name)); var fields = consoleCommand.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance) .Where(p => !consoleCommand._skippedProperties.Contains(p.Name)); Dictionary<string,string> allValuesToTrace = new Dictionary<string, string>(); foreach (var property in properties) allValuesToTrace[property.Name] = property.GetValue(consoleCommand, new object[0]).ToString(); foreach (var field in fields) { object value = field.GetValue(consoleCommand); if (value != null) allValuesToTrace[field.Name] = value.ToString(); else allValuesToTrace[field.Name] = "null"; } consoleOut.WriteLine(); consoleOut.WriteLine("Executing {0} ({1}):", consoleCommand.Command, consoleCommand.OneLineDescription ?? ""); foreach(var value in allValuesToTrace.OrderBy(k => k.Key)) consoleOut.WriteLine(" " + value.Key + " : " + value.Value); consoleOut.WriteLine(); }
public static void ShowCommandHelp(ConsoleCommand selectedCommand, TextWriter console, bool skipExeInExpectedUsage = false) { var haveOptions = selectedCommand.GetActualOptions().Count > 0; console.WriteLine(); console.WriteLine("'" + selectedCommand.Command + "' - " + selectedCommand.OneLineDescription); console.WriteLine(); if (!string.IsNullOrEmpty(selectedCommand.LongDescription)) { console.WriteLine(selectedCommand.LongDescription); console.WriteLine(); } console.Write("Expected usage:"); if (!skipExeInExpectedUsage) { var exectuableName = System.IO.Path.GetFileNameWithoutExtension(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); console.Write(" " + exectuableName); } console.Write(" " + selectedCommand.Command); if (haveOptions) console.Write(" <options> "); console.WriteLine(selectedCommand.RemainingArgumentsHelpText); if (haveOptions) { console.WriteLine("<options> available:"); selectedCommand.GetActualOptions().WriteOptionDescriptions(console); } console.WriteLine(); }
public void DeregisterCommand_ObjectExistingCommand_Deregister() { var target = GetConsole(); var command = new ConsoleCommand("test", strings => { }); target.RegisterCommand(command); target.DeregisterCommand(command); Assert.IsFalse(target.IsRegistered(command)); }
public void AddConsoleCommand(string name, Plugin plugin, string callback_name) { // Hook the unload event if (plugin) plugin.OnRemovedFromManager += plugin_OnRemovedFromManager; var full_name = name.Trim(); ConsoleCommand cmd; if (consoleCommands.TryGetValue(full_name, out cmd)) { // This is a custom command which was already registered by another plugin var previous_plugin_name = cmd.PluginCallbacks[0].Plugin?.Name ?? "An unknown plugin"; var new_plugin_name = plugin?.Name ?? "An unknown plugin"; var msg = $"{new_plugin_name} has replaced the '{name}' console command previously registered by {previous_plugin_name}"; Interface.Oxide.LogWarning(msg); consoleCommands.Remove(full_name); } // The command either does not already exist or is replacing a previously registered command cmd = new ConsoleCommand(full_name); cmd.AddCallback(plugin, callback_name); // Add the new command to collections consoleCommands[full_name] = cmd; }
public void TryDeregisterCommand_ObjectExistingCommand_ReturnTrue() { var target = GetConsole(); var command = new ConsoleCommand("test", strings => { }); target.RegisterCommand(command); var result = target.TryDeregisterCommand(command); Assert.IsTrue(result); Assert.IsFalse(target.IsRegistered(command)); }
/// <summary> /// Adds a console command with a delegate callback /// </summary> /// <param name="name"></param> /// <param name="plugin"></param> /// <param name="callback"></param> public void AddConsoleCommand(string name, Plugin plugin, Func<ConsoleSystem.Arg, bool> callback) { // Hack us the dictionary if (rustcommands == null) rustcommands = typeof(ConsoleSystem.Index).GetField("dictionary", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null) as IDictionary<string, ConsoleSystem.Command>; // Hook the unload event if (plugin) { plugin.OnRemovedFromManager -= plugin_OnRemovedFromManager; plugin.OnRemovedFromManager += plugin_OnRemovedFromManager; } var full_name = name.Trim(); ConsoleCommand cmd; if (consoleCommands.TryGetValue(full_name, out cmd)) { // Another plugin registered this command if (cmd.OriginalCallback != null) { // This is a vanilla rust command which has already been pre-hooked by another plugin cmd.AddCallback(plugin, callback); return; } // This is a custom command which was already registered by another plugin var previous_plugin_name = cmd.PluginCallbacks[0].Plugin?.Name ?? "an unknown plugin"; var new_plugin_name = plugin?.Name ?? "An unknown plugin"; var msg = $"{new_plugin_name} has replaced the '{name}' console command previously registered by {previous_plugin_name}"; Interface.Oxide.LogWarning(msg); rustcommands.Remove(full_name); ConsoleSystem.Index.GetAll().Remove(cmd.RustCommand); } // The command either does not already exist or is replacing a previously registered command cmd = new ConsoleCommand(full_name); cmd.AddCallback(plugin, callback); ConsoleSystem.Command rust_command; if (rustcommands.TryGetValue(full_name, out rust_command)) { // This is a vanilla rust command which has not yet been hooked by a plugin if (rust_command.isVariable) { var new_plugin_name = plugin?.Name ?? "An unknown plugin"; Interface.Oxide.LogError($"{new_plugin_name} tried to register the {name} console variable as a command!"); return; } cmd.OriginalCallback = cmd.RustCommand.Call; cmd.RustCommand.Call = cmd.HandleCommand; } else { // This is a custom command which needs to be created rustcommands[cmd.RustCommand.namefull] = cmd.RustCommand; ConsoleSystem.Index.GetAll().Add(cmd.RustCommand); } consoleCommands[full_name] = cmd; }
void Execute(ConsoleCommand consoleCommand, string[] args) { consoleCommand.Action(consoleCommand, args); }
void Help(ConsoleCommand command, string[] args) { Debug.LogFormat("Available Commands:"); foreach (var c in Commands) { if (c.Elevated) { Debug.LogFormat("\t*{0} {1}", c.Command, c.Help); } else { Debug.LogFormat("\t*{0} {1}", c.Command, c.Help); } } }
public void RegisterCommand(ConsoleCommand action) { Commands.Add(action); }
public void RegisterElevatedCommand(ConsoleCommand action) { action.MakeElevated(); Commands.Add(action); }
public void PrintError(ConsoleCommand consoleCommand) { Debug.LogErrorFormat("Incorrect number of arguments for {0}. Requires {1}", consoleCommand.Command, consoleCommand.Help); }
public void AddCommand(ConsoleCommand command) { if (command != null) { this.Commands.Add(command); } }
public void TryRegisterCommand_ObjectNotExistingCommand_ReturnTrue() { var console = GetConsole(); var command = new ConsoleCommand("test", strings => { }); var result = console.TryRegisterCommand(command); Assert.IsTrue(result); Assert.IsTrue(console.IsRegistered(command)); }
/// <summary> /// Construct a new ConsolePluginCommand /// /// for use with OpenSim.RegisterConsolePluginCommand(myCmd); /// /// </summary> /// <param name="command">in the form of "showme new commands"</param> /// <param name="dlg">ommand delegate used in running</param> /// <param name="help">the text displayed in "help showme new commands"</param> public ConsolePluginCommand(string command, ConsoleCommand dlg, string help) { m_cmdText = command.Split(new char[] { ' ' }); m_commandDelegate = dlg; m_helpText = help; }
public void RegisterCommand_ObjectNotExistingCommand_Registered() { var console = GetConsole(); var command = new ConsoleCommand("test", strings => { }); console.RegisterCommand(command); Assert.IsTrue(console.IsRegistered(command)); }