using System.Text; namespace etoy { class TSKeyValueTableGenerater : IGenerater { public void Generate(Context context) { var tables = context.Blackboard.KeyValueTables; foreach (var table in tables) GenSingle(context, table); } void GenSingle(Context context, KeyValueTable table) { const string FIELD_REPEATED = "[]"; string fileName = "KeyValue.ts"; string directory = context.Option.ServerCodeOutput; string path = Path.Combine(directory, fileName); if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); //using var writer = new TSCodeWriter(path); var sb = new StringBuilder(); sb.AppendLine("// Generate By EToy"); sb.AppendLine("// Don't Edit It!!"); sb.AppendLine(); // class sb.AppendLine("export default class KeyValue {"); { for (int i = 0, length = table.Rows.Length; i < length; i++) { var row = table.Rows[i]; if (!row.IsServerField) continue; string summary = row.Description; string fieldType = row.Type; string fieldName = row.Key; string content = row.Value; // summary sb.AppendLine(" /**"); sb.AppendLine($" * {summary}"); sb.AppendLine($" * {content}"); sb.AppendLine(" */"); // field var fieldValue = string.Empty; var repeadIdx = fieldType.IndexOf(FIELD_REPEATED); if (repeadIdx > 0) { // 是数组类型 fieldValue = content; } else { switch (fieldType) { case FieldTypeDefine.Boolean: fieldValue = (content == "1" || content == "true") ? "true" : "false"; break; case FieldTypeDefine.Int: case FieldTypeDefine.Long: case FieldTypeDefine.Float: case FieldTypeDefine.Double: fieldValue = content; break; case FieldTypeDefine.String: fieldValue = content.Replace("\"", "\\\""); // "前面多加个反斜杠 fieldValue = $"\"{fieldValue}\""; break; default: throw new NotSupportedException($"KeyValue表TS代码生成失败, 不支持string/int外的类型{row.Type}字段。{table.Path}"); } } sb.AppendLine($" public static {fieldName} = {fieldValue};"); // enter if (i < length - 1) sb.AppendLine(); } sb.AppendLine("}"); } File.WriteAllText(path, sb.ToString(), Encoding.UTF8); } } }