We will use Text Template Transformation Toolkit also known as T4.
-
Create a console application.
dotnet new console -o MyTool
-
Create a template file
ClassTemplate.tt
in the project directory.
<#@ output extension=".cs" #> <#@ template language="C#" hostspecific="true" #> <#@parameter type="System.String" name="ClassName" #> public class <#=ClassName#> { }
-
To process the template, we need a templating engine, Mono.TextTemplating is an open source implementation for that.
dotnet add package Mono.TextTemplating
-
In
Program.cs
, write the code for processing the template.
var className = args[0]; var templatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ClassTemplate.tt"); var outputPath = Path.Combine(Directory.GetCurrentDirectory(), className); var generator = new Mono.TextTemplating.TemplateGenerator(); var session = generator.GetOrCreateSession(); session.Add("ClassName", className); generator.ProcessTemplate(templatePath, outputPath);
-
Go to the desired directory and run:
ProjectA> dotnet run path/to/MyTool Person
This creates Person.cs in ProjectA directory:
public class Person { }
If you want to install and run it as a dotnet tool, read this.
Top comments (0)