Exemple #1
0
        public void AddDependencyLocationThrowsOnNull()
        {
            var loader = new DefaultAnalyzerAssemblyLoader();

            Assert.Throws <ArgumentNullException>("fullPath", () => loader.AddDependencyLocation(null));
            Assert.Throws <ArgumentException>("fullPath", () => loader.AddDependencyLocation("a"));
        }
Exemple #2
0
        public void ThrowsForMissingFile()
        {
            var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".dll");

            var loader = new DefaultAnalyzerAssemblyLoader();

            Assert.ThrowsAny <Exception>(() => loader.LoadFromPath(path));
        }
Exemple #3
0
        public void BasicLoad()
        {
            var directory = Temp.CreateDirectory();

            var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha);

            var loader = new DefaultAnalyzerAssemblyLoader();

            Assembly alpha = loader.LoadFromPath(alphaDll.Path);

            Assert.NotNull(alpha);
        }
        public void AssemblyLoading()
        {
            StringBuilder sb        = new StringBuilder();
            var           directory = Temp.CreateDirectory();

            var alphaDll = Temp.CreateDirectory()
                           .CreateFile("Alpha.dll")
                           .WriteAllBytes(TestResources.AssemblyLoadTests.Alpha);
            var betaDll = Temp.CreateDirectory()
                          .CreateFile("Beta.dll")
                          .WriteAllBytes(TestResources.AssemblyLoadTests.Beta);
            var gammaDll = Temp.CreateDirectory()
                           .CreateFile("Gamma.dll")
                           .WriteAllBytes(TestResources.AssemblyLoadTests.Gamma);
            var deltaDll = Temp.CreateDirectory()
                           .CreateFile("Delta.dll")
                           .WriteAllBytes(TestResources.AssemblyLoadTests.Delta);

            var loader = new DefaultAnalyzerAssemblyLoader();

            loader.AddDependencyLocation(alphaDll.Path);
            loader.AddDependencyLocation(betaDll.Path);
            loader.AddDependencyLocation(gammaDll.Path);
            loader.AddDependencyLocation(deltaDll.Path);

            Assembly alpha = loader.LoadFromPath(alphaDll.Path);

            var a = alpha.CreateInstance("Alpha.A");

            a.GetType().GetMethod("Write").Invoke(a, new object[] { sb, "Test A" });

            Assembly beta = loader.LoadFromPath(betaDll.Path);

            var b = beta.CreateInstance("Beta.B");

            b.GetType().GetMethod("Write").Invoke(b, new object[] { sb, "Test B" });

            var expected =
                @"Delta: Gamma: Alpha: Test A
Delta: Gamma: Beta: Test B
";

            var actual = sb.ToString();

            Assert.Equal(expected, actual);
        }
        public static IServiceProvider Create(
            ITestOutputHelper testOutput,
            IOmniSharpEnvironment environment,
            IConfiguration configurationData  = null,
            DotNetCliVersion dotNetCliVersion = DotNetCliVersion.Current,
            IEventEmitter eventEmitter        = null)
        {
            var loggerFactory = new LoggerFactory()
                                .AddXunit(testOutput);

            eventEmitter = eventEmitter ?? NullEventEmitter.Instance;

            var assemblyLoader         = CreateAssemblyLoader(loggerFactory);
            var dotNetCliService       = CreateDotNetCliService(dotNetCliVersion, loggerFactory, environment, eventEmitter);
            var configuration          = CreateConfiguration(configurationData);
            var msbuildLocator         = CreateMSBuildLocator(loggerFactory, assemblyLoader);
            var sharedTextWriter       = CreateSharedTextWriter(testOutput);
            var analyzerAssemblyLoader = new DefaultAnalyzerAssemblyLoader();

            return(new TestServiceProvider(
                       environment, loggerFactory, assemblyLoader, analyzerAssemblyLoader, sharedTextWriter,
                       msbuildLocator, eventEmitter, dotNetCliService, configuration));
        }
Exemple #6
0
        public static async Task <CompilerInvocation> CreateFromJsonAsync(string jsonContents)
        {
            var invocationInfo = JsonConvert.DeserializeObject <CompilerInvocationInfo>(jsonContents);

            // We will use a Workspace to simplify the creation of the compilation, but will be careful not to return the Workspace instance from this class.
            // We will still provide the language services which are used by the generator itself, but we don't tie it to a Workspace object so we can
            // run this as an in-proc source generator if one day desired.
            var workspace = new AdhocWorkspace();

            var languageName     = GetLanguageName(invocationInfo);
            var languageServices = workspace.Services.GetLanguageServices(languageName);

            var mapPath = GetPathMapper(invocationInfo);

            var splitCommandLine = CommandLineParser.SplitCommandLineIntoArguments(invocationInfo.Arguments, removeHashComments: false).ToList();

            // Unfortunately for us there are a few paths that get directly read by the command line parse which we need to remap,
            // such as /ruleset files. So let's go through and process them now.
            for (var i = 0; i < splitCommandLine.Count; i++)
            {
                const string RuleSetSwitch = "/ruleset:";

                if (splitCommandLine[i].StartsWith(RuleSetSwitch, StringComparison.Ordinal))
                {
                    var rulesetPath = splitCommandLine[i].Substring(RuleSetSwitch.Length);

                    var quoted = rulesetPath.Length > 2 &&
                                 rulesetPath.StartsWith("\"", StringComparison.Ordinal) &&
                                 rulesetPath.EndsWith("\"", StringComparison.Ordinal);

                    if (quoted)
                    {
                        rulesetPath = rulesetPath.Substring(1, rulesetPath.Length - 2);
                    }

                    rulesetPath = mapPath(rulesetPath);

                    if (quoted)
                    {
                        rulesetPath = "\"" + rulesetPath + "\"";
                    }

                    splitCommandLine[i] = RuleSetSwitch + rulesetPath;
                }
            }

            var commandLineParserService = languageServices.GetRequiredService <ICommandLineParserService>();
            var parsedCommandLine        = commandLineParserService.Parse(splitCommandLine, Path.GetDirectoryName(invocationInfo.ProjectFilePath), isInteractive: false, sdkDirectory: null);

            var analyzerLoader = new DefaultAnalyzerAssemblyLoader();

            var projectId = ProjectId.CreateNewId(invocationInfo.ProjectFilePath);

            var projectInfo = ProjectInfo.Create(
                projectId,
                VersionStamp.Default,
                name: Path.GetFileNameWithoutExtension(invocationInfo.ProjectFilePath),
                assemblyName: parsedCommandLine.CompilationName !,
                language: languageName,
                filePath: invocationInfo.ProjectFilePath,
                outputFilePath: parsedCommandLine.OutputFileName,
                parsedCommandLine.CompilationOptions,
                parsedCommandLine.ParseOptions,
                parsedCommandLine.SourceFiles.Select(s => CreateDocumentInfo(unmappedPath: s.Path)),
                metadataReferences: parsedCommandLine.MetadataReferences.Select(r => MetadataReference.CreateFromFile(mapPath(r.Reference), r.Properties)),
                additionalDocuments: parsedCommandLine.AdditionalFiles.Select(f => CreateDocumentInfo(unmappedPath: f.Path)),
                analyzerReferences: parsedCommandLine.AnalyzerReferences.Select(r => new AnalyzerFileReference(r.FilePath, analyzerLoader)))
                              .WithAnalyzerConfigDocuments(parsedCommandLine.AnalyzerConfigPaths.Select(CreateDocumentInfo));

            workspace.AddProject(projectInfo);

            var compilation = await workspace.CurrentSolution.GetProject(projectId) !.GetRequiredCompilationAsync(CancellationToken.None);

            return(new CompilerInvocation(compilation, languageServices, invocationInfo.ProjectFilePath, workspace.CurrentSolution.Options));

            // Local methods:
            DocumentInfo CreateDocumentInfo(string unmappedPath)
            {
                var mappedPath = mapPath(unmappedPath);

                return(DocumentInfo.Create(
                           DocumentId.CreateNewId(projectId, mappedPath),
                           name: mappedPath,
                           filePath: mappedPath,
                           loader: new FileTextLoader(mappedPath, parsedCommandLine.Encoding)));
            }
        }