Exemplo n.º 1
0
        protected TReturn ProcessScriptState <TReturn>(ScriptState <TReturn> scriptState)
        {
            if (scriptState.Exception != null)
            {
                Logger.Log("Script execution resulted in an exception.");
                Logger.Log(scriptState.Exception.Message);
                Logger.Log(scriptState.Exception.StackTrace);
            }

            return(scriptState.ReturnValue);
        }
Exemplo n.º 2
0
        public virtual ScriptCompilationContext <TReturn> CreateCompilationContext <TReturn, THost>(ScriptContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var runtimeIdentitfer = GetRuntimeIdentitifer();

            _logger.Verbose($"Current runtime is '{runtimeIdentitfer}'.");

            var opts = CreateScriptOptions(context);

            var runtimeId = RuntimeEnvironment.GetRuntimeIdentifier();
            var inheritedAssemblyNames = DependencyContext.Default.GetRuntimeAssemblyNames(runtimeId).Where(x =>
                                                                                                            x.FullName.StartsWith("system.", StringComparison.OrdinalIgnoreCase) ||
                                                                                                            x.FullName.StartsWith("microsoft.codeanalysis", StringComparison.OrdinalIgnoreCase) ||
                                                                                                            x.FullName.StartsWith("mscorlib", StringComparison.OrdinalIgnoreCase));

            foreach (var inheritedAssemblyName in inheritedAssemblyNames)
            {
                _logger.Verbose("Adding reference to an inherited dependency => " + inheritedAssemblyName.FullName);
                var assembly = Assembly.Load(inheritedAssemblyName);
                opts = opts.AddReferences(assembly);
            }

            var runtimeContext = File.Exists(Path.Combine(context.WorkingDirectory, Project.FileName)) ? ProjectContext.CreateContextForEachTarget(context.WorkingDirectory).FirstOrDefault() : null;

            if (runtimeContext == null)
            {
                _logger.Verbose("Unable to find project context for CSX files. Will default to non-context usage.");
                var scriptProjectProvider = ScriptProjectProvider.Create(new LoggerFactory());
                var scriptProjectInfo     = scriptProjectProvider.CreateProject(context.WorkingDirectory, "netcoreapp1.1");
                runtimeContext = ProjectContext.CreateContextForEachTarget(scriptProjectInfo.PathToProjectJson).FirstOrDefault();
            }

            _logger.Verbose($"Found runtime context for '{runtimeContext.ProjectFile.ProjectFilePath}'.");
            var projectExporter = runtimeContext.CreateExporter(context.Configuration);

            var runtimeDependencies = new HashSet <string>();
            var projectDependencies = projectExporter.GetDependencies();

            foreach (var projectDependency in projectDependencies)
            {
                var runtimeAssemblyGroups = projectDependency.RuntimeAssemblyGroups;

                foreach (var libraryAsset in runtimeAssemblyGroups.GetDefaultAssets())
                {
                    var runtimeAssemblyPath = libraryAsset.ResolvedPath;
                    _logger.Verbose($"Discovered runtime dependency for '{runtimeAssemblyPath}'");
                    runtimeDependencies.Add(runtimeAssemblyPath);
                }

                foreach (var runtimeAssemblyGroup in runtimeAssemblyGroups)
                {
                    if (!string.IsNullOrWhiteSpace(runtimeAssemblyGroup.Runtime) && runtimeAssemblyGroup.Runtime == runtimeIdentitfer)
                    {
                        foreach (var runtimeAsset in runtimeAssemblyGroups.GetRuntimeAssets(GetRuntimeIdentitifer()))
                        {
                            var runtimeAssetPath = runtimeAsset.ResolvedPath;
                            _logger.Verbose($"Discovered runtime asset dependency ('{runtimeIdentitfer}') for '{runtimeAssetPath}'");
                            runtimeDependencies.Add(runtimeAssetPath);
                        }
                    }
                }
            }

            foreach (var runtimeDep in runtimeDependencies)
            {
                _logger.Verbose("Adding reference to a runtime dependency => " + runtimeDep);
                opts = opts.AddReferences(MetadataReference.CreateFromFile(runtimeDep));
            }

            var loader             = new InteractiveAssemblyLoader();
            var script             = CSharpScript.Create <TReturn>(context.Code.ToString(), opts, typeof(THost), loader);
            var orderedDiagnostics = script.GetDiagnostics(SuppressedDiagnosticIds);

            if (orderedDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error))
            {
                foreach (var diagnostic in orderedDiagnostics)
                {
                    _logger.Log(diagnostic.ToString());
                }

                throw new CompilationErrorException("Script compilation failed due to one or more errors.",
                                                    orderedDiagnostics.ToImmutableArray());
            }

            return(new ScriptCompilationContext <TReturn>(script, context.Code, loader));
        }
Exemplo n.º 3
0
        public void CreateNewScriptFile(string fileName, string currentDirectory)
        {
            _logger.Log($"Creating '{fileName}'");
            if (!Path.HasExtension(fileName))
            {
                fileName = Path.ChangeExtension(fileName, ".csx");
            }
            var pathToScriptFile = Path.Combine(currentDirectory, fileName);

            if (!File.Exists(pathToScriptFile))
            {
                var scriptFileTemplate = TemplateLoader.ReadTemplate("helloworld.csx.template");
                File.WriteAllText(pathToScriptFile, scriptFileTemplate);
                _logger.Log($"...'{pathToScriptFile}' [Created]");
            }
            else
            {
                _logger.Log($"...'{pathToScriptFile}' already exists [Skipping]");
            }
        }
        public ScriptCompilationContext <TReturn> CreateCompilationContext <TReturn, THost>(ScriptContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var runtimeContext = ProjectContext.CreateContextForEachTarget(context.WorkingDirectory).First();

            _logger.Verbose($"Found runtime context for '{runtimeContext.ProjectFile.ProjectFilePath}'");

            var projectExporter     = runtimeContext.CreateExporter(context.Configuration);
            var runtimeDependencies = new HashSet <string>();
            var projectDependencies = projectExporter.GetDependencies();

            foreach (var projectDependency in projectDependencies)
            {
                var runtimeAssemblies = projectDependency.RuntimeAssemblyGroups;

                foreach (var runtimeAssembly in runtimeAssemblies.GetDefaultAssets())
                {
                    var runtimeAssemblyPath = runtimeAssembly.ResolvedPath;
                    _logger.Verbose($"Discovered runtime dependency for '{runtimeAssemblyPath}'");
                    runtimeDependencies.Add(runtimeAssemblyPath);
                }
            }

            var opts = ScriptOptions.Default.
                       AddImports(DefaultNamespaces).
                       AddReferences(DefaultAssemblies).
                       WithSourceResolver(new RemoteFileResolver(context.WorkingDirectory));

            if (!string.IsNullOrWhiteSpace(context.FilePath))
            {
                opts = opts.WithFilePath(context.FilePath);
            }

            var runtimeId = RuntimeEnvironment.GetRuntimeIdentifier();
            var inheritedAssemblyNames = DependencyContext.Default.GetRuntimeAssemblyNames(runtimeId).Where(x =>
                                                                                                            x.FullName.ToLowerInvariant().StartsWith("system.") ||
                                                                                                            x.FullName.ToLowerInvariant().StartsWith("microsoft.codeanalysis") ||
                                                                                                            x.FullName.ToLowerInvariant().StartsWith("mscorlib"));

            foreach (var inheritedAssemblyName in inheritedAssemblyNames)
            {
                _logger.Verbose("Adding reference to an inherited dependency => " + inheritedAssemblyName.FullName);
                var assembly = Assembly.Load(inheritedAssemblyName);
                opts = opts.AddReferences(assembly);
            }

            foreach (var runtimeDep in runtimeDependencies)
            {
                _logger.Verbose("Adding reference to a runtime dependency => " + runtimeDep);
                opts = opts.AddReferences(MetadataReference.CreateFromFile(runtimeDep));
            }

            var loader      = new InteractiveAssemblyLoader();
            var script      = CSharpScript.Create <TReturn>(context.Code.ToString(), opts, typeof(THost), loader);
            var compilation = script.GetCompilation();
            var diagnostics = compilation.GetDiagnostics();

            if (diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error))
            {
                foreach (var diagnostic in diagnostics)
                {
                    _logger.Log(diagnostic.ToString());
                }

                throw new CompilationErrorException("Script compilation failed due to one or more errors.",
                                                    diagnostics);
            }

            return(new ScriptCompilationContext <TReturn>(script, context.Code, loader));
        }
Exemplo n.º 5
0
        public virtual ScriptCompilationContext <TReturn> CreateCompilationContext <TReturn, THost>(ScriptContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var platformIdentifier = RuntimeHelper.GetPlatformIdentifier();

            _logger.Verbose($"Current runtime is '{platformIdentifier}'.");

            var opts = CreateScriptOptions(context);

            var runtimeId = RuntimeEnvironment.GetRuntimeIdentifier();
            var inheritedAssemblyNames = DependencyContext.Default.GetRuntimeAssemblyNames(runtimeId).Where(x =>
                                                                                                            x.FullName.StartsWith("system.", StringComparison.OrdinalIgnoreCase) ||
                                                                                                            x.FullName.StartsWith("microsoft.codeanalysis", StringComparison.OrdinalIgnoreCase) ||
                                                                                                            x.FullName.StartsWith("mscorlib", StringComparison.OrdinalIgnoreCase));

            foreach (var inheritedAssemblyName in inheritedAssemblyNames)
            {
                _logger.Verbose("Adding reference to an inherited dependency => " + inheritedAssemblyName.FullName);
                var assembly = Assembly.Load(inheritedAssemblyName);
                opts = opts.AddReferences(assembly);
            }

            var pathToProjectJson = Path.Combine(context.WorkingDirectory, Project.FileName);

            IList <RuntimeDependency> runtimeDependencies = new List <RuntimeDependency>();

            if (!File.Exists(pathToProjectJson))
            {
                _logger.Verbose("Unable to find project context for CSX files. Will default to non-context usage.");
                var pathToCsProj       = _scriptProjectProvider.CreateProject(context.WorkingDirectory);
                var dependencyResolver = new DependencyResolver(new CommandRunner(_logger), _logger);
                runtimeDependencies = dependencyResolver.GetRuntimeDependencies(pathToCsProj).ToList();
            }
            else
            {
                _logger.Verbose($"Found runtime context for '{pathToProjectJson}'.");
                var dependencyResolver = new LegacyDependencyResolver(_logger);
                runtimeDependencies = dependencyResolver.GetRuntimeDependencies(pathToProjectJson).ToList();
            }

            AssemblyLoadContext.Default.Resolving +=
                (assemblyLoadContext, assemblyName) => MapUnresolvedAssemblyToRuntimeLibrary(runtimeDependencies.ToList(), assemblyLoadContext, assemblyName);


            foreach (var runtimeDep in runtimeDependencies)
            {
                _logger.Verbose("Adding reference to a runtime dependency => " + runtimeDep);
                opts = opts.AddReferences(MetadataReference.CreateFromFile(runtimeDep.Path));
            }

            var loader             = new InteractiveAssemblyLoader();
            var script             = CSharpScript.Create <TReturn>(context.Code.ToString(), opts, typeof(THost), loader);
            var orderedDiagnostics = script.GetDiagnostics(SuppressedDiagnosticIds);

            if (orderedDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error))
            {
                foreach (var diagnostic in orderedDiagnostics)
                {
                    _logger.Log(diagnostic.ToString());
                }

                throw new CompilationErrorException("Script compilation failed due to one or more errors.",
                                                    orderedDiagnostics.ToImmutableArray());
            }

            return(new ScriptCompilationContext <TReturn>(script, context.Code, loader));
        }
Exemplo n.º 6
0
        public virtual ScriptCompilationContext <TReturn> CreateCompilationContext <TReturn, THost>(ScriptContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var runtimeContext    = ProjectContext.CreateContextForEachTarget(context.WorkingDirectory).First();
            var runtimeIdentitfer = GetRuntimeIdentitifer();

            _logger.Verbose($"Current runtime is '{runtimeIdentitfer}'.");
            _logger.Verbose($"Found runtime context for '{runtimeContext.ProjectFile.ProjectFilePath}'.");

            var projectExporter = runtimeContext.CreateExporter(context.Configuration);

            var runtimeDependencies = new HashSet <string>();
            var projectDependencies = projectExporter.GetDependencies();

            foreach (var projectDependency in projectDependencies)
            {
                var runtimeAssemblyGroups = projectDependency.RuntimeAssemblyGroups;

                foreach (var libraryAsset in runtimeAssemblyGroups.GetDefaultAssets())
                {
                    var runtimeAssemblyPath = libraryAsset.ResolvedPath;
                    _logger.Verbose($"Discovered runtime dependency for '{runtimeAssemblyPath}'");
                    runtimeDependencies.Add(runtimeAssemblyPath);
                }

                foreach (var runtimeAssemblyGroup in runtimeAssemblyGroups)
                {
                    if (!string.IsNullOrWhiteSpace(runtimeAssemblyGroup.Runtime) && runtimeAssemblyGroup.Runtime == runtimeIdentitfer)
                    {
                        foreach (var runtimeAsset in runtimeAssemblyGroups.GetRuntimeAssets(GetRuntimeIdentitifer()))
                        {
                            var runtimeAssetPath = runtimeAsset.ResolvedPath;
                            _logger.Verbose($"Discovered runtime asset dependency ('{runtimeIdentitfer}') for '{runtimeAssetPath}'");
                            runtimeDependencies.Add(runtimeAssetPath);
                        }
                    }
                }
            }

            var opts = CreateScriptOptions(context);

            var runtimeId = RuntimeEnvironment.GetRuntimeIdentifier();
            var inheritedAssemblyNames = DependencyContext.Default.GetRuntimeAssemblyNames(runtimeId).Where(x =>
                                                                                                            x.FullName.StartsWith("system.", StringComparison.OrdinalIgnoreCase) ||
                                                                                                            x.FullName.StartsWith("microsoft.codeanalysis", StringComparison.OrdinalIgnoreCase) ||
                                                                                                            x.FullName.StartsWith("mscorlib", StringComparison.OrdinalIgnoreCase));

            foreach (var inheritedAssemblyName in inheritedAssemblyNames)
            {
                _logger.Verbose("Adding reference to an inherited dependency => " + inheritedAssemblyName.FullName);
                var assembly = Assembly.Load(inheritedAssemblyName);
                opts = opts.AddReferences(assembly);
            }

            foreach (var runtimeDep in runtimeDependencies)
            {
                _logger.Verbose("Adding reference to a runtime dependency => " + runtimeDep);
                opts = opts.AddReferences(MetadataReference.CreateFromFile(runtimeDep));
            }

            var loader      = new InteractiveAssemblyLoader();
            var script      = CSharpScript.Create <TReturn>(context.Code.ToString(), opts, typeof(THost), loader);
            var compilation = script.GetCompilation();

            var diagnostics        = compilation.GetDiagnostics();
            var orderedDiagnostics = diagnostics.OrderBy((d1, d2) =>
            {
                var severityDiff = (int)d2.Severity - (int)d1.Severity;
                return(severityDiff != 0 ? severityDiff : d1.Location.SourceSpan.Start - d2.Location.SourceSpan.Start);
            });

            if (orderedDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error))
            {
                foreach (var diagnostic in orderedDiagnostics)
                {
                    _logger.Log(diagnostic.ToString());
                }

                throw new CompilationErrorException("Script compilation failed due to one or more errors.",
                                                    orderedDiagnostics.ToImmutableArray());
            }

            return(new ScriptCompilationContext <TReturn>(script, context.Code, loader));
        }