From fa1ceeb63e0a9ceb2a3adcf03ede248375284d1a Mon Sep 17 00:00:00 2001 From: nitram509 Date: Mon, 29 May 2023 11:31:11 +0200 Subject: [PATCH] fix using tab (\t) as separator for custom type names --- parser_test.go | 24 ++++++++++++++++++++++++ types.go | 11 +++++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/parser_test.go b/parser_test.go index f070376db..71dc90da4 100644 --- a/parser_test.go +++ b/parser_test.go @@ -3249,6 +3249,30 @@ func Fun() { assert.Equal(t, "#/definitions/Teacher", ref.String()) } +func TestParseTabFormattedRenamedStructDefinition(t *testing.T) { + t.Parallel() + + src := "package main\n" + + "\n" + + "type Child struct {\n" + + "\tName string\n" + + "}\t//\t@name\tPupil\n" + + "\n" + + "// @Success 200 {object} Pupil\n" + + "func Fun() { }" + + p := New() + _ = p.packages.ParseFile("api", "api/api.go", src, ParseAll) + _, err := p.packages.ParseTypes() + assert.NoError(t, err) + + err = p.packages.RangeFiles(p.ParseRouterAPIInfo) + assert.NoError(t, err) + + _, ok := p.swagger.Definitions["Pupil"] + assert.True(t, ok) +} + func TestParseFunctionScopedStructDefinition(t *testing.T) { t.Parallel() diff --git a/types.go b/types.go index 8e2f51d87..ebb373d7f 100644 --- a/types.go +++ b/types.go @@ -3,6 +3,7 @@ package swag import ( "go/ast" "go/token" + "regexp" "strings" "github.com/go-openapi/spec" @@ -47,9 +48,15 @@ func (t *TypeSpecDef) TypeName() string { return t.TypeSpec.Name.Name[1:] } else if t.TypeSpec.Comment != nil { // get alias from comment '// @name ' + const regexCaseInsensitive = "(?i)" + reTypeName, err := regexp.Compile(regexCaseInsensitive + `^@name\s+(\S+)`) + if err != nil { + panic(err) + } for _, comment := range t.TypeSpec.Comment.List { - texts := strings.Split(strings.TrimSpace(strings.TrimLeft(comment.Text, "/")), " ") - if len(texts) > 1 && strings.ToLower(texts[0]) == "@name" { + trimmedComment := strings.TrimSpace(strings.TrimLeft(comment.Text, "/")) + texts := reTypeName.FindStringSubmatch(trimmedComment) + if len(texts) > 1 { return texts[1] } }