otac0n / Weave

Weave is a text templating engine for .NET that is all about attention to detail. Weave handles the tricky work of making your rendered text beautiful.
MIT License
22 stars 4 forks source link

Source Generators #14

Closed otac0n closed 10 months ago

otac0n commented 11 months ago

Basic Approach:

<Project>
  <ItemGroup>
    <AvailableItemName Include="WeaveTemplate" />
    <CompilerVisibleItemMetadata Include="WeaveTemplate" MetadataName="OutputPath" />
    <CompilerVisibleItemMetadata Include="AdditionalFiles" MetadataName="SourceItemGroup" />
  </ItemGroup>
  <Target Name="_InjectWeaveTemplateAdditionalFiles" BeforeTargets="GenerateMSBuildEditorConfigFileShouldRun">
    <ItemGroup>
      <AdditionalFiles Include="@(WeaveTemplate)" SourceItemGroup="WeaveTemplate" />
    </ItemGroup>
  </Target>
</Project>
[Generator(LanguageNames.CSharp)]
internal class TestGenerator : IIncrementalGenerator
{
    private const string OutputPath = "build_metadata.WeaveTemplate.OutputPath";

    public void Initialize(IncrementalGeneratorInitializationContext context)
    {
        var weaveFiles = context.AdditionalTextsProvider
            .Combine(context.AnalyzerConfigOptionsProvider)
            .Where(p => p.Right.GetOptions(p.Left).Keys.Contains(OutputPath, StringComparer.InvariantCultureIgnoreCase))
            .Select((p, ct) => (p.Left.Path, Text: p.Left.GetText(ct)));

        context.RegisterSourceOutput(
            weaveFiles,
            static (context, file) => CompileWeaveFile(context, file.Path, file.Text));
    }

    private static void CompileWeaveFile(SourceProductionContext context, string path, SourceText? text)
    {
        if (text != null)
        {
            context.AddSource(Path.GetFileName(path) + ".g.cs", Compiler.Compile(text.ToString(), path));
        }
    }
}
otac0n commented 11 months ago

Real talk: I want to make sure we maintain backwards compatibility with .NET 4.8 but that's not the easiest thing to do with the old/new MSBUILD properties.

otac0n commented 11 months ago

Feature branch here: https://github.com/otac0n/Weave/tree/feature-source-generators