TSKeyValueTableGenerater.cs 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System.Text;
  2. namespace etoy
  3. {
  4. class TSKeyValueTableGenerater : IGenerater
  5. {
  6. public void Generate(Context context)
  7. {
  8. var tables = context.Blackboard.KeyValueTables;
  9. foreach (var table in tables)
  10. GenSingle(context, table);
  11. }
  12. void GenSingle(Context context, KeyValueTable table)
  13. {
  14. const string FIELD_REPEATED = "[]";
  15. string fileName = "KeyValue.ts";
  16. string directory = context.Option.ServerCodeOutput;
  17. string path = Path.Combine(directory, fileName);
  18. if (!Directory.Exists(directory))
  19. Directory.CreateDirectory(directory);
  20. //using var writer = new TSCodeWriter(path);
  21. var sb = new StringBuilder();
  22. sb.AppendLine("// Generate By EToy");
  23. sb.AppendLine("// Don't Edit It!!");
  24. sb.AppendLine();
  25. // class
  26. sb.AppendLine("export default class KeyValue {");
  27. {
  28. for (int i = 0, length = table.Rows.Length; i < length; i++)
  29. {
  30. var row = table.Rows[i];
  31. if (!row.IsServerField)
  32. continue;
  33. string summary = row.Description;
  34. string fieldType = row.Type;
  35. string fieldName = row.Key;
  36. string content = row.Value;
  37. // summary
  38. sb.AppendLine(" /**");
  39. sb.AppendLine($" * {summary}");
  40. sb.AppendLine($" * {content}");
  41. sb.AppendLine(" */");
  42. // field
  43. var fieldValue = string.Empty;
  44. var repeadIdx = fieldType.IndexOf(FIELD_REPEATED);
  45. if (repeadIdx > 0)
  46. { // 是数组类型
  47. fieldValue = content;
  48. }
  49. else
  50. {
  51. switch (fieldType)
  52. {
  53. case FieldTypeDefine.Boolean:
  54. fieldValue = (content == "1" || content == "true") ? "true" : "false";
  55. break;
  56. case FieldTypeDefine.Int:
  57. case FieldTypeDefine.Long:
  58. case FieldTypeDefine.Float:
  59. case FieldTypeDefine.Double:
  60. fieldValue = content;
  61. break;
  62. case FieldTypeDefine.String:
  63. fieldValue = content.Replace("\"", "\\\""); // "前面多加个反斜杠
  64. fieldValue = $"\"{fieldValue}\"";
  65. break;
  66. default:
  67. throw new NotSupportedException($"KeyValue表TS代码生成失败, 不支持string/int外的类型{row.Type}字段。{table.Path}");
  68. }
  69. }
  70. sb.AppendLine($" public static {fieldName} = {fieldValue};");
  71. // enter
  72. if (i < length - 1)
  73. sb.AppendLine();
  74. }
  75. sb.AppendLine("}");
  76. }
  77. File.WriteAllText(path, sb.ToString(), Encoding.UTF8);
  78. }
  79. }
  80. }