Skip to content

Commit

Permalink
fix using tab (\t) as separator for custom type names (#1594)
Browse files Browse the repository at this point in the history
  • Loading branch information
nitram509 committed Jun 7, 2023
1 parent ea35767 commit e73a0d0
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
24 changes: 24 additions & 0 deletions parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
11 changes: 9 additions & 2 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package swag
import (
"go/ast"
"go/token"
"regexp"
"strings"

"github.com/go-openapi/spec"
Expand Down Expand Up @@ -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]
}
}
Expand Down

0 comments on commit e73a0d0

Please sign in to comment.