Skip to content

Support generating non-source files #57608

@geeknoid

Description

@geeknoid

We have a few use cases where we'd like to leverage source generators to produce non-source files. Basically, we want to use source generators to generate secondary build outputs. For example:

  • We annotate data models with data classification attributes to denote PII and we produce a CSV file that enumerates the types and members in the project and their data classification. You can then take this CSV file and use it when doing privacy audits.

  • We use source generators to produce a bunch of code around metrics. We'd like to emit a schema file describing the effective shape of the metrics being produced by the code. This would probably be in the form of an output JSON file.

We have a few other scenarios in the wings which could leverage this approach.

Unfortunately, source generation is currently limited to C# sources. Trying to emit files with other extensions doesn't work. As a result, our source generator currently contains this horrible hack:

        public void Execute(GeneratorExecutionContext context)
        {
            ... generate the CSV file ...

            context.CancellationToken.ThrowIfCancellationRequested();

            /// Adding the workaround to generate reports via File writes since <see cref="GeneratorExecutionContext.AddSource(string, CodeAnalysis.Text.SourceText)"/>
            /// has an underlying check for `.cs` files and automatically adds the `.cs` suffix if the provided filename has some other filetype.
            /// Refer <see href="https://github.com/dotnet/roslyn/blob/v3.8.0/src/Compilers/Core/Portable/SourceGeneration/AdditionalSourcesCollection.cs#L63">AppendExtensionIfRequired</see>.
            _directory ??= FileUtilHelpers.GetOutputDirectoryForGeneratedFile(typeof(Generator), context.Compilation.Assembly, context.Compilation.Options.OptimizationLevel);
            _ = Directory.CreateDirectory(_directory);

            // Write properties to CSV file.
            File.WriteAllText(Path.Combine(_directory, _propertiesFileName), properties);

            // Write log methods to CSV file.
            File.WriteAllText(Path.Combine(_directory, _logMethodsFileName), logMethods);
      }

Could we get 1st class support for producing more than .cs files?

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions