Skip to content

Commit e73a0d0

Browse files
authored
fix using tab (\t) as separator for custom type names (#1594)
1 parent ea35767 commit e73a0d0

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

parser_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3249,6 +3249,30 @@ func Fun() {
32493249
assert.Equal(t, "#/definitions/Teacher", ref.String())
32503250
}
32513251

3252+
func TestParseTabFormattedRenamedStructDefinition(t *testing.T) {
3253+
t.Parallel()
3254+
3255+
src := "package main\n" +
3256+
"\n" +
3257+
"type Child struct {\n" +
3258+
"\tName string\n" +
3259+
"}\t//\t@name\tPupil\n" +
3260+
"\n" +
3261+
"// @Success 200 {object} Pupil\n" +
3262+
"func Fun() { }"
3263+
3264+
p := New()
3265+
_ = p.packages.ParseFile("api", "api/api.go", src, ParseAll)
3266+
_, err := p.packages.ParseTypes()
3267+
assert.NoError(t, err)
3268+
3269+
err = p.packages.RangeFiles(p.ParseRouterAPIInfo)
3270+
assert.NoError(t, err)
3271+
3272+
_, ok := p.swagger.Definitions["Pupil"]
3273+
assert.True(t, ok)
3274+
}
3275+
32523276
func TestParseFunctionScopedStructDefinition(t *testing.T) {
32533277
t.Parallel()
32543278

types.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package swag
33
import (
44
"go/ast"
55
"go/token"
6+
"regexp"
67
"strings"
78

89
"github.com/go-openapi/spec"
@@ -47,9 +48,15 @@ func (t *TypeSpecDef) TypeName() string {
4748
return t.TypeSpec.Name.Name[1:]
4849
} else if t.TypeSpec.Comment != nil {
4950
// get alias from comment '// @name '
51+
const regexCaseInsensitive = "(?i)"
52+
reTypeName, err := regexp.Compile(regexCaseInsensitive + `^@name\s+(\S+)`)
53+
if err != nil {
54+
panic(err)
55+
}
5056
for _, comment := range t.TypeSpec.Comment.List {
51-
texts := strings.Split(strings.TrimSpace(strings.TrimLeft(comment.Text, "/")), " ")
52-
if len(texts) > 1 && strings.ToLower(texts[0]) == "@name" {
57+
trimmedComment := strings.TrimSpace(strings.TrimLeft(comment.Text, "/"))
58+
texts := reTypeName.FindStringSubmatch(trimmedComment)
59+
if len(texts) > 1 {
5360
return texts[1]
5461
}
5562
}

0 commit comments

Comments
 (0)