示例#1
0
        public async Task <Dictionary <string, ProjectAnalysisResult> > AnalyzeSolution(
            string solutionFilename, List <string> projects, string targetFramework = "netcoreapp3.1")
        {
            try
            {
                var configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
                {
                    MetaDataSettings =
                    {
                        LiteralExpressions    = true,
                        MethodInvocations     = true,
                        ReferenceData         = true,
                        Annotations           = true,
                        DeclarationNodes      = true,
                        LoadBuildData         = true,
                        LocationData          = true,
                        InterfaceDeclarations = true
                    }
                };
                var analyzer      = CodeAnalyzerFactory.GetAnalyzer(configuration, _logger);
                var analyzersTask = await analyzer.AnalyzeSolution(solutionFilename);

                var analysisActions = AnalyzeActions(projects, targetFramework, analyzersTask, solutionFilename);

                return(projects
                       .Select((project) => new KeyValuePair <string, ProjectAnalysisResult>(project, AnalyzeProject(project, analyzersTask, analysisActions, targetFramework)))
                       .Where(p => p.Value != null)
                       .ToDictionary(p => p.Key, p => p.Value));
            }
            finally
            {
                CommonUtils.RunGarbageCollection(_logger, "PortingAssistantAnalysisHandler.AnalyzeSolution");
            }
        }
示例#2
0
        /// <summary>
        /// Initializes a new instance of SolutionRewriter, analyzing the solution path using the provided config.
        /// WARNING: This constructor will rebuild and reanalyze the solution, which will have a performance impact. If you
        /// have an already analyzed solution, use another constructor
        /// </summary>
        /// <param name="analyzerConfiguration">Configuration for code analyzer to be used (AnalyzerConfiguration)</param>
        /// <param name="solutionFilePath">Path to solution file</param>
        /// <param name="solutionConfiguration">Configuration for each project in solution to be built</param>
        public SolutionRewriter(string solutionFilePath, List <ProjectConfiguration> solutionConfiguration, IProjectRewriterFactory projectRewriterFactory = null)
        {
            DownloadResourceFiles();
            _solutionResult         = new SolutionResult();
            _projectRewriterFactory = projectRewriterFactory ?? new DefaultProjectRewriterFactory();
            AnalyzerConfiguration analyzerConfiguration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                MetaDataSettings = new MetaDataSettings()
                {
                    Annotations           = true,
                    DeclarationNodes      = true,
                    MethodInvocations     = true,
                    ReferenceData         = true,
                    LoadBuildData         = true,
                    InterfaceDeclarations = true,
                    MemberAccess          = true,
                    ElementAccess         = true
                }
            };

            _projectRewriters = new List <ProjectRewriter>();
            CodeAnalyzer analyzer        = CodeAnalyzerFactory.GetAnalyzer(analyzerConfiguration, LogHelper.Logger);
            var          analyzerResults = analyzer.AnalyzeSolution(solutionFilePath).Result;

            InitializeProjectRewriters(analyzerResults, solutionConfiguration);
        }
示例#3
0
        private async Task <IDEProjectResult> AnalyzeProjectFiles(string projectPath, string fileContent, string filePath, List <string> preportReferences, List <string> currentReferences)
        {
            try
            {
                var configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
                {
                    MetaDataSettings =
                    {
                        LiteralExpressions    = true,
                        MethodInvocations     = true,
                        ReferenceData         = true,
                        Annotations           = true,
                        DeclarationNodes      = true,
                        LoadBuildData         = true,
                        LocationData          = true,
                        InterfaceDeclarations = true
                    }
                };
                var analyzer         = CodeAnalyzerFactory.GetAnalyzer(configuration, _logger);
                var ideProjectResult = await analyzer.AnalyzeFile(projectPath, filePath, fileContent, preportReferences, currentReferences);

                return(ideProjectResult);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error while analyzing files");
            }
            finally
            {
                CommonUtils.RunGarbageCollection(_logger, "PortingAssistantAnalysisHandler.AnalyzeFileIncremental");
            }
            return(null);
        }
示例#4
0
        private CodeAnalyzer CreateDefaultCodeAnalyzer()
        {
            // Create a basic logger
            var loggerFactory = LoggerFactory.Create(builder => builder.SetMinimumLevel(LogLevel.Debug).AddConsole());
            var logger        = loggerFactory.CreateLogger("");

            // Set up analyzer config
            var configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                ExportSettings   = { GenerateJsonOutput = false },
                MetaDataSettings =
                {
                    ReferenceData         = true,
                    LoadBuildData         = true,
                    GenerateBinFiles      = true,
                    LocationData          = false,
                    MethodInvocations     = false,
                    LiteralExpressions    = false,
                    LambdaMethods         = false,
                    DeclarationNodes      = false,
                    Annotations           = false,
                    InterfaceDeclarations = false,
                    EnumDeclarations      = false,
                    StructDeclarations    = false,
                    ReturnStatements      = false,
                    InvocationArguments   = false,
                    ElementAccess         = false,
                    MemberAccess          = false
                }
            };

            return(CodeAnalyzerFactory.GetAnalyzer(configuration, logger));
        }
示例#5
0
        /// <summary>
        /// Initializes a new instance of Solution Port, analyzing the solution path using the provided config.
        /// WARNING: This constructor will rebuild and reanalyze the solution, which will have a performance impact. If you 
        /// have an already analyzed solution, use another constructor
        /// </summary>
        /// <param name="solutionFilePath">Path to solution file</param>
        /// <param name="solutionConfiguration">Configuration for each project in solution to be built</param>
        public SolutionPort(string solutionFilePath, List<PortCoreConfiguration> solutionConfiguration, ILogger logger = null)
        {
            if (logger != null)
            {
                LogHelper.Logger = logger;
            }
            _portSolutionResult = new PortSolutionResult(solutionFilePath);
            _solutionPath = solutionFilePath;
            AnalyzerConfiguration analyzerConfiguration = new AnalyzerConfiguration(LanguageOptions.CSharp);
            analyzerConfiguration.MetaDataSettings = new MetaDataSettings()
            {
                Annotations = true,
                DeclarationNodes = true,
                MethodInvocations = true,
                ReferenceData = true,
                LoadBuildData = true,
                InterfaceDeclarations = true
            };

            CodeAnalyzer analyzer = CodeAnalyzerFactory.GetAnalyzer(analyzerConfiguration, LogHelper.Logger);
            var analyzerResults = analyzer.AnalyzeSolution(solutionFilePath).Result;

            _context = new MetricsContext(solutionFilePath, analyzerResults);
            InitSolutionRewriter(analyzerResults, solutionConfiguration);
        }
示例#6
0
        protected List <AnalyzerResult> GenerateSolutionAnalysis(string solutionPath)
        {
            AnalyzerConfiguration configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                ExportSettings =
                {
                    GenerateJsonOutput = false,
                    OutputPath         = @"/tmp/UnitTests"
                },

                MetaDataSettings =
                {
                    LiteralExpressions = true,
                    MethodInvocations  = true,
                    Annotations        = true,
                    DeclarationNodes   = true,
                    LocationData       = false,
                    ReferenceData      = true,
                    LoadBuildData      = true,
                    ElementAccess      = true,
                    MemberAccess       = true
                }
            };
            CodeAnalyzer analyzer = CodeAnalyzerFactory.GetAnalyzer(configuration, NullLogger.Instance);
            var          result   = analyzer.AnalyzeSolution(solutionPath).Result;

            return(result);
        }
示例#7
0
        public async Task TestAnalyzer()
        {
            string projectPath = string.Concat(GetTstPath(Path.Combine(new[] { "Projects", "CodelyzerDummy", "CodelyzerDummy" })), ".csproj");

            AnalyzerConfiguration configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                ExportSettings =
                {
                    GenerateJsonOutput    = true,
                    GenerateGremlinOutput = false,
                    GenerateRDFOutput     = false,
                    OutputPath            = @"/tmp/UnitTests"
                },

                MetaDataSettings =
                {
                    LiteralExpressions = true,
                    MethodInvocations  = true,
                    Annotations        = true,
                    DeclarationNodes   = true,
                    LocationData       = true,
                    ReferenceData      = true,
                    LoadBuildData      = true
                }
            };
            CodeAnalyzer analyzer = CodeAnalyzerFactory.GetAnalyzer(configuration, NullLogger.Instance);

            using AnalyzerResult result = await analyzer.AnalyzeProject(projectPath);

            Assert.True(result != null);
        }
示例#8
0
        private CodeAnalyzer GetCodeAnalyzer()
        {
            AnalyzerConfiguration analyzerConfiguration = new AnalyzerConfiguration(LanguageOptions.CSharp);
            ExportSettings        exportSettings        = new ExportSettings()
            {
                GenerateGremlinOutput = false, GenerateJsonOutput = false, GenerateRDFOutput = false
            };
            MetaDataSettings metaDataSettings = new MetaDataSettings()
            {
                Annotations        = false,
                DeclarationNodes   = false,
                LambdaMethods      = false,
                LiteralExpressions = false,
                LocationData       = false,
                MethodInvocations  = false,
                ReferenceData      = false
            };

            analyzerConfiguration.ExportSettings   = exportSettings;
            analyzerConfiguration.MetaDataSettings = metaDataSettings;

            CodeAnalyzer analyzer = CodeAnalyzerFactory.GetAnalyzer(analyzerConfiguration, LogHelper.Logger);

            return(analyzer);
        }
示例#9
0
        public async Task TestMvcMusicStore()
        {
            string solutionPath = Directory.EnumerateFiles(tempDir, "MvcMusicStore.sln", SearchOption.AllDirectories).FirstOrDefault();

            FileAssert.Exists(solutionPath);

            AnalyzerConfiguration configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                ExportSettings =
                {
                    GenerateJsonOutput = false,
                    OutputPath         = @"/tmp/UnitTests"
                },

                MetaDataSettings =
                {
                    LiteralExpressions = true,
                    MethodInvocations  = true,
                    Annotations        = true,
                    DeclarationNodes   = true,
                    LocationData       = false,
                    ReferenceData      = true,
                    LoadBuildData      = true
                }
            };
            CodeAnalyzer analyzer = CodeAnalyzerFactory.GetAnalyzer(configuration, NullLogger.Instance);

            using var result = (await analyzer.AnalyzeSolution(solutionPath)).FirstOrDefault();
            Assert.True(result != null);
            Assert.False(result.ProjectBuildResult.IsSyntaxAnalysis);

            Assert.AreEqual(28, result.ProjectResult.SourceFiles.Count);

            //Project has 16 nuget references and 19 framework/dll references:
            Assert.AreEqual(29, result.ProjectResult.ExternalReferences.NugetReferences.Count);
            Assert.AreEqual(24, result.ProjectResult.ExternalReferences.SdkReferences.Count);

            var homeController = result.ProjectResult.SourceFileResults.Where(f => f.FilePath.EndsWith("HomeController.cs")).FirstOrDefault();

            Assert.NotNull(homeController);

            var classDeclarations = homeController.Children.OfType <Codelyzer.Analysis.Model.NamespaceDeclaration>().FirstOrDefault();

            Assert.Greater(classDeclarations.Children.Count, 0);

            var classDeclaration = homeController.Children.OfType <Codelyzer.Analysis.Model.NamespaceDeclaration>().FirstOrDefault().Children[0];

            Assert.NotNull(classDeclaration);

            var declarationNodes   = classDeclaration.Children.OfType <Codelyzer.Analysis.Model.DeclarationNode>();
            var methodDeclarations = classDeclaration.Children.OfType <Model.MethodDeclaration>();

            //HouseController has 3 identifiers declared within the class declaration:
            Assert.AreEqual(4, declarationNodes.Count());

            //It has 2 method declarations
            Assert.AreEqual(2, methodDeclarations.Count());
        }
示例#10
0
文件: PortCoreTests.cs 项目: aws/cta
        public async Task TestWebApiWithReferencesUsingGenerator(string version)
        {
            var solutionPath = CopySolutionFolderToTemp("WebApiWithReferences.sln", tempDir);

            AnalyzerConfiguration configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                ExportSettings =
                {
                    GenerateJsonOutput = false,
                    OutputPath         = @"/tmp/UnitTests"
                },

                MetaDataSettings =
                {
                    LiteralExpressions = true,
                    MethodInvocations  = true,
                    Annotations        = true,
                    DeclarationNodes   = true,
                    LocationData       = false,
                    ReferenceData      = true,
                    LoadBuildData      = true,
                    ElementAccess      = true,
                    MemberAccess       = true
                }
            };

            CodeAnalyzer analyzer     = CodeAnalyzerFactory.GetAnalyzer(configuration, NullLogger.Instance);
            SolutionPort solutionPort = new SolutionPort(solutionPath);

            var resultEnumerator = analyzer.AnalyzeSolutionGeneratorAsync(solutionPath).GetAsyncEnumerator();

            while (await resultEnumerator.MoveNextAsync())
            {
                using var result = resultEnumerator.Current;
                PortCoreConfiguration projectConfiguration = new PortCoreConfiguration()
                {
                    SolutionPath    = solutionPath,
                    ProjectPath     = result.ProjectResult.ProjectFilePath,
                    IsMockRun       = false,
                    UseDefaultRules = true,
                    PortCode        = true,
                    PortProject     = true,
                    TargetVersions  = new List <string> {
                        version
                    }
                };

                solutionPort.RunProject(result, projectConfiguration);
            }
            var portSolutionResult = solutionPort.GenerateResults();
            var testSolutionResult = GenerateSolutionResult(solutionPath, solutionPort.GetAnalysisResult(), portSolutionResult);

            ValidateWebApiWithReferences(testSolutionResult);
        }
示例#11
0
        private async Task <List <AnalyzerResult> > RunCoderlyzerAnalysis(string solutionFilename)
        {
            MemoryUtils.LogSystemInfo(_logger);
            MemoryUtils.LogSolutiontSize(_logger, solutionFilename);
            _logger.LogInformation("Memory usage before RunCoderlyzerAnalysis: ");
            MemoryUtils.LogMemoryConsumption(_logger);

            var configuration   = GetAnalyzerConfiguration();
            var analyzer        = CodeAnalyzerFactory.GetAnalyzer(configuration, _logger);
            var analyzerResults = await analyzer.AnalyzeSolution(solutionFilename);

            _logger.LogInformation("Memory usage after RunCoderlyzerAnalysis: ");
            MemoryUtils.LogMemoryConsumption(_logger);

            return(analyzerResults);
        }
示例#12
0
        public async IAsyncEnumerable <ProjectAnalysisResult> AnalyzeSolutionGeneratorAsync(string solutionFilename, List <string> projects, string targetFramework = "netcoreapp3.1")
        {
            var configuration = GetAnalyzerConfiguration();
            var analyzer      = CodeAnalyzerFactory.GetAnalyzer(configuration, _logger);

            var resultEnumerator = analyzer.AnalyzeSolutionGeneratorAsync(solutionFilename).GetAsyncEnumerator();

            try
            {
                SolutionPort solutionPort = new SolutionPort(solutionFilename);

                while (await resultEnumerator.MoveNextAsync().ConfigureAwait(false))
                {
                    var result      = resultEnumerator.Current;
                    var projectPath = result?.ProjectResult?.ProjectFilePath;
                    PortCoreConfiguration projectConfiguration = new PortCoreConfiguration()
                    {
                        ProjectPath     = projectPath,
                        UseDefaultRules = true,
                        TargetVersions  = new List <string> {
                            targetFramework
                        },
                        PortCode    = false,
                        PortProject = false
                    };

                    var projectResult = solutionPort.RunProject(result, projectConfiguration);

                    var analysisActions = AnalyzeActions(new List <string> {
                        projectPath
                    }, targetFramework, new List <AnalyzerResult> {
                        result
                    }, solutionFilename);

                    var analysisResult = AnalyzeProject(projectPath, solutionFilename, new List <AnalyzerResult> {
                        result
                    }, analysisActions, isIncremental: false, targetFramework);
                    result.Dispose();
                    yield return(analysisResult);
                }
            }
            finally
            {
                await resultEnumerator.DisposeAsync();
            }
        }
示例#13
0
        public async Task TestAnalysis()
        {
            string projectPath = string.Concat(GetTstPath(Path.Combine(new string[] { "Projects", "CodelyzerDummy", "CodelyzerDummy" })), ".csproj");

            AnalyzerConfiguration configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                ExportSettings =
                {
                    GenerateJsonOutput = true,
                    OutputPath         = @"/tmp/UnitTests"
                },

                MetaDataSettings =
                {
                    LiteralExpressions = true,
                    MethodInvocations  = true,
                    Annotations        = true,
                    LambdaMethods      = true,
                    DeclarationNodes   = true,
                    LocationData       = true,
                    ReferenceData      = true,
                    LoadBuildData      = true
                }
            };
            CodeAnalyzer   analyzer = CodeAnalyzerFactory.GetAnalyzer(configuration, NullLogger.Instance);
            AnalyzerResult result   = await analyzer.AnalyzeProject(projectPath);

            Assert.False(result.ProjectBuildResult.IsSyntaxAnalysis);

            Assert.True(result != null);

            // Extract the subject node
            var testClassRootNode = result.ProjectResult.SourceFileResults
                                    .First(s => s.FileFullPath.EndsWith("Class2.cs"))
                                    as UstNode;

            // Nested class is found
            Assert.AreEqual(1, testClassRootNode.AllClasses().Count(c => c.Identifier == "NestedClass"));

            // Chained method is found
            Assert.AreEqual(1, testClassRootNode.AllInvocationExpressions().Count(c => c.MethodName == "ChainedMethod"));

            // Constructor is found
            Assert.AreEqual(1, testClassRootNode.AllConstructors().Count);
        }
示例#14
0
        /// <summary>
        /// Initializes a new instance of Solution Port, analyzing the solution path using the provided config.
        /// WARNING: This constructor will rebuild and reanalyze the solution, which will have a performance impact. If you
        /// have an already analyzed solution, use another constructor
        /// </summary>
        /// <param name="solutionFilePath">Path to solution file</param>
        /// <param name="solutionConfiguration">Configuration for each project in solution to be built</param>
        public SolutionPort(string solutionFilePath, List <PortCoreConfiguration> solutionConfiguration, ILogger logger = null)
        {
            if (logger != null)
            {
                LogHelper.Logger = logger;
            }
            _portSolutionResult = new PortSolutionResult(solutionFilePath);
            SkipDownloadFiles   = new ConcurrentDictionary <string, bool>();
            _solutionPath       = solutionFilePath;
            AnalyzerConfiguration analyzerConfiguration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                MetaDataSettings = new MetaDataSettings()
                {
                    Annotations           = true,
                    DeclarationNodes      = true,
                    MethodInvocations     = true,
                    ReferenceData         = true,
                    LoadBuildData         = true,
                    InterfaceDeclarations = true,
                    MemberAccess          = true,
                    ElementAccess         = true
                }
            };

            CodeAnalyzer analyzer = CodeAnalyzerFactory.GetAnalyzer(analyzerConfiguration, LogHelper.Logger);

            List <AnalyzerResult> analyzerResults = null;

            //We are building using references
            if (solutionConfiguration.Any(p => p.MetaReferences?.Any() == true))
            {
                var currentReferences   = solutionConfiguration.ToDictionary(s => s.ProjectPath, s => s.MetaReferences);
                var frameworkReferences = solutionConfiguration.ToDictionary(s => s.ProjectPath, s => s.FrameworkMetaReferences);
                analyzerResults = analyzer.AnalyzeSolution(solutionFilePath, frameworkReferences, currentReferences).Result;
            }
            else
            {
                analyzerResults = analyzer.AnalyzeSolution(solutionFilePath).Result;
            }

            _context = new MetricsContext(solutionFilePath, analyzerResults);
            InitSolutionRewriter(analyzerResults, solutionConfiguration);
        }
示例#15
0
        private static CodeAnalyzer GetDefaultCodeAnalyzer(string solutionOrProjectPath)
        {
            // Codelyzer input
            var analyzerOutputDir = Path.Combine("..", "..");

            /* 1. Logger object */
            var logger = Log.Logger;

            /* 2. Get Analyzer instance based on language */
            var args = new[]
            {
                "-p", solutionOrProjectPath
            };
            AnalyzerCLI cli = new AnalyzerCLI();

            cli.HandleCommand(args);
            cli.Configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                ExportSettings =
                {
                    GenerateJsonOutput = false,
                    OutputPath         = analyzerOutputDir
                },

                MetaDataSettings =
                {
                    LiteralExpressions    = true,
                    MethodInvocations     = true,
                    Annotations           = true,
                    LambdaMethods         = true,
                    DeclarationNodes      = true,
                    LocationData          = true,
                    ReferenceData         = true,
                    LoadBuildData         = true,
                    ReturnStatements      = true,
                    InterfaceDeclarations = true
                }
            };

            return(CodeAnalyzerFactory.GetAnalyzer(cli.Configuration, logger));
        }
示例#16
0
        public async Task TestNopCommerce()
        {
            string solutionPath = Directory.EnumerateFiles(tempDir, "nopCommerce.sln", SearchOption.AllDirectories).FirstOrDefault();

            FileAssert.Exists(solutionPath);

            AnalyzerConfiguration configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                ExportSettings =
                {
                    GenerateJsonOutput = false,
                    OutputPath         = @"/tmp/UnitTests"
                },

                MetaDataSettings =
                {
                    LiteralExpressions    = true,
                    MethodInvocations     = true,
                    Annotations           = true,
                    DeclarationNodes      = true,
                    LocationData          = false,
                    ReferenceData         = true,
                    EnumDeclarations      = true,
                    StructDeclarations    = true,
                    InterfaceDeclarations = true
                }
            };

            CodeAnalyzer analyzer = CodeAnalyzerFactory.GetAnalyzer(configuration, NullLogger.Instance);
            var          results  = (await analyzer.AnalyzeSolution(solutionPath)).ToList();

            var enumDeclarations      = results.Sum(r => r.ProjectResult.SourceFileResults.Where(s => s.AllEnumDeclarations().Count > 0).Sum(s => s.AllEnumDeclarations().Count));
            var structDeclarations    = results.Sum(r => r.ProjectResult.SourceFileResults.Where(s => s.AllStructDeclarations().Count > 0).Sum(s => s.AllStructDeclarations().Count));
            var arrowClauseStatements = results.Sum(r => r.ProjectResult.SourceFileResults.Where(s => s.AllArrowExpressionClauses().Count > 0).Sum(s => s.AllArrowExpressionClauses().Count));

            Assert.AreEqual(80, enumDeclarations);
            Assert.AreEqual(1, structDeclarations);
            Assert.AreEqual(2, arrowClauseStatements);

            results.ForEach(r => r.Dispose());
        }
示例#17
0
        /// <summary>
        /// Initializes a new instance of SolutionRewriter, analyzing the solution path using the provided config.
        /// WARNING: This constructor will rebuild and reanalyze the solution, which will have a performance impact. If you
        /// have an already analyzed solution, use another constructor
        /// </summary>
        /// <param name="analyzerConfiguration">Configuration for code analyzer to be used (AnalyzerConfiguration)</param>
        /// <param name="solutionFilePath">Path to solution file</param>
        /// <param name="solutionConfiguration">Configuration for each project in solution to be built</param>
        public SolutionRewriter(string solutionFilePath, List <ProjectConfiguration> solutionConfiguration)
        {
            _solutionResult = new SolutionResult();
            AnalyzerConfiguration analyzerConfiguration = new AnalyzerConfiguration(LanguageOptions.CSharp);

            analyzerConfiguration.MetaDataSettings = new MetaDataSettings()
            {
                Annotations           = true,
                DeclarationNodes      = true,
                MethodInvocations     = true,
                ReferenceData         = true,
                LoadBuildData         = true,
                InterfaceDeclarations = true
            };

            _rulesRewriters = new List <ProjectRewriter>();
            CodeAnalyzer analyzer        = CodeAnalyzerFactory.GetAnalyzer(analyzerConfiguration, LogHelper.Logger);
            var          analyzerResults = analyzer.AnalyzeSolution(solutionFilePath).Result;

            InitializeProjects(analyzerResults, solutionConfiguration);
        }
示例#18
0
        private CodeAnalyzer GetDefaultCodeAnalyzer()
        {
            var analyzerOutputDir = Path.Combine("..", "..");
            var cli = new AnalyzerCLI
            {
                Configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
                {
                    ExportSettings =
                    {
                        GenerateJsonOutput = true,
                        OutputPath         = analyzerOutputDir
                    },

                    MetaDataSettings =
                    {
                        LiteralExpressions    = true,
                        MethodInvocations     = true,
                        Annotations           = true,
                        LambdaMethods         = true,
                        DeclarationNodes      = true,
                        LocationData          = true,
                        ReferenceData         = true,
                        LoadBuildData         = true,
                        InterfaceDeclarations = true
                    }
                }
            };

            Logger.LogInformation("Creating default CodeAnalyzer with the following parameters:");
            Logger.LogInformation(cli.Project + " -- " + cli.FilePath);
            Logger.LogInformation(SerializeUtils.ToJson(cli.Configuration));

            /* Get Analyzer instance based on language */
            var analyzer = CodeAnalyzerFactory.GetAnalyzer(cli.Configuration, Logger);

            return(analyzer);
        }
示例#19
0
        public async Task TestSampleWebApi()
        {
            string solutionPath = Directory.EnumerateFiles(tempDir, "SampleWebApi.sln", SearchOption.AllDirectories).FirstOrDefault();

            FileAssert.Exists(solutionPath);

            string solutionDir = Directory.GetParent(solutionPath).FullName;

            AnalyzerConfiguration configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                ExportSettings =
                {
                    GenerateJsonOutput = true,
                    OutputPath         = Path.Combine("/", "tmp", "UnitTests")
                },

                MetaDataSettings =
                {
                    LiteralExpressions    = true,
                    MethodInvocations     = true,
                    Annotations           = true,
                    DeclarationNodes      = true,
                    LocationData          = false,
                    ReferenceData         = true,
                    InterfaceDeclarations = true,
                    GenerateBinFiles      = true,
                    LoadBuildData         = true,
                    ReturnStatements      = true,
                    InvocationArguments   = true
                }
            };
            CodeAnalyzer   analyzer = CodeAnalyzerFactory.GetAnalyzer(configuration, NullLogger.Instance);
            AnalyzerResult result   = (await analyzer.AnalyzeSolution(solutionPath)).FirstOrDefault();

            Assert.True(result != null);
            Assert.False(result.ProjectBuildResult.IsSyntaxAnalysis);

            //Project has 16 nuget references and 19 framework/dll references:
            Assert.AreEqual(16, result.ProjectResult.ExternalReferences.NugetReferences.Count);
            Assert.AreEqual(19, result.ProjectResult.ExternalReferences.SdkReferences.Count);

            Assert.AreEqual(10, result.ProjectResult.SourceFiles.Count);

            var houseController = result.ProjectResult.SourceFileResults.Where(f => f.FilePath.EndsWith("HouseController.cs")).FirstOrDefault();

            Assert.NotNull(houseController);

            var ihouseRepository = result.ProjectResult.SourceFileResults.Where(f => f.FilePath.EndsWith("IHouseRepository.cs")).FirstOrDefault();

            Assert.NotNull(ihouseRepository);

            var blockStatements           = houseController.AllBlockStatements();
            var classDeclarations         = houseController.AllClasses();
            var expressionStatements      = houseController.AllExpressions();
            var invocationExpressions     = houseController.AllInvocationExpressions();
            var literalExpressions        = houseController.AllLiterals();
            var methodDeclarations        = houseController.AllMethods();
            var returnStatements          = houseController.AllReturnStatements();
            var annotations               = houseController.AllAnnotations();
            var namespaceDeclarations     = houseController.AllNamespaces();
            var objectCreationExpressions = houseController.AllObjectCreationExpressions();
            var usingDirectives           = houseController.AllUsingDirectives();
            var interfaces = ihouseRepository.AllInterfaces();
            var arguments  = houseController.AllArguments();

            Assert.AreEqual(7, blockStatements.Count);
            Assert.AreEqual(1, classDeclarations.Count);
            Assert.AreEqual(89, expressionStatements.Count);
            Assert.AreEqual(75, invocationExpressions.Count);
            Assert.AreEqual(14, literalExpressions.Count);
            Assert.AreEqual(6, methodDeclarations.Count);
            Assert.AreEqual(16, returnStatements.Count);
            Assert.AreEqual(17, annotations.Count);
            Assert.AreEqual(1, namespaceDeclarations.Count);
            Assert.AreEqual(0, objectCreationExpressions.Count);
            Assert.AreEqual(10, usingDirectives.Count);
            Assert.AreEqual(1, interfaces.Count);
            Assert.AreEqual(63, arguments.Count);

            var dllFiles = Directory.EnumerateFiles(Path.Combine(result.ProjectResult.ProjectRootPath, "bin"), "*.dll");

            Assert.AreEqual(dllFiles.Count(), 16);

            await RunAgainWithChangedFile(solutionPath, result.ProjectBuildResult.ProjectPath, configuration, analyzer);
        }