Created
September 7, 2018 06:18
-
-
Save sakapon/c6574bc3c84e1da5f8ef2255a2f4315e to your computer and use it in GitHub Desktop.
TextTemplateSample/RecordGenConsole/RecordTypes.tt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<#@ 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