I wonder if there is a native way how to store and access additional settings for custom roslyn analyzers. Let's say I have rule with diagnostic Id 'XA0001' and in editor config I will set
dotnet_diagnostic.XA0001.severity = error
So far, everyhting is ok. Now I would like to add something like this to create settings for that new rule:
dotnet_diagnostic.XA0001.scope = class, enum, interface
dotnet_diagnostic.XA0001.level = toplevel
where scope and level are additional properties for my rule that I need to be configurable (ususally a string or enumeration of some sort) because they can VARY. Everytime there will be default settings of that rule that are overridable by editorconfig.
Is it possible and if so is there any super short example ev. a link to a post how to access additional editorconfig settings in analyzer class or simply from that project level?
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class RuleXA0001Analyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(RuleXA0001.Descriptor);
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
//TODO access editorconfig settings for this rule
//Perform analysis & report diagnostics
}
}
}
No need to access other rules settings even it might be benefitial in other cases.
Thanks
The AnalyzerOptions
class has a property AnalyzerConfigOptionsProvider
, which can be used to access .editorconfig settings.
For example, if you're analyzing a code block, you can do something like this:
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationStartAction(RegisterCompilationStart);
}
private static void RegisterCompilationStart(CompilationStartAnalysisContext startContext)
{
var optionsProvider = startContext.Options.AnalyzerConfigOptionsProvider;
startContext.RegisterCodeBlockAction(actionContext => AnalyzeCodeBlock(actionContext, optionsProvider));
}
private static void AnalyzeCodeBlock(CodeBlockAnalysisContext context, AnalyzerConfigOptionsProvider optionsProvider)
{
// The options contains the .editorconfig settings
var options = optionsProvider.GetOptions(context.CodeBlock.SyntaxTree);
var isFound = options.TryGetValue("dotnet_diagnostic.XA0001.level", out var value);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With