コード例 #1
0
        private void CompileIntoAssembly(string sourceCode, string assemblyName)
        {
            var compilation       = CompilationHelper.CreateCompilation(sourceCode, assemblyName);
            var assemblyFileName  = Path.GetTempFileName();
            var result            = compilation.Emit(assemblyFileName);
            var compilationReport = String.Join(Environment.NewLine, result.Diagnostics.Where(l => l.Severity != DiagnosticSeverity.Hidden).Select(l => $"[{l.Severity}] {l}"));

            if (!String.IsNullOrEmpty(compilationReport))
            {
                _outputHelper.WriteLine(compilationReport);
            }

            var errorReport = String.Join(Environment.NewLine, result.Diagnostics.Where(l => l.Severity == DiagnosticSeverity.Error).Select(l => $"[{l.Severity}] {l}"));

            errorReport.ShouldBeNullOrEmpty();

            Assembly.LoadFrom(assemblyFileName);
        }
        private SourceText GenerateSource(AdditionalText additionalFile, string scalarFieldTypeMappingProviderTypeName)
        {
            var sourceGenerator = new GraphQlClientSourceGenerator();

            sourceGenerator.Initialize(new GeneratorInitializationContext());

            var configurationOptions =
                new Dictionary <string, string>
            {
                { "build_property.GraphQlClientGenerator_ClassPrefix", "SourceGenerated" },
                { "build_property.GraphQlClientGenerator_ClassSuffix", "V2" },
                { "build_property.GraphQlClientGenerator_IncludeDeprecatedFields", "true" },
                { "build_property.GraphQlClientGenerator_CommentGeneration", "CodeSummary" },
                { "build_property.GraphQlClientGenerator_FloatTypeMapping", "Double" },
                { "build_property.GraphQlClientGenerator_BooleanTypeMapping", "Boolean" },
                { "build_property.GraphQlClientGenerator_IdTypeMapping", "String" },
                { "build_property.GraphQlClientGenerator_JsonPropertyGeneration", "Always" },
                { "build_property.GraphQlClientGenerator_CustomClassMapping", "Query:Tibber|RootMutation:TibberMutation Consumption:ConsumptionEntry;Production:ProductionEntry" },
                { "build_property.GraphQlClientGenerator_Headers", "Authorization:Basic XXX|X-REQUEST-ID:123456789" }
            };

            if (scalarFieldTypeMappingProviderTypeName != null)
            {
                configurationOptions.Add("build_property.GraphQlClientGenerator_ScalarFieldTypeMappingProvider", scalarFieldTypeMappingProviderTypeName);
            }

            var compilerAnalyzerConfigOptionsProvider = new CompilerAnalyzerConfigOptionsProvider(new CompilerAnalyzerConfigOptions(configurationOptions));

            var compilation = CompilationHelper.CreateCompilation(null, "SourceGeneratorTestAssembly");

            var generatorExecutionContextType = typeof(GeneratorExecutionContext);
            var constructorInfo = generatorExecutionContextType.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0];
            var additionalFiles = new List <AdditionalText> {
                _fileGraphQlSchema
            };

            if (additionalFile != null)
            {
                additionalFiles.Add(additionalFile);
            }

            var additionalSourcesCollectionType = Type.GetType("Microsoft.CodeAnalysis.AdditionalSourcesCollection, Microsoft.CodeAnalysis");
            var additionalSourcesCollection     = additionalSourcesCollectionType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(string) }, null).Invoke(new object[] { ".cs" });

            var executionContext =
                (GeneratorExecutionContext)constructorInfo.Invoke(
                    new[]
            {
                compilation,
                new CSharpParseOptions(LanguageVersion.CSharp9),
                additionalFiles.ToImmutableArray(),
                compilerAnalyzerConfigOptionsProvider,
                null,
                additionalSourcesCollection,
                CancellationToken.None
            });

            var additionalSourceFiles = generatorExecutionContextType.GetField("_additionalSources", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(executionContext);

            sourceGenerator.Execute(executionContext);

            var sourcesAdded = ((IEnumerable)additionalSourceFiles.GetType().GetField("_sourcesAdded", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(additionalSourceFiles)).GetEnumerator();

            sourcesAdded.MoveNext().ShouldBeTrue();
            var sourceText = (SourceText)sourcesAdded.Current.GetType().GetProperty("Text").GetValue(sourcesAdded.Current);

            sourcesAdded.MoveNext().ShouldBeFalse();
            return(sourceText);
        }