Templating Roslyn Source Code Generators
I want that , when I generate code with Roslyn, to have a template that I can easy modify to generate code . Also, I want to let the user ( the programmer , in this case) modify this template – maybe he has better ideas than me.
For reading from the RSCG, is pretty simple: Make as an embedded resource and read with
internal class EmbedReader
{
static Assembly assembly;
static EmbedReader()
{
assembly = Assembly.GetExecutingAssembly();}
public static string ContentFile(string name)
{
var resourceName = name;using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
string result = reader.ReadToEnd();
//this is the content
}
}
}
For let the programmer user put his template, put as as additional file in the csproj
<ItemGroup>
<AdditionalFiles Include=”context.txt” /></ItemGroup>
and read with
var file = context.AdditionalFiles.Where(it => it.Path.EndsWith($”{val}.txt”))
.Select(it => it.GetText())
.FirstOrDefault();
if (file != null)
{
content = string.Join(Environment.NewLine, file.Lines.Select(it => it.ToString()));
}
To do both,if the result of the first is empty, read the second (or opposite ? )
Leave a Reply