Wednesday, June 10, 2015

Configure StyleCop with MSBuild to treat Warnings as Errors


We can easily configure StyleCop with MSBuild to make warnings appear as errors with the help of StyleCop.MSBuild NuGet package.

First go to Package Manager Console and install it with following command.


Install-Package StyleCop.MSBuild
Then unload your project and open the project file to modify it.



Now you have to add "StyleCopTreatErrorsAsWarnings" property inside "PropertyGroup" tag as below.
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
  <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
  <StyleCopTreatErrorsAsWarnings>false</StyleCopTreatErrorsAsWarnings>
</PropertyGroup>
<Error Condition="!Exists('..\packages\StyleCop.MSBuild.4.7.49.1\build\StyleCop.MSBuild.Targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\StyleCop.MSBuild.4.7.49.1\build\StyleCop.MSBuild.Targets'))" />
</Target>
Almost done, but sometimes auto generated files gives errors when we build the project, to overcome that we need to modify "Settings.StyleCop" file.

Go to project folder and inside that you can find folder called "packages". It contains StyleCop files and inside "tools" folder you can find that setting file. You can open it with a test editor.


Now you can add new value to GeneratedFileFilters as bellow to ignore those generated files.
<Parser ParserId="StyleCop.CSharp.CsParser">
  <ParserSettings>
 <CollectionProperty Name="GeneratedFileFilters">
   <Value>\.g\.cs$</Value>
   <Value>\.generated\.cs$</Value>
   <Value>\.g\.i\.cs$</Value>
   <Value>TemporaryGeneratedFile_.*\.cs$</Value>
 </CollectionProperty>
  </ParserSettings>
</Parser>
Now reload your project and try to build your project. You will be able to see that all the warnings appear as errors.

0 comments:

Post a Comment