Search code examples
c#sourcegeneratorscsharp-source-generator

Is there a way to configure a Source Generator from the consuming project?


I can configure a source generator by looking for a JSON file and using that, but this method is limited and generally slow to implement.

What I’m looking for is something like fluent syntax on the consuming project, e.g.

generator.UseFormat(c)

As far as I know this doesn’t exist, but I will be happy to be proven otherwise.

One hacky solution I’ve theorised is using another source generator for the fluent configuration to then configure the original source generator. This could work but would be so convoluted there has to be another way.


Solution

  • There are a two good options I believe:

    • Read the code. Source Generators have access to all the code, and it'd be possible to just detect generator.UseFormat(c)..., but that's probably quite difficult. You could also read Attributes here, or read the values of constants, etc. Depends on your needs really.

    • Use .editorconfig. Source Generators get access to the editorconfig, just like analyzers. you can put settings such as format in there. This is probably the easiest. (this works by using sourceGeneratorContext.AnalyzerConfigOptions.GetOptions(SyntaxTree))

    There are other options, like accessing MSBuild stuff to put the configuration in csproj & friends, but that seems pointless and is probably difficult to do.