Beispiel #1
0
        static AsyncCodeConfiguration Configure()
        {
            var xmlConfig = new FileInfo("AsyncGenerator.xml");

            if (xmlConfig.Exists)
            {
                using (var stream = xmlConfig.OpenRead())
                {
                    return(AsyncCodeConfiguration.Create()
                           .LoggerFactory(new Log4NetLoggerFactory())
                           .ConfigureFromStream <XmlFileConfigurator>(stream, Environment.CurrentDirectory));
                }
            }
            var ymlConfig = new FileInfo("AsyncGenerator.yml");

            if (ymlConfig.Exists)
            {
                using (var stream = ymlConfig.OpenRead())
                {
                    return(AsyncCodeConfiguration.Create()
                           .LoggerFactory(new Log4NetLoggerFactory())
                           .ConfigureFromStream <YamlFileConfigurator>(stream, Environment.CurrentDirectory));
                }
            }

            return(null);
        }
Beispiel #2
0
        public async Task TestNullableRestoreDirective()
        {
            var ignore = false;
            var config = AsyncCodeConfiguration.Create()
                         .ConfigureProject(GetTestProjectPath("NullableRestore"), p => p
                                           .ConfigureAnalyzation(a => a
                                                                 .MethodConversion(s => MethodConversion.Smart)
                                                                 .CancellationTokens(true))
                                           .ConfigureTransformation(t => t
                                                                    .AfterTransformation(result =>
            {
                if (((CSharpCompilationOptions)result.Project.CompilationOptions).NullableContextOptions == NullableContextOptions.Disable)
                {
                    ignore = true;
                    return;
                }

                AssertValidAnnotations(result);
                Assert.AreEqual(1, result.Documents.Count);
                var document = result.Documents[0];
                Assert.NotNull(document.OriginalModified);
                Assert.AreEqual(GetOutputFile("NullableRestore"), document.Transformed.ToFullString());
            }))
                                           .ApplyChanges(false));

            await AsyncCodeGenerator.GenerateAsync(config);

            if (ignore)
            {
                Assert.Ignore("Nullable is not enabled.");
            }
        }
        public async Task GenerateAsync(AsyncCodeConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }
            foreach (var config in configuration.SolutionConfigurations)
            {
                var solutionData = await CreateSolutionData(config).ConfigureAwait(false);

                foreach (var projectData in solutionData.ProjectData.Values)
                {
                    // Initialize plugins
                    foreach (var registeredPlugin in projectData.Configuration.RegisteredPlugins)
                    {
                        await registeredPlugin.Initialize(projectData.Project).ConfigureAwait(false);
                    }
                    // Analyze project
                    var analyzeConfig     = projectData.Configuration.AnalyzeConfiguration;
                    var analyzationResult = await AnalyzeProject(projectData).ConfigureAwait(false);

                    foreach (var action in analyzeConfig.Callbacks.AfterAnalyzation)
                    {
                        action(analyzationResult);
                    }

                    // Transform documents
                    var transformConfig = projectData.Configuration.TransformConfiguration;
                    //TransformProject(analyzationResult, transformConfig);
                }
            }

            //conf.SolutionConfigurations.First().ProjectConfigurations.First().TransformConfiguration.
        }
        public Task TestProject()
        {
            var config = AsyncCodeConfiguration.Create()
                         .ConfigureProject(GetTestProjectPath("MultiTargetFrameworks"), p => p
                                           .TargetFramework("net461")
                                           .ApplyChanges(false)
                                           .RegisterPlugin <NUnitAsyncCounterpartsFinder>());

            return(AsyncCodeGenerator.GenerateAsync(config));
        }
Beispiel #5
0
        public Task TestYamlAfterTransformation()
        {
            var configPath = Path.GetFullPath(Path.Combine(GetExternalProjectDirectory("NHibernate"), "src", "AsyncGenerator.yml"));

            var config = AsyncCodeConfiguration.Create()
                         .LoggerFactory(new Log4NetLoggerFactory())
                         .ConfigureFromFile <YamlFileConfigurator>(configPath);

            return(AsyncCodeGenerator.GenerateAsync(config));
        }
Beispiel #6
0
        public Task TestSolution()
        {
            var config = AsyncCodeConfiguration.Create()
                         .ConfigureSolution(GetTestSolutionPath("MultiTargetFrameworks"), s => s
                                            .TargetFramework("net461")
                                            .ApplyChanges(false)
                                            .ConfigureProject("MultiTargetFrameworks", p => p
                                                              .RegisterPlugin(new NUnitPlugin(false))));

            return(AsyncCodeGenerator.GenerateAsync(config));
        }
Beispiel #7
0
        public Task TestYamlProjectConfigurationAfterTransformation()
        {
            var asm      = Assembly.GetExecutingAssembly();
            var resource = $"{GetType().Namespace}.ProjectConfiguration.yml";
            var stream   = asm.GetManifestResourceStream(resource);
            var config   = AsyncCodeConfiguration.Create()
                           .LoggerFactory(new Log4NetLoggerFactory())
                           .ConfigureFromStream <YamlFileConfigurator>(stream);

            return(AsyncCodeGenerator.GenerateAsync(config));
        }
Beispiel #8
0
        public virtual AsyncCodeConfiguration Configure(Action <IFluentProjectConfiguration> action = null)
        {
            var filePath = Path.GetFullPath(Path.Combine(GetBaseDirectory(), "..", "..", "..", "AsyncGenerator.Tests.csproj"));

            return(AsyncCodeConfiguration.Create()
                   .ConfigureProject(filePath, p =>
            {
                p.ConfigureAnalyzation(a => a
                                       .DocumentSelection(o => string.Join("/", o.Folders) == InputFolderPath)
                                       );
                action?.Invoke(p);
            })
                   );
        }
Beispiel #9
0
        public AsyncCodeConfiguration Configure(string fileName, Action <IFluentProjectConfiguration> action = null)
        {
            var slnFilePath = Path.GetFullPath(Path.Combine(GetBaseDirectory(), "..", "..", "..", "..", "AsyncGenerator.sln"));

            return(AsyncCodeConfiguration.Create()
                   .ConfigureSolution(slnFilePath, c => c
                                      .ConfigureProject("AsyncGenerator.Tests", p =>
            {
                p.ConfigureAnalyzation(a => a
                                       .DocumentSelection(o => string.Join("/", o.Folders) == InputFolderPath && o.Name == fileName + ".cs")
                                       );
                action?.Invoke(p);
            })

                                      ));
        }
Beispiel #10
0
        public AsyncCodeConfiguration Configure(Action <IProjectConfiguration> action = null)
        {
            var slnFilePath = Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory + @"..\..\..\..\AsyncGenerator.sln");

            return(AsyncCodeConfiguration.Create()
                   .ConfigureSolution(slnFilePath, c => c
                                      .ConfigureProject("AsyncGenerator.Tests", p =>
            {
                p.ConfigureAnalyzation(a => a
                                       .DocumentSelection(o => string.Join("/", o.Folders) == FolderPath && o.Name == FileName + ".cs")
                                       //.ScanMethodBody(true)
                                       );
                action?.Invoke(p);
            })

                                      ));
        }
Beispiel #11
0
        public async Task TestCS0103LocalizationAfterTransformation(string culture)
        {
            var origUiCluture = CultureInfo.CurrentUICulture;

            try
            {
                var cultureInfo = CultureInfo.GetCultureInfo(culture);
                CultureInfo.CurrentUICulture = cultureInfo;
                CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;

                await AsyncCodeGenerator.GenerateAsync(AsyncCodeConfiguration.Create()
                                                       .ConfigureProject(GetTestProjectPath("Localization"), o => o
                                                                         .ConfigureAnalyzation(a => a
                                                                                               .CancellationTokens(true)
                                                                                               .DocumentSelection(d => d.Name == "PrivateMethods.cs")
                                                                                               .MethodConversion(symbol => symbol.Name == "List" ? MethodConversion.Smart : MethodConversion.Unknown)
                                                                                               )
                                                                         .ConfigureParsing(p => p
                                                                                           .AddPreprocessorSymbolName("TEST")
                                                                                           )
                                                                         .ConfigureTransformation(t => t
                                                                                                  .AfterTransformation(result =>
                {
                    AssertValidAnnotations(result);
                    Assert.AreEqual(1, result.Documents.Count);
                    var document = result.Documents[0];
                    Assert.NotNull(document.OriginalModified);
                    Assert.AreEqual(GetOutputFile("PrivateMethods"), document.Transformed.ToFullString());
                })
                                                                                                  )
                                                                         .ApplyChanges(false)));
            }
            finally
            {
                CultureInfo.CurrentUICulture = origUiCluture;
                CultureInfo.DefaultThreadCurrentUICulture = origUiCluture;
            }
        }
Beispiel #12
0
 public AsyncCodeConfiguration ConfigureByXml(string xmlConfig, string fileName = null, Action <IFluentProjectConfiguration> action = null)
 {
     return(AsyncCodeConfiguration.Create()
            .ConfigureFromStream(GenerateStreamFromString(xmlConfig), new TestProjectXmlFileConfigurator(InputFolderPath, fileName, action)));
 }
        public static async Task GenerateAsync(AsyncCodeConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }
            if (cancellationToken.IsCancellationRequested)
            {
                cancellationToken.ThrowIfCancellationRequested();
            }
            var logger = configuration.LoggerFactoryInstance.GetLogger(nameof(AsyncCodeGenerator));

            logger.Info("Generating async code started");

            foreach (var config in configuration.SolutionConfigurations)
            {
                var workspace = CreateWorkspace(config.TargetFramework);
                logger.Info($"Opening solution '{config.Path}' started");
                var solution = await OpenSolution(workspace, config.Path,
                                                  config.SuppressDiagnosticFailuresPrediactes, logger, cancellationToken).ConfigureAwait(false);

                logger.Info($"Opening solution '{config.Path}' completed");

                logger.Info("Configuring solution prior analyzation started");
                var solutionData = CreateSolutionData(solution, config);
                logger.Info("Configuring solution prior analyzation completed");

                foreach (var projectData in solutionData.GetProjects())
                {
                    await GenerateProject(projectData, configuration.LoggerFactoryInstance, logger, cancellationToken).ConfigureAwait(false);
                }
                if (config.ApplyChanges)
                {
                    await ApplyChanges(workspace, solutionData.Solution, logger, cancellationToken).ConfigureAwait(false);
                }
                workspace.Dispose();
            }

            foreach (var config in configuration.ProjectConfigurations)
            {
                var workspace = CreateWorkspace(config.TargetFramework);
                logger.Info($"Opening project '{config.Path}' started");
                var project = await OpenProject(workspace, config.Path,
                                                config.SuppressDiagnosticFailuresPrediactes, logger, cancellationToken).ConfigureAwait(false);

                logger.Info($"Opening project '{config.Path}' completed");

                logger.Info("Configuring project prior analyzation started");
                var projectData = CreateProjectData(project, config);
                logger.Info("Configuring project prior analyzation completed");

                await GenerateProject(projectData, configuration.LoggerFactoryInstance, logger, cancellationToken).ConfigureAwait(false);

                if (config.ApplyChanges)
                {
                    await ApplyChanges(workspace, projectData.Project.Solution, logger, cancellationToken).ConfigureAwait(false);
                }
                workspace.Dispose();
            }

            logger.Info("Generating async code completed");
        }
Beispiel #14
0
        public Task TestAfterTransformation()
        {
            var slnFilePath = Path.GetFullPath(Path.Combine(GetExternalProjectDirectory("NHibernate"), "src", "NHibernate.sln"));

            var config = AsyncCodeConfiguration.Create()
                         .LoggerFactory(new Log4NetLoggerFactory())
                         .ConfigureSolution(slnFilePath, s => s
                                            .ConcurrentRun()
                                            .SuppressDiagnosticFailures("NHibernate.Test.VisualBasic.vbproj")
                                            .ConfigureProject("NHibernate", p => p
                                                              .ConfigureAnalyzation(a => a
                                                                                    .MethodConversion(GetMethodConversion)
                                                                                    .SearchForAsyncCounterparts(symbol =>
            {
                switch (symbol.Name)
                {
                case "GetFieldValue":
                case "IsDBNull":
                case "WriteLine":
                    return(false);
                }
                return(true);
            })
                                                                                    .CallForwarding(true)
                                                                                    .CancellationTokens(t => t
                                                                                                        .Guards(true)
                                                                                                        .ParameterGeneration(symbolInfo =>
            {
                if (IsPubliclyExposedType(symbolInfo.Symbol.ContainingType) ||                                                         // For public types generate default parameter
                    symbolInfo.ImplementedInterfaces.Any(o => IsPubliclyExposedType(o.ContainingType)))                                // The rule for public types shall be passed to implementors
                {
                    return(MethodCancellationToken.Optional);
                }
                return(MethodCancellationToken.Required);
            })
                                                                                                        .RequiresCancellationToken(symbol =>
            {
                if (IsEventListener(symbol.ContainingType))
                {
                    return(true);
                }
                return(null);                                                        // Leave the decision to the generator
            })
                                                                                                        )
                                                                                    .ScanMethodBody(true)
                                                                                    )
                                                              .ConfigureTransformation(t => t
                                                                                       .AsyncLock("NHibernate.Util.AsyncLock", "LockAsync")
                                                                                       .LocalFunctions(true)
                                                                                       .ConfigureAwaitArgument(false)
                                                                                       .DocumentationComments(d => d
                                                                                                              .AddOrReplaceMethodSummary(GetMethodSummary)
                                                                                                              )
                                                                                       )
                                                              .RegisterPlugin <EmptyRegionRemover>()
                                                              .RegisterPlugin <TransactionScopeAsyncFlowAdder>() // Rewrite TransactionScope in AdoNetWithDistributedTransactionFactory
                                                              )
                                            .ConfigureProject("NHibernate.DomainModel", p => p
                                                              .ConfigureAnalyzation(a => a
                                                                                    .ScanForMissingAsyncMembers(true)
                                                                                    .ScanMethodBody(true)
                                                                                    )
                                                              )
                                            .ConfigureProject("NHibernate.Test", p => p
                                                              .ConfigureAnalyzation(a => a
                                                                                    .MethodConversion(symbol =>
            {
                if (symbol.GetAttributes().Any(o => o.AttributeClass.Name == "IgnoreAttribute"))
                {
                    return(MethodConversion.Ignore);
                }
                if (symbol.GetAttributes().Any(o => o.AttributeClass.Name == "TestAttribute"))
                {
                    return(MethodConversion.Smart);
                }
                return(MethodConversion.Unknown);
            })
                                                                                    .AsyncExtensionMethods(e => e
                                                                                                           .ProjectFile("NHibernate", "LinqExtensionMethods.cs")
                                                                                                           )
                                                                                    .PreserveReturnType(symbol => symbol.GetAttributes().Any(o => o.AttributeClass.Name == "TestAttribute"))
                                                                                    .ScanForMissingAsyncMembers(o => o.AllInterfaces.Any(i => i.ContainingAssembly.Name == "NHibernate"))
                                                                                    .CancellationTokens(t => t
                                                                                                        .RequiresCancellationToken(symbol => symbol.GetAttributes().Any(o => o.AttributeClass.Name == "TestAttribute") ? (bool?)false : null))
                                                                                    .ScanMethodBody(true)
                                                                                    .DocumentSelection(doc =>
            {
                return
                // AsQueryable method is called on a retrieved list from db and the result is used elsewhere in code
                (!doc.FilePath.EndsWith(@"Linq\MathTests.cs")
                 // It looks like that GC.Collect works differently with async.
                 // if "await Task.Yield();" is added after DoLinqInSeparateSessionAsync then the test runs successfully (TODO: discover why)
                 && !doc.FilePath.EndsWith(@"Linq\ExpressionSessionLeakTest.cs")
                );
            })
                                                                                    .TypeConversion(type =>
            {
                if (type.Name == "NorthwindDbCreator" ||                                                        // Ignored for performance reasons
                    type.Name == "ObjectAssert" ||                                                              // Has a TestFixture attribute but is not a test
                    type.Name == "LinqReadonlyTestsContext")                                                    // SetUpFixture
                {
                    return(TypeConversion.Ignore);
                }
                if (type.GetAttributes().Any(o => o.AttributeClass.Name == "IgnoreAttribute"))
                {
                    return(TypeConversion.Ignore);
                }
                if (type.GetAttributes().Any(o => o.AttributeClass.Name == "TestFixtureAttribute"))
                {
                    return(TypeConversion.NewType);
                }
                var currentType = type;
                while (currentType != null)
                {
                    if (currentType.Name == "TestCase")
                    {
                        return(TypeConversion.Ignore);
                    }
                    currentType = currentType.BaseType;
                }
                return(TypeConversion.Unknown);
            })
                                                                                    )
                                                              .RegisterPlugin <TransactionScopeAsyncFlowAdder>()
                                                              .RegisterPlugin(new NUnitPlugin(false))
                                                              )
                                            .ApplyChanges(true)
                                            );

            return(AsyncCodeGenerator.GenerateAsync(config));
        }