Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix using tab (\t) as separator for custom type names #1594

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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