MSBuildでコードスタイル分析のIDE0005を有効にする
.NETのコード分析のブログの続きを書こうとしたら、まだ解決されていない不具合に遭遇したので解決方法を記載しておきます。
環境
- .NET Core 3.1
- Visual Studio 2022 for Mac
- バージョン 17.4.2(build 17)
- Microsoft.CodeAnalysis.NetAnalyzers 7.0.0
同じ環境を構築するには前回のブログを実施してください。
原因
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"
こんな感じでエラーが出ます。