Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Linq;
- using System.Reflection;
- using TypeLite;
- using TypeLite.TsModels;
- namespace MyApp.Devel.TypeLite
- {
- public class CustomScriptGenerator : TsGenerator
- {
- public CustomScriptGenerator()
- {
- }
- public string GenerateEnumsCustom(TsModel model)
- {
- var sb = new ScriptBuilder(IndentationString);
- foreach (var module in model.Modules)
- this.AppendCustomEnumModule(module, sb);
- return sb.ToString();
- }
- private void AppendCustomEnumModule(TsModule module, ScriptBuilder sb)
- {
- var enums = module.Enums.Where(e => !_typeConvertors.IsConvertorRegistered(e.Type) && !e.IsIgnored).ToList();
- var moduleName = GetModuleName(module);
- if (moduleName != module.Name)
- {
- _renamedModules.Add(module.Name, moduleName);
- }
- if (enums.Any())
- {
- sb.AppendLine(string.Format("module {0} {{", moduleName));
- using (sb.IncreaseIndentation())
- {
- foreach (var enumModel in enums)
- {
- this.AppendCustomEnumDefinition(enumModel, sb);
- }
- }
- sb.AppendLine("}");
- sb.AppendLine(string.Format("export = {0};", moduleName));
- }
- }
- private void AppendCustomEnumDefinition(TsEnum enumModel, ScriptBuilder sb)
- {
- var typeName = this.GetTypeName(enumModel);
- var descriptionDictionary = new Dictionary<string, string>();
- sb.AppendLineIndented(string.Format("export module {0} {{", typeName));
- using (sb.IncreaseIndentation())
- {
- sb.AppendLineIndented("export enum Enum {");
- using (sb.IncreaseIndentation())
- {
- var i = 1;
- foreach (var v in enumModel.Values)
- {
- sb.AppendLineIndented(string.Format(i < enumModel.Values.Count ? "{0} = {1}," : "{0} = {1}", v.Name, v.Value));
- i++;
- var description = v.Field.GetCustomAttributes(typeof(DescriptionAttribute))
- .Cast<DescriptionAttribute>()
- .Select(attribute => attribute.Description.Replace("\"", "\\\""))
- .FirstOrDefault();
- description = description ?? v.Name;
- descriptionDictionary.Add(v.Name, description);
- }
- }
- sb.AppendLineIndented("}");
- sb.AppendLine();
- sb.AppendLineIndented("export function describe (enumValue: Enum) {");
- using (sb.IncreaseIndentation())
- {
- sb.AppendLineIndented("switch (enumValue) {");
- using (sb.IncreaseIndentation())
- {
- foreach (var key in descriptionDictionary.Keys)
- {
- sb.AppendLineIndented(string.Format("case Enum.{0}:", key));
- using (sb.IncreaseIndentation())
- {
- sb.AppendLineIndented(string.Format("return \"{0}\";", descriptionDictionary[key]));
- }
- }
- sb.AppendLineIndented("default:");
- using (sb.IncreaseIndentation())
- {
- sb.AppendLineIndented("throw Error(\"Unknown Enum Value\");");
- }
- }
- sb.AppendLineIndented("}");
- }
- sb.AppendLineIndented("}");
- }
- sb.AppendLineIndented("}");
- _generatedEnums.Add(enumModel);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement