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");
                    });
                });
            });
        }
コード例 #2
0
        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);
        }
コード例 #3
0
ファイル: ConsoleHelp.cs プロジェクト: lavige777/ManyConsole
        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();
        }
コード例 #4
0
        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;
        }
コード例 #5
0
        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");
                    });
                });
            });
        }
コード例 #6
0
ファイル: AppConsole.cs プロジェクト: Trainfire/Drawesome
 void RequestAdmin(ConsoleCommand command, string[] args)
 {
     if (args.Length == 1)
     {
         Client.Messenger.RequestAdmin(args[0]);
     }
     else
     {
         Controller.PrintError(command);
     }
 }
コード例 #7
0
ファイル: AppConsole.cs プロジェクト: Trainfire/Drawesome
 void RequestRooms(ConsoleCommand command, string[] args)
 {
     if (args.Length > 0)
     {
         Controller.PrintError(command);
     }
     else
     {
         Debug.Log("Request rooms");
         Client.Messenger.RequestRooms();
     }
 }
コード例 #8
0
        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();
        }
コード例 #9
0
        //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);
            }
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: JNickVA1/TeqTankSampleCode
        /// <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);
        }
コード例 #11
0
ファイル: Console.cs プロジェクト: sloovi90/HologramClient
 /// <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);
     }
 }
コード例 #12
0
    //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);
        }
    }
コード例 #13
0
 /// <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;
     }
 }
コード例 #14
0
        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);
        }
コード例 #15
0
        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);
        }
コード例 #16
0
ファイル: GrepEngine.cs プロジェクト: 7k8m/Windows-BudgetGrep
        /// <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);
        }
コード例 #17
0
        static FormHelper()
        {
            AvailableForms = new List <FormInfo>();
            ConsoleCommand.Register("mono_extensions", (args) =>
            {
                if (instance == null)
                {
                    instance = new FormLoader();
                }

                instance.Show();
            });
        }
コード例 #18
0
 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()));
     }
 }
コード例 #19
0
ファイル: Parser.cs プロジェクト: wert007/StealthyGame
        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);
        }
コード例 #20
0
        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"));
        }
コード例 #21
0
        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);
        }
コード例 #22
0
        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); });
            });
        }
コード例 #23
0
        /// <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;
        }
コード例 #24
0
ファイル: GrepEngine.cs プロジェクト: 7k8m/Windows-BudgetGrep
        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);
        }
コード例 #25
0
        // 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!");
        }
コード例 #26
0
    void Say(ConsoleCommand command, string[] args)
    {
        // lmao hack.
        string str = "";

        foreach (var arg in args)
        {
            str += arg + " ";
        }

        str.TrimEnd(' ');

        Client.Messenger.Say(str);
    }
コード例 #27
0
        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);
        }
コード例 #28
0
    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);
    }
コード例 #29
0
        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);
            }
        }
コード例 #30
0
        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));
        }
コード例 #31
0
 //
 // 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);
         }
     }
 }
コード例 #32
0
ファイル: Floodlight.cs プロジェクト: Wampa842/MySummerMods
        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());
            }
        }
コード例 #33
0
        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");
                    });
                });
            });
        }
コード例 #34
0
        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");
                    });
                });
            });
        }
コード例 #35
0
        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);
            }
        }
コード例 #36
0
 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!");
     }
 }
コード例 #37
0
        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);
        }
コード例 #38
0
        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
        }
コード例 #39
0
 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);
     }
 }
コード例 #40
0
 /// <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;
     }
 }
コード例 #41
0
ファイル: AppConsole.cs プロジェクト: Trainfire/Drawesome
 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]);
         }
     }
 }
コード例 #42
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);
                        });
                });
        }
コード例 #43
0
ファイル: ConsoleHelp.cs プロジェクト: rohancragg/ManyConsole
        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();
        }
コード例 #44
0
        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" });
            });
        }
コード例 #45
0
ファイル: TestLog.cs プロジェクト: Assin/GearUnity
	// 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();

	}
コード例 #46
0
ファイル: ConsoleHelp.cs プロジェクト: rohancragg/ManyConsole
        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();
        }
コード例 #47
0
        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();
        }
コード例 #48
0
ファイル: ConsoleTest.cs プロジェクト: drussilla/ConsoleX
        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));
        }
コード例 #49
0
ファイル: Command.cs プロジェクト: 906507516/Oxide
        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;
        }
コード例 #50
0
ファイル: ConsoleTest.cs プロジェクト: drussilla/ConsoleX
        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));
        }
コード例 #51
0
ファイル: Command.cs プロジェクト: strykes/Oxide
        /// <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;
        }
コード例 #52
0
 void Execute(ConsoleCommand consoleCommand, string[] args)
 {
     consoleCommand.Action(consoleCommand, args);
 }
コード例 #53
0
    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);
            }
        }
    }
コード例 #54
0
 public void RegisterCommand(ConsoleCommand action)
 {
     Commands.Add(action);
 }
コード例 #55
0
 public void RegisterElevatedCommand(ConsoleCommand action)
 {
     action.MakeElevated();
     Commands.Add(action);
 }
コード例 #56
0
 public void PrintError(ConsoleCommand consoleCommand)
 {
     Debug.LogErrorFormat("Incorrect number of arguments for {0}. Requires {1}", consoleCommand.Command, consoleCommand.Help);
 }
コード例 #57
0
ファイル: DebugCommands.cs プロジェクト: jmdjr/jd-bacon
 public void AddCommand(ConsoleCommand command)
 {
     if (command != null)
     {
         this.Commands.Add(command);
     }
 }
コード例 #58
0
ファイル: ConsoleTest.cs プロジェクト: drussilla/ConsoleX
        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));
        }
コード例 #59
0
 /// <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;
 }
コード例 #60
0
ファイル: ConsoleTest.cs プロジェクト: drussilla/ConsoleX
        public void RegisterCommand_ObjectNotExistingCommand_Registered()
        {
            var console = GetConsole();
            var command = new ConsoleCommand("test", strings => { });

            console.RegisterCommand(command);

            Assert.IsTrue(console.IsRegistered(command));
        }