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); }
/// <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); }
public override async Task <CommandResult> ExecuteAsync(ProjectOrSolution projectOrSolution, CancellationToken cancellationToken = default) { AssemblyResolver.Register(); var codeAnalyzerOptions = new CodeAnalyzerOptions( ignoreAnalyzerReferences: Options.IgnoreAnalyzerReferences, ignoreCompilerDiagnostics: Options.IgnoreCompilerDiagnostics, reportNotConfigurable: Options.ReportNotConfigurable, reportSuppressedDiagnostics: Options.ReportSuppressedDiagnostics, logAnalyzerExecutionTime: Options.ExecutionTime, severityLevel: SeverityLevel, supportedDiagnosticIds: Options.SupportedDiagnostics, ignoredDiagnosticIds: Options.IgnoredDiagnostics, projectNames: Options.Projects, ignoredProjectNames: Options.IgnoredProjects, language: Language); IEnumerable <string> analyzerAssemblies = Options.AnalyzerAssemblies; if (Options.UseRoslynatorAnalyzers) { analyzerAssemblies = analyzerAssemblies.Concat(RoslynatorAnalyzersAssemblies); } CultureInfo culture = (Options.Culture != null) ? CultureInfo.GetCultureInfo(Options.Culture) : null; var codeAnalyzer = new CodeAnalyzer( analyzerAssemblies: AnalyzerAssemblyLoader.LoadFiles(analyzerAssemblies, loadFixers: false), formatProvider: culture, options: codeAnalyzerOptions); if (projectOrSolution.IsProject) { Project project = projectOrSolution.AsProject(); WriteLine($"Analyze '{project.Name}'", ConsoleColor.Cyan, Verbosity.Minimal); ProjectAnalysisResult result = await codeAnalyzer.AnalyzeProjectAsync(project, cancellationToken); if (Options.Output != null && result.Diagnostics.Any()) { DiagnosticXmlSerializer.Serialize(result, project, Options.Output, culture); } } else { Solution solution = projectOrSolution.AsSolution(); ImmutableArray <ProjectAnalysisResult> results = await codeAnalyzer.AnalyzeSolutionAsync(solution, cancellationToken); if (Options.Output != null && results.Any(f => f.Diagnostics.Any())) { DiagnosticXmlSerializer.Serialize(results, solution, Options.Output, culture); } } return(CommandResult.Success); }
/// <summary> /// Performs code analysis of a repo /// </summary> public void AnalyzeRepo() { foreach (var file in repoSource.GetFiles()) { try { var analyzer = new CodeAnalyzer(file); AnalysisResult.Add(analyzer.AnalyzeCode()); } catch (Esprima.ParserException e) { var error = new ParseErrorResponse() { errorName = "PARSE_ERROR", message = e.Description, line = e.LineNumber, column = e.Column }; AnalysisResult.Add(new FileAnalysisResult() { error = error, FileName = file.fileName }); } } }
public CodeStatistics(List <Tuple <SyntaxTree, TreeStatistics> > treestats) { TreeStats = treestats; CatchBlocks = new CatchDic(); APICalls = new CallDic(); CodeStats = new Dictionary <String, int>(); foreach (var treetuple in treestats) { if (treetuple == null) { continue; } if (treetuple.Item2.CatchBlockList != null) { CatchBlocks.Add(treetuple.Item2.CatchBlockList); } if (treetuple.Item2.APICallList != null) { APICalls.Add(treetuple.Item2.APICallList); } if (treetuple.Item2.CodeStats != null) { CodeAnalyzer.MergeDic <String>(ref CodeStats, treetuple.Item2.CodeStats); } } CodeStats["NumExceptionType"] = CatchBlocks.Count; CodeStats["NumLoggedCatchBlock"] = CatchBlocks.NumLogged; CodeStats["NumCallType"] = APICalls.Count; CodeStats["NumAPICall"] = APICalls.NumAPICall; CodeStats["NumLoggedAPICall"] = APICalls.NumLogged; }
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); }
public static void LoadByTxtFile(String folderPath) { String txtFilePath = IOFile.CompleteFileName("AllSource.txt"); Logger.Log("Load from txt file: " + txtFilePath); String content = ""; try { using (StreamReader sr = new StreamReader(txtFilePath)) { content = sr.ReadToEnd(); } } catch (Exception e) { Logger.Log("Txt file may not exist."); Logger.Log(e); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } var tree = SyntaxTree.ParseText(content); var model = GetSemanticInfo(tree); var treeAndModelDic = new Dictionary <SyntaxTree, SemanticModel>(); treeAndModelDic.Add(tree, model); var compilation = BuildCompilation(new List <SyntaxTree> { tree }); CodeAnalyzer.AnalyzeAllTrees(treeAndModelDic, compilation); }
/// <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); }
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); }
public void TestDiagnoseNetCoreAnalyzers() { var expected = @"file: example/Class2.cs id: CA5392 location: (10,28)-(10,41) severity: Warning message: The method SetWindowText didn't use DefaultDllImportSearchPaths attribute for P/Invokes. id: CA2201 location: (20,10)-(20,25) severity: Warning message: Exception type System.Exception is not sufficiently specific. id: CA1401 location: (10,28)-(10,41) severity: Warning message: P/Invoke method 'SetWindowText' should not be visible id: CA2101 location: (9,3)-(9,56) severity: Warning message: Specify marshaling for P/Invoke string arguments "; var actual = CodeAnalyzer.Create(CSharp, new[] { MicrosoftNetCoreAnalyzersDll }) .Diagnose(new[] { @"example/Class2.cs" }) .ToSimpleText(); Assert.AreEqual(expected, actual); }
public void BasicTest() { CodeAnalyzerResult result = new CodeAnalyzer("Workbook1.xlsm").AnalyzeModule("Module1", @"Option Explicit"); Assert.IsNotNull(result); Assert.AreEqual(0, result.VbaCodeIssues.Count); }
public static int Main(string[] args) { int exitCode; var parseResult = Parser.Default.ParseArguments <Options>(args); if (parseResult.Tag == ParserResultType.NotParsed) { exitCode = 1; goto Exit; } try { var parsed = (Parsed <Options>)parseResult; var outputFile = parsed.Value.OutputFile; using var writer = outputFile == Options.Stdout ? Console.Out : File.CreateText(outputFile); CodeAnalyzer .Create(parsed.Value.Language, Analyzers) .Diagnose(parsed.Value.Targets) .DumpJsonStringTo(writer); exitCode = 0; } catch (Exception e) { Console.Error.WriteLine(e); exitCode = 2; } Exit: return(exitCode); }
public void ShouldReturnTrueIfIsMethod() { const string Code = "void Bar() { }"; var analyser = new CodeAnalyzer(); analyser.IsMethod(Code).ShouldBeTrue(); }
public void ShouldReturnFalseIfMissingMethodBody() { const string Code = "void Bar()"; var analyser = new CodeAnalyzer(); analyser.IsMethod(Code).ShouldBeFalse(); }
public void ShouldReturnFalseIfIncompeteMethod() { const string Code = "void Bar() { "; var analyser = new CodeAnalyzer(); analyser.IsMethod(Code).ShouldBeFalse(); }
public void ShouldReturnFalseIfIsNotMethod() { const string Code = "class A { } "; var rewriter = new CodeAnalyzer(); rewriter.IsMethod(Code).ShouldBeFalse(); }
public void ShouldReturnFalseIfIsNotClass() { const string Code = "void Bar() { }"; var analyser = new CodeAnalyzer(); analyser.IsClass(Code).ShouldBeFalse(); }
public void ShouldReturnTrueIfIsClass() { const string Code = "class A { }"; var analyser = new CodeAnalyzer(); analyser.IsClass(Code).ShouldBeTrue(); }
protected void ExpectSingleError(CodeAnalyzer analyzer, DiagnosticDescriptor descriptor) { Assert.AreEqual(1, analyzer.Diagnostics.Count()); var error = analyzer.Diagnostics.First(); Assert.AreEqual(descriptor, error.Descriptor); Assert.AreNotEqual(Location.None, error.Location); }
public FileAnalysisResult Analyze([FromBody] AnalyzeCodeResource data) { var analyzer = new CodeAnalyzer(data.Code); var res = analyzer.AnalyzeCode(); UpdateStats(res.LinesAnalyzed, res.SmellCount, 1, 0); return(res); }
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()); }
public void ObsoleteTypeHintTest() { const string inputCode = @"Option Explicit Public Foo&"; CodeAnalyzerResult result = new CodeAnalyzer("Workbook1.xlsm").AnalyzeModule("Module1", "" + inputCode); Assert.AreEqual(1, result.VbaCodeIssues.Count(x => x.Type == "ObsoleteTypeHint")); }
public void OptionExcplicitTest() { const string inputCode = @"Sub ExcelSub() Dim foo As Double End Sub"; CodeAnalyzerResult result = new CodeAnalyzer("Workbook1.xlsm").AnalyzeModule("Module1", inputCode); Assert.AreEqual(1, result.VbaCodeIssues.Count(x => x.Type == "OptionExplicit")); }
public void CanEvaluateGuess(int[] guess, int[] code, int[] expected) { CodePeg[] Guess = guess.Select(g => (CodePeg)g).ToArray(); CodePeg[] Code = code.Select(c => (CodePeg)c).ToArray(); List <KeyPeg> key = new CodeAnalyzer().EvaluateGuess(Guess, Code).ToList(); int[] result = { key.Count(k => k == KeyPeg.Black), key.Count(k => k == KeyPeg.White) }; Assert.Equal(expected, result); }
public void ObsoleteGlobalTest() { const string inputCode = @"Option Explicit Global var1 As Integer"; CodeAnalyzerResult result = new CodeAnalyzer("Workbook1.xlsm").AnalyzeModule("Module1", "" + inputCode); Assert.AreEqual(1, result.VbaCodeIssues.Count(x => x.Type == "ObsoleteGlobal")); }
public void OptionBaseTest() { const string inputCode = @"Option Explicit Option Base 1"; CodeAnalyzerResult result = new CodeAnalyzer("Workbook1.xlsm").AnalyzeModule("Module1", "" + inputCode); Assert.AreEqual(2, result.VbaCodeIssues.Count(x => x.Type == "OptionBase")); }
public static void AnalyzeShouldReturnAllAnalysisIssues() { const string relativeSolutionPath = @"..\.."; var projectPath = Path.GetFullPath(relativeSolutionPath); if (projectPath == null) { throw new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, "Unable to retrieve project directory off relative path: {0}", relativeSolutionPath)); } var styleCop = new CodeAnalyzer(projectPath); var violations = styleCop.Analyze(Path.Combine(Directory.GetCurrentDirectory(), @"Resources\TestClass.cs")).ToList(); Assert.That( violations[0].Message, Is.EqualTo("An opening curly bracket must not be followed by a blank line.")); Assert.That(violations[0].RuleId, Is.EqualTo("SA1505")); Assert.That( violations[1].Message, Is.EqualTo("A closing curly bracket must not be preceded by a blank line.")); Assert.That(violations[1].RuleId, Is.EqualTo("SA1508")); Assert.That( violations[2].Message, Is.EqualTo("Statements or elements wrapped in curly brackets must be followed by a blank line.")); Assert.That(violations[2].RuleId, Is.EqualTo("SA1513")); Assert.That( violations[3].Message, Is.EqualTo("All using directives must be placed inside of the namespace.")); Assert.That(violations[3].RuleId, Is.EqualTo("SA1200")); Assert.That( violations[4].Message, Is.EqualTo("All using directives must be placed inside of the namespace.")); Assert.That(violations[4].RuleId, Is.EqualTo("SA1200")); Assert.That( violations[5].Message, Is.EqualTo("All using directives must be placed inside of the namespace.")); Assert.That(violations[5].RuleId, Is.EqualTo("SA1200")); Assert.That( violations[6].Message, Is.EqualTo("All using directives must be placed inside of the namespace.")); Assert.That(violations[6].RuleId, Is.EqualTo("SA1200")); Assert.That( violations[7].Message, Is.EqualTo("All using directives must be placed inside of the namespace.")); Assert.That(violations[7].RuleId, Is.EqualTo("SA1200")); Assert.That( violations[8].Message, Is.EqualTo( "The comment must start with a single space. To ignore this error when commenting out a line of code, begin the comment with '////' rather than '//'.")); Assert.That(violations[8].RuleId, Is.EqualTo("SA1005")); }
private static int Main() { using (var analyzer = new CodeAnalyzer()) { analyzer.Run() .GetAwaiter().GetResult(); } return(0); }
public async Task ComplexityMathTest() { var codeAnalyzer = new CodeAnalyzer(); var result = await codeAnalyzer.Analyze(sourceFile, CancellationToken.None); Assert.True(result.LineComplexities.ToArray().Length == result.NrMethods, "Line complexity doesn't match"); Assert.True(result.Complexity == result.LineComplexities.Max(x => x.Value), "Complexity is not calculated correctly"); }
public async Task ResultJsonCheckTest() { var codeAnalyzer = new CodeAnalyzer(); var result = await codeAnalyzer.Analyze(sourceFile, CancellationToken.None); // check json parsing var expectedResult = File.ReadLines("Resources/Astar.json").First(); Assert.True(result.ToString() == expectedResult, "Wrong json format"); }
public void GetAllRegionDirectivesTest() { CodeAnalyzer analyzer = new CodeAnalyzer(new Utility.Factories.DirectiveParserFactory()); SyntaxNode root = CSharpSyntaxTree.ParseText(_testCode) .GetRoot(); List <DirectiveSyntaxNode> nodes = analyzer.GetRegionNodes(root); Assert.AreEqual(2, nodes.Count); }