首页 > 解决方案 > 如何在解决方案中获取所有分析器规则

问题描述

我在我的解决方案中通过 NuGet 添加了一些分析器。如何从 NuGet 引用中获取所有添加的分析器规则?我需要所有启用的分析器的 ID(例如 CA1001)和描述。

编辑:我需要一些 C# 代码来做到这一点。

标签: .netvisual-studioroslyn-code-analysisstatic-code-analysismicrosoft.codeanalysis

解决方案


来自GitHub的答案。jmarolf的学分:

参考:

<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}");
            }
        }
    }
}

推荐阅读