Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
TextTemplateSample/RecordGenConsole/RecordTypes.tt
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Linq" #>
<#@ output extension=".cs" #>
<#
var types = GetTypeDefs(Host.ResolvePath("RecordTypes.md"));
#>
using System;
namespace RecordGenConsole
{
<# foreach (var type in types) { #>
public partial class <#= type.Key #>
{
<# foreach (var prop in type.Value) { #>
public <#= prop.Value #> <#= prop.Key #> { get; }
<# } #>
public <#= type.Key #>(<#= string.Join(", ", type.Value.Select(p => $"{p.Value} {ToCamel(p.Key)}")) #>)
{
<# foreach (var prop in type.Value) { #>
<#= prop.Key #> = <#= ToCamel(prop.Key) #>;
<# } #>
}
}
<# } #>
}
<#+
Dictionary<string, Dictionary<string, string>> GetTypeDefs(string filePath)
{
var lines = File.ReadLines(filePath)
.Where(l => !string.IsNullOrWhiteSpace(l))
.ToArray();
var typeLines = lines
.Select((l, i) => new { l, i })
.Where(_ => !_.l.StartsWith("-"))
.ToArray();
return typeLines
.ToDictionary(_ => ToPascal(_.l.Trim()), _ => GetProps(_.i));
Dictionary<string, string> GetProps(int i) => lines
.Skip(i + 1)
.TakeWhile(l => l.StartsWith("-"))
.Select(l => l.Trim('-', ' ').Split())
.ToDictionary(p => ToPascal(GetPropName(p)), p => p[0]);
}
string GetPropName(string[] prop) => prop[prop.Length == 1 ? 0 : 1];
string ToPascal(string s) => char.ToUpperInvariant(s[0]) + s.Substring(1);
string ToCamel(string s) => char.ToLowerInvariant(s[0]) + s.Substring(1);
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment