SANDFISH FACTORY

技術ブログです。python・vuejsを愛でる日々について綴ります

MSBuildでコードスタイル分析のIDE0005を有効にする

.NETのコード分析のブログの続きを書こうとしたら、まだ解決されていない不具合に遭遇したので解決方法を記載しておきます。

環境

同じ環境を構築するには前回のブログを実施してください。

原因

Compiler does not report unused imports when XML doc comments are disabled · Issue #41640 · dotnet/roslyn · GitHub

IDE上では問題ないですが、MSBuildでビルドしようとするときにGenerateDocumentationFileが有効でないとIDE0005(不要な using ディレクティブを削除する)が無視されます。
以下の設定をMSBuildのプロジェクトファイルに追記してください。

<!-- Workaround for https://github.com/dotnet/roslyn/issues/41640 -->
<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);CS1591;CS1573</NoWarn>
</PropertyGroup>

サンプルコード

前回のブログで作成した.csprojファイルに上記の設定を追記します。

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
      <NoWarn>$(NoWarn);CS1591;CS1573</NoWarn>
  </PropertyGroup>
  <ItemGroup>
    <None Remove="Microsoft.CodeAnalysis.NetAnalyzers" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="7.0.0">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
  </ItemGroup>
</Project>

Program.csにはエラーを発生させるため、using System.IO を追記します。

using System;
using System.IO; // 追記

namespace SampleCode
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

.editorconfigにはIDE0005を有効にする設定を追記します。

[*.{cs,vb}]
dotnet_diagnostic.IDE0005.severity = warning

以下のコマンドを実行します。
EnforceCodeStyleInBuildを有効にしてコードスタイル分析を実施します。
また、TreatWarningsAsErrorsを有効にしてwarrningが一つでもあればエラーとします。

dotnet build SampleCode.csproj -target:"clean;rebuild" -property:"EnforceCodeStyleInBuild=true;TreatWarningsAsErrors=true"

こんな感じでエラーが出ます。