Exemplo n.º 1
0
        public IEnumerable <CompilationDependency> GetDependencies(string targetDirectory, IEnumerable <string> scriptFiles, bool enableScriptNugetReferences, string defaultTargetFramework = "net46")
        {
            var projectFileInfo = _scriptProjectProvider.CreateProject(targetDirectory, scriptFiles, defaultTargetFramework, enableScriptNugetReferences);

            _restorer.Restore(projectFileInfo, packageSources: Array.Empty <string>());
            var pathToAssetsFile  = Path.Combine(Path.GetDirectoryName(projectFileInfo.Path), "obj", "project.assets.json");
            var dependencyContext = _scriptDependencyContextReader.ReadDependencyContext(pathToAssetsFile);
            var result            = new List <CompilationDependency>();

            foreach (var scriptDependency in dependencyContext.Dependencies)
            {
                var compilationDependency = new CompilationDependency(scriptDependency.Name, scriptDependency.Version, scriptDependency.CompileTimeDependencyPaths, scriptDependency.ScriptPaths);
                result.Add(compilationDependency);
            }

            // On .Net Core, we need to fetch the compilation references for framework assemblies separately.
            if (defaultTargetFramework.StartsWith("netcoreapp3", StringComparison.InvariantCultureIgnoreCase) ||
                defaultTargetFramework.StartsWith("net5", StringComparison.InvariantCultureIgnoreCase))
            {
                var compilationreferences = _compilationReferenceReader.Read(projectFileInfo);
                result.Add(new CompilationDependency("Dotnet.Script.Default.Dependencies", "99.0", compilationreferences.Select(cr => cr.Path).ToArray(), Array.Empty <string>()));
            }

            return(result);
        }
        public IEnumerable <string> GetDependencies(string targetDirectory, bool enableScriptNugetReferences, string defaultTargetFramework = "net46")
        {
            var pathToProjectFile = _scriptProjectProvider.CreateProject(targetDirectory, defaultTargetFramework,
                                                                         enableScriptNugetReferences);

            if (pathToProjectFile == null)
            {
                return(Array.Empty <string>());
            }

            var dependencyInfo = _scriptDependencyInfoProvider.GetDependencyInfo(pathToProjectFile);

            var dependencyContext = dependencyInfo.DependencyContext;

            var compilationAssemblyResolvers = GetCompilationAssemblyResolvers(dependencyInfo.NugetPackageFolders);

            var resolvedReferencePaths = new HashSet <string>();

            var compileLibraries = dependencyContext.CompileLibraries;

            foreach (var compilationLibrary in compileLibraries)
            {
                _logger.Debug($"Resolving compilation reference paths for {compilationLibrary.Name}");
                var referencePaths = ResolveReferencePaths(compilationLibrary, compilationAssemblyResolvers);
                foreach (var referencePath in referencePaths)
                {
                    resolvedReferencePaths.Add(referencePath);
                }
            }
            return(resolvedReferencePaths);
        }
Exemplo n.º 3
0
        public IEnumerable <RuntimeDependency> GetDependencies(string targetDirectory, ScriptMode scriptMode, string[] packagesSources, string code = null)
        {
            var pathToProjectFile = scriptMode == ScriptMode.Script
                ? _scriptProjectProvider.CreateProject(targetDirectory, _scriptEnvironment.TargetFramework, true)
                : _scriptProjectProvider.CreateProjectForRepl(code, Path.Combine(targetDirectory, scriptMode.ToString()), ScriptEnvironment.Default.TargetFramework);

            return(GetDependenciesInternal(pathToProjectFile, packagesSources));
        }
Exemplo n.º 4
0
        public void DefaultLanguageVersionShouldBeLatest()
        {
            var scriptProjectProvider = new ScriptProjectProvider(new ScriptOptions(), new OmniSharpEnvironment(), new LoggerFactory(), true, false);
            var scriptProjectInfo     = scriptProjectProvider.CreateProject("test.csx", Enumerable.Empty <MetadataReference>(), Path.GetTempPath(), typeof(CommandLineScriptGlobals));

            Assert.Equal(LanguageVersion.Latest, ((CSharpParseOptions)scriptProjectInfo.ParseOptions).SpecifiedLanguageVersion);
            Assert.Equal(LanguageVersion.CSharp9, ((CSharpParseOptions)scriptProjectInfo.ParseOptions).LanguageVersion);
        }
        public IEnumerable <RuntimeDependency> GetDependencies(string targetDirectory, ScriptMode scriptMode, string code = null)
        {
            var pathToProjectFile = scriptMode == ScriptMode.Script
                ? _scriptProjectProvider.CreateProject(targetDirectory, RuntimeHelper.TargetFramework, true)
                : _scriptProjectProvider.CreateProjectForRepl(code, Path.Combine(targetDirectory, scriptMode.ToString()), RuntimeHelper.TargetFramework);

            return(GetDependenciesInternal(pathToProjectFile));
        }
        public void ShouldLogProjectFileContent()
        {
            StringBuilder log      = new StringBuilder();
            var           provider = new ScriptProjectProvider(type => ((level, message) => log.AppendLine(message)));

            provider.CreateProject(TestPathUtils.GetFullPathToTestFixture("HelloWorld"), RuntimeHelper.TargetFramework, true);
            var output = log.ToString();

            Assert.Contains("<Project Sdk=\"Microsoft.NET.Sdk\">", output);
        }
Exemplo n.º 7
0
        public void ShouldCreateNet46Project()
        {
            ScriptProjectProvider p = ScriptProjectProvider.Create(CreateLoggerFactory());
            var pathToScript        = Path.Combine(Path.GetDirectoryName(new Uri(typeof(ScriptParserTests).GetTypeInfo().Assembly.CodeBase)
                                                                         .LocalPath), "sample");
            var result = p.CreateProject(pathToScript);
            var json   = File.ReadAllText(result.PathToProjectJson);

            json.ShouldContain("net46");
        }
Exemplo n.º 8
0
        public IEnumerable <CompilationDependency> GetDependencies(string targetDirectory, IEnumerable <string> scriptFiles, bool enableScriptNugetReferences, string defaultTargetFramework = "net46")
        {
            var pathToProjectFile = scriptFiles == null?
                                    _scriptProjectProvider.CreateProject(targetDirectory, defaultTargetFramework, enableScriptNugetReferences) :
                                        _scriptProjectProvider.CreateProject(targetDirectory, scriptFiles, defaultTargetFramework, enableScriptNugetReferences);

            if (pathToProjectFile == null)
            {
                return(Array.Empty <CompilationDependency>());
            }

            var dependencyInfo               = _scriptDependencyInfoProvider.GetDependencyInfo(pathToProjectFile, Array.Empty <string>());
            var dependencyContext            = dependencyInfo.DependencyContext;
            var compilationAssemblyResolvers = GetCompilationAssemblyResolvers(dependencyInfo.NugetPackageFolders);

            List <CompilationDependency> result = new List <CompilationDependency>();
            var compileLibraries = dependencyContext.CompileLibraries;

            foreach (var compilationLibrary in compileLibraries)
            {
                var resolvedReferencePaths = new HashSet <string>();
                _logger.Trace($"Resolving compilation reference paths for {compilationLibrary.Name}");
                var referencePaths = ResolveReferencePaths(compilationLibrary, compilationAssemblyResolvers);
                var scripts        =
                    _scriptFilesDependencyResolver.GetScriptFileDependencies(compilationLibrary.Path, dependencyInfo.NugetPackageFolders);
                foreach (var referencePath in referencePaths)
                {
                    resolvedReferencePaths.Add(referencePath);
                }
                var compilationDependency = new CompilationDependency(
                    compilationLibrary.Name,
                    compilationLibrary.Version,
                    resolvedReferencePaths.ToList(),
                    scripts);

                result.Add(compilationDependency);
            }
            return(result);
        }
Exemplo n.º 9
0
        public IEnumerable <CompilationDependency> GetDependencies(string targetDirectory, IEnumerable <string> scriptFiles, bool enableScriptNugetReferences, string defaultTargetFramework = "net46")
        {
            var pathToProjectFile = _scriptProjectProvider.CreateProject(targetDirectory, scriptFiles, defaultTargetFramework, enableScriptNugetReferences);

            _restorer.Restore(pathToProjectFile, packageSources: Array.Empty <string>());
            var pathToAssetsFile  = Path.Combine(Path.GetDirectoryName(pathToProjectFile), "obj", "project.assets.json");
            var dependencyContext = _scriptDependencyContextReader.ReadDependencyContext(pathToAssetsFile);
            var result            = new List <CompilationDependency>();

            foreach (var scriptDependency in dependencyContext.Dependencies)
            {
                var compilationDependency = new CompilationDependency(scriptDependency.Name, scriptDependency.Version, scriptDependency.CompileTimeDependencyPaths, scriptDependency.ScriptPaths);
                result.Add(compilationDependency);
            }
            return(result);
        }
Exemplo n.º 10
0
        public static void AddCsxProjectToWorkspace(OmniSharpWorkspace workspace, TestFile testFile)
        {
            var references   = GetReferences();
            var scriptHelper = new ScriptProjectProvider(new ScriptOptions(), new OmniSharpEnvironment(), new LoggerFactory(), true);
            var project      = scriptHelper.CreateProject(testFile.FileName, references.Union(new[] { MetadataReference.CreateFromFile(typeof(CommandLineScriptGlobals).GetTypeInfo().Assembly.Location) }), testFile.FileName, typeof(CommandLineScriptGlobals), Enumerable.Empty <string>());

            workspace.AddProject(project);

            var documentInfo = DocumentInfo.Create(
                id: DocumentId.CreateNewId(project.Id),
                name: testFile.FileName,
                sourceCodeKind: SourceCodeKind.Script,
                loader: TextLoader.From(TextAndVersion.Create(testFile.Content.Text, VersionStamp.Create())),
                filePath: testFile.FileName);

            workspace.AddDocument(documentInfo);
        }
        public IEnumerable <RuntimeDependency> GetDependencies(string targetDirectory)
        {
            var pathToProjectFile = _scriptProjectProvider.CreateProject(targetDirectory, "netcoreapp2.0", true);

            return(GetDependenciesInternal(pathToProjectFile));
        }
Exemplo n.º 12
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));
        }