SourceGenerator.md

February 10, 2024 · View on GitHub

NTypewriter.SourceGenerator

Warning NTypewriter.SourceGenerator is at early stage of its development, not everything may works as intended, and breaking changes may happen very often.

NTypewriter.SourceGenerator allows to run NTypewriter as part of a C# compilation process. It is fully autonomous and does not require installation of any extensions for IDE or CI/Pipeline.

For performance reasons, NTypewriter.SourceGenerator renders/generates files only during build that emits assemblies, which is contrary to other source generators that usually do generation on every change in source code. NTypewriter.SourceGenerator always does render/generation on the first run, which usually happens during IDE startup, and may affect its time.

NTypewriter.SourceGenerator runs in the context of a project to which it is added, it does not have access to a solution or other projects from solution, which is contrary to NTypewriter editor.

 standard SourceGeneratorNTypewriter.SourceGeneratorNTypewriter editor for VS
outputreadonly file included in compilationregular fileregular file
scopeprojectprojectsolution
runs
during buildyesyesyes (opt-in)
on every change in source codeyesnono
when template (*.nt) is savednonoyes (opt-in)
on demendnonoyes

Nugets

https://www.nuget.org/packages/NTypewriter.SourceGenerator

How to use it?

Just instal nuget to the project that contains *.nt templates.

Templates (*.nt) discovery

Template file (*.nt) must be added to project with the property Build action set to C# analyzer additional file in VS, in .csproj it looks like that:

<Project Sdk="Microsoft.NET.Sdk">
  <ItemGroup>
    <AdditionalFiles Include="sample_template.nt" />   
  </ItemGroup>
</Project>

User code (*.nt.cs) discovery

User code (*.nt.cs) must be added to project with the property Build action set to C# compiler in VS, which is a default value for .cs file.

Configuration

Option 
AddGeneratedFilesToVSProjectignored, source generator does not have access to project file
NamespacesToBeSearchedworks as expected
ProjectsToBeSearchedworks, but source generator has access only to single project
SearchInReferencedProjectsAndAssembliesworks as expected
RenderWhenTemplateIsSavedignored, source generator does not render when template is saved
RenderWhenProjectBuildIsDoneignored, source generator always renders during a build

Diagnostics

*.ntsg.log file can be found alongside of generated assemblies in the project outputPath.

Proof of concept

Sample project that generates files during GitHub Actions workflows: