Пример #1
0
 public TheInitializeMethod()
 {
     _contextMock1    = new Mock <IScriptPackContext>();
     _contextMock2    = new Mock <IScriptPackContext>();
     _scriptPackMock1 = new Mock <IScriptPack>();
     _scriptPackMock1.Setup(p => p.GetContext()).Returns(_contextMock1.Object);
     _scriptPackMock2 = new Mock <IScriptPack>();
     _scriptPackMock2.Setup(p => p.GetContext()).Returns(_contextMock2.Object);
     _scriptPackSession = new ScriptPackSession(new List <IScriptPack> {
         _scriptPackMock1.Object, _scriptPackMock2.Object
     });
     _scriptPackSession.InitializePacks();
 }
Пример #2
0
        public virtual void Initialize(
            IEnumerable <string> paths, IEnumerable <IScriptPack> scriptPacks, params string[] scriptArgs)
        {
            AddReferences(paths.ToArray());
            var bin   = Path.Combine(FileSystem.CurrentDirectory, FileSystem.BinFolder);
            var cache = Path.Combine(FileSystem.CurrentDirectory, FileSystem.DllCacheFolder);

            ScriptEngine.BaseDirectory  = bin;
            ScriptEngine.CacheDirectory = cache;

            _log.Debug("Initializing script packs");
            var scriptPackSession = new ScriptPackSession(scriptPacks, scriptArgs);

            ScriptPackSession = scriptPackSession;
            scriptPackSession.InitializePacks();
        }
Пример #3
0
        static public ScriptCSSession Create(Cmdlet cmdlet)
        {
            ScriptCSSession session = null;
            var             logger  = new CurrentLogger();

            using (logger.CreateActiveLoggerSession(new CmdletLogger(cmdlet)))
            {
                IScriptHostFactory factory = new ScriptHostFactory();
                var engine = new RoslynScriptEngine(factory, logger);
                engine.BaseDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var currentCmdletScriptPack = new CurrentCmdletScriptPack();
                var scriptPackSession       = new ScriptPackSession(new IScriptPack[] { currentCmdletScriptPack });
                scriptPackSession.InitializePacks();

                session = new ScriptCSSession(engine, scriptPackSession, currentCmdletScriptPack, logger);
            }

            return(session);
        }
Пример #4
0
        public void Execute(string script, IEnumerable<string> paths, IEnumerable<IScriptPack> scriptPacks)
        {
            var bin = Path.Combine(_fileSystem.GetWorkingDirectory(script), "bin");

            var references = DefaultReferences.Union(paths);

            _scriptEngine.BaseDirectory = bin;

            var scriptPackSession = new ScriptPackSession(scriptPacks);

            scriptPackSession.InitializePacks();

            var path = Path.IsPathRooted(script) ? script : Path.Combine(_fileSystem.CurrentDirectory, script);
            var code = _filePreProcessor.ProcessFile(path);

            _scriptEngine.Execute(code, references, DefaultNamespaces, scriptPackSession);

            scriptPackSession.TerminatePacks();
        }
        public static ScriptCSSession Create(Cmdlet cmdlet)
        {
            ScriptCSSession session = null;
            var logger = new CurrentLogger();

            using (logger.CreateActiveLoggerSession(new CmdletLogger(cmdlet)))
            {
                IScriptHostFactory factory = new ScriptHostFactory();
                var engine = new RoslynScriptEngine(factory, logger);
                engine.BaseDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var currentCmdletScriptPack = new CurrentCmdletScriptPack();
                var scriptPackSession = new ScriptPackSession(new IScriptPack[] { currentCmdletScriptPack });
                scriptPackSession.InitializePacks();

                session = new ScriptCSSession( engine, scriptPackSession, currentCmdletScriptPack, logger );
            }

            return session;
        }
Пример #6
0
        public virtual void Initialize(IEnumerable<string> paths, IEnumerable<IScriptPack> scriptPacks)
        {
            References = DefaultReferences.Union(paths);
            var bin = Path.Combine(FileSystem.CurrentDirectory, "bin");

            ScriptEngine.BaseDirectory = bin;

            Logger.Debug("Initializing script packs");
            var scriptPackSession = new ScriptPackSession(scriptPacks);

            scriptPackSession.InitializePacks();
            ScriptPackSession = scriptPackSession;
        }
        public virtual void Initialize(IEnumerable<string> paths, IEnumerable<IScriptPack> scriptPacks, params string[] scriptArgs)
        {
            AddReferences(paths.ToArray());
            var bin = Path.Combine(FileSystem.CurrentDirectory, "bin");

            ScriptEngine.BaseDirectory = bin;

            Logger.Debug("Initializing script packs");
            var scriptPackSession = new ScriptPackSession(scriptPacks, scriptArgs);

            scriptPackSession.InitializePacks();
            ScriptPackSession = scriptPackSession;
        }
Пример #8
0
        public virtual void Initialize(
            IEnumerable<string> paths, IEnumerable<IScriptPack> scriptPacks, params string[] scriptArgs)
        {
            AddReferences(paths.ToArray());
            var bin = Path.Combine(FileSystem.CurrentDirectory, FileSystem.BinFolder);
            var cache = Path.Combine(FileSystem.CurrentDirectory, FileSystem.DllCacheFolder);

            ScriptEngine.BaseDirectory = bin;
            ScriptEngine.CacheDirectory = cache;

            _log.Debug("Initializing script packs");
            var scriptPackSession = new ScriptPackSession(scriptPacks, scriptArgs);
            ScriptPackSession = scriptPackSession;
            scriptPackSession.InitializePacks();
        }
        public void Initalize(IConfiguration configuration)
        {
            _logger.LogInformation($"Detecting CSX files in '{_env.Path}'.");

            var allCsxFiles = Directory.GetFiles(_env.Path, "*.csx", SearchOption.TopDirectoryOnly);

            if (allCsxFiles.Length == 0)
            {
                _logger.LogInformation("Could not find any CSX files");
                return;
            }

            _scriptCsContext.Path = _env.Path;
            _logger.LogInformation($"Found {allCsxFiles.Length} CSX files.");

            //script name is added here as a fake one (dir path not even a real file); this is OK though -> it forces MEF initialization
            var scriptServicesBuilder = new ScriptServicesBuilder(new ScriptConsole(), LogManager.GetCurrentClassLogger()).
                                        LogLevel(LogLevel.Info).Cache(false).Repl(false).ScriptName(_env.Path).ScriptEngine <NullScriptEngine>();

            _scriptServices = scriptServicesBuilder.Build();

            var mscorlib          = MetadataReference.CreateFromAssembly(typeof(object).GetTypeInfo().Assembly);
            var systemCore        = MetadataReference.CreateFromAssembly(typeof(Enumerable).GetTypeInfo().Assembly);
            var scriptcsContracts = MetadataReference.CreateFromAssembly(typeof(IScriptHost).Assembly);

            var parseOptions = new CSharpParseOptions(LanguageVersion.CSharp6, DocumentationMode.Parse, SourceCodeKind.Script);

            var scriptPacks   = _scriptServices.ScriptPackResolver.GetPacks().ToList();
            var assemblyPaths = _scriptServices.AssemblyResolver.GetAssemblyPaths(_env.Path);

            foreach (var csxPath in allCsxFiles)
            {
                try
                {
                    _scriptCsContext.CsxFiles.Add(csxPath);
                    var processResult = _scriptServices.FilePreProcessor.ProcessFile(csxPath);

                    var references = new List <MetadataReference> {
                        mscorlib, systemCore, scriptcsContracts
                    };
                    var usings = new List <string>(ScriptExecutor.DefaultNamespaces);

                    //default references
                    ImportReferences(references, ScriptExecutor.DefaultReferences);

                    //file usings
                    usings.AddRange(processResult.Namespaces);

                    //#r references
                    ImportReferences(references, processResult.References);

                    //nuget references
                    ImportReferences(references, assemblyPaths);

                    //script packs
                    if (scriptPacks != null && scriptPacks.Any())
                    {
                        var scriptPackSession = new ScriptPackSession(scriptPacks, new string[0]);
                        scriptPackSession.InitializePacks();

                        //script pack references
                        ImportReferences(references, scriptPackSession.References);

                        //script pack usings
                        usings.AddRange(scriptPackSession.Namespaces);

                        _scriptCsContext.ScriptPacks.UnionWith(scriptPackSession.Contexts.Select(pack => pack.GetType().ToString()));
                    }

                    _scriptCsContext.References.UnionWith(references.Select(x => x.Display));
                    _scriptCsContext.Usings.UnionWith(usings);

                    var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, usings: usings.Distinct());

                    var fileName = Path.GetFileName(csxPath);

                    var projectId = ProjectId.CreateNewId(Guid.NewGuid().ToString());
                    var project   = ProjectInfo.Create(projectId, VersionStamp.Create(), fileName, $"{fileName}.dll", LanguageNames.CSharp, null, null,
                                                       compilationOptions, parseOptions, null, null, references, null, null, true, typeof(IScriptHost));

                    _workspace.AddProject(project);
                    AddFile(csxPath, projectId);

                    foreach (var filePath in processResult.LoadedScripts.Distinct().Except(new[] { csxPath }))
                    {
                        _scriptCsContext.CsxFiles.Add(filePath);
                        var loadedFileName = Path.GetFileName(filePath);

                        var loadedFileProjectId         = ProjectId.CreateNewId(Guid.NewGuid().ToString());
                        var loadedFileSubmissionProject = ProjectInfo.Create(loadedFileProjectId, VersionStamp.Create(),
                                                                             $"{loadedFileName}-LoadedFrom-{fileName}", $"{loadedFileName}-LoadedFrom-{fileName}.dll", LanguageNames.CSharp, null, null,
                                                                             compilationOptions, parseOptions, null, null, references, null, null, true, typeof(IScriptHost));

                        _workspace.AddProject(loadedFileSubmissionProject);
                        AddFile(filePath, loadedFileProjectId);
                        _workspace.AddProjectReference(projectId, new ProjectReference(loadedFileProjectId));
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError($"{csxPath} will be ignored due to the following error:", ex);
                }
            }
        }
        public void Initalize(IConfiguration configuration)
        {
            _logger.LogInformation($"Detecting CSX files in '{_env.Path}'.");

            var allCsxFiles = Directory.GetFiles(_env.Path, "*.csx", SearchOption.TopDirectoryOnly);

            if (allCsxFiles.Length == 0)
            {
                _logger.LogInformation("Could not find any CSX files");
                return;
            }

            _scriptCsContext.Path = _env.Path;
            _logger.LogInformation($"Found {allCsxFiles.Length} CSX files.");

            //script name is added here as a fake one (dir path not even a real file); this is OK though -> it forces MEF initialization
            var scriptServicesBuilder = new ScriptServicesBuilder(new ScriptConsole(), LogManager.GetCurrentClassLogger()).
                LogLevel(LogLevel.Info).Cache(false).Repl(false).ScriptName(_env.Path).ScriptEngine<NullScriptEngine>();

            _scriptServices = scriptServicesBuilder.Build();

            var mscorlib = MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location);
            var systemCore = MetadataReference.CreateFromFile(typeof(Enumerable).GetTypeInfo().Assembly.Location);
            var scriptcsContracts = MetadataReference.CreateFromFile(typeof(IScriptHost).Assembly.Location);

            var parseOptions = new CSharpParseOptions(LanguageVersion.CSharp6, DocumentationMode.Parse, SourceCodeKind.Script);

            var scriptPacks = _scriptServices.ScriptPackResolver.GetPacks().ToList();
            var assemblyPaths = _scriptServices.AssemblyResolver.GetAssemblyPaths(_env.Path);

            foreach (var csxPath in allCsxFiles)
            {
                try
                {
                    _scriptCsContext.CsxFiles.Add(csxPath);
                    var processResult = _scriptServices.FilePreProcessor.ProcessFile(csxPath);

                    var references = new List<MetadataReference> { mscorlib, systemCore, scriptcsContracts };
                    var usings = new List<string>(ScriptExecutor.DefaultNamespaces);

                    //default references
                    ImportReferences(references, ScriptExecutor.DefaultReferences);

                    //file usings
                    usings.AddRange(processResult.Namespaces);

                    //#r references
                    ImportReferences(references, processResult.References);

                    //nuget references
                    ImportReferences(references, assemblyPaths);

                    //script packs
                    if (scriptPacks != null && scriptPacks.Any())
                    {
                        var scriptPackSession = new ScriptPackSession(scriptPacks, new string[0]);
                        scriptPackSession.InitializePacks();

                        //script pack references
                        ImportReferences(references, scriptPackSession.References);

                        //script pack usings
                        usings.AddRange(scriptPackSession.Namespaces);

                        _scriptCsContext.ScriptPacks.UnionWith(scriptPackSession.Contexts.Select(pack => pack.GetType().ToString()));
                    }

                    _scriptCsContext.References.UnionWith(references.Select(x => x.Display));
                    _scriptCsContext.Usings.UnionWith(usings);

                    var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, usings: usings.Distinct());

                    var fileName = Path.GetFileName(csxPath);

                    var projectId = ProjectId.CreateNewId(Guid.NewGuid().ToString());
                    var project = ProjectInfo.Create(projectId, VersionStamp.Create(), fileName, $"{fileName}.dll", LanguageNames.CSharp, null, null,
                                                            compilationOptions, parseOptions, null, null, references, null, null, true, typeof(IScriptHost));

                    _workspace.AddProject(project);
                    AddFile(csxPath, projectId);

                    foreach (var filePath in processResult.LoadedScripts.Distinct().Except(new[] { csxPath }))
                    {
                        _scriptCsContext.CsxFiles.Add(filePath);
                        var loadedFileName = Path.GetFileName(filePath);

                        var loadedFileProjectId = ProjectId.CreateNewId(Guid.NewGuid().ToString());
                        var loadedFileSubmissionProject = ProjectInfo.Create(loadedFileProjectId, VersionStamp.Create(),
                            $"{loadedFileName}-LoadedFrom-{fileName}", $"{loadedFileName}-LoadedFrom-{fileName}.dll", LanguageNames.CSharp, null, null,
                                            compilationOptions, parseOptions, null, null, references, null, null, true, typeof(IScriptHost));

                        _workspace.AddProject(loadedFileSubmissionProject);
                        AddFile(filePath, loadedFileProjectId);
                        _workspace.AddProjectReference(projectId, new ProjectReference(loadedFileProjectId));
                    }

                }
                catch (Exception ex)
                {
                    _logger.LogError($"{csxPath} will be ignored due to the following error:", ex);
                }
            }
        }
        protected override void ProcessRecord()
        {
            var currentCmdletScriptPack = new CurrentCmdletScriptPack(this);
            var scriptPackSession = new ScriptPackSession(new IScriptPack[] { currentCmdletScriptPack });
            scriptPackSession.InitializePacks();

            var result = _engine.Execute(Script, References, Namespaces, scriptPackSession);

            WriteObject(result);

            currentCmdletScriptPack.Terminate();
        }
        public void Initalize(IConfiguration configuration)
        {
            Logger.LogInformation($"Detecting CSX files in '{Env.Path}'.");

            // Nothing to do if there are no CSX files
            var allCsxFiles = Directory.GetFiles(Env.Path, "*.csx", SearchOption.AllDirectories);

            if (allCsxFiles.Length == 0)
            {
                Logger.LogInformation("Could not find any CSX files");
                return;
            }

            Context.RootPath = Env.Path;
            Logger.LogInformation($"Found {allCsxFiles.Length} CSX files.");

            // TODO: write and adapter to implement the new ScriptCs ILogProvider interface
            #pragma warning disable 0618
            //script name is added here as a fake one (dir path not even a real file); this is OK though -> it forces MEF initialization
            var baseScriptServicesBuilder = new ScriptServicesBuilder(new ScriptConsole(), LogManager.GetCurrentClassLogger())
                                            .LogLevel(LogLevel.Debug)
                                            .Cache(false)
                                            .Repl(false)
                                            .ScriptName(Env.Path)
                                            .ScriptEngine <NullScriptEngine>();

            var scriptServices = baseScriptServicesBuilder.Build();

            var scriptPacks   = scriptServices.ScriptPackResolver.GetPacks().ToList();
            var assemblyPaths = scriptServices.AssemblyResolver.GetAssemblyPaths(Env.Path);

            // Common usings and references
            Context.CommonUsings.UnionWith(ScriptExecutor.DefaultNamespaces);

            Context.CommonReferences.UnionWith(DotNetBaseReferences);
            Context.CommonReferences.UnionWith(scriptServices.MakeMetadataReferences(ScriptExecutor.DefaultReferences));     // ScriptCs defaults
            Context.CommonReferences.UnionWith(scriptServices.MakeMetadataReferences(assemblyPaths));                        // nuget references

            if (scriptPacks != null && scriptPacks.Any())
            {
                var scriptPackSession = new ScriptPackSession(scriptPacks, new string[0]);
                scriptPackSession.InitializePacks();

                //script pack references
                Context.CommonReferences.UnionWith(scriptServices.MakeMetadataReferences(scriptPackSession.References));

                //script pack usings
                Context.CommonUsings.UnionWith(scriptPackSession.Namespaces);

                Context.ScriptPacks.UnionWith(scriptPackSession.Contexts.Select(pack => pack.GetType().ToString()));
            }

            // Process each .CSX file
            foreach (var csxPath in allCsxFiles)
            {
                try
                {
                    CreateCsxProject(csxPath, baseScriptServicesBuilder);
                }
                catch (Exception ex)
                {
                    Logger.LogError($"{csxPath} will be ignored due to the following error:", ex.ToString());
                    Logger.LogError(ex.ToString());
                    Logger.LogError(ex.InnerException?.ToString() ?? "No inner exception.");
                }
            }
        }