Kirk Woll
Kirk Woll

Reputation: 77546

How to make an analyzer project-specific?

Microsoft.CodeAnalysis (née Roslyn) allows you to create "analyzers" to inspect your code within Visual Studio and (optionally) provide code-fixes to automatically solve the issue.

Generally-speaking, any analyzer you create will always be active in every project. However, sometimes you may want to create a set of analyzers for your team that you want to be active only for that team's projects. The only way I could find of being able to do that was to make use of a custom preprocessor symbol.

So, for your team's projects, you could add an entry in "Conditional compilation symbols" for your team, such as MYTEAM.

Next in your analyzer, your context should provide you with some AST node from which you can obtain the current syntax tree. From the syntax tree, you can get its options, which include the set of active preprocessor symbols ("Conditional compilation symbols"). Thus, to make an analyzer specific to your team, simply abort if you don't find your custom symbol:

private void Action(SyntaxNodeAnalysisContext context)
{
    if (!context.Node.SyntaxTree.Options.PreprocessorSymbolNames.Contains("MYTEAM"))
    {
        return;
    }

    // Code for your team-specific analyzer follows
}

This feels like a hack, so I'd like to know if this is the idiomatic way to constrain an analyzer using Roslyn. Or perhaps there's a better way? (And by "better" way, I mean being able to determine whether or not to use your analyzer without having to modify the "Conditional compilation symbols". Perhaps by interrogating the existence of a custom assembly-level attribute.)

Upvotes: 2

Views: 556

Answers (1)

Kevin Pilch
Kevin Pilch

Reputation: 11605

If you add the analyzer to the project's command line options (right click on the Analyzers node under References in Solution Explorer, or via a NuGet package), instead of installing your vsix, then it will be tied to that project. Additionally, it will run as part of command line and continuous integration builds too.

Upvotes: 3

Related Questions