Search code examples
.netvisual-studioroslyn-code-analysisstatic-code-analysismicrosoft.codeanalysis

How to get all analyzers rules in a solution


I have added some analyzer via NuGet in my solution. How to get all added analyzer rules from NuGet references? I need the ID (e.g. CA1001) and descriptions of all my enabled analyzers.

EDIT: I need some C# code to do this.


Solution

  • From the answer at GitHub. Credits by jmarolf:

    References:

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net5.0</TargetFramework>
        <Nullable>enable</Nullable>
      </PropertyGroup>
    
      <ItemGroup>
        <PackageReference Include="Microsoft.Build.Locator" Version="1.4.1" />
        <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.2" PrivateAssets="all" />
        <PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="3.9.0" />
        <PackageReference Include="Microsoft.CodeAnalysis.VisualBasic.Workspaces" Version="3.9.0" />
        <PackageReference Include="Microsoft.CodeAnalysis.Workspaces.MSBuild" Version="3.9.0" />
      </ItemGroup>
    
    </Project>
    

    C#:

    using System;
    using System.IO;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.Build.Locator;
    using Microsoft.CodeAnalysis;
    using Microsoft.CodeAnalysis.MSBuild;
    
    namespace AnalyzerReader
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                // Attempt to set the version of MSBuild.
                var instance = MSBuildLocator.RegisterDefaults();
    
                Console.WriteLine($"Using MSBuild at '{instance.MSBuildPath}' to load projects.");
    
                using var workspace = MSBuildWorkspace.Create();
    
                // Print message for WorkspaceFailed event to help diagnosing project load failures.
                workspace.WorkspaceFailed += (o, e) => Console.WriteLine(e.Diagnostic.Message);
    
                var solutionPath = args[0];
                Console.WriteLine($"Loading solution '{solutionPath}'");
    
                // Attach progress reporter so we print projects as they are loaded.
                var solution = await workspace.OpenSolutionAsync(solutionPath, new ConsoleProgressReporter());
                Console.WriteLine($"Finished loading solution '{solutionPath}'");
    
                // Get all analyzers in the project
                var diagnosticDescriptors = solution.Projects
                    .SelectMany(project => project.AnalyzerReferences)
                    .SelectMany(analyzerReference => analyzerReference.GetAnalyzersForAllLanguages())
                    .SelectMany(analyzer => analyzer.SupportedDiagnostics)
                    .Distinct().OrderBy(x => x.Id);
    
                Console.WriteLine($"{nameof(DiagnosticDescriptor.Id),-15} {nameof(DiagnosticDescriptor.Title)}");
                foreach (var diagnosticDescriptor in diagnosticDescriptors)
                {
                    Console.WriteLine($"{diagnosticDescriptor.Id,-15} {diagnosticDescriptor.Title}");
                }
            }
    
            private class ConsoleProgressReporter : IProgress<ProjectLoadProgress>
            {
                public void Report(ProjectLoadProgress loadProgress)
                {
                    var projectDisplay = Path.GetFileName(loadProgress.FilePath);
                    if (loadProgress.TargetFramework != null)
                    {
                        projectDisplay += $" ({loadProgress.TargetFramework})";
                    }
    
                    Console.WriteLine($"{loadProgress.Operation,-15} {loadProgress.ElapsedTime,-15:m\\:ss\\.fffffff} {projectDisplay}");
                }
            }
        }
    }