예제 #1
0
            public void ShouldAliasCommandWithNewName()
            {
                // arrange
                var currentDir   = @"C:\";
                var dummyCommand = new Mock <IReplCommand>();

                dummyCommand.Setup(x => x.CommandName).Returns("foo");

                var fs = new Mock <IFileSystem>();

                fs.Setup(x => x.BinFolder).Returns(Path.Combine(currentDir, "bin"));
                fs.Setup(x => x.DllCacheFolder).Returns(Path.Combine(currentDir, "cache"));

                var console  = new Mock <IConsole>();
                var executor = new Repl(null, fs.Object, null, null, null, null, null, new List <IReplCommand> {
                    dummyCommand.Object
                });

                var cmd = new AliasCommand(console.Object);

                // act
                cmd.Execute(executor, new[] { "foo", "bar" });

                // assert
                executor.Commands.Count.ShouldEqual(2);
                executor.Commands["bar"].ShouldBeSameAs(executor.Commands["foo"]);
            }
예제 #2
0
            public void ShouldPrintTheReturnToConsoleIfCommandHasReturnValue()
            {
                object returnValue = new DummyClass {
                    Hello = "World"
                };

                var helloCommand = new Mock <IReplCommand>();

                helloCommand.SetupGet(x => x.CommandName).Returns("hello");
                helloCommand.Setup(x => x.Execute(It.IsAny <IScriptExecutor>(), It.IsAny <object[]>()))
                .Returns(returnValue);

                var mocks = new Mocks {
                    ReplCommands = new[] { helloCommand }
                };

                mocks.ObjectSerializer.Setup(x => x.Serialize(returnValue)).Returns("hello world");

                _repl = GetRepl(mocks);

                _repl.Execute(":hello", null);

                mocks.ObjectSerializer.Verify(x => x.Serialize(returnValue), Times.Once);
                mocks.Console.Verify(x => x.WriteLine("hello world"), Times.Once);
            }
예제 #3
0
 public void Execute(Repl repl, ReplParser.BangContext tree, bool piped)
 {
     if (tree.BANG().GetText() == "!!")
     {
         var recall = repl.History.Last();
         System.Console.Error.WriteLine(recall);
         repl.Execute(recall);
         return;
     }
     else if (int.TryParse(tree.BANG().GetText().Substring(1), out int num))
     {
         var recall = repl.History[num];
         System.Console.Error.WriteLine(recall);
         repl.Execute(recall);
         return;
     }
     else
     {
         var s = tree.BANG().GetText().Substring(1);
         for (int i = repl.History.Count - 1; i >= 0; --i)
         {
             if (repl.History[i].StartsWith(s))
             {
                 var recall = repl.History[i];
                 System.Console.Error.WriteLine(recall);
                 repl.Execute(recall);
                 return;
             }
         }
         System.Console.Error.WriteLine("No previous command starts with " + s);
     }
 }
예제 #4
0
            public void ShouldSurfaceIncompleteArguments()
            {
                var helloCommand = new Mock <IReplCommand>();

                helloCommand.SetupGet(x => x.CommandName).Returns("hello");

                var mocks = new Mocks {
                    ReplCommands = new[] { helloCommand }
                };

                mocks.ScriptEngine.Setup(x => x.Execute(
                                             It.IsAny <string>(),
                                             It.IsAny <string[]>(),
                                             It.IsAny <AssemblyReferences>(),
                                             It.IsAny <IEnumerable <string> >(),
                                             It.IsAny <ScriptPackSession>()))
                .Returns(ScriptResult.Incomplete);

                _repl = GetRepl(mocks);

                var result = _repl.Execute(":hello foo", null);

                result.ExecuteExceptionInfo.SourceException.Message.ShouldContain(
                    "argument is not a valid expression: foo", StringComparison.OrdinalIgnoreCase);
            }
예제 #5
0
        public void Execute(Repl repl, ReplParser.CatContext tree, bool piped)
        {
            var args = tree.arg();

            if (args.Length == 0)
            {
                args = null;
            }
            var           list = new Globbing().Contents(args?.Select(t => repl.GetArg(t)).ToList());
            StringBuilder sb   = new StringBuilder();

            foreach (var f in list)
            {
                if (f is DirectoryInfo d)
                {
                    throw new Exception("Cannot cat a directory.");
                }
                else
                {
                    string input = System.IO.File.ReadAllText(f.FullName);
                    sb.Append(input);
                }
            }
            repl.input_output_stack.Push(sb.ToString());
        }
예제 #6
0
 public TheExecuteMethod()
 {
     _mocks = new Mocks();
     _repl  = GetRepl(_mocks);
     _repl.Console.ForegroundColor = ConsoleColor.White;
     _repl.Execute("foo");
 }
예제 #7
0
        public void Execute(Repl repl, ReplParser.AglContext tree, bool piped)
        {
            string lines            = repl.input_output_stack.Pop();
            var    doc              = repl.stack.Peek();
            var    pr               = ParsingResultsFactory.Create(doc);
            var    lexer            = pr.Lexer;
            var    parser           = pr.Parser;
            var    serializeOptions = new JsonSerializerOptions();

            serializeOptions.Converters.Add(new AntlrJson.ParseTreeConverter());
            serializeOptions.WriteIndented = false;
            var parse_info = JsonSerializer.Deserialize <AntlrJson.ParsingResultSet>(lines, serializeOptions);
            var nodes      = parse_info.Nodes;

            System.Windows.Forms.Form form = new System.Windows.Forms.Form();
            Microsoft.Msagl.GraphViewerGdi.GViewer viewer = new Microsoft.Msagl.GraphViewerGdi.GViewer();
            Microsoft.Msagl.Drawing.Graph          graph  = CreateGraph(nodes, parser.RuleNames.ToList());
            graph.LayoutAlgorithmSettings = new Microsoft.Msagl.Layout.Layered.SugiyamaLayoutSettings();
            viewer.Graph = graph;
            form.SuspendLayout();
            viewer.Dock = System.Windows.Forms.DockStyle.Fill;
            form.Controls.Add(viewer);
            form.ResumeLayout();
            form.ShowDialog();
        }
예제 #8
0
        private bool ExecuteLine(Repl repl)
        {
            if (string.IsNullOrWhiteSpace(repl.Buffer))
            {
                _console.Write("> ");
            }

            string line = null;

            try
            {
                line = _console.ReadLine();
            }
            catch
            {
                return(false);
            }

            if (!string.IsNullOrWhiteSpace(line))
            {
                repl.Execute(line);
            }

            return(true);
        }
예제 #9
0
        public void Execute(Repl repl, ReplParser.DelabelContext tree, bool piped)
        {
            var doc     = repl.stack.Peek();
            var results = LanguageServer.Transform.Delabel(doc);

            repl.EnactEdits(results);
        }
예제 #10
0
        public void Execute(Repl repl, ReplParser.CtreeContext tree, bool piped)
        {
            var lines            = repl.input_output_stack.Pop();
            var serializeOptions = new JsonSerializerOptions();

            serializeOptions.Converters.Add(new AntlrJson.ParseTreeConverter());
            serializeOptions.WriteIndented = false;
            var           in_tuple = JsonSerializer.Deserialize <AntlrJson.ParsingResultSet>(lines, serializeOptions);
            var           nodes    = in_tuple.Nodes;
            var           lexer    = in_tuple.Lexer;
            var           parser   = in_tuple.Parser;
            StringBuilder sb       = new StringBuilder();

            foreach (var node in nodes)
            {
                TerminalNodeImpl x = TreeEdits.LeftMostToken(node);
                var ts             = x.Payload.TokenSource;
                sb.AppendLine();
                sb.AppendLine(
                    TreeOutput.OutputTree(
                        node,
                        lexer,
                        parser,
                        null).ToString());
            }
            repl.input_output_stack.Push(sb.ToString());
        }
예제 #11
0
        private Repl GetRepl(string[] args, out MemoryBufferConsole memoryBufferConsole)
        {
            SetProfile();
            var arguments             = ParseArguments(args);
            var scriptServicesBuilder = ScriptServicesBuilderFactory.Create(arguments.CommandArguments, arguments.ScriptArguments);
            IInitializationServices _initializationServices = scriptServicesBuilder.InitializationServices;
            IFileSystem             _fileSystem             = _initializationServices.GetFileSystem();

            if (_fileSystem.PackagesFile == null)
            {
                throw new ArgumentException("The file system provided by the initialization services provided by the script services builder has a null packages file.");
            }

            if (_fileSystem.PackagesFolder == null)
            {
                throw new ArgumentException("The file system provided by the initialization services provided by the script services builder has a null package folder.");
            }

            ScriptServices scriptServices = scriptServicesBuilder.Build();

            memoryBufferConsole = new MemoryBufferConsole();
            Repl repl = new Repl(arguments.ScriptArguments, _fileSystem, scriptServices.Engine,
                                 scriptServices.ObjectSerializer, scriptServices.Logger, memoryBufferConsole,
                                 scriptServices.FilePreProcessor, scriptServices.ReplCommands);

            var workingDirectory = _fileSystem.CurrentDirectory;
            var assemblies       = scriptServices.AssemblyResolver.GetAssemblyPaths(workingDirectory);
            var scriptPacks      = scriptServices.ScriptPackResolver.GetPacks();

            repl.Initialize(assemblies, scriptPacks, null);

            return(repl);
        }
예제 #12
0
            public void ShouldResetBufferIfLineIsNoLongerMultilineConstruct()
            {
                var mocks = new Mocks();

                mocks.ScriptEngine.Setup(
                    x =>
                    x.Execute(
                        It.IsAny <string>(),
                        It.IsAny <string[]>(),
                        It.IsAny <AssemblyReferences>(),
                        It.IsAny <IEnumerable <string> >(),
                        It.IsAny <ScriptPackSession>()))
                .Returns(ScriptResult.Empty);
                mocks.FilePreProcessor.Setup(x => x.ProcessScript(It.IsAny <string>()))
                .Returns(new FilePreProcessorResult {
                    Code = "}"
                });
                mocks.FileSystem.Setup(i => i.CurrentDirectory).Returns("C:/");
                _repl        = GetRepl(mocks);
                _repl.Buffer = "class test {";
                _repl.Initialize(Enumerable.Empty <string>(), Enumerable.Empty <IScriptPack>());
                _repl.Execute("}");

                _repl.Buffer.ShouldBeNull();
            }
예제 #13
0
        public void GoShouldWork()
        {
            var adminThing = new AdminThing("some weirdo");

            adminThing.Unique = true;

            var room1 = new RoomThing("room one");
            var room2 = new RoomThing("room two");

            adminThing.Move(room1);

            var exit = new Exit("strange portal", room2);

            exit.Unique = true;

            exit.Move(room1);

            Assert.IsTrue(adminThing.Container == room1);

            Repl repl = new Repl();

            repl.Parse("l", adminThing);
            repl.Parse("go portal", adminThing);

            Assert.IsTrue(adminThing.Container == room2);
        }
예제 #14
0
            public void ShouldEvaluateStrings()
            {
                var helloCommand = new Mock <IReplCommand>();

                helloCommand.SetupGet(x => x.CommandName).Returns("hello");

                var mocks = new Mocks {
                    ReplCommands = new[] { helloCommand }
                };

                mocks.ScriptEngine.Setup(x => x.Execute(
                                             "\"world\"",
                                             It.IsAny <string[]>(),
                                             It.IsAny <AssemblyReferences>(),
                                             It.IsAny <IEnumerable <string> >(),
                                             It.IsAny <ScriptPackSession>()))
                .Returns(new ScriptResult(returnValue: "world"));

                _repl = GetRepl(mocks);

                _repl.Execute(":hello \"world\"", null);

                helloCommand.Verify(
                    x => x.Execute(
                        _repl,
                        It.Is <object[]>(i =>
                                         i[0].GetType() == typeof(string) &&
                                         (string)i[0] == "world")),
                    Times.Once);
            }
예제 #15
0
        public void Execute(Repl repl, ReplParser.UnulliteralContext tree, bool piped)
        {
            var type = tree.uclc()?.GetText();
            var expr = tree.StringLiteral()?.GetText();

            expr = expr?.Substring(1, expr.Length - 2);
            var doc     = repl.stack.Peek();
            var pr      = ParsingResultsFactory.Create(doc);
            var aparser = pr.Parser;
            var atree   = pr.ParseTree;

            if (expr != null)
            {
                using (AntlrTreeEditing.AntlrDOM.AntlrDynamicContext dynamicContext = new AntlrTreeEditing.AntlrDOM.ConvertToDOM().Try(atree, aparser))
                {
                    org.eclipse.wst.xml.xpath2.processor.Engine engine = new org.eclipse.wst.xml.xpath2.processor.Engine();
                    var nodes = engine.parseExpression(expr,
                                                       new StaticContextBuilder()).evaluate(dynamicContext, new object[] { dynamicContext.Document })
                                .Select(x => (x.NativeValue as AntlrTreeEditing.AntlrDOM.AntlrElement).AntlrIParseTree as TerminalNodeImpl).ToList();
                    var results = LanguageServer.Transform.UnUpperLowerCaseLiteral(nodes, type == "uc", doc);
                    repl.EnactEdits(results);
                }
            }
            else
            {
                var results = LanguageServer.Transform.UnUpperLowerCaseLiteral(null, type == "uc", doc);
                repl.EnactEdits(results);
            }
        }
예제 #16
0
        public CommandResult Execute()
        {
            _console.WriteLine("scriptcs (ctrl-c to exit)" + Environment.NewLine);
            var repl = new Repl(_scriptArgs, _fileSystem, _scriptEngine, _serializer, _logger, _console, _filePreProcessor, _replCommands);

            var workingDirectory = _fileSystem.CurrentDirectory;
            var assemblies = _assemblyResolver.GetAssemblyPaths(workingDirectory);
            var scriptPacks = _scriptPackResolver.GetPacks();

            repl.Initialize(assemblies, scriptPacks, ScriptArgs);

            try
            {
                if (!string.IsNullOrWhiteSpace(_scriptName))
                {
                    _logger.Info(string.Format("Loading script: {0}", _scriptName));
                    repl.Execute(string.Format("#load {0}", _scriptName));
                }

                while (ExecuteLine(repl))
                {
                }

                _console.WriteLine();
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                return CommandResult.Error;
            }

            repl.Terminate();
            return CommandResult.Success;
        }
예제 #17
0
        public void SetUp()
        {
            _calls      = new List <string>();
            _testObject = new TestObject(_calls);

            _repl = new Repl()
                    .Register("action0", () => _calls.Add("action0"))
                    .Register <string>("action1", x => _calls.Add($"action1 {x}"))
                    .Register("func0", () =>
            {
                _calls.Add("func0");
                return(this);
            })
                    .Register <int, string>("func1", x =>
            {
                _calls.Add($"func1 {x}");
                return($"value {x}");
            })
                    .Register <string, int, string>("func2", (v, x) =>
            {
                _calls.Add($"func2 {v} {x}");
                return($"value {v}={x}");
            })
                    .Register <string, int, bool, string>("func3", (v, x, f) =>
            {
                _calls.Add($"func3 {v} {x} {f}");
                return($"value {v}={x}[{f}]");
            })
                    .Register("method", this, nameof(TestMethod))
                    .Register("value", 3)
                    .Register("object", _testObject);
        }
예제 #18
0
파일: Program.cs 프로젝트: rpwjanzen/robin
        static void Main(string[] args)
        {
            var currentUser = "******";

            Console.WriteLine("Hello " + currentUser + ".");
            Repl.Start(Console.In, Console.Out);
        }
예제 #19
0
        public void Stop()
        {
            _log.Information("Stopping MCSM");

            //Stops the repl loop
            Repl.Exit();
        }
예제 #20
0
        public void Execute(Repl repl, ReplParser.RupContext tree, bool piped)
        {
            var expr = tree.StringLiteral()?.GetText();

            expr = expr?.Substring(1, expr.Length - 2);
            var doc                 = repl.stack.Peek();
            var pr                  = ParsingResultsFactory.Create(doc);
            var aparser             = pr.Parser;
            var atree               = pr.ParseTree;
            List <IParseTree> nodes = null;

            if (expr != null)
            {
                using (AntlrTreeEditing.AntlrDOM.AntlrDynamicContext dynamicContext = new AntlrTreeEditing.AntlrDOM.ConvertToDOM().Try(atree, aparser))
                {
                    org.eclipse.wst.xml.xpath2.processor.Engine engine = new org.eclipse.wst.xml.xpath2.processor.Engine();
                    nodes = engine.parseExpression(expr,
                                                   new StaticContextBuilder()).evaluate(dynamicContext, new object[] { dynamicContext.Document })
                            .Select(x => (x.NativeValue as AntlrTreeEditing.AntlrDOM.AntlrElement).AntlrIParseTree).ToList();
                }
            }
            var results = LanguageServer.Transform.RemoveUselessParentheses(doc, nodes);

            repl.EnactEdits(results);
        }
예제 #21
0
        public CommandResult Execute()
        {
            _console.WriteLine("scriptcs (ctrl-c or blank to exit)\r\n");
            var repl = new Repl(_scriptArgs, _fileSystem, _scriptEngine, _logger, _console, _filePreProcessor);

            var workingDirectory = _fileSystem.CurrentDirectory;
            var assemblies       = _assemblyResolver.GetAssemblyPaths(workingDirectory);
            var scriptPacks      = _scriptPackResolver.GetPacks();

            repl.Initialize(assemblies, scriptPacks);

            try
            {
                while (ExecuteLine(repl))
                {
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                return(CommandResult.Error);
            }

            repl.Terminate();
            return(CommandResult.Success);
        }
예제 #22
0
        public CommandResult Execute()
        {
            _console.WriteLine("scriptcs (ctrl-c or blank to exit)\r\n");
            var repl = new Repl(_scriptArgs, _fileSystem, _scriptEngine, _logger, _console, _filePreProcessor, _replCommandService);

            var workingDirectory = _fileSystem.CurrentDirectory;
            var assemblies       = _assemblyResolver.GetAssemblyPaths(workingDirectory, string.Empty);
            var scriptPacks      = _scriptPackResolver.GetPacks();

            repl.Initialize(assemblies, scriptPacks, ScriptArgs);

            try
            {
                if (!string.IsNullOrWhiteSpace(_scriptName))
                {
                    _logger.Info(string.Format("Loading preseeded script: {0}", _scriptName));
                    repl.Execute(string.Format("#load {0}", _scriptName));
                }

                while (ExecuteLine(repl))
                {
                }

                _console.WriteLine();
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                return(CommandResult.Error);
            }

            repl.Terminate();
            return(CommandResult.Success);
        }
예제 #23
0
        public void Execute(Repl repl, ReplParser.XgrepContext tree, bool piped)
        {
            var expr = repl.GetArg(tree.arg());

            IParseTree[] atrees;
            Parser       parser;
            Lexer        lexer;
            string       text;
            string       fn;
            ITokenStream tokstream;

            if (piped)
            {
                var lines            = repl.input_output_stack.Pop();
                var serializeOptions = new JsonSerializerOptions();
                serializeOptions.Converters.Add(new AntlrJson.ParseTreeConverter());
                serializeOptions.WriteIndented = false;
                var parse_info = JsonSerializer.Deserialize <AntlrJson.ParsingResultSet>(lines, serializeOptions);
                text      = parse_info.Text;
                fn        = parse_info.FileName;
                atrees    = parse_info.Nodes;
                parser    = parse_info.Parser;
                lexer     = parse_info.Lexer;
                tokstream = parse_info.Stream;
            }
            else
            {
                var doc = repl.stack.Peek();
                var pr  = ParsingResultsFactory.Create(doc);
                parser    = pr.Parser;
                lexer     = pr.Lexer;
                text      = pr.Code;
                fn        = pr.FullFileName;
                tokstream = pr.TokStream;
                IParseTree atree = pr.ParseTree;
                atrees = new IParseTree[] { atree };
            }
            org.eclipse.wst.xml.xpath2.processor.Engine engine = new org.eclipse.wst.xml.xpath2.processor.Engine();
            IParseTree root = atrees.First().Root();
            var        ate  = new AntlrTreeEditing.AntlrDOM.ConvertToDOM();

            using (AntlrTreeEditing.AntlrDOM.AntlrDynamicContext dynamicContext = ate.Try(root, parser))
            {
                var l     = atrees.Select(t => ate.FindDomNode(t));
                var nodes = engine.parseExpression(expr,
                                                   new StaticContextBuilder()).evaluate(dynamicContext, l.ToArray())
                            .Select(x => (x.NativeValue as AntlrTreeEditing.AntlrDOM.AntlrElement).AntlrIParseTree).ToArray();

                var serializeOptions = new JsonSerializerOptions();
                serializeOptions.Converters.Add(new AntlrJson.ParseTreeConverter());
                serializeOptions.WriteIndented = false;
                var parse_info_out = new AntlrJson.ParsingResultSet()
                {
                    Text = text, FileName = fn, Lexer = lexer, Parser = parser, Stream = tokstream, Nodes = nodes
                };
                string js1 = JsonSerializer.Serialize(parse_info_out, serializeOptions);
                repl.input_output_stack.Push(js1);
            }
        }
예제 #24
0
        private bool handleEnter()
        {
            TextRange textRange = new TextRange(
                // TextPointer to the start of content in the RichTextBox.
                Repl.Document.ContentStart,
                // TextPointer to the end of content in the RichTextBox.
                Repl.Document.ContentEnd
                );

            // The Text property on a TextRange object returns a string
            // representing the plain text content of the TextRange.
            String s         = textRange.Text;
            int    last_i_of = s.LastIndexOf(">");

            if (last_i_of < 0)
            {
                Repl.AppendText("Error, this repl window sucks real bad, there _MUST_ be a >. Blame crappy C# WPF code\r\n");
                Repl.AppendText("> " + s);
                return(true);
            }

            String ss = s.Substring(last_i_of + 1);

            if (string.IsNullOrWhiteSpace(ss))
            {
                Repl.AppendText("\r> ");
                Repl.CaretPosition = Repl.Document.ContentEnd;
                return(true);
            }
            if (matchParens(ss))
            {
                Repl.AppendText("\r");
                List <string> F;
                try
                {
                    F = ev.evaluate(ss);
                    foreach (string x in F)
                    {
                        Repl.AppendText(x + "\r");
                    }
                }
                catch (Exception e)
                {
                    Repl.AppendText("Error!\r");
                    Repl.AppendText(e.Message + "\r");
                }
                finally
                {
                    Repl.AppendText("> ");
                    Repl.CaretPosition = Repl.Document.ContentEnd;
                }
                return(true);
            }

            Repl.AppendText("\rParen Mismatch detected\r");
            Repl.AppendText("> " + ss.TrimEnd());
            Repl.CaretPosition = Repl.Document.ContentEnd;
            return(true);
        }
예제 #25
0
 public TheTerminateMethod()
 {
     _mocks = new Mocks();
     _repl  = GetRepl(_mocks);
     _mocks.FileSystem.Setup(x => x.CurrentDirectory).Returns(@"c:\");
     _repl.Initialize(new List <string>(), new[] { _mocks.ScriptPack.Object });
     _repl.Terminate();
 }
예제 #26
0
        static void Main(string[] args)
        {
            var user = System.Environment.UserName;

            Console.WriteLine($"Hello {user}, welcome to Monkey program language!");
            Console.WriteLine("Feel free to type any command.");
            Repl.Start(System.Console.In, System.Console.Out);
        }
예제 #27
0
        public void ShouldSerialize()
        {
            var repl       = new Repl();
            var serialized = repl.Serialize();

            System.Console.WriteLine(serialized);
            Assert.IsTrue(serialized != null);
        }
예제 #28
0
        public void Execute(Repl repl, ReplParser.CombineContext tree, bool piped)
        {
            var doc1    = repl.stack.PeekTop(0);
            var doc2    = repl.stack.PeekTop(1);
            var results = LanguageServer.Transform.CombineGrammars(doc1, doc2);

            repl.EnactEdits(results);
        }
예제 #29
0
        public void Execute(Repl repl, ReplParser.PrintContext tree, bool piped)
        {
            var doc = repl.stack.Peek();

            System.Console.Error.WriteLine();
            System.Console.Error.WriteLine(doc.FullPath);
            System.Console.WriteLine(doc.Code);
        }
예제 #30
0
        public void Execute(Repl repl, ReplParser.RunContext tree, bool piped)
        {
            var g     = new Grun(repl);
            var a     = tree.arg();
            var input = repl.GetArg(a);

            g.Run(repl, input);
        }
예제 #31
0
        public void Execute(Repl repl, ReplParser.GenerateContext tree, bool piped)
        {
            var g          = new Generate(repl);
            var p          = tree.arg();
            var parameters = p.Select(a => repl.GetArg(a)).ToArray();

            g.Run(repl, parameters);
        }
예제 #32
0
        private bool ExecuteLine(Repl repl)
        {
            _console.Write("> ");
            var line = _console.ReadLine();
            if (line == "")
                return false;

            repl.Execute(line);
            return true;
        }
예제 #33
0
        private bool ExecuteLine(Repl repl)
        {
            if (string.IsNullOrWhiteSpace(repl.Buffer))
                _console.Write("> ");

            var line = _console.ReadLine();
            if (line == string.Empty && string.IsNullOrWhiteSpace(repl.Buffer)) return false;

            repl.Execute(line);
            return true;
        }
예제 #34
0
        public void InstructionWorksEndToEnd(SetUp setup, string input,
                                         string expectedOutput)
        {
            var model = new ProgrammingModel();
              var memory = new Memory();
              setup(model, memory);
              var repl = new Repl(model, memory);

              if (!repl.TryRead(input))
            Assert.Fail(string.Format("Unable to read assembly input: '{0}'", input));
              if (!repl.Execute())
            Assert.Fail(string.Format("Unable to execute input: '{0}'", input));
              Assert.That(repl.PrintRegisters(), Is.StringContaining(expectedOutput));
        }
예제 #35
0
 public CommandResult Execute()
 {
     _console.WriteLine("scriptcs (ctrl-c or blank to exit)\r\n");
     var repl = new Repl(_fileSystem, _scriptEngine, _logger, _console, _filePreProcessor);
     repl.Initialize(GetAssemblyPaths(_fileSystem.CurrentDirectory), _scriptPackResolver.GetPacks());
     try
     {
         while (ExecuteLine(repl))
         {
         }
     }
     catch (Exception ex)
     {
         _logger.Error(ex.Message);
         return CommandResult.Error;
     }
     repl.Terminate();
     return CommandResult.Success;
 }
예제 #36
0
            public void ShouldAliasCommandWithNewName()
            {
                // arrange
                var currentDir = @"C:\";
                var dummyCommand = new Mock<IReplCommand>();
                dummyCommand.Setup(x => x.CommandName).Returns("foo");

                var fs = new Mock<IFileSystem>();
                fs.Setup(x => x.BinFolder).Returns(Path.Combine(currentDir, "bin"));
                fs.Setup(x => x.DllCacheFolder).Returns(Path.Combine(currentDir, "cache"));

                var console = new Mock<IConsole>();
                var executor = new Repl(null, fs.Object, null, null, null, null, null, new List<IReplCommand> { dummyCommand.Object });

                var cmd = new AliasCommand(console.Object);

                // act
                cmd.Execute(executor, new[] { "foo", "bar" });

                // assert
                executor.Commands.Count.ShouldEqual(2);
                executor.Commands["bar"].ShouldBeSameAs(executor.Commands["foo"]);
            }
예제 #37
0
            public void ShouldAliasCommandWithNewName(
                Mock<IFileSystem> fileSystem,
                Mock<IScriptEngine> engine,
                Mock<IObjectSerializer> serializer,
                Mock<ILog> logger,
                Mock<IScriptLibraryComposer> composer,
                Mock<IConsole> console,
                Mock<IFilePreProcessor> filePreProcessor)
            {
                // arrange
                var currentDir = @"C:\";
                var dummyCommand = new Mock<IReplCommand>();
                dummyCommand.Setup(x => x.CommandName).Returns("foo");

                fileSystem.Setup(x => x.BinFolder).Returns(Path.Combine(currentDir, "bin"));
                fileSystem.Setup(x => x.DllCacheFolder).Returns(Path.Combine(currentDir, "cache"));

                var executor = new Repl(
                    new string[0],
                    fileSystem.Object,
                    engine.Object,
                    serializer.Object,
                    logger.Object,
                    composer.Object,
                    console.Object,
                    filePreProcessor.Object,
                    new List<IReplCommand> { dummyCommand.Object });

                var cmd = new AliasCommand(console.Object);

                // act
                cmd.Execute(executor, new[] { "foo", "bar" });

                // assert
                executor.Commands.Count.ShouldEqual(2);
                executor.Commands["bar"].ShouldBeSameAs(executor.Commands["foo"]);
            }
예제 #38
0
            public void ShouldReferenceAssemblyBasedOnNameWithExtensionIfFileDoesNotExistBecauseItLooksInGACThen()
            {
                var mocks = new Mocks();
                mocks.FileSystem.Setup(i => i.CurrentDirectory).Returns("C:/");
                mocks.FileSystem.Setup(i => i.GetFullPath(It.IsAny<string>())).Returns(@"C:/my.dll");
                mocks.FileSystem.Setup(i => i.FileExists(It.IsAny<string>())).Returns(false);
                mocks.FilePreProcessor.Setup(x => x.ProcessScript(It.IsAny<string>()))
                    .Returns(new FilePreProcessorResult { References = new List<string> { "my.dll" } });

                _repl = GetRepl(mocks);
                _repl.Initialize(Enumerable.Empty<string>(), Enumerable.Empty<IScriptPack>());
                _repl.Execute("#r \"my.dll\"");

                _repl.References.PathReferences.Contains("my.dll").ShouldBeTrue();
            }
예제 #39
0
            public void ShouldReferenceAssemblyBasedOnFullPathIfFileExists()
            {
                var mocks = new Mocks();
                mocks.FileSystem.Setup(i => i.CurrentDirectory).Returns("C:/");
                mocks.FileSystem.Setup(i => i.GetFullPath(It.IsAny<string>())).Returns(@"C:/my.dll");
                mocks.FilePreProcessor.Setup(x => x.ProcessScript(It.IsAny<string>()))
                    .Returns(new FilePreProcessorResult { References = new List<string> { "my.dll" } });

                _repl = GetRepl(mocks);
                _repl.Initialize(Enumerable.Empty<string>(), Enumerable.Empty<IScriptPack>());
                _repl.Execute("#r \"my.dll\"");

                mocks.FileSystem.Verify(x => x.FileExists("C:/my.dll"), Times.Once());
            }
예제 #40
0
            public void ShouldReturnCommandsScriptResultfCommandHasReturnValueThatAlreadyIsScriptResult()
            {
                var returnValue = new ScriptResult("hello world");

                var helloCommand = new Mock<IReplCommand>();
                helloCommand.SetupGet(x => x.CommandName).Returns("hello");
                helloCommand.Setup(x => x.Execute(It.IsAny<IRepl>(), It.IsAny<object[]>()))
                    .Returns(returnValue);

                var mocks = new Mocks { ReplCommands = new[] { helloCommand } };
                mocks.ObjectSerializer.Setup(x => x.Serialize(returnValue.ReturnValue)).Returns("hello world");

                _repl = GetRepl(mocks);

                var result = _repl.Execute(":hello", null);

                mocks.ObjectSerializer.Verify(x => x.Serialize(returnValue.ReturnValue), Times.Once);
                mocks.Console.Verify(x => x.WriteLine("hello world"), Times.Once);
                result.ShouldBeSameAs(returnValue);
            }
예제 #41
0
            public void ShouldResetBufferIfLineIsNoLongerMultilineConstruct()
            {
                var mocks = new Mocks();
                mocks.ScriptEngine.Setup(
                    x =>
                    x.Execute(It.IsAny<string>(), It.IsAny<string[]>(), It.IsAny<AssemblyReferences>(),
                              It.IsAny<IEnumerable<string>>(), It.IsAny<ScriptPackSession>()))
                     .Returns(ScriptResult.Empty);
                mocks.FilePreProcessor.Setup(x => x.ProcessScript(It.IsAny<string>()))
                    .Returns(new FilePreProcessorResult { Code = "}" });
                mocks.FileSystem.Setup(i => i.CurrentDirectory).Returns("C:/");
                _repl = GetRepl(mocks);
                _repl.Buffer = "class test {";
                _repl.Initialize(Enumerable.Empty<string>(), Enumerable.Empty<IScriptPack>());
                _repl.Execute("}");

                _repl.Buffer.ShouldBeNull();
            }
예제 #42
0
 public TheInitializeMethod()
 {
     _mocks = new Mocks();
     _repl = GetRepl(_mocks);
     _mocks.FileSystem.Setup(x => x.CurrentDirectory).Returns(@"c:\");
     var paths = new[] { @"c:\path" };
     _repl.Initialize(paths, new[] { _mocks.ScriptPack.Object });
 }
예제 #43
0
            public void ShouldResubmitEverytingIfLineIsNoLongerMultilineConstruct()
            {
                var mocks = new Mocks();
                mocks.ScriptEngine.Setup(
                    x =>
                    x.Execute(It.Is<string>(i => i == "class test {}"), It.IsAny<string[]>(), It.IsAny<AssemblyReferences>(),
                              It.IsAny<IEnumerable<string>>(), It.IsAny<ScriptPackSession>()))
                     .Returns(new ScriptResult
                     {
                         IsPendingClosingChar = false
                     });
                mocks.FileSystem.Setup(i => i.CurrentDirectory).Returns("C:/");
                _repl = GetRepl(mocks);
                _repl.Buffer = "class test {";
                _repl.Initialize(Enumerable.Empty<string>(), Enumerable.Empty<IScriptPack>());
                _repl.Execute("}");

                mocks.ScriptEngine.Verify();
            }
예제 #44
0
            public void ShouldPickReplCommandIfLineStartsWithColon()
            {
                var helloCommand = new Mock<IReplCommand>();
                helloCommand.SetupGet(x => x.CommandName).Returns("hello");

                var mocks = new Mocks { ReplCommands = new[] { helloCommand } };
                _repl = GetRepl(mocks);

                _repl.Execute(":hello", null);

                helloCommand.Verify(x => x.Execute(_repl, It.Is<object[]>(i => i.Length == 0)), Times.Once);
            }
예제 #45
0
            public void ShouldReferenceAssemblyBasedOnNameIfFileDoesNotExistBecauseItLooksInGACThen()
            {
                var mocks = new Mocks();
                mocks.FileSystem.Setup(i => i.CurrentDirectory).Returns("C:/");
                mocks.FileSystem.Setup(i => i.FileExists(It.IsAny<string>())).Returns(false);

                _repl = GetRepl(mocks);
                _repl.Initialize(Enumerable.Empty<string>(), Enumerable.Empty<IScriptPack>());
                _repl.Execute("#r \"PresentationCore\"");

                _repl.References.Contains("PresentationCore").ShouldBeTrue();
            }
예제 #46
0
 public TheExecuteMethod()
 {
     _mocks = new Mocks();
     _repl = GetRepl(_mocks);
     _repl.Console.ForegroundColor = ConsoleColor.White;
     _repl.Execute("foo");
 }
예제 #47
0
            public void ShouldEvaluateArgs()
            {
                var dummyObject = new DummyClass { Hello = "World" };
                var helloCommand = new Mock<IReplCommand>();
                helloCommand.SetupGet(x => x.CommandName).Returns("hello");

                var mocks = new Mocks { ReplCommands = new[] { helloCommand } };
                mocks.ScriptEngine.Setup(x => x.Execute(
                        "myObj",
                        It.IsAny<string[]>(),
                        It.IsAny<AssemblyReferences>(),
                        It.IsAny<IEnumerable<string>>(),
                        It.IsAny<ScriptPackSession>()))
                    .Returns(new ScriptResult(returnValue: dummyObject));

                mocks.ScriptEngine.Setup(x => x.Execute(
                        "100",
                        It.IsAny<string[]>(),
                        It.IsAny<AssemblyReferences>(),
                        It.IsAny<IEnumerable<string>>(),
                        It.IsAny<ScriptPackSession>()))
                    .Returns(new ScriptResult(returnValue: 100));

                _repl = GetRepl(mocks);

                _repl.Execute(":hello 100 myObj", null);

                helloCommand.Verify(
                    x => x.Execute(
                        _repl,
                        It.Is<object[]>(i =>
                            i[0].GetType() == typeof(int) &&
                            (int)i[0] == 100 &&
                            i[1].Equals(dummyObject))),
                    Times.Once);
            }
예제 #48
0
            public void ShouldSurfaceIncompleteArguments()
            {
                var helloCommand = new Mock<IReplCommand>();
                helloCommand.SetupGet(x => x.CommandName).Returns("hello");

                var mocks = new Mocks { ReplCommands = new[] { helloCommand } };
                mocks.ScriptEngine.Setup(x => x.Execute(
                        It.IsAny<string>(),
                        It.IsAny<string[]>(),
                        It.IsAny<AssemblyReferences>(),
                        It.IsAny<IEnumerable<string>>(),
                        It.IsAny<ScriptPackSession>()))
                        .Returns(ScriptResult.Incomplete);

                _repl = GetRepl(mocks);

                var result = _repl.Execute(":hello foo", null);

                result.ExecuteExceptionInfo.SourceException.Message.ShouldContain(
                    "argument is not a valid expression: foo", StringComparison.OrdinalIgnoreCase);
            }
예제 #49
0
            public void ShouldPrintTheReturnToConsoleIfCommandHasReturnValue()
            {
                object returnValue = new DummyClass { Hello = "World" };

                var helloCommand = new Mock<IReplCommand>();
                helloCommand.SetupGet(x => x.CommandName).Returns("hello");
                helloCommand.Setup(x => x.Execute(It.IsAny<IRepl>(), It.IsAny<object[]>()))
                    .Returns(returnValue);

                var mocks = new Mocks { ReplCommands = new[] { helloCommand } };
                mocks.ObjectSerializer.Setup(x => x.Serialize(returnValue)).Returns("hello world");

                _repl = GetRepl(mocks);

                _repl.Execute(":hello", null);

                mocks.ObjectSerializer.Verify(x => x.Serialize(returnValue), Times.Once);
                mocks.Console.Verify(x => x.WriteLine("hello world"), Times.Once);
            }
예제 #50
0
            public void ShouldReferenceAssemblyIfLineIsAReference()
            {
                var mocks = new Mocks();
                mocks.FileSystem.Setup(i => i.CurrentDirectory).Returns("C:/");
                mocks.FileSystem.Setup(i => i.GetFullPath(It.IsAny<string>())).Returns(@"c:/my.dll");
                mocks.FileSystem.Setup(x => x.FileExists("c:/my.dll")).Returns(true);
                mocks.FilePreProcessor.Setup(x => x.ProcessScript(It.IsAny<string>()))
                    .Returns(new FilePreProcessorResult { References = new List<string> { "my.dll" } });

                _repl = GetRepl(mocks);
                _repl.Initialize(Enumerable.Empty<string>(), Enumerable.Empty<IScriptPack>());
                _repl.Execute("#r \"my.dll\"");

                //default references = 6, + 1 we just added
                _repl.References.PathReferences.Count().ShouldEqual(7);
            }
예제 #51
0
            public void ShouldRemoveReferenceIfAssemblyIsNotFound()
            {
                var mocks = new Mocks();
                mocks.FileSystem.Setup(i => i.CurrentDirectory).Returns("C:/");
                mocks.FileSystem.Setup(i => i.GetFullPath(It.IsAny<string>())).Returns(@"C:/my.dll");
                mocks.FileSystem.Setup(i => i.FileExists(It.IsAny<string>())).Returns(false);
                mocks.FilePreProcessor.Setup(x => x.ProcessScript(It.IsAny<string>()))
                    .Returns(new FilePreProcessorResult { References = new List<string> { "my.dll" } });
                mocks.ScriptEngine.Setup(
                    i =>
                    i.Execute(It.IsAny<string>(), It.IsAny<string[]>(), It.IsAny<AssemblyReferences>(),
                              It.IsAny<IEnumerable<string>>(), It.IsAny<ScriptPackSession>()))
                     .Throws(new FileNotFoundException("error", "my.dll"));

                _repl = GetRepl(mocks);
                _repl.Initialize(Enumerable.Empty<string>(), Enumerable.Empty<IScriptPack>());
                _repl.Execute("#r \"my.dll\"");
                _repl.References.PathReferences.Contains("my.dll").ShouldBeFalse();
            }
예제 #52
0
 public TheExecuteMethod()
 {
     _mocks = new Mocks();
     _mocks.FilePreProcessor.Setup(x => x.ProcessScript("foo"))
         .Returns(new FilePreProcessorResult { Code = "foo" });
     _repl = GetRepl(_mocks);
     _repl.Console.ForegroundColor = ConsoleColor.White;
     _repl.Execute("foo");
 }
예제 #53
0
            public void ShouldSetBufferIFLineIsFirstOfMultilineConstruct()
            {
                var mocks = new Mocks();
                mocks.ScriptEngine.Setup(
                    x =>
                    x.Execute(It.IsAny<string>(), It.IsAny<string[]>(), It.IsAny<AssemblyReferences>(),
                              It.IsAny<IEnumerable<string>>(), It.IsAny<ScriptPackSession>()))
                     .Returns<ScriptResult>(x => new ScriptResult()
                     {
                         ExpectingClosingChar = ')',
                         IsPendingClosingChar = true
                     });
                mocks.FilePreProcessor.Setup(x => x.ProcessScript(It.IsAny<string>()))
                    .Returns(new FilePreProcessorResult { Code = "var x = 1;" });
                mocks.FileSystem.Setup(i => i.CurrentDirectory).Returns("C:/");
                _repl = GetRepl(mocks);
                _repl.Initialize(Enumerable.Empty<string>(), Enumerable.Empty<IScriptPack>());
                _repl.Execute("var x = 1;");

                _repl.Buffer.ShouldNotBeNull();
            }
예제 #54
0
            public void ShouldExecuteLoadedFileIfLineIsALoad()
            {
                var mocks = new Mocks();
                mocks.FilePreProcessor.Setup(x => x.ProcessScript(It.IsAny<string>()))
                     .Returns(new FilePreProcessorResult());
                mocks.FileSystem.Setup(x => x.FileExists("file.csx")).Returns(true);

                _repl = GetRepl(mocks);
                _repl.Execute("#load \"file.csx\"");

                mocks.ScriptEngine.Verify(i => i.Execute(It.IsAny<string>(), It.IsAny<string[]>(), It.IsAny<AssemblyReferences>(), It.IsAny<IEnumerable<string>>(), It.IsAny<ScriptPackSession>()), Times.Once());
            }
예제 #55
0
 public TheTerminateMethod()
 {
     _mocks = new Mocks();
     _repl = GetRepl(_mocks);
     _mocks.FileSystem.Setup(x => x.CurrentDirectory).Returns(@"c:\");
     _repl.Initialize(new List<string>(), new[] { _mocks.ScriptPack.Object });
     _repl.Terminate();
 }
예제 #56
0
            public void ShouldNotExecuteAnythingIfLineIsAReference()
            {
                var mocks = new Mocks();
                mocks.FileSystem.Setup(i => i.CurrentDirectory).Returns("C:/");
                _repl = GetRepl(mocks);
                _repl.Initialize(Enumerable.Empty<string>(), Enumerable.Empty<IScriptPack>());
                _repl.Execute("#r \"my.dll\"");

                mocks.ScriptEngine.Verify(i => i.Execute(It.IsAny<string>(), It.IsAny<string[]>(), It.IsAny<AssemblyReferences>(), It.IsAny<IEnumerable<string>>(), It.IsAny<ScriptPackSession>()), Times.Never());
            }
예제 #57
0
            public void ShouldNotExecuteLoadedFileIfFileDoesNotExist()
            {
                var mocks = new Mocks();
                mocks.FileSystem.Setup(x => x.FileExists("file.csx")).Returns(false);

                _repl = GetRepl(mocks);
                _repl.Execute("#load \"file.csx\"");

                mocks.ScriptEngine.Verify(i => i.Execute(It.IsAny<string>(), It.IsAny<string[]>(), It.IsAny<AssemblyReferences>(), It.IsAny<IEnumerable<string>>(), It.IsAny<ScriptPackSession>()), Times.Never());
            }
예제 #58
0
            public void ShouldProcessFileIfLineIsALoad()
            {
                var mocks = new Mocks();
                mocks.FileSystem.Setup(x => x.FileExists("file.csx")).Returns(true);

                _repl = GetRepl(mocks);
                _repl.Execute("#load \"file.csx\"");

                mocks.FilePreProcessor.Verify(i => i.ProcessScript("#load \"file.csx\""), Times.Once());
            }
예제 #59
0
            public void ShouldEvaluateStrings()
            {
                var helloCommand = new Mock<IReplCommand>();
                helloCommand.SetupGet(x => x.CommandName).Returns("hello");

                var mocks = new Mocks { ReplCommands = new[] { helloCommand } };
                mocks.ScriptEngine.Setup(x => x.Execute(
                        "\"world\"",
                        It.IsAny<string[]>(),
                        It.IsAny<AssemblyReferences>(),
                        It.IsAny<IEnumerable<string>>(),
                        It.IsAny<ScriptPackSession>()))
                    .Returns(new ScriptResult(returnValue: "world"));

                _repl = GetRepl(mocks);

                _repl.Execute(":hello \"world\"", null);

                helloCommand.Verify(
                    x => x.Execute(
                        _repl,
                        It.Is<object[]>(i =>
                            i[0].GetType() == typeof(string) &&
                            (string)i[0] == "world")),
                    Times.Once);
            }
예제 #60
0
            public TheInitializeMethod()
            {
                _tempPath = Path.GetTempPath();

                _mocks = new Mocks();
                _repl = GetRepl(_mocks);
                _mocks.FileSystem.Setup(x => x.CurrentDirectory).Returns(_tempPath);
                var paths = new[] { Path.Combine(_tempPath, "path") };
                _repl.Initialize(paths, new[] { _mocks.ScriptPack.Object });
            }