From 731c00cf52358b83c808faaa3725df8c5718f1b8 Mon Sep 17 00:00:00 2001 From: Igor Derkach Date: Sat, 14 Dec 2024 17:57:12 +0400 Subject: [PATCH] Intermediate commit --- assets/default_config.yaml | 16 +-- cmd/go-asyncapi/generate.go | 31 +++-- go.mod | 1 + go.sum | 2 + internal/asyncapi/amqp/channel.go | 34 +++--- internal/asyncapi/amqp/message.go | 2 +- internal/asyncapi/bindings.go | 4 +- internal/asyncapi/channel.go | 50 ++++---- internal/asyncapi/correlationid.go | 4 +- internal/asyncapi/extra.go | 4 +- internal/asyncapi/http/channel.go | 2 +- internal/asyncapi/kafka/channel.go | 12 +- internal/asyncapi/kafka/message.go | 2 +- internal/asyncapi/kafka/server.go | 2 +- internal/asyncapi/message.go | 42 +++---- internal/asyncapi/mqtt/channel.go | 4 +- internal/asyncapi/mqtt/server.go | 4 +- internal/asyncapi/object.go | 56 ++++----- internal/asyncapi/parameter.go | 12 +- internal/asyncapi/protobuilder.go | 22 ++-- internal/asyncapi/server.go | 19 +-- internal/asyncapi/servervariable.go | 10 +- internal/asyncapi/ws/channel.go | 4 +- internal/common/compile_context.go | 8 +- internal/common/render.go | 2 + internal/render/amqp/channel.go | 22 ++-- internal/render/amqp/server.go | 8 +- internal/render/asyncapi.go | 4 + internal/render/bindings.go | 18 +-- internal/render/channel.go | 39 +++--- internal/render/context/context.go | 81 +++++++++---- internal/render/correlationid.go | 43 ++++--- internal/render/http/channel.go | 12 +- internal/render/http/server.go | 8 +- internal/render/ip/channel.go | 12 +- internal/render/ip/server.go | 8 +- internal/render/kafka/channel.go | 14 +-- internal/render/kafka/server.go | 8 +- internal/render/lang/base.go | 35 ++---- internal/render/lang/goarray.go | 47 +------- internal/render/lang/gomap.go | 40 +------ internal/render/lang/gopointer.go | 28 +---- internal/render/lang/gosimple.go | 43 ++----- internal/render/lang/gostruct.go | 61 +++------- internal/render/lang/gotypealias.go | 43 +------ internal/render/lang/gounion.go | 38 ++---- internal/render/lang/govalue.go | 47 +++++--- internal/render/lang/promise.go | 68 +++++++---- internal/render/message.go | 47 ++++---- internal/render/mqtt/channel.go | 14 +-- internal/render/mqtt/server.go | 8 +- internal/render/parameter.go | 28 +++-- internal/render/proto/channel.go | 20 ++-- internal/render/proto/server.go | 18 +-- internal/render/redis/channel.go | 12 +- internal/render/redis/server.go | 8 +- internal/render/server.go | 25 ++-- internal/render/servervariable.go | 12 +- internal/render/tcp/channel.go | 12 +- internal/render/tcp/server.go | 8 +- internal/render/udp/channel.go | 12 +- internal/render/udp/server.go | 8 +- internal/render/ws/channel.go | 12 +- internal/render/ws/server.go | 8 +- internal/selector/selector.go | 17 +-- internal/tmpl/context.go | 49 ++++++++ internal/tmpl/functions.go | 177 ++++++++++++++++++++++++++++ internal/{tpl => tmpl}/load.go | 2 +- internal/{tpl => tmpl}/sprout.go | 2 +- internal/tpl/context.go | 47 -------- internal/tpl/functions.go | 131 -------------------- internal/utils/names.go | 9 +- internal/utils/render.go | 6 +- internal/writer/render.go | 162 ++++++++++++++++--------- templates/amqp/amqp_channel.tmpl | 53 +++++---- templates/amqp/amqp_server.tmpl | 34 +++--- templates/channel.tmpl | 69 +++++------ templates/common/proto.tmpl | 159 ++++++++++++------------- templates/http/http_channel.tmpl | 11 +- templates/http/http_server.tmpl | 35 +++--- templates/ip/ip_channel.tmpl | 11 +- templates/ip/ip_server.tmpl | 34 +++--- templates/kafka/kafka_channel.tmpl | 53 +++++---- templates/kafka/kafka_server.tmpl | 34 +++--- templates/lang/goarray.tmpl | 30 ++--- templates/lang/gomap.tmpl | 28 ++--- templates/lang/gopointer.tmpl | 6 + templates/lang/gosimple.tmpl | 16 +-- templates/lang/gostruct.tmpl | 50 ++++---- templates/lang/gotypealias.tmpl | 30 ++--- templates/lang/gounion.tmpl | 10 +- templates/lang/govalue.tmpl | 117 +++++++++--------- templates/main.tmpl | 34 +++--- templates/message.tmpl | 76 ++++++------ templates/mqtt/mqtt_channel.tmpl | 47 ++++---- templates/mqtt/mqtt_server.tmpl | 34 +++--- templates/parameter.tmpl | 14 +-- templates/preamble.tmpl | 12 ++ templates/preambule.tmpl | 12 -- templates/redis/redis_channel.tmpl | 11 +- templates/redis/redis_server.tmpl | 34 +++--- templates/schema.tmpl | 2 +- templates/server.tmpl | 53 +++++---- templates/tcp/tcp_channel.tmpl | 11 +- templates/tcp/tcp_server.tmpl | 34 +++--- templates/udp/udp_channel.tmpl | 11 +- templates/udp/udp_server.tmpl | 34 +++--- templates/ws/ws_channel.tmpl | 11 +- templates/ws/ws_server.tmpl | 34 +++--- 109 files changed, 1593 insertions(+), 1581 deletions(-) create mode 100644 internal/tmpl/context.go create mode 100644 internal/tmpl/functions.go rename internal/{tpl => tmpl}/load.go (97%) rename internal/{tpl => tmpl}/sprout.go (99%) delete mode 100644 internal/tpl/context.go delete mode 100644 internal/tpl/functions.go create mode 100644 templates/lang/gopointer.tmpl create mode 100644 templates/preamble.tmpl delete mode 100644 templates/preambule.tmpl diff --git a/assets/default_config.yaml b/assets/default_config.yaml index ddda767..cc4a8fc 100644 --- a/assets/default_config.yaml +++ b/assets/default_config.yaml @@ -1,18 +1,18 @@ render: selections: - objectKindRe: schema - file: schemas/{{.Name | toSnakeCase}}.go + file: schemas/{{. | goid | toSnakeCase}}.go - objectKindRe: parameter - file: parameters/{{.Name | toSnakeCase}}.go + file: parameters/{{. | goid | toSnakeCase}}.go - objectKindRe: channel - file: channels/{{.Name | toSnakeCase}}.go + file: channels/{{. | goid | toSnakeCase}}.go - objectKindRe: protoChannel - file: channels/{{.Name | toSnakeCase}}.go + file: channels/{{. | goid | toSnakeCase}}.go - objectKindRe: server - file: servers/{{.Name | toSnakeCase}}.go + file: servers/{{. | goid | toSnakeCase}}.go - objectKindRe: protoServer - file: servers/{{.Name | toSnakeCase}}.go + file: servers/{{. | goid | toSnakeCase}}.go - objectKindRe: message - file: messages/{{.Name | toSnakeCase}}.go + file: messages/{{. | goid | toSnakeCase}}.go - objectKindRe: protoMessage - file: messages/{{.Name | toSnakeCase}}.go + file: messages/{{. | goid | toSnakeCase}}.go diff --git a/cmd/go-asyncapi/generate.go b/cmd/go-asyncapi/generate.go index 4dbcc82..3cb26ad 100644 --- a/cmd/go-asyncapi/generate.go +++ b/cmd/go-asyncapi/generate.go @@ -59,7 +59,7 @@ type GenerateCmd struct { type generatePubSubArgs struct { Spec string `arg:"required,positional" help:"AsyncAPI specification file path or url" placeholder:"PATH"` - ProjectModule string `arg:"-M,--project-module" help:"Project module name to use [default: extracted from go.mod file in the current working directory]" placeholder:"MODULE"` + ProjectModule string `arg:"-M,--module" help:"Module path to use [default: extracted from go.mod file in the current working directory concatenated with target dir]" placeholder:"MODULE"` TemplateDir string `arg:"--template-dir" help:"Directory with custom templates" placeholder:"DIR"` ConfigFile string `arg:"--config-file" help:"YAML configuration file path" placeholder:"PATH"` generateObjectSelectionOpts @@ -154,7 +154,7 @@ func generate(cmd *GenerateCmd) error { } // Rendering - files, err := writer.RenderPackages(mainModule, renderOpts) + files, err := writer.RenderFiles(mainModule, renderOpts) if err != nil { return fmt.Errorf("schema render: %w", err) } @@ -304,7 +304,7 @@ func generationWriteImplementations(selectedImpls map[string]string, protocols [ return nil } -func getImportBase() (string, error) { +func getProjectModule() (string, error) { pwd, err := os.Getwd() if err != nil { return "", fmt.Errorf("cannot get current working directory: %w", err) @@ -437,7 +437,12 @@ func getRenderOpts(opts generatePubSubArgs, targetDir string) (common.RenderOpts return res, err } for _, item := range conf.Render.Selections { - pkg, _ := lo.Coalesce(item.Package, lo.Ternary(targetDir != "", path.Base(targetDir), defaultPackage)) + pkg, _ := lo.Coalesce( + item.Package, + lo.Ternary(path.Dir(item.File) != ".", path.Dir(item.File), ""), + lo.Ternary(targetDir != "", path.Base(targetDir), ""), + defaultPackage, + ) templateName, _ := lo.Coalesce(item.Template,defaultTemplate) sel := common.RenderSelectionConfig{ Template: templateName, @@ -453,16 +458,20 @@ func getRenderOpts(opts generatePubSubArgs, targetDir string) (common.RenderOpts } // ImportBase - importBase := opts.ProjectModule - if importBase == "" { - b, err := getImportBase() + res.ImportBase = opts.ProjectModule + if res.ImportBase == "" { + m, err := getProjectModule() if err != nil { - return res, fmt.Errorf("determine project's module (use -M arg to override): %w", err) + return res, fmt.Errorf("getting project module from ./go.mod (use -M arg to override): %w", err) } - importBase = b + // Clean path and remove empty, current and parent directories, leaving only names + // This is not a best solution, however, it should work for most cases. Moreover, user can always override it. + parts := lo.Filter(strings.Split(path.Clean(targetDir), string(os.PathSeparator)), func(s string, _ int) bool { + return !lo.Contains([]string{"", ".", ".."}, s) + }) + res.ImportBase = path.Join(m, path.Join(parts...)) } - mainLogger.Debugf("Target import base is %s", importBase) - res.ImportBase = importBase + mainLogger.Debugf("Target import base is %s", res.ImportBase) return res, nil } diff --git a/go.mod b/go.mod index 7499ea8..b64b031 100644 --- a/go.mod +++ b/go.mod @@ -36,6 +36,7 @@ require ( github.com/gobwas/httphead v0.1.0 // indirect github.com/gobwas/pool v0.2.1 // indirect github.com/gorilla/websocket v1.5.1 // indirect + github.com/iancoleman/strcase v0.3.0 // indirect github.com/klauspost/compress v1.17.8 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/lucasb-eyer/go-colorful v1.2.0 // indirect diff --git a/go.sum b/go.sum index 7607dec..105d967 100644 --- a/go.sum +++ b/go.sum @@ -53,6 +53,8 @@ github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWm github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY= github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY= +github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= +github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= github.com/klauspost/compress v1.17.4 h1:Ej5ixsIri7BrIjBkRZLTo6ghwrEtHFk7ijlczPW4fZ4= github.com/klauspost/compress v1.17.4/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM= github.com/klauspost/compress v1.17.8 h1:YcnTYrq7MikUT7k0Yb5eceMmALQPYBW/Xltxn0NAMnU= diff --git a/internal/asyncapi/amqp/channel.go b/internal/asyncapi/amqp/channel.go index fc288bf..b2c057a 100644 --- a/internal/asyncapi/amqp/channel.go +++ b/internal/asyncapi/amqp/channel.go @@ -57,9 +57,9 @@ func (pb ProtoBuilder) BuildChannel(ctx *common.CompileContext, channel *asyncap chanStruct.Fields = append( chanStruct.Fields, - lang.GoStructField{Name: "exchange", Type: &lang.GoSimple{Name: "string"}}, - lang.GoStructField{Name: "queue", Type: &lang.GoSimple{Name: "string"}}, - lang.GoStructField{Name: "routingKey", Type: &lang.GoSimple{Name: "string"}}, + lang.GoStructField{Name: "exchange", Type: &lang.GoSimple{OriginalName: "string"}}, + lang.GoStructField{Name: "queue", Type: &lang.GoSimple{OriginalName: "string"}}, + lang.GoStructField{Name: "routingKey", Type: &lang.GoSimple{OriginalName: "string"}}, ) return &render.ProtoChannel{ @@ -76,30 +76,30 @@ func (pb ProtoBuilder) BuildChannelBindings(ctx *common.CompileContext, rawData return } - vals = &lang.GoValue{Type: &lang.GoSimple{Name: "ChannelBindings", Import: ctx.RuntimeModule(pb.ProtoName)}, EmptyCurlyBrackets: true} + vals = &lang.GoValue{Type: &lang.GoSimple{OriginalName: "ChannelBindings", Import: ctx.RuntimeModule(pb.ProtoName)}, EmptyCurlyBrackets: true} switch bindings.Is { case "queue": - vals.StructValues.Set("ChannelType", &lang.GoSimple{Name: "ChannelTypeQueue", Import: ctx.RuntimeModule(pb.ProtoName)}) + vals.StructValues.Set("ChannelType", &lang.GoSimple{OriginalName: "ChannelTypeQueue", Import: ctx.RuntimeModule(pb.ProtoName)}) default: // routingKey and any other value - vals.StructValues.Set("ChannelType", &lang.GoSimple{Name: "ChannelTypeRoutingKey", Import: ctx.RuntimeModule(pb.ProtoName)}) + vals.StructValues.Set("ChannelType", &lang.GoSimple{OriginalName: "ChannelTypeRoutingKey", Import: ctx.RuntimeModule(pb.ProtoName)}) } if bindings.Exchange != nil { - ecVals := lang.ConstructGoValue(*bindings.Exchange, []string{"Type"}, &lang.GoSimple{Name: "ExchangeConfiguration", Import: ctx.RuntimeModule(pb.ProtoName)}) + ecVals := lang.ConstructGoValue(*bindings.Exchange, []string{"Type"}, &lang.GoSimple{OriginalName: "ExchangeConfiguration", Import: ctx.RuntimeModule(pb.ProtoName)}) switch bindings.Exchange.Type { case "default": - ecVals.StructValues.Set("Type", &lang.GoSimple{Name: "ExchangeTypeDefault", Import: ctx.RuntimeModule(pb.ProtoName)}) + ecVals.StructValues.Set("Type", &lang.GoSimple{OriginalName: "ExchangeTypeDefault", Import: ctx.RuntimeModule(pb.ProtoName)}) case "topic": - ecVals.StructValues.Set("Type", &lang.GoSimple{Name: "ExchangeTypeTopic", Import: ctx.RuntimeModule(pb.ProtoName)}) + ecVals.StructValues.Set("Type", &lang.GoSimple{OriginalName: "ExchangeTypeTopic", Import: ctx.RuntimeModule(pb.ProtoName)}) case "direct": - ecVals.StructValues.Set("Type", &lang.GoSimple{Name: "ExchangeTypeDirect", Import: ctx.RuntimeModule(pb.ProtoName)}) + ecVals.StructValues.Set("Type", &lang.GoSimple{OriginalName: "ExchangeTypeDirect", Import: ctx.RuntimeModule(pb.ProtoName)}) case "fanout": - ecVals.StructValues.Set("Type", &lang.GoSimple{Name: "ExchangeTypeFanout", Import: ctx.RuntimeModule(pb.ProtoName)}) + ecVals.StructValues.Set("Type", &lang.GoSimple{OriginalName: "ExchangeTypeFanout", Import: ctx.RuntimeModule(pb.ProtoName)}) case "headers": - ecVals.StructValues.Set("Type", &lang.GoSimple{Name: "ExchangeTypeHeaders", Import: ctx.RuntimeModule(pb.ProtoName)}) + ecVals.StructValues.Set("Type", &lang.GoSimple{OriginalName: "ExchangeTypeHeaders", Import: ctx.RuntimeModule(pb.ProtoName)}) } vals.StructValues.Set("ExchangeConfiguration", ecVals) } - qVals := lang.ConstructGoValue(*bindings.Queue, nil, &lang.GoSimple{Name: "QueueConfiguration", Import: ctx.RuntimeModule(pb.ProtoName)}) + qVals := lang.ConstructGoValue(*bindings.Queue, nil, &lang.GoSimple{OriginalName: "QueueConfiguration", Import: ctx.RuntimeModule(pb.ProtoName)}) vals.StructValues.Set("QueueConfiguration", qVals) return @@ -112,16 +112,16 @@ func (pb ProtoBuilder) BuildOperationBindings(ctx *common.CompileContext, rawDat return } - vals = lang.ConstructGoValue(bindings, []string{"Expiration", "DeliveryMode"}, &lang.GoSimple{Name: "OperationBindings", Import: ctx.RuntimeModule(pb.ProtoName)}) + vals = lang.ConstructGoValue(bindings, []string{"Expiration", "DeliveryMode"}, &lang.GoSimple{OriginalName: "OperationBindings", Import: ctx.RuntimeModule(pb.ProtoName)}) if bindings.Expiration > 0 { - v := lang.ConstructGoValue(bindings.Expiration*int(time.Millisecond), nil, &lang.GoSimple{Name: "Duration", Import: "time"}) + v := lang.ConstructGoValue(bindings.Expiration*int(time.Millisecond), nil, &lang.GoSimple{OriginalName: "Duration", Import: "time"}) vals.StructValues.Set("Expiration", v) } switch bindings.DeliveryMode { case 1: - vals.StructValues.Set("DeliveryMode", &lang.GoSimple{Name: "DeliveryModeTransient", Import: ctx.RuntimeModule(pb.ProtoName)}) + vals.StructValues.Set("DeliveryMode", &lang.GoSimple{OriginalName: "DeliveryModeTransient", Import: ctx.RuntimeModule(pb.ProtoName)}) case 2: - vals.StructValues.Set("DeliveryMode", &lang.GoSimple{Name: "DeliveryModePersistent", Import: ctx.RuntimeModule(pb.ProtoName)}) + vals.StructValues.Set("DeliveryMode", &lang.GoSimple{OriginalName: "DeliveryModePersistent", Import: ctx.RuntimeModule(pb.ProtoName)}) } return diff --git a/internal/asyncapi/amqp/message.go b/internal/asyncapi/amqp/message.go index 75dc1c8..fd3b453 100644 --- a/internal/asyncapi/amqp/message.go +++ b/internal/asyncapi/amqp/message.go @@ -21,6 +21,6 @@ func (pb ProtoBuilder) BuildMessageBindings(ctx *common.CompileContext, rawData return } - vals = lang.ConstructGoValue(bindings, nil, &lang.GoSimple{Name: "MessageBindings", Import: ctx.RuntimeModule(pb.ProtoName)}) + vals = lang.ConstructGoValue(bindings, nil, &lang.GoSimple{OriginalName: "MessageBindings", Import: ctx.RuntimeModule(pb.ProtoName)}) return } diff --git a/internal/asyncapi/bindings.go b/internal/asyncapi/bindings.go index b4447b0..4b94f8b 100644 --- a/internal/asyncapi/bindings.go +++ b/internal/asyncapi/bindings.go @@ -34,12 +34,12 @@ func (b *Bindings) build( ) (common.Renderable, error) { if b.Ref != "" { ctx.Logger.Trace("Ref", "$ref", b.Ref) - res := lang.NewRenderablePromise(b.Ref, common.PromiseOriginUser) + res := lang.NewUserPromise(b.Ref, bindingsKey, nil) ctx.PutPromise(res) return res, nil } - res := render.Bindings{Name: bindingsKey} + res := render.Bindings{OriginalName: bindingsKey} for _, e := range b.ProtocolValues.Entries() { ctx.Logger.Trace("Bindings", "proto", e.Key) builder, ok := ProtocolBuilders[e.Key] diff --git a/internal/asyncapi/channel.go b/internal/asyncapi/channel.go index 5b86d50..9c2a3e5 100644 --- a/internal/asyncapi/channel.go +++ b/internal/asyncapi/channel.go @@ -27,32 +27,33 @@ type Channel struct { func (c Channel) Compile(ctx *common.CompileContext) error { ctx.RegisterNameTop(ctx.Stack.Top().PathItem) - obj, err := c.buildChannels(ctx, ctx.Stack.Top().PathItem) + obj, err := c.build(ctx, ctx.Stack.Top().PathItem, ctx.Stack.Top().Flags) if err != nil { return err } ctx.PutObject(obj) - if v, ok := obj.(*render.ProtoChannel); ok { - ctx.Logger.Trace("ProtoObjects", "object", obj) - for _, protoObj := range v.ProtoChannels { - ctx.PutObject(protoObj) - } - } + //if v, ok := obj.(*render.Channel); ok { + // ctx.Logger.Trace("Objects", "object", obj) + // for _, protoObj := range v.ProtoChannels { + // ctx.PutObject(protoObj) + // } + //} return nil } -func (c Channel) buildChannels(ctx *common.CompileContext, channelKey string) (common.Renderable, error) { +func (c Channel) build(ctx *common.CompileContext, channelKey string, flags map[common.SchemaTag]string) (common.Renderable, error) { ignore := c.XIgnore || (!ctx.CompileOpts.GeneratePublishers && !ctx.CompileOpts.GenerateSubscribers) // || //!ctx.CompileOpts.ChannelOpts.IsAllowedName(channelKey) + _, isComponent := flags[common.SchemaTagComponent] if ignore { ctx.Logger.Debug("Channel denoted to be ignored") return &render.Channel{Dummy: true}, nil } if c.Ref != "" { ctx.Logger.Trace("Ref", "$ref", c.Ref) - prm := lang.NewRenderablePromise(c.Ref, common.PromiseOriginUser) - // Set a channel to be rendered if we reference it from `channels` document section + // Always draw the promises that are located in the `channels` section + prm := lang.NewUserPromise(c.Ref, channelKey, lo.Ternary(isComponent, nil, lo.ToPtr(true))) ctx.PutPromise(prm) return prm, nil } @@ -60,9 +61,10 @@ func (c Channel) buildChannels(ctx *common.CompileContext, channelKey string) (c chName, _ := lo.Coalesce(c.XGoName, channelKey) // Render only the channels defined directly in `channels` document section, not in `components` res := &render.Channel{ - Name: chName, - TypeNamePrefix: ctx.GenerateObjName(chName, ""), - SpecKey: channelKey, + OriginalName: chName, + TypeNamePrefix: ctx.GenerateObjName(chName, ""), + SpecKey: channelKey, + IsComponent: isComponent, } // Channel parameters @@ -71,14 +73,14 @@ func (c Channel) buildChannels(ctx *common.CompileContext, channelKey string) (c ctx.Logger.NextCallLevel() res.ParametersType = &lang.GoStruct{ BaseType: lang.BaseType{ - Name: ctx.GenerateObjName(chName, "Parameters"), + OriginalName: ctx.GenerateObjName(chName, "Parameters"), HasDefinition: true, }, } for _, paramName := range c.Parameters.Keys() { ctx.Logger.Trace("Channel parameter", "name", paramName) ref := ctx.PathStackRef("parameters", paramName) - prm := lang.NewGolangTypeAssignCbPromise(ref, common.PromiseOriginInternal, func(obj any) common.GolangType { + prm := lang.NewInternalGolangTypeAssignCbPromise(ref, func(obj any) common.GolangType { return obj.(*render.Parameter).Type }) ctx.PutPromise(prm) @@ -100,7 +102,7 @@ func (c Channel) buildChannels(ctx *common.CompileContext, channelKey string) (c if !ok { return false } - return lo.Contains(*c.Servers, srv.Name) + return lo.Contains(*c.Servers, srv.OriginalName) }) res.ServersPromise = prm ctx.PutListPromise(prm) @@ -121,7 +123,7 @@ func (c Channel) buildChannels(ctx *common.CompileContext, channelKey string) (c hasBindings = true ref := ctx.PathStackRef("bindings") - res.BindingsChannelPromise = lang.NewPromise[*render.Bindings](ref, common.PromiseOriginInternal) + res.BindingsChannelPromise = lang.NewInternalPromise[*render.Bindings](ref) ctx.PutPromise(res.BindingsChannelPromise) } @@ -134,13 +136,13 @@ func (c Channel) buildChannels(ctx *common.CompileContext, channelKey string) (c hasBindings = true ref := ctx.PathStackRef("publish", "bindings") - res.BindingsPublishPromise = lang.NewPromise[*render.Bindings](ref, common.PromiseOriginInternal) + res.BindingsPublishPromise = lang.NewInternalPromise[*render.Bindings](ref) ctx.PutPromise(res.BindingsPublishPromise) } if c.Publish.Message != nil { ctx.Logger.Trace("Found publish operation message") ref := ctx.PathStackRef("publish", "message") - res.PublisherMessageTypePromise = lang.NewPromise[*render.Message](ref, common.PromiseOriginInternal) + res.PublisherMessageTypePromise = lang.NewInternalPromise[*render.Message](ref) ctx.PutPromise(res.PublisherMessageTypePromise) } } @@ -151,27 +153,27 @@ func (c Channel) buildChannels(ctx *common.CompileContext, channelKey string) (c hasBindings = true ref := ctx.PathStackRef("subscribe", "bindings") - res.BindingsSubscribePromise = lang.NewPromise[*render.Bindings](ref, common.PromiseOriginInternal) + res.BindingsSubscribePromise = lang.NewInternalPromise[*render.Bindings](ref) ctx.PutPromise(res.BindingsSubscribePromise) } if c.Subscribe.Message != nil { ctx.Logger.Trace("Channel subscribe operation message") ref := ctx.PathStackRef("subscribe", "message") - res.SubscribeMessageTypePromise = lang.NewPromise[*render.Message](ref, common.PromiseOriginInternal) - ctx.PutPromise(res.SubscribeMessageTypePromise) + res.SubscriberMessageTypePromise = lang.NewInternalPromise[*render.Message](ref) + ctx.PutPromise(res.SubscriberMessageTypePromise) } } if hasBindings { res.BindingsType = &lang.GoStruct{ BaseType: lang.BaseType{ - Name: ctx.GenerateObjName(chName, "Bindings"), + OriginalName: ctx.GenerateObjName(chName, "Bindings"), HasDefinition: true, }, } } // Build protocol-specific channels for all supported protocols - // Here we don't know yet which servers this channel is applied to, so we don't have the protocols list to compile. + // At this point we don't know yet which servers this channel is applied to, so we don't have the protocols list to compile. // Servers will be known on rendering stage (after linking), but there we will already need to have proto // channels to be compiled for certain protocols we want to render. // As a solution, here we just build the proto channels for all supported protocols diff --git a/internal/asyncapi/correlationid.go b/internal/asyncapi/correlationid.go index f76908c..ffaad4b 100644 --- a/internal/asyncapi/correlationid.go +++ b/internal/asyncapi/correlationid.go @@ -41,7 +41,7 @@ func (c CorrelationID) build(ctx *common.CompileContext, correlationIDKey string // TODO: move this ref code from everywhere to single place? if c.Ref != "" { ctx.Logger.Trace("Ref", "$ref", c.Ref) - res := lang.NewRenderablePromise(c.Ref, common.PromiseOriginUser) + res := lang.NewUserPromise(c.Ref, correlationIDKey, nil) ctx.PutPromise(res) return res, nil } @@ -75,7 +75,7 @@ func (c CorrelationID) build(ctx *common.CompileContext, correlationIDKey string ctx.Logger.Trace("CorrelationID object", "messageField", structField, "path", locationPath) return &render.CorrelationID{ - Name: correlationIDKey, + OriginalName: correlationIDKey, Description: c.Description, StructField: structField, LocationPath: locationPath, diff --git a/internal/asyncapi/extra.go b/internal/asyncapi/extra.go index 019326f..c430de3 100644 --- a/internal/asyncapi/extra.go +++ b/internal/asyncapi/extra.go @@ -27,9 +27,9 @@ func buildXGoType(xGoTypeValue *types.Union2[string, xGoType]) (golangType commo switch xGoTypeValue.Selector { case 0: - t.Name = xGoTypeValue.V0 + t.OriginalName = xGoTypeValue.V0 case 1: - t.Name = xGoTypeValue.V1.Type + t.OriginalName = xGoTypeValue.V1.Type t.Import = xGoTypeValue.V1.Import.Package t.IsInterface = xGoTypeValue.V1.Hint.Kind == "interface" diff --git a/internal/asyncapi/http/channel.go b/internal/asyncapi/http/channel.go index 6b4dc84..94277dc 100644 --- a/internal/asyncapi/http/channel.go +++ b/internal/asyncapi/http/channel.go @@ -43,7 +43,7 @@ func (pb ProtoBuilder) BuildOperationBindings(ctx *common.CompileContext, rawDat return } - vals = lang.ConstructGoValue(bindings, []string{"Query"}, &lang.GoSimple{Name: "OperationBindings", Import: ctx.RuntimeModule(pb.ProtoName)}) + vals = lang.ConstructGoValue(bindings, []string{"Query"}, &lang.GoSimple{OriginalName: "OperationBindings", Import: ctx.RuntimeModule(pb.ProtoName)}) if bindings.Query != nil { v, err2 := json.Marshal(bindings.Query) if err2 != nil { diff --git a/internal/asyncapi/kafka/channel.go b/internal/asyncapi/kafka/channel.go index 96a642d..a035770 100644 --- a/internal/asyncapi/kafka/channel.go +++ b/internal/asyncapi/kafka/channel.go @@ -41,7 +41,7 @@ func (pb ProtoBuilder) BuildChannel(ctx *common.CompileContext, channel *asyncap return nil, err } - chanStruct.Fields = append(chanStruct.Fields, lang.GoStructField{Name: "topic", Type: &lang.GoSimple{Name: "string"}}) + chanStruct.Fields = append(chanStruct.Fields, lang.GoStructField{Name: "topic", Type: &lang.GoSimple{OriginalName: "string"}}) return &render.ProtoChannel{ Channel: parent, @@ -57,7 +57,7 @@ func (pb ProtoBuilder) BuildChannelBindings(ctx *common.CompileContext, rawData return } - vals = lang.ConstructGoValue(bindings, []string{"Partitions", "Replicas", "TopicConfiguration"}, &lang.GoSimple{Name: "ChannelBindings", Import: ctx.RuntimeModule(pb.ProtoName)}) + vals = lang.ConstructGoValue(bindings, []string{"Partitions", "Replicas", "TopicConfiguration"}, &lang.GoSimple{OriginalName: "ChannelBindings", Import: ctx.RuntimeModule(pb.ProtoName)}) if bindings.Partitions != nil { vals.StructValues.Set("Partitions", *bindings.Partitions) } @@ -65,11 +65,11 @@ func (pb ProtoBuilder) BuildChannelBindings(ctx *common.CompileContext, rawData vals.StructValues.Set("Replicas", *bindings.Replicas) } if bindings.TopicConfiguration != nil { - tcVals := lang.ConstructGoValue(*bindings.TopicConfiguration, []string{"CleanupPolicy", "RetentionMs", "DeleteRetentionMs"}, &lang.GoSimple{Name: "TopicConfiguration", Import: ctx.RuntimeModule(pb.ProtoName)}) + tcVals := lang.ConstructGoValue(*bindings.TopicConfiguration, []string{"CleanupPolicy", "RetentionMs", "DeleteRetentionMs"}, &lang.GoSimple{OriginalName: "TopicConfiguration", Import: ctx.RuntimeModule(pb.ProtoName)}) // TopicConfiguration->CleanupPolicy if len(bindings.TopicConfiguration.CleanupPolicy) > 0 { - cpVal := &lang.GoValue{Type: &lang.GoSimple{Name: "TopicCleanupPolicy", Import: ctx.RuntimeModule(pb.ProtoName)}, EmptyCurlyBrackets: true} + cpVal := &lang.GoValue{Type: &lang.GoSimple{OriginalName: "TopicCleanupPolicy", Import: ctx.RuntimeModule(pb.ProtoName)}, EmptyCurlyBrackets: true} switch { case lo.Contains(bindings.TopicConfiguration.CleanupPolicy, "delete"): cpVal.StructValues.Set("Delete", true) @@ -82,12 +82,12 @@ func (pb ProtoBuilder) BuildChannelBindings(ctx *common.CompileContext, rawData } // TopicConfiguration->RetentionMs if bindings.TopicConfiguration.RetentionMs > 0 { - v := lang.ConstructGoValue(bindings.TopicConfiguration.RetentionMs*int(time.Millisecond), nil, &lang.GoSimple{Name: "Duration", Import: "time"}) + v := lang.ConstructGoValue(bindings.TopicConfiguration.RetentionMs*int(time.Millisecond), nil, &lang.GoSimple{OriginalName: "Duration", Import: "time"}) tcVals.StructValues.Set("RetentionMs", v) } // TopicConfiguration->DeleteRetentionMs if bindings.TopicConfiguration.DeleteRetentionMs > 0 { - v := lang.ConstructGoValue(bindings.TopicConfiguration.DeleteRetentionMs*int(time.Millisecond), nil, &lang.GoSimple{Name: "Duration", Import: "time"}) + v := lang.ConstructGoValue(bindings.TopicConfiguration.DeleteRetentionMs*int(time.Millisecond), nil, &lang.GoSimple{OriginalName: "Duration", Import: "time"}) tcVals.StructValues.Set("DeleteRetentionMs", v) } vals.StructValues.Set("TopicConfiguration", tcVals) diff --git a/internal/asyncapi/kafka/message.go b/internal/asyncapi/kafka/message.go index 9b5e80f..3095afc 100644 --- a/internal/asyncapi/kafka/message.go +++ b/internal/asyncapi/kafka/message.go @@ -23,7 +23,7 @@ func (pb ProtoBuilder) BuildMessageBindings(ctx *common.CompileContext, rawData return } - vals = lang.ConstructGoValue(bindings, []string{"Key"}, &lang.GoSimple{Name: "MessageBindings", Import: ctx.RuntimeModule(pb.ProtoName)}) + vals = lang.ConstructGoValue(bindings, []string{"Key"}, &lang.GoSimple{OriginalName: "MessageBindings", Import: ctx.RuntimeModule(pb.ProtoName)}) if bindings.Key != nil { v, err2 := json.Marshal(bindings.Key) if err2 != nil { diff --git a/internal/asyncapi/kafka/server.go b/internal/asyncapi/kafka/server.go index 8394648..adda50e 100644 --- a/internal/asyncapi/kafka/server.go +++ b/internal/asyncapi/kafka/server.go @@ -33,7 +33,7 @@ func (pb ProtoBuilder) BuildServerBindings(ctx *common.CompileContext, rawData t if err = types.UnmarshalRawsUnion2(rawData, &bindings); err != nil { return vals, jsonVals, types.CompileError{Err: err, Path: ctx.PathStackRef(), Proto: pb.ProtoName} } - vals = lang.ConstructGoValue(bindings, nil, &lang.GoSimple{Name: "ServerBindings", Import: ctx.RuntimeModule(pb.ProtoName)}) + vals = lang.ConstructGoValue(bindings, nil, &lang.GoSimple{OriginalName: "ServerBindings", Import: ctx.RuntimeModule(pb.ProtoName)}) return } diff --git a/internal/asyncapi/message.go b/internal/asyncapi/message.go index b88fa7f..2aa3c86 100644 --- a/internal/asyncapi/message.go +++ b/internal/asyncapi/message.go @@ -46,17 +46,17 @@ func (m Message) Compile(ctx *common.CompileContext) error { return err } ctx.PutObject(obj) - if v, ok := obj.(*render.ProtoMessage); ok { - ctx.Logger.Trace("ProtoObjects", "object", obj) - for _, protoObj := range v.ProtoMessages { - ctx.PutObject(protoObj) - } - } + //if v, ok := obj.(*render.Message); ok { + // ctx.Logger.Trace("ProtoObjects", "object", obj) + // for _, protoObj := range v.ProtoMessages { + // ctx.PutObject(protoObj) + // } + //} return nil } func (m Message) build(ctx *common.CompileContext, messageKey string) (common.Renderable, error) { - //_, isComponent := ctx.Stack.Top().Flags[common.SchemaTagComponent] + _, isComponent := ctx.Stack.Top().Flags[common.SchemaTagComponent] ignore := m.XIgnore //|| (isComponent && !ctx.CompileOpts.MessageOpts.IsAllowedName(messageKey)) if ignore { ctx.Logger.Debug("Message denoted to be ignored") @@ -64,7 +64,8 @@ func (m Message) build(ctx *common.CompileContext, messageKey string) (common.Re } if m.Ref != "" { ctx.Logger.Trace("Ref", "$ref", m.Ref) - prm := lang.NewRenderablePromise(m.Ref, common.PromiseOriginUser) + // Always draw the promises that are located in the `messages` section + prm := lang.NewUserPromise(m.Ref, messageKey, lo.Ternary(isComponent, nil, lo.ToPtr(true))) ctx.PutPromise(prm) return prm, nil } @@ -79,24 +80,25 @@ func (m Message) build(ctx *common.CompileContext, messageKey string) (common.Re msgName, _ = lo.Coalesce(m.XGoName, msgName) res := render.Message{ - Name: msgName, + OriginalName: msgName, OutType: &lang.GoStruct{ BaseType: lang.BaseType{ - Name: ctx.GenerateObjName(msgName, "Out"), + OriginalName: ctx.GenerateObjName(msgName, "Out"), Description: utils.JoinNonemptyStrings("\n", m.Summary+" (Outbound Message)", m.Description), HasDefinition: true, }, }, InType: &lang.GoStruct{ BaseType: lang.BaseType{ - Name: ctx.GenerateObjName(msgName, "In"), + OriginalName: ctx.GenerateObjName(msgName, "In"), Description: utils.JoinNonemptyStrings("\n", m.Summary+" (Inbound Message)", m.Description), HasDefinition: true, }, }, PayloadType: m.getPayloadType(ctx), - HeadersFallbackType: &lang.GoMap{KeyType: &lang.GoSimple{Name: "string"}, ValueType: &lang.GoSimple{Name: "any", IsInterface: true}}, + HeadersFallbackType: &lang.GoMap{KeyType: &lang.GoSimple{OriginalName: "string"}, ValueType: &lang.GoSimple{OriginalName: "any", IsInterface: true}}, ContentType: m.ContentType, + IsComponent: isComponent, } ctx.Logger.Trace(fmt.Sprintf("Message content type is %q", res.ContentType)) @@ -108,7 +110,7 @@ func (m Message) build(ctx *common.CompileContext, messageKey string) (common.Re res.AllServersPromise = prm ctx.PutListPromise(prm) - prm2 := lang.NewCbPromise[*render.AsyncAPI](func(item common.CompileObject, path []string) bool { + prm2 := lang.NewInternalCbPromise[*render.AsyncAPI](func(item common.CompileObject, path []string) bool { _, ok := item.Renderable.(*render.AsyncAPI) return ok }) @@ -119,7 +121,7 @@ func (m Message) build(ctx *common.CompileContext, messageKey string) (common.Re if m.Headers != nil { ctx.Logger.Trace("Message headers") ref := ctx.PathStackRef("headers") - res.HeadersTypePromise = lang.NewPromise[*lang.GoStruct](ref, common.PromiseOriginInternal) + res.HeadersTypePromise = lang.NewInternalPromise[*lang.GoStruct](ref) res.HeadersTypePromise.AssignErrorNote = "Probably the headers schema has type other than of 'object'?" ctx.PutPromise(res.HeadersTypePromise) } @@ -130,13 +132,13 @@ func (m Message) build(ctx *common.CompileContext, messageKey string) (common.Re ctx.Logger.Trace("Message bindings") res.BindingsType = &lang.GoStruct{ BaseType: lang.BaseType{ - Name: ctx.GenerateObjName(msgName, "Bindings"), + OriginalName: ctx.GenerateObjName(msgName, "Bindings"), HasDefinition: true, }, } ref := ctx.PathStackRef("bindings") - res.BindingsPromise = lang.NewPromise[*render.Bindings](ref, common.PromiseOriginInternal) + res.BindingsPromise = lang.NewInternalPromise[*render.Bindings](ref) ctx.PutPromise(res.BindingsPromise) } @@ -144,7 +146,7 @@ func (m Message) build(ctx *common.CompileContext, messageKey string) (common.Re if m.CorrelationID != nil { ctx.Logger.Trace("Message correlationId") ref := ctx.PathStackRef("correlationId") - res.CorrelationIDPromise = lang.NewPromise[*render.CorrelationID](ref, common.PromiseOriginInternal) + res.CorrelationIDPromise = lang.NewInternalPromise[*render.CorrelationID](ref) ctx.PutPromise(res.CorrelationIDPromise) } @@ -170,7 +172,7 @@ func (m Message) setStructFields(ctx *common.CompileContext, langMessage *render } if langMessage.HeadersTypePromise != nil { ctx.Logger.Trace("Message headers has a concrete type") - prm := lang.NewGolangTypePromise(langMessage.HeadersTypePromise.Ref(), common.PromiseOriginInternal) + prm := lang.NewInternalGolangTypePromise(langMessage.HeadersTypePromise.Ref()) ctx.PutPromise(prm) fields = append(fields, lang.GoStructField{Name: "Headers", Type: prm}) } else { @@ -186,13 +188,13 @@ func (m Message) getPayloadType(ctx *common.CompileContext) common.GolangType { if m.Payload != nil { ctx.Logger.Trace("Message payload has a concrete type") ref := ctx.PathStackRef("payload") - prm := lang.NewGolangTypePromise(ref, common.PromiseOriginInternal) + prm := lang.NewInternalGolangTypePromise(ref) ctx.PutPromise(prm) return prm } ctx.Logger.Trace("Message payload has `any` type") - return &lang.GoSimple{Name: "any", IsInterface: true} + return &lang.GoSimple{OriginalName: "any", IsInterface: true} } type Tag struct { diff --git a/internal/asyncapi/mqtt/channel.go b/internal/asyncapi/mqtt/channel.go index ff0863f..676f15d 100644 --- a/internal/asyncapi/mqtt/channel.go +++ b/internal/asyncapi/mqtt/channel.go @@ -24,7 +24,7 @@ func (pb ProtoBuilder) BuildChannel(ctx *common.CompileContext, channel *asyncap return nil, err } - chanStruct.Fields = append(chanStruct.Fields, lang.GoStructField{Name: "topic", Type: &lang.GoSimple{Name: "string"}}) + chanStruct.Fields = append(chanStruct.Fields, lang.GoStructField{Name: "topic", Type: &lang.GoSimple{OriginalName: "string"}}) return &render.ProtoChannel{ Channel: parent, @@ -46,6 +46,6 @@ func (pb ProtoBuilder) BuildOperationBindings( err = types.CompileError{Err: err, Path: ctx.PathStackRef(), Proto: pb.ProtoName} return } - vals = lang.ConstructGoValue(bindings, nil, &lang.GoSimple{Name: "OperationBindings", Import: ctx.RuntimeModule(pb.ProtoName)}) + vals = lang.ConstructGoValue(bindings, nil, &lang.GoSimple{OriginalName: "OperationBindings", Import: ctx.RuntimeModule(pb.ProtoName)}) return } diff --git a/internal/asyncapi/mqtt/server.go b/internal/asyncapi/mqtt/server.go index 08201a3..04e109d 100644 --- a/internal/asyncapi/mqtt/server.go +++ b/internal/asyncapi/mqtt/server.go @@ -42,9 +42,9 @@ func (pb ProtoBuilder) BuildServerBindings(ctx *common.CompileContext, rawData t if err = types.UnmarshalRawsUnion2(rawData, &bindings); err != nil { return vals, jsonVals, types.CompileError{Err: err, Path: ctx.PathStackRef(), Proto: pb.ProtoName} } - vals = lang.ConstructGoValue(bindings, []string{"LastWill"}, &lang.GoSimple{Name: "ServerBindings", Import: ctx.RuntimeModule(pb.ProtoName)}) + vals = lang.ConstructGoValue(bindings, []string{"LastWill"}, &lang.GoSimple{OriginalName: "ServerBindings", Import: ctx.RuntimeModule(pb.ProtoName)}) if bindings.LastWill != nil { - vals.StructValues.Set("LastWill", lang.ConstructGoValue(*bindings.LastWill, []string{}, &lang.GoSimple{Name: "LastWill", Import: ctx.RuntimeModule(pb.ProtoName)})) + vals.StructValues.Set("LastWill", lang.ConstructGoValue(*bindings.LastWill, []string{}, &lang.GoSimple{OriginalName: "LastWill", Import: ctx.RuntimeModule(pb.ProtoName)})) } return diff --git a/internal/asyncapi/object.go b/internal/asyncapi/object.go index 19bdde0..b054010 100644 --- a/internal/asyncapi/object.go +++ b/internal/asyncapi/object.go @@ -82,16 +82,16 @@ func (o Object) Compile(ctx *common.CompileContext) error { return nil } -func (o Object) build(ctx *common.CompileContext, flags map[common.SchemaTag]string, objectKey string) (common.GolangType, error) { +func (o Object) build(ctx *common.CompileContext, flags map[common.SchemaTag]string, objectKey string) (common.Renderable, error) { //_, isComponent := flags[common.SchemaTagComponent] ignore := o.XIgnore //|| (isComponent && !ctx.CompileOpts.ModelOpts.IsAllowedName(objectKey)) if ignore { ctx.Logger.Debug("Object denoted to be ignored") - return &lang.GoSimple{Name: "any", IsInterface: true}, nil + return &lang.GoSimple{OriginalName: "any", IsInterface: true}, nil } if o.Ref != "" { ctx.Logger.Trace("Ref", "$ref", o.Ref) - res := lang.NewGolangTypePromise(o.Ref, common.PromiseOriginUser) + res := lang.NewUserPromise(o.Ref, objectKey, nil) ctx.PutPromise(res) return res, nil } @@ -186,21 +186,21 @@ func (o Object) buildGolangType(ctx *common.CompileContext, flags map[common.Sch } case "null", "": ctx.Logger.Trace("Object is any") - golangType = &lang.GoSimple{Name: "any", IsInterface: true} + golangType = &lang.GoSimple{OriginalName: "any", IsInterface: true} case "boolean": ctx.Logger.Trace("Object is bool") - aliasedType = &lang.GoSimple{Name: "bool"} + aliasedType = &lang.GoSimple{OriginalName: "bool"} case "integer": // TODO: "format:" ctx.Logger.Trace("Object is int") - aliasedType = &lang.GoSimple{Name: "int"} + aliasedType = &lang.GoSimple{OriginalName: "int"} case "number": // TODO: "format:" ctx.Logger.Trace("Object is float64") - aliasedType = &lang.GoSimple{Name: "float64"} + aliasedType = &lang.GoSimple{OriginalName: "float64"} case "string": ctx.Logger.Trace("Object is string") - aliasedType = &lang.GoSimple{Name: "string"} + aliasedType = &lang.GoSimple{OriginalName: "string"} default: return nil, types.CompileError{Err: fmt.Errorf("unknown jsonschema type %q", typeName), Path: ctx.PathStackRef()} } @@ -209,7 +209,7 @@ func (o Object) buildGolangType(ctx *common.CompileContext, flags map[common.Sch _, hasDefinition := flags[common.SchemaTagDefinition] golangType = &lang.GoTypeAlias{ BaseType: lang.BaseType{ - Name: ctx.GenerateObjName(o.Title, ""), + OriginalName: ctx.GenerateObjName(o.Title, ""), Description: o.Description, HasDefinition: hasDefinition, }, @@ -241,7 +241,7 @@ func (o Object) buildLangStruct(ctx *common.CompileContext, flags map[common.Sch objName, _ := lo.Coalesce(o.XGoName, o.Title) res := lang.GoStruct{ BaseType: lang.BaseType{ - Name: ctx.GenerateObjName(objName, ""), + OriginalName: ctx.GenerateObjName(objName, ""), Description: o.Description, HasDefinition: hasDefinition, }, @@ -277,7 +277,7 @@ func (o Object) buildLangStruct(ctx *common.CompileContext, flags map[common.Sch for _, entry := range o.Properties.Entries() { ctx.Logger.Trace("Object property", "name", entry.Key) ref := ctx.PathStackRef("properties", entry.Key) - prm := lang.NewGolangTypePromise(ref, common.PromiseOriginInternal) + prm := lang.NewInternalGolangTypePromise(ref) ctx.PutPromise(prm) var langObj common.GolangType = prm @@ -308,7 +308,7 @@ func (o Object) buildLangStruct(ctx *common.CompileContext, flags map[common.Sch case 0: // "additionalProperties:" is an object ctx.Logger.Trace("Object additional properties as an object") ref := ctx.PathStackRef("additionalProperties") - prm := lang.NewGolangTypePromise(ref, common.PromiseOriginInternal) + prm := lang.NewInternalGolangTypePromise(ref) ctx.PutPromise(prm) xTags, xTagNames, xTagVals := o.AdditionalProperties.V0.xGoTagsInfo(ctx) f := lang.GoStructField{ @@ -316,11 +316,11 @@ func (o Object) buildLangStruct(ctx *common.CompileContext, flags map[common.Sch Description: o.AdditionalProperties.V0.Description, Type: &lang.GoMap{ BaseType: lang.BaseType{ - Name: ctx.GenerateObjName(propName, "AdditionalProperties"), + OriginalName: ctx.GenerateObjName(propName, "AdditionalProperties"), Description: o.AdditionalProperties.V0.Description, HasDefinition: false, }, - KeyType: &lang.GoSimple{Name: "string"}, + KeyType: &lang.GoSimple{OriginalName: "string"}, ValueType: prm, }, ExtraTags: xTags, @@ -333,21 +333,21 @@ func (o Object) buildLangStruct(ctx *common.CompileContext, flags map[common.Sch if o.AdditionalProperties.V1 { // "additionalProperties: true" -- allow any additional properties valTyp := lang.GoTypeAlias{ BaseType: lang.BaseType{ - Name: ctx.GenerateObjName(propName, "AdditionalPropertiesValue"), + OriginalName: ctx.GenerateObjName(propName, "AdditionalPropertiesValue"), Description: "", HasDefinition: false, }, - AliasedType: &lang.GoSimple{Name: "any", IsInterface: true}, + AliasedType: &lang.GoSimple{OriginalName: "any", IsInterface: true}, } f := lang.GoStructField{ Name: "AdditionalProperties", Type: &lang.GoMap{ BaseType: lang.BaseType{ - Name: ctx.GenerateObjName(propName, "AdditionalProperties"), + OriginalName: ctx.GenerateObjName(propName, "AdditionalProperties"), Description: "", HasDefinition: false, }, - KeyType: &lang.GoSimple{Name: "string"}, + KeyType: &lang.GoSimple{OriginalName: "string"}, ValueType: &valTyp, }, ContentTypesFunc: contentTypesFunc, @@ -365,7 +365,7 @@ func (o Object) buildLangArray(ctx *common.CompileContext, flags map[common.Sche objName, _ := lo.Coalesce(o.XGoName, o.Title) res := lang.GoArray{ BaseType: lang.BaseType{ - Name: ctx.GenerateObjName(objName, ""), + OriginalName: ctx.GenerateObjName(objName, ""), Description: o.Description, HasDefinition: hasDefinition, }, @@ -376,26 +376,26 @@ func (o Object) buildLangArray(ctx *common.CompileContext, flags map[common.Sche case o.Items != nil && o.Items.Selector == 0: // Only one "type:" of items ctx.Logger.Trace("Object items (single type)") ref := ctx.PathStackRef("items") - prm := lang.NewGolangTypePromise(ref, common.PromiseOriginInternal) + prm := lang.NewInternalGolangTypePromise(ref) ctx.PutPromise(prm) res.ItemsType = prm case o.Items == nil || o.Items.Selector == 1: // No items or Several types for each item sequentially ctx.Logger.Trace("Object items (zero or several types)") valTyp := lang.GoTypeAlias{ BaseType: lang.BaseType{ - Name: ctx.GenerateObjName(objName, "ItemsItemValue"), + OriginalName: ctx.GenerateObjName(objName, "ItemsItemValue"), Description: "", HasDefinition: false, }, - AliasedType: &lang.GoSimple{Name: "any", IsInterface: true}, + AliasedType: &lang.GoSimple{OriginalName: "any", IsInterface: true}, } res.ItemsType = &lang.GoMap{ BaseType: lang.BaseType{ - Name: ctx.GenerateObjName(objName, "ItemsItem"), + OriginalName: ctx.GenerateObjName(objName, "ItemsItem"), Description: "", HasDefinition: false, }, - KeyType: &lang.GoSimple{Name: "string"}, + KeyType: &lang.GoSimple{OriginalName: "string"}, ValueType: &valTyp, } } @@ -410,7 +410,7 @@ func (o Object) buildUnionStruct(ctx *common.CompileContext, flags map[common.Sc res := lang.UnionStruct{ GoStruct: lang.GoStruct{ BaseType: lang.BaseType{ - Name: ctx.GenerateObjName(objName, ""), + OriginalName: ctx.GenerateObjName(objName, ""), Description: o.Description, HasDefinition: hasDefinition, }, @@ -427,19 +427,19 @@ func (o Object) buildUnionStruct(ctx *common.CompileContext, flags map[common.Sc res.Fields = lo.Times(len(o.OneOf), func(index int) lang.GoStructField { ref := ctx.PathStackRef("oneOf", strconv.Itoa(index)) - prm := lang.NewGolangTypePromise(ref, common.PromiseOriginInternal) + prm := lang.NewInternalGolangTypePromise(ref) ctx.PutPromise(prm) return lang.GoStructField{Type: &lang.GoPointer{Type: prm}} }) res.Fields = append(res.Fields, lo.Times(len(o.AnyOf), func(index int) lang.GoStructField { ref := ctx.PathStackRef("anyOf", strconv.Itoa(index)) - prm := lang.NewGolangTypePromise(ref, common.PromiseOriginInternal) + prm := lang.NewInternalGolangTypePromise(ref) ctx.PutPromise(prm) return lang.GoStructField{Type: &lang.GoPointer{Type: prm}} })...) res.Fields = append(res.Fields, lo.Times(len(o.AllOf), func(index int) lang.GoStructField { ref := ctx.PathStackRef("allOf", strconv.Itoa(index)) - prm := lang.NewGolangTypePromise(ref, common.PromiseOriginInternal) + prm := lang.NewInternalGolangTypePromise(ref) ctx.PutPromise(prm) return lang.GoStructField{Type: prm} })...) diff --git a/internal/asyncapi/parameter.go b/internal/asyncapi/parameter.go index 78c2e72..b859efb 100644 --- a/internal/asyncapi/parameter.go +++ b/internal/asyncapi/parameter.go @@ -36,21 +36,21 @@ func (p Parameter) build(ctx *common.CompileContext, parameterKey string) (commo //} if p.Ref != "" { ctx.Logger.Trace("Ref", "$ref", p.Ref) - res := lang.NewRenderablePromise(p.Ref, common.PromiseOriginUser) + res := lang.NewUserPromise(p.Ref, parameterKey, nil) ctx.PutPromise(res) return res, nil } parName, _ := lo.Coalesce(p.XGoName, parameterKey) - res := &render.Parameter{Name: parName} + res := &render.Parameter{OriginalName: parName} if p.Schema != nil { ctx.Logger.Trace("Parameter schema") - prm := lang.NewGolangTypePromise(ctx.PathStackRef("schema"), common.PromiseOriginInternal) + prm := lang.NewInternalGolangTypePromise(ctx.PathStackRef("schema")) ctx.PutPromise(prm) res.Type = &lang.GoStruct{ BaseType: lang.BaseType{ - Name: ctx.GenerateObjName(parName, ""), + OriginalName: ctx.GenerateObjName(parName, ""), Description: p.Description, HasDefinition: true, }, @@ -60,11 +60,11 @@ func (p Parameter) build(ctx *common.CompileContext, parameterKey string) (commo ctx.Logger.Trace("Parameter has no schema") res.Type = &lang.GoTypeAlias{ BaseType: lang.BaseType{ - Name: ctx.GenerateObjName(parName, ""), + OriginalName: ctx.GenerateObjName(parName, ""), Description: p.Description, HasDefinition: true, }, - AliasedType: &lang.GoSimple{Name: "string"}, + AliasedType: &lang.GoSimple{OriginalName: "string"}, } res.IsStringType = true } diff --git a/internal/asyncapi/protobuilder.go b/internal/asyncapi/protobuilder.go index 58348a5..ab2444e 100644 --- a/internal/asyncapi/protobuilder.go +++ b/internal/asyncapi/protobuilder.go @@ -32,12 +32,12 @@ func BuildProtoChannelStruct( ) (*lang.GoStruct, error) { chanStruct := lang.GoStruct{ BaseType: lang.BaseType{ - Name: golangName, + OriginalName: golangName, Description: source.Description, HasDefinition: true, }, Fields: []lang.GoStructField{ - {Name: "name", Type: &lang.GoSimple{Name: "ParamString", Import: ctx.RuntimeModule("")}}, + {Name: "name", Type: &lang.GoSimple{OriginalName: "ParamString", Import: ctx.RuntimeModule("")}}, }, } @@ -48,9 +48,9 @@ func BuildProtoChannelStruct( Name: "publisher", Description: source.Publish.Description, Type: &lang.GoSimple{ - Name: "Publisher", - Import: ctx.RuntimeModule(protoName), - IsInterface: true, + OriginalName: "Publisher", + Import: ctx.RuntimeModule(protoName), + IsInterface: true, }, }) } @@ -62,9 +62,9 @@ func BuildProtoChannelStruct( Name: "subscriber", Description: source.Subscribe.Description, Type: &lang.GoSimple{ - Name: "Subscriber", - Import: ctx.RuntimeModule(protoName), - IsInterface: true, + OriginalName: "Subscriber", + Import: ctx.RuntimeModule(protoName), + IsInterface: true, }, }) } @@ -80,7 +80,7 @@ func BuildProtoServerStruct( ) (*lang.GoStruct, error) { srvStruct := lang.GoStruct{ BaseType: lang.BaseType{ - Name: target.TypeNamePrefix, + OriginalName: target.TypeNamePrefix, Description: source.Description, HasDefinition: true, }, @@ -90,14 +90,14 @@ func BuildProtoServerStruct( ctx.Logger.Trace("Server producer", "proto", protoName) fld := lang.GoStructField{ Name: "producer", - Type: &lang.GoSimple{Name: "Producer", Import: ctx.RuntimeModule(protoName), IsInterface: true}, + Type: &lang.GoSimple{OriginalName: "Producer", Import: ctx.RuntimeModule(protoName), IsInterface: true}, } srvStruct.Fields = append(srvStruct.Fields, fld) ctx.Logger.Trace("Server consumer", "proto", protoName) fld = lang.GoStructField{ Name: "consumer", - Type: &lang.GoSimple{Name: "Consumer", Import: ctx.RuntimeModule(protoName), IsInterface: true}, + Type: &lang.GoSimple{OriginalName: "Consumer", Import: ctx.RuntimeModule(protoName), IsInterface: true}, } srvStruct.Fields = append(srvStruct.Fields, fld) diff --git a/internal/asyncapi/server.go b/internal/asyncapi/server.go index b90db47..df86c3e 100644 --- a/internal/asyncapi/server.go +++ b/internal/asyncapi/server.go @@ -33,9 +33,9 @@ func (s Server) Compile(ctx *common.CompileContext) error { return err } ctx.PutObject(obj) - if v, ok := obj.(*render.ProtoServer); ok { - ctx.PutObject(v.ProtoServer) - } + //if v, ok := obj.(*render.Server); ok { + // ctx.PutObject(v.ProtoServer) + //} return nil } @@ -48,8 +48,8 @@ func (s Server) build(ctx *common.CompileContext, serverKey string) (common.Rend } if s.Ref != "" { ctx.Logger.Trace("Ref", "$ref", s.Ref) - prm := lang.NewRenderablePromise(s.Ref, common.PromiseOriginUser) - // Set a server to be rendered if we reference it from `servers` document section + // Always draw the promises that are located in the `servers` section + prm := lang.NewUserPromise(s.Ref, serverKey, lo.Ternary(isComponent, nil, lo.ToPtr(true))) ctx.PutPromise(prm) return prm, nil } @@ -57,12 +57,13 @@ func (s Server) build(ctx *common.CompileContext, serverKey string) (common.Rend srvName, _ := lo.Coalesce(s.XGoName, serverKey) // Render only the servers defined directly in `servers` document section, not in `components` res := render.Server{ - Name: srvName, + OriginalName: srvName, SpecKey: serverKey, TypeNamePrefix: ctx.GenerateObjName(srvName, ""), URL: s.URL, Protocol: s.Protocol, ProtocolVersion: s.ProtocolVersion, + IsComponent: isComponent, } // Channels which are connected to this server @@ -81,13 +82,13 @@ func (s Server) build(ctx *common.CompileContext, serverKey string) (common.Rend ctx.Logger.Trace("Server bindings") res.BindingsType = &lang.GoStruct{ BaseType: lang.BaseType{ - Name: ctx.GenerateObjName(srvName, "Bindings"), + OriginalName: ctx.GenerateObjName(srvName, "Bindings"), HasDefinition: true, }, } ref := ctx.PathStackRef("bindings") - res.BindingsPromise = lang.NewPromise[*render.Bindings](ref, common.PromiseOriginInternal) + res.BindingsPromise = lang.NewInternalPromise[*render.Bindings](ref) ctx.PutPromise(res.BindingsPromise) } @@ -95,7 +96,7 @@ func (s Server) build(ctx *common.CompileContext, serverKey string) (common.Rend for _, v := range s.Variables.Entries() { ctx.Logger.Trace("Server variable", "name", v.Key) ref := ctx.PathStackRef("variables", v.Key) - prm := lang.NewPromise[*render.ServerVariable](ref, common.PromiseOriginInternal) + prm := lang.NewInternalPromise[*render.ServerVariable](ref) ctx.PutPromise(prm) res.VariablesPromises.Set(v.Key, prm) } diff --git a/internal/asyncapi/servervariable.go b/internal/asyncapi/servervariable.go index f2cac93..8c1fe24 100644 --- a/internal/asyncapi/servervariable.go +++ b/internal/asyncapi/servervariable.go @@ -29,16 +29,16 @@ func (sv ServerVariable) Compile(ctx *common.CompileContext) error { func (sv ServerVariable) build(ctx *common.CompileContext, serverVariableKey string) (common.Renderable, error) { if sv.Ref != "" { ctx.Logger.Trace("Ref", "$ref", sv.Ref) - res := lang.NewRenderablePromise(sv.Ref, common.PromiseOriginUser) + res := lang.NewUserPromise(sv.Ref, serverVariableKey, nil) ctx.PutPromise(res) return res, nil } res := &render.ServerVariable{ - Name: utils.ToGolangName(serverVariableKey, false), - Enum: sv.Enum, - Default: sv.Default, - Description: sv.Description, + OriginalName: utils.ToGolangName(serverVariableKey, false), + Enum: sv.Enum, + Default: sv.Default, + Description: sv.Description, } return res, nil diff --git a/internal/asyncapi/ws/channel.go b/internal/asyncapi/ws/channel.go index c82106e..55046e6 100644 --- a/internal/asyncapi/ws/channel.go +++ b/internal/asyncapi/ws/channel.go @@ -25,7 +25,7 @@ func (pb ProtoBuilder) BuildChannel(ctx *common.CompileContext, channel *asyncap return nil, err } - chanStruct.Fields = append(chanStruct.Fields, lang.GoStructField{Name: "topic", Type: &lang.GoSimple{Name: "string"}}) + chanStruct.Fields = append(chanStruct.Fields, lang.GoStructField{Name: "topic", Type: &lang.GoSimple{OriginalName: "string"}}) return &render.ProtoChannel{ Channel: parent, @@ -44,7 +44,7 @@ func (pb ProtoBuilder) BuildChannelBindings( return } - vals = lang.ConstructGoValue(bindings, []string{"Query", "Headers"}, &lang.GoSimple{Name: "ChannelBindings", Import: ctx.RuntimeModule(pb.ProtoName)}) + vals = lang.ConstructGoValue(bindings, []string{"Query", "Headers"}, &lang.GoSimple{OriginalName: "ChannelBindings", Import: ctx.RuntimeModule(pb.ProtoName)}) if bindings.Query != nil { v, err2 := json.Marshal(bindings.Query) if err2 != nil { diff --git a/internal/common/compile_context.go b/internal/common/compile_context.go index 4a83c44..bceba40 100644 --- a/internal/common/compile_context.go +++ b/internal/common/compile_context.go @@ -15,9 +15,9 @@ import ( const nameWordSep = "_" -// ErrDefinitionNotRendered is returned when we try to get a package in the generated code for an object, but the +// ErrDefinitionLocationUnknown is returned when we try to get a package in the generated code for an object, but the // definition of this object has not been rendered, therefore its location is unknown yet. -var ErrDefinitionNotRendered = errors.New("definition is not rendered") +var ErrDefinitionLocationUnknown = errors.New("definition location is unknown") type CompileObject struct { Renderable @@ -30,9 +30,7 @@ type GolangTypeDefinitionInfo struct { type GolangType interface { Renderable - TypeName() string // TODO: remove? - D() string - U() string + GoTemplate() string IsPointer() bool DefinitionInfo() (*GolangTypeDefinitionInfo, error) SetDefinitionInfo(info *GolangTypeDefinitionInfo) diff --git a/internal/common/render.go b/internal/common/render.go index 0fd6438..8f85b9f 100644 --- a/internal/common/render.go +++ b/internal/common/render.go @@ -23,6 +23,7 @@ type Renderable interface { // TODO: rename // Selectable returns true if object can be selected to pass to the templates for rendering. Selectable() bool String() string + GetOriginalName() string } type ( @@ -51,6 +52,7 @@ type RenderContext interface { QualifiedRuntimeName(parts ...string) string QualifiedGeneratedPackage(obj GolangType) (string, error) CurrentDefinitionInfo() *GolangTypeDefinitionInfo + CurrentObject() CompileObject } type ImportItem struct { diff --git a/internal/render/amqp/channel.go b/internal/render/amqp/channel.go index 08b5d55..d2fe437 100644 --- a/internal/render/amqp/channel.go +++ b/internal/render/amqp/channel.go @@ -5,7 +5,7 @@ package amqp //} //func (pc ProtoChannel) D(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Channel", "", pc.Parent.Name, "definition", pc.Selectable(), "proto", pc.ProtoName) +// ctx.LogStartRender("Channel", "", pc.Parent.GetOriginalName, "definition", pc.Selectable(), "proto", pc.ProtoName) // defer ctx.LogFinishRender() // // var res []*j.Statement @@ -26,17 +26,17 @@ package amqp //} //func (pc ProtoChannel) U(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Channel", "", pc.Parent.Name, "usage", pc.Selectable(), "proto", pc.ProtoName) +// ctx.LogStartRender("Channel", "", pc.Parent.GetOriginalName, "usage", pc.Selectable(), "proto", pc.ProtoName) // defer ctx.LogFinishRender() // return pc.Type.U(ctx) //} //func (pc ProtoChannel) ID() string { -// return pc.Parent.Name +// return pc.Parent.GetOriginalName //} // //func (pc ProtoChannel) String() string { -// return "AMQP ProtoChannel " + pc.Parent.Name +// return "AMQP ProtoChannel " + pc.Parent.GetOriginalName //} //func (pc ProtoChannel) renderNewFunc(ctx *common.RenderContext) []*j.Statement { @@ -58,7 +58,7 @@ package amqp // Op("*").Add(utils.ToCode(pc.Type.U(ctx))...). // BlockFunc(func(bg *j.Group) { // bg.Op("res := ").Add(utils.ToCode(pc.Type.U(ctx))...).Values(j.DictFunc(func(d j.Dict) { -// d[j.Id("name")] = j.Id(pc.Parent.TypeNamePrefix + "Name").CallFunc(func(g *j.Group) { +// d[j.Id("name")] = j.Id(pc.Parent.TypeNamePrefix + "GetOriginalName").CallFunc(func(g *j.Group) { // if pc.Parent.ParametersType != nil { // g.Id("params") // } @@ -84,11 +84,11 @@ package amqp // ) // }) // bg.Op(` -// if bindings.ExchangeConfiguration.Name != nil { -// res.exchange = *bindings.ExchangeConfiguration.Name +// if bindings.ExchangeConfiguration.GetOriginalName != nil { +// res.exchange = *bindings.ExchangeConfiguration.GetOriginalName // } -// if bindings.QueueConfiguration.Name != "" { -// res.queue = bindings.QueueConfiguration.Name +// if bindings.QueueConfiguration.GetOriginalName != "" { +// res.queue = bindings.QueueConfiguration.GetOriginalName // }`) // } // bg.Op(`return &res`) @@ -99,7 +99,7 @@ package amqp //func (pc ProtoChannel) renderProtoMethods(ctx *common.RenderContext) []*j.Statement { // ctx.Logger.Trace("renderProtoMethods", "proto", pc.ProtoName) // rn := pc.Type.ReceiverName() -// receiver := j.Id(rn).Id(pc.Type.Name) +// receiver := j.Id(rn).Id(pc.Type.GetOriginalName) // // return []*j.Statement{ // // Method Exchange() string @@ -131,7 +131,7 @@ package amqp //func (pc ProtoChannel) renderProtoPublisherMethods(ctx *common.RenderContext) []*j.Statement { // ctx.Logger.Trace("renderProtoPublisherMethods", "proto", pc.ProtoName) // rn := pc.Type.ReceiverName() -// receiver := j.Id(rn).Id(pc.Type.Name) +// receiver := j.Id(rn).Id(pc.Type.GetOriginalName) // // var msgTyp common.GolangType = render.GoPointer{Type: pc.FallbackMessageType, HasDefinition: true} // if pc.PublisherMessageTypePromise != nil { diff --git a/internal/render/amqp/server.go b/internal/render/amqp/server.go index eeddb9b..dea9d86 100644 --- a/internal/render/amqp/server.go +++ b/internal/render/amqp/server.go @@ -12,7 +12,7 @@ package amqp //} //func (ps ProtoServer) D(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Server", "", ps.Parent.Name, "definition", ps.Selectable(), "proto", ps.ProtoName) +// ctx.LogStartRender("Server", "", ps.Parent.GetOriginalName, "definition", ps.Selectable(), "proto", ps.ProtoName) // defer ctx.LogFinishRender() // // var res []*j.Statement @@ -26,17 +26,17 @@ package amqp //} //func (ps ProtoServer) U(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Server", "", ps.Parent.Name, "usage", ps.Selectable(), "proto", ps.ProtoName) +// ctx.LogStartRender("Server", "", ps.Parent.GetOriginalName, "usage", ps.Selectable(), "proto", ps.ProtoName) // defer ctx.LogFinishRender() // return ps.Type.U(ctx) //} // //func (ps ProtoServer) ID() string { -// return ps.Parent.Name +// return ps.Parent.GetOriginalName //} // //func (ps ProtoServer) String() string { -// return "AMQP ProtoServer " + ps.Parent.Name +// return "AMQP ProtoServer " + ps.Parent.GetOriginalName //} //func (ps ProtoServer) renderChannelMethods(ctx *common.RenderContext) []*j.Statement { diff --git a/internal/render/asyncapi.go b/internal/render/asyncapi.go index 943e476..ceeafae 100644 --- a/internal/render/asyncapi.go +++ b/internal/render/asyncapi.go @@ -30,6 +30,10 @@ func (a *AsyncAPI) String() string { return "AsyncAPI" } +func (a *AsyncAPI) GetOriginalName() string { + return "" +} + //// SpecEffectiveContentTypes returns a list of all unique content types used in the spec. This includes all content //// types from all messages and the default content type. //func (a AsyncAPI) SpecEffectiveContentTypes() []string { diff --git a/internal/render/bindings.go b/internal/render/bindings.go index af92d7f..16a4fdb 100644 --- a/internal/render/bindings.go +++ b/internal/render/bindings.go @@ -8,7 +8,7 @@ import ( // Bindings never renders itself, only as a part of other object type Bindings struct { - Name string + OriginalName string Values types.OrderedMap[string, *lang.GoValue] // Binding values by protocol // Value of jsonschema fields as json marshalled strings @@ -24,11 +24,15 @@ func (b *Bindings) Selectable() bool { } //func (b *Bindings) ID() string { -// return b.Name +// return b.GetOriginalName //} func (b *Bindings) String() string { - return "Bindings " + b.Name + return "Bindings " + b.OriginalName +} + +func (b *Bindings) GetOriginalName() string { + return b.OriginalName } //func (b *Bindings) RenderBindingsMethod( @@ -36,13 +40,13 @@ func (b *Bindings) String() string { // bindingsStruct *GoStruct, // protoName, protoTitle string, //) []*j.Statement { -// ctx.LogStartRender("Bindings.RenderBindingsMethod", "", bindingsStruct.Name, "definition", false) +// ctx.LogStartRender("Bindings.RenderBindingsMethod", "", bindingsStruct.GetOriginalName, "definition", false) // defer ctx.LogFinishRender() // // receiver := j.Id(bindingsStruct.ReceiverName()).Add(utils.ToCode(bindingsStruct.U(ctx))...) // pv, ok := b.Values.Get(protoName) // if !ok { -// ctx.Logger.Debug("Skip render bindings method", "name", bindingsStruct.Name, "proto", protoName) +// ctx.Logger.Debug("Skip render bindings method", "name", bindingsStruct.GetOriginalName, "proto", protoName) // return nil // } // @@ -68,7 +72,7 @@ func (b *Bindings) String() string { // channelBindings, publishBindings, subscribeBindings *Bindings, // protoName, protoTitle string, //) []*j.Statement { -// ctx.LogStartRender("renderChannelAndOperationBindingsMethod", "", bindingsStruct.Name, "definition", false) +// ctx.LogStartRender("renderChannelAndOperationBindingsMethod", "", bindingsStruct.GetOriginalName, "definition", false) // defer ctx.LogFinishRender() // // receiver := j.Id(bindingsStruct.ReceiverName()).Add(utils.ToCode(bindingsStruct.U(ctx))...) @@ -78,7 +82,7 @@ func (b *Bindings) String() string { // Params(). // Qual(ctx.RuntimeModule(protoName), "ChannelBindings"). // BlockFunc(func(bg *j.Group) { -// cb := &GoValue{Type: &GoSimple{Name: "ChannelBindings", Import: ctx.RuntimeModule(protoName)}, EmptyCurlyBrackets: true} +// cb := &GoValue{Type: &GoSimple{GetOriginalName: "ChannelBindings", Import: ctx.RuntimeModule(protoName)}, EmptyCurlyBrackets: true} // if channelBindings != nil { // if b, ok := channelBindings.Values.Get(protoName); ok { // ctx.Logger.Debug("Channel bindings", "proto", protoName) diff --git a/internal/render/channel.go b/internal/render/channel.go index bf61723..026e143 100644 --- a/internal/render/channel.go +++ b/internal/render/channel.go @@ -7,7 +7,7 @@ import ( ) type Channel struct { - Name string // Channel name, typically equals to Channel key, can get overridden in x-go-name + OriginalName string // Channel name, typically equals to Channel key, can get overridden in x-go-name TypeNamePrefix string // Prefix for a proto channel type name Dummy bool SpecKey string // Key in the source document @@ -16,11 +16,12 @@ type Channel struct { IsPublisher bool // true if channel has `publish` operation IsSubscriber bool // true if channel has `subscribe` operation + IsComponent bool // true if channel is defined in `components` section ParametersType *lang.GoStruct // nil if no parameters - PublisherMessageTypePromise *lang.Promise[*Message] // nil when message is not set - SubscribeMessageTypePromise *lang.Promise[*Message] // nil when message is not set + PublisherMessageTypePromise *lang.Promise[*Message] // nil when message is not set + SubscriberMessageTypePromise *lang.Promise[*Message] // nil when message is not set BindingsType *lang.GoStruct // nil if no bindings are set for channel at all BindingsChannelPromise *lang.Promise[*Bindings] // nil if channel bindings are not set @@ -35,7 +36,11 @@ func (c *Channel) Kind() common.ObjectKind { } func (c *Channel) Selectable() bool { - return !c.Dummy + return !c.Dummy && !c.IsComponent // Select only the channels defined in the `channels` section` +} + +func (c *Channel) GetOriginalName() string { + return c.OriginalName } //ServersProtocols returns supported protocol list for the given servers, throwing out unsupported ones @@ -57,7 +62,7 @@ func (c *Channel) Selectable() bool { //func (c Channel) D(ctx *common.RenderContext) []*j.Statement { // var res []*j.Statement -// ctx.LogStartRender("Channel", "", c.Name, "definition", c.Selectable()) +// ctx.LogStartRender("Channel", "", c.GetOriginalName, "definition", c.Selectable()) // defer ctx.LogFinishRender() // // // Parameters @@ -105,8 +110,8 @@ func (c *Channel) Selectable() bool { // res = append(res, r.D(ctx)...) // } // if len(protocols) == 0 { -// res = append(res, j.Comment(fmt.Sprintf("Channel %q is not assigned to any server with supported protocol, so no code to generate", c.Name))) -// ctx.Logger.Info("Channel is not assigned to any server with supported protocol, so no code to generate", "channel", c.Name) +// res = append(res, j.Comment(fmt.Sprintf("Channel %q is not assigned to any server with supported protocol, so no code to generate", c.GetOriginalName))) +// ctx.Logger.Info("Channel is not assigned to any server with supported protocol, so no code to generate", "channel", c.GetOriginalName) // } // return res //} @@ -116,18 +121,15 @@ func (c *Channel) Selectable() bool { //} // //func (c Channel) ID() string { -// return c.Name +// return c.GetOriginalName //} // func (c *Channel) String() string { - return "Channel " + c.Name + return "Channel " + c.OriginalName } func (c *Channel) ProtoObjects() []common.Renderable { - k := lo.FilterMap(c.ProtoChannels, func(p *ProtoChannel, _ int) (common.Renderable, bool) { - return p, p.Selectable() - }) - return k + return lo.Map(c.ProtoChannels, func(p *ProtoChannel, _ int) common.Renderable { return p }) } //func (c Channel) renderChannelNameFunc(ctx *common.RenderContext) []*j.Statement { @@ -135,7 +137,7 @@ func (c *Channel) ProtoObjects() []common.Renderable { // // // Channel1Name(params Chan1Parameters) runtime.ParamString // return []*j.Statement{ -// j.Func().Id(c.TypeNamePrefix+"Name"). +// j.Func().Id(c.TypeNamePrefix+"GetOriginalName"). // ParamsFunc(func(g *j.Group) { // if c.ParametersType != nil { // g.Id("params").Add(utils.ToCode(c.ParametersType.U(ctx))...) @@ -150,7 +152,7 @@ func (c *Channel) ProtoObjects() []common.Renderable { // } else { // bg.Op("paramMap := map[string]string").Values(j.DictFunc(func(d j.Dict) { // for _, f := range c.ParametersType.Fields { -// d[j.Id("params").Dot(f.Name).Dot("Name").Call()] = j.Id("params").Dot(f.Name).Dot("String").Call() +// d[j.Id("params").Dot(f.GetOriginalName).Dot("GetOriginalName").Call()] = j.Id("params").Dot(f.GetOriginalName).Dot("String").Call() // } // })) // bg.Return(j.Qual(ctx.RuntimeModule(""), "ParamString").Values(j.Dict{ @@ -180,7 +182,7 @@ func (c *Channel) BindingsProtocols() (res []string) { func (c *Channel) ProtoBindingsValue(protoName string) common.Renderable { res := &lang.GoValue{ - Type: &lang.GoSimple{Name: "ChannelBindings", Import: common.GetContext().RuntimeModule(protoName)}, + Type: &lang.GoSimple{OriginalName: "ChannelBindings", Import: common.GetContext().RuntimeModule(protoName)}, EmptyCurlyBrackets: true, } if c.BindingsChannelPromise != nil { @@ -220,13 +222,14 @@ func (p *ProtoChannel) Kind() common.ObjectKind { } func (p *ProtoChannel) String() string { - return "ProtoChannel " + p.Name + return "ProtoChannel " + p.OriginalName } // isBound returns true if channel is bound to at least one server with supported protocol func (p *ProtoChannel) isBound() bool { + protos := lo.Map(p.ServersPromise.T(), func(s *Server, _ int) string { return s.Protocol }) r := lo.Contains( - lo.Map(p.ServersPromise.T(), func(s *Server, _ int) string { return s.Protocol }), + protos, p.ProtoName, ) return r diff --git a/internal/render/context/context.go b/internal/render/context/context.go index eea44f4..6d705a2 100644 --- a/internal/render/context/context.go +++ b/internal/render/context/context.go @@ -6,6 +6,7 @@ import ( "github.com/bdragon300/go-asyncapi/internal/common" "github.com/bdragon300/go-asyncapi/internal/utils" "github.com/samber/lo" + "go/token" "path" "slices" "strings" @@ -16,7 +17,8 @@ import ( type RenderContextImpl struct { RenderOpts common.RenderOpts CurrentSelectionConfig common.RenderSelectionConfig - imports map[string]common.ImportItem // Key: package path + FileHeader *RenderFileHeader + Object common.CompileObject } func (c *RenderContextImpl) RuntimeModule(subPackage string) string { @@ -24,8 +26,12 @@ func (c *RenderContextImpl) RuntimeModule(subPackage string) string { } func (c *RenderContextImpl) QualifiedName(parts ...string) string { - pkgPath, pkgName, name := qualifiedToImport(parts) - return fmt.Sprintf("%s.%s", c.importPackage(pkgPath, pkgName), utils.ToGolangName(name, unicode.IsUpper(rune(name[0])))) + pkgPath, pkgName, n := qualifiedToImport(parts) + var name string + if n != "" { + name = utils.ToGolangName(n, unicode.IsUpper(rune(n[0]))) + } + return fmt.Sprintf("%s.%s", c.FileHeader.addImport(pkgPath, pkgName), name) } // QualifiedGeneratedPackage checks if the object is in the generated package of CurrentSelectionConfig and returns @@ -38,20 +44,25 @@ func (c *RenderContextImpl) QualifiedGeneratedPackage(obj common.GolangType) (st if defInfo == nil { return "", nil // Object has no definition (e.g. Go built-in types) } - d := path.Dir(defInfo.Selection.File) - if d == path.Dir(c.CurrentSelectionConfig.File) { - return "", nil // Object is defined in the current package, it name doesn't require a package name + // Check if the object is defined in the same directory (assuming the directory is equal to package) + fileDir := path.Dir(defInfo.Selection.File) + if fileDir == path.Dir(c.CurrentSelectionConfig.File) { + return "", nil // Object is defined in the current package, its name doesn't require a package name } - b, _ := path.Split(d) - pkgPath := path.Join(c.RenderOpts.ImportBase, b, defInfo.Selection.Package) - return c.importPackage(pkgPath, defInfo.Selection.Package), nil + parentDir := path.Dir(fileDir) + pkgPath := path.Join(c.RenderOpts.ImportBase, parentDir, defInfo.Selection.Package) + return c.FileHeader.addImport(pkgPath, defInfo.Selection.Package), nil } func (c *RenderContextImpl) QualifiedRuntimeName(parts ...string) string { - p := append([]string{c.RenderOpts.ImportBase}, parts...) - pkgPath, pkgName, name := qualifiedToImport(p) - return fmt.Sprintf("%s.%s", c.importPackage(pkgPath, pkgName), utils.ToGolangName(name, unicode.IsUpper(rune(name[0])))) + p := append([]string{c.RenderOpts.RuntimeModule}, parts...) + pkgPath, pkgName, n := qualifiedToImport(p) + var name string + if n != "" { + name = utils.ToGolangName(n, unicode.IsUpper(rune(n[0]))) + } + return fmt.Sprintf("%s.%s", c.FileHeader.addImport(pkgPath, pkgName), name) } func (c *RenderContextImpl) CurrentDefinitionInfo() *common.GolangTypeDefinitionInfo { @@ -62,31 +73,50 @@ func (c *RenderContextImpl) CurrentSelection() common.RenderSelectionConfig { return c.CurrentSelectionConfig } -func (c *RenderContextImpl) Imports() []common.ImportItem { - res := lo.Values(c.imports) +func (c *RenderContextImpl) CurrentObject() common.CompileObject { + return c.Object +} + + +func NewRenderFileHeader(packageName string) *RenderFileHeader { + return &RenderFileHeader{packageName: packageName} +} + +type RenderFileHeader struct { + packageName string + imports map[string]common.ImportItem +} + +func (s *RenderFileHeader) Imports() []common.ImportItem { + res := lo.Values(s.imports) slices.SortFunc(res, func(a, b common.ImportItem) int { return cmp.Compare(a.PackagePath, b.PackagePath) }) return res } -func (c *RenderContextImpl) importPackage(pkgPath string, pkgName string) string { - if c.imports == nil { - c.imports = make(map[string]common.ImportItem) +func (s *RenderFileHeader) PackageName() string { + return s.packageName +} + +func (s *RenderFileHeader) addImport(pkgPath string, pkgName string) string { + if s.imports == nil { + s.imports = make(map[string]common.ImportItem) } - if _, ok := c.imports[pkgPath]; !ok { + if _, ok := s.imports[pkgPath]; !ok { res := common.ImportItem{PackageName: pkgName, PackagePath: pkgPath} - // Find imports with the same package name - namesakes := lo.Filter(lo.Entries(c.imports), func(item lo.Entry[string, common.ImportItem], _ int) bool { + // Generate alias if the package with the same name already imported, or its name is not a valid Go identifier (e.g. "go-asyncapi") + namesakes := lo.Filter(lo.Entries(s.imports), func(item lo.Entry[string, common.ImportItem], _ int) bool { return item.Key != pkgPath && item.Value.PackageName == pkgName }) - if len(namesakes) > 0 { - res.Alias = fmt.Sprintf("%s%d", pkgName, len(namesakes)+1) // Generate a new alias to avoid package name conflict + if len(namesakes) > 0 || !token.IsIdentifier(pkgName) { + // Generate a new alias to avoid package name conflict + res.Alias = fmt.Sprintf("%s%d", utils.ToGolangName(pkgName, false), len(namesakes)+1) } - c.imports[pkgPath] = res + s.imports[pkgPath] = res } - if v := c.imports[pkgPath]; v.Alias != "" { + if v := s.imports[pkgPath]; v.Alias != "" { return v.Alias // Return alias } return pkgName @@ -129,7 +159,7 @@ func qualifiedToImport(parts []string) (pkgPath string, pkgName string, name str // parts["a/b/c"] -> ["a/b/c", "c", ""] // parts["a", "x"] -> ["a", "a", "x"] // parts["a/b.c", "x"] -> ["a/b.c", "bc", "x"] - // parts["n", "d", "a/b.c", "x"] -> ["n/d/a/b.c", "bc", "x"] + // parts["n", "d", "a/b.c", "x"] -> ["n/d/a/b.c-e", "b.c-e", "x"] switch len(parts) { case 0: panic("Empty parameters, at least one is required") @@ -146,6 +176,5 @@ func qualifiedToImport(parts []string) (pkgPath string, pkgName string, name str if pos := strings.LastIndex(pkgPath, "/"); pos >= 0 { pkgName = pkgPath[pos+1:] } - pkgName = strings.ReplaceAll(pkgName, ".", "") return } \ No newline at end of file diff --git a/internal/render/correlationid.go b/internal/render/correlationid.go index 7c33e22..34e991e 100644 --- a/internal/render/correlationid.go +++ b/internal/render/correlationid.go @@ -3,6 +3,7 @@ package render import ( "fmt" "github.com/bdragon300/go-asyncapi/internal/render/lang" + "github.com/bdragon300/go-asyncapi/internal/tmpl" "github.com/bdragon300/go-asyncapi/internal/utils" "net/url" "strconv" @@ -23,7 +24,7 @@ const ( // CorrelationID never renders itself, only as a part of message struct type CorrelationID struct { - Name string + OriginalName string Description string StructField CorrelationIDStructField // Type field name to store the value to or to load the value from LocationPath []string // JSONPointer path to the field in the message, should be non-empty @@ -37,6 +38,10 @@ func (c *CorrelationID) Selectable() bool { return false } +func (c *CorrelationID) GetOriginalName() string { + return c.OriginalName +} + //func (c CorrelationID) D(_ *common.RenderContext) []*j.Statement { // panic("not implemented") //} @@ -46,15 +51,15 @@ func (c *CorrelationID) Selectable() bool { //} // //func (c CorrelationID) ID() string { -// return c.Name +// return c.GetOriginalName //} func (c *CorrelationID) String() string { - return "CorrelationID " + c.Name + return "CorrelationID " + c.OriginalName } func (c *CorrelationID) RenderSetterBody(inVar string, inVarType *lang.GoStruct) string { - //ctx.LogStartRender("CorrelationID.RenderSetterBody", "", c.Name, "definition", false) + //ctx.LogStartRender("CorrelationID.RenderSetterBody", "", c.GetOriginalName, "definition", false) //defer ctx.LogFinishRender() f, ok := lo.Find(inVarType.Fields, func(item lang.GoStructField) bool { return item.Name == string(c.StructField) }) @@ -110,10 +115,10 @@ func (c *CorrelationID) TargetVarType(varType *lang.GoStruct) common.GolangType } //func (c CorrelationID) RenderSetterDefinition(ctx *common.RenderContext, message *Message) []*j.Statement { -// ctx.LogStartRender("CorrelationID.RenderSetterDefinition", "", c.Name, "definition", false) +// ctx.LogStartRender("CorrelationID.RenderSetterDefinition", "", c.GetOriginalName, "definition", false) // defer ctx.LogFinishRender() // -// f, ok := lo.Find(message.OutType.Fields, func(item GoStructField) bool { return item.Name == c.StructField }) +// f, ok := lo.Find(message.OutType.Fields, func(item GoStructField) bool { return item.GetOriginalName == c.StructField }) // if !ok { // panic(fmt.Errorf("field %s not found in OutType", c.StructField)) // } @@ -146,7 +151,7 @@ func (c *CorrelationID) TargetVarType(varType *lang.GoStruct) common.GolangType // } // codeLines = append(codeLines, j.Id(message.OutType.ReceiverName()+"."+c.StructField).Op("= v0")) // -// receiver := j.Id(message.OutType.ReceiverName()).Id(message.OutType.Name) +// receiver := j.Id(message.OutType.ReceiverName()).Id(message.OutType.GetOriginalName) // // // Method SetCorrelationID(value any) // // TODO: comment from description @@ -158,7 +163,7 @@ func (c *CorrelationID) TargetVarType(varType *lang.GoStruct) common.GolangType //} func (c *CorrelationID) RenderGetterBody(outVar string, outVarType *lang.GoStruct) string { - //ctx.LogStartRender("CorrelationID.RenderGetterDefinition", "", c.Name, "definition", false) + //ctx.LogStartRender("CorrelationID.RenderGetterDefinition", "", c.GetOriginalName, "definition", false) //defer ctx.LogFinishRender() f, ok := lo.Find(outVarType.Fields, func(item lang.GoStructField) bool { return item.Name == string(c.StructField) }) @@ -189,10 +194,10 @@ func (c *CorrelationID) RenderGetterBody(outVar string, outVarType *lang.GoStruc } //func (c CorrelationID) RenderGetterDefinition(ctx *common.RenderContext, message *Message) []*j.Statement { -// ctx.LogStartRender("CorrelationID.RenderGetterDefinition", "", c.Name, "definition", false) +// ctx.LogStartRender("CorrelationID.RenderGetterDefinition", "", c.GetOriginalName, "definition", false) // defer ctx.LogFinishRender() // -// f, ok := lo.Find(message.InType.Fields, func(item GoStructField) bool { return item.Name == c.StructField }) +// f, ok := lo.Find(message.InType.Fields, func(item GoStructField) bool { return item.GetOriginalName == c.StructField }) // if !ok { // panic(fmt.Errorf("field %s not found in InType", c.StructField)) // } @@ -214,7 +219,7 @@ func (c *CorrelationID) RenderGetterBody(outVar string, outVarType *lang.GoStruc // codeLines = append(codeLines, lo.FlatMap(bodySteps, func(item correlationIDExpansionStep, _ int) []*j.Statement { // return item.codeLines // })...) -// receiver := j.Id(message.InType.ReceiverName()).Id(message.InType.Name) +// receiver := j.Id(message.InType.ReceiverName()).Id(message.InType.GetOriginalName) // // codeLines = append(codeLines, // j.Id("value").Op("=").Id(bodySteps[len(bodySteps)-1].varName), @@ -270,7 +275,7 @@ func (c *CorrelationID) renderValueExtractionCode( if !ok { err = fmt.Errorf( "field %q not found in struct %s, path: /%s", - memberName, typ.Name, strings.Join(path[:pathIdx], "/"), + memberName, typ.OriginalName, strings.Join(path[:pathIdx], "/"), ) return } @@ -282,10 +287,10 @@ func (c *CorrelationID) renderValueExtractionCode( //ctx.Logger.Trace("In GoMap", "path", path[:pathIdx], "name", typ.ID(), "member", memberName) varValueStmts = fmt.Sprintf("%s[%s]", anchor, utils.ToGoLiteral(memberName)) baseType = typ.ValueType - varExpr := fmt.Sprintf("var %s %s", nextAnchor, typ.ValueType.U()) - if t, ok := typ.ValueType.(lang.GolangPointerType); ok && t.IsPointer() { + varExpr := fmt.Sprintf("var %s %s", nextAnchor, lo.Must(tmpl.TemplateGoUsage(typ.ValueType))) + if typ.ValueType.IsPointer() { // Append ` = new(TYPE)` to initialize a pointer - varExpr += fmt.Sprintf(" = new(%s)", typ.ValueType.U()) + varExpr += fmt.Sprintf(" = new(%s)", lo.Must(tmpl.TemplateGoUsage(typ.ValueType))) } ifExpr := fmt.Sprintf(`if v, ok := %s; ok { @@ -301,7 +306,7 @@ func (c *CorrelationID) renderValueExtractionCode( body = []string{ fmt.Sprintf(`if %s == nil { %s = make(%s) - }`, anchor, anchor, typ.U()), + }`, anchor, anchor, lo.Must(tmpl.TemplateGoUsage(typ))), varExpr, ifExpr, } @@ -311,7 +316,7 @@ func (c *CorrelationID) renderValueExtractionCode( err = fmt.Errorf( "index %q is not a number, array %s, path: /%s", memberName, - typ.Name, + typ.OriginalName, strings.Join(path[:pathIdx], "/"), ) return @@ -331,7 +336,7 @@ func (c *CorrelationID) renderValueExtractionCode( if pathIdx >= len(path)-1 { // Primitive types should get addressed by the last path item err = fmt.Errorf( "type %q cannot be resolved further, path: /%s", - typ.TypeName(), + typ.GetOriginalName(), // TODO: check if this is correct strings.Join(path[:pathIdx], "/"), ) return @@ -357,7 +362,7 @@ func (c *CorrelationID) renderValueExtractionCode( //ctx.Logger.Trace("Unknown type", "path", path[:pathIdx], "name", typ.String(), "type", fmt.Sprintf("%T", typ)) err = fmt.Errorf( "type %s is not addressable, path: /%s", - typ.TypeName(), + typ.GetOriginalName(), // TODO: check if this is correct strings.Join(path[:pathIdx], "/"), ) return diff --git a/internal/render/http/channel.go b/internal/render/http/channel.go index 5051de9..51d96ed 100644 --- a/internal/render/http/channel.go +++ b/internal/render/http/channel.go @@ -13,7 +13,7 @@ package http //} //func (pc ProtoChannel) D(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Channel", "", pc.Parent.Name, "definition", pc.Selectable(), "proto", pc.ProtoName) +// ctx.LogStartRender("Channel", "", pc.Parent.GetOriginalName, "definition", pc.Selectable(), "proto", pc.ProtoName) // defer ctx.LogFinishRender() // var res []*j.Statement // res = append(res, pc.ServerIface.D(ctx)...) @@ -33,17 +33,17 @@ package http //} //func (pc ProtoChannel) U(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Channel", "", pc.Parent.Name, "usage", pc.Selectable(), "proto", pc.ProtoName) +// ctx.LogStartRender("Channel", "", pc.Parent.GetOriginalName, "usage", pc.Selectable(), "proto", pc.ProtoName) // defer ctx.LogFinishRender() // return pc.Type.U(ctx) //} //func (pc ProtoChannel) ID() string { -// return pc.Parent.Name +// return pc.Parent.GetOriginalName //} // //func (pc ProtoChannel) String() string { -// return "HTTP ProtoChannel " + pc.Parent.Name +// return "HTTP ProtoChannel " + pc.Parent.GetOriginalName //} //func (pc ProtoChannel) renderNewFunc(ctx *common.RenderContext) []*j.Statement { @@ -66,7 +66,7 @@ package http // Op("*").Add(utils.ToCode(pc.Type.U(ctx))...). // BlockFunc(func(bg *j.Group) { // bg.Op("res := ").Add(utils.ToCode(pc.Type.U(ctx))...).Values(j.DictFunc(func(d j.Dict) { -// d[j.Id("name")] = j.Id(pc.Parent.TypeNamePrefix + "Name").CallFunc(func(g *j.Group) { +// d[j.Id("name")] = j.Id(pc.Parent.TypeNamePrefix + "GetOriginalName").CallFunc(func(g *j.Group) { // if pc.Parent.ParametersType != nil { // g.Id("params") // } @@ -91,7 +91,7 @@ package http // ctx.Logger.Trace("renderProtoPublisherMethods", "proto", pc.ProtoName) // // rn := pc.Type.ReceiverName() -// receiver := j.Id(rn).Id(pc.Type.Name) +// receiver := j.Id(rn).Id(pc.Type.GetOriginalName) // // var msgTyp common.GolangType = render.GoPointer{Type: pc.Parent.FallbackMessageType, HasDefinition: true} // if pc.Parent.PublisherMessageTypePromise != nil { diff --git a/internal/render/http/server.go b/internal/render/http/server.go index 78b1918..3e0cc9b 100644 --- a/internal/render/http/server.go +++ b/internal/render/http/server.go @@ -12,7 +12,7 @@ package http //} // //func (ps ProtoServer) D(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Server", "", ps.Parent.Name, "definition", ps.Selectable(), "proto", ps.ProtoName) +// ctx.LogStartRender("Server", "", ps.Parent.GetOriginalName, "definition", ps.Selectable(), "proto", ps.ProtoName) // defer ctx.LogFinishRender() // var res []*j.Statement // res = append(res, ps.RenderNewFunc(ctx)...) @@ -25,17 +25,17 @@ package http //} // //func (ps ProtoServer) U(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Server", "", ps.Parent.Name, "usage", ps.Selectable(), "proto", ps.ProtoName) +// ctx.LogStartRender("Server", "", ps.Parent.GetOriginalName, "usage", ps.Selectable(), "proto", ps.ProtoName) // defer ctx.LogFinishRender() // return ps.Type.U(ctx) //} // //func (ps ProtoServer) ID() string { -// return ps.Parent.Name +// return ps.Parent.GetOriginalName //} // //func (ps ProtoServer) String() string { -// return "HTTP ProtoServer " + ps.Parent.Name +// return "HTTP ProtoServer " + ps.Parent.GetOriginalName //} //func (ps ProtoServer) renderChannelMethods(ctx *common.RenderContext) []*j.Statement { diff --git a/internal/render/ip/channel.go b/internal/render/ip/channel.go index 0915cb5..f6cb3fe 100644 --- a/internal/render/ip/channel.go +++ b/internal/render/ip/channel.go @@ -13,7 +13,7 @@ package ip //} // //func (pc ProtoChannel) D(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Channel", "", pc.Parent.Name, "definition", pc.Selectable(), "proto", pc.ProtoName) +// ctx.LogStartRender("Channel", "", pc.Parent.GetOriginalName, "definition", pc.Selectable(), "proto", pc.ProtoName) // defer ctx.LogFinishRender() // var res []*j.Statement // res = append(res, pc.ServerIface.D(ctx)...) @@ -33,17 +33,17 @@ package ip //} // //func (pc ProtoChannel) U(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Channel", "", pc.Parent.Name, "usage", pc.Selectable(), "proto", pc.ProtoName) +// ctx.LogStartRender("Channel", "", pc.Parent.GetOriginalName, "usage", pc.Selectable(), "proto", pc.ProtoName) // defer ctx.LogFinishRender() // return pc.Type.U(ctx) //} // //func (pc ProtoChannel) ID() string { -// return pc.Parent.Name +// return pc.Parent.GetOriginalName //} // //func (pc ProtoChannel) String() string { -// return "IP ProtoChannel " + pc.Parent.Name +// return "IP ProtoChannel " + pc.Parent.GetOriginalName //} //func (pc ProtoChannel) renderNewFunc(ctx *common.RenderContext) []*j.Statement { @@ -66,7 +66,7 @@ package ip // Op("*").Add(utils.ToCode(pc.Type.U(ctx))...). // BlockFunc(func(bg *j.Group) { // bg.Op("res := ").Add(utils.ToCode(pc.Type.U(ctx))...).Values(j.DictFunc(func(d j.Dict) { -// d[j.Id("name")] = j.Id(pc.Parent.TypeNamePrefix + "Name").CallFunc(func(g *j.Group) { +// d[j.Id("name")] = j.Id(pc.Parent.TypeNamePrefix + "GetOriginalName").CallFunc(func(g *j.Group) { // if pc.Parent.ParametersType != nil { // g.Id("params") // } @@ -91,7 +91,7 @@ package ip // ctx.Logger.Trace("renderProtoPublisherMethods", "proto", pc.ProtoName) // // rn := pc.Type.ReceiverName() -// receiver := j.Id(rn).Id(pc.Type.Name) +// receiver := j.Id(rn).Id(pc.Type.GetOriginalName) // // var msgTyp common.GolangType = render.GoPointer{Type: pc.Parent.FallbackMessageType, HasDefinition: true} // if pc.Parent.PublisherMessageTypePromise != nil { diff --git a/internal/render/ip/server.go b/internal/render/ip/server.go index ebea892..93787d1 100644 --- a/internal/render/ip/server.go +++ b/internal/render/ip/server.go @@ -12,7 +12,7 @@ package ip //} // //func (ps ProtoServer) D(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Server", "", ps.Parent.Name, "definition", ps.Selectable(), "proto", ps.ProtoName) +// ctx.LogStartRender("Server", "", ps.Parent.GetOriginalName, "definition", ps.Selectable(), "proto", ps.ProtoName) // defer ctx.LogFinishRender() // var res []*j.Statement // res = append(res, ps.RenderNewFunc(ctx)...) @@ -25,17 +25,17 @@ package ip //} //func (ps ProtoServer) U(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Server", "", ps.Parent.Name, "usage", ps.Selectable(), "proto", ps.ProtoName) +// ctx.LogStartRender("Server", "", ps.Parent.GetOriginalName, "usage", ps.Selectable(), "proto", ps.ProtoName) // defer ctx.LogFinishRender() // return ps.Type.U(ctx) //} // //func (ps ProtoServer) ID() string { -// return ps.Parent.Name +// return ps.Parent.GetOriginalName //} // //func (ps ProtoServer) String() string { -// return "IP ProtoServer " + ps.Parent.Name +// return "IP ProtoServer " + ps.Parent.GetOriginalName //} // //func (ps ProtoServer) renderChannelMethods(ctx *common.RenderContext) []*j.Statement { diff --git a/internal/render/kafka/channel.go b/internal/render/kafka/channel.go index 8d8efd3..f8e42ff 100644 --- a/internal/render/kafka/channel.go +++ b/internal/render/kafka/channel.go @@ -13,7 +13,7 @@ package kafka //} // //func (pc ProtoChannel) D(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Channel", "", pc.Parent.Name, "definition", pc.Selectable(), "proto", pc.ProtoName) +// ctx.LogStartRender("Channel", "", pc.Parent.GetOriginalName, "definition", pc.Selectable(), "proto", pc.ProtoName) // defer ctx.LogFinishRender() // var res []*j.Statement // res = append(res, pc.ServerIface.D(ctx)...) @@ -33,17 +33,17 @@ package kafka //} //func (pc ProtoChannel) U(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Channel", "", pc.Parent.Name, "usage", pc.Selectable(), "proto", pc.ProtoName) +// ctx.LogStartRender("Channel", "", pc.Parent.GetOriginalName, "usage", pc.Selectable(), "proto", pc.ProtoName) // defer ctx.LogFinishRender() // return pc.Type.U(ctx) //} // //func (pc ProtoChannel) ID() string { -// return pc.Parent.Name +// return pc.Parent.GetOriginalName //} // //func (pc ProtoChannel) String() string { -// return "Kafka ProtoChannel " + pc.Parent.Name +// return "Kafka ProtoChannel " + pc.Parent.GetOriginalName //} //func (pc ProtoChannel) renderNewFunc(ctx *common.RenderContext) []*j.Statement { @@ -66,7 +66,7 @@ package kafka // Op("*").Add(utils.ToCode(pc.Type.U(ctx))...). // BlockFunc(func(bg *j.Group) { // bg.Op("res := ").Add(utils.ToCode(pc.Type.U(ctx))...).Values(j.DictFunc(func(d j.Dict) { -// d[j.Id("name")] = j.Id(pc.Parent.TypeNamePrefix + "Name").CallFunc(func(g *j.Group) { +// d[j.Id("name")] = j.Id(pc.Parent.TypeNamePrefix + "GetOriginalName").CallFunc(func(g *j.Group) { // if pc.Parent.ParametersType != nil { // g.Id("params") // } @@ -95,7 +95,7 @@ package kafka // ctx.Logger.Trace("renderProtoMethods", "proto", pc.ProtoName) // // rn := pc.Type.ReceiverName() -// receiver := j.Id(rn).Id(pc.Type.Name) +// receiver := j.Id(rn).Id(pc.Type.GetOriginalName) // // return []*j.Statement{ // // Method Topic() string @@ -112,7 +112,7 @@ package kafka // ctx.Logger.Trace("renderProtoPublisherMethods", "proto", pc.ProtoName) // // rn := pc.Type.ReceiverName() -// receiver := j.Id(rn).Id(pc.Type.Name) +// receiver := j.Id(rn).Id(pc.Type.GetOriginalName) // // var msgTyp common.GolangType = render.GoPointer{Type: pc.Parent.FallbackMessageType, HasDefinition: true} // if pc.Parent.PublisherMessageTypePromise != nil { diff --git a/internal/render/kafka/server.go b/internal/render/kafka/server.go index 31c05d6..8bf7e60 100644 --- a/internal/render/kafka/server.go +++ b/internal/render/kafka/server.go @@ -12,7 +12,7 @@ package kafka //} // //func (ps ProtoServer) D(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Server", "", ps.Parent.Name, "definition", ps.Selectable(), "proto", ps.ProtoName) +// ctx.LogStartRender("Server", "", ps.Parent.GetOriginalName, "definition", ps.Selectable(), "proto", ps.ProtoName) // defer ctx.LogFinishRender() // var res []*j.Statement // res = append(res, ps.RenderNewFunc(ctx)...) @@ -25,17 +25,17 @@ package kafka //} // //func (ps ProtoServer) U(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Server", "", ps.Parent.Name, "usage", ps.Selectable(), "proto", ps.ProtoName) +// ctx.LogStartRender("Server", "", ps.Parent.GetOriginalName, "usage", ps.Selectable(), "proto", ps.ProtoName) // defer ctx.LogFinishRender() // return ps.Type.U(ctx) //} // //func (ps ProtoServer) ID() string { -// return ps.Parent.Name +// return ps.Parent.GetOriginalName //} // //func (ps ProtoServer) String() string { -// return "Kafka ProtoServer " + ps.Parent.Name +// return "Kafka ProtoServer " + ps.Parent.GetOriginalName //} // //func (ps ProtoServer) renderChannelMethods(ctx *common.RenderContext) []*j.Statement { diff --git a/internal/render/lang/base.go b/internal/render/lang/base.go index 474f0ff..e1f1db3 100644 --- a/internal/render/lang/base.go +++ b/internal/render/lang/base.go @@ -2,13 +2,11 @@ package lang import ( "github.com/bdragon300/go-asyncapi/internal/common" - "github.com/bdragon300/go-asyncapi/internal/tpl" - "strings" ) type BaseType struct { - Name string - Description string + OriginalName string + Description string // HasDefinition is true if this type should have a definition in the generated code. Otherwise, it renders as // inline type. Such as inlined `field struct{...}` and separate `field StructName`, or `field []type` @@ -26,17 +24,13 @@ func (b *BaseType) Selectable() bool { return b.HasDefinition } -func (b *BaseType) TypeName() string { - return b.Name -} - func (b *BaseType) IsPointer() bool { return false } func (b *BaseType) DefinitionInfo() (*common.GolangTypeDefinitionInfo, error) { if b.definitionInfo == nil { - return nil, common.ErrDefinitionNotRendered + return nil, common.ErrDefinitionLocationUnknown } return b.definitionInfo, nil } @@ -45,29 +39,14 @@ func (b *BaseType) SetDefinitionInfo(info *common.GolangTypeDefinitionInfo) { b.definitionInfo = info } -type GolangTypeWrapperType interface { - UnwrapGolangType() (common.GolangType, bool) - //String() string +func (b *BaseType) GetOriginalName() string { + return b.OriginalName } -type GolangPointerType interface { // TODO: replace with common.GolangType? or move where it is used - IsPointer() bool +type GolangTypeWrapperType interface { + UnwrapGolangType() (common.GolangType, bool) } type golangStructType interface { IsStruct() bool } - -func renderTemplate[T common.Renderable](name string, obj T) string { - var b strings.Builder - tmpl := tpl.LoadTemplate(name) - if tmpl == nil { - panic("template not found: " + name) - } - - //tmpl = tmpl.Funcs(tpl.GetTemplateFunctions(context.GetContext())) - if err := tmpl.Execute(&b, obj); err != nil { - panic(err) - } - return b.String() -} \ No newline at end of file diff --git a/internal/render/lang/goarray.go b/internal/render/lang/goarray.go index 3b90d1a..1595b14 100644 --- a/internal/render/lang/goarray.go +++ b/internal/render/lang/goarray.go @@ -10,52 +10,13 @@ type GoArray struct { Size int } -func (a *GoArray) D() string { - //ctx.LogStartRender("GoArray", a.Import, a.Name, "definition", a.Selectable()) - //defer ctx.LogFinishRender() - // - //var b strings.Builder - //if a.Description != "" { - // res = append(res, jen.Comment(a.Name+" -- "+utils.ToLowerFirstLetter(a.Description))) - //} - // - //stmt := jen.Type().Id(a.Name) - //if a.Size > 0 { - // stmt = stmt.Index(jen.Lit(a.Size)) - //} else { - // stmt = stmt.Index() - //} - //items := utils.ToCode(a.ItemsType.U()) - //res = append(res, stmt.Add(items...)) - // - //return res - a.SetDefinitionInfo(common.GetContext().CurrentDefinitionInfo()) - return renderTemplate("lang/goarray/definition", a) -} - -func (a *GoArray) U() string { - //ctx.LogStartRender("GoArray", a.Import, a.Name, "usage", a.Selectable()) - //defer ctx.LogFinishRender() - // - //if a.HasDefinition { - // if a.Import != "" && a.Import != context.Context.CurrentPackage { - // return []*jen.Statement{jen.Qual(context.Context.GeneratedModule(a.Import), a.Name)} - // } - // return []*jen.Statement{jen.Id(a.Name)} - //} - // - //items := utils.ToCode(a.ItemsType.U()) - //if a.Size > 0 { - // return []*jen.Statement{jen.Index(jen.Lit(a.Size)).Add(items...)} - //} - // - //return []*jen.Statement{jen.Index().Add(items...)} - return renderTemplate("lang/goarray/usage", a) +func (a *GoArray) GoTemplate() string { + return "lang/goarray" } func (a *GoArray) String() string { if a.Import != "" { - return "GoArray /" + a.Import + "." + a.Name + return "GoArray /" + a.Import + "." + a.OriginalName } - return "GoArray " + a.Name + return "GoArray " + a.OriginalName } \ No newline at end of file diff --git a/internal/render/lang/gomap.go b/internal/render/lang/gomap.go index a001283..47b3b01 100644 --- a/internal/render/lang/gomap.go +++ b/internal/render/lang/gomap.go @@ -10,45 +10,13 @@ type GoMap struct { ValueType common.GolangType } -func (m *GoMap) D() string { - //ctx.LogStartRender("GoMap", m.Import, m.Name, "definition", m.Selectable()) - //defer ctx.LogFinishRender() - // - //var res []*jen.Statement - //if m.Description != "" { - // res = append(res, jen.Comment(m.Name+" -- "+utils.ToLowerFirstLetter(m.Description))) - //} - // - //stmt := jen.Type().Id(m.Name) - //keyType := utils.ToCode(m.KeyType.U()) - //valueType := utils.ToCode(m.ValueType.U()) - //res = append(res, stmt.Map((&jen.Statement{}).Add(keyType...)).Add(valueType...)) - // - //return res - m.SetDefinitionInfo(common.GetContext().CurrentDefinitionInfo()) - return renderTemplate("lang/gomap/definition", m) -} - -func (m *GoMap) U() string { - //ctx.LogStartRender("GoMap", m.Import, m.Name, "usage", m.Selectable()) - //defer ctx.LogFinishRender() - // - //if m.HasDefinition { - // if m.Import != "" && m.Import != context.Context.CurrentPackage { - // return []*jen.Statement{jen.Qual(context.Context.GeneratedModule(m.Import), m.Name)} - // } - // return []*jen.Statement{jen.Id(m.Name)} - //} - // - //keyType := utils.ToCode(m.KeyType.U()) - //valueType := utils.ToCode(m.ValueType.U()) - //return []*jen.Statement{jen.Map((&jen.Statement{}).Add(keyType...)).Add(valueType...)} - return renderTemplate("lang/gomap/usage", m) +func (m *GoMap) GoTemplate() string { + return "lang/gomap" } func (m *GoMap) String() string { if m.Import != "" { - return "GoMap /" + m.Import + "." + m.Name + return "GoMap /" + m.Import + "." + m.OriginalName } - return "GoMap " + m.Name + return "GoMap " + m.OriginalName } \ No newline at end of file diff --git a/internal/render/lang/gopointer.go b/internal/render/lang/gopointer.go index 9bf89be..b99e049 100644 --- a/internal/render/lang/gopointer.go +++ b/internal/render/lang/gopointer.go @@ -16,34 +16,18 @@ func (p *GoPointer) Selectable() bool { return p.Type.Selectable() } -func (p *GoPointer) D() string { - //ctx.LogStartRender("GoPointer", "", "", "definition", p.IsDefinition()) - //defer ctx.LogFinishRender() - return p.Type.D() -} - -func (p *GoPointer) U() string { - //ctx.LogStartRender("GoPointer", "", "", "usage", p.IsDefinition()) - //defer ctx.LogFinishRender() - - drawPtr := true - if v, ok := p.Type.(GolangPointerType); ok { - drawPtr = !v.IsPointer() // Prevent appearing pointer to pointer - } - if drawPtr { - return "*" + p.Type.U() - } - return p.Type.U() -} - -func (p *GoPointer) TypeName() string { - return p.Type.TypeName() +func (p *GoPointer) GoTemplate() string { + return "lang/gopointer" } func (p *GoPointer) String() string { return "GoPointer -> " + p.Type.String() } +func (p *GoPointer) GetOriginalName() string { + return "" +} + func (p *GoPointer) UnwrapGolangType() (common.GolangType, bool) { if v, ok := p.Type.(GolangTypeWrapperType); ok { return v.UnwrapGolangType() diff --git a/internal/render/lang/gosimple.go b/internal/render/lang/gosimple.go index d076e67..552f6f1 100644 --- a/internal/render/lang/gosimple.go +++ b/internal/render/lang/gosimple.go @@ -5,9 +5,9 @@ import ( ) type GoSimple struct { - Name string // type name - IsInterface bool // true if type is interface, which means it cannot be rendered as pointer // TODO: use or remove - Import string // optional generated package name or module to import a type from + OriginalName string // type name + IsInterface bool // true if type is interface, which means it cannot be rendered as pointer // TODO: use or remove + Import string // optional generated package name or module to import a type from } func (p *GoSimple) Kind() common.ObjectKind { @@ -22,40 +22,15 @@ func (p *GoSimple) IsPointer() bool { return false } -func (p *GoSimple) D() string { - //ctx.LogStartRender("GoSimple", p.Import, p.Name, "definition", p.Selectable()) - //defer ctx.LogFinishRender() - // - //stmt := jen.Id(p.Name) - //return []*jen.Statement{stmt} - return renderTemplate("lang/gosimple/definition", p) -} - -func (p *GoSimple) U() string { - //ctx.LogStartRender("GoSimple", p.Import, p.Name, "usage", p.Selectable()) - //defer ctx.LogFinishRender() - // - //stmt := &jen.Statement{} - //switch { - //case p.Import != "" && p.Import != context.Context.CurrentPackage: - // stmt = stmt.Qual(p.Import, p.Name) - //default: - // stmt = stmt.Id(p.Name) - //} - // - //return []*jen.Statement{stmt} - return renderTemplate("lang/gosimple/usage", p) -} - -func (p *GoSimple) TypeName() string { - return p.Name +func (p *GoSimple) GoTemplate() string { + return "lang/gosimple" } func (p *GoSimple) String() string { if p.Import != "" { - return "GoSimple /" + p.Import + "." + p.Name + return "GoSimple /" + p.Import + "." + p.OriginalName } - return "GoSimple " + p.Name + return "GoSimple " + p.OriginalName } func (p *GoSimple) DefinitionInfo() (*common.GolangTypeDefinitionInfo, error) { @@ -64,4 +39,8 @@ func (p *GoSimple) DefinitionInfo() (*common.GolangTypeDefinitionInfo, error) { func (p *GoSimple) SetDefinitionInfo(_ *common.GolangTypeDefinitionInfo) { // do nothing +} + +func (p *GoSimple) GetOriginalName() string { + return p.OriginalName } \ No newline at end of file diff --git a/internal/render/lang/gostruct.go b/internal/render/lang/gostruct.go index 4037b34..d360f06 100644 --- a/internal/render/lang/gostruct.go +++ b/internal/render/lang/gostruct.go @@ -23,56 +23,24 @@ func (s *GoStruct) Kind() common.ObjectKind { return s.ObjectKind } -func (s *GoStruct) D() string { - //var res []*jen.Statement - //ctx.LogStartRender("GoStruct", s.Import, s.Name, "definition", s.Selectable()) - //defer ctx.LogFinishRender() - // - //if s.Description != "" { - // res = append(res, jen.Comment(s.Name+" -- "+utils.ToLowerFirstLetter(s.Description))) - //} - //code := lo.FlatMap(s.Fields, func(item GoStructField, _ int) []*jen.Statement { - // return item.renderDefinition(ctx) - //}) - //res = append(res, jen.Type().Id(s.Name).Type(utils.ToCode(code)...)) - //return res - s.SetDefinitionInfo(common.GetContext().CurrentDefinitionInfo()) - return renderTemplate("lang/gostruct/definition", s) -} - -func (s *GoStruct) U() string { - //ctx.LogStartRender("GoStruct", s.Import, s.Name, "usage", s.IsDefinition()) - //defer ctx.LogFinishRender() - // - //if s.HasDefinition { - // if s.Import != "" && s.Import != context.Context.CurrentPackage { - // return []*jen.Statement{jen.Qual(context.Context.GeneratedModule(s.Import), s.Name)} - // } - // return []*jen.Statement{jen.Id(s.Name)} - //} - // - //code := lo.FlatMap(s.Fields, func(item GoStructField, _ int) []*jen.Statement { - // return item.renderDefinition() - //}) - // - //return []*jen.Statement{jen.Type(utils.ToCode(code)...)} - return renderTemplate("lang/gostruct/usage", s) +func (s *GoStruct) GoTemplate() string { + return "lang/gostruct" } //func (s GoStruct) NewFuncName() string { -// return "New" + s.Name +// return "New" + s.GetOriginalName //} //func (s GoStruct) ReceiverName() string { -// return strings.ToLower(string(s.Name[0])) +// return strings.ToLower(string(s.GetOriginalName[0])) //} //func (s GoStruct) MustGetField(name string) GoStructField { // f, ok := lo.Find(s.Fields, func(item GoStructField) bool { -// return item.Name == name +// return item.GetOriginalName == name // }) // if !ok { -// panic(fmt.Errorf("field %s.%s not found", s.Name, name)) +// panic(fmt.Errorf("field %s.%s not found", s.GetOriginalName, name)) // } // return f //} @@ -83,15 +51,15 @@ func (s *GoStruct) IsStruct() bool { func (s *GoStruct) String() string { if s.Import != "" { - return "GoStruct /" + s.Import + "." + s.Name + return "GoStruct /" + s.Import + "." + s.OriginalName } - return "GoStruct " + s.Name + return "GoStruct " + s.OriginalName } // GoStructField defines the data required to generate a field in Go. type GoStructField struct { - Name string - MarshalName string + Name string + MarshalName string Description string Type common.GolangType ContentTypesFunc func() []string // Returns list of content types associated with the struct @@ -102,14 +70,14 @@ type GoStructField struct { //func (f GoStructField) renderDefinition() []*jen.Statement { // var res []*jen.Statement -// ctx.LogStartRender("GoStructField", "", f.Name, "definition", false) +// ctx.LogStartRender("GoStructField", "", f.GetOriginalName, "definition", false) // defer ctx.LogFinishRender() // // if f.Description != "" { -// res = append(res, jen.Comment(f.Name+" -- "+utils.ToLowerFirstLetter(f.Description))) +// res = append(res, jen.Comment(f.GetOriginalName+" -- "+utils.ToLowerFirstLetter(f.Description))) // } // -// stmt := jen.Id(f.Name) +// stmt := jen.Id(f.GetOriginalName) // // items := utils.ToCode(f.Type.U()) // stmt = stmt.Add(items...) @@ -136,6 +104,9 @@ type GoStructField struct { func(f *GoStructField) RenderTags() string { tags := f.getTags() + if tags.Len() == 0 { + return "" + } var b strings.Builder for _, e := range tags.Entries() { diff --git a/internal/render/lang/gotypealias.go b/internal/render/lang/gotypealias.go index aeda9c1..e51f143 100644 --- a/internal/render/lang/gotypealias.go +++ b/internal/render/lang/gotypealias.go @@ -9,38 +9,8 @@ type GoTypeAlias struct { AliasedType common.GolangType } -func (p *GoTypeAlias) D() string { - //ctx.LogStartRender("GoTypeAlias", p.Import, p.Name, "definition", p.Selectable()) - //defer ctx.LogFinishRender() - // - //var res []*jen.Statement - //if p.Description != "" { - // res = append(res, jen.Comment(p.Name+" -- "+utils.ToLowerFirstLetter(p.Description))) - //} - // - //aliasedStmt := utils.ToCode(p.AliasedType.D()) - //res = append(res, jen.Type().Id(p.Name).Add(aliasedStmt...)) - //return res - p.SetDefinitionInfo(common.GetContext().CurrentDefinitionInfo()) - return renderTemplate("lang/gotypealias/definition", p) -} - -func (p *GoTypeAlias) U() string { - //ctx.LogStartRender("GoTypeAlias", p.Import, p.Name, "usage", p.IsDefinition()) - //defer ctx.LogFinishRender() - // - //if p.HasDefinition { - // if p.Import != "" && p.Import != context.Context.CurrentPackage { - // return []*jen.Statement{jen.Qual(context.Context.GeneratedModule(p.Import), p.Name)} - // } - // return []*jen.Statement{jen.Id(p.Name)} - //} - // - //// This GoTypeAlias definition is not directly rendered anywhere, so it's name is unknown for the calling code. - //// Just use the underlying type then - //aliasedStmt := utils.ToCode(p.AliasedType.U()) - //return []*jen.Statement{jen.Add(aliasedStmt...)} - return renderTemplate("lang/gotypealias/usage", p) +func (p *GoTypeAlias) GoTemplate() string { + return "lang/gotypealias" } func (p *GoTypeAlias) UnwrapGolangType() (common.GolangType, bool) { @@ -51,10 +21,7 @@ func (p *GoTypeAlias) UnwrapGolangType() (common.GolangType, bool) { } func (p *GoTypeAlias) IsPointer() bool { - if v, ok := any(p.AliasedType).(GolangPointerType); ok { - return v.IsPointer() - } - return false + return p.AliasedType.IsPointer() } func (p *GoTypeAlias) IsStruct() bool { @@ -66,7 +33,7 @@ func (p *GoTypeAlias) IsStruct() bool { func (p *GoTypeAlias) String() string { if p.Import != "" { - return "GoTypeAlias /" + p.Import + "." + p.Name + return "GoTypeAlias /" + p.Import + "." + p.OriginalName } - return "GoTypeAlias " + p.Name + return "GoTypeAlias " + p.OriginalName } \ No newline at end of file diff --git a/internal/render/lang/gounion.go b/internal/render/lang/gounion.go index 2f9d8b9..0e7cbaf 100644 --- a/internal/render/lang/gounion.go +++ b/internal/render/lang/gounion.go @@ -10,30 +10,8 @@ type UnionStruct struct { GoStruct } -func (s *UnionStruct) D() string { - //var res []*jen.Statement - //ctx.LogStartRender("UnionStruct", s.Import, s.Name, "definition", s.IsDefinition()) - //defer ctx.LogFinishRender() - // - //onlyStructs := lo.EveryBy(s.Fields, func(item GoStructField) bool { - // return isTypeStruct(item.Type) - //}) - //if onlyStructs { // Draw simplified union with embedded fields - // res = s.GoStruct.D() - //} else { // Draw union with named fields and methods - // strct := s.GoStruct - // strct.Fields = lo.Map(strct.Fields, func(item GoStructField, _ int) GoStructField { - // item.Name = item.Type.TypeName() - // return item - // }) - // if reflect.DeepEqual(strct.Fields, s.Fields) { // TODO: move this check to unit tests - // panic("Must not happen") - // } - // res = strct.D() - // res = append(res, s.renderMethods()...) - //} - //return res - return renderTemplate("lang/gounion/definition", s) +func (s *UnionStruct) GoTemplate() string { + return "lang/gounion" } func (s *UnionStruct) UnionStruct() common.GolangType { @@ -47,7 +25,7 @@ func (s *UnionStruct) UnionStruct() common.GolangType { // Draw union with named fields and methods strct := s.GoStruct strct.Fields = lo.Map(strct.Fields, func(item GoStructField, _ int) GoStructField { - item.Name = item.Type.TypeName() + item.Name = item.Type.GetOriginalName() // FIXME: check if this is will be correct return item }) if reflect.DeepEqual(strct.Fields, s.Fields) { // TODO: move this check to unit tests @@ -58,16 +36,16 @@ func (s *UnionStruct) UnionStruct() common.GolangType { func (s *UnionStruct) String() string { if s.Import != "" { - return "UnionStruct /" + s.Import + "." + s.Name + return "UnionStruct /" + s.Import + "." + s.OriginalName } - return "UnionStruct " + s.Name + return "UnionStruct " + s.OriginalName } //func (s UnionStruct) renderMethods() []*jen.Statement { // ctx.Logger.Trace("renderMethods") // // var res []*jen.Statement -// receiverName := strings.ToLower(string(s.GoStruct.Name[0])) +// receiverName := strings.ToLower(string(s.GoStruct.GetOriginalName[0])) // // // Method UnmarshalJSON(bytes []byte) error // body := []jen.Code{jen.Var().Err().Error()} @@ -78,7 +56,7 @@ func (s *UnionStruct) String() string { // op = "&" // } // stmt = stmt.If( -// jen.Err().Op("=").Qual("encoding/json", "Unmarshal").Call(jen.Id("bytes"), jen.Op(op).Id(receiverName).Dot(f.Type.TypeName())), +// jen.Err().Op("=").Qual("encoding/json", "Unmarshal").Call(jen.Id("bytes"), jen.Op(op).Id(receiverName).Dot(f.Type.IsPromise())), // jen.Err().Op("!=").Nil(), // ). // Block(jen.Return(jen.Nil())). @@ -91,7 +69,7 @@ func (s *UnionStruct) String() string { // } // body = append(body, stmt) // -// res = append(res, jen.Func().Params(jen.Id(receiverName).Op("*").Id(s.GoStruct.Name)).Id("UnmarshalJSON"). +// res = append(res, jen.Func().Params(jen.Id(receiverName).Op("*").Id(s.GoStruct.GetOriginalName)).Id("UnmarshalJSON"). // Params(jen.Id("bytes").Index().Byte()). // Error(). // Block(body...), diff --git a/internal/render/lang/govalue.go b/internal/render/lang/govalue.go index 38adbc2..3c35c5e 100644 --- a/internal/render/lang/govalue.go +++ b/internal/render/lang/govalue.go @@ -18,11 +18,6 @@ type GoValue struct { MapValues types.OrderedMap[string, any] // Render as map initialization in curly brackets } -type GolangPointerWrapperType interface { - GolangTypeWrapperType - GolangPointerType -} - func (gv *GoValue) Kind() common.ObjectKind { return common.ObjectKindOther } @@ -31,8 +26,22 @@ func (gv *GoValue) Selectable() bool { return false } -func (gv *GoValue) U() string { - return renderTemplate("lang/govalue/usage", gv) +func (gv *GoValue) GoTemplate() string { + return "lang/govalue" +} + +func (gv *GoValue) IsPointer() bool { + return gv.Type != nil && gv.Type.IsPointer() +} + +func (gv *GoValue) DefinitionInfo() (*common.GolangTypeDefinitionInfo, error) { + return nil, nil +} + +func (gv *GoValue) SetDefinitionInfo(_ *common.GolangTypeDefinitionInfo) {} + +func (gv *GoValue) GetOriginalName() string { + return "" } func (gv *GoValue) Empty() bool { @@ -88,11 +97,11 @@ func ConstructGoValue(value any, excludeFields []string, overrideType common.Gol } if res.Type == nil { res.Type = &GoArray{ - BaseType: BaseType{Name: rtyp.Name(), Import: rtyp.PkgPath()}, + BaseType: BaseType{OriginalName: rtyp.Name(), Import: rtyp.PkgPath()}, ItemsType: &GoSimple{ - Name: elemType.Name(), - IsInterface: elemType.Kind() == reflect.Interface, - Import: elemType.PkgPath(), + OriginalName: elemType.Name(), + IsInterface: elemType.Kind() == reflect.Interface, + Import: elemType.PkgPath(), }, Size: elemSize, } @@ -108,16 +117,16 @@ func ConstructGoValue(value any, excludeFields []string, overrideType common.Gol elemType := rtyp.Elem() if res.Type == nil { res.Type = &GoMap{ - BaseType: BaseType{Name: rtyp.Name(), Import: rtyp.PkgPath()}, + BaseType: BaseType{OriginalName: rtyp.Name(), Import: rtyp.PkgPath()}, KeyType: &GoSimple{ - Name: keyType.Name(), - IsInterface: keyType.Kind() == reflect.Interface, - Import: keyType.PkgPath(), + OriginalName: keyType.Name(), + IsInterface: keyType.Kind() == reflect.Interface, + Import: keyType.PkgPath(), }, ValueType: &GoSimple{ - Name: elemType.Name(), - IsInterface: elemType.Kind() == reflect.Interface, - Import: elemType.PkgPath(), + OriginalName: elemType.Name(), + IsInterface: elemType.Kind() == reflect.Interface, + Import: elemType.PkgPath(), }, } } @@ -130,7 +139,7 @@ func ConstructGoValue(value any, excludeFields []string, overrideType common.Gol case reflect.Struct: if res.Type == nil { res.Type = &GoStruct{ - BaseType: BaseType{Name: rtyp.Name(), Import: rtyp.PkgPath()}, + BaseType: BaseType{OriginalName: rtyp.Name(), Import: rtyp.PkgPath()}, } } res.EmptyCurlyBrackets = true diff --git a/internal/render/lang/promise.go b/internal/render/lang/promise.go index 833fb89..55d9bf4 100644 --- a/internal/render/lang/promise.go +++ b/internal/render/lang/promise.go @@ -14,16 +14,20 @@ func defaultAssignCb[T any](obj any) T { return t } -func NewPromise[T any](ref string, origin common.PromiseOrigin) *Promise[T] { - return &Promise[T]{ref: ref, origin: origin, assignCb: defaultAssignCb[T]} +func newPromise[T any](ref string, origin common.PromiseOrigin) *Promise[T] { + return &Promise[T]{ref: ref, origin: origin} } -func NewCbPromise[T any](findCb func(item common.CompileObject, path []string) bool) *Promise[T] { - return &Promise[T]{origin: common.PromiseOriginInternal, findCb: findCb} +func newAssignCbPromise[T any](ref string, origin common.PromiseOrigin, assignCb func(obj any) T) *Promise[T] { + return &Promise[T]{ref: ref, origin: origin, assignCb: assignCb} } -func NewAssignCbPromise[T any](ref string, origin common.PromiseOrigin, assignCb func(obj any) T) *Promise[T] { - return &Promise[T]{ref: ref, origin: origin, assignCb: assignCb} +func NewInternalPromise[T any](ref string) *Promise[T] { + return &Promise[T]{ref: ref, origin: common.PromiseOriginInternal, assignCb: defaultAssignCb[T]} +} + +func NewInternalCbPromise[T any](findCb func(item common.CompileObject, path []string) bool) *Promise[T] { + return &Promise[T]{origin: common.PromiseOriginInternal, findCb: findCb} } type Promise[T any] struct { @@ -86,7 +90,7 @@ func (r *Promise[T]) IsPointer() bool { if !r.assigned { return false } - if v, ok := any(r.target).(GolangPointerType); ok { + if v, ok := any(r.target).(common.GolangType); ok { return v.IsPointer() } return false @@ -140,14 +144,18 @@ func (r *ListPromise[T]) Ref() string { return r.ref } -func NewRenderablePromise(ref string, origin common.PromiseOrigin) *RenderablePromise { +func NewUserPromise(ref string, name string, selectable *bool) *RenderablePromise { return &RenderablePromise{ - Promise: *NewPromise[common.Renderable](ref, origin), + Promise: *newPromise[common.Renderable](ref, common.PromiseOriginUser), + selectable: selectable, + name: name, } } type RenderablePromise struct { Promise[common.Renderable] + selectable *bool + name string } func (r *RenderablePromise) Kind() common.ObjectKind { @@ -155,22 +163,34 @@ func (r *RenderablePromise) Kind() common.ObjectKind { } func (r *RenderablePromise) Selectable() bool { - return r.origin == common.PromiseOriginUser && r.target.Selectable() + if r.selectable == nil { + return r.origin == common.PromiseOriginUser && r.target.Selectable() + } + return r.origin == common.PromiseOriginUser && *r.selectable } func (r *RenderablePromise) String() string { return "RenderablePromise -> " + r.ref } -func NewGolangTypePromise(ref string, origin common.PromiseOrigin) *GolangTypePromise { +func (r *RenderablePromise) GetOriginalName() string { + n, _ := lo.Coalesce(r.name, r.target.GetOriginalName()) + return n +} + +func (r *RenderablePromise) RenderableT() common.Renderable { + return r.target +} + +func NewInternalGolangTypePromise(ref string) *GolangTypePromise { return &GolangTypePromise{ - Promise: *NewPromise[common.GolangType](ref, origin), + Promise: *newPromise[common.GolangType](ref, common.PromiseOriginInternal), } } -func NewGolangTypeAssignCbPromise(ref string, origin common.PromiseOrigin, assignCb func(obj any) common.GolangType) *GolangTypePromise { +func NewInternalGolangTypeAssignCbPromise(ref string, assignCb func(obj any) common.GolangType) *GolangTypePromise { return &GolangTypePromise{ - Promise: *NewAssignCbPromise[common.GolangType](ref, origin, assignCb), + Promise: *newAssignCbPromise[common.GolangType](ref, common.PromiseOriginInternal, assignCb), } } @@ -182,24 +202,24 @@ func (r *GolangTypePromise) Kind() common.ObjectKind { return r.target.Kind() } -func (r *GolangTypePromise) TypeName() string { - return r.target.TypeName() -} - func (r *GolangTypePromise) Selectable() bool { return r.origin == common.PromiseOriginUser && r.target.Selectable() } -func (r *GolangTypePromise) IsPointer() bool { - return r.target.IsPointer() +func (r *GolangTypePromise) GetOriginalName() string { + return r.target.GetOriginalName() } -func (r *GolangTypePromise) D() string { - return r.target.D() +func (r *GolangTypePromise) GolangTypeT() common.GolangType { + return r.target +} + +func (r *GolangTypePromise) IsPointer() bool { + return r.target.IsPointer() } -func (r *GolangTypePromise) U() string { - return r.target.U() +func (r *GolangTypePromise) GoTemplate() string { + return r.target.GoTemplate() } func (r *GolangTypePromise) DefinitionInfo() (*common.GolangTypeDefinitionInfo, error) { diff --git a/internal/render/message.go b/internal/render/message.go index b3e5c1e..fcf285d 100644 --- a/internal/render/message.go +++ b/internal/render/message.go @@ -7,18 +7,23 @@ import ( ) type Message struct { - Name string - Dummy bool - OutType *lang.GoStruct + OriginalName string + OutType *lang.GoStruct InType *lang.GoStruct - PayloadType common.GolangType // `any` or a particular type + Dummy bool + IsComponent bool // true if message is defined in `components` section + HeadersFallbackType *lang.GoMap HeadersTypePromise *lang.Promise[*lang.GoStruct] + AllServersPromise *lang.ListPromise[*Server] // For extracting all using protocols + BindingsType *lang.GoStruct // nil if message bindings are not defined for message BindingsPromise *lang.Promise[*Bindings] // nil if message bindings are not defined for message as well + ContentType string // Message's content type CorrelationIDPromise *lang.Promise[*CorrelationID] // nil if correlationID is not defined for message + PayloadType common.GolangType // `any` or a particular type AsyncAPIPromise *lang.Promise[*AsyncAPI] ProtoMessages []*ProtoMessage @@ -29,13 +34,15 @@ func (m *Message) Kind() common.ObjectKind { } func (m *Message) Selectable() bool { - return !m.Dummy + return !m.Dummy && !m.IsComponent // Select only the messages defined in the `channels` section` } func (m *Message) ProtoObjects() []common.Renderable { - return lo.FilterMap(m.ProtoMessages, func(p *ProtoMessage, _ int) (common.Renderable, bool) { - return p, p.Selectable() - }) + return lo.Map(m.ProtoMessages, func(p *ProtoMessage, _ int) common.Renderable { return p }) +} + +func (m *Message) GetOriginalName() string { + return m.OriginalName } func (m *Message) EffectiveContentType() string { @@ -58,7 +65,7 @@ func (m *Message) BindingsProtocols() (res []string) { //func (m Message) D(ctx *common.RenderContext) []*j.Statement { //var res []*j.Statement - //ctx.LogStartRender("Message", "", m.Name, "definition", m.Selectable()) + //ctx.LogStartRender("Message", "", m.GetOriginalName, "definition", m.Selectable()) //defer ctx.LogFinishRender() // //// Bindings struct and its methods according to protocols of channels where the message is used @@ -87,11 +94,11 @@ func (m *Message) BindingsProtocols() (res []string) { //} // //func (m Message) ID() string { -// return m.Name +// return m.GetOriginalName //} // func (m *Message) String() string { - return "Message " + m.Name + return "Message " + m.OriginalName } func (m *Message) HasProtoBindings(protoName string) bool { @@ -105,7 +112,7 @@ func (m *Message) HasProtoBindings(protoName string) bool { func (m *Message) ProtoBindingsValue(protoName string) common.Renderable { res := &lang.GoValue{ - Type: &lang.GoSimple{Name: "ServerBindings", Import: common.GetContext().RuntimeModule(protoName)}, + Type: &lang.GoSimple{OriginalName: "ServerBindings", Import: common.GetContext().RuntimeModule(protoName)}, EmptyCurlyBrackets: true, } if m.BindingsPromise != nil { @@ -137,7 +144,7 @@ func (m *Message) ProtoBindingsValue(protoName string) common.Renderable { //func (m Message) renderPublishCommonMethods(ctx *common.RenderContext) []*j.Statement { // ctx.Logger.Trace("renderPublishCommonMethods") // -// structName := m.OutType.Name +// structName := m.OutType.GetOriginalName // rn := m.OutType.ReceiverName() // receiver := j.Id(rn).Op("*").Id(structName) // payloadFieldType := utils.ToCode(m.PayloadType.U(ctx)) @@ -177,7 +184,7 @@ func (m *Message) ProtoBindingsValue(protoName string) common.Renderable { // ctx.Logger.Trace("renderMarshalEnvelopeMethod") // // rn := m.OutType.ReceiverName() -// receiver := j.Id(rn).Op("*").Id(m.OutType.Name) +// receiver := j.Id(rn).Op("*").Id(m.OutType.GetOriginalName) // // return []*j.Statement{ // // Method MarshalProtoEnvelope(envelope proto.EnvelopeWriter) error @@ -198,7 +205,7 @@ func (m *Message) ProtoBindingsValue(protoName string) common.Renderable { // bg.Id("envelope").Dot("SetHeaders").Call( // j.Qual(ctx.RuntimeModule(""), "Headers").Values(j.DictFunc(func(d j.Dict) { // for _, f := range m.HeadersTypePromise.Target().Fields { -// d[j.Lit(f.Name)] = j.Id(rn).Dot("Headers").Dot(f.Name) +// d[j.Lit(f.GetOriginalName)] = j.Id(rn).Dot("Headers").Dot(f.GetOriginalName) // } // })), // ) @@ -232,7 +239,7 @@ func (m *Message) ProtoBindingsValue(protoName string) common.Renderable { //func (m Message) renderSubscribeCommonMethods(ctx *common.RenderContext) []*j.Statement { // ctx.Logger.Trace("renderSubscribeCommonMethods") // -// structName := m.InType.Name +// structName := m.InType.GetOriginalName // rn := m.InType.ReceiverName() // receiver := j.Id(rn).Op("*").Id(structName) // payloadFieldType := utils.ToCode(m.PayloadType.U(ctx)) @@ -268,7 +275,7 @@ func (m *Message) ProtoBindingsValue(protoName string) common.Renderable { // ctx.Logger.Trace("renderUnmarshalEnvelopeMethod") // // rn := m.InType.ReceiverName() -// receiver := j.Id(rn).Op("*").Id(m.InType.Name) +// receiver := j.Id(rn).Op("*").Id(m.InType.GetOriginalName) // // return []*j.Statement{ // // Method UnmarshalProtoEnvelope(envelope proto.EnvelopeReader) error @@ -289,8 +296,8 @@ func (m *Message) ProtoBindingsValue(protoName string) common.Renderable { // bg.Op("headers := envelope.Headers()") // for _, f := range m.HeadersTypePromise.Target().Fields { // fType := j.Add(utils.ToCode(f.Type.U(ctx))...) -// bg.If(j.Op("v, ok := headers").Index(j.Lit(f.Name)), j.Id("ok")). -// Block(j.Id(rn).Dot("Headers").Dot(f.Name).Op("=").Id("v").Assert(fType)) +// bg.If(j.Op("v, ok := headers").Index(j.Lit(f.GetOriginalName)), j.Id("ok")). +// Block(j.Id(rn).Dot("Headers").Dot(f.GetOriginalName).Op("=").Id("v").Assert(fType)) // } // } // } else { @@ -326,7 +333,7 @@ func (p *ProtoMessage) Selectable() bool { } func (p *ProtoMessage) String() string { - return "Message " + p.Name + return "Message " + p.OriginalName } func (p *ProtoMessage) Kind() common.ObjectKind { diff --git a/internal/render/mqtt/channel.go b/internal/render/mqtt/channel.go index 7a8aeb7..2402572 100644 --- a/internal/render/mqtt/channel.go +++ b/internal/render/mqtt/channel.go @@ -13,7 +13,7 @@ package mqtt //} // //func (pc ProtoChannel) D(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Channel", "", pc.Parent.Name, "definition", pc.Selectable(), "proto", pc.ProtoName) +// ctx.LogStartRender("Channel", "", pc.Parent.GetOriginalName, "definition", pc.Selectable(), "proto", pc.ProtoName) // defer ctx.LogFinishRender() // var res []*j.Statement // res = append(res, pc.ServerIface.D(ctx)...) @@ -33,17 +33,17 @@ package mqtt //} // //func (pc ProtoChannel) U(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Channel", "", pc.Parent.Name, "usage", pc.Selectable(), "proto", pc.ProtoName) +// ctx.LogStartRender("Channel", "", pc.Parent.GetOriginalName, "usage", pc.Selectable(), "proto", pc.ProtoName) // defer ctx.LogFinishRender() // return pc.Type.U(ctx) //} // //func (pc ProtoChannel) ID() string { -// return pc.Parent.Name +// return pc.Parent.GetOriginalName //} // //func (pc ProtoChannel) String() string { -// return "MQTT ProtoChannel " + pc.Parent.Name +// return "MQTT ProtoChannel " + pc.Parent.GetOriginalName //} //func (pc ProtoChannel) renderNewFunc(ctx *common.RenderContext) []*j.Statement { @@ -66,7 +66,7 @@ package mqtt // Op("*").Add(utils.ToCode(pc.Type.U(ctx))...). // BlockFunc(func(bg *j.Group) { // bg.Op("res := ").Add(utils.ToCode(pc.Type.U(ctx))...).Values(j.DictFunc(func(d j.Dict) { -// d[j.Id("name")] = j.Id(pc.Parent.TypeNamePrefix + "Name").CallFunc(func(g *j.Group) { +// d[j.Id("name")] = j.Id(pc.Parent.TypeNamePrefix + "GetOriginalName").CallFunc(func(g *j.Group) { // if pc.Parent.ParametersType != nil { // g.Id("params") // } @@ -88,7 +88,7 @@ package mqtt // ctx.Logger.Trace("renderProtoMethods", "proto", pc.ProtoName) // // rn := pc.Type.ReceiverName() -// receiver := j.Id(rn).Id(pc.Type.Name) +// receiver := j.Id(rn).Id(pc.Type.GetOriginalName) // // return []*j.Statement{ // // Method Topic() string @@ -105,7 +105,7 @@ package mqtt // ctx.Logger.Trace("renderProtoPublisherMethods", "proto", pc.ProtoName) // // rn := pc.Type.ReceiverName() -// receiver := j.Id(rn).Id(pc.Type.Name) +// receiver := j.Id(rn).Id(pc.Type.GetOriginalName) // // var msgTyp common.GolangType = render.GoPointer{Type: pc.Parent.FallbackMessageType, HasDefinition: true} // if pc.Parent.PublisherMessageTypePromise != nil { diff --git a/internal/render/mqtt/server.go b/internal/render/mqtt/server.go index 353acbf..4a8f981 100644 --- a/internal/render/mqtt/server.go +++ b/internal/render/mqtt/server.go @@ -12,7 +12,7 @@ package mqtt //} // //func (ps ProtoServer) D(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Server", "", ps.Parent.Name, "definition", ps.Selectable(), "proto", ps.ProtoName) +// ctx.LogStartRender("Server", "", ps.Parent.GetOriginalName, "definition", ps.Selectable(), "proto", ps.ProtoName) // defer ctx.LogFinishRender() // var res []*j.Statement // res = append(res, ps.RenderNewFunc(ctx)...) @@ -25,17 +25,17 @@ package mqtt //} // //func (ps ProtoServer) U(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Server", "", ps.Parent.Name, "usage", ps.Selectable(), "proto", ps.ProtoName) +// ctx.LogStartRender("Server", "", ps.Parent.GetOriginalName, "usage", ps.Selectable(), "proto", ps.ProtoName) // defer ctx.LogFinishRender() // return ps.Type.U(ctx) //} // //func (ps ProtoServer) ID() string { -// return ps.Parent.Name +// return ps.Parent.GetOriginalName //} // //func (ps ProtoServer) String() string { -// return "MQTT ProtoServer " + ps.Parent.Name +// return "MQTT ProtoServer " + ps.Parent.GetOriginalName //} // //func (ps ProtoServer) renderChannelMethods(ctx *common.RenderContext) []*j.Statement { diff --git a/internal/render/parameter.go b/internal/render/parameter.go index b360670..b1f770c 100644 --- a/internal/render/parameter.go +++ b/internal/render/parameter.go @@ -5,8 +5,8 @@ import ( ) type Parameter struct { - Name string - Dummy bool + OriginalName string + Dummy bool Type common.GolangType IsStringType bool // true if Type contains a type alias to built-in string type } @@ -19,9 +19,13 @@ func (p *Parameter) Selectable() bool { return !p.Dummy && p.Type.Selectable() } +func (p *Parameter) GetOriginalName() string { + return p.OriginalName +} + //func (p Parameter) D(ctx *common.RenderContext) []*j.Statement { // var res []*j.Statement -// ctx.LogStartRender("Parameter", "", p.Name, "definition", p.Selectable()) +// ctx.LogStartRender("Parameter", "", p.GetOriginalName, "definition", p.Selectable()) // defer ctx.LogFinishRender() // // res = append(res, p.Type.D(ctx)...) @@ -30,29 +34,29 @@ func (p *Parameter) Selectable() bool { //} //func (p Parameter) ID() string { -// return p.Name +// return p.GetOriginalName //} // func (p *Parameter) String() string { - return "Parameter " + p.Name + return "Parameter " + p.OriginalName } //func (p Parameter) renderMethods(ctx *common.RenderContext) []*j.Statement { // ctx.Logger.Trace("renderMethods") // -// rn := strings.ToLower(string(p.Type.TypeName()[0])) -// receiver := j.Id(rn).Id(p.Type.TypeName()) +// rn := strings.ToLower(string(p.Type.IsPromise()[0])) +// receiver := j.Id(rn).Id(p.Type.IsPromise()) // // stringBody := j.Return(j.String().Call(j.Id(rn))) // if !p.IsStringType { // stringBody = j.Return(j.Qual("fmt", "Sprint").Call(j.Id(rn).Dot("Value"))) // } // return []*j.Statement{ -// j.Func().Params(receiver.Clone()).Id("Name"). +// j.Func().Params(receiver.Clone()).Id("GetOriginalName"). // Params(). // String(). // Block( -// j.Return(j.Lit(p.Name)), +// j.Return(j.Lit(p.GetOriginalName)), // ), // // j.Func().Params(receiver.Clone()).Id("String"). @@ -63,12 +67,12 @@ func (p *Parameter) String() string { //} //func (p Parameter) U(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Parameter", "", p.Name, "usage", p.Selectable()) +// ctx.LogStartRender("Parameter", "", p.GetOriginalName, "usage", p.Selectable()) // defer ctx.LogFinishRender() // // return p.Type.U(ctx) //} -//func (p Parameter) TypeName() string { -// return p.Type.TypeName() +//func (p Parameter) IsPromise() string { +// return p.Type.IsPromise() //} diff --git a/internal/render/proto/channel.go b/internal/render/proto/channel.go index bc08707..cf499d8 100644 --- a/internal/render/proto/channel.go +++ b/internal/render/proto/channel.go @@ -23,10 +23,10 @@ package proto // ctx.Logger.Trace("RenderCommonSubscriberMethods", "proto", pc.ProtoName) // // rn := pc.Type.ReceiverName() -// receiver := j.Id(rn).Id(pc.Type.Name) +// receiver := j.Id(rn).Id(pc.Type.GetOriginalName) // var msgTyp common.GolangType = render.GoPointer{Type: pc.Parent.FallbackMessageType, HasDefinition: true} -// if pc.Parent.SubscribeMessageTypePromise != nil { -// msgTyp = render.GoPointer{Type: pc.Parent.SubscribeMessageTypePromise.Target().InType, HasDefinition: true} +// if pc.Parent.SubscriberMessageTypePromise != nil { +// msgTyp = render.GoPointer{Type: pc.Parent.SubscriberMessageTypePromise.Target().InType, HasDefinition: true} // } // // return []*j.Statement{ @@ -38,7 +38,7 @@ package proto // ). // Error(). // BlockFunc(func(bg *j.Group) { -// if pc.Parent.SubscribeMessageTypePromise == nil { +// if pc.Parent.SubscriberMessageTypePromise == nil { // bg.Empty().Add(utils.QualSprintf(` // enc := %Q(encoding/json,NewDecoder)(envelope) // if err := enc.Decode(message); err != nil { @@ -75,7 +75,7 @@ package proto // ctx.Logger.Trace("RenderCommonPublisherMethods", "proto", pc.ProtoName) // // rn := pc.Type.ReceiverName() -// receiver := j.Id(rn).Id(pc.Type.Name) +// receiver := j.Id(rn).Id(pc.Type.GetOriginalName) // // return []*j.Statement{ // // Method Publisher() proto.Publisher @@ -103,11 +103,11 @@ package proto // ctx.Logger.Trace("RenderCommonMethods", "proto", pc.ProtoName) // // rn := pc.Type.ReceiverName() -// receiver := j.Id(rn).Id(pc.Type.Name) +// receiver := j.Id(rn).Id(pc.Type.GetOriginalName) // // return []*j.Statement{ -// // Method Name() string -// j.Func().Params(receiver.Clone()).Id("Name"). +// // Method GetOriginalName() string +// j.Func().Params(receiver.Clone()).Id("GetOriginalName"). // Params(). // Qual(ctx.RuntimeModule(""), "ParamString"). // Block( @@ -151,13 +151,13 @@ package proto // BlockFunc(func(bg *j.Group) { // bg.Op("if len(servers) == 0").Block(j.Op("return nil, ").Qual(ctx.RuntimeModule(""), "ErrEmptyServers")) // if pc.Parent.Publisher || pc.Parent.Subscriber { -// bg.Id("name").Op(":=").Id(pc.Parent.TypeNamePrefix + "Name").CallFunc(func(g *j.Group) { +// bg.Id("name").Op(":=").Id(pc.Parent.TypeNamePrefix + "GetOriginalName").CallFunc(func(g *j.Group) { // if pc.Parent.ParametersType != nil { // g.Id("params") // } // }) // if pc.Parent.BindingsType != nil { -// bg.Id("bindings").Op(":=").Id(pc.Parent.BindingsType.Name).Values().Dot(pc.ProtoTitle).Call() +// bg.Id("bindings").Op(":=").Id(pc.Parent.BindingsType.GetOriginalName).Values().Dot(pc.ProtoTitle).Call() // } // if pc.Parent.Publisher { // bg.Var().Id("prod").Index().Qual(ctx.RuntimeModule(pc.ProtoName), "Producer") diff --git a/internal/render/proto/server.go b/internal/render/proto/server.go index ae76ad2..ba9eb3d 100644 --- a/internal/render/proto/server.go +++ b/internal/render/proto/server.go @@ -30,15 +30,15 @@ package proto //func (ps BaseProtoServer) RenderCommonMethods(ctx *common.RenderContext) []*j.Statement { // ctx.Logger.Trace("RenderCommonMethods", "proto", ps.ProtoName) // -// receiver := j.Id(ps.Type.ReceiverName()).Id(ps.Type.Name) +// receiver := j.Id(ps.Type.ReceiverName()).Id(ps.Type.GetOriginalName) // // return []*j.Statement{ -// // Method Name() string -// j.Func().Params(receiver.Clone()).Id("Name"). +// // Method GetOriginalName() string +// j.Func().Params(receiver.Clone()).Id("GetOriginalName"). // Params(). // String(). // Block( -// j.Return(j.Lit(ps.Parent.Name)), +// j.Return(j.Lit(ps.Parent.GetOriginalName)), // ), // } //} @@ -47,11 +47,11 @@ package proto // ctx.Logger.Trace("RenderOpenChannelMethod", "proto", ps.ProtoName) // // rn := ps.Type.ReceiverName() -// receiver := j.Id(rn).Id(ps.Type.Name) +// receiver := j.Id(rn).Id(ps.Type.GetOriginalName) // // return []*j.Statement{ // // Method OpenChannel1Proto(ctx context.Context, params Channel1Parameters) (*Channel1Proto, error) -// j.Func().Params(receiver.Clone()).Id("Open"+channelStruct.Name). +// j.Func().Params(receiver.Clone()).Id("Open"+channelStruct.GetOriginalName). // ParamsFunc(func(g *j.Group) { // g.Id("ctx").Qual("context", "Context") // if channelParametersStructNoRender != nil { @@ -60,7 +60,7 @@ package proto // }). // Params(j.Op("*").Add(utils.ToCode(channel.U(ctx))...), j.Error()). // Block( -// j.Return(j.Qual(ctx.GeneratedModule(channelStruct.Import), "Open"+channelStruct.Name).CallFunc(func(g *j.Group) { +// j.Return(j.Qual(ctx.GeneratedModule(channelStruct.Import), "Open"+channelStruct.GetOriginalName).CallFunc(func(g *j.Group) { // g.Id("ctx") // if channelParametersStructNoRender != nil { // g.Id("params") @@ -75,7 +75,7 @@ package proto // ctx.Logger.Trace("RenderProducerMethods", "proto", ps.ProtoName) // // rn := ps.Type.ReceiverName() -// receiver := j.Id(rn).Id(ps.Type.Name) +// receiver := j.Id(rn).Id(ps.Type.GetOriginalName) // // return []*j.Statement{ // // Method Producer() proto.Producer @@ -92,7 +92,7 @@ package proto // ctx.Logger.Trace("RenderConsumerMethods", "proto", ps.ProtoName) // // rn := ps.Type.ReceiverName() -// receiver := j.Id(rn).Id(ps.Type.Name) +// receiver := j.Id(rn).Id(ps.Type.GetOriginalName) // // return []*j.Statement{ // // Method Consumer() proto.Consumer diff --git a/internal/render/redis/channel.go b/internal/render/redis/channel.go index 448d1a4..9ab98f6 100644 --- a/internal/render/redis/channel.go +++ b/internal/render/redis/channel.go @@ -13,7 +13,7 @@ package redis //} // //func (pc ProtoChannel) D(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Channel", "", pc.Parent.Name, "definition", pc.Selectable(), "proto", pc.ProtoName) +// ctx.LogStartRender("Channel", "", pc.Parent.GetOriginalName, "definition", pc.Selectable(), "proto", pc.ProtoName) // defer ctx.LogFinishRender() // var res []*j.Statement // res = append(res, pc.ServerIface.D(ctx)...) @@ -33,17 +33,17 @@ package redis //} // //func (pc ProtoChannel) U(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Channel", "", pc.Parent.Name, "usage", pc.Selectable(), "proto", pc.ProtoName) +// ctx.LogStartRender("Channel", "", pc.Parent.GetOriginalName, "usage", pc.Selectable(), "proto", pc.ProtoName) // defer ctx.LogFinishRender() // return pc.Type.U(ctx) //} // //func (pc ProtoChannel) ID() string { -// return pc.Parent.Name +// return pc.Parent.GetOriginalName //} // //func (pc ProtoChannel) String() string { -// return "Redis ProtoChannel " + pc.Parent.Name +// return "Redis ProtoChannel " + pc.Parent.GetOriginalName //} //func (pc ProtoChannel) renderNewFunc(ctx *common.RenderContext) []*j.Statement { @@ -66,7 +66,7 @@ package redis // Op("*").Add(utils.ToCode(pc.Type.U(ctx))...). // BlockFunc(func(bg *j.Group) { // bg.Op("res := ").Add(utils.ToCode(pc.Type.U(ctx))...).Values(j.DictFunc(func(d j.Dict) { -// d[j.Id("name")] = j.Id(pc.Parent.TypeNamePrefix + "Name").CallFunc(func(g *j.Group) { +// d[j.Id("name")] = j.Id(pc.Parent.TypeNamePrefix + "GetOriginalName").CallFunc(func(g *j.Group) { // if pc.Parent.ParametersType != nil { // g.Id("params") // } @@ -91,7 +91,7 @@ package redis // ctx.Logger.Trace("renderProtoPublisherMethods", "proto", pc.ProtoName) // // rn := pc.Type.ReceiverName() -// receiver := j.Id(rn).Id(pc.Type.Name) +// receiver := j.Id(rn).Id(pc.Type.GetOriginalName) // // var msgTyp common.GolangType = render.GoPointer{Type: pc.Parent.FallbackMessageType, HasDefinition: true} // if pc.Parent.PublisherMessageTypePromise != nil { diff --git a/internal/render/redis/server.go b/internal/render/redis/server.go index e5a5081..ad924d5 100644 --- a/internal/render/redis/server.go +++ b/internal/render/redis/server.go @@ -12,7 +12,7 @@ package redis //} // //func (ps ProtoServer) D(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Server", "", ps.Parent.Name, "definition", ps.Selectable(), "proto", ps.ProtoName) +// ctx.LogStartRender("Server", "", ps.Parent.GetOriginalName, "definition", ps.Selectable(), "proto", ps.ProtoName) // defer ctx.LogFinishRender() // var res []*j.Statement // res = append(res, ps.RenderNewFunc(ctx)...) @@ -25,17 +25,17 @@ package redis //} // //func (ps ProtoServer) U(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Server", "", ps.Parent.Name, "usage", ps.Selectable(), "proto", ps.ProtoName) +// ctx.LogStartRender("Server", "", ps.Parent.GetOriginalName, "usage", ps.Selectable(), "proto", ps.ProtoName) // defer ctx.LogFinishRender() // return ps.Type.U(ctx) //} // //func (ps ProtoServer) ID() string { -// return ps.Parent.Name +// return ps.Parent.GetOriginalName //} // //func (ps ProtoServer) String() string { -// return "Redis ProtoServer " + ps.Parent.Name +// return "Redis ProtoServer " + ps.Parent.GetOriginalName //} // //func (ps ProtoServer) renderChannelMethods(ctx *common.RenderContext) []*j.Statement { diff --git a/internal/render/server.go b/internal/render/server.go index 60ca5c5..6c45b9c 100644 --- a/internal/render/server.go +++ b/internal/render/server.go @@ -8,12 +8,13 @@ import ( ) type Server struct { - Name string - SpecKey string // Name as it is in the source document, without considering `x-go-name` extension + OriginalName string + SpecKey string // Name as it is in the source document, without considering `x-go-name` extension TypeNamePrefix string // Name of server struct Dummy bool + IsComponent bool // true if server is defined in `components` section - URL string // TODO + URL string Protocol string ProtocolVersion string @@ -31,16 +32,20 @@ func (s *Server) Kind() common.ObjectKind { } func (s *Server) Selectable() bool { - return !s.Dummy + return !s.Dummy && !s.IsComponent // Select only the servers defined in the `channels` section` } func (s *Server) ProtoObjects() []common.Renderable { return []common.Renderable{s.ProtoServer} } +func (s *Server) GetOriginalName() string { + return s.OriginalName +} + //func (s Server) D(ctx *common.RenderContext) []*j.Statement { // var res []*j.Statement -// ctx.LogStartRender("Server", "", s.Name, "definition", s.Selectable()) +// ctx.LogStartRender("Server", "", s.GetOriginalName, "definition", s.Selectable()) // defer ctx.LogFinishRender() // // if s.ProtocolVersion != "" { @@ -104,7 +109,7 @@ func (s *Server) ProtoObjects() []common.Renderable { // } // bg.Op("paramMap := map[string]string").Values(j.DictFunc(func(d j.Dict) { // for _, entry := range s.VariablesPromises.Entries() { -// d[j.Lit(entry.Key)] = j.Id(entry.Value.Target().Name) +// d[j.Lit(entry.Key)] = j.Id(entry.Value.Target().GetOriginalName) // } // })) // bg.Return(j.Qual(ctx.RuntimeModule(""), "ParamString").Values(j.Dict{ @@ -121,11 +126,11 @@ func (s *Server) ProtoObjects() []common.Renderable { //} //func (s Server) ID() string { -// return s.Name +// return s.GetOriginalName //} // func (s *Server) String() string { - return "Server " + s.Name + return "Server " + s.OriginalName } func (s *Server) GetRelevantProtoChannels(protoName string) []*ProtoChannel { @@ -150,7 +155,7 @@ func (c *Server) BindingsProtocols() (res []string) { func (c *Server) ProtoBindingsValue(protoName string) common.Renderable { res := &lang.GoValue{ - Type: &lang.GoSimple{Name: "ServerBindings", Import: common.GetContext().RuntimeModule(protoName)}, + Type: &lang.GoSimple{OriginalName: "ServerBindings", Import: common.GetContext().RuntimeModule(protoName)}, EmptyCurlyBrackets: true, } if c.BindingsPromise != nil { @@ -170,7 +175,7 @@ type ProtoServer struct { } func (p *ProtoServer) String() string { - return "ProtoServer " + p.Name + return "ProtoServer " + p.OriginalName } func (p *ProtoServer) Kind() common.ObjectKind { diff --git a/internal/render/servervariable.go b/internal/render/servervariable.go index dc02264..04cb97b 100644 --- a/internal/render/servervariable.go +++ b/internal/render/servervariable.go @@ -5,8 +5,8 @@ import ( ) type ServerVariable struct { - Name string - Description string // TODO + OriginalName string + Description string // TODO Enum []string // TODO: implement validation Default string } @@ -19,6 +19,10 @@ func (s *ServerVariable) Selectable() bool { return false } +func (s *ServerVariable) GetOriginalName() string { + return s.OriginalName +} + // //func (s ServerVariable) D(_ *common.RenderContext) []*j.Statement { // panic("not implemented") @@ -29,9 +33,9 @@ func (s *ServerVariable) Selectable() bool { //} // //func (s ServerVariable) ID() string { -// return s.Name +// return s.GetOriginalName //} // func (s *ServerVariable) String() string { - return "ServerVariable " + s.Name + return "ServerVariable " + s.OriginalName } diff --git a/internal/render/tcp/channel.go b/internal/render/tcp/channel.go index 807d1f6..2a81224 100644 --- a/internal/render/tcp/channel.go +++ b/internal/render/tcp/channel.go @@ -13,7 +13,7 @@ package tcp //} // //func (pc ProtoChannel) D(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Channel", "", pc.Parent.Name, "definition", pc.Selectable(), "proto", pc.ProtoName) +// ctx.LogStartRender("Channel", "", pc.Parent.GetOriginalName, "definition", pc.Selectable(), "proto", pc.ProtoName) // defer ctx.LogFinishRender() // var res []*j.Statement // res = append(res, pc.ServerIface.D(ctx)...) @@ -33,17 +33,17 @@ package tcp //} // //func (pc ProtoChannel) U(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Channel", "", pc.Parent.Name, "usage", pc.Selectable(), "proto", pc.ProtoName) +// ctx.LogStartRender("Channel", "", pc.Parent.GetOriginalName, "usage", pc.Selectable(), "proto", pc.ProtoName) // defer ctx.LogFinishRender() // return pc.Type.U(ctx) //} //func (pc ProtoChannel) ID() string { -// return pc.Parent.Name +// return pc.Parent.GetOriginalName //} // //func (pc ProtoChannel) String() string { -// return "TCP ProtoChannel " + pc.Parent.Name // TODO: substitute ProtoName (everywhere) + remove copypaste everywhere +// return "TCP ProtoChannel " + pc.Parent.GetOriginalName // TODO: substitute ProtoName (everywhere) + remove copypaste everywhere //} // //func (pc ProtoChannel) renderNewFunc(ctx *common.RenderContext) []*j.Statement { @@ -66,7 +66,7 @@ package tcp // Op("*").Add(utils.ToCode(pc.Type.U(ctx))...). // BlockFunc(func(bg *j.Group) { // bg.Op("res := ").Add(utils.ToCode(pc.Type.U(ctx))...).Values(j.DictFunc(func(d j.Dict) { -// d[j.Id("name")] = j.Id(pc.Parent.TypeNamePrefix + "Name").CallFunc(func(g *j.Group) { +// d[j.Id("name")] = j.Id(pc.Parent.TypeNamePrefix + "GetOriginalName").CallFunc(func(g *j.Group) { // if pc.Parent.ParametersType != nil { // g.Id("params") // } @@ -91,7 +91,7 @@ package tcp // ctx.Logger.Trace("renderProtoPublisherMethods", "proto", pc.ProtoName) // // rn := pc.Type.ReceiverName() -// receiver := j.Id(rn).Id(pc.Type.Name) +// receiver := j.Id(rn).Id(pc.Type.GetOriginalName) // // var msgTyp common.GolangType = render.GoPointer{Type: pc.Parent.FallbackMessageType, HasDefinition: true} // if pc.Parent.PublisherMessageTypePromise != nil { diff --git a/internal/render/tcp/server.go b/internal/render/tcp/server.go index 9f916d8..11548fd 100644 --- a/internal/render/tcp/server.go +++ b/internal/render/tcp/server.go @@ -12,7 +12,7 @@ package tcp //} // //func (ps ProtoServer) D(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Server", "", ps.Parent.Name, "definition", ps.Selectable(), "proto", ps.ProtoName) +// ctx.LogStartRender("Server", "", ps.Parent.GetOriginalName, "definition", ps.Selectable(), "proto", ps.ProtoName) // defer ctx.LogFinishRender() // var res []*j.Statement // res = append(res, ps.RenderNewFunc(ctx)...) @@ -25,17 +25,17 @@ package tcp //} // //func (ps ProtoServer) U(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Server", "", ps.Parent.Name, "usage", ps.Selectable(), "proto", ps.ProtoName) +// ctx.LogStartRender("Server", "", ps.Parent.GetOriginalName, "usage", ps.Selectable(), "proto", ps.ProtoName) // defer ctx.LogFinishRender() // return ps.Type.U(ctx) //} // //func (ps ProtoServer) ID() string { -// return ps.Parent.Name +// return ps.Parent.GetOriginalName //} // //func (ps ProtoServer) String() string { -// return "TCP ProtoServer " + ps.Parent.Name +// return "TCP ProtoServer " + ps.Parent.GetOriginalName //} // //func (ps ProtoServer) renderChannelMethods(ctx *common.RenderContext) []*j.Statement { diff --git a/internal/render/udp/channel.go b/internal/render/udp/channel.go index 96a47bf..0c91bcb 100644 --- a/internal/render/udp/channel.go +++ b/internal/render/udp/channel.go @@ -13,7 +13,7 @@ package udp //} // //func (pc ProtoChannel) D(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Channel", "", pc.Parent.Name, "definition", pc.Selectable(), "proto", pc.ProtoName) +// ctx.LogStartRender("Channel", "", pc.Parent.GetOriginalName, "definition", pc.Selectable(), "proto", pc.ProtoName) // defer ctx.LogFinishRender() // var res []*j.Statement // res = append(res, pc.ServerIface.D(ctx)...) @@ -33,17 +33,17 @@ package udp //} // //func (pc ProtoChannel) U(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Channel", "", pc.Parent.Name, "usage", pc.Selectable(), "proto", pc.ProtoName) +// ctx.LogStartRender("Channel", "", pc.Parent.GetOriginalName, "usage", pc.Selectable(), "proto", pc.ProtoName) // defer ctx.LogFinishRender() // return pc.Type.U(ctx) //} // //func (pc ProtoChannel) ID() string { -// return pc.Parent.Name +// return pc.Parent.GetOriginalName //} // //func (pc ProtoChannel) String() string { -// return "UDP ProtoChannel " + pc.Parent.Name +// return "UDP ProtoChannel " + pc.Parent.GetOriginalName //} // //func (pc ProtoChannel) renderNewFunc(ctx *common.RenderContext) []*j.Statement { @@ -66,7 +66,7 @@ package udp // Op("*").Add(utils.ToCode(pc.Type.U(ctx))...). // BlockFunc(func(bg *j.Group) { // bg.Op("res := ").Add(utils.ToCode(pc.Type.U(ctx))...).Values(j.DictFunc(func(d j.Dict) { -// d[j.Id("name")] = j.Id(pc.Parent.TypeNamePrefix + "Name").CallFunc(func(g *j.Group) { +// d[j.Id("name")] = j.Id(pc.Parent.TypeNamePrefix + "GetOriginalName").CallFunc(func(g *j.Group) { // if pc.Parent.ParametersType != nil { // g.Id("params") // } @@ -91,7 +91,7 @@ package udp // ctx.Logger.Trace("renderProtoPublisherMethods", "proto", pc.ProtoName) // // rn := pc.Type.ReceiverName() -// receiver := j.Id(rn).Id(pc.Type.Name) +// receiver := j.Id(rn).Id(pc.Type.GetOriginalName) // // var msgTyp common.GolangType = render.GoPointer{Type: pc.Parent.FallbackMessageType, HasDefinition: true} // if pc.Parent.PublisherMessageTypePromise != nil { diff --git a/internal/render/udp/server.go b/internal/render/udp/server.go index 8a4a77b..6172f2e 100644 --- a/internal/render/udp/server.go +++ b/internal/render/udp/server.go @@ -12,7 +12,7 @@ package udp //} // //func (ps ProtoServer) D(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Server", "", ps.Parent.Name, "definition", ps.Selectable(), "proto", ps.ProtoName) +// ctx.LogStartRender("Server", "", ps.Parent.GetOriginalName, "definition", ps.Selectable(), "proto", ps.ProtoName) // defer ctx.LogFinishRender() // var res []*j.Statement // res = append(res, ps.RenderNewFunc(ctx)...) @@ -25,17 +25,17 @@ package udp //} // //func (ps ProtoServer) U(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Server", "", ps.Parent.Name, "usage", ps.Selectable(), "proto", ps.ProtoName) +// ctx.LogStartRender("Server", "", ps.Parent.GetOriginalName, "usage", ps.Selectable(), "proto", ps.ProtoName) // defer ctx.LogFinishRender() // return ps.Type.U(ctx) //} // //func (ps ProtoServer) ID() string { -// return ps.Parent.Name +// return ps.Parent.GetOriginalName //} // //func (ps ProtoServer) String() string { -// return "UDP ProtoServer " + ps.Parent.Name +// return "UDP ProtoServer " + ps.Parent.GetOriginalName //} // //func (ps ProtoServer) renderChannelMethods(ctx *common.RenderContext) []*j.Statement { diff --git a/internal/render/ws/channel.go b/internal/render/ws/channel.go index 6bcd294..1285a0d 100644 --- a/internal/render/ws/channel.go +++ b/internal/render/ws/channel.go @@ -13,7 +13,7 @@ package ws //} // //func (pc ProtoChannel) D(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Channel", "", pc.Parent.Name, "definition", pc.Selectable(), "proto", pc.ProtoName) +// ctx.LogStartRender("Channel", "", pc.Parent.GetOriginalName, "definition", pc.Selectable(), "proto", pc.ProtoName) // defer ctx.LogFinishRender() // var res []*j.Statement // res = append(res, pc.ServerIface.D(ctx)...) @@ -33,17 +33,17 @@ package ws //} // //func (pc ProtoChannel) U(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Channel", "", pc.Parent.Name, "usage", pc.Selectable(), "proto", pc.ProtoName) +// ctx.LogStartRender("Channel", "", pc.Parent.GetOriginalName, "usage", pc.Selectable(), "proto", pc.ProtoName) // defer ctx.LogFinishRender() // return pc.Type.U(ctx) //} // //func (pc ProtoChannel) ID() string { -// return pc.Parent.Name +// return pc.Parent.GetOriginalName //} // //func (pc ProtoChannel) String() string { -// return "WS ProtoChannel " + pc.Parent.Name +// return "WS ProtoChannel " + pc.Parent.GetOriginalName //} // //func (pc ProtoChannel) renderNewFunc(ctx *common.RenderContext) []*j.Statement { @@ -66,7 +66,7 @@ package ws // Op("*").Add(utils.ToCode(pc.Type.U(ctx))...). // BlockFunc(func(bg *j.Group) { // bg.Op("res := ").Add(utils.ToCode(pc.Type.U(ctx))...).Values(j.DictFunc(func(d j.Dict) { -// d[j.Id("name")] = j.Id(pc.Parent.TypeNamePrefix + "Name").CallFunc(func(g *j.Group) { +// d[j.Id("name")] = j.Id(pc.Parent.TypeNamePrefix + "GetOriginalName").CallFunc(func(g *j.Group) { // if pc.Parent.ParametersType != nil { // g.Id("params") // } @@ -92,7 +92,7 @@ package ws // ctx.Logger.Trace("renderProtoPublisherMethods", "proto", pc.ProtoName) // // rn := pc.Type.ReceiverName() -// receiver := j.Id(rn).Id(pc.Type.Name) +// receiver := j.Id(rn).Id(pc.Type.GetOriginalName) // // var msgTyp common.GolangType = render.GoPointer{Type: pc.Parent.FallbackMessageType, HasDefinition: true} // if pc.Parent.PublisherMessageTypePromise != nil { diff --git a/internal/render/ws/server.go b/internal/render/ws/server.go index c995a99..63a766c 100644 --- a/internal/render/ws/server.go +++ b/internal/render/ws/server.go @@ -12,7 +12,7 @@ package ws //} // //func (ps ProtoServer) D(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Server", "", ps.Parent.Name, "definition", ps.Selectable(), "proto", ps.ProtoName) +// ctx.LogStartRender("Server", "", ps.Parent.GetOriginalName, "definition", ps.Selectable(), "proto", ps.ProtoName) // defer ctx.LogFinishRender() // var res []*j.Statement // res = append(res, ps.RenderNewFunc(ctx)...) @@ -25,17 +25,17 @@ package ws //} // //func (ps ProtoServer) U(ctx *common.RenderContext) []*j.Statement { -// ctx.LogStartRender("Server", "", ps.Parent.Name, "usage", ps.Selectable(), "proto", ps.ProtoName) +// ctx.LogStartRender("Server", "", ps.Parent.GetOriginalName, "usage", ps.Selectable(), "proto", ps.ProtoName) // defer ctx.LogFinishRender() // return ps.Type.U(ctx) //} // //func (ps ProtoServer) ID() string { -// return ps.Parent.Name +// return ps.Parent.GetOriginalName //} // //func (ps ProtoServer) String() string { -// return "WS ProtoServer " + ps.Parent.Name +// return "WS ProtoServer " + ps.Parent.GetOriginalName //} // //func (ps ProtoServer) renderChannelMethods(ctx *common.RenderContext) []*j.Statement { diff --git a/internal/selector/selector.go b/internal/selector/selector.go index 15dc4fd..7ab1b51 100644 --- a/internal/selector/selector.go +++ b/internal/selector/selector.go @@ -3,27 +3,28 @@ package selector import ( "github.com/bdragon300/go-asyncapi/internal/common" "github.com/samber/lo" - "reflect" "regexp" ) +type protoObjectContainer interface { + ProtoObjects() []common.Renderable +} func SelectObjects(objects []common.CompileObject, selection common.RenderSelectionConfig) []common.CompileObject { var res []common.CompileObject filterChain := getFiltersChain(selection) // TODO: logging - // Unwrap promise(s) until we get the actual object for _, object := range objects { r := object.Renderable - for { - v, ok := r.(common.ObjectPromise) - if !ok { - break + res = append(res, common.CompileObject{Renderable: r, ObjectURL: object.ObjectURL}) + + // Extract proto objects and add it to the result + if po, ok := r.(protoObjectContainer); ok { + for _, o := range po.ProtoObjects() { + res = append(res, common.CompileObject{Renderable: o, ObjectURL: object.ObjectURL}) } - r = reflect.ValueOf(v).MethodByName("T").Call(nil)[0].Interface().(common.Renderable) } - res = append(res, common.CompileObject{Renderable: r, ObjectURL: object.ObjectURL}) } return lo.Filter(res, func(object common.CompileObject, _ int) bool { diff --git a/internal/tmpl/context.go b/internal/tmpl/context.go new file mode 100644 index 0000000..50a63f3 --- /dev/null +++ b/internal/tmpl/context.go @@ -0,0 +1,49 @@ +package tmpl + +import ( + "github.com/bdragon300/go-asyncapi/internal/common" +) + +type renderContext interface { + CurrentSelection() common.RenderSelectionConfig +} + +type fileHeaderStorage interface { + Imports() []common.ImportItem + PackageName() string +} + +func NewTemplateContext(renderContext renderContext, object common.Renderable, headerStorage fileHeaderStorage) *TemplateContext { + return &TemplateContext{ + renderContext: renderContext, + fileHeaderStorage: headerStorage, + object: object, + } +} + +// TemplateContext is passed as value to the root template on selections processing. +type TemplateContext struct { + renderContext renderContext + // object contains an actual object to be rendered, without any promises. + object common.Renderable + fileHeaderStorage fileHeaderStorage +} + +func (t TemplateContext) Imports() []common.ImportItem { + return t.fileHeaderStorage.Imports() +} + +func (t TemplateContext) PackageName() string { + return t.fileHeaderStorage.PackageName() +} + +func (t TemplateContext) CurrentSelection() common.RenderSelectionConfig { + return t.renderContext.CurrentSelection() +} + +func (t TemplateContext) Object() common.Renderable { + if t.object == nil { + return nil + } + return t.object +} diff --git a/internal/tmpl/functions.go b/internal/tmpl/functions.go new file mode 100644 index 0000000..cc0521f --- /dev/null +++ b/internal/tmpl/functions.go @@ -0,0 +1,177 @@ +package tmpl + +import ( + "fmt" + "github.com/bdragon300/go-asyncapi/internal/common" + "github.com/bdragon300/go-asyncapi/internal/utils" + "github.com/samber/lo" + "path" + "strings" + "text/template" + "unicode" +) + +func GetTemplateFunctions() template.FuncMap { + type golangTypeWrapperType interface { + UnwrapGolangType() (common.GolangType, bool) + } + + extraFuncs := template.FuncMap{ + "golit": func(val any) (string, error) { return templateGoLit(val) }, + "goptr": func(val common.GolangType) (string, error) { return templateGoPtr(val) }, + "unwrapgoptr": func(val common.GolangType) common.GolangType { + if v, ok := any(val).(golangTypeWrapperType); ok { + if wt, ok := v.UnwrapGolangType(); ok { + return wt + } + } + return nil + }, + "goid": func(val any) string { return templateGoID(val) }, + "gocomment": func(text string) (string, error) { return templateGoComment(text) }, + "qual": func(parts ...string) string { return common.GetContext().QualifiedName(parts...) }, + "qualgenpkg": func(obj common.GolangType) (string, error) { + pkg, err := common.GetContext().QualifiedGeneratedPackage(obj) + if pkg == "" { + return "", err + } + return pkg + ".", err + }, + "qualrun": func(parts ...string) string { return common.GetContext().QualifiedRuntimeName(parts...) }, // TODO: check if .Import and qual is enough + "execTemplate": func(templateName string, ctx any) (string, error) { + return templateExecTemplate(templateName, ctx) + }, + "localobj": func(obj ...common.GolangType) string { + for _, o := range obj { + o.SetDefinitionInfo(common.GetContext().CurrentDefinitionInfo()) + } + return "" + }, + "godef": func(r common.GolangType) (string, error) { + tplName := path.Join(r.GoTemplate(), "definition") + r.SetDefinitionInfo(common.GetContext().CurrentDefinitionInfo()) + return templateExecTemplate(tplName, unwrapGolangPromise(r)) + }, + "gousage": func(r common.GolangType) (string, error) { return TemplateGoUsage(r) }, + // TODO: function to run external command + } + + return lo.Assign(sproutFunctions, extraFuncs) +} + +func TemplateGoUsage(r common.GolangType) (string, error) { + tplName := path.Join(r.GoTemplate(), "usage") + return templateExecTemplate(tplName, unwrapGolangPromise(r)) +} + +func templateExecTemplate(templateName string, ctx any) (string, error) { + var bld strings.Builder + + tpl := LoadTemplate(templateName) + if err := tpl.Execute(&bld, ctx); err != nil { + return "", err + } + return bld.String(), nil +} + +func templateGoLit(val any) (string, error) { + if v, ok := val.(common.GolangType); ok { + return TemplateGoUsage(v) + } + return utils.ToGoLiteral(val), nil +} + +func templateGoPtr(val common.GolangType) (string, error) { + if val == nil { + return "", fmt.Errorf("cannot get a pointer to nil") + } + s, err := TemplateGoUsage(val) + if err != nil { + return "", err + } + return lo.Ternary(val.IsPointer(), s, "*"+s), nil +} + + + +func templateGoID(val any) string { + var res string + + switch v := val.(type) { + case common.Renderable: + r := unwrapRenderablePromise(common.GetContext().CurrentObject().Renderable) + // If an object passed as an argument is the same as the current object, return name taken from context + // This name can be either original name or alias taken from promise + if r == v { + return common.GetContext().CurrentObject().GetOriginalName() + } + return v.GetOriginalName() // This is some another object, just return its original name + case string: + res = v + default: + panic(fmt.Sprintf("goid doesn't support the type %[1]T: %[1]v", val)) + } + + if res == "" { + return "" + } + return utils.ToGolangName(res, unicode.IsUpper(rune(res[0]))) +} + +type golangTypePromise interface { + GolangTypeT() common.GolangType +} + +func unwrapGolangPromise(val common.GolangType) common.GolangType { + o, ok := val.(golangTypePromise) + for ok { + val = o.GolangTypeT() + o, ok = val.(golangTypePromise) + } + return val +} + +type renderablePromise interface { + RenderableT() common.Renderable +} + +func unwrapRenderablePromise(val common.Renderable) common.Renderable { + o, ok := val.(renderablePromise) + for ok { + val = o.RenderableT() + o, ok = val.(renderablePromise) + } + return val +} + +func templateGoComment(text string) (string, error) { + if strings.HasPrefix(text, "//") || strings.HasPrefix(text, "/*") { + // automatic formatting disabled. + return text, nil + } + + var b strings.Builder + if strings.Contains(text, "\n") { + if _, err := b.WriteString("/*\n"); err != nil { + return "", err + } + } else { + if _, err := b.WriteString("// "); err != nil { + return "", err + } + } + if _, err := b.WriteString(text); err != nil { + return "", err + } + if strings.Contains(text, "\n") { + if !strings.HasSuffix(text, "\n") { + if _, err := b.WriteString("\n"); err != nil { + return "", err + } + } + if _, err := b.WriteString("*/"); err != nil { + return "", err + } + } + return b.String(), nil +} diff --git a/internal/tpl/load.go b/internal/tmpl/load.go similarity index 97% rename from internal/tpl/load.go rename to internal/tmpl/load.go index 311ff15..f20a4ef 100644 --- a/internal/tpl/load.go +++ b/internal/tmpl/load.go @@ -1,4 +1,4 @@ -package tpl +package tmpl import ( "github.com/bdragon300/go-asyncapi/templates" diff --git a/internal/tpl/sprout.go b/internal/tmpl/sprout.go similarity index 99% rename from internal/tpl/sprout.go rename to internal/tmpl/sprout.go index 12e502f..4340f48 100644 --- a/internal/tpl/sprout.go +++ b/internal/tmpl/sprout.go @@ -1,4 +1,4 @@ -package tpl +package tmpl import ( "github.com/go-sprout/sprout" diff --git a/internal/tpl/context.go b/internal/tpl/context.go deleted file mode 100644 index 78a50d7..0000000 --- a/internal/tpl/context.go +++ /dev/null @@ -1,47 +0,0 @@ -package tpl - -import ( - "github.com/bdragon300/go-asyncapi/internal/common" -) - -type renderContext interface { - Imports() []common.ImportItem - CurrentSelection() common.RenderSelectionConfig -} - -func NewTemplateContext(renderContext renderContext, object common.CompileObject, selectionIndex, overallIndex int) TemplateContext { - return TemplateContext{ - renderContext: renderContext, - object: object, - selectionIndex: selectionIndex, - overallIndex: overallIndex, - } -} - -// TemplateContext is passed as value to the root template on selections processing. -type TemplateContext struct { - renderContext renderContext - object common.CompileObject - selectionIndex int - overallIndex int -} - -func (t TemplateContext) Imports() []common.ImportItem { - return t.renderContext.Imports() -} - -func (t TemplateContext) CurrentSelection() common.RenderSelectionConfig { - return t.renderContext.CurrentSelection() -} - -func (t TemplateContext) SelectionIndex() int { - return t.selectionIndex -} - -func (t TemplateContext) OverallIndex() int { - return t.overallIndex -} - -func (t TemplateContext) Object() any { - return t.object.Renderable -} diff --git a/internal/tpl/functions.go b/internal/tpl/functions.go deleted file mode 100644 index 11c406c..0000000 --- a/internal/tpl/functions.go +++ /dev/null @@ -1,131 +0,0 @@ -package tpl - -import ( - "fmt" - "github.com/bdragon300/go-asyncapi/internal/common" - "github.com/bdragon300/go-asyncapi/internal/utils" - "github.com/samber/lo" - "strings" - "text/template" - "unicode" -) - -func GetTemplateFunctions() template.FuncMap { - type golangTypeWrapperType interface { - UnwrapGolangType() (common.GolangType, bool) - } - - extraFuncs := template.FuncMap{ - "golit": func(val any) string { return templateGoLit(val) }, - "goptr": func(val common.GolangType) (string, error) { return templateGoPtr(val) }, - "unwrapgoptr": func(val common.GolangType) common.GolangType { - if v, ok := any(val).(golangTypeWrapperType); ok { - if wt, ok := v.UnwrapGolangType(); ok { - return wt - } - } - return nil - }, - "goid": func(name string) string { return templateGoID(name) }, - "gocomment": func(text string) (string, error) { return templateGoComment(text) }, - "qual": func(parts ...string) string { return common.GetContext().QualifiedName(parts...) }, - "qualgenpkg": func(obj common.GolangType) (string, error) { - pkg, err := common.GetContext().QualifiedGeneratedPackage(obj) - if pkg == "" { - return "", err - } - return pkg + ".", err - }, - "qualrun": func(parts ...string) string { return common.GetContext().QualifiedRuntimeName(parts...) }, // TODO: check if .Import and qual is enough - "execTemplate": func(templateName string, ctx any) (string, error) { - tmpl := LoadTemplate(templateName) - var bld strings.Builder - if err := tmpl.Execute(&bld, ctx); err != nil { - return "", err - } - return bld.String(), nil - }, - "debug": func(params ...any) string { - params = append([]any{"DEBUG: "}, params...) - fmt.Print(params...) - return "" - }, - "localobj": func(obj ...common.GolangType) string { - for _, o := range obj { - o.SetDefinitionInfo(common.GetContext().CurrentDefinitionInfo()) - } - return "" - }, - // TODO: function to run external command - } - - return lo.Assign(sproutFunctions, extraFuncs) -} - -func templateGoLit(val any) string { - type usageDrawable interface { - U() string - } - - if v, ok := val.(usageDrawable); ok { - return v.U() - } - return utils.ToGoLiteral(val) -} - -func templateGoPtr(val common.GolangType) (string, error) { - type golangPointerType interface { - IsPointer() bool - } - - if val == nil { - return "", fmt.Errorf("cannot get a pointer to nil") - } - var isPtr bool - if v, ok := val.(golangPointerType); ok && v.IsPointer() { - isPtr = true - } - if isPtr { - return "*" + val.U(), nil - } - return val.U(), nil -} - -func templateGoID(val string) string { - if val == "" { - return "" - } - return utils.ToGolangName(val, unicode.IsUpper(rune(val[0]))) -} - -func templateGoComment(text string) (string, error) { - if strings.HasPrefix(text, "//") || strings.HasPrefix(text, "/*") { - // automatic formatting disabled. - return text, nil - } - - var b strings.Builder - if strings.Contains(text, "\n") { - if _, err := b.WriteString("/*\n"); err != nil { - return "", err - } - } else { - if _, err := b.WriteString("// "); err != nil { - return "", err - } - } - if _, err := b.WriteString(text); err != nil { - return "", err - } - if strings.Contains(text, "\n") { - if !strings.HasSuffix(text, "\n") { - if _, err := b.WriteString("\n"); err != nil { - return "", err - } - } - if _, err := b.WriteString("*/"); err != nil { - return "", err - } - } - return b.String(), nil -} diff --git a/internal/utils/names.go b/internal/utils/names.go index 359c6bc..87f7108 100644 --- a/internal/utils/names.go +++ b/internal/utils/names.go @@ -1,6 +1,7 @@ package utils import ( + "github.com/iancoleman/strcase" "go/token" "regexp" "strings" @@ -9,8 +10,6 @@ import ( ahocorasick "github.com/BobuSumisu/aho-corasick" "github.com/samber/lo" - - "github.com/stoewer/go-strcase" ) var ( @@ -43,9 +42,11 @@ func ToGolangName(rawString string, exported bool) string { var camel string if exported { - camel = strcase.UpperCamelCase(rawString) + //camel = strcase.UpperCamelCase(rawString) + camel = strcase.ToCamel(rawString) } else { - camel = strcase.LowerCamelCase(rawString) + camel = strcase.ToLowerCamel(rawString) + //camel = strcase.LowerCamelCase(rawString) } str := TransformInitialisms(camel) diff --git a/internal/utils/render.go b/internal/utils/render.go index 331cee1..c089256 100644 --- a/internal/utils/render.go +++ b/internal/utils/render.go @@ -49,9 +49,7 @@ func ToGoLiteral(val any) string { if !strings.Contains(res, ".") && !strings.Contains(res, "e") { // If the formatted value is not in scientific notation, and does not have a dot, then // we add ".0". Otherwise, it will be interpreted as an int. - // See: - // https://github.com/dave/jennifer/issues/39 - // https://github.com/golang/go/issues/26363 + // See: https://github.com/golang/go/issues/26363 res += ".0" } return res @@ -64,4 +62,4 @@ func ToGoLiteral(val any) string { } panic(fmt.Sprintf("unsupported type for literal: %T", val)) -} \ No newline at end of file +} diff --git a/internal/writer/render.go b/internal/writer/render.go index 707c409..295618c 100644 --- a/internal/writer/render.go +++ b/internal/writer/render.go @@ -7,11 +7,10 @@ import ( "github.com/bdragon300/go-asyncapi/internal/common" "github.com/bdragon300/go-asyncapi/internal/render/context" "github.com/bdragon300/go-asyncapi/internal/selector" - "github.com/bdragon300/go-asyncapi/internal/tpl" + "github.com/bdragon300/go-asyncapi/internal/tmpl" "github.com/bdragon300/go-asyncapi/internal/types" "github.com/samber/lo" "go/format" - "io" "os" "path" "text/template" @@ -49,60 +48,55 @@ import ( // return bld.String() //} -const defaultPreambuleTemplateName = "preambule.tmpl" +const defaultPreambleTemplateName = "preamble.tmpl" type renderSource interface { AllObjects() []common.CompileObject } +type fileRenderState struct { + fileHeader *context.RenderFileHeader + buf *bytes.Buffer +} + type renderQueueItem struct { selection common.RenderSelectionConfig object common.CompileObject - selectionIndex int - overallIndex int err error } -func RenderPackages(source renderSource, opts common.RenderOpts) (map[string]*bytes.Buffer, error) { - files := make(map[string]*bytes.Buffer) +func RenderFiles(source renderSource, opts common.RenderOpts) (map[string]*bytes.Buffer, error) { + files := make(map[string]fileRenderState) // TODO: logging queue := buildRenderQueue(source, opts.Selections) var deferred []renderQueueItem for len(queue) > 0 { for _, item := range queue { - ctx := &context.RenderContextImpl{RenderOpts: opts, CurrentSelectionConfig: item.selection} - tplCtx := tpl.NewTemplateContext(ctx, item.object, item.selectionIndex, item.overallIndex) - common.SetContext(ctx) - - rd, err := renderFile(tplCtx, item.selection.Template) + fileName, err := renderInlineTemplate(item, opts, item.selection.File) switch { - case errors.Is(err, common.ErrDefinitionNotRendered): + case errors.Is(err, common.ErrDefinitionLocationUnknown): // Template can't be rendered right now due to unknown object definition, defer it - item.err = err deferred = append(deferred, item) continue case err != nil: return nil, err } - fileName, err := renderInlineTemplate(tplCtx, item.selection.File) + if _, ok := files[fileName]; !ok { + files[fileName] = fileRenderState{fileHeader: context.NewRenderFileHeader(item.selection.Package), buf: &bytes.Buffer{}} + } + + err = renderObject(item, opts, item.selection.Template, files[fileName]) switch { - case errors.Is(err, common.ErrDefinitionNotRendered): + case errors.Is(err, common.ErrDefinitionLocationUnknown): // Template can't be rendered right now due to unknown object definition, defer it + item.err = err deferred = append(deferred, item) continue case err != nil: return nil, err } - - if _, ok := files[fileName]; !ok { - files[fileName] = &bytes.Buffer{} - } - - if _, err = files[fileName].ReadFrom(rd); err != nil { - return nil, err - } } if len(deferred) == len(queue) { return nil, fmt.Errorf( @@ -113,61 +107,123 @@ func RenderPackages(source renderSource, opts common.RenderOpts) (map[string]*by queue, deferred = deferred, nil } - return files, nil + res, err := renderFiles(files, opts) + if err != nil { + return res, err + } + + return res, nil } func buildRenderQueue(source renderSource, selections []common.RenderSelectionConfig) (res []renderQueueItem) { - var c int for _, selection := range selections { objects := selector.SelectObjects(source.AllObjects(), selection) - for ind, obj := range objects { - res = append(res, renderQueueItem{selection: selection, object: obj, selectionIndex: ind, overallIndex: c}) - c++ + for _, obj := range objects { + res = append(res, renderQueueItem{selection: selection, object: obj}) } } return } -func renderFile(tplCtx tpl.TemplateContext, templateName string) (io.Reader, error) { +type renderablePromise interface { + RenderableT() common.Renderable +} + +func unwrapPromise(obj common.CompileObject) common.Renderable { + // Unwrap promise(s) until we get the actual object + r := obj.Renderable + v, ok := r.(renderablePromise) + for ok { + r = v.RenderableT() + v, ok = r.(renderablePromise) + } + return r +} + +func renderInlineTemplate(item renderQueueItem, opts common.RenderOpts, text string) (string, error) { + ctx := &context.RenderContextImpl{ + RenderOpts: opts, + CurrentSelectionConfig: item.selection, + FileHeader: context.NewRenderFileHeader(""), + Object: item.object, + } + common.SetContext(ctx) + tplCtx := tmpl.NewTemplateContext(ctx, unwrapPromise(item.object), ctx.FileHeader) + var res bytes.Buffer - var tmpl *template.Template + tpl, err := template.New("").Funcs(tmpl.GetTemplateFunctions()).Parse(text) + if err != nil { + return "", err + } + if err = tpl.Execute(&res, tplCtx.Object()); err != nil { + return "", err + } + return res.String(), nil +} + +func renderObject(item renderQueueItem, opts common.RenderOpts, templateName string, renderState fileRenderState) error { + var tpl *template.Template + + ctx := &context.RenderContextImpl{ + RenderOpts: opts, + CurrentSelectionConfig: item.selection, + FileHeader: renderState.fileHeader, + Object: item.object, + } + common.SetContext(ctx) + tplCtx := tmpl.NewTemplateContext(ctx, unwrapPromise(item.object), renderState.fileHeader) // Execute the main template first to accumulate imports and other data, that will be rendered in preamble - var buf bytes.Buffer - if tmpl = tpl.LoadTemplate(templateName); tmpl == nil { - return nil, fmt.Errorf("template %q not found", templateName) + if tpl = tmpl.LoadTemplate(templateName); tpl == nil { + return fmt.Errorf("template %q not found", templateName) } - if err := tmpl.Execute(&buf, tplCtx); err != nil { - return nil, err + if err := tpl.Execute(renderState.buf, tplCtx); err != nil { + return err } + renderState.buf.WriteRune('\n') // Separate writes following each other (if any) - // TODO: redefinition preambule in config/cli args - if tmpl = tpl.LoadTemplate(defaultPreambuleTemplateName); tmpl == nil { - return nil, fmt.Errorf("template %q not found", defaultPreambuleTemplateName) - } - if err := tmpl.Execute(&res, tplCtx); err != nil { - return nil, err + return nil +} + +func renderFiles(files map[string]fileRenderState, opts common.RenderOpts) (map[string]*bytes.Buffer, error) { + var res = make(map[string]*bytes.Buffer, len(files)) + + // TODO: redefinition preamble in config/cli args + tpl := tmpl.LoadTemplate(defaultPreambleTemplateName) + if tpl == nil { + return nil, fmt.Errorf("template %q not found", defaultPreambleTemplateName) } - if _, err := res.ReadFrom(&buf); err != nil { - return nil, err + + for fileName, state := range files { + b, err := renderFile(tpl, opts, state) + if err != nil { + return nil, err + } + res[fileName] = b } - return &res, nil + return res, nil } -func renderInlineTemplate(tplCtx tpl.TemplateContext, text string) (string, error) { +func renderFile(preambleTpl *template.Template, opts common.RenderOpts, renderState fileRenderState) (*bytes.Buffer, error) { var res bytes.Buffer - tmpl, err := template.New("").Funcs(tpl.GetTemplateFunctions()).Parse(text) - if err != nil { - return "", err + + ctx := &context.RenderContextImpl{RenderOpts: opts, FileHeader: renderState.fileHeader} + common.SetContext(ctx) + tplCtx := tmpl.NewTemplateContext(ctx, nil, renderState.fileHeader) + + if err := preambleTpl.Execute(&res, tplCtx); err != nil { + return nil, err } - if err := tmpl.Execute(&res, tplCtx.Object()); err != nil { - return "", err + res.WriteRune('\n') + if _, err := res.ReadFrom(renderState.buf); err != nil { + return nil, err } - return res.String(), nil + + return &res, nil } -//func RenderPackages(source renderSource, opts common.RenderOpts) (fileContents map[string]*bytes.Buffer, err error) { +//func RenderFiles(source renderSource, opts common.RenderOpts) (fileContents map[string]*bytes.Buffer, err error) { // fileContents = make(map[string]*bytes.Buffer) // logger := types.NewLogger("Rendering 🎨") // rendered := 0 diff --git a/templates/amqp/amqp_channel.tmpl b/templates/amqp/amqp_channel.tmpl index b7a0498..c024c83 100644 --- a/templates/amqp/amqp_channel.tmpl +++ b/templates/amqp/amqp_channel.tmpl @@ -1,21 +1,22 @@ -type {{(print .Type.Name "Server") | toCamelCase}} interface { - Open{{.Type.Name}}(ctx {{qual "context.Context"}}, {{if .ParametersType}}params {{.ParametersType.U}}{{end}}) (*{{.Type.U}}, error) - {{if .IsPublisher}}Producer() {{qualrun .ProtoName "Producer"}}{{end}} - {{if .IsSubscriber}}Consumer() {{qualrun .ProtoName "Consumer"}}{{end}} +{{- localobj .Type}} +type {{ .Type | goid }}Server interface { + Open{{.Type | goid}}(ctx {{qual "context.Context"}}, {{if .ParametersType}}params {{ .ParametersType | gousage }}{{end}}) (*{{ .Type | gousage }}, error) + {{- if .IsPublisher}}Producer() {{qualrun .ProtoName "Producer"}}{{end}} + {{- if .IsSubscriber}}Consumer() {{qualrun .ProtoName "Consumer"}}{{end}} } -func New{{.Type.Name}}( - {{if .ParametersType}}params {{.ParametersType.U}},{{end}} - {{if .IsPublisher}}publisher {{qualrun .ProtoName "Publisher"}},{{end}} - {{if .IsSubscriber}}subscriber {{qualrun .ProtoName "Subscriber"}},{{end}} -) *{{.Type.U}} { - res := {{.Type.U}}{ +func New{{ .Type | goid }}( + {{- if .ParametersType}}params {{ .ParametersType | gousage }},{{end}} + {{- if .IsPublisher}}publisher {{qualrun .ProtoName "Publisher"}},{{end}} + {{- if .IsSubscriber}}subscriber {{qualrun .ProtoName "Subscriber"}},{{end}} +) *{{ .Type | gousage }} { + res := {{ .Type | gousage }}{ name: {{.TypeNamePrefix}}Name({{if .ParametersType}}params{{end}}), {{if .IsPublisher}}publisher: publisher,{{end}} {{if .IsSubscriber}}subscriber: subscriber,{{end}} } - {{if .BindingsType}} - bindings := {{.BindingsType.U}}{}.{{.ProtoName | capitalize}}() + {{- if .BindingsType}} + bindings := {{ .BindingsType | gousage }}{}.{{.ProtoName | capitalize}}() switch bindings.ChannelType { case {{qualrun .ProtoName "ChannelTypeQueue"}}: res.queue = res.name.String() @@ -28,51 +29,51 @@ func New{{.Type.Name}}( if bindings.QueueConfiguration.Name != "" { res.queue = bindings.QueueConfiguration.Name } - {{end}} + {{- end}} return &res } {{template "proto/channel/openFunction" .}} -{{.Type.D}} +{{ .Type | godef }} {{template "proto/channel/commonMethods" .}} -func (c {{.Type.U}}) Exchange() string { +func (c {{ .Type | gousage }}) Exchange() string { return c.exchange } -func (c {{.Type.U}}) Queue() string { +func (c {{ .Type | gousage }}) Queue() string { return c.queue } -func (c {{.Type.U}}) RoutingKey() string { +func (c {{ .Type | gousage }}) RoutingKey() string { return c.routingKey } -{{if .IsPublisher}} +{{- if .IsPublisher}} {{template "proto/channel/outputMethods" .}} - func (c {{.Type.U}}) SealEnvelope(envelope {{qualrun .ProtoName "EnvelopeWriter"}}, message {{if .PublisherMessageTypePromise}}{{goptr .PublisherMessageTypePromise.T.OutType.U}}{{else}}any{{end}}) error { + func (c {{ .Type | gousage }}) SealEnvelope(envelope {{qualrun .ProtoName "EnvelopeWriter"}}, message {{if .PublisherMessageTypePromise}}{{goptr .PublisherMessageTypePromise.T.OutType}}{{else}}any{{end}}) error { envelope.ResetPayload() - {{ if .PublisherMessageTypePromise}} + {{- if .PublisherMessageTypePromise}} {{- /* Message is set for Channel in spec */ -}} if err := message.Marshal{{.ProtoName | capitalize}}Envelope(envelope); err != nil { return err } - {{else}} + {{- else}} {{- /* No Message set for Channel in spec */ -}} enc := {{qual "encoding/json.NewEncoder"}}(envelope) if err := enc.Encode(message); err != nil { return err } - {{end}} + {{- end}} envelope.SetRoutingKey(c.RoutingKey()) - {{if and .PublisherMessageTypePromise (.PublisherMessageTypePromise.T.HasProtoBindings .ProtoName)}} - envelope.SetBindings(.PublisherMessageTypePromise.T.BindingsType.U){}.{{.ProtoName | capitalize}}() - {{end}} + {{- if and .PublisherMessageTypePromise (.PublisherMessageTypePromise.T.HasProtoBindings .ProtoName)}} + envelope.SetBindings({{ .PublisherMessageTypePromise.T.BindingsType | gousage }}){}.{{.ProtoName | capitalize}}() + {{- end}} return nil } -{{end}} +{{- end}} {{if .IsSubscriber}}{{template "proto/channel/subscribeMethods" .}}{{end}} \ No newline at end of file diff --git a/templates/amqp/amqp_server.tmpl b/templates/amqp/amqp_server.tmpl index ec771da..442ea2b 100644 --- a/templates/amqp/amqp_server.tmpl +++ b/templates/amqp/amqp_server.tmpl @@ -1,35 +1,35 @@ -{{localobj .Type}} -func New{{.Type.Name}}(producer {{qualrun .ProtoName "Producer"}}, consumer {{qualrun .ProtoName "Consumer"}}) *{{.Type.U}} { - return &{{.Type.U}}{ +{{- localobj .Type -}} +func New{{ .Type | goid }}(producer {{qualrun .ProtoName "Producer"}}, consumer {{qualrun .ProtoName "Consumer"}}) *{{ .Type | gousage }} { + return &{{ .Type | gousage }}{ producer: producer, consumer: consumer, } } -{{.Type.D}} +{{ .Type| godef }} -func (s {{.Type.U}}) Name() string { - return "{{.Name}}" +func (s {{ .Type | gousage }}) Name() string { + return "{{ . | goid }}" } -func (s {{.Type.U}}) Producer() {{qualrun .ProtoName "Producer"}} { +func (s {{ .Type | gousage }}) Producer() {{qualrun .ProtoName "Producer"}} { return s.producer } -func (s {{.Type.U}}) Consumer() {{qualrun .ProtoName "Consumer"}} { +func (s {{ .Type | gousage }}) Consumer() {{qualrun .ProtoName "Consumer"}} { return s.consumer } -{{range .GetRelevantProtoChannels .ProtoName}} -func (s {{$.Type.U}}) Open{{.Type.Name}}( +{{- range .GetRelevantProtoChannels .ProtoName}} +func (s {{ $.Type | gousage }}) Open{{ .Type | goid }}( ctx {{qual "context.Context"}}, - {{if .ParametersType}}params {{.ParametersType.U}},{{end}} -) (ch *{{.Type.U}}, err error) { - return {{qualgenpkg .Type}}{{print "Open" .Type.Name | goid}}( + {{- if .ParametersType}}params {{ .ParametersType | gousage }},{{end}} +) (ch *{{ .Type | gousage }}, err error) { + return {{qualgenpkg .Type}}Open{{ .Type | goid }}( ctx, - {{if .ParametersType}}params,{{end}} - {{if .IsPublisher}}s.producer,{{end}} - {{if .IsSubscriber}}s.consumer,{{end}} + {{- if .ParametersType}}params,{{end}} + {{- if .IsPublisher}}s.producer,{{end}} + {{- if .IsSubscriber}}s.consumer,{{end}} ) } -{{end}} \ No newline at end of file +{{- end}} \ No newline at end of file diff --git a/templates/channel.tmpl b/templates/channel.tmpl index 79c6365..16e1c8d 100644 --- a/templates/channel.tmpl +++ b/templates/channel.tmpl @@ -1,52 +1,53 @@ -{{if .ParametersType}} - {{.ParametersType.D}} -{{end}} +{{- if .ParametersType }} + {{ .ParametersType| godef }} +{{- end }} -{{ if .BindingsType}} - {{ .BindingsType.D }} - {{range $proto := .BindingsProtocols}} - {{$bindingsValue := $.ProtoBindingsValue $proto}} - func (c *{{ $.BindingsType.U }}) {{ $proto | capitalize }}() {{$bindingsValue.Type.U}} { - b := {{$bindingsValue.U}} - {{if $.BindingsChannelPromise}} - {{$jvals := $.BindingsChannelPromise.T.JSONValues.GetOrEmpty $proto}} - {{range $jvals.Entries}} +{{- if .BindingsType }} + {{ .BindingsType| godef }} + {{- range $proto := .BindingsProtocols }} + {{- $bindingsValue := $.ProtoBindingsValue $proto }} + func (c *{{ $.BindingsType | gousage }}) {{ $proto | capitalize }}() {{$bindingsValue.Type | gousage}} { + b := {{$bindingsValue | gousage}} + {{- if $.BindingsChannelPromise }} + {{- $jvals := $.BindingsChannelPromise.T.JSONValues.GetOrEmpty $proto }} + {{- range $jvals.Entries}} {{.Key | toCamelCase }} := {{.Value | golit}} _ = {{qual "encoding/json.Unmarshal"}}([]byte({{.Key | toCamelCase }}), &b.{{.Key}}) - {{end}} - {{end}} - {{if $.BindingsPublishPromise}} - {{$jvals := $.BindingsPublishPromise.T.JSONValues.GetOrEmpty $proto}} - {{range $jvals.Entries}} + {{- end}} + {{- end}} + {{- if $.BindingsPublishPromise}} + {{- $jvals := $.BindingsPublishPromise.T.JSONValues.GetOrEmpty $proto}} + {{- range $jvals.Entries}} {{.Key | toCamelCase }}Pub := {{.Value | golit}} _ = {{qual "encoding/json.Unmarshal"}}([]byte({{.Key | toCamelCase }}Pub), &b.PublisherBindings.{{.Key}}) - {{end}} - {{end}} - {{if $.BindingsSubscribePromise}} - {{$jvals := $.BindingsSubscribePromise.T.JSONValues.GetOrEmpty $proto}} - {{range $jvals.Entries}} + {{- end}} + {{- end}} + {{- if $.BindingsSubscribePromise}} + {{- $jvals := $.BindingsSubscribePromise.T.JSONValues.GetOrEmpty $proto}} + {{- range $jvals.Entries}} {{.Key | toCamelCase }}Sub := {{.Value | golit}} _ = {{qual "encoding/json.Unmarshal"}}([]byte({{.Key | toCamelCase }}Sub), &b.SubscriberBindings.{{.Key}}) - {{end}} - {{end}} + {{- end}} + {{- end}} return b } - {{end}} -{{end}} + {{- end}} +{{- end}} -func {{.TypeNamePrefix}}Name({{if .ParametersType}}params {{.ParametersType.U}}{{end}}) {{qualrun "ParamString"}} { - {{if .ParametersType}} +func {{.TypeNamePrefix}}Name({{if .ParametersType}}params {{.ParametersType| gousage}}{{end}}) {{qualrun "ParamString"}} { + {{- if .ParametersType}} paramMap := map[string]string{ - {{range .ParametersType.Fields}}params.{{.Name}}.Name(): params.{{.Name}}.String(), - {{end}} + {{- range .ParametersType.Fields}} + params.{{.Name}}.Name(): params.{{.Name}}.String(), + {{- end}} } return {{qualrun "ParamString"}}{ - Expr: "{{.SpecKey | golit}}", + Expr: {{.SpecKey | golit}}, Parameters: paramMap, } - {{else}} + {{- else}} return {{qualrun "ParamString"}}{ - Expr: "{{.SpecKey | golit}}", + Expr: {{.SpecKey | golit}}, } - {{end}} + {{- end}} } diff --git a/templates/common/proto.tmpl b/templates/common/proto.tmpl index 4b6e220..837184f 100644 --- a/templates/common/proto.tmpl +++ b/templates/common/proto.tmpl @@ -1,192 +1,193 @@ {{define "proto/channel/commonMethods"}} -func (c {{.Struct.U}}) Name() {{qualrun "ParamString"}} { +func (c {{.Type| gousage}}) Name() {{qualrun "ParamString"}} { return c.name } -func (c {{.Struct.U}}) Close() (err error) { - {{if .IsPublisher}} +func (c {{.Type| gousage}}) Close() (err error) { + {{- if .IsPublisher}} if c.publisher != nil { err = {{qual "errors.Join"}}(err, c.publisher.Close()) } - {{end}} - {{if .IsSubscriber}} + {{- end}} + {{- if .IsSubscriber}} if c.subscriber != nil { err = {{qual "errors.Join"}}(err, c.subscriber.Close()) } - {{end}} + {{- end}} return } -{{end}} +{{- end}} {{define "proto/channel/outputMethods"}} -func (c {{.Struct.U}}) Publisher() {{qualrun .ProtoName "Producer"}} { +func (c {{.Type| gousage}}) Publisher() {{qualrun .ProtoName "Producer"}} { return c.publisher } -func (c {{.Struct.U}}) Publish(ctx {{qual "context.Context"}}, envelopes ...{{qualrun .ProtoName "EnvelopeWriter"}}) error { +func (c {{.Type| gousage}}) Publish(ctx {{qual "context.Context"}}, envelopes ...{{qualrun .ProtoName "EnvelopeWriter"}}) error { return c.publisher.Publish(ctx, envelopes...) } -{{end}} +{{- end}} -{{- /* Common template for channel publish methods that doesn't contain protocol-specific bindings manipulations */ -}} +{{- /* Common template for channel publish methods that doesn't contain protocol-specific bindings manipulations */}} {{define "proto/channel/barePublishMethods"}} {{template "proto/channel/outputMethods" .}} - func (c {{.Struct.U}}) SealEnvelope(envelope {{qualrun .ProtoName "EnvelopeWriter"}}, message {{if .PublisherMessageTypePromise}}{{goptr .PublisherMessageTypePromise.T.OutType.U}}{{else}}any{{end}}) error { + func (c {{.Type| gousage}}) SealEnvelope(envelope {{qualrun .ProtoName "EnvelopeWriter"}}, message {{if .PublisherMessageTypePromise}}{{goptr .PublisherMessageTypePromise.T.OutType}}{{else}}any{{end}}) error { envelope.ResetPayload() - {{if .PublisherMessageTypePromise}} + {{- if .PublisherMessageTypePromise}} {{- /*Message is set for Channel in spec*/ -}} if err := message.Marshal{{.ProtoName | capitalize}}Envelope(envelope); err != nil { return err } - {{else}} + {{- else}} {{- /* No Message set for Channel in spec */ -}} enc := {{qual "encoding/json.NewEncoder"}}(envelope) if err := enc.Encode(message); err != nil { return err } - {{end}} + {{- end}} - {{if and .PublisherMessageTypePromise (.PublisherMessageTypePromise.T.HasProtoBindings .ProtoName)}} - envelope.SetBindings(.PublisherMessageTypePromise.T.BindingsType.U){}.{{.ProtoName | capitalize}}() - {{end}} + {{- if and .PublisherMessageTypePromise (.PublisherMessageTypePromise.T.HasProtoBindings .ProtoName)}} + envelope.SetBindings(.PublisherMessageTypePromise.T.BindingsType| gousage){}.{{.ProtoName | capitalize}}() + {{- end}} return nil } -{{end}} +{{- end}} {{define "proto/channel/subscribeMethods"}} -func (c {{.Struct.U}}) ExtractEnvelope(envelope {{qualrun .ProtoName "EnvelopeReader"}}, message {{if .SubscriberMessageTypePromise}}{{goptr .SubscriberMessageTypePromise.T.InType.U}}{{else}}any{{end}}) error { - {{if .SubscriberMessageTypePromise}} +func (c {{.Type| gousage}}) ExtractEnvelope(envelope {{qualrun .ProtoName "EnvelopeReader"}}, message {{if .SubscriberMessageTypePromise}}{{goptr .SubscriberMessageTypePromise.T.InType}}{{else}}any{{end}}) error { + {{- if .SubscriberMessageTypePromise}} {{- /* Message set for Channel in spec */ -}} return message.Unmarshal{{.ProtoName | capitalize}}Envelope(envelope) - {{else}} + {{- else}} {{- /* No Message set for Channel in spec */ -}} dec := {{qual "encoding/json.NewDecoder"}}(envelope) return dec.Decode(message) - {{end}} + {{- end}} } -func (c {{.Struct.U}}) IsSubscriber() {{qualrun .ProtoName "Subscriber"}} { +func (c {{.Type| gousage}}) IsSubscriber() {{qualrun .ProtoName "Subscriber"}} { return c.subscriber } -func (c {{.Struct.U}}) Subscribe(ctx {{qual "context.Context"}}, cb func(envelope {{qualrun .ProtoName "EnvelopeReader"}})) error { +func (c {{.Type| gousage}}) Subscribe(ctx {{qual "context.Context"}}, cb func(envelope {{qualrun .ProtoName "EnvelopeReader"}})) error { return c.subscriber.Receive(ctx, cb) } -{{end}} +{{- end}} -{{- /* Common template for channel OpenChannel function that doesn't contain protocol-specific bindings manipulations */ -}} +{{- /* Common template for channel OpenChannel function that doesn't contain protocol-specific bindings manipulations */}} {{define "proto/channel/openFunction"}} - func Open{{.Struct.Name}}( + func Open{{ .Type | goid }}( ctx {{qual "context.Context"}}, - {{if .ParametersType}}params {{.ParametersType.U}},{{end}} - {{if .IsPublisher}}producer {{qualrun .ProtoName "Producer"}},{{end}} - {{if .IsSubscriber}}consumer {{qualrun .ProtoName "Consumer"}},{{end}} - ) (ch *{{.Struct.U}}, err error) { + {{- if .ParametersType}}params {{.ParametersType| gousage}},{{end}} + {{- if .IsPublisher}}producer {{qualrun .ProtoName "Producer"}},{{end}} + {{- if .IsSubscriber}}consumer {{qualrun .ProtoName "Consumer"}},{{end}} + ) (ch *{{.Type| gousage}}, err error) { name := {{.TypeNamePrefix}}Name({{if .ParametersType}}params{{end}}) - bindings := {{.BindingsType.U}}{}.{{.ProtoName | capitalize}}() + {{- if .BindingsType}}bindings := {{.BindingsType| gousage}}{}.{{.ProtoName | capitalize}}(){{ end }} - {{if .IsPublisher}} + {{- if .IsPublisher}} var publisher {{qualrun .ProtoName "Publisher"}} if producer != nil { if publisher, err = producer.Publisher(ctx, name, {{if .BindingsType}}&bindings{{else}}nil{{end}}); err != nil { return nil, err } } - {{end}} - {{if .IsSubscriber}} + {{- end}} + {{- if .IsSubscriber}} var subscriber {{qualrun .ProtoName "Subscriber"}} if consumer != nil { if subscriber, err = consumer.Consumer(ctx, name, {{if .BindingsType}}&bindings{{else}}nil{{end}}); err != nil { return nil, err } } - {{end}} + {{- end}} - return &{{.Struct.U}}{ + return &{{.Type| gousage}}{ name: name, - {{if .IsPublisher}}publisher: publisher,{{end}} - {{if .IsSubscriber}}subscriber: subscriber,{{end}} + {{- if .IsPublisher}}publisher: publisher,{{end}} + {{- if .IsSubscriber}}subscriber: subscriber,{{end}} } } -{{end}} +{{- end}} -{{- /* Common template for channel NewChannel function that doesn't contain protocol-specific bindings manipulations */ -}} +{{- /* Common template for channel NewChannel function that doesn't contain protocol-specific bindings manipulations */}} {{define "proto/channel/bareNewFunction"}} - func New{{.Struct.Name}}( - {{if .ParametersType}}params {{.ParametersType.U}},{{end}} - {{if .IsPublisher}}publisher {{qualrun .ProtoName "Publisher"}},{{end}} - {{if .IsSubscriber}}subscriber {{qualrun .ProtoName "Subscriber"}},{{end}} - ) *{{.Struct.U}} { - res := {{.Struct.U}}{ + func New{{ .Type | goid }}( + {{- if .ParametersType}}params {{.ParametersType| gousage}},{{end}} + {{- if .IsPublisher}}publisher {{qualrun .ProtoName "Publisher"}},{{end}} + {{- if .IsSubscriber}}subscriber {{qualrun .ProtoName "Subscriber"}},{{end}} + ) *{{.Type| gousage}} { + res := {{.Type| gousage}}{ name: {{.TypeNamePrefix}}Name({{if .ParametersType}}params{{end}}), - {{if .IsPublisher}}publisher: publisher,{{end}} - {{if .IsSubscriber}}subscriber: subscriber,{{end}} + {{- if .IsPublisher}}publisher: publisher,{{end}} + {{- if .IsSubscriber}}subscriber: subscriber,{{end}} } return &res } -{{end}} +{{- end}} {{define "proto/message/marshalUnmarshalMethods"}} -func (m *{{.OutType.Name}}) Marshal{{ .ProtoName | capitalize }}Envelope(envelope {{qualrun .ProtoName "EnvelopeWriter"}} error { +func (m *{{ .OutType | goid }}) Marshal{{ .ProtoName | capitalize }}Envelope(envelope {{qualrun .ProtoName "EnvelopeWriter"}} error { {{template "proto/message/encodeExpr" .}} envelope.SetContentType({{.ContentType | golit}}) - {{if .HeadersTypePromise}} + {{- if .HeadersTypePromise}} envelope.SetHeaders({ - {{range .HeadersTypePromise.T.Fields}}{{.Name | golit}}: m.Headers.{{.Name}}, - {{end}} + {{- range .HeadersTypePromise.T.Fields}} + {{ .Name | golit}}: m.Headers.{{.Name}}, + {{- end}} }) - {{else}} + {{- else}} envelope.SetHeaders({{qualrun "Headers"}}(m.Headers)) - {{end}} + {{- end}} return nil } -func (m *{{.InType.Name}}) Unmarshal{{ .ProtoName | capitalize }}Envelope(envelope {{qualrun .ProtoName "EnvelopeReader"}} error { +func (m *{{ .InType | goid }}) Unmarshal{{ .ProtoName | capitalize }}Envelope(envelope {{qualrun .ProtoName "EnvelopeReader"}} error { {{template "proto/message/decodeExpr" .}} - {{if .HeadersTypePromise }} - {{- /* Empty headers should not generate code */ -}} - {{if gt (len .HeadersTypePromise.T.Fields) 0}} + {{- if .HeadersTypePromise }} + {{- /* Empty headers should not generate code */}} + {{- if gt (len .HeadersTypePromise.T.Fields) 0}} headers := envelope.Headers() - {{range .HeadersTypePromise.T.Fields}} + {{- range .HeadersTypePromise.T.Fields}} if v, ok := headers[{{.Name | golit}}]; ok { - m.Headers.{{.Name}} = v.({{.Type.U}}) + m.Headers.{{.Name}} = v.({{.Type| gousage}}) } - {{end}} - {{end}} - {{else}} - m.Headers = {{.HeadersFallbackType.U}}(envelope.Headers()) - {{end}} + {{- end}} + {{- end}} + {{- else}} + m.Headers = {{.HeadersFallbackType| gousage}}(envelope.Headers()) + {{- end}} return nil } -{{end}} +{{- end}} {{define "proto/message/encodeExpr"}} -{{if .EffectiveContentType | hasSuffix "yaml"}} +{{- if .EffectiveContentType | hasSuffix "yaml"}} enc := {{qual "encoding/yaml.v3.NewEncoder"}}(envelope) if err := enc.Encode(m.Payload); err != nil { return err } -{{else}} - {{- /* Use json even we dealing with unknown content type */ -}} +{{- else}} + {{- /* Use json even we dealing with unknown content type */}} enc := {{qual "encoding/json.NewEncoder"}}(envelope) if err := enc.Encode(m.Payload); err != nil { return err } -{{end}} -{{end}} +{{- end}} +{{- end}} {{define "proto/message/decodeExpr"}} -{{if .EffectiveContentType | hasSuffix "yaml"}} +{{- if .EffectiveContentType | hasSuffix "yaml"}} dec := {{qual "encoding/yaml.v3.NewDecoder"}}(envelope) if err := dec.Decode(&m.Payload); err != nil { return err } -{{else}} - {{- /* Use json even we dealing with unknown content type */ -}} +{{- else}} + {{- /* Use json even we dealing with unknown content type */}} dec := {{qual "encoding/json.NewDecoder"}}(envelope) if err := dec.Decode(&m.Payload); err != nil { return err } -{{end}} -{{end}} +{{- end}} +{{- end}} diff --git a/templates/http/http_channel.tmpl b/templates/http/http_channel.tmpl index 5f9920e..395a208 100644 --- a/templates/http/http_channel.tmpl +++ b/templates/http/http_channel.tmpl @@ -1,14 +1,15 @@ -type {{(print .Type.Name "Server") | toCamelCase}} interface { - Open{{.Type.Name}}(ctx {{qual "context.Context"}}, {{if .ParametersType}}params {{.ParametersType.U}}{{end}}) (*{{.Type.U}}, error) - {{if .IsPublisher}}Producer() {{qualrun .ProtoName "Producer"}}{{end}} - {{if .IsSubscriber}}Consumer() {{qualrun .ProtoName "Consumer"}}{{end}} +{{- localobj .Type}} +type {{ .Type | goid }}Server interface { + Open{{.Type | goid}}(ctx {{qual "context.Context"}}, {{if .ParametersType}}params {{.ParametersType | gousage }}{{end}}) (*{{.Type | gousage }}, error) + {{- if .IsPublisher}}Producer() {{qualrun .ProtoName "Producer"}}{{end}} + {{- if .IsSubscriber}}Consumer() {{qualrun .ProtoName "Consumer"}}{{end}} } {{template "proto/channel/bareNewFunction" .}} {{template "proto/channel/openFunction" .}} -{{.Type.D}} +{{.Type| godef}} {{template "proto/channel/commonMethods" .}} diff --git a/templates/http/http_server.tmpl b/templates/http/http_server.tmpl index 5bc849c..681aab0 100644 --- a/templates/http/http_server.tmpl +++ b/templates/http/http_server.tmpl @@ -1,36 +1,35 @@ -{{localobj .Type}} - -func New{{.Type.Name}}(producer {{qualrun .ProtoName "Producer"}}, consumer {{qualrun .ProtoName "Consumer"}}) *{{.Type.U}} { - return &{{.Type.U}}{ +{{- localobj .Type}} +func New{{ .Type | goid }}(producer {{qualrun .ProtoName "Producer"}}, consumer {{qualrun .ProtoName "Consumer"}}) *{{.Type| gousage}} { + return &{{.Type| gousage}}{ producer: producer, consumer: consumer, } } -{{.Type.D}} +{{.Type| godef}} -func (s {{.Type.U}}) Name() string { - return "{{.Name}}" +func (s {{.Type| gousage}}) Name() string { + return "{{ . | goid }}" } -func (s {{.Type.U}}) Producer() {{qualrun .ProtoName "Producer"}} { +func (s {{.Type| gousage}}) Producer() {{qualrun .ProtoName "Producer"}} { return s.producer } -func (s {{.Type.U}}) Consumer() {{qualrun .ProtoName "Consumer"}} { +func (s {{.Type| gousage}}) Consumer() {{qualrun .ProtoName "Consumer"}} { return s.consumer } -{{range .GetRelevantProtoChannels .ProtoName}} -func (s {{$.Type.U}}) Open{{.Type.Name}}( +{{- range .GetRelevantProtoChannels .ProtoName}} +func (s {{$.Type| gousage}}) Open{{ .Type | goid }}( ctx {{qual "context.Context"}}, - {{if .ParametersType}}params {{.ParametersType.U}},{{end}} -) (ch *{{.Type.U}}, err error) { - return {{qualgenpkg .Type}}{{print "Open" .Type.Name | goid}}( + {{- if .ParametersType}}params {{.ParametersType| gousage}},{{end}} +) (ch *{{.Type| gousage}}, err error) { + return {{qualgenpkg .Type}}Open{{ .Type | goid }}( ctx, - {{if .ParametersType}}params,{{end}} - {{if .IsPublisher}}s.producer,{{end}} - {{if .IsSubscriber}}s.consumer,{{end}} + {{- if .ParametersType}}params,{{end}} + {{- if .IsPublisher}}s.producer,{{end}} + {{- if .IsSubscriber}}s.consumer,{{end}} ) } -{{end}} \ No newline at end of file +{{- end}} \ No newline at end of file diff --git a/templates/ip/ip_channel.tmpl b/templates/ip/ip_channel.tmpl index 5f9920e..d2485ef 100644 --- a/templates/ip/ip_channel.tmpl +++ b/templates/ip/ip_channel.tmpl @@ -1,14 +1,15 @@ -type {{(print .Type.Name "Server") | toCamelCase}} interface { - Open{{.Type.Name}}(ctx {{qual "context.Context"}}, {{if .ParametersType}}params {{.ParametersType.U}}{{end}}) (*{{.Type.U}}, error) - {{if .IsPublisher}}Producer() {{qualrun .ProtoName "Producer"}}{{end}} - {{if .IsSubscriber}}Consumer() {{qualrun .ProtoName "Consumer"}}{{end}} +{{- localobj .Type}} +type {{ .Type | goid }}Server interface { + Open{{.Type | goid}}(ctx {{qual "context.Context"}}, {{if .ParametersType}}params {{.ParametersType| gousage}}{{end}}) (*{{.Type| gousage}}, error) + {{- if .IsPublisher}}Producer() {{qualrun .ProtoName "Producer"}}{{end}} + {{- if .IsSubscriber}}Consumer() {{qualrun .ProtoName "Consumer"}}{{end}} } {{template "proto/channel/bareNewFunction" .}} {{template "proto/channel/openFunction" .}} -{{.Type.D}} +{{.Type| godef}} {{template "proto/channel/commonMethods" .}} diff --git a/templates/ip/ip_server.tmpl b/templates/ip/ip_server.tmpl index ec771da..681aab0 100644 --- a/templates/ip/ip_server.tmpl +++ b/templates/ip/ip_server.tmpl @@ -1,35 +1,35 @@ -{{localobj .Type}} -func New{{.Type.Name}}(producer {{qualrun .ProtoName "Producer"}}, consumer {{qualrun .ProtoName "Consumer"}}) *{{.Type.U}} { - return &{{.Type.U}}{ +{{- localobj .Type}} +func New{{ .Type | goid }}(producer {{qualrun .ProtoName "Producer"}}, consumer {{qualrun .ProtoName "Consumer"}}) *{{.Type| gousage}} { + return &{{.Type| gousage}}{ producer: producer, consumer: consumer, } } -{{.Type.D}} +{{.Type| godef}} -func (s {{.Type.U}}) Name() string { - return "{{.Name}}" +func (s {{.Type| gousage}}) Name() string { + return "{{ . | goid }}" } -func (s {{.Type.U}}) Producer() {{qualrun .ProtoName "Producer"}} { +func (s {{.Type| gousage}}) Producer() {{qualrun .ProtoName "Producer"}} { return s.producer } -func (s {{.Type.U}}) Consumer() {{qualrun .ProtoName "Consumer"}} { +func (s {{.Type| gousage}}) Consumer() {{qualrun .ProtoName "Consumer"}} { return s.consumer } -{{range .GetRelevantProtoChannels .ProtoName}} -func (s {{$.Type.U}}) Open{{.Type.Name}}( +{{- range .GetRelevantProtoChannels .ProtoName}} +func (s {{$.Type| gousage}}) Open{{ .Type | goid }}( ctx {{qual "context.Context"}}, - {{if .ParametersType}}params {{.ParametersType.U}},{{end}} -) (ch *{{.Type.U}}, err error) { - return {{qualgenpkg .Type}}{{print "Open" .Type.Name | goid}}( + {{- if .ParametersType}}params {{.ParametersType| gousage}},{{end}} +) (ch *{{.Type| gousage}}, err error) { + return {{qualgenpkg .Type}}Open{{ .Type | goid }}( ctx, - {{if .ParametersType}}params,{{end}} - {{if .IsPublisher}}s.producer,{{end}} - {{if .IsSubscriber}}s.consumer,{{end}} + {{- if .ParametersType}}params,{{end}} + {{- if .IsPublisher}}s.producer,{{end}} + {{- if .IsSubscriber}}s.consumer,{{end}} ) } -{{end}} \ No newline at end of file +{{- end}} \ No newline at end of file diff --git a/templates/kafka/kafka_channel.tmpl b/templates/kafka/kafka_channel.tmpl index 93363ed..ca3740a 100644 --- a/templates/kafka/kafka_channel.tmpl +++ b/templates/kafka/kafka_channel.tmpl @@ -1,62 +1,63 @@ -type {{(print .Type.Name "Server") | toCamelCase}} interface { - Open{{.Type.Name}}(ctx {{qual "context.Context"}}, {{if .ParametersType}}params {{.ParametersType.U}}{{end}}) (*{{.Type.U}}, error) - {{if .IsPublisher}}Producer() {{qualrun .ProtoName "Producer"}}{{end}} - {{if .IsSubscriber}}Consumer() {{qualrun .ProtoName "Consumer"}}{{end}} +{{- localobj .Type}} +type {{ .Type | goid }}Server interface { + Open{{.Type | goid}}(ctx {{qual "context.Context"}}, {{if .ParametersType}}params {{.ParametersType| gousage}}{{end}}) (*{{.Type| gousage}}, error) + {{- if .IsPublisher}}Producer() {{qualrun .ProtoName "Producer"}}{{end}} + {{- if .IsSubscriber}}Consumer() {{qualrun .ProtoName "Consumer"}}{{end}} } -func New{{.Type.Name}}( - {{if .ParametersType}}params {{.ParametersType.U}},{{end}} - {{if .IsPublisher}}publisher {{qualrun .ProtoName "Publisher"}},{{end}} - {{if .IsSubscriber}}subscriber {{qualrun .ProtoName "Subscriber"}},{{end}} -) *{{.Type.U}} { - res := {{.Type.U}}{ +func New{{ .Type | goid }}( + {{- if .ParametersType}}params {{.ParametersType| gousage}},{{end}} + {{- if .IsPublisher}}publisher {{qualrun .ProtoName "Publisher"}},{{end}} + {{- if .IsSubscriber}}subscriber {{qualrun .ProtoName "Subscriber"}},{{end}} +) *{{.Type| gousage}} { + res := {{.Type| gousage}}{ name: {{.TypeNamePrefix}}Name({{if .ParametersType}}params{{end}}), - {{if .IsPublisher}}publisher: publisher,{{end}} - {{if .IsSubscriber}}subscriber: subscriber,{{end}} + {{- if .IsPublisher}}publisher: publisher,{{end}} + {{- if .IsSubscriber}}subscriber: subscriber,{{end}} } res.topic = res.name.String() - {{if .BindingsType}} - bindings := {{.BindingsType.U}}{}.{{.ProtoName | capitalize}}() + {{- if .BindingsType}} + bindings := {{.BindingsType| gousage}}{}.{{.ProtoName | capitalize}}() if bindings.Topic != "" { res.topic = bindings.Topic } - {{end}} + {{- end}} return &res } {{template "proto/channel/openFunction" .}} -{{.Type.D}} +{{.Type| godef}} {{template "proto/channel/commonMethods" .}} -func (c {{.Type.U}}) Topic() string { +func (c {{.Type| gousage}}) Topic() string { return c.topic } -{{if .IsPublisher}} +{{- if .IsPublisher}} {{template "proto/channel/outputMethods" .}} - func (c {{.Type.U}}) SealEnvelope(envelope {{qualrun .ProtoName "EnvelopeWriter"}}, message {{if .PublisherMessageTypePromise}}{{goptr .PublisherMessageTypePromise.T.OutType.U}}{{else}}any{{end}}) error { + func (c {{.Type| gousage}}) SealEnvelope(envelope {{qualrun .ProtoName "EnvelopeWriter"}}, message {{if .PublisherMessageTypePromise}}{{goptr .PublisherMessageTypePromise.T.OutType}}{{else}}any{{end}}) error { envelope.ResetPayload() - {{if .PublisherMessageTypePromise}} + {{- if .PublisherMessageTypePromise}} {{- /* Message is set for Channel in spec */ -}} if err := message.Marshal{{.ProtoName | capitalize}}Envelope(envelope); err != nil { return err } - {{else}} + {{- else}} {{- /* No Message set for Channel in spec */ -}} enc := {{qual "encoding/json.NewEncoder"}}(envelope) if err := enc.Encode(message); err != nil { return err } - {{end}} + {{- end}} envelope.SetTopic(c.topic) - {{if and .PublisherMessageTypePromise (.PublisherMessageTypePromise.T.HasProtoBindings .ProtoName)}} - envelope.SetBindings(.PublisherMessageTypePromise.T.BindingsType.U){}.{{.ProtoName | capitalize}}() - {{end}} + {{- if and .PublisherMessageTypePromise (.PublisherMessageTypePromise.T.HasProtoBindings .ProtoName)}} + envelope.SetBindings({{.PublisherMessageTypePromise.T.BindingsType | gousage }}){}.{{.ProtoName | capitalize}}() + {{- end}} return nil } -{{end}} +{{- end}} {{if .IsSubscriber}}{{template "proto/channel/subscribeMethods" .}}{{end}} \ No newline at end of file diff --git a/templates/kafka/kafka_server.tmpl b/templates/kafka/kafka_server.tmpl index ec771da..681aab0 100644 --- a/templates/kafka/kafka_server.tmpl +++ b/templates/kafka/kafka_server.tmpl @@ -1,35 +1,35 @@ -{{localobj .Type}} -func New{{.Type.Name}}(producer {{qualrun .ProtoName "Producer"}}, consumer {{qualrun .ProtoName "Consumer"}}) *{{.Type.U}} { - return &{{.Type.U}}{ +{{- localobj .Type}} +func New{{ .Type | goid }}(producer {{qualrun .ProtoName "Producer"}}, consumer {{qualrun .ProtoName "Consumer"}}) *{{.Type| gousage}} { + return &{{.Type| gousage}}{ producer: producer, consumer: consumer, } } -{{.Type.D}} +{{.Type| godef}} -func (s {{.Type.U}}) Name() string { - return "{{.Name}}" +func (s {{.Type| gousage}}) Name() string { + return "{{ . | goid }}" } -func (s {{.Type.U}}) Producer() {{qualrun .ProtoName "Producer"}} { +func (s {{.Type| gousage}}) Producer() {{qualrun .ProtoName "Producer"}} { return s.producer } -func (s {{.Type.U}}) Consumer() {{qualrun .ProtoName "Consumer"}} { +func (s {{.Type| gousage}}) Consumer() {{qualrun .ProtoName "Consumer"}} { return s.consumer } -{{range .GetRelevantProtoChannels .ProtoName}} -func (s {{$.Type.U}}) Open{{.Type.Name}}( +{{- range .GetRelevantProtoChannels .ProtoName}} +func (s {{$.Type| gousage}}) Open{{ .Type | goid }}( ctx {{qual "context.Context"}}, - {{if .ParametersType}}params {{.ParametersType.U}},{{end}} -) (ch *{{.Type.U}}, err error) { - return {{qualgenpkg .Type}}{{print "Open" .Type.Name | goid}}( + {{- if .ParametersType}}params {{.ParametersType| gousage}},{{end}} +) (ch *{{.Type| gousage}}, err error) { + return {{qualgenpkg .Type}}Open{{ .Type | goid }}( ctx, - {{if .ParametersType}}params,{{end}} - {{if .IsPublisher}}s.producer,{{end}} - {{if .IsSubscriber}}s.consumer,{{end}} + {{- if .ParametersType}}params,{{end}} + {{- if .IsPublisher}}s.producer,{{end}} + {{- if .IsSubscriber}}s.consumer,{{end}} ) } -{{end}} \ No newline at end of file +{{- end}} \ No newline at end of file diff --git a/templates/lang/goarray.tmpl b/templates/lang/goarray.tmpl index c87adfe..317e4d0 100644 --- a/templates/lang/goarray.tmpl +++ b/templates/lang/goarray.tmpl @@ -1,17 +1,17 @@ {{define "lang/goarray/definition"}} - {{- if .Description -}} - {{ print .Name "--" .Description | gocomment }} - {{- end -}} - type {{ .Name | goid }} [{{ if .Size }}{{ .Size }}{{ end }}]{{ .ItemsType.U }} -{{end}} + {{- if .Description }} + {{- print (goid .) "--" .Description | gocomment }} + {{- end }} + type {{ . | goid }} [{{ if .Size }}{{ .Size }}{{ end }}]{{ .ItemsType | gousage }} +{{- end}} {{define "lang/goarray/usage"}} - {{- if .HasDefinition -}} - {{if .Import -}} - {{ qual .Import .Name }} - {{- else -}} - {{ qualgenpkg . }}{{.Name | goid}} - {{- end -}} - {{- else -}} - [{{ if .Size }}{{ .Size }}{{ end }}]{{.ItemsType.U}} - {{- end -}} -{{end}} \ No newline at end of file + {{- if .HasDefinition }} + {{- if .Import }} + {{- qual .Import (goid .) }} + {{- else }} + {{- qualgenpkg . }}{{ . | goid }} + {{- end }} + {{- else }} + [{{ if .Size }}{{ .Size }}{{ end }}]{{ .ItemsType | gousage }} + {{- end }} +{{- end}} \ No newline at end of file diff --git a/templates/lang/gomap.tmpl b/templates/lang/gomap.tmpl index f7907e6..e45cc04 100644 --- a/templates/lang/gomap.tmpl +++ b/templates/lang/gomap.tmpl @@ -1,17 +1,17 @@ {{define "lang/gomap/definition"}} - {{- if .Description -}} - {{ print .Name "--" .Description | gocomment }} - {{- end -}} - type {{ .Name | goid }} map[{{.KeyType.U}}]{{.ValueType.U}} + {{- if .Description }} + {{ print (goid .) "--" .Description | gocomment }} + {{- end }} + type {{ . | goid }} map[{{ .KeyType | gousage }}]{{ .ValueType | gousage }} {{end}} {{define "lang/gomap/usage"}} - {{- if .HasDefinition -}} - {{if .Import -}} - {{ qual .Import .Name }} - {{- else -}} - {{ qualgenpkg . }}{{.Name | goid}} - {{- end -}} - {{- else -}} - map[{{.KeyType.U}}]{{.ValueType.U}} - {{- end -}} -{{end}} \ No newline at end of file + {{- if .HasDefinition }} + {{if .Import }} + {{ qual .Import (goid .) }} + {{- else }} + {{ qualgenpkg . }}{{ . | goid }} + {{- end }} + {{- else }} + map[{{ .KeyType | gousage }}]{{ .ValueType | gousage }} + {{- end }} +{{- end}} \ No newline at end of file diff --git a/templates/lang/gopointer.tmpl b/templates/lang/gopointer.tmpl new file mode 100644 index 0000000..4adfc93 --- /dev/null +++ b/templates/lang/gopointer.tmpl @@ -0,0 +1,6 @@ +{{define "lang/gopointer/definition"}} + {{- .Type | godef }} +{{- end}} +{{define "lang/gopointer/usage"}} + {{- .Type | goptr }} +{{- end}} diff --git a/templates/lang/gosimple.tmpl b/templates/lang/gosimple.tmpl index 5c4272b..55821e0 100644 --- a/templates/lang/gosimple.tmpl +++ b/templates/lang/gosimple.tmpl @@ -1,10 +1,10 @@ {{define "lang/gosimple/definition"}} - {{ .Name | goid }} -{{end}} + {{- . | goid }} +{{- end}} {{define "lang/gosimple/usage"}} - {{if .Import -}} - {{ qual .Import .Name }} - {{- else -}} - {{ qualgenpkg . }}{{.Name | goid}} - {{- end -}} -{{end}} \ No newline at end of file + {{- if .Import }} + {{- qual .Import (goid .) }} + {{- else }} + {{- qualgenpkg . }}{{ . | goid }} + {{- end }} +{{- end}} \ No newline at end of file diff --git a/templates/lang/gostruct.tmpl b/templates/lang/gostruct.tmpl index 062ca7b..3f56e2b 100644 --- a/templates/lang/gostruct.tmpl +++ b/templates/lang/gostruct.tmpl @@ -1,31 +1,31 @@ {{define "lang/gostruct/definition"}} - {{- if .Description -}} - {{ print .Name "--" .Description | gocomment }} - {{- end -}} - type {{ .Name | goid }} struct { - {{range .Fields -}} - {{- if .Description -}} - {{ print .Name "--" .Description | gocomment }} - {{- end}} - {{.Name | goid}} {{.Type.U}} {{.RenderTags}} - {{- end}} + {{- if .Description }} + {{- print (goid .) "--" .Description | gocomment }} + {{- end }} + type {{ . | goid }} struct { + {{- range .Fields }} + {{- if .Description }} + {{ print (goid .) "--" .Description | gocomment }} + {{- end }} + {{ .Name }} {{ .Type | gousage }} {{.RenderTags}} + {{- end }} } -{{end}} +{{- end}} {{define "lang/gostruct/usage"}} - {{- if .HasDefinition -}} - {{if .Import -}} - {{ qual .Import .Name }} - {{- else -}} - {{ qualgenpkg . }}{{.Name | goid}} - {{- end -}} - {{- else -}} + {{- if .HasDefinition }} + {{- if .Import }} + {{- qual .Import (goid .) }} + {{- else }} + {{- qualgenpkg . }}{{ . | goid }} + {{- end }} + {{- else }} struct { - {{range .Fields -}} - {{- if .Description -}} + {{- range .Fields }} + {{- if .Description }} {{ print .Name "--" .Description | gocomment }} - {{- end}} - {{.Name | goid}} {{.Type.U}} {{.RenderTags}} - {{- end}} + {{- end }} + {{ .Name }} {{ .Type | gousage }} {{.RenderTags}} + {{- end }} } - {{- end -}} -{{end}} \ No newline at end of file + {{- end }} +{{- end}} \ No newline at end of file diff --git a/templates/lang/gotypealias.tmpl b/templates/lang/gotypealias.tmpl index ee57e87..237d098 100644 --- a/templates/lang/gotypealias.tmpl +++ b/templates/lang/gotypealias.tmpl @@ -1,17 +1,17 @@ {{define "lang/gotypealias/definition"}} - {{- if .Description -}} - {{ print .Name "--" .Description | gocomment }} - {{- end -}} - type {{ .Name | goid }} {{.AliasedType.D}} -{{end}} + {{- if .Description }} + {{- print (goid .) "--" .Description | gocomment }} + {{- end }} + type {{ . | goid }} {{.AliasedType | godef }} +{{- end}} {{define "lang/gotypealias/usage"}} - {{- if .HasDefinition -}} - {{if .Import -}} - {{ qual .Import .Name }} - {{- else -}} - {{ qualgenpkg . }}{{.Name | goid}} - {{- end -}} - {{- else -}} - {{.AliasedType.U}} - {{- end -}} -{{end}} \ No newline at end of file + {{- if .HasDefinition }} + {{- if .Import }} + {{- qual .Import (goid .) }} + {{- else }} + {{- qualgenpkg . }}{{ . | goid }} + {{- end }} + {{- else }} + {{- .AliasedType | gousage }} + {{- end }} +{{- end}} \ No newline at end of file diff --git a/templates/lang/gounion.tmpl b/templates/lang/gounion.tmpl index 7604663..42f09fa 100644 --- a/templates/lang/gounion.tmpl +++ b/templates/lang/gounion.tmpl @@ -1,12 +1,12 @@ {{define "lang/gounion/definition"}} -{{.UnionStruct.D}} +{{ .UnionStruct | godef }} -func (u *{{.Name}}) UnmarshalJSON(data []byte) (err error) { -{{range .Fields}} +func (u *{{ . | goid }}) UnmarshalJSON(data []byte) (err error) { +{{- range .Fields}} if err = {{qual "encoding/json.Unmarshal"}}(bytes, {{if not .Type.IsPointer}}&{{end}}u{{.Type.TypeName}}; err == nil { return } -{{end}} +{{- end}} return } -{{end}} \ No newline at end of file +{{- end}} \ No newline at end of file diff --git a/templates/lang/govalue.tmpl b/templates/lang/govalue.tmpl index 83c2793..04a17f4 100644 --- a/templates/lang/govalue.tmpl +++ b/templates/lang/govalue.tmpl @@ -1,72 +1,65 @@ {{define "lang/govalue/usage"}} - {{if .Type}} - {{if .Type.IsPointer}} - {{- if .Empty -}} - {{- if .EmptyCurlyBrackets -}} - {{- /* &{} -> ToPtr({}) */ -}} - {{- qualrun "ToPtr"}}({}) - {{- else -}} - {{- /* &nil -> nil */ -}} - nil - {{- end -}} - {{- else if .LiteralValue -}} - {{$t := unwrapgoptr .Type}} - {{- if $t -}} - {{- /* &int(123) -> ToPtr(int(123)) */ -}} - {{- qualrun "ToPtr"}}({{$t.U}}({{template "lang/gotypealias/value_expr" .}})) - {{- else -}} - {{- /* &123 -> ToPtr(123) */ -}} + {{- if .Type }} + {{- if .Type.IsPointer }} + {{- if .Empty }} + {{- if .EmptyCurlyBrackets }} + {{- /* &{} -> ToPtr({}) */}}{{ qualrun "ToPtr"}}({}) + {{- else }} + {{- /* &nil -> nil */}}nil + {{- end }} + {{- else if .LiteralValue }} + {{- $t := unwrapgoptr .Type }} + {{- if $t }} + {{- /* &int(123) -> ToPtr(int(123)) */}} + {{- qualrun "ToPtr"}}({{ $t | gousage }}({{template "lang/gotypealias/value_expr" .}})) + {{- else }} + {{- /* &123 -> ToPtr(123) */}} {{- qualrun "ToPtr"}}({{template "lang/gotypealias/value_expr" .}}) - {{- end -}} - {{- else -}} - {{- /* &AnyType{}; &map[string]int{}; &[]int{} */ -}} - &{{.Type.U}} - {{- if .LiteralValue -}} - {{- /* int(123) */ -}}({{template "lang/gotypealias/value_expr" .}}) - {{- else -}} - {{- template "lang/gotypealias/value_expr" . -}} - {{- end -}} - {{- end -}} - {{else}} - {{.Type.U}} - {{- if .LiteralValue -}} - {{- /* int(123) */ -}}({{template "lang/gotypealias/value_expr" .}}) - {{- else -}} - {{- template "lang/gotypealias/value_expr" . -}} - {{- end -}} - {{end}} - {{else}} - {{template "lang/gotypealias/value_expr" .}} - {{end}} -{{end}} + {{- end }} + {{- else }} + {{- /* &AnyType{}; &map[string]int{}; &[]int{} */}}&{{- .Type | gousage }} + {{- if .LiteralValue }} + {{- /* int(123) */}}({{template "lang/gotypealias/value_expr" .}}) + {{- else }} + {{- template "lang/gotypealias/value_expr" . }} + {{- end }} + {{- end }} + {{- else }} + {{- .Type | gousage }} + {{- if .LiteralValue }} + {{- /* int(123) */}}({{template "lang/gotypealias/value_expr" .}}) + {{- else }} + {{- template "lang/gotypealias/value_expr" . }} + {{- end }} + {{- end }} + {{- else }} + {{- template "lang/gotypealias/value_expr" .}} + {{- end }} +{{- end}} {{define "lang/gotypealias/value_expr"}} - {{- if .LiteralValue -}} - {{- /* Literal */ -}} - {{- .LiteralValue | golit -}} - {{- else if .MapValues.Len -}} - {{- /* Map */ -}} - { - {{range .MapValues.Entries}} + {{- if .LiteralValue }} + {{- /* Literal */}}{{ .LiteralValue | golit }} + {{- else if .MapValues.Len }} + {{- /* Map */}}{ + {{- range .MapValues.Entries }} {{.Key | golit }}: {{ .Value | golit }}, - {{end}} + {{- end }} } - {{- else if .StructValues.Len -}} - {{- /* Struct */ -}} - { - {{range .StructValues.Entries}} + {{- else if .StructValues.Len }} + {{- /* Struct */}}{ + {{- range .StructValues.Entries }} {{.Key | goid }}: {{ .Value | golit }}, - {{end}} + {{- end }} } - {{- else if .ArrayValues -}} - {{- /* Array/slice */ -}} - { - {{range .ArrayValues}} + {{- else if .ArrayValues }} + {{- /* Array/slice */}}{ + {{- range .ArrayValues }} {{ . | golit }}, - {{end}} + {{- end }} } - {{- else -}} - {{- /* Empty value */ -}} - {{if .EmptyCurlyBrackets}}{}{{else}}nil{{end}} - {{- end -}} -{{end}} \ No newline at end of file + {{- else }} + {{- /* Empty value */}} + {{- if .EmptyCurlyBrackets}}{}{{else}}nil{{end}} + {{- end }} +{{- end}} \ No newline at end of file diff --git a/templates/main.tmpl b/templates/main.tmpl index cda8ed7..9b0a380 100644 --- a/templates/main.tmpl +++ b/templates/main.tmpl @@ -1,17 +1,17 @@ -{{if eq .Object.Kind "schema" }} - {{template "schema.tmpl" .}} -{{else if eq .Object.Kind "server"}} - {{template "server.tmpl" .Object }} -{{else if eq .Object.Kind "protoServer"}} - {{execTemplate (print .Object.ProtoName "_" "server.tmpl") .Object }} -{{else if eq .Object.Kind "parameter"}} - {{template "parameter.tmpl" .Object}} -{{else if eq .Object.Kind "channel"}} - {{template "channel.tmpl" .Object}} -{{else if eq .Object.Kind "protoChannel"}} - {{execTemplate (print .Object.ProtoName "_" "channel.tmpl") .Object}} -{{else if eq .Object.Kind "message"}} - {{template "message.tmpl" .Object}} -{{else if eq .Object.Kind "protoMessage"}} - {{execTemplate (print .Object.ProtoName "_" "message.tmpl") .Object}} -{{end}} +{{- if eq .Object.Kind "schema" }} + {{- template "schema.tmpl" .}} +{{- else if eq .Object.Kind "server"}} + {{- template "server.tmpl" .Object }} +{{- else if eq .Object.Kind "protoServer"}} + {{- execTemplate (print .Object.ProtoName "_" "server.tmpl") .Object }} +{{- else if eq .Object.Kind "parameter"}} + {{- template "parameter.tmpl" .Object}} +{{- else if eq .Object.Kind "channel"}} + {{- template "channel.tmpl" .Object}} +{{- else if eq .Object.Kind "protoChannel"}} + {{- execTemplate (print .Object.ProtoName "_" "channel.tmpl") .Object}} +{{- else if eq .Object.Kind "message"}} + {{- template "message.tmpl" .Object}} +{{- else if eq .Object.Kind "protoMessage"}} + {{- execTemplate (print .Object.ProtoName "_" "message.tmpl") .Object}} +{{- end}} diff --git a/templates/message.tmpl b/templates/message.tmpl index 1f00639..22519e1 100644 --- a/templates/message.tmpl +++ b/templates/message.tmpl @@ -1,67 +1,67 @@ -{{ if .BindingsType}} - {{ .BindingsType.D }} - {{range $proto := .BindingsProtocols}} - {{$bindingsValue := $.ProtoBindingsValue $proto}} - func (c *{{ $.BindingsType.U }}) {{ $proto | capitalize }}() {{$bindingsValue.Type.U}} { - b := {{$bindingsValue.U}} - {{if $.BindingsPromise}} - {{$jvals := $.BindingsPromise.T.JSONValues.GetOrEmpty $proto}} - {{range $jval := $jvals.Entries}} - {{$jval.Key | toCamelCase }} := {{$jval.Value | golit}} +{{- if .BindingsType}} + {{- .BindingsType| godef }} + {{- range $proto := .BindingsProtocols}} + {{- $bindingsValue := $.ProtoBindingsValue $proto}} + func (c *{{ $.BindingsType| gousage }}) {{ $proto | capitalize }}() {{$bindingsValue.Type| gousage}} { + b := {{$bindingsValue| gousage}} + {{- if $.BindingsPromise}} + {{- $jvals := $.BindingsPromise.T.JSONValues.GetOrEmpty $proto}} + {{- range $jval := $jvals.Entries}} + {{- $jval.Key | toCamelCase }} := {{$jval.Value | golit}} _ = {{qual "encoding/json.Unmarshal"}}([]byte({{$jval.Key | toCamelCase }}), &b.{{$jval.Key}}) - {{end}} - {{end}} + {{- end}} + {{- end}} return b } - {{end}} -{{ end }} + {{- end}} +{{- end }} -{{$headersType := .HeadersFallbackType}} -{{if .HeadersTypePromise}} - {{$headersType := .HeadersTypePromise.T}} -{{end}} +{{- $headersType := .HeadersFallbackType}} +{{- if .HeadersTypePromise}} + {{- $headersType := .HeadersTypePromise.T}} +{{- end}} -{{localobj .OutType}} -func New{{ .OutType.Name }}() *{{ .OutType.U }} { - return &{{ .OutType.U }}{} +{{- localobj .OutType}} +func New{{ .OutType | goid }}() *{{ .OutType| gousage }} { + return &{{ .OutType| gousage }}{} } -{{.OutType.D}} +{{.OutType| godef}} -func (m *{{.OutType.Name}}) WithPayload(payload {{.PayloadType.U}}) *{{.OutType.Name}} { +func (m *{{ .OutType | goid }}) WithPayload(payload {{.PayloadType| gousage}}) *{{ .OutType | goid }} { m.Payload = payload return m } -func (m *{{.OutType.Name}}) WithHeaders(headers {{$headersType.U}}) *{{.OutType.Name}} { +func (m *{{ .OutType | goid }}) WithHeaders(headers {{$headersType| gousage}}) *{{ .OutType | goid }} { m.Headers = headers return m } -{{if .CorrelationIDPromise}} -func (m {{.OutType.Name}}) SetCorrelationID(value {{(.CorrelationIDPromise.T.TargetVarType .OutType).U}}) { - {{(.CorrelationIDPromise.T.RenderSetterBody "value" .OutType).U}} +{{- if .CorrelationIDPromise}} +func (m {{ .OutType | goid }}) SetCorrelationID(value {{ .CorrelationIDPromise.T.TargetVarType .OutType | gousage}}) { + {{ .CorrelationIDPromise.T.RenderSetterBody "value" .OutType | gousage}} } -{{end}} +{{- end}} -{{localobj .InType}} -func New{{ .InType.Name }}() *{{ .InType.U }} { - return &{{ .InType.U }}{} +{{- localobj .InType}} +func New{{ .InType | goid }}() *{{ .InType| gousage }} { + return &{{ .InType| gousage }}{} } -{{.InType.D}} +{{.InType| godef}} -func (m *{{.InType.Name}}) MessagePayload() {{.PayloadType.U}} { +func (m *{{ .InType | goid }}) MessagePayload() {{.PayloadType| gousage}} { return m.Payload } -func (m *{{.InType.Name}}) MessageHeaders() {{$headersType.U}} { +func (m *{{ .InType | goid }}) MessageHeaders() {{$headersType| gousage}} { return m.Headers } -{{if .CorrelationIDPromise}} -func (m {{.InType.Name}}) CorrelationID() (value {{(.CorrelationIDPromise.T.TargetVarType .InType).U}}}, err error) { - {{(.CorrelationIDPromise.T.RenderGetterBody "value" .InType).U}} +{{- if .CorrelationIDPromise}} +func (m {{ .InType | goid }}) CorrelationID() (value {{.CorrelationIDPromise.T.TargetVarType .InType | gousage}}}, err error) { + {{ .CorrelationIDPromise.T.RenderGetterBody "value" .InType | gousage}} return } -{{end}} +{{- end}} diff --git a/templates/mqtt/mqtt_channel.tmpl b/templates/mqtt/mqtt_channel.tmpl index 580d6d8..998f7e2 100644 --- a/templates/mqtt/mqtt_channel.tmpl +++ b/templates/mqtt/mqtt_channel.tmpl @@ -1,18 +1,19 @@ -type {{(print .Type.Name "Server") | toCamelCase}} interface { - Open{{.Type.Name}}(ctx {{qual "context.Context"}}, {{if .ParametersType}}params {{.ParametersType.U}}{{end}}) (*{{.Type.U}}, error) - {{if .IsPublisher}}Producer() {{qualrun .ProtoName "Producer"}}{{end}} - {{if .IsSubscriber}}Consumer() {{qualrun .ProtoName "Consumer"}}{{end}} +{{- localobj .Type}} +type {{ .Type | goid }}Server interface { + Open{{.Type | goid}}(ctx {{qual "context.Context"}}, {{if .ParametersType}}params {{.ParametersType| gousage}}{{end}}) (*{{.Type| gousage}}, error) + {{- if .IsPublisher}}Producer() {{qualrun .ProtoName "Producer"}}{{end}} + {{- if .IsSubscriber}}Consumer() {{qualrun .ProtoName "Consumer"}}{{end}} } -func New{{.Type.Name}}( - {{if .ParametersType}}params {{.ParametersType.U}},{{end}} - {{if .IsPublisher}}publisher {{qualrun .ProtoName "Publisher"}},{{end}} - {{if .IsSubscriber}}subscriber {{qualrun .ProtoName "Subscriber"}},{{end}} -) *{{.Type.U}} { - res := {{.Type.U}}{ +func New{{ .Type | goid }}( + {{- if .ParametersType}}params {{.ParametersType| gousage}},{{end}} + {{- if .IsPublisher}}publisher {{qualrun .ProtoName "Publisher"}},{{end}} + {{- if .IsSubscriber}}subscriber {{qualrun .ProtoName "Subscriber"}},{{end}} +) *{{.Type| gousage}} { + res := {{.Type| gousage}}{ name: {{.TypeNamePrefix}}Name({{if .ParametersType}}params{{end}}), - {{if .IsPublisher}}publisher: publisher,{{end}} - {{if .IsSubscriber}}subscriber: subscriber,{{end}} + {{- if .IsPublisher}}publisher: publisher,{{end}} + {{- if .IsSubscriber}}subscriber: subscriber,{{end}} } res.topic = res.name.String() return &res @@ -20,36 +21,36 @@ func New{{.Type.Name}}( {{template "proto/channel/openFunction" .}} -{{.Type.D}} +{{.Type| godef}} {{template "proto/channel/commonMethods" .}} -func (c {{.Type.U}}) Topic() string { +func (c {{.Type| gousage}}) Topic() string { return c.topic } -{{if .IsPublisher}} +{{- if .IsPublisher}} {{template "proto/channel/outputMethods" .}} - func (c {{.Type.U}}) SealEnvelope(envelope {{qualrun .ProtoName "EnvelopeWriter"}}, message {{if .PublisherMessageTypePromise}}{{goptr .PublisherMessageTypePromise.T.OutType.U}}{{else}}any{{end}}) error { + func (c {{.Type| gousage}}) SealEnvelope(envelope {{qualrun .ProtoName "EnvelopeWriter"}}, message {{if .PublisherMessageTypePromise}}{{goptr .PublisherMessageTypePromise.T.OutType}}{{else}}any{{end}}) error { envelope.ResetPayload() - {{if .PublisherMessageTypePromise }} + {{- if .PublisherMessageTypePromise }} {{- /*Message is set for Channel in spec*/ -}} if err := message.Marshal{{.ProtoName | capitalize}}Envelope(envelope); err != nil { return err } - {{else}} + {{- else}} {{- /*No Message set for Channel in spec*/ -}} enc := {{qual "encoding/json.NewEncoder"}}(envelope) if err := enc.Encode(message); err != nil { return err } - {{end}} + {{- end}} envelope.SetTopic(c.topic) - {{if and .PublisherMessageTypePromise (.PublisherMessageTypePromise.T.HasProtoBindings .ProtoName)}} - envelope.SetBindings(.PublisherMessageTypePromise.T.BindingsType.U){}.{{.ProtoName | capitalize}}() - {{end}} + {{- if and .PublisherMessageTypePromise (.PublisherMessageTypePromise.T.HasProtoBindings .ProtoName)}} + envelope.SetBindings({{.PublisherMessageTypePromise.T.BindingsType | gousage }}){}.{{.ProtoName | capitalize}}() + {{- end}} return nil } -{{end}} +{{- end}} {{if .IsSubscriber}}{{template "proto/channel/subscribeMethods" .}}{{end}} \ No newline at end of file diff --git a/templates/mqtt/mqtt_server.tmpl b/templates/mqtt/mqtt_server.tmpl index ec771da..a11ba39 100644 --- a/templates/mqtt/mqtt_server.tmpl +++ b/templates/mqtt/mqtt_server.tmpl @@ -1,35 +1,35 @@ -{{localobj .Type}} -func New{{.Type.Name}}(producer {{qualrun .ProtoName "Producer"}}, consumer {{qualrun .ProtoName "Consumer"}}) *{{.Type.U}} { - return &{{.Type.U}}{ +{{- localobj .Type}} +func New{{.Type | goid}}(producer {{qualrun .ProtoName "Producer"}}, consumer {{qualrun .ProtoName "Consumer"}}) *{{.Type| gousage}} { + return &{{.Type| gousage}}{ producer: producer, consumer: consumer, } } -{{.Type.D}} +{{.Type| godef}} -func (s {{.Type.U}}) Name() string { - return "{{.Name}}" +func (s {{.Type| gousage}}) Name() string { + return "{{ . | goid }}" } -func (s {{.Type.U}}) Producer() {{qualrun .ProtoName "Producer"}} { +func (s {{.Type| gousage}}) Producer() {{qualrun .ProtoName "Producer"}} { return s.producer } -func (s {{.Type.U}}) Consumer() {{qualrun .ProtoName "Consumer"}} { +func (s {{.Type| gousage}}) Consumer() {{qualrun .ProtoName "Consumer"}} { return s.consumer } -{{range .GetRelevantProtoChannels .ProtoName}} -func (s {{$.Type.U}}) Open{{.Type.Name}}( +{{- range .GetRelevantProtoChannels .ProtoName}} +func (s {{$.Type| gousage}}) Open{{ .Type | goid }}( ctx {{qual "context.Context"}}, - {{if .ParametersType}}params {{.ParametersType.U}},{{end}} -) (ch *{{.Type.U}}, err error) { - return {{qualgenpkg .Type}}{{print "Open" .Type.Name | goid}}( + {{- if .ParametersType}}params {{.ParametersType| gousage}},{{end}} +) (ch *{{.Type| gousage}}, err error) { + return {{qualgenpkg .Type}}Open{{ .Type | goid }}( ctx, - {{if .ParametersType}}params,{{end}} - {{if .IsPublisher}}s.producer,{{end}} - {{if .IsSubscriber}}s.consumer,{{end}} + {{- if .ParametersType}}params,{{end}} + {{- if .IsPublisher}}s.producer,{{end}} + {{- if .IsSubscriber}}s.consumer,{{end}} ) } -{{end}} \ No newline at end of file +{{- end}} \ No newline at end of file diff --git a/templates/parameter.tmpl b/templates/parameter.tmpl index c7acdcd..a9921fb 100644 --- a/templates/parameter.tmpl +++ b/templates/parameter.tmpl @@ -1,13 +1,13 @@ -{{.Type.D}} +{{.Type | godef}} -func (p {{.Type.U}}) Name() string { - return {{.Name | golit}} +func (p {{.Type| gousage}}) Name() string { + return {{ . | goid | golit }} } -func (p {{.Type.U}}) String() string { - {{if .IsStringType}} +func (p {{.Type| gousage}}) String() string { + {{- if .IsStringType}} return string(p) - {{else}} + {{- else}} return {{qual "fmt.Sprint"}}(p.Value) - {{end}} + {{- end}} } \ No newline at end of file diff --git a/templates/preamble.tmpl b/templates/preamble.tmpl new file mode 100644 index 0000000..b6a1028 --- /dev/null +++ b/templates/preamble.tmpl @@ -0,0 +1,12 @@ +// Code generated by go-asyncapi tool. DO NOT EDIT. + +package {{ .PackageName }} + +{{- $imports := .Imports }} +{{- if $imports }} +import ( +{{- range $imports }} + {{ if .Alias }}{{ .Alias }} {{ end }}"{{ .PackagePath }}" +{{- end }} +) +{{- end }} diff --git a/templates/preambule.tmpl b/templates/preambule.tmpl deleted file mode 100644 index c131452..0000000 --- a/templates/preambule.tmpl +++ /dev/null @@ -1,12 +0,0 @@ -// Code generated by go-asyncapi tool. DO NOT EDIT. - -package {{.CurrentSelection.Package}} - -{{ $imports := .Imports }} -{{if $imports}} -import ( -{{range $imports}} - {{if .Alias}}{{.Alias}} {{end}}"{{.PackagePath}}" -{{end}} -) -{{end}} diff --git a/templates/redis/redis_channel.tmpl b/templates/redis/redis_channel.tmpl index 5f9920e..d2485ef 100644 --- a/templates/redis/redis_channel.tmpl +++ b/templates/redis/redis_channel.tmpl @@ -1,14 +1,15 @@ -type {{(print .Type.Name "Server") | toCamelCase}} interface { - Open{{.Type.Name}}(ctx {{qual "context.Context"}}, {{if .ParametersType}}params {{.ParametersType.U}}{{end}}) (*{{.Type.U}}, error) - {{if .IsPublisher}}Producer() {{qualrun .ProtoName "Producer"}}{{end}} - {{if .IsSubscriber}}Consumer() {{qualrun .ProtoName "Consumer"}}{{end}} +{{- localobj .Type}} +type {{ .Type | goid }}Server interface { + Open{{.Type | goid}}(ctx {{qual "context.Context"}}, {{if .ParametersType}}params {{.ParametersType| gousage}}{{end}}) (*{{.Type| gousage}}, error) + {{- if .IsPublisher}}Producer() {{qualrun .ProtoName "Producer"}}{{end}} + {{- if .IsSubscriber}}Consumer() {{qualrun .ProtoName "Consumer"}}{{end}} } {{template "proto/channel/bareNewFunction" .}} {{template "proto/channel/openFunction" .}} -{{.Type.D}} +{{.Type| godef}} {{template "proto/channel/commonMethods" .}} diff --git a/templates/redis/redis_server.tmpl b/templates/redis/redis_server.tmpl index ec771da..681aab0 100644 --- a/templates/redis/redis_server.tmpl +++ b/templates/redis/redis_server.tmpl @@ -1,35 +1,35 @@ -{{localobj .Type}} -func New{{.Type.Name}}(producer {{qualrun .ProtoName "Producer"}}, consumer {{qualrun .ProtoName "Consumer"}}) *{{.Type.U}} { - return &{{.Type.U}}{ +{{- localobj .Type}} +func New{{ .Type | goid }}(producer {{qualrun .ProtoName "Producer"}}, consumer {{qualrun .ProtoName "Consumer"}}) *{{.Type| gousage}} { + return &{{.Type| gousage}}{ producer: producer, consumer: consumer, } } -{{.Type.D}} +{{.Type| godef}} -func (s {{.Type.U}}) Name() string { - return "{{.Name}}" +func (s {{.Type| gousage}}) Name() string { + return "{{ . | goid }}" } -func (s {{.Type.U}}) Producer() {{qualrun .ProtoName "Producer"}} { +func (s {{.Type| gousage}}) Producer() {{qualrun .ProtoName "Producer"}} { return s.producer } -func (s {{.Type.U}}) Consumer() {{qualrun .ProtoName "Consumer"}} { +func (s {{.Type| gousage}}) Consumer() {{qualrun .ProtoName "Consumer"}} { return s.consumer } -{{range .GetRelevantProtoChannels .ProtoName}} -func (s {{$.Type.U}}) Open{{.Type.Name}}( +{{- range .GetRelevantProtoChannels .ProtoName}} +func (s {{$.Type| gousage}}) Open{{ .Type | goid }}( ctx {{qual "context.Context"}}, - {{if .ParametersType}}params {{.ParametersType.U}},{{end}} -) (ch *{{.Type.U}}, err error) { - return {{qualgenpkg .Type}}{{print "Open" .Type.Name | goid}}( + {{- if .ParametersType}}params {{.ParametersType| gousage}},{{end}} +) (ch *{{.Type| gousage}}, err error) { + return {{qualgenpkg .Type}}Open{{ .Type | goid }}( ctx, - {{if .ParametersType}}params,{{end}} - {{if .IsPublisher}}s.producer,{{end}} - {{if .IsSubscriber}}s.consumer,{{end}} + {{- if .ParametersType}}params,{{end}} + {{- if .IsPublisher}}s.producer,{{end}} + {{- if .IsSubscriber}}s.consumer,{{end}} ) } -{{end}} \ No newline at end of file +{{- end}} \ No newline at end of file diff --git a/templates/schema.tmpl b/templates/schema.tmpl index beb3746..a1b17dd 100644 --- a/templates/schema.tmpl +++ b/templates/schema.tmpl @@ -1 +1 @@ -{{.D}} \ No newline at end of file +{{ . | godef }} \ No newline at end of file diff --git a/templates/server.tmpl b/templates/server.tmpl index b5f047e..8e53c42 100644 --- a/templates/server.tmpl +++ b/templates/server.tmpl @@ -1,46 +1,47 @@ -{{if .ProtocolVersion}} -const {{.TypeNamePrefix}}ProtocolVersion = "{{.ProtocolVersion | golit}}" -{{end}} +{{- if .ProtocolVersion}} +const {{.TypeNamePrefix}}ProtocolVersion = {{.ProtocolVersion | golit}} +{{- end}} func {{.TypeNamePrefix}}URL( - {{range .VariablesPromises.Entries}}{{.Key | goid}} string,{{end}} -) {{qualrun "ParamString"}} { - {{if gt .VariablesPromises.Len 0}} - {{range .VariablesPromises.Entries}} - {{if .Value.T.Default}} +{{- range .VariablesPromises.Entries}} + {{- .Key | goid}} string, +{{- end }}) {{qualrun "ParamString"}} { + {{- if gt .VariablesPromises.Len 0}} + {{- range .VariablesPromises.Entries}} + {{- if .Value.T.Default}} if {{.Key | goid}} == "" { {{.Key | goid}} = "{{.Value.T.Default}}" } - {{end}} - {{end}} + {{- end}} + {{- end}} paramMap := map[string]string{ - {{range .VariablesPromises.Entries}}{{.Key | golit}}: {{.Value.T.Name | goid}},{{end}} + {{- range .VariablesPromises.Entries}}{{.Key | golit}}: {{.Value.T | goid}},{{end}} } return {{qualrun "ParamString"}}{ Expr: {{.URL | golit}}, Parameters: paramMap, } - {{else}} + {{- else}} return {{qualrun "ParamString"}}{ Expr: {{.URL | golit}}, } - {{end}} + {{- end}} } -{{if .BindingsType}} - {{.BindingsType.D}} - {{range $proto := .BindingsProtocols}} - {{$bindingsValue := $.ProtoBindingsValue $proto}} - func (c *{{ $.BindingsType.U }}) {{ $proto | capitalize }}() {{$bindingsValue.Type.U}} { - b := {{$bindingsValue.U}} - {{if $.BindingsPromise}} - {{$jvals := $.BindingsPromise.T.JSONValues.GetOrEmpty $proto}} - {{range $jval := $jvals.Entries}} +{{- if .BindingsType}} + {{- .BindingsType| godef}} + {{- range $proto := .BindingsProtocols}} + {{- $bindingsValue := $.ProtoBindingsValue $proto}} + func (c *{{ $.BindingsType| gousage }}) {{ $proto | capitalize }}() {{$bindingsValue.Type| gousage}} { + b := {{$bindingsValue| gousage}} + {{- if $.BindingsPromise}} + {{- $jvals := $.BindingsPromise.T.JSONValues.GetOrEmpty $proto}} + {{- range $jval := $jvals.Entries}} {{$jval.Key | toCamelCase }} := {{$jval.Value | golit}} _ = {{qual "encoding/json.Unmarshal"}}([]byte({{$jval.Key | toCamelCase }}), &b.{{$jval.Key}}) - {{end}} - {{end}} + {{- end}} + {{- end}} return b } - {{end}} -{{end}} + {{- end}} +{{- end}} diff --git a/templates/tcp/tcp_channel.tmpl b/templates/tcp/tcp_channel.tmpl index 5f9920e..d2485ef 100644 --- a/templates/tcp/tcp_channel.tmpl +++ b/templates/tcp/tcp_channel.tmpl @@ -1,14 +1,15 @@ -type {{(print .Type.Name "Server") | toCamelCase}} interface { - Open{{.Type.Name}}(ctx {{qual "context.Context"}}, {{if .ParametersType}}params {{.ParametersType.U}}{{end}}) (*{{.Type.U}}, error) - {{if .IsPublisher}}Producer() {{qualrun .ProtoName "Producer"}}{{end}} - {{if .IsSubscriber}}Consumer() {{qualrun .ProtoName "Consumer"}}{{end}} +{{- localobj .Type}} +type {{ .Type | goid }}Server interface { + Open{{.Type | goid}}(ctx {{qual "context.Context"}}, {{if .ParametersType}}params {{.ParametersType| gousage}}{{end}}) (*{{.Type| gousage}}, error) + {{- if .IsPublisher}}Producer() {{qualrun .ProtoName "Producer"}}{{end}} + {{- if .IsSubscriber}}Consumer() {{qualrun .ProtoName "Consumer"}}{{end}} } {{template "proto/channel/bareNewFunction" .}} {{template "proto/channel/openFunction" .}} -{{.Type.D}} +{{.Type| godef}} {{template "proto/channel/commonMethods" .}} diff --git a/templates/tcp/tcp_server.tmpl b/templates/tcp/tcp_server.tmpl index ec771da..681aab0 100644 --- a/templates/tcp/tcp_server.tmpl +++ b/templates/tcp/tcp_server.tmpl @@ -1,35 +1,35 @@ -{{localobj .Type}} -func New{{.Type.Name}}(producer {{qualrun .ProtoName "Producer"}}, consumer {{qualrun .ProtoName "Consumer"}}) *{{.Type.U}} { - return &{{.Type.U}}{ +{{- localobj .Type}} +func New{{ .Type | goid }}(producer {{qualrun .ProtoName "Producer"}}, consumer {{qualrun .ProtoName "Consumer"}}) *{{.Type| gousage}} { + return &{{.Type| gousage}}{ producer: producer, consumer: consumer, } } -{{.Type.D}} +{{.Type| godef}} -func (s {{.Type.U}}) Name() string { - return "{{.Name}}" +func (s {{.Type| gousage}}) Name() string { + return "{{ . | goid }}" } -func (s {{.Type.U}}) Producer() {{qualrun .ProtoName "Producer"}} { +func (s {{.Type| gousage}}) Producer() {{qualrun .ProtoName "Producer"}} { return s.producer } -func (s {{.Type.U}}) Consumer() {{qualrun .ProtoName "Consumer"}} { +func (s {{.Type| gousage}}) Consumer() {{qualrun .ProtoName "Consumer"}} { return s.consumer } -{{range .GetRelevantProtoChannels .ProtoName}} -func (s {{$.Type.U}}) Open{{.Type.Name}}( +{{- range .GetRelevantProtoChannels .ProtoName}} +func (s {{$.Type| gousage}}) Open{{ .Type | goid }}( ctx {{qual "context.Context"}}, - {{if .ParametersType}}params {{.ParametersType.U}},{{end}} -) (ch *{{.Type.U}}, err error) { - return {{qualgenpkg .Type}}{{print "Open" .Type.Name | goid}}( + {{- if .ParametersType}}params {{.ParametersType| gousage}},{{end}} +) (ch *{{.Type| gousage}}, err error) { + return {{qualgenpkg .Type}}Open{{ .Type | goid }}( ctx, - {{if .ParametersType}}params,{{end}} - {{if .IsPublisher}}s.producer,{{end}} - {{if .IsSubscriber}}s.consumer,{{end}} + {{- if .ParametersType}}params,{{end}} + {{- if .IsPublisher}}s.producer,{{end}} + {{- if .IsSubscriber}}s.consumer,{{end}} ) } -{{end}} \ No newline at end of file +{{- end}} \ No newline at end of file diff --git a/templates/udp/udp_channel.tmpl b/templates/udp/udp_channel.tmpl index 5f9920e..d2485ef 100644 --- a/templates/udp/udp_channel.tmpl +++ b/templates/udp/udp_channel.tmpl @@ -1,14 +1,15 @@ -type {{(print .Type.Name "Server") | toCamelCase}} interface { - Open{{.Type.Name}}(ctx {{qual "context.Context"}}, {{if .ParametersType}}params {{.ParametersType.U}}{{end}}) (*{{.Type.U}}, error) - {{if .IsPublisher}}Producer() {{qualrun .ProtoName "Producer"}}{{end}} - {{if .IsSubscriber}}Consumer() {{qualrun .ProtoName "Consumer"}}{{end}} +{{- localobj .Type}} +type {{ .Type | goid }}Server interface { + Open{{.Type | goid}}(ctx {{qual "context.Context"}}, {{if .ParametersType}}params {{.ParametersType| gousage}}{{end}}) (*{{.Type| gousage}}, error) + {{- if .IsPublisher}}Producer() {{qualrun .ProtoName "Producer"}}{{end}} + {{- if .IsSubscriber}}Consumer() {{qualrun .ProtoName "Consumer"}}{{end}} } {{template "proto/channel/bareNewFunction" .}} {{template "proto/channel/openFunction" .}} -{{.Type.D}} +{{.Type| godef}} {{template "proto/channel/commonMethods" .}} diff --git a/templates/udp/udp_server.tmpl b/templates/udp/udp_server.tmpl index ec771da..681aab0 100644 --- a/templates/udp/udp_server.tmpl +++ b/templates/udp/udp_server.tmpl @@ -1,35 +1,35 @@ -{{localobj .Type}} -func New{{.Type.Name}}(producer {{qualrun .ProtoName "Producer"}}, consumer {{qualrun .ProtoName "Consumer"}}) *{{.Type.U}} { - return &{{.Type.U}}{ +{{- localobj .Type}} +func New{{ .Type | goid }}(producer {{qualrun .ProtoName "Producer"}}, consumer {{qualrun .ProtoName "Consumer"}}) *{{.Type| gousage}} { + return &{{.Type| gousage}}{ producer: producer, consumer: consumer, } } -{{.Type.D}} +{{.Type| godef}} -func (s {{.Type.U}}) Name() string { - return "{{.Name}}" +func (s {{.Type| gousage}}) Name() string { + return "{{ . | goid }}" } -func (s {{.Type.U}}) Producer() {{qualrun .ProtoName "Producer"}} { +func (s {{.Type| gousage}}) Producer() {{qualrun .ProtoName "Producer"}} { return s.producer } -func (s {{.Type.U}}) Consumer() {{qualrun .ProtoName "Consumer"}} { +func (s {{.Type| gousage}}) Consumer() {{qualrun .ProtoName "Consumer"}} { return s.consumer } -{{range .GetRelevantProtoChannels .ProtoName}} -func (s {{$.Type.U}}) Open{{.Type.Name}}( +{{- range .GetRelevantProtoChannels .ProtoName}} +func (s {{$.Type| gousage}}) Open{{ .Type | goid }}( ctx {{qual "context.Context"}}, - {{if .ParametersType}}params {{.ParametersType.U}},{{end}} -) (ch *{{.Type.U}}, err error) { - return {{qualgenpkg .Type}}{{print "Open" .Type.Name | goid}}( + {{- if .ParametersType}}params {{.ParametersType| gousage}},{{end}} +) (ch *{{.Type| gousage}}, err error) { + return {{qualgenpkg .Type}}Open{{ .Type | goid }}( ctx, - {{if .ParametersType}}params,{{end}} - {{if .IsPublisher}}s.producer,{{end}} - {{if .IsSubscriber}}s.consumer,{{end}} + {{- if .ParametersType}}params,{{end}} + {{- if .IsPublisher}}s.producer,{{end}} + {{- if .IsSubscriber}}s.consumer,{{end}} ) } -{{end}} \ No newline at end of file +{{- end}} \ No newline at end of file diff --git a/templates/ws/ws_channel.tmpl b/templates/ws/ws_channel.tmpl index 5f9920e..d2485ef 100644 --- a/templates/ws/ws_channel.tmpl +++ b/templates/ws/ws_channel.tmpl @@ -1,14 +1,15 @@ -type {{(print .Type.Name "Server") | toCamelCase}} interface { - Open{{.Type.Name}}(ctx {{qual "context.Context"}}, {{if .ParametersType}}params {{.ParametersType.U}}{{end}}) (*{{.Type.U}}, error) - {{if .IsPublisher}}Producer() {{qualrun .ProtoName "Producer"}}{{end}} - {{if .IsSubscriber}}Consumer() {{qualrun .ProtoName "Consumer"}}{{end}} +{{- localobj .Type}} +type {{ .Type | goid }}Server interface { + Open{{.Type | goid}}(ctx {{qual "context.Context"}}, {{if .ParametersType}}params {{.ParametersType| gousage}}{{end}}) (*{{.Type| gousage}}, error) + {{- if .IsPublisher}}Producer() {{qualrun .ProtoName "Producer"}}{{end}} + {{- if .IsSubscriber}}Consumer() {{qualrun .ProtoName "Consumer"}}{{end}} } {{template "proto/channel/bareNewFunction" .}} {{template "proto/channel/openFunction" .}} -{{.Type.D}} +{{.Type| godef}} {{template "proto/channel/commonMethods" .}} diff --git a/templates/ws/ws_server.tmpl b/templates/ws/ws_server.tmpl index ec771da..681aab0 100644 --- a/templates/ws/ws_server.tmpl +++ b/templates/ws/ws_server.tmpl @@ -1,35 +1,35 @@ -{{localobj .Type}} -func New{{.Type.Name}}(producer {{qualrun .ProtoName "Producer"}}, consumer {{qualrun .ProtoName "Consumer"}}) *{{.Type.U}} { - return &{{.Type.U}}{ +{{- localobj .Type}} +func New{{ .Type | goid }}(producer {{qualrun .ProtoName "Producer"}}, consumer {{qualrun .ProtoName "Consumer"}}) *{{.Type| gousage}} { + return &{{.Type| gousage}}{ producer: producer, consumer: consumer, } } -{{.Type.D}} +{{.Type| godef}} -func (s {{.Type.U}}) Name() string { - return "{{.Name}}" +func (s {{.Type| gousage}}) Name() string { + return "{{ . | goid }}" } -func (s {{.Type.U}}) Producer() {{qualrun .ProtoName "Producer"}} { +func (s {{.Type| gousage}}) Producer() {{qualrun .ProtoName "Producer"}} { return s.producer } -func (s {{.Type.U}}) Consumer() {{qualrun .ProtoName "Consumer"}} { +func (s {{.Type| gousage}}) Consumer() {{qualrun .ProtoName "Consumer"}} { return s.consumer } -{{range .GetRelevantProtoChannels .ProtoName}} -func (s {{$.Type.U}}) Open{{.Type.Name}}( +{{- range .GetRelevantProtoChannels .ProtoName}} +func (s {{$.Type| gousage}}) Open{{ .Type | goid }}( ctx {{qual "context.Context"}}, - {{if .ParametersType}}params {{.ParametersType.U}},{{end}} -) (ch *{{.Type.U}}, err error) { - return {{qualgenpkg .Type}}{{print "Open" .Type.Name | goid}}( + {{- if .ParametersType}}params {{.ParametersType| gousage}},{{end}} +) (ch *{{.Type| gousage}}, err error) { + return {{qualgenpkg .Type}}Open{{ .Type | goid }}( ctx, - {{if .ParametersType}}params,{{end}} - {{if .IsPublisher}}s.producer,{{end}} - {{if .IsSubscriber}}s.consumer,{{end}} + {{- if .ParametersType}}params,{{end}} + {{- if .IsPublisher}}s.producer,{{end}} + {{- if .IsSubscriber}}s.consumer,{{end}} ) } -{{end}} \ No newline at end of file +{{- end}} \ No newline at end of file