Наследование: IFilePreProcessor
Пример #1
0
        public ScriptServices Build(IRepl repl)
        {
            //TODO: this need to be wired up properly using our own IoC container from caliburn.

            var underlyingLogger = LogManager.GetCurrentClassLogger();
            var replLogger = new ReplLogger(LogLevel.Info, repl, underlyingLogger);
            ILog logger = replLogger;

            var fileSystem = new FileSystem();
            var engine = new RoslynScriptEngine(new ReplScriptHostFactory(), logger);
            var filePreProcessor = new FilePreProcessor(fileSystem, logger, new ILineProcessor[] {new LoadLineProcessor(fileSystem), new ReferenceLineProcessor(fileSystem), new UsingLineProcessor() });
            var packageAssemblyResolver = new PackageAssemblyResolver(fileSystem, new PackageContainer(fileSystem, logger), logger);
            var installationProvider = new NugetInstallationProvider(fileSystem, logger);

            return new ScriptServices(
                fileSystem,
                packageAssemblyResolver,
                new ScriptExecutor(fileSystem, filePreProcessor, engine, logger),
                engine,
                filePreProcessor,
                new ScriptPackResolver(new IScriptPack[0]),
                new PackageInstaller(installationProvider, logger),
                null, //IObjectSerializer
                logger,
                new AssemblyResolver(fileSystem, packageAssemblyResolver, new AssemblyUtility(), logger),
                null, //IConsole
                installationProvider
                );
        }
Пример #2
0
        public object LoadFromFile(ISimpleConfig config, string path)
        {
            var fileSystem = new FileSystem { CurrentDirectory = AppDomain.CurrentDomain.SetupInformation.ApplicationBase };
            log.InfoFormat(CultureInfo.InvariantCulture, "Executing '{0}'", fileSystem.GetFullPath(path));
            log.DebugFormat(CultureInfo.InvariantCulture, "The current directory is {0}", fileSystem.CurrentDirectory);

            var scriptCsLog = LogManager.GetLogger("ScriptCs");
            var lineProcessors = new ILineProcessor[]
            {
                new LoadLineProcessor(fileSystem),
                new ReferenceLineProcessor(fileSystem),
                new UsingLineProcessor(),
            };

            var filePreProcessor = new FilePreProcessor(fileSystem, scriptCsLog, lineProcessors);
            var engine = new RoslynScriptInMemoryEngine(new ConfigRScriptHostFactory(config), scriptCsLog);
            var executor = new ConfigRScriptExecutor(fileSystem, filePreProcessor, engine, scriptCsLog);
            executor.AddReferenceAndImportNamespaces(new[] { typeof(Config), typeof(IScriptHost) });

            ScriptResult result;
            executor.Initialize(new string[0], new IScriptPack[0]);
            try
            {
                result = executor.Execute(path);
            }
            finally
            {
                executor.Terminate();
            }

            RethrowExceptionIfAny(result, path);
            return result.ReturnValue;
        }
Пример #3
0
        public void Execute(string script)
        {
            var foregroundColor = Console.ForegroundColor;

            try
            {
                if (PreProcessorUtil.IsLoadLine(script))
                {
                    var filepath = PreProcessorUtil.GetPath(PreProcessorUtil.LoadString, script);
                    script = FilePreProcessor.ProcessFile(filepath);
                }
                else if (PreProcessorUtil.IsRLine(script))
                {
                    var assemblyPath = PreProcessorUtil.GetPath(PreProcessorUtil.RString, script);
                    References = References.Union(new[] { assemblyPath });
                    return;
                }

                Console.ForegroundColor = ConsoleColor.Cyan;
                var result = ScriptEngine.Execute(script, References, DefaultNamespaces, ScriptPackSession);
                if (result != null)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine(result.ToJsv()

                                      );
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("\r\n" + ex + "\r\n");
            }
            Console.ForegroundColor = foregroundColor;
        }
Пример #4
0
        public virtual ScriptResult Execute(string script, params string[] scriptArgs)
        {
            var path   = Path.IsPathRooted(script) ? script : Path.Combine(FileSystem.CurrentDirectory, script);
            var result = FilePreProcessor.ProcessFile(path);

            ScriptEngine.FileName = Path.GetFileName(path);
            return(EngineExecute(Path.GetDirectoryName(path), scriptArgs, result));
        }
Пример #5
0
        public virtual ScriptResult ExecuteScript(string script, params string[] scriptArgs)
        {
            var result     = FilePreProcessor.ProcessScript(script);
            var references = References.Union(result.References);
            var namespaces = Namespaces.Union(result.Namespaces);

            Logger.Debug("Starting execution in engine");
            return(ScriptEngine.Execute(result.Code, scriptArgs, references, namespaces, ScriptPackSession));
        }
Пример #6
0
        public virtual ScriptResult Execute(string script, string[] scriptArgs)
        {
            var path       = Path.IsPathRooted(script) ? script : Path.Combine(FileSystem.CurrentDirectory, script);
            var result     = FilePreProcessor.ProcessFile(path);
            var references = References.Union(result.References);
            var namespaces = Namespaces.Union(result.UsingStatements);

            Logger.Debug("Starting execution in engine");
            return(ScriptEngine.Execute(result.Code, scriptArgs, references, namespaces, ScriptPackSession));
        }
Пример #7
0
        public virtual ScriptResult ExecuteScript(string script, params string[] scriptArgs)
        {
            var result = FilePreProcessor.ProcessScript(script);

            References = References.Union(result.References);
            var namespaces = Namespaces.Union(result.Namespaces);

            Logger.Debug("Starting execution in engine");

            InjectScriptLibraries(FileSystem.CurrentDirectory, result, ScriptPackSession.State);
            return(ScriptEngine.Execute(result.Code, scriptArgs, References, namespaces, ScriptPackSession));
        }
Пример #8
0
        public virtual ScriptResult Execute(string script, params string[] scriptArgs)
        {
            var path   = Path.IsPathRooted(script) ? script : Path.Combine(FileSystem.CurrentDirectory, script);
            var result = FilePreProcessor.ProcessFile(path);

            References = References.Union(result.References);
            var namespaces = Namespaces.Union(result.Namespaces);

            ScriptEngine.FileName = Path.GetFileName(path);

            Logger.Debug("Starting execution in engine");

            InjectScriptLibraries(Path.GetDirectoryName(path), result, ScriptPackSession.State);
            return(ScriptEngine.Execute(result.Code, scriptArgs, References, namespaces, ScriptPackSession));
        }
Пример #9
0
        protected internal virtual FilePreProcessorResult LoadScriptLibraries(string workingDirectory)
        {
            if (string.IsNullOrWhiteSpace(ScriptLibraryComposer.ScriptLibrariesFile))
            {
                return(null);
            }

            var scriptLibrariesPath = Path.Combine(workingDirectory, FileSystem.PackagesFolder,
                                                   ScriptLibraryComposer.ScriptLibrariesFile);

            if (FileSystem.FileExists(scriptLibrariesPath))
            {
                _log.DebugFormat("Found Script Library at {0}", scriptLibrariesPath);
                return(FilePreProcessor.ProcessFile(scriptLibrariesPath));
            }

            return(null);
        }
Пример #10
0
        public object LoadFromFile(ISimpleConfig config, string path)
        {
            var fileSystem = new FileSystem { CurrentDirectory = AppDomain.CurrentDomain.SetupInformation.ApplicationBase };
            log.InfoFormat("Executing '{0}'", fileSystem.GetFullPath(path));
            log.DebugFormat("The current directory is {0}", fileSystem.CurrentDirectory);

            var scriptCsLog = new LogProviderAdapter();
            var lineProcessors = new ILineProcessor[]
            {
                new LoadLineProcessor(fileSystem),
                new ReferenceLineProcessor(fileSystem),
                new UsingLineProcessor(),
            };

            var filePreProcessor = new FilePreProcessor(fileSystem, scriptCsLog, lineProcessors);
            var engine = new RoslynScriptInMemoryEngine(new ConfigRScriptHostFactory(config), scriptCsLog);
            var executor = new ScriptExecutor(fileSystem, filePreProcessor, engine, scriptCsLog);
            executor.AddReferenceAndImportNamespaces(new[] { typeof(Config), typeof(IScriptHost) });
            executor.AddReferences(this.references);

            ScriptResult result;
            executor.Initialize(new string[0], new IScriptPack[0]);

            // HACK (adamralph): BaseDirectory is set to bin subfolder in Initialize()!
            executor.ScriptEngine.BaseDirectory = executor.FileSystem.CurrentDirectory;
            try
            {
                result = executor.Execute(path);
            }
            finally
            {
                executor.Terminate();
            }

            RethrowExceptionIfAny(result, path);
            return result.ReturnValue;
        }
Пример #11
0
        public override ScriptResult Execute(string script, params string[] scriptArgs)
        {
            Guard.AgainstNullArgument("script", script);

            try
            {
                if (script.StartsWith(":"))
                {
                    var tokens = script.Split(' ');
                    if (tokens[0].Length > 1)
                    {
                        var command = Commands.FirstOrDefault(x => x.CommandName == tokens[0].Substring(1));

                        if (command != null)
                        {
                            var argsToPass = new List <object>();
                            foreach (var argument in tokens.Skip(1))
                            {
                                var argumentResult = ScriptEngine.Execute(
                                    argument, _scriptArgs, References, Namespaces, ScriptPackSession);

                                if (argumentResult.CompileExceptionInfo != null)
                                {
                                    throw new Exception(
                                              GetInvalidCommandArgumentMessage(argument),
                                              argumentResult.CompileExceptionInfo.SourceException);
                                }

                                if (argumentResult.ExecuteExceptionInfo != null)
                                {
                                    throw new Exception(
                                              GetInvalidCommandArgumentMessage(argument),
                                              argumentResult.ExecuteExceptionInfo.SourceException);
                                }

                                if (!argumentResult.IsCompleteSubmission)
                                {
                                    throw new Exception(GetInvalidCommandArgumentMessage(argument));
                                }

                                argsToPass.Add(argumentResult.ReturnValue);
                            }

                            var commandResult = command.Execute(this, argsToPass.ToArray());
                            return(ProcessCommandResult(commandResult));
                        }
                    }
                }

                var preProcessResult = FilePreProcessor.ProcessScript(script);

                ImportNamespaces(preProcessResult.Namespaces.ToArray());

                foreach (var reference in preProcessResult.References)
                {
                    var referencePath = FileSystem.GetFullPath(Path.Combine(FileSystem.BinFolder, reference));
                    AddReferences(FileSystem.FileExists(referencePath) ? referencePath : reference);
                }

                Console.ForegroundColor = ConsoleColor.Cyan;

                Buffer = (Buffer == null)
                    ? preProcessResult.Code
                    : Buffer + Environment.NewLine + preProcessResult.Code;

                var result = ScriptEngine.Execute(Buffer, _scriptArgs, References, Namespaces, ScriptPackSession);
                if (result == null)
                {
                    return(ScriptResult.Empty);
                }

                if (result.CompileExceptionInfo != null)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(result.CompileExceptionInfo.SourceException.Message);
                }

                if (result.ExecuteExceptionInfo != null)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(result.ExecuteExceptionInfo.SourceException.Message);
                }

                if (result.InvalidNamespaces.Any())
                {
                    RemoveNamespaces(result.InvalidNamespaces.ToArray());
                }

                if (!result.IsCompleteSubmission)
                {
                    return(result);
                }

                if (result.ReturnValue != null)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;

                    var serializedResult = _serializer.Serialize(result.ReturnValue);

                    Console.WriteLine(serializedResult);
                }

                Buffer = null;
                return(result);
            }
            catch (FileNotFoundException fileEx)
            {
                RemoveReferences(fileEx.FileName);

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(Environment.NewLine + fileEx + Environment.NewLine);

                return(new ScriptResult(compilationException: fileEx));
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(Environment.NewLine + ex + Environment.NewLine);

                return(new ScriptResult(executionException: ex));
            }
            finally
            {
                Console.ResetColor();
            }
        }
Пример #12
0
        public virtual ScriptResult ExecuteScript(string script, params string[] scriptArgs)
        {
            var result = FilePreProcessor.ProcessScript(script);

            return(EngineExecute(FileSystem.CurrentDirectory, scriptArgs, result));
        }
Пример #13
0
        public override ScriptResult Execute(string script, params string[] scriptArgs)
        {
            try
            {
                if (PreProcessorUtil.IsLoadLine(script))
                {
                    var filepath = PreProcessorUtil.GetPath(PreProcessorUtil.LoadString, script);
                    if (FileSystem.FileExists(filepath))
                    {
                        var processorResult = FilePreProcessor.ProcessFile(filepath);
                        script = processorResult.Code;
                    }
                    else
                    {
                        throw new FileNotFoundException(string.Format("Could not find script '{0}'", filepath), filepath);
                    }
                }
                else if (PreProcessorUtil.IsRLine(script))
                {
                    var assemblyName = PreProcessorUtil.GetPath(PreProcessorUtil.RString, script);
                    var assemblyPath = FileSystem.GetFullPath(Path.Combine(Constants.BinFolder, assemblyName));
                    AddReferences(FileSystem.FileExists(assemblyPath) ? assemblyPath : assemblyName);

                    return new ScriptResult();
                }

                Console.ForegroundColor = ConsoleColor.Cyan;

                Buffer += script;

                var result = ScriptEngine.Execute(Buffer, _scriptArgs, References, DefaultNamespaces, ScriptPackSession);
                if (result != null)
                {
                    if (result.CompileExceptionInfo != null)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(result.CompileExceptionInfo.SourceException.ToString());
                    }

                    if (result.ExecuteExceptionInfo != null)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(result.ExecuteExceptionInfo.SourceException.ToString());
                    }

                    if (result.IsPendingClosingChar)
                    {
                        return result;
                    }

                    if (result.ReturnValue != null)
                    {
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine(result.ReturnValue.ToJsv());
                    }

                    Buffer = null;
                }

                return result;
            }
            catch (FileNotFoundException fileEx)
            {
                RemoveReferences(fileEx.FileName);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("\r\n" + fileEx + "\r\n");
                return new ScriptResult { CompileExceptionInfo = ExceptionDispatchInfo.Capture(fileEx) };
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("\r\n" + ex + "\r\n");
                return new ScriptResult { ExecuteExceptionInfo = ExceptionDispatchInfo.Capture(ex) };
            }
            finally
            {
                Console.ResetColor();
            }
        }
Пример #14
0
        public override ScriptResult Execute(string script, params string[] scriptArgs)
        {
            try
            {
                if (script.StartsWith("#clear", StringComparison.OrdinalIgnoreCase))
                {
                    Console.Clear();
                    return(new ScriptResult());
                }

                if (script.StartsWith("#reset"))
                {
                    Reset();
                    return(new ScriptResult());
                }

                var preProcessResult = FilePreProcessor.ProcessScript(script);

                ImportNamespaces(preProcessResult.Namespaces.ToArray());

                foreach (var reference in preProcessResult.References)
                {
                    var referencePath = FileSystem.GetFullPath(Path.Combine(Constants.BinFolder, reference));
                    AddReferences(FileSystem.FileExists(referencePath) ? referencePath : reference);
                }

                Console.ForegroundColor = ConsoleColor.Cyan;

                Buffer += preProcessResult.Code;

                var result = ScriptEngine.Execute(Buffer, _scriptArgs, References, DefaultNamespaces, ScriptPackSession);
                if (result == null)
                {
                    return(new ScriptResult());
                }

                if (result.CompileExceptionInfo != null)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(result.CompileExceptionInfo.SourceException.Message);
                }

                if (result.ExecuteExceptionInfo != null)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(result.ExecuteExceptionInfo.SourceException.Message);
                }

                if (result.IsPendingClosingChar)
                {
                    return(result);
                }

                if (result.ReturnValue != null)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine(result.ReturnValue.ToJsv());
                }

                Buffer = null;
                return(result);
            }
            catch (FileNotFoundException fileEx)
            {
                RemoveReferences(fileEx.FileName);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("\r\n" + fileEx + "\r\n");
                return(new ScriptResult {
                    CompileExceptionInfo = ExceptionDispatchInfo.Capture(fileEx)
                });
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("\r\n" + ex + "\r\n");
                return(new ScriptResult {
                    ExecuteExceptionInfo = ExceptionDispatchInfo.Capture(ex)
                });
            }
            finally
            {
                Console.ResetColor();
            }
        }