Providing a code analysis ruleset to a .net core project through NuGet

我与影子孤独终老i 提交于 2019-12-01 02:45:24

问题


I've run into a problem when upgrading a .NET 4.6 project to .NET Core 2.0. All our projects use a custom StyleCop ruleset which is provided by a NuGet package. The ruleset is in a file called custom.ruleset and lives in the content folder inside the package. All our projects consume this package and so get a copy of custom.ruleset.

However, in Core 2.0 and Standard 2.0 projects this doesn't work. Files are no longer copied from the content folder of a package, and we're told to use the contentFiles folder instead.

I have a nuspec that now looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
  <version>1.0.11</version>      
  <metadata>
    ...
    <contentFiles>
      <files include="content\*.ruleset" buildAction="None" copyToOutput="false" flatten="true"/>
    </contentFiles>
  </metadata>
  <files>
    <file src="content\**" target="contentFiles/any/any" />
  </files>
</package>

With this structure the ruleset appears in Visual Studio under the project, but trying to reference it from the project's .csproj file with <CodeAnalysisRuleSet>custom.ruleset</CodeAnalysisRuleSet> silently fails and reverts to using the default ruleset. I can force it to work by adding <CodeAnalysisRuleSet>$(NuGetPackageRoot)CustomRuleset\1.0.11\contentFiles\any\any\custom.ruleset</CodeAnalysisRuleSet> but this means the csproj will need updating whenever the ruleset changes, so it may as well be a manual process. Any ideas how to fix this?


回答1:


The idea is to not try to deploy the file as content but add build logic to the NuGet package.

Make sure that the package is structured in the following way:

  • build\
  • build\custom.ruleset
  • build\{YourPackageName}.targets (e.g. CustomRuleset.targets)

This structure causes the .targets file to be automatically imported into the consuming project by convention.

The .targets file should then contain:

<Project>
  <PropertyGroup>
    <CodeAnalysisRuleSet>$(MSBuildThisFileDirectory)custom.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
</Project>

This will cause the project's ruleset property to be overwritten to the location relative to the .targets file.

Note that this also applies to .net framework projects using the new PackageReference style of NuGet packages (replacement of packages.config) which is opt-in in VS 2017 (15.2+).



来源:https://stackoverflow.com/questions/46115024/providing-a-code-analysis-ruleset-to-a-net-core-project-through-nuget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!