Add code analysis ruleset through nuget package

2019-02-06 21:15发布

问题:

I'm trying to build a NuGet package that adds our company's code analysis dictionary automatically and updatable.

The rule set is added in the content folder and now I want to use the install.ps1 script to add the rule set in the project file.
I figured out the way to go would be to use the envDTE, but I can't find much useful documentation about it other then this overwhelming object graph in which I can't find the CodeAnalysisRuleset node.
http://msdn.microsoft.com/en-us/library/za2b25t3(v=vs.100).aspx

Am I pursuing the right path?
Is there any relevant tutorial/documentation on how to use the envDTE in NuGet powershell?
How can I run/debug my install script without having to actually add it to a package and install it against a project?

Sidenote
Although @Nicole Calinoiu showed the better way, this morsel of information might come in handy later on:

foreach ($config in $project.ConfigurationManager){
  $config.Properties.Item("CodeAnalysisRuleSet").Value = "myruleset.ruleset"
}

回答1:

There's no need to script this. Both the ruleset and dictionary can be registered via an imported MSBuild .props file, as described at https://docs.microsoft.com/en-us/nuget/create-packages/creating-a-package#including-msbuild-props-and-targets-in-a-package.

For example, your NuGet source folder structure might look like this (assuming "CodeAnalysisSettings" is your package ID):

  • build
    • CodeAnalysisSettings.props
  • content
    • MyCustomDictionary.xml
    • MyRules.ruleset

where the contents of CodeAnalysisSettings.props are something like the following:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <PropertyGroup>
        <RunCodeAnalysis>true</RunCodeAnalysis>
        <CodeAnalysisRuleSet>MyRules.ruleset</CodeAnalysisRuleSet>
    </PropertyGroup>
    <ItemGroup>
        <CodeAnalysisDictionary Include="MyCustomDictionary.xml" />
    </ItemGroup>
</Project>


回答2:

I had the same problem as reported in the comments: the dictionary was added as content, not as a CodeAnalysisDictionary.

I added this piece of code in the install.ps1 of the nuget package to solve this:

$dictionary = $project.ProjectItems | Where-Object {$_.Name.EndsWith("CustomDictionary.xml")}
$dictionary.Properties.Item("Buildaction").Value = [int]5;


回答3:

You can also do it manually by using the following steps.

  • Right click project
  • Go to properties
  • Go to the dropdown [Run this rule set]
  • Select the [Browse..] option
  • Choose your company ruleset which you may place at a predefined location in source code.
  • Click Open on the Open window
  • Save the project file.

You may repeat the step for other projects in the solution.