Skip to content

Commit

Permalink
fix some issues
Browse files Browse the repository at this point in the history
  • Loading branch information
ubogdan committed Oct 18, 2024
1 parent 5b930d4 commit 36c14a4
Show file tree
Hide file tree
Showing 10 changed files with 82 additions and 69 deletions.
2 changes: 1 addition & 1 deletion cmd/swag/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const (
tagsFlag = "tags"
parseExtensionFlag = "parseExtension"
templateDelimsFlag = "templateDelims"
openAPIVersionFlag = "v3.1"
openAPIVersionFlag = "v3.1"
packageName = "packageName"
collectionFormatFlag = "collectionFormat"
packagePrefixFlag = "packagePrefix"
Expand Down
10 changes: 5 additions & 5 deletions enums_test.go
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
package swag

import (

"encoding/json"
"math/bits"
"os"
"path/filepath"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestParseGlobalEnums(t *testing.T) {
searchDir := "testdata/enums"
expected, err := os.ReadFile(filepath.Join(searchDir, "expected.json"))
assert.NoError(t, err)

p := New()
err = p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
assert.NoError(t, err)

b, err := json.MarshalIndent(p.swagger, "", " ")
assert.NoError(t, err)
assert.Equal(t, string(expected), string(b))

constsPath := "github.com/swaggo/swag/v2/testdata/enums/consts"

assert.Equal(t, bits.UintSize, p.packages.packages[constsPath].ConstTable["uintSize"].Value)
assert.Equal(t, int32(62), p.packages.packages[constsPath].ConstTable["maxBase"].Value)
assert.Equal(t, 8, p.packages.packages[constsPath].ConstTable["shlByLen"].Value)
Expand Down
3 changes: 2 additions & 1 deletion field_parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -725,8 +725,9 @@ func TestValidTags(t *testing.T) {
assert.Equal(t, 2, len(fieldnames))
assert.Equal(t, "x", fieldnames[0])
assert.Equal(t, "y", fieldnames[1])
})

t.Run("Pattern tag", func(t *testing.T) {
t.Run("Pattern tag", func(t *testing.T) {
t.Parallel()

schema := spec.Schema{}
Expand Down
5 changes: 2 additions & 3 deletions gen/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@ import (
"text/template"
"time"


jsoniter "github.com/json-iterator/go"

v2 "github.com/go-openapi/spec"
v3 "github.com/sv-tools/openapi/spec"

"github.com/swaggo/swag/v2"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"sigs.k8s.io/yaml"
)

Expand Down Expand Up @@ -538,7 +539,6 @@ func (g *Gen) writeGoDoc(packageName string, output io.Writer, swagger *v2.Swagg
return err
}


func (g *Gen) writeGoDocV3(packageName string, output io.Writer, openAPI *v3.OpenAPI, config *Config) error {
generator, err := template.New("oas3.tmpl").Funcs(template.FuncMap{
"printDoc": func(v string) string {
Expand Down Expand Up @@ -611,7 +611,6 @@ func (g *Gen) writeGoDocV3(packageName string, output io.Writer, openAPI *v3.Ope
return err
}


code := g.formatSource(buffer.Bytes())

// write
Expand Down
1 change: 0 additions & 1 deletion gen/gen_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,6 @@ func TestGen_BuildDocCustomDelims(t *testing.T) {
}
}


cmd := exec.Command("go", "build", "-buildmode=plugin", "github.com/swaggo/swag/v2/testdata/delims")

cmd.Dir = config.SearchDir
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect
golang.org/x/text v0.14.0 // indirect
)

require (
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsr
golang.org/x/mod v0.10.0 h1:lFO9qtOdlre5W1jxS3r/4szv2/6iXxScdzjoBMXNhYk=
golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.8.0 h1:vSDcovVPld282ceKgDimkRSC8kpaH1dgyc9UMzlt84Y=
golang.org/x/tools v0.8.0/go.mod h1:JxBZ99ISMI5ViVkT1tr6tdNmXeTrcpVSD3vZ1RsRdN4=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
Expand Down
29 changes: 14 additions & 15 deletions packages.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,6 @@ func (pkgDefs *PackagesDefinitions) parseTypesFromFile(astFile *ast.File, packag
if !ok {
continue
}

if generalDeclaration.Tok == token.TYPE {
for _, astSpec := range generalDeclaration.Specs {
if typeSpec, ok := astSpec.(*ast.TypeSpec); ok {
Expand Down Expand Up @@ -581,20 +580,20 @@ func (pkgDefs *PackagesDefinitions) FindTypeSpec(typeName string, file *ast.File
}
}
typeDef := pkgDefs.findTypeSpecFromPackagePaths(pkgPaths, externalPkgPaths, parts[1])
/*
TODO : remove
if len(pkgPaths) == 0 && len(externalPkgPaths) == 0 {
pkgDefinition := pkgDefs.packages["pkg/"+parts[0]]
if pkgDefinition == nil {
return pkgDefs.findTypeSpec("", parts[1])
}
typeDef = pkgDefinition.TypeDefinitions[parts[1]]
} else {
typeDef = pkgDefs.findTypeSpecFromPackagePaths(pkgPaths, externalPkgPaths, parts[1])
}
*/
/*
TODO : remove
if len(pkgPaths) == 0 && len(externalPkgPaths) == 0 {
pkgDefinition := pkgDefs.packages["pkg/"+parts[0]]
if pkgDefinition == nil {
return pkgDefs.findTypeSpec("", parts[1])
}
typeDef = pkgDefinition.TypeDefinitions[parts[1]]
} else {
typeDef = pkgDefs.findTypeSpecFromPackagePaths(pkgPaths, externalPkgPaths, parts[1])
}
*/
return pkgDefs.parametrizeGenericType(file, typeDef, typeName)
}

Expand Down
80 changes: 41 additions & 39 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,42 +35,44 @@ const (
// SnakeCase indicates using SnakeCase strategy for struct field.
SnakeCase = "snakecase"

idAttr = "@id"
acceptAttr = "@accept"
produceAttr = "@produce"
paramAttr = "@param"
successAttr = "@success"
failureAttr = "@failure"
responseAttr = "@response"
headerAttr = "@header"
tagsAttr = "@tags"
routerAttr = "@router"
deprecatedRouterAttr = "@deprecatedrouter"

summaryAttr = "@summary"
deprecatedAttr = "@deprecated"
securityAttr = "@security"
titleAttr = "@title"
conNameAttr = "@contact.name"
conURLAttr = "@contact.url"
conEmailAttr = "@contact.email"
licNameAttr = "@license.name"
licURLAttr = "@license.url"
versionAttr = "@version"
descriptionAttr = "@description"
descriptionMarkdownAttr = "@description.markdown"
secBasicAttr = "@securitydefinitions.basic"
secAPIKeyAttr = "@securitydefinitions.apikey"
secApplicationAttr = "@securitydefinitions.oauth2.application"
secImplicitAttr = "@securitydefinitions.oauth2.implicit"
secPasswordAttr = "@securitydefinitions.oauth2.password"
secAccessCodeAttr = "@securitydefinitions.oauth2.accesscode"
tosAttr = "@termsofservice"
extDocsDescAttr = "@externaldocs.description"
extDocsURLAttr = "@externaldocs.url"
xCodeSamplesAttr = "@x-codesamples"
scopeAttrPrefix = "@scope."
stateAttr = "@state"
idAttr = "@id"
acceptAttr = "@accept"
produceAttr = "@produce"
paramAttr = "@param"
successAttr = "@success"
failureAttr = "@failure"
responseAttr = "@response"
headerAttr = "@header"
tagsAttr = "@tags"
routerAttr = "@router"
deprecatedRouterAttr = "@deprecatedrouter"

summaryAttr = "@summary"
deprecatedAttr = "@deprecated"
securityAttr = "@security"
titleAttr = "@title"
conNameAttr = "@contact.name"
conURLAttr = "@contact.url"
conEmailAttr = "@contact.email"
licNameAttr = "@license.name"
licURLAttr = "@license.url"
versionAttr = "@version"
descriptionAttr = "@description"
descriptionMarkdownAttr = "@description.markdown"
secBasicAttr = "@securitydefinitions.basic"
secAPIKeyAttr = "@securitydefinitions.apikey"
secBearerAuthAttr = "@securitydefinitions.bearerauth"
secApplicationAttr = "@securitydefinitions.oauth2.application"
secImplicitAttr = "@securitydefinitions.oauth2.implicit"
secPasswordAttr = "@securitydefinitions.oauth2.password"
secAccessCodeAttr = "@securitydefinitions.oauth2.accesscode"
tosAttr = "@termsofservice"
extDocsDescAttr = "@externaldocs.description"
extDocsURLAttr = "@externaldocs.url"
xCodeSamplesAttr = "@x-codesamples"
xCodeSamplesAttrOriginal = "@x-codeSamples"
scopeAttrPrefix = "@scope."
stateAttr = "@state"
)

// ParseFlag determine what to parse
Expand Down Expand Up @@ -198,7 +200,7 @@ type Parser struct {
// ParseFuncBody whether swag should parse api info inside of funcs
ParseFuncBody bool

// use new openAPI version
// use new openAPI version
openAPIVersion bool
}

Expand Down Expand Up @@ -517,7 +519,7 @@ func (parser *Parser) parseDeps(absMainAPIFilePath string, parseDepth int) error

length := len(pkgs)
for i := 0; i < length; i++ {
err := parser.getAllGoFileInfoFromDepsByList(pkgs[i])
err := parser.getAllGoFileInfoFromDepsByList(pkgs[i], parser.ParseDependency)
if err != nil {
return err
}
Expand All @@ -537,7 +539,7 @@ func (parser *Parser) parseDeps(absMainAPIFilePath string, parseDepth int) error
}

for i := 0; i < len(t.Root.Deps); i++ {
if err := parser.getAllGoFileInfoFromDeps(&t.Root.Deps[i]); err != nil {
if err := parser.getAllGoFileInfoFromDeps(&t.Root.Deps[i], parser.ParseDependency); err != nil {
return errors.Wrap(err, "could not parse dependencies")
}
}
Expand Down
18 changes: 14 additions & 4 deletions parserv3.go
Original file line number Diff line number Diff line change
Expand Up @@ -722,7 +722,7 @@ func (p *Parser) ParseDefinitionV3(typeSpecDef *TypeSpecDef) (*SchemaV3, error)
}

if definition.Spec.Description == "" {
fillDefinitionDescriptionV3(definition.Spec, typeSpecDef.File, typeSpecDef)
fillDefinitionDescriptionV3(p, definition.Spec, typeSpecDef.File, typeSpecDef)
}

if len(typeSpecDef.Enums) > 0 {
Expand Down Expand Up @@ -764,7 +764,7 @@ func (p *Parser) ParseDefinitionV3(typeSpecDef *TypeSpecDef) (*SchemaV3, error)

// fillDefinitionDescription additionally fills fields in definition (spec.Schema)
// TODO: If .go file contains many types, it may work for a long time
func fillDefinitionDescriptionV3(definition *spec.Schema, file *ast.File, typeSpecDef *TypeSpecDef) {
func fillDefinitionDescriptionV3(parser *Parser, definition *spec.Schema, file *ast.File, typeSpecDef *TypeSpecDef) {
for _, astDeclaration := range file.Decls {
generalDeclaration, ok := astDeclaration.(*ast.GenDecl)
if !ok || generalDeclaration.Tok != token.TYPE {
Expand All @@ -777,8 +777,18 @@ func fillDefinitionDescriptionV3(definition *spec.Schema, file *ast.File, typeSp
continue
}

definition.Description =
extractDeclarationDescription(typeSpec.Doc, typeSpec.Comment, generalDeclaration.Doc)
var typeName string
if typeSpec.Name != nil {
typeName = typeSpec.Name.Name
}

text, err := parser.extractDeclarationDescription(typeName, typeSpec.Comment, generalDeclaration.Doc)
if err != nil {
parser.debug.Printf("Error extracting declaration description: %s", err)
continue
}

definition.Description = text
}
}
}
Expand Down

0 comments on commit 36c14a4

Please sign in to comment.