Add v16.8.0

This commit is contained in:
Jan Stabenow
2022-06-03 17:21:52 +02:00
parent c8bebd95ef
commit 9746248c10
431 changed files with 14782 additions and 13944 deletions

View File

@@ -3,14 +3,13 @@ module github.com/swaggo/echo-swagger
go 1.15
require (
github.com/labstack/echo/v4 v4.1.14
github.com/labstack/gommon v0.3.1 // indirect
github.com/labstack/echo/v4 v4.7.2
github.com/mailru/easyjson v0.7.7 // indirect
github.com/stretchr/testify v1.7.0
github.com/swaggo/files v0.0.0-20210815190702-a29dd2bc99b2
github.com/swaggo/swag v1.7.9
golang.org/x/crypto v0.0.0-20220131195533-30dcbda58838 // indirect
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd
golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a // indirect
golang.org/x/tools v0.1.9 // indirect
github.com/swaggo/swag v1.8.1
golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 // indirect
golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4
golang.org/x/sys v0.0.0-20220422013727-9388b58f7150 // indirect
golang.org/x/tools v0.1.10 // indirect
)

View File

@@ -12,7 +12,6 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY=
@@ -24,6 +23,7 @@ github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7
github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk=
github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM=
github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
@@ -33,9 +33,8 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/labstack/echo/v4 v4.1.14 h1:h8XP66UfB3tUm+L3QPw7tmwAu3pJaA/nyfHPCcz46ic=
github.com/labstack/echo/v4 v4.1.14/go.mod h1:Q5KZ1vD3V5FEzjM79hjwVrC3ABr7F5IdM23bXQMRDGg=
github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k=
github.com/labstack/echo/v4 v4.7.2 h1:Kv2/p8OaQ+M6Ex4eGimg9b9e6icoxA42JSlOR3msKtI=
github.com/labstack/echo/v4 v4.7.2/go.mod h1:xkCDAdFCIf8jsFQ5NnbK7oqaF/yU1A1X20Ltm0OvSks=
github.com/labstack/gommon v0.3.1 h1:OomWaJXm7xR6L1HmEtGyQf26TEn7V6X88mktX9kee9o=
github.com/labstack/gommon v0.3.1/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM=
github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
@@ -43,13 +42,8 @@ github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN
github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-colorable v0.1.11 h1:nQ+aFkoE2TMGc0b68U2OKSexC+eq46+XwZzWXHRmPYs=
github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ=
github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
@@ -70,49 +64,43 @@ github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/swaggo/files v0.0.0-20210815190702-a29dd2bc99b2 h1:+iNTcqQJy0OZ5jk6a5NLib47eqXK8uYcPX+O4+cBpEM=
github.com/swaggo/files v0.0.0-20210815190702-a29dd2bc99b2/go.mod h1:lKJPbtWzJ9JhsTN1k1gZgleJWY/cqq0psdoMmaThG3w=
github.com/swaggo/swag v1.7.9 h1:6vCG5mm43ebDzGlZPMGYrYI4zKFfOr5kicQX8qjeDwc=
github.com/swaggo/swag v1.7.9/go.mod h1:gZ+TJ2w/Ve1RwQsA2IRoSOTidHz6DX+PIG8GWvbnoLU=
github.com/swaggo/swag v1.8.1 h1:JuARzFX1Z1njbCGz+ZytBR15TFJwF2Q7fu8puJHhQYI=
github.com/swaggo/swag v1.8.1/go.mod h1:ugemnJsPZm/kRwFUnzBlbHRd0JY9zE1M4F+uy2pAaPQ=
github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8=
github.com/valyala/fasttemplate v1.1.0/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8=
github.com/valyala/fasttemplate v1.2.1 h1:TVEnxayobAdVkhQfrfes2IzOB6o+z4roRkPF52WA1u4=
github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191227163750-53104e6ec876/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20220131195533-30dcbda58838 h1:71vQrMauZZhcTVK6KdYM+rklehEEwb3E+ZhaE5jrPrE=
golang.org/x/crypto v0.0.0-20220131195533-30dcbda58838/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 h1:kUhD7nTDoI3fVd9G4ORWrbV5NY0liEs/Jg2pv5f+bBA=
golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.5.1 h1:OJxoQ/rynoF0dcCdI7cLPktw/hR2cueqYfjm43oqK38=
golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 h1:kQgndtyPBW/JIYERgdxfwMYh3AVStj88WQTlNDi2a+o=
golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM=
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd h1:O7DYs+zxREGLKzKoMQrtrEacpb0ZVXA5rIwylE2Xchk=
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4 h1:HVyaeDAYux4pnY+D/SiwmLOR36ewZ4iGQIIrtnuCjFA=
golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -122,23 +110,23 @@ golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e h1:fLOSk5Q00efkSvAm+4xcoXD+RRmLmmulPn5I3Y9F2EM=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a h1:ppl5mZgokTT8uPkmYOyEUmPTr3ypaKkg5eFOGrAmxxE=
golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220422013727-9388b58f7150 h1:xHms4gcpe1YE7A3yIllJXP16CMAGuqwO2lX1mTyyRRc=
golang.org/x/sys v0.0.0-20220422013727-9388b58f7150/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo=
golang.org/x/tools v0.1.9 h1:j9KsMiaP1c3B0OTQGth0/k+miLGTgLsAFUCrF2vLcF8=
golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU=
golang.org/x/tools v0.1.10 h1:QjFRCZxdOhBJ/UNgnBZLbNV13DlbnK0quyivTnXJM20=
golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
@@ -152,7 +140,6 @@ gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776 h1:tQIYjPdBoyREyB9XMu+nnTclpTYkz2zFM+lzLJFO4gQ=
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -17,77 +17,88 @@ import (
type Config struct {
// The url pointing to API definition (normally swagger.json or swagger.yaml). Default is `mockedSwag.json`.
URL string
DeepLinking bool
DocExpansion string
DomID string
InstanceName string
DeepLinking bool
PersistAuthorization bool
}
// URL presents the url pointing to API definition (normally swagger.json or swagger.yaml).
func URL(url string) func(c *Config) {
func URL(url string) func(*Config) {
return func(c *Config) {
c.URL = url
}
}
// DeepLinking true, false.
func DeepLinking(deepLinking bool) func(c *Config) {
func DeepLinking(deepLinking bool) func(*Config) {
return func(c *Config) {
c.DeepLinking = deepLinking
}
}
// DocExpansion list, full, none.
func DocExpansion(docExpansion string) func(c *Config) {
func DocExpansion(docExpansion string) func(*Config) {
return func(c *Config) {
c.DocExpansion = docExpansion
}
}
// DomID #swagger-ui.
func DomID(domID string) func(c *Config) {
func DomID(domID string) func(*Config) {
return func(c *Config) {
c.DomID = domID
}
}
// InstanceName specified swag instance name
func InstanceName(instanceName string) func(c *Config) {
// InstanceName specified swag instance name.
func InstanceName(instanceName string) func(*Config) {
return func(c *Config) {
c.InstanceName = instanceName
}
}
// If set to true, it persists authorization data and it would not be lost on browser close/refresh
// Defaults to false
func PersistAuthorization(persistAuthorization bool) func(c *Config) {
// PersistAuthorization Persist authorization information over browser close/refresh.
// Defaults to false.
func PersistAuthorization(persistAuthorization bool) func(*Config) {
return func(c *Config) {
c.PersistAuthorization = persistAuthorization
}
}
func newConfig(configFns ...func(*Config)) *Config {
config := Config{
URL: "doc.json",
DocExpansion: "list",
DomID: "swagger-ui",
InstanceName: "swagger",
DeepLinking: true,
PersistAuthorization: false,
}
for _, fn := range configFns {
fn(&config)
}
if config.InstanceName == "" {
config.InstanceName = swag.Name
}
return &config
}
// WrapHandler wraps swaggerFiles.Handler and returns echo.HandlerFunc
var WrapHandler = EchoWrapHandler()
// EchoWrapHandler wraps `http.Handler` into `echo.HandlerFunc`.
func EchoWrapHandler(configFns ...func(c *Config)) echo.HandlerFunc {
func EchoWrapHandler(options ...func(*Config)) echo.HandlerFunc {
var once sync.Once
config := &Config{
URL: "doc.json",
DeepLinking: true,
DocExpansion: "list",
DomID: "#swagger-ui",
}
for _, configFn := range configFns {
configFn(config)
}
config := newConfig(options...)
// create a template with name
t := template.New("swagger_index.html")
index, _ := t.Parse(indexTemplate)
index, _ := template.New("swagger_index.html").Parse(indexTemplate)
var re = regexp.MustCompile(`^(.*/)([^?].*)?[?|.]*$`)
@@ -97,6 +108,10 @@ func EchoWrapHandler(configFns ...func(c *Config)) echo.HandlerFunc {
}
return func(c echo.Context) error {
if c.Request().Method != http.MethodGet {
return echo.NewHTTPError(http.StatusMethodNotAllowed, http.StatusText(http.StatusMethodNotAllowed))
}
matches := re.FindStringSubmatch(c.Request().RequestURI)
path := matches[2]
@@ -125,7 +140,7 @@ func EchoWrapHandler(configFns ...func(c *Config)) echo.HandlerFunc {
switch path {
case "":
c.Redirect(301, h.Prefix+"index.html")
_ = c.Redirect(http.StatusMovedPermanently, h.Prefix+"index.html")
case "index.html":
_ = index.Execute(c.Response().Writer, config)
case "doc.json":
@@ -212,7 +227,7 @@ const indexTemplate = `<!-- HTML for static distribution bundle build -->
</defs>
</svg>
<div id="swagger-ui"></div>
<div id="{{.DomID}}"></div>
<script src="./swagger-ui-bundle.js"> </script>
<script src="./swagger-ui-standalone-preset.js"> </script>
@@ -224,7 +239,7 @@ window.onload = function() {
deepLinking: {{.DeepLinking}},
docExpansion: "{{.DocExpansion}}",
persistAuthorization: {{.PersistAuthorization}},
dom_id: "{{.DomID}}",
dom_id: "#{{.DomID}}",
validatorUrl: null,
presets: [
SwaggerUIBundle.presets.apis,

View File

@@ -13,7 +13,7 @@ GOPATH:=$(shell $(GOCMD) env GOPATH)
u := $(if $(update),-u)
BINARY_NAME:=swag
PACKAGES:=$(shell $(GOLIST) github.com/swaggo/swag github.com/swaggo/swag/cmd/swag github.com/swaggo/swag/gen)
PACKAGES:=$(shell $(GOLIST) github.com/swaggo/swag github.com/swaggo/swag/cmd/swag github.com/swaggo/swag/gen github.com/swaggo/swag/format)
GOFILES:=$(shell find . -name "*.go" -type f)
export GO111MODULE := on
@@ -63,9 +63,9 @@ deps:
$(GOGET) golang.org/x/tools/go/loader
.PHONY: devel-deps
devel-deps:
devel-deps:
GO111MODULE=off $(GOGET) -v -u \
golang.org/x/lint/golint
golang.org/x/lint/golint
.PHONY: lint
lint: devel-deps
@@ -91,4 +91,4 @@ fmt-check:
.PHONY: view-covered
view-covered:
$(GOTEST) -coverprofile=cover.out $(TARGET)
$(GOCMD) tool cover -html=cover.out
$(GOCMD) tool cover -html=cover.out

View File

@@ -9,7 +9,7 @@
[![Go Report Card](https://goreportcard.com/badge/github.com/swaggo/swag)](https://goreportcard.com/report/github.com/swaggo/swag)
[![codebeat badge](https://codebeat.co/badges/71e2f5e5-9e6b-405d-baf9-7cc8b5037330)](https://codebeat.co/projects/github-com-swaggo-swag-master)
[![Go Doc](https://godoc.org/github.com/swaggo/swagg?status.svg)](https://godoc.org/github.com/swaggo/swag)
[![Backers on Open Collective](https://opencollective.com/swag/backers/badge.svg)](#backers)
[![Backers on Open Collective](https://opencollective.com/swag/backers/badge.svg)](#backers)
[![Sponsors on Open Collective](https://opencollective.com/swag/sponsors/badge.svg)](#sponsors) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fswaggo%2Fswag.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fswaggo%2Fswag?ref=badge_shield)
[![Release](https://img.shields.io/github/release/swaggo/swag.svg?style=flat-square)](https://github.com/swaggo/swag/releases)
@@ -30,9 +30,10 @@ Swag converts Go annotations to Swagger Documentation 2.0. We've created a varie
- [Descriptions over multiple lines](#descriptions-over-multiple-lines)
- [User defined structure with an array type](#user-defined-structure-with-an-array-type)
- [Model composition in response](#model-composition-in-response)
- [Add a headers in response](#add-a-headers-in-response)
- [Add a headers in response](#add-a-headers-in-response)
- [Use multiple path params](#use-multiple-path-params)
- [Example value of struct](#example-value-of-struct)
- [SchemaExample of body](#schemaexample-of-body)
- [Description of struct](#description-of-struct)
- [Use swaggertype tag to supported custom type](#use-swaggertype-tag-to-supported-custom-type)
- [Use global overrides to support a custom type](#use-global-overrides-to-support-a-custom-type)
@@ -192,7 +193,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/swaggo/files"
"github.com/swaggo/gin-swagger"
"./docs" // docs is generated by Swag CLI, you have to import it.
)
@@ -211,7 +212,7 @@ func main() {
docs.SwaggerInfo.Host = "petstore.swagger.io"
docs.SwaggerInfo.BasePath = "/v2"
docs.SwaggerInfo.Schemes = []string{"http", "https"}
r := gin.New()
// use ginSwagger middleware to serve the API docs
@@ -297,10 +298,10 @@ $ swag init
## The swag formatter
The Swag Comments can be automatically formatted, just like 'go fmt'.
The Swag Comments can be automatically formatted, just like 'go fmt'.
Find the result of formatting [here](https://github.com/swaggo/swag/tree/master/example/celler).
Usage:
Usage:
```shell
swag fmt
```
@@ -382,7 +383,7 @@ When a short string in your documentation is insufficient, or you need images, c
| annotation | description |
|-------------|----------------------------------------------------------------------------------------------------------------------------|
| description | A verbose explanation of the operation behavior. |
| description.markdown | A short description of the application. The description will be read from a file named like endpointname.md| // @description.file endpoint.description.markdown |
| description.markdown | A short description of the application. The description will be read from a file. E.g. `@description.markdown details` will load `details.md`| // @description.file endpoint.description.markdown |
| id | A unique string used to identify the operation. Must be unique among all API operations. |
| tags | A list of tags to each API operation that separated by commas. |
| summary | A short summary of what the operation does. |
@@ -443,21 +444,21 @@ Besides that, `swag` also accepts aliases for some MIME Types as follows:
| annotation | description | parameters | example |
|------------|-------------|------------|---------|
| securitydefinitions.basic | [Basic](https://swagger.io/docs/specification/2-0/authentication/basic-authentication/) auth. | | // @securityDefinitions.basic BasicAuth |
| securitydefinitions.apikey | [API key](https://swagger.io/docs/specification/2-0/authentication/api-keys/) auth. | in, name | // @securityDefinitions.apikey ApiKeyAuth |
| securitydefinitions.oauth2.application | [OAuth2 application](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, scope | // @securitydefinitions.oauth2.application OAuth2Application |
| securitydefinitions.oauth2.implicit | [OAuth2 implicit](https://swagger.io/docs/specification/authentication/oauth2/) auth. | authorizationUrl, scope | // @securitydefinitions.oauth2.implicit OAuth2Implicit |
| securitydefinitions.oauth2.password | [OAuth2 password](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, scope | // @securitydefinitions.oauth2.password OAuth2Password |
| securitydefinitions.oauth2.accessCode | [OAuth2 access code](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, authorizationUrl, scope | // @securitydefinitions.oauth2.accessCode OAuth2AccessCode |
| securitydefinitions.apikey | [API key](https://swagger.io/docs/specification/2-0/authentication/api-keys/) auth. | in, name, description | // @securityDefinitions.apikey ApiKeyAuth |
| securitydefinitions.oauth2.application | [OAuth2 application](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, scope, description | // @securitydefinitions.oauth2.application OAuth2Application |
| securitydefinitions.oauth2.implicit | [OAuth2 implicit](https://swagger.io/docs/specification/authentication/oauth2/) auth. | authorizationUrl, scope, description | // @securitydefinitions.oauth2.implicit OAuth2Implicit |
| securitydefinitions.oauth2.password | [OAuth2 password](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, scope, description | // @securitydefinitions.oauth2.password OAuth2Password |
| securitydefinitions.oauth2.accessCode | [OAuth2 access code](https://swagger.io/docs/specification/authentication/oauth2/) auth. | tokenUrl, authorizationUrl, scope, description | // @securitydefinitions.oauth2.accessCode OAuth2AccessCode |
| parameters annotation | example |
|-----------------------|----------------------------------------------------------|
| in | // @in header |
| name | // @name Authorization |
| tokenUrl | // @tokenUrl https://example.com/oauth/token |
| authorizationurl | // @authorizationurl https://example.com/oauth/authorize |
| scope.hoge | // @scope.write Grants write access |
| parameters annotation | example |
|---------------------------------|-------------------------------------------------------------------------|
| in | // @in header |
| name | // @name Authorization |
| tokenUrl | // @tokenUrl https://example.com/oauth/token |
| authorizationurl | // @authorizationurl https://example.com/oauth/authorize |
| scope.hoge | // @scope.write Grants write access |
| description | // @description OAuth protects our entity endpoints |
## Attribute
@@ -468,6 +469,7 @@ Besides that, `swag` also accepts aliases for some MIME Types as follows:
// @Param string query string false "string valid" minlength(5) maxlength(10)
// @Param int query int false "int valid" minimum(1) maximum(10)
// @Param default query string false "string default" default(A)
// @Param example query string false "string example" example(string)
// @Param collection query []string false "string collection" collectionFormat(multi)
// @Param extensions query []string false "string collection" extensions(x-example=test,x-nullable)
```
@@ -476,7 +478,7 @@ It also works for the struct fields:
```go
type Foo struct {
Bar string `minLength:"4" maxLength:"16"`
Bar string `minLength:"4" maxLength:"16" example:"random string"`
Baz int `minimum:"10" maximum:"20" default:"15"`
Qux []string `enums:"foo,bar,baz"`
}
@@ -486,7 +488,7 @@ type Foo struct {
Field Name | Type | Description
---|:---:|---
<a name="validate"></a>validate | `string` | Determines the validation for the parameter. Possible values are: `required`.
<a name="validate"></a>validate | `string` | Determines the validation for the parameter. Possible values are: `required`.
<a name="parameterDefault"></a>default | * | Declares the value of the parameter that the server will use if none is provided, for example a "count" to control the number of results per page might default to 100 if not supplied by the client in the request. (Note: "default" has no meaning for required parameters.) See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2. Unlike JSON Schema this value MUST conform to the defined [`type`](#parameterType) for this parameter.
<a name="parameterMaximum"></a>maximum | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2.
<a name="parameterMinimum"></a>minimum | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3.
@@ -496,6 +498,7 @@ Field Name | Type | Description
<a name="parameterEnums"></a>enums | [\*] | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1.
<a name="parameterFormat"></a>format | `string` | The extending format for the previously mentioned [`type`](#parameterType). See [Data Type Formats](https://swagger.io/specification/v2/#dataTypeFormat) for further details.
<a name="parameterCollectionFormat"></a>collectionFormat | `string` |Determines the format of the array if type array is used. Possible values are: <ul><li>`csv` - comma separated values `foo,bar`. <li>`ssv` - space separated values `foo bar`. <li>`tsv` - tab separated values `foo\tbar`. <li>`pipes` - pipe separated values <code>foo&#124;bar</code>. <li>`multi` - corresponds to multiple parameter instances instead of multiple values for a single instance `foo=bar&foo=baz`. This is valid only for parameters [`in`](#parameterIn) "query" or "formData". </ul> Default value is `csv`.
<a name="parameterExample"></a>example | * | Declares the example for the parameter value
<a name="parameterExtensions"></a>extensions | `string` | Add extension to parameters.
### Future
@@ -511,7 +514,7 @@ Field Name | Type | Description
### Descriptions over multiple lines
You can add descriptions spanning multiple lines in either the general api description or routes definitions like so:
You can add descriptions spanning multiple lines in either the general api description or routes definitions like so:
```go
// @description This is the first line
@@ -560,7 +563,7 @@ type Order struct { //in `proto` package
@success 200 {object} jsonresult.JSONResult{data=[]string} "desc"
```
- overriding multiple fields. field will be added if not exists
- overriding multiple fields. field will be added if not exists
```go
@success 200 {object} jsonresult.JSONResult{data1=string,data2=[]string,data3=proto.Order,data4=[]proto.Order} "desc"
```
@@ -613,6 +616,12 @@ type Account struct {
}
```
### SchemaExample of body
```go
// @Param email body string true "message/rfc822" SchemaExample(Subject: Testmail\r\n\r\nBody Message\r\n)
```
### Description of struct
```go
@@ -744,7 +753,7 @@ Rendered:
"id": "integer"
}
```
### Use swaggerignore tag to exclude a field
@@ -813,6 +822,14 @@ Make it AND condition
// @Security OAuth2Application[write, admin]
```
Make it OR condition
```go
// @Security ApiKeyAuth || firebase
// @Security OAuth2Application[write, admin] || APIKeyAuth
```
### Add a description for enum items
```go

View File

@@ -348,8 +348,8 @@ swag fmt -d ./ --exclude ./internal
| license.url | 用于API的许可证的URL。 必须采用网址格式。 | // @license.url http://www.apache.org/licenses/LICENSE-2.0.html |
| host | 运行API的主机主机名或IP地址。 | // @host localhost:8080 |
| BasePath | 运行API的基本路径。 | // @BasePath /api/v1 |
| accept | API 可以使用的 MIME 类型列表。 请注意Accept 仅影响具有请求正文的操作,例如 POST、PUT 和 PATCH。 值必须如“[Mime类型](#mime-types)”中所述。 | // @accept json |
| produce | API可以生成的MIME类型的列表。值必须如“[Mime类型](#mime-types)”中所述。 | // @produce json |
| accept | API 可以使用的 MIME 类型列表。 请注意Accept 仅影响具有请求正文的操作,例如 POST、PUT 和 PATCH。 值必须如“[Mime类型](#mime类型)”中所述。 | // @accept json |
| produce | API可以生成的MIME类型的列表。值必须如“[Mime类型](#mime类型)”中所述。 | // @produce json |
| query.collection.format | 请求URI query里数组参数的默认格式csvmultipipestsvssv。 如果未设置则默认为csv。 | // @query.collection.format multi |
| schemes | 用空格分隔的请求的传输协议。 | // @schemes http https |
| x-name | 扩展的键必须以x-开头并且只能使用json值 | // @x-example-key {"key": "value"} |
@@ -377,8 +377,8 @@ Example [celler/controller](https://github.com/swaggo/swag/tree/master/example/c
| id | 用于标识操作的唯一字符串。在所有API操作中必须唯一。 |
| tags | 每个API操作的标签列表以逗号分隔。 |
| summary | 该操作的简短摘要。 |
| accept | API 可以使用的 MIME 类型列表。 请注意Accept 仅影响具有请求正文的操作,例如 POST、PUT 和 PATCH。 值必须如“[Mime类型](#mime-types)”中所述。 |
| produce | API可以生成的MIME类型的列表。值必须如“[Mime类型](#mime-types)”中所述。 |
| accept | API 可以使用的 MIME 类型列表。 请注意Accept 仅影响具有请求正文的操作,例如 POST、PUT 和 PATCH。 值必须如“[Mime类型](#mime类型)”中所述。 |
| produce | API可以生成的MIME类型的列表。值必须如“[Mime类型](#mime类型)”中所述。 |
| param | 用空格分隔的参数。`param name`,`param type`,`data type`,`is mandatory?`,`comment` `attribute(optional)` |
| security | 每个API操作的[安全性](#安全性)。 |
| success | 以空格分隔的成功响应。`return code`,`{param type}`,`data type`,`comment` |

View File

@@ -10,10 +10,17 @@ import (
"sync"
"unicode"
"github.com/go-openapi/jsonreference"
"github.com/go-openapi/spec"
)
var _ FieldParser = &tagBaseFieldParser{}
var _ FieldParser = &tagBaseFieldParser{p: nil, field: nil, tag: ""}
const (
requiredLabel = "required"
swaggerTypeTag = "swaggertype"
swaggerIgnoreTag = "swaggerignore"
)
type tagBaseFieldParser struct {
p *Parser
@@ -22,46 +29,47 @@ type tagBaseFieldParser struct {
}
func newTagBaseFieldParser(p *Parser, field *ast.Field) FieldParser {
ps := &tagBaseFieldParser{
fieldParser := tagBaseFieldParser{
p: p,
field: field,
tag: "",
}
if ps.field.Tag != nil {
ps.tag = reflect.StructTag(strings.Replace(field.Tag.Value, "`", "", -1))
if fieldParser.field.Tag != nil {
fieldParser.tag = reflect.StructTag(strings.ReplaceAll(field.Tag.Value, "`", ""))
}
return ps
return &fieldParser
}
func (ps *tagBaseFieldParser) ShouldSkip() (bool, error) {
func (ps *tagBaseFieldParser) ShouldSkip() bool {
// Skip non-exported fields.
if !ast.IsExported(ps.field.Names[0].Name) {
return true, nil
return true
}
if ps.field.Tag == nil {
return false, nil
return false
}
ignoreTag := ps.tag.Get("swaggerignore")
ignoreTag := ps.tag.Get(swaggerIgnoreTag)
if strings.EqualFold(ignoreTag, "true") {
return true, nil
return true
}
// json:"tag,hoge"
name := strings.TrimSpace(strings.Split(ps.tag.Get("json"), ",")[0])
name := strings.TrimSpace(strings.Split(ps.tag.Get(jsonTag), ",")[0])
if name == "-" {
return true, nil
return true
}
return false, nil
return false
}
func (ps *tagBaseFieldParser) FieldName() (string, error) {
var name string
if ps.field.Tag != nil {
// json:"tag,hoge"
name = strings.TrimSpace(strings.Split(ps.tag.Get("json"), ",")[0])
name = strings.TrimSpace(strings.Split(ps.tag.Get(jsonTag), ",")[0])
if name != "" {
return name, nil
@@ -79,34 +87,40 @@ func (ps *tagBaseFieldParser) FieldName() (string, error) {
}
func toSnakeCase(in string) string {
runes := []rune(in)
length := len(runes)
var (
runes = []rune(in)
length = len(runes)
out []rune
)
var out []rune
for i := 0; i < length; i++ {
if i > 0 && unicode.IsUpper(runes[i]) &&
((i+1 < length && unicode.IsLower(runes[i+1])) || unicode.IsLower(runes[i-1])) {
for idx := 0; idx < length; idx++ {
if idx > 0 && unicode.IsUpper(runes[idx]) &&
((idx+1 < length && unicode.IsLower(runes[idx+1])) || unicode.IsLower(runes[idx-1])) {
out = append(out, '_')
}
out = append(out, unicode.ToLower(runes[i]))
out = append(out, unicode.ToLower(runes[idx]))
}
return string(out)
}
func toLowerCamelCase(in string) string {
runes := []rune(in)
var flag bool
var out []rune
flag := false
out := make([]rune, len(in))
runes := []rune(in)
for i, curr := range runes {
if (i == 0 && unicode.IsUpper(curr)) || (flag && unicode.IsUpper(curr)) {
out = append(out, unicode.ToLower(curr))
out[i] = unicode.ToLower(curr)
flag = true
} else {
out = append(out, curr)
flag = false
continue
}
out[i] = curr
flag = false
}
return string(out)
@@ -117,7 +131,7 @@ func (ps *tagBaseFieldParser) CustomSchema() (*spec.Schema, error) {
return nil, nil
}
typeTag := ps.tag.Get("swaggertype")
typeTag := ps.tag.Get(swaggerTypeTag)
if typeTag != "" {
return BuildCustomSchema(strings.Split(typeTag, ","))
}
@@ -126,7 +140,6 @@ func (ps *tagBaseFieldParser) CustomSchema() (*spec.Schema, error) {
}
type structField struct {
desc string
schemaType string
arrayType string
formatType string
@@ -138,11 +151,8 @@ type structField struct {
maxItems *int64
minItems *int64
exampleValue interface{}
defaultValue interface{}
extensions map[string]interface{}
enums []interface{}
enumVarNames []interface{}
readOnly bool
unique bool
}
@@ -155,32 +165,42 @@ func splitNotWrapped(s string, sep rune) []string {
'{': '}',
}
result := make([]string, 0)
current := ""
var openCount = 0
var openChar rune
var (
result = make([]string, 0)
current = strings.Builder{}
openCount = 0
openChar rune
)
for _, char := range s {
if openChar == 0 && openCloseMap[char] != 0 {
switch {
case openChar == 0 && openCloseMap[char] != 0:
openChar = char
openCount++
current += string(char)
} else if char == openChar {
current.WriteRune(char)
case char == openChar:
openCount++
current = current + string(char)
} else if openCount > 0 && char == openCloseMap[openChar] {
current.WriteRune(char)
case openCount > 0 && char == openCloseMap[openChar]:
openCount--
current += string(char)
} else if openCount == 0 && char == sep {
result = append(result, current)
current.WriteRune(char)
case openCount == 0 && char == sep:
result = append(result, current.String())
openChar = 0
current = ""
} else {
current += string(char)
current = strings.Builder{}
default:
current.WriteRune(char)
}
}
if current != "" {
result = append(result, current)
if current.String() != "" {
result = append(result, current.String())
}
return result
@@ -196,157 +216,110 @@ func (ps *tagBaseFieldParser) ComplementSchema(schema *spec.Schema) error {
if ps.field.Doc != nil {
schema.Description = strings.TrimSpace(ps.field.Doc.Text())
}
if schema.Description == "" && ps.field.Comment != nil {
schema.Description = strings.TrimSpace(ps.field.Comment.Text())
}
return nil
}
structField := &structField{
field := &structField{
schemaType: types[0],
formatType: ps.tag.Get(formatTag),
readOnly: ps.tag.Get(readOnlyTag) == "true",
}
if len(types) > 1 && (types[0] == ARRAY || types[0] == OBJECT) {
structField.arrayType = types[1]
field.arrayType = types[1]
}
if ps.field.Doc != nil {
structField.desc = strings.TrimSpace(ps.field.Doc.Text())
}
if structField.desc == "" && ps.field.Comment != nil {
structField.desc = strings.TrimSpace(ps.field.Comment.Text())
jsonTagValue := ps.tag.Get(jsonTag)
bindingTagValue := ps.tag.Get(bindingTag)
if bindingTagValue != "" {
parseValidTags(bindingTagValue, field)
}
jsonTag := ps.tag.Get(jsonTag)
// json:"name,string" or json:",string"
exampleTag, ok := ps.tag.Lookup(exampleTag)
if ok {
structField.exampleValue = exampleTag
if !strings.Contains(jsonTag, ",string") {
example, err := defineTypeOfExample(structField.schemaType, structField.arrayType, exampleTag)
if err != nil {
return err
}
structField.exampleValue = example
}
validateTagValue := ps.tag.Get(validateTag)
if validateTagValue != "" {
parseValidTags(validateTagValue, field)
}
bindingTag := ps.tag.Get(bindingTag)
if bindingTag != "" {
ps.parseValidTags(bindingTag, structField)
}
validateTag := ps.tag.Get(validateTag)
if validateTag != "" {
ps.parseValidTags(validateTag, structField)
}
extensionsTag := ps.tag.Get(extensionsTag)
if extensionsTag != "" {
structField.extensions = map[string]interface{}{}
for _, val := range splitNotWrapped(extensionsTag, ',') {
parts := strings.SplitN(val, "=", 2)
if len(parts) == 2 {
structField.extensions[parts[0]] = parts[1]
} else {
if len(parts[0]) > 0 && string(parts[0][0]) == "!" {
structField.extensions[parts[0][1:]] = false
} else {
structField.extensions[parts[0]] = true
}
}
}
}
enumsTag := ps.tag.Get(enumsTag)
if enumsTag != "" {
enumType := structField.schemaType
if structField.schemaType == ARRAY {
enumType = structField.arrayType
}
structField.enums = nil
for _, e := range strings.Split(enumsTag, ",") {
value, err := defineType(enumType, e)
if err != nil {
return err
}
structField.enums = append(structField.enums, value)
}
}
varnamesTag := ps.tag.Get("x-enum-varnames")
if varnamesTag != "" {
if structField.extensions == nil {
structField.extensions = map[string]interface{}{}
}
varNames := strings.Split(varnamesTag, ",")
if len(varNames) != len(structField.enums) {
return fmt.Errorf("invalid count of x-enum-varnames. expected %d, got %d", len(structField.enums), len(varNames))
}
structField.enumVarNames = nil
for _, v := range varNames {
structField.enumVarNames = append(structField.enumVarNames, v)
}
structField.extensions["x-enum-varnames"] = structField.enumVarNames
}
defaultTag := ps.tag.Get(defaultTag)
if defaultTag != "" {
value, err := defineType(structField.schemaType, defaultTag)
enumsTagValue := ps.tag.Get(enumsTag)
if enumsTagValue != "" {
err := parseEnumTags(enumsTagValue, field)
if err != nil {
return err
}
structField.defaultValue = value
}
if IsNumericType(structField.schemaType) || IsNumericType(structField.arrayType) {
if IsNumericType(field.schemaType) || IsNumericType(field.arrayType) {
maximum, err := getFloatTag(ps.tag, maximumTag)
if err != nil {
return err
}
if maximum != nil {
structField.maximum = maximum
field.maximum = maximum
}
minimum, err := getFloatTag(ps.tag, minimumTag)
if err != nil {
return err
}
if minimum != nil {
structField.minimum = minimum
field.minimum = minimum
}
multipleOf, err := getFloatTag(ps.tag, multipleOfTag)
if err != nil {
return err
}
if multipleOf != nil {
structField.multipleOf = multipleOf
field.multipleOf = multipleOf
}
}
if structField.schemaType == STRING || structField.arrayType == STRING {
maxLength, err := getIntTag(ps.tag, "maxLength")
if field.schemaType == STRING || field.arrayType == STRING {
maxLength, err := getIntTag(ps.tag, maxLengthTag)
if err != nil {
return err
}
if maxLength != nil {
structField.maxLength = maxLength
}
minLength, err := getIntTag(ps.tag, "minLength")
if maxLength != nil {
field.maxLength = maxLength
}
minLength, err := getIntTag(ps.tag, minLengthTag)
if err != nil {
return err
}
if minLength != nil {
structField.minLength = minLength
field.minLength = minLength
}
}
// json:"name,string" or json:",string"
exampleTagValue, ok := ps.tag.Lookup(exampleTag)
if ok {
field.exampleValue = exampleTagValue
if !strings.Contains(jsonTagValue, ",string") {
example, err := defineTypeOfExample(field.schemaType, field.arrayType, exampleTagValue)
if err != nil {
return err
}
field.exampleValue = example
}
}
// perform this after setting everything else (min, max, etc...)
if strings.Contains(jsonTag, ",string") { // @encoding/json: "It applies only to fields of string, floating point, integer, or boolean types."
if strings.Contains(jsonTagValue, ",string") {
// @encoding/json: "It applies only to fields of string, floating point, integer, or boolean types."
defaultValues := map[string]string{
// Zero Values as string
STRING: "",
@@ -355,51 +328,103 @@ func (ps *tagBaseFieldParser) ComplementSchema(schema *spec.Schema) error {
NUMBER: "0",
}
defaultValue, ok := defaultValues[structField.schemaType]
defaultValue, ok := defaultValues[field.schemaType]
if ok {
structField.schemaType = STRING
field.schemaType = STRING
*schema = *PrimitiveSchema(field.schemaType)
if structField.exampleValue == nil {
if field.exampleValue == nil {
// if exampleValue is not defined by the user,
// we will force an example with a correct value
// (eg: int->"0", bool:"false")
structField.exampleValue = defaultValue
field.exampleValue = defaultValue
}
}
}
if structField.schemaType == STRING && types[0] != STRING {
*schema = *PrimitiveSchema(structField.schemaType)
if ps.field.Doc != nil {
schema.Description = strings.TrimSpace(ps.field.Doc.Text())
}
schema.Description = structField.desc
schema.ReadOnly = structField.readOnly
if schema.Description == "" && ps.field.Comment != nil {
schema.Description = strings.TrimSpace(ps.field.Comment.Text())
}
schema.ReadOnly = ps.tag.Get(readOnlyTag) == "true"
if !reflect.ValueOf(schema.Ref).IsZero() && schema.ReadOnly {
schema.AllOf = []spec.Schema{*spec.RefSchema(schema.Ref.String())}
schema.Ref = spec.Ref{} // clear out existing ref
schema.Ref = spec.Ref{
Ref: jsonreference.Ref{
HasFullURL: false,
HasURLPathOnly: false,
HasFragmentOnly: false,
HasFileScheme: false,
HasFullFilePath: false,
},
} // clear out existing ref
}
schema.Default = structField.defaultValue
schema.Example = structField.exampleValue
if structField.schemaType != ARRAY {
schema.Format = structField.formatType
defaultTagValue := ps.tag.Get(defaultTag)
if defaultTagValue != "" {
value, err := defineType(field.schemaType, defaultTagValue)
if err != nil {
return err
}
schema.Default = value
}
schema.Extensions = structField.extensions
schema.Example = field.exampleValue
if field.schemaType != ARRAY {
schema.Format = field.formatType
}
extensionsTagValue := ps.tag.Get(extensionsTag)
if extensionsTagValue != "" {
schema.Extensions = setExtensionParam(extensionsTagValue)
}
varNamesTag := ps.tag.Get("x-enum-varnames")
if varNamesTag != "" {
if schema.Extensions == nil {
schema.Extensions = map[string]interface{}{}
}
varNames := strings.Split(varNamesTag, ",")
if len(varNames) != len(field.enums) {
return fmt.Errorf("invalid count of x-enum-varnames. expected %d, got %d", len(field.enums), len(varNames))
}
field.enumVarNames = nil
for _, v := range varNames {
field.enumVarNames = append(field.enumVarNames, v)
}
schema.Extensions["x-enum-varnames"] = field.enumVarNames
}
eleSchema := schema
if structField.schemaType == ARRAY {
if field.schemaType == ARRAY {
// For Array only
schema.MaxItems = structField.maxItems
schema.MinItems = structField.minItems
schema.UniqueItems = structField.unique
schema.MaxItems = field.maxItems
schema.MinItems = field.minItems
schema.UniqueItems = field.unique
eleSchema = schema.Items.Schema
eleSchema.Format = structField.formatType
eleSchema.Format = field.formatType
}
eleSchema.Maximum = structField.maximum
eleSchema.Minimum = structField.minimum
eleSchema.MultipleOf = structField.multipleOf
eleSchema.MaxLength = structField.maxLength
eleSchema.MinLength = structField.minLength
eleSchema.Enum = structField.enums
eleSchema.Maximum = field.maximum
eleSchema.Minimum = field.minimum
eleSchema.MultipleOf = field.multipleOf
eleSchema.MaxLength = field.maxLength
eleSchema.MinLength = field.minLength
eleSchema.Enum = field.enums
return nil
}
@@ -439,7 +464,7 @@ func (ps *tagBaseFieldParser) IsRequired() (bool, error) {
bindingTag := ps.tag.Get(bindingTag)
if bindingTag != "" {
for _, val := range strings.Split(bindingTag, ",") {
if val == "required" {
if val == requiredLabel {
return true, nil
}
}
@@ -448,7 +473,7 @@ func (ps *tagBaseFieldParser) IsRequired() (bool, error) {
validateTag := ps.tag.Get(validateTag)
if validateTag != "" {
for _, val := range strings.Split(validateTag, ",") {
if val == "required" {
if val == requiredLabel {
return true, nil
}
}
@@ -457,27 +482,24 @@ func (ps *tagBaseFieldParser) IsRequired() (bool, error) {
return false, nil
}
func (ps *tagBaseFieldParser) parseValidTags(validTag string, sf *structField) {
func parseValidTags(validTag string, sf *structField) {
// `validate:"required,max=10,min=1"`
// ps. required checked by IsRequired().
for _, val := range strings.Split(validTag, ",") {
var (
valKey string
valValue string
keyVal = strings.Split(val, "=")
)
kv := strings.Split(val, "=")
switch len(kv) {
switch len(keyVal) {
case 1:
valKey = kv[0]
case 2:
valKey = kv[0]
valValue = kv[1]
valValue = strings.ReplaceAll(strings.ReplaceAll(keyVal[1], utf8HexComma, ","), utf8Pipe, "|")
default:
continue
}
valValue = strings.Replace(strings.Replace(valValue, utf8HexComma, ",", -1), utf8Pipe, "|", -1)
switch valKey {
switch keyVal[0] {
case "max", "lte":
sf.setMax(valValue)
case "min", "gte":
@@ -497,6 +519,26 @@ func (ps *tagBaseFieldParser) parseValidTags(validTag string, sf *structField) {
}
}
func parseEnumTags(enumTag string, field *structField) error {
enumType := field.schemaType
if field.schemaType == ARRAY {
enumType = field.arrayType
}
field.enums = nil
for _, e := range strings.Split(enumTag, ",") {
value, err := defineType(enumType, e)
if err != nil {
return err
}
field.enums = append(field.enums, value)
}
return nil
}
func (sf *structField) setOneOf(valValue string) {
if len(sf.enums) != 0 {
return
@@ -513,6 +555,7 @@ func (sf *structField) setOneOf(valValue string) {
if err != nil {
continue
}
sf.enums = append(sf.enums, value)
}
}
@@ -522,6 +565,7 @@ func (sf *structField) setMin(valValue string) {
if err != nil {
return
}
switch sf.schemaType {
case INTEGER, NUMBER:
sf.minimum = &value
@@ -539,6 +583,7 @@ func (sf *structField) setMax(valValue string) {
if err != nil {
return
}
switch sf.schemaType {
case INTEGER, NUMBER:
sf.maximum = &value
@@ -558,25 +603,30 @@ const (
// These code copy from
// https://github.com/go-playground/validator/blob/d4271985b44b735c6f76abc7a06532ee997f9476/baked_in.go#L207
// ---
// ---.
var oneofValsCache = map[string][]string{}
var oneofValsCacheRWLock = sync.RWMutex{}
var splitParamsRegex = regexp.MustCompile(`'[^']*'|\S+`)
func parseOneOfParam2(s string) []string {
func parseOneOfParam2(param string) []string {
oneofValsCacheRWLock.RLock()
values, ok := oneofValsCache[s]
values, ok := oneofValsCache[param]
oneofValsCacheRWLock.RUnlock()
if !ok {
oneofValsCacheRWLock.Lock()
values = splitParamsRegex.FindAllString(s, -1)
values = splitParamsRegex.FindAllString(param, -1)
for i := 0; i < len(values); i++ {
values[i] = strings.Replace(values[i], "'", "", -1)
values[i] = strings.ReplaceAll(values[i], "'", "")
}
oneofValsCache[s] = values
oneofValsCache[param] = values
oneofValsCacheRWLock.Unlock()
}
return values
}
// ---
// ---.

View File

@@ -1,326 +0,0 @@
package swag
import (
"bytes"
"crypto/md5"
"fmt"
"go/ast"
goparser "go/parser"
"go/token"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"text/tabwriter"
)
const splitTag = "&*"
// Formater implements a formater for Go source files.
type Formater struct {
// debugging output goes here
debug Debugger
// excludes excludes dirs and files in SearchDir
excludes map[string]struct{}
mainFile string
}
// NewFormater create a new formater instance.
func NewFormater() *Formater {
formater := &Formater{
debug: log.New(os.Stdout, "", log.LstdFlags),
excludes: make(map[string]struct{}),
}
return formater
}
// FormatAPI format the swag comment.
func (f *Formater) FormatAPI(searchDir, excludeDir, mainFile string) error {
searchDirs := strings.Split(searchDir, ",")
for _, searchDir := range searchDirs {
if _, err := os.Stat(searchDir); os.IsNotExist(err) {
return fmt.Errorf("dir: %s does not exist", searchDir)
}
}
for _, fi := range strings.Split(excludeDir, ",") {
fi = strings.TrimSpace(fi)
if fi != "" {
fi = filepath.Clean(fi)
f.excludes[fi] = struct{}{}
}
}
// parse main.go
absMainAPIFilePath, err := filepath.Abs(filepath.Join(searchDirs[0], mainFile))
if err != nil {
return err
}
err = f.FormatMain(absMainAPIFilePath)
if err != nil {
return err
}
f.mainFile = mainFile
err = f.formatMultiSearchDir(searchDirs)
if err != nil {
return err
}
return nil
}
func (f *Formater) formatMultiSearchDir(searchDirs []string) error {
for _, searchDir := range searchDirs {
f.debug.Printf("Format API Info, search dir:%s", searchDir)
err := filepath.Walk(searchDir, f.visit)
if err != nil {
return err
}
}
return nil
}
func (f *Formater) visit(path string, fileInfo os.FileInfo, err error) error {
if err := walkWith(f.excludes, false)(path, fileInfo); err != nil {
return err
} else if fileInfo.IsDir() {
// skip if file is folder
return nil
}
if strings.HasSuffix(strings.ToLower(path), "_test.go") || filepath.Ext(path) != ".go" {
// skip if file not has suffix "*.go"
return nil
}
if strings.HasSuffix(strings.ToLower(path), f.mainFile) {
// skip main file
return nil
}
err = f.FormatFile(path)
if err != nil {
return fmt.Errorf("ParseFile error:%+v", err)
}
return nil
}
// FormatMain format the main.go comment.
func (f *Formater) FormatMain(mainFilepath string) error {
fileSet := token.NewFileSet()
astFile, err := goparser.ParseFile(fileSet, mainFilepath, nil, goparser.ParseComments)
if err != nil {
return fmt.Errorf("cannot format file, err: %w path : %s ", err, mainFilepath)
}
var (
formatedComments = bytes.Buffer{}
// CommentCache
oldCommentsMap = make(map[string]string)
)
if astFile.Comments != nil {
for _, comment := range astFile.Comments {
formatFuncDoc(comment.List, &formatedComments, oldCommentsMap)
}
}
return writeFormatedComments(mainFilepath, formatedComments, oldCommentsMap)
}
// FormatFile format the swag comment in go function.
func (f *Formater) FormatFile(filepath string) error {
fileSet := token.NewFileSet()
astFile, err := goparser.ParseFile(fileSet, filepath, nil, goparser.ParseComments)
if err != nil {
return fmt.Errorf("cannot format file, err: %w path : %s ", err, filepath)
}
var (
formatedComments = bytes.Buffer{}
// CommentCache
oldCommentsMap = make(map[string]string)
)
for _, astDescription := range astFile.Decls {
astDeclaration, ok := astDescription.(*ast.FuncDecl)
if ok && astDeclaration.Doc != nil && astDeclaration.Doc.List != nil {
formatFuncDoc(astDeclaration.Doc.List, &formatedComments, oldCommentsMap)
}
}
return writeFormatedComments(filepath, formatedComments, oldCommentsMap)
}
func writeFormatedComments(filepath string, formatedComments bytes.Buffer, oldCommentsMap map[string]string) error {
// Replace the file
// Read the file
srcBytes, err := ioutil.ReadFile(filepath)
if err != nil {
return fmt.Errorf("cannot open file, err: %w path : %s ", err, filepath)
}
replaceSrc := string(srcBytes)
newComments := strings.Split(formatedComments.String(), "\n")
for _, e := range newComments {
commentSplit := strings.Split(e, splitTag)
if len(commentSplit) == 2 {
commentHash, commentContent := commentSplit[0], commentSplit[1]
if !isBlankComment(commentContent) {
replaceSrc = strings.Replace(replaceSrc, oldCommentsMap[commentHash], commentContent, 1)
}
}
}
return writeBack(filepath, []byte(replaceSrc), srcBytes)
}
func formatFuncDoc(commentList []*ast.Comment, formatedComments io.Writer, oldCommentsMap map[string]string) {
tabw := tabwriter.NewWriter(formatedComments, 0, 0, 2, ' ', 0)
for _, comment := range commentList {
commentLine := comment.Text
if isSwagComment(commentLine) || isBlankComment(commentLine) {
cmd5 := fmt.Sprintf("%x", md5.Sum([]byte(commentLine)))
// Find the separator and replace to \t
c := separatorFinder(commentLine, '\t')
oldCommentsMap[cmd5] = commentLine
// md5 + splitTag + srcCommentLine
// eg. xxx&*@Description get struct array
_, _ = fmt.Fprintln(tabw, cmd5+splitTag+c)
}
}
// format by tabwriter
_ = tabw.Flush()
}
// Check of @Param @Success @Failure @Response @Header
var specialTagForSplit = map[string]byte{
paramAttr: 1,
successAttr: 1,
failureAttr: 1,
responseAttr: 1,
headerAttr: 1,
}
var skipChar = map[byte]byte{
'"': 1,
'(': 1,
'{': 1,
'[': 1,
}
var skipCharEnd = map[byte]byte{
'"': 1,
')': 1,
'}': 1,
']': 1,
}
func separatorFinder(comment string, rp byte) string {
commentBytes := []byte(comment)
commentLine := strings.TrimSpace(strings.TrimLeft(comment, "/"))
if len(commentLine) == 0 {
return ""
}
attribute := strings.Fields(commentLine)[0]
attrLen := strings.Index(comment, attribute) + len(attribute)
attribute = strings.ToLower(attribute)
var i = attrLen
if _, ok := specialTagForSplit[attribute]; ok {
var skipFlag bool
for ; i < len(commentBytes); i++ {
if !skipFlag && commentBytes[i] == ' ' {
j := i
for j < len(commentBytes) && commentBytes[j] == ' ' {
j++
}
commentBytes = replaceRange(commentBytes, i, j, rp)
}
if _, ok := skipChar[commentBytes[i]]; ok && !skipFlag {
skipFlag = true
} else if _, ok := skipCharEnd[commentBytes[i]]; ok && skipFlag {
skipFlag = false
}
}
} else {
for i < len(commentBytes) && commentBytes[i] == ' ' {
i++
}
if i >= len(commentBytes) {
return comment
}
commentBytes = replaceRange(commentBytes, attrLen, i, rp)
}
return string(commentBytes)
}
func replaceRange(s []byte, start, end int, new byte) []byte {
if start > end || end < 1 {
return s
}
if end > len(s) {
end = len(s)
}
s = append(s[:start], s[end-1:]...)
s[start] = new
return s
}
var swagCommentExpression = regexp.MustCompile("@[A-z]+")
func isSwagComment(comment string) bool {
return swagCommentExpression.MatchString(strings.ToLower(comment))
}
func isBlankComment(comment string) bool {
lc := strings.TrimSpace(comment)
return len(lc) == 0
}
// writeBack write to file
func writeBack(filepath string, src, old []byte) error {
// make a temporary backup before overwriting original
bakname, err := backupFile(filepath+".", old, 0644)
if err != nil {
return err
}
err = ioutil.WriteFile(filepath, src, 0644)
if err != nil {
_ = os.Rename(bakname, filepath)
return err
}
_ = os.Remove(bakname)
return nil
}
const chmodSupported = runtime.GOOS != "windows"
// backupFile writes data to a new file named filename<number> with permissions perm,
// with <number randomly chosen such that the file name is unique. backupFile returns
// the chosen file name.
// copy from golang/cmd/gofmt
func backupFile(filename string, data []byte, perm os.FileMode) (string, error) {
// create backup file
f, err := ioutil.TempFile(filepath.Dir(filename), filepath.Base(filename))
if err != nil {
return "", err
}
if chmodSupported {
_ = f.Chmod(perm)
}
// write data to backup file
_, err = f.Write(data)
if err1 := f.Close(); err == nil {
err = err1
}
return f.Name(), err
}

132
vendor/github.com/swaggo/swag/formatter.go generated vendored Normal file
View File

@@ -0,0 +1,132 @@
package swag
import (
"bytes"
"crypto/md5"
"fmt"
"go/ast"
goparser "go/parser"
"go/token"
"io"
"log"
"os"
"regexp"
"strings"
"text/tabwriter"
)
const splitTag = "&*"
// Check of @Param @Success @Failure @Response @Header
var specialTagForSplit = map[string]bool{
paramAttr: true,
successAttr: true,
failureAttr: true,
responseAttr: true,
headerAttr: true,
}
var skipChar = map[byte]byte{
'"': '"',
'(': ')',
'{': '}',
'[': ']',
}
// Formatter implements a formatter for Go source files.
type Formatter struct {
// debugging output goes here
debug Debugger
}
// NewFormatter create a new formatter instance.
func NewFormatter() *Formatter {
formatter := &Formatter{
debug: log.New(os.Stdout, "", log.LstdFlags),
}
return formatter
}
// Format formats swag comments in contents. It uses fileName to report errors
// that happen during parsing of contents.
func (f *Formatter) Format(fileName string, contents []byte) ([]byte, error) {
fileSet := token.NewFileSet()
ast, err := goparser.ParseFile(fileSet, fileName, contents, goparser.ParseComments)
if err != nil {
return nil, err
}
formattedComments := bytes.Buffer{}
oldComments := map[string]string{}
if ast.Comments != nil {
for _, comment := range ast.Comments {
formatFuncDoc(comment.List, &formattedComments, oldComments)
}
}
return formatComments(fileName, contents, formattedComments.Bytes(), oldComments), nil
}
func formatComments(fileName string, contents []byte, formattedComments []byte, oldComments map[string]string) []byte {
for _, comment := range bytes.Split(formattedComments, []byte("\n")) {
splits := bytes.SplitN(comment, []byte(splitTag), 2)
if len(splits) == 2 {
hash, line := splits[0], splits[1]
contents = bytes.Replace(contents, []byte(oldComments[string(hash)]), line, 1)
}
}
return contents
}
func formatFuncDoc(commentList []*ast.Comment, formattedComments io.Writer, oldCommentsMap map[string]string) {
w := tabwriter.NewWriter(formattedComments, 0, 0, 2, ' ', 0)
for _, comment := range commentList {
text := comment.Text
if attr, body, found := swagComment(text); found {
cmd5 := fmt.Sprintf("%x", md5.Sum([]byte(text)))
oldCommentsMap[cmd5] = text
formatted := "// " + attr
if body != "" {
formatted += "\t" + splitComment2(attr, body)
}
// md5 + splitTag + srcCommentLine
// eg. xxx&*@Description get struct array
_, _ = fmt.Fprintln(w, cmd5+splitTag+formatted)
}
}
// format by tabwriter
_ = w.Flush()
}
func splitComment2(attr, body string) string {
if specialTagForSplit[strings.ToLower(attr)] {
for i := 0; i < len(body); i++ {
if skipEnd, ok := skipChar[body[i]]; ok {
if skipLen := strings.IndexByte(body[i+1:], skipEnd); skipLen > 0 {
i += skipLen
}
} else if body[i] == ' ' {
j := i
for ; j < len(body) && body[j] == ' '; j++ {
}
body = replaceRange(body, i, j, "\t")
}
}
}
return body
}
func replaceRange(s string, start, end int, new string) string {
return s[:start] + new + s[end:]
}
var swagCommentLineExpression = regexp.MustCompile(`^\/\/\s+(@[\S.]+)\s*(.*)`)
func swagComment(comment string) (string, string, bool) {
matches := swagCommentLineExpression.FindStringSubmatch(comment)
if matches == nil {
return "", "", false
}
return matches[1], matches[2], true
}

12
vendor/github.com/swaggo/swag/go.mod generated vendored
View File

@@ -1,16 +1,15 @@
module github.com/swaggo/swag
go 1.17
go 1.18
require (
github.com/KyleBanks/depth v1.2.1
github.com/agiledragon/gomonkey/v2 v2.3.1
github.com/ghodss/yaml v1.0.0
github.com/go-openapi/jsonreference v0.19.6
github.com/go-openapi/spec v0.20.4
github.com/otiai10/copy v1.7.0
github.com/stretchr/testify v1.7.0
github.com/urfave/cli/v2 v2.3.0
golang.org/x/tools v0.1.7
golang.org/x/tools v0.1.10
)
require (
@@ -19,15 +18,14 @@ require (
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-openapi/jsonpointer v0.19.5 // indirect
github.com/go-openapi/jsonreference v0.19.6 // indirect
github.com/go-openapi/swag v0.19.15 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/mailru/easyjson v0.7.6 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/russross/blackfriday/v2 v2.0.1 // indirect
github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d // indirect
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e // indirect
golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4 // indirect
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e // indirect
golang.org/x/text v0.3.7 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776 // indirect

45
vendor/github.com/swaggo/swag/go.sum generated vendored
View File

@@ -5,8 +5,6 @@ github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tN
github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
github.com/agiledragon/gomonkey/v2 v2.3.1 h1:k+UnUY0EMNYUFUAQVETGY9uUTxjMdnUkP0ARyJS1zzs=
github.com/agiledragon/gomonkey/v2 v2.3.1/go.mod h1:ap1AmDzcVOAz1YpeJ3TCzIgstoaWLA6jbbgxfB4w2iY=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
@@ -25,10 +23,8 @@ github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7
github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk=
github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM=
github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
@@ -40,21 +36,12 @@ github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA
github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/otiai10/copy v1.7.0 h1:hVoPiN+t+7d2nzzwMiDHPSOogsWAStewq3TwU05+clE=
github.com/otiai10/copy v1.7.0/go.mod h1:rmRl6QPdJj6EiUqXQ/4Nn2lLXoNQjFCQbbNrxgc/t3U=
github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE=
github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs=
github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo=
github.com/otiai10/mint v1.3.3 h1:7JgpsBaN0uMkyju4tbYHu0mnM55hNKVYLsXmwr15NQI=
github.com/otiai10/mint v1.3.3/go.mod h1:/yxELlJQ0ufhjUwhshSj+wFjZ78CnZ48/1wtmBH1OTc=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
@@ -62,40 +49,22 @@ github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5Cc
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/urfave/cli/v2 v2.3.0 h1:qph92Y649prgesehzOrQjdWyxFOp/QVM+6imKHad91M=
github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI=
github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 h1:kQgndtyPBW/JIYERgdxfwMYh3AVStj88WQTlNDi2a+o=
golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM=
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d h1:20cMwl2fHAzkJMEA+8J4JgqBQcQGzbisXo31MIeenXI=
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4 h1:HVyaeDAYux4pnY+D/SiwmLOR36ewZ4iGQIIrtnuCjFA=
golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e h1:WUoyKPm6nCo1BnNUvPGnFG3T5DUVem42yDJZZ4CNxMA=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e h1:fLOSk5Q00efkSvAm+4xcoXD+RRmLmmulPn5I3Y9F2EM=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.7 h1:6j8CgantCy3yc8JGBqkDLMKWqZ0RDU2g1HVgacojGWQ=
golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/tools v0.1.10 h1:QjFRCZxdOhBJ/UNgnBZLbNV13DlbnK0quyivTnXJM20=
golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=

View File

@@ -62,8 +62,23 @@ func NewOperation(parser *Parser, options ...func(*Operation)) *Operation {
RouterProperties: []RouteProperties{},
Operation: spec.Operation{
OperationProps: spec.OperationProps{
ID: "",
Description: "",
Summary: "",
Security: nil,
ExternalDocs: nil,
Deprecated: false,
Tags: []string{},
Consumes: []string{},
Produces: []string{},
Schemes: []string{},
Parameters: []spec.Parameter{},
Responses: &spec.Responses{
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{},
},
ResponsesProps: spec.ResponsesProps{
Default: nil,
StatusCodeResponses: make(map[int]spec.Response),
},
},
@@ -72,6 +87,7 @@ func NewOperation(parser *Parser, options ...func(*Operation)) *Operation {
Extensions: spec.Extensions{},
},
},
codeExampleFilesDir: "",
}
for _, option := range options {
@@ -94,11 +110,10 @@ func (operation *Operation) ParseComment(comment string, astFile *ast.File) erro
if len(commentLine) == 0 {
return nil
}
attribute := strings.Fields(commentLine)[0]
lineRemainder := strings.TrimSpace(commentLine[len(attribute):])
lowerAttribute := strings.ToLower(attribute)
var err error
attribute := strings.Fields(commentLine)[0]
lineRemainder, lowerAttribute := strings.TrimSpace(commentLine[len(attribute):]), strings.ToLower(attribute)
switch lowerAttribute {
case descriptionAttr:
operation.ParseDescriptionComment(lineRemainder)
@@ -107,6 +122,7 @@ func (operation *Operation) ParseComment(comment string, astFile *ast.File) erro
if err != nil {
return err
}
operation.ParseDescriptionComment(string(commentInfo))
case summaryAttr:
operation.Summary = lineRemainder
@@ -115,28 +131,28 @@ func (operation *Operation) ParseComment(comment string, astFile *ast.File) erro
case tagsAttr:
operation.ParseTagsComment(lineRemainder)
case acceptAttr:
err = operation.ParseAcceptComment(lineRemainder)
return operation.ParseAcceptComment(lineRemainder)
case produceAttr:
err = operation.ParseProduceComment(lineRemainder)
return operation.ParseProduceComment(lineRemainder)
case paramAttr:
err = operation.ParseParamComment(lineRemainder, astFile)
return operation.ParseParamComment(lineRemainder, astFile)
case successAttr, failureAttr, responseAttr:
err = operation.ParseResponseComment(lineRemainder, astFile)
return operation.ParseResponseComment(lineRemainder, astFile)
case headerAttr:
err = operation.ParseResponseHeaderComment(lineRemainder, astFile)
return operation.ParseResponseHeaderComment(lineRemainder, astFile)
case routerAttr:
err = operation.ParseRouterComment(lineRemainder)
return operation.ParseRouterComment(lineRemainder)
case securityAttr:
err = operation.ParseSecurityComment(lineRemainder)
return operation.ParseSecurityComment(lineRemainder)
case deprecatedAttr:
operation.Deprecate()
case xCodeSamplesAttr:
err = operation.ParseCodeSample(attribute, commentLine, lineRemainder)
return operation.ParseCodeSample(attribute, commentLine, lineRemainder)
default:
err = operation.ParseMetadata(attribute, lowerAttribute, lineRemainder)
return operation.ParseMetadata(attribute, lowerAttribute, lineRemainder)
}
return err
return nil
}
// ParseCodeSample godoc.
@@ -148,6 +164,7 @@ func (operation *Operation) ParseCodeSample(attribute, _, lineRemainder string)
}
var valueJSON interface{}
err = json.Unmarshal(data, &valueJSON)
if err != nil {
return fmt.Errorf("annotation %s need a valid json value", attribute)
@@ -170,6 +187,7 @@ func (operation *Operation) ParseDescriptionComment(lineRemainder string) {
return
}
operation.Description += "\n" + lineRemainder
}
@@ -182,6 +200,7 @@ func (operation *Operation) ParseMetadata(attribute, lowerAttribute, lineRemaind
}
var valueJSON interface{}
err := json.Unmarshal([]byte(lineRemainder), &valueJSON)
if err != nil {
return fmt.Errorf("annotation %s need a valid json value", attribute)
@@ -194,7 +213,7 @@ func (operation *Operation) ParseMetadata(attribute, lowerAttribute, lineRemaind
return nil
}
var paramPattern = regexp.MustCompile(`(\S+)[\s]+([\w]+)[\s]+([\S.]+)[\s]+([\w]+)[\s]+"([^"]+)"`)
var paramPattern = regexp.MustCompile(`(\S+)\s+(\w+)\s+([\S.]+)\s+(\w+)\s+"([^"]+)"`)
func findInSlice(arr []string, target string) bool {
for _, str := range arr {
@@ -210,13 +229,39 @@ func (operation *Operation) parseArrayParam(param *spec.Parameter, paramType, re
if !IsPrimitiveType(refType) {
return fmt.Errorf("%s is not supported array type for %s", refType, paramType)
}
param.SimpleSchema.Type = objectType
if operation.parser != nil {
param.CollectionFormat = TransToValidCollectionFormat(operation.parser.collectionFormatInQuery)
}
param.SimpleSchema.Items = &spec.Items{
SimpleSchema: spec.SimpleSchema{
Type: refType,
Default: nil,
Nullable: false,
Format: "",
Items: nil,
CollectionFormat: "",
Type: refType,
Example: nil,
},
CommonValidations: spec.CommonValidations{
Maximum: nil,
ExclusiveMaximum: false,
Minimum: nil,
ExclusiveMinimum: false,
MaxLength: nil,
MinLength: nil,
Pattern: "",
MaxItems: nil,
MinItems: nil,
UniqueItems: false,
MultipleOf: nil,
Enum: nil,
},
VendorExtensible: spec.VendorExtensible{
Extensions: nil,
},
}
@@ -232,6 +277,7 @@ func (operation *Operation) ParseParamComment(commentLine string, astFile *ast.F
if len(matches) != 6 {
return fmt.Errorf("missing required param comment parameters \"%s\"", commentLine)
}
name := matches[1]
paramType := matches[2]
refType := TransToValidSchemeType(matches[3])
@@ -248,7 +294,7 @@ func (operation *Operation) ParseParamComment(commentLine string, astFile *ast.F
}
requiredText := strings.ToLower(matches[4])
required := requiredText == "true" || requiredText == "required"
required := requiredText == "true" || requiredText == requiredLabel
description := matches[5]
param := createParameter(paramType, description, name, refType, required)
@@ -276,27 +322,30 @@ func (operation *Operation) ParseParamComment(commentLine string, astFile *ast.F
if err != nil {
return err
}
if len(schema.Properties) == 0 {
return nil
}
items := schema.Properties.ToOrderedSchemaItems()
for _, item := range items {
name := item.Name
prop := item.Schema
name, prop := item.Name, item.Schema
if len(prop.Type) == 0 {
continue
}
switch {
case prop.Type[0] == ARRAY &&
prop.Items.Schema != nil &&
len(prop.Items.Schema.Type) > 0 &&
IsSimplePrimitiveType(prop.Items.Schema.Type[0]):
case prop.Type[0] == ARRAY && prop.Items.Schema != nil &&
len(prop.Items.Schema.Type) > 0 && IsSimplePrimitiveType(prop.Items.Schema.Type[0]):
param = createParameter(paramType, prop.Description, name, prop.Type[0], findInSlice(schema.Required, name))
param.SimpleSchema.Type = prop.Type[0]
if operation.parser != nil && operation.parser.collectionFormatInQuery != "" && param.CollectionFormat == "" {
param.CollectionFormat = TransToValidCollectionFormat(operation.parser.collectionFormatInQuery)
}
param.SimpleSchema.Items = &spec.Items{
SimpleSchema: spec.SimpleSchema{
Type: prop.Items.Schema.Type[0],
@@ -309,6 +358,7 @@ func (operation *Operation) ParseParamComment(commentLine string, astFile *ast.F
continue
}
param.Nullable = prop.Nullable
param.Format = prop.Format
param.Default = prop.Default
@@ -339,16 +389,18 @@ func (operation *Operation) ParseParamComment(commentLine string, astFile *ast.F
if err != nil {
return err
}
param.Schema = schema
}
default:
return fmt.Errorf("%s is not supported paramType", paramType)
}
err := operation.parseAndExtractionParamAttribute(commentLine, objectType, refType, &param)
err := operation.parseParamAttribute(commentLine, objectType, refType, &param)
if err != nil {
return err
}
operation.Operation.Parameters = append(operation.Operation.Parameters, param)
return nil
@@ -360,12 +412,13 @@ const (
defaultTag = "default"
enumsTag = "enums"
exampleTag = "example"
schemaExampleTag = "schemaExample"
formatTag = "format"
validateTag = "validate"
minimumTag = "minimum"
maximumTag = "maximum"
minLengthTag = "minlength"
maxLengthTag = "maxlength"
minLengthTag = "minLength"
maxLengthTag = "maxLength"
multipleOfTag = "multipleOf"
readOnlyTag = "readonly"
extensionsTag = "extensions"
@@ -393,33 +446,40 @@ var regexAttributes = map[string]*regexp.Regexp{
collectionFormatTag: regexp.MustCompile(`(?i)\s+collectionFormat\(.*\)`),
// example(0)
exampleTag: regexp.MustCompile(`(?i)\s+example\(.*\)`),
// schemaExample(0)
schemaExampleTag: regexp.MustCompile(`(?i)\s+schemaExample\(.*\)`),
}
func (operation *Operation) parseAndExtractionParamAttribute(commentLine, objectType, schemaType string, param *spec.Parameter) error {
func (operation *Operation) parseParamAttribute(comment, objectType, schemaType string, param *spec.Parameter) error {
schemaType = TransToValidSchemeType(schemaType)
for attrKey, re := range regexAttributes {
attr, err := findAttr(re, commentLine)
attr, err := findAttr(re, comment)
if err != nil {
continue
}
switch attrKey {
case enumsTag:
err = setEnumParam(param, attr, objectType, schemaType)
case minimumTag, maximumTag:
err = setNumberParam(param, attrKey, schemaType, attr, commentLine)
err = setNumberParam(param, attrKey, schemaType, attr, comment)
case defaultTag:
err = setDefault(param, schemaType, attr)
case minLengthTag, maxLengthTag:
err = setStringParam(param, attrKey, schemaType, attr, commentLine)
err = setStringParam(param, attrKey, schemaType, attr, comment)
case formatTag:
param.Format = attr
case exampleTag:
err = setExample(param, schemaType, attr)
case schemaExampleTag:
err = setSchemaExample(param, schemaType, attr)
case extensionsTag:
_ = setExtensionParam(param, attr)
param.Extensions = setExtensionParam(attr)
case collectionFormatTag:
err = setCollectionFormatParam(param, attrKey, objectType, attr, commentLine)
err = setCollectionFormatParam(param, attrKey, objectType, attr, comment)
}
if err != nil {
return err
}
@@ -430,8 +490,8 @@ func (operation *Operation) parseAndExtractionParamAttribute(commentLine, object
func findAttr(re *regexp.Regexp, commentLine string) (string, error) {
attr := re.FindString(commentLine)
l := strings.Index(attr, "(")
r := strings.Index(attr, ")")
l, r := strings.Index(attr, "("), strings.Index(attr, ")")
if l == -1 || r == -1 {
return "", fmt.Errorf("can not find regex=%s, comment=%s", re.String(), commentLine)
}
@@ -466,12 +526,14 @@ func setNumberParam(param *spec.Parameter, name, schemaType, attr, commentLine s
if err != nil {
return fmt.Errorf("maximum is allow only a number. comment=%s got=%s", commentLine, attr)
}
switch name {
case minimumTag:
param.Minimum = &n
case maximumTag:
param.Maximum = &n
}
return nil
default:
return fmt.Errorf("%s is attribute to set to a number. comment=%s got=%s", name, commentLine, schemaType)
@@ -498,23 +560,33 @@ func setEnumParam(param *spec.Parameter, attr, objectType, schemaType string) er
return nil
}
func setExtensionParam(param *spec.Parameter, attr string) error {
param.Extensions = map[string]interface{}{}
func setExtensionParam(attr string) spec.Extensions {
extensions := spec.Extensions{}
for _, val := range splitNotWrapped(attr, ',') {
parts := strings.SplitN(val, "=", 2)
if len(parts) == 2 {
param.Extensions.Add(parts[0], parts[1])
extensions.Add(parts[0], parts[1])
continue
}
param.Extensions.Add(parts[0], true)
if len(parts[0]) > 0 && string(parts[0][0]) == "!" {
extensions.Add(parts[0][1:], false)
continue
}
extensions.Add(parts[0], true)
}
return nil
return extensions
}
func setCollectionFormatParam(param *spec.Parameter, name, schemaType, attr, commentLine string) error {
if schemaType == ARRAY {
param.CollectionFormat = TransToValidCollectionFormat(attr)
return nil
}
@@ -526,7 +598,30 @@ func setDefault(param *spec.Parameter, schemaType string, value string) error {
if err != nil {
return nil // Don't set a default value if it's not valid
}
param.Default = val
return nil
}
func setSchemaExample(param *spec.Parameter, schemaType string, value string) error {
val, err := defineType(schemaType, value)
if err != nil {
return nil // Don't set a example value if it's not valid
}
// skip schema
if param.Schema == nil {
return nil
}
switch v := val.(type) {
case string:
// replaces \r \n \t in example string values.
param.Schema.Example = strings.NewReplacer(`\r`, "\r", `\n`, "\n", `\t`, "\t").Replace(v)
default:
param.Schema.Example = val
}
return nil
}
@@ -535,13 +630,16 @@ func setExample(param *spec.Parameter, schemaType string, value string) error {
if err != nil {
return nil // Don't set a example value if it's not valid
}
param.Example = val
return nil
}
// defineType enum value define the type (object and array unsupported).
func defineType(schemaType string, value string) (v interface{}, err error) {
schemaType = TransToValidSchemeType(schemaType)
switch schemaType {
case STRING:
return value, nil
@@ -569,8 +667,7 @@ func defineType(schemaType string, value string) (v interface{}, err error) {
// ParseTagsComment parses comment for given `tag` comment string.
func (operation *Operation) ParseTagsComment(commentLine string) {
tags := strings.Split(commentLine, ",")
for _, tag := range tags {
for _, tag := range strings.Split(commentLine, ",") {
operation.Tags = append(operation.Tags, strings.TrimSpace(tag))
}
}
@@ -589,13 +686,13 @@ func (operation *Operation) ParseProduceComment(commentLine string) error {
// `produce` (`Content-Type:` response header) or
// `accept` (`Accept:` request header).
func parseMimeTypeList(mimeTypeList string, typeList *[]string, format string) error {
mimeTypes := strings.Split(mimeTypeList, ",")
for _, typeName := range mimeTypes {
for _, typeName := range strings.Split(mimeTypeList, ",") {
if mimeTypePattern.MatchString(typeName) {
*typeList = append(*typeList, typeName)
continue
}
aliasMimeType, ok := mimeTypeAliases[typeName]
if !ok {
return fmt.Errorf(format, typeName)
@@ -615,6 +712,7 @@ func (operation *Operation) ParseRouterComment(commentLine string) error {
if len(matches) != 3 {
return fmt.Errorf("can not parse router comment \"%s\"", commentLine)
}
signature := RouteProperties{
Path: matches[1],
HTTPMethod: strings.ToUpper(matches[2]),
@@ -631,33 +729,41 @@ func (operation *Operation) ParseRouterComment(commentLine string) error {
// ParseSecurityComment parses comment for given `security` comment string.
func (operation *Operation) ParseSecurityComment(commentLine string) error {
securitySource := commentLine[strings.Index(commentLine, "@Security")+1:]
l := strings.Index(securitySource, "[")
r := strings.Index(securitySource, "]")
// exists scope
if !(l == -1 && r == -1) {
scopes := securitySource[l+1 : r]
var s []string
for _, scope := range strings.Split(scopes, ",") {
s = append(s, strings.TrimSpace(scope))
var (
securityMap = make(map[string][]string)
securitySource = commentLine[strings.Index(commentLine, "@Security")+1:]
)
for _, securityOption := range strings.Split(securitySource, "||") {
securityOption = strings.TrimSpace(securityOption)
left, right := strings.Index(securityOption, "["), strings.Index(securityOption, "]")
if !(left == -1 && right == -1) {
scopes := securityOption[left+1 : right]
var options []string
for _, scope := range strings.Split(scopes, ",") {
options = append(options, strings.TrimSpace(scope))
}
securityKey := securityOption[0:left]
securityMap[securityKey] = append(securityMap[securityKey], options...)
} else {
securityKey := strings.TrimSpace(securityOption)
securityMap[securityKey] = []string{}
}
securityKey := securitySource[0:l]
securityMap := map[string][]string{}
securityMap[securityKey] = append(securityMap[securityKey], s...)
operation.Security = append(operation.Security, securityMap)
} else {
securityKey := strings.TrimSpace(securitySource)
securityMap := map[string][]string{}
securityMap[securityKey] = []string{}
operation.Security = append(operation.Security, securityMap)
}
operation.Security = append(operation.Security, securityMap)
return nil
}
// findTypeDef attempts to find the *ast.TypeSpec for a specific type given the
// type's name and the package's import path.
// TODO: improve finding external pkg
// TODO: improve finding external pkg.
func findTypeDef(importPath, typeName string) (*ast.TypeSpec, error) {
cwd, err := os.Getwd()
if err != nil {
@@ -693,7 +799,6 @@ func findTypeDef(importPath, typeName string) (*ast.TypeSpec, error) {
}
// TODO: possibly cache pkgInfo since it's an expensive operation
for i := range pkgInfo.Files {
for _, astDeclaration := range pkgInfo.Files[i].Decls {
generalDeclaration, ok := astDeclaration.(*ast.GenDecl)
@@ -713,7 +818,7 @@ func findTypeDef(importPath, typeName string) (*ast.TypeSpec, error) {
return nil, fmt.Errorf("type spec not found")
}
var responsePattern = regexp.MustCompile(`^([\w,]+)[\s]+([\w{}]+)[\s]+([\w\-.\\{}=,\[\]]+)[^"]*(.*)?`)
var responsePattern = regexp.MustCompile(`^([\w,]+)\s+([\w{}]+)\s+([\w\-.\\{}=,\[\]]+)[^"]*(.*)?`)
// ResponseType{data1=Type1,data2=Type2}.
var combinedPattern = regexp.MustCompile(`^([\w\-./\[\]]+){(.*)}$`)
@@ -722,7 +827,9 @@ func (operation *Operation) parseObjectSchema(refType string, astFile *ast.File)
switch {
case refType == NIL:
return nil, nil
case refType == "interface{}":
case refType == INTERFACE:
return PrimitiveSchema(OBJECT), nil
case refType == ANY:
return PrimitiveSchema(OBJECT), nil
case IsGolangPrimitiveType(refType):
refType = TransToValidSchemeType(refType)
@@ -743,10 +850,12 @@ func (operation *Operation) parseObjectSchema(refType string, astFile *ast.File)
if idx < 0 {
return nil, fmt.Errorf("invalid type: %s", refType)
}
refType = refType[idx+1:]
if refType == "interface{}" {
if refType == INTERFACE || refType == ANY {
return spec.MapProperty(nil), nil
}
schema, err := operation.parseObjectSchema(refType, astFile)
if err != nil {
return nil, err
@@ -769,45 +878,46 @@ func (operation *Operation) parseObjectSchema(refType string, astFile *ast.File)
}
}
func parseFields(s string) []string {
nestLevel := 0
return strings.FieldsFunc(s, func(char rune) bool {
if char == '{' {
nestLevel++
return false
} else if char == '}' {
nestLevel--
return false
}
return char == ',' && nestLevel == 0
})
}
func (operation *Operation) parseCombinedObjectSchema(refType string, astFile *ast.File) (*spec.Schema, error) {
matches := combinedPattern.FindStringSubmatch(refType)
if len(matches) != 3 {
return nil, fmt.Errorf("invalid type: %s", refType)
}
refType = matches[1]
schema, err := operation.parseObjectSchema(refType, astFile)
schema, err := operation.parseObjectSchema(matches[1], astFile)
if err != nil {
return nil, err
}
parseFields := func(s string) []string {
n := 0
fields, props := parseFields(matches[2]), map[string]spec.Schema{}
return strings.FieldsFunc(s, func(r rune) bool {
if r == '{' {
n++
return false
} else if r == '}' {
n--
return false
}
return r == ',' && n == 0
})
}
fields := parseFields(matches[2])
props := map[string]spec.Schema{}
for _, field := range fields {
matches := strings.SplitN(field, "=", 2)
if len(matches) == 2 {
schema, err := operation.parseObjectSchema(matches[1], astFile)
keyVal := strings.SplitN(field, "=", 2)
if len(keyVal) == 2 {
schema, err := operation.parseObjectSchema(keyVal[1], astFile)
if err != nil {
return nil, err
}
props[matches[0]] = *schema
props[keyVal[0]] = *schema
}
}
@@ -829,6 +939,7 @@ func (operation *Operation) parseAPIObjectSchema(schemaType, refType string, ast
if !strings.HasPrefix(refType, "[]") {
return operation.parseObjectSchema(refType, astFile)
}
refType = refType[2:]
fallthrough
@@ -857,6 +968,7 @@ func (operation *Operation) ParseResponseComment(commentLine string, astFile *as
}
description := strings.Trim(matches[4], "\"")
schema, err := operation.parseAPIObjectSchema(strings.Trim(matches[2], "{}"), matches[3], astFile)
if err != nil {
return err
@@ -868,6 +980,7 @@ func (operation *Operation) ParseResponseComment(commentLine string, astFile *as
continue
}
code, err := strconv.Atoi(codeStr)
if err != nil {
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
@@ -892,6 +1005,23 @@ func newHeaderSpec(schemaType, description string) spec.Header {
HeaderProps: spec.HeaderProps{
Description: description,
},
VendorExtensible: spec.VendorExtensible{
Extensions: nil,
},
CommonValidations: spec.CommonValidations{
Maximum: nil,
ExclusiveMaximum: false,
Minimum: nil,
ExclusiveMinimum: false,
MaxLength: nil,
MinLength: nil,
Pattern: "",
MaxItems: nil,
MinItems: nil,
UniqueItems: false,
MultipleOf: nil,
Enum: nil,
},
}
}
@@ -934,6 +1064,7 @@ func (operation *Operation) ParseResponseHeaderComment(commentLine string, _ *as
if err != nil {
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
}
if operation.Responses.StatusCodeResponses != nil {
response, responseExist := operation.Responses.StatusCodeResponses[code]
if responseExist {
@@ -947,7 +1078,7 @@ func (operation *Operation) ParseResponseHeaderComment(commentLine string, _ *as
return nil
}
var emptyResponsePattern = regexp.MustCompile(`([\w,]+)[\s]+"(.*)"`)
var emptyResponsePattern = regexp.MustCompile(`([\w,]+)\s+"(.*)"`)
// ParseEmptyResponseComment parse only comment out status code and description,eg: @Success 200 "it's ok".
func (operation *Operation) ParseEmptyResponseComment(commentLine string) error {
@@ -957,6 +1088,7 @@ func (operation *Operation) ParseEmptyResponseComment(commentLine string) error
}
description := strings.Trim(matches[2], "\"")
for _, codeStr := range strings.Split(matches[1], ",") {
if strings.EqualFold(codeStr, defaultTag) {
operation.DefaultResponse().WithDescription(description)
@@ -983,6 +1115,7 @@ func (operation *Operation) ParseEmptyResponseOnly(commentLine string) error {
continue
}
code, err := strconv.Atoi(codeStr)
if err != nil {
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
@@ -999,7 +1132,8 @@ func (operation *Operation) DefaultResponse() *spec.Response {
if operation.Responses.Default == nil {
operation.Responses.Default = &spec.Response{
ResponseProps: spec.ResponseProps{
Headers: make(map[string]spec.Header),
Description: "",
Headers: make(map[string]spec.Header),
},
}
}
@@ -1012,6 +1146,7 @@ func (operation *Operation) AddResponse(code int, response *spec.Response) {
if response.Headers == nil {
response.Headers = make(map[string]spec.Header)
}
operation.Responses.StatusCodeResponses[code] = *response
}
@@ -1020,10 +1155,12 @@ func createParameter(paramType, description, paramName, schemaType string, requi
// //five possible parameter types. query, path, body, header, form
result := spec.Parameter{
ParamProps: spec.ParamProps{
Name: paramName,
Description: description,
Required: required,
In: paramType,
Name: paramName,
Description: description,
Required: required,
In: paramType,
Schema: nil,
AllowEmptyValue: false,
},
}
@@ -1038,7 +1175,9 @@ func createParameter(paramType, description, paramName, schemaType string, requi
}
result.SimpleSchema = spec.SimpleSchema{
Type: schemaType,
Type: schemaType,
Nullable: false,
Format: "",
}
return result
@@ -1054,6 +1193,7 @@ func getCodeExampleForSummary(summaryName string, dirPath string) ([]byte, error
if fileInfo.IsDir() {
continue
}
fileName := fileInfo.Name()
if !strings.Contains(fileName, ".json") {
@@ -1062,6 +1202,7 @@ func getCodeExampleForSummary(summaryName string, dirPath string) ([]byte, error
if strings.Contains(fileName, summaryName) {
fullPath := filepath.Join(dirPath, fileName)
commentInfo, err := ioutil.ReadFile(fullPath)
if err != nil {
return nil, fmt.Errorf("Failed to read code example file %s error: %s ", fullPath, err)

View File

@@ -29,13 +29,13 @@ func NewPackagesDefinitions() *PackagesDefinitions {
}
// CollectAstFile collect ast.file.
func (pkgs *PackagesDefinitions) CollectAstFile(packageDir, path string, astFile *ast.File) error {
if pkgs.files == nil {
pkgs.files = make(map[*ast.File]*AstFileInfo)
func (pkgDefs *PackagesDefinitions) CollectAstFile(packageDir, path string, astFile *ast.File) error {
if pkgDefs.files == nil {
pkgDefs.files = make(map[*ast.File]*AstFileInfo)
}
if pkgs.packages == nil {
pkgs.packages = make(map[string]*PackageDefinitions)
if pkgDefs.packages == nil {
pkgDefs.packages = make(map[string]*PackageDefinitions)
}
// return without storing the file if we lack a packageDir
@@ -48,23 +48,24 @@ func (pkgs *PackagesDefinitions) CollectAstFile(packageDir, path string, astFile
return err
}
pd, ok := pkgs.packages[packageDir]
dependency, ok := pkgDefs.packages[packageDir]
if ok {
// return without storing the file if it already exists
_, exists := pd.Files[path]
_, exists := dependency.Files[path]
if exists {
return nil
}
pd.Files[path] = astFile
dependency.Files[path] = astFile
} else {
pkgs.packages[packageDir] = &PackageDefinitions{
pkgDefs.packages[packageDir] = &PackageDefinitions{
Name: astFile.Name.Name,
Files: map[string]*ast.File{path: astFile},
TypeDefinitions: make(map[string]*TypeSpecDef),
}
}
pkgs.files[astFile] = &AstFileInfo{
pkgDefs.files[astFile] = &AstFileInfo{
File: astFile,
Path: path,
PackagePath: packageDir,
@@ -96,15 +97,15 @@ func rangeFiles(files map[*ast.File]*AstFileInfo, handle func(filename string, f
// ParseTypes parse types
// @Return parsed definitions.
func (pkgs *PackagesDefinitions) ParseTypes() (map[*TypeSpecDef]*Schema, error) {
func (pkgDefs *PackagesDefinitions) ParseTypes() (map[*TypeSpecDef]*Schema, error) {
parsedSchemas := make(map[*TypeSpecDef]*Schema)
for astFile, info := range pkgs.files {
pkgs.parseTypesFromFile(astFile, info.PackagePath, parsedSchemas)
for astFile, info := range pkgDefs.files {
pkgDefs.parseTypesFromFile(astFile, info.PackagePath, parsedSchemas)
}
return parsedSchemas, nil
}
func (pkgs *PackagesDefinitions) parseTypesFromFile(astFile *ast.File, packagePath string, parsedSchemas map[*TypeSpecDef]*Schema) {
func (pkgDefs *PackagesDefinitions) parseTypesFromFile(astFile *ast.File, packagePath string, parsedSchemas map[*TypeSpecDef]*Schema) {
for _, astDeclaration := range astFile.Decls {
if generalDeclaration, ok := astDeclaration.(*ast.GenDecl); ok && generalDeclaration.Tok == token.TYPE {
for _, astSpec := range generalDeclaration.Specs {
@@ -123,29 +124,29 @@ func (pkgs *PackagesDefinitions) parseTypesFromFile(astFile *ast.File, packagePa
}
}
if pkgs.uniqueDefinitions == nil {
pkgs.uniqueDefinitions = make(map[string]*TypeSpecDef)
if pkgDefs.uniqueDefinitions == nil {
pkgDefs.uniqueDefinitions = make(map[string]*TypeSpecDef)
}
fullName := typeSpecDef.FullName()
anotherTypeDef, ok := pkgs.uniqueDefinitions[fullName]
anotherTypeDef, ok := pkgDefs.uniqueDefinitions[fullName]
if ok {
if typeSpecDef.PkgPath == anotherTypeDef.PkgPath {
continue
} else {
delete(pkgs.uniqueDefinitions, fullName)
delete(pkgDefs.uniqueDefinitions, fullName)
}
} else {
pkgs.uniqueDefinitions[fullName] = typeSpecDef
pkgDefs.uniqueDefinitions[fullName] = typeSpecDef
}
if pkgs.packages[typeSpecDef.PkgPath] == nil {
pkgs.packages[typeSpecDef.PkgPath] = &PackageDefinitions{
if pkgDefs.packages[typeSpecDef.PkgPath] == nil {
pkgDefs.packages[typeSpecDef.PkgPath] = &PackageDefinitions{
Name: astFile.Name.Name,
TypeDefinitions: map[string]*TypeSpecDef{typeSpecDef.Name(): typeSpecDef},
}
} else if _, ok = pkgs.packages[typeSpecDef.PkgPath].TypeDefinitions[typeSpecDef.Name()]; !ok {
pkgs.packages[typeSpecDef.PkgPath].TypeDefinitions[typeSpecDef.Name()] = typeSpecDef
} else if _, ok = pkgDefs.packages[typeSpecDef.PkgPath].TypeDefinitions[typeSpecDef.Name()]; !ok {
pkgDefs.packages[typeSpecDef.PkgPath].TypeDefinitions[typeSpecDef.Name()] = typeSpecDef
}
}
}
@@ -153,11 +154,12 @@ func (pkgs *PackagesDefinitions) parseTypesFromFile(astFile *ast.File, packagePa
}
}
func (pkgs *PackagesDefinitions) findTypeSpec(pkgPath string, typeName string) *TypeSpecDef {
if pkgs.packages == nil {
func (pkgDefs *PackagesDefinitions) findTypeSpec(pkgPath string, typeName string) *TypeSpecDef {
if pkgDefs.packages == nil {
return nil
}
pd, found := pkgs.packages[pkgPath]
pd, found := pkgDefs.packages[pkgPath]
if found {
typeSpec, ok := pd.TypeDefinitions[typeName]
if ok {
@@ -168,7 +170,7 @@ func (pkgs *PackagesDefinitions) findTypeSpec(pkgPath string, typeName string) *
return nil
}
func (pkgs *PackagesDefinitions) loadExternalPackage(importPath string) error {
func (pkgDefs *PackagesDefinitions) loadExternalPackage(importPath string) error {
cwd, err := os.Getwd()
if err != nil {
return err
@@ -189,7 +191,7 @@ func (pkgs *PackagesDefinitions) loadExternalPackage(importPath string) error {
for _, info := range loaderProgram.AllPackages {
pkgPath := strings.TrimPrefix(info.Pkg.Path(), "vendor/")
for _, astFile := range info.Files {
pkgs.parseTypesFromFile(astFile, pkgPath, nil)
pkgDefs.parseTypesFromFile(astFile, pkgPath, nil)
}
}
@@ -201,7 +203,7 @@ func (pkgs *PackagesDefinitions) loadExternalPackage(importPath string) error {
// @file current ast.File in which to search imports
// @fuzzy search for the package path that the last part matches the @pkg if true
// @return the package path of a package of @pkg.
func (pkgs *PackagesDefinitions) findPackagePathFromImports(pkg string, file *ast.File, fuzzy bool) string {
func (pkgDefs *PackagesDefinitions) findPackagePathFromImports(pkg string, file *ast.File, fuzzy bool) string {
if file == nil {
return ""
}
@@ -214,6 +216,7 @@ func (pkgs *PackagesDefinitions) findPackagePathFromImports(pkg string, file *as
matchLastPathPart := func(pkgPath string) bool {
paths := strings.Split(pkgPath, "/")
return paths[len(paths)-1] == pkg
}
@@ -223,26 +226,33 @@ func (pkgs *PackagesDefinitions) findPackagePathFromImports(pkg string, file *as
if imp.Name.Name == pkg {
return strings.Trim(imp.Path.Value, `"`)
}
if imp.Name.Name == "_" {
hasAnonymousPkg = true
}
continue
}
if pkgs.packages != nil {
if pkgDefs.packages != nil {
path := strings.Trim(imp.Path.Value, `"`)
if fuzzy {
if matchLastPathPart(path) {
return path
}
} else if pd, ok := pkgs.packages[path]; ok && pd.Name == pkg {
continue
}
pd, ok := pkgDefs.packages[path]
if ok && pd.Name == pkg {
return path
}
}
}
// match unnamed package
if hasAnonymousPkg && pkgs.packages != nil {
if hasAnonymousPkg && pkgDefs.packages != nil {
for _, imp := range file.Imports {
if imp.Name == nil {
continue
@@ -253,7 +263,7 @@ func (pkgs *PackagesDefinitions) findPackagePathFromImports(pkg string, file *as
if matchLastPathPart(path) {
return path
}
} else if pd, ok := pkgs.packages[path]; ok && pd.Name == pkg {
} else if pd, ok := pkgDefs.packages[path]; ok && pd.Name == pkg {
return path
}
}
@@ -267,12 +277,13 @@ func (pkgs *PackagesDefinitions) findPackagePathFromImports(pkg string, file *as
// @typeName the name of the target type, if it starts with a package name, find its own package path from imports on top of @file
// @file the ast.file in which @typeName is used
// @pkgPath the package path of @file.
func (pkgs *PackagesDefinitions) FindTypeSpec(typeName string, file *ast.File, parseDependency bool) *TypeSpecDef {
func (pkgDefs *PackagesDefinitions) FindTypeSpec(typeName string, file *ast.File, parseDependency bool) *TypeSpecDef {
if IsGolangPrimitiveType(typeName) {
return nil
}
if file == nil { // for test
return pkgs.uniqueDefinitions[typeName]
return pkgDefs.uniqueDefinitions[typeName]
}
parts := strings.Split(typeName, ".")
@@ -290,42 +301,43 @@ func (pkgs *PackagesDefinitions) FindTypeSpec(typeName string, file *ast.File, p
}
if !isAliasPkgName(file, parts[0]) {
typeDef, ok := pkgs.uniqueDefinitions[typeName]
typeDef, ok := pkgDefs.uniqueDefinitions[typeName]
if ok {
return typeDef
}
}
pkgPath := pkgs.findPackagePathFromImports(parts[0], file, false)
pkgPath := pkgDefs.findPackagePathFromImports(parts[0], file, false)
if len(pkgPath) == 0 {
// check if the current package
if parts[0] == file.Name.Name {
pkgPath = pkgs.files[file].PackagePath
pkgPath = pkgDefs.files[file].PackagePath
} else if parseDependency {
// take it as an external package, needs to be loaded
if pkgPath = pkgs.findPackagePathFromImports(parts[0], file, true); len(pkgPath) > 0 {
if err := pkgs.loadExternalPackage(pkgPath); err != nil {
if pkgPath = pkgDefs.findPackagePathFromImports(parts[0], file, true); len(pkgPath) > 0 {
if err := pkgDefs.loadExternalPackage(pkgPath); err != nil {
return nil
}
}
}
}
return pkgs.findTypeSpec(pkgPath, parts[1])
return pkgDefs.findTypeSpec(pkgPath, parts[1])
}
typeDef, ok := pkgs.uniqueDefinitions[fullTypeName(file.Name.Name, typeName)]
typeDef, ok := pkgDefs.uniqueDefinitions[fullTypeName(file.Name.Name, typeName)]
if ok {
return typeDef
}
typeDef = pkgs.findTypeSpec(pkgs.files[file].PackagePath, typeName)
typeDef = pkgDefs.findTypeSpec(pkgDefs.files[file].PackagePath, typeName)
if typeDef != nil {
return typeDef
}
for _, imp := range file.Imports {
if imp.Name != nil && imp.Name.Name == "." {
typeDef := pkgs.findTypeSpec(strings.Trim(imp.Path.Value, `"`), typeName)
typeDef := pkgDefs.findTypeSpec(strings.Trim(imp.Path.Value, `"`), typeName)
if typeDef != nil {
return typeDef
}

View File

@@ -65,7 +65,7 @@ var (
// ErrFailedConvertPrimitiveType Failed to convert for swag to interpretable type.
ErrFailedConvertPrimitiveType = errors.New("swag property: failed convert primitive type")
// ErrSkippedField .swaggo specifies field should be skipped
// ErrSkippedField .swaggo specifies field should be skipped.
ErrSkippedField = errors.New("field is skipped by global overrides")
)
@@ -142,12 +142,12 @@ type Parser struct {
Overrides map[string]string
}
// FieldParserFactory create FieldParser
// FieldParserFactory create FieldParser.
type FieldParserFactory func(ps *Parser, field *ast.Field) FieldParser
// FieldParser parse struct field
// FieldParser parse struct field.
type FieldParser interface {
ShouldSkip() (bool, error)
ShouldSkip() bool
FieldName() (string, error)
CustomSchema() (*spec.Schema, error)
ComplementSchema(schema *spec.Schema) error
@@ -161,8 +161,6 @@ type Debugger interface {
// New creates a new Parser with default properties.
func New(options ...func(*Parser)) *Parser {
// parser.swagger.SecurityDefinitions =
parser := &Parser{
swagger: &spec.Swagger{
SwaggerProps: spec.SwaggerProps{
@@ -177,10 +175,16 @@ func New(options ...func(*Parser)) *Parser {
},
Paths: &spec.Paths{
Paths: make(map[string]spec.PathItem),
VendorExtensible: spec.VendorExtensible{
Extensions: nil,
},
},
Definitions: make(map[string]spec.Schema),
SecurityDefinitions: make(map[string]*spec.SecurityScheme),
},
VendorExtensible: spec.VendorExtensible{
Extensions: nil,
},
},
packages: NewPackagesDefinitions(),
debug: log.New(os.Stdout, "", log.LstdFlags),
@@ -284,22 +288,22 @@ func (parser *Parser) ParseAPIMultiSearchDir(searchDirs []string, mainAPIFile st
}
if parser.ParseDependency {
var t depth.Tree
t.ResolveInternal = true
t.MaxDepth = parseDepth
var tree depth.Tree
tree.ResolveInternal = true
tree.MaxDepth = parseDepth
pkgName, err := getPkgName(filepath.Dir(absMainAPIFilePath))
if err != nil {
return err
}
err = t.Resolve(pkgName)
err = tree.Resolve(pkgName)
if err != nil {
return fmt.Errorf("pkg %s cannot find all dependencies, %s", pkgName, err)
}
for i := 0; i < len(t.Root.Deps); i++ {
err := parser.getAllGoFileInfoFromDeps(&t.Root.Deps[i])
for i := 0; i < len(tree.Root.Deps); i++ {
err := parser.getAllGoFileInfoFromDeps(&tree.Root.Deps[i])
if err != nil {
return err
}
@@ -329,7 +333,9 @@ func (parser *Parser) ParseAPIMultiSearchDir(searchDirs []string, mainAPIFile st
func getPkgName(searchDir string) (string, error) {
cmd := exec.Command("go", "list", "-f={{.ImportPath}}")
cmd.Dir = searchDir
var stdout, stderr strings.Builder
cmd.Stdout = &stdout
cmd.Stderr = &stderr
@@ -342,7 +348,9 @@ func getPkgName(searchDir string) (string, error) {
if outStr[0] == '_' { // will shown like _/{GOPATH}/src/{YOUR_PACKAGE} when NOT enable GO MODULE.
outStr = strings.TrimPrefix(outStr, "_"+build.Default.GOPATH+"/src/")
}
f := strings.Split(outStr, "\n")
outStr = f[0]
return outStr, nil
@@ -370,7 +378,8 @@ func (parser *Parser) ParseGeneralAPIInfo(mainAPIFile string) error {
if !isGeneralAPIComment(comments) {
continue
}
err := parseGeneralAPIInfo(parser, comments)
err = parseGeneralAPIInfo(parser, comments)
if err != nil {
return err
}
@@ -383,13 +392,15 @@ func parseGeneralAPIInfo(parser *Parser, comments []string) error {
previousAttribute := ""
// parsing classic meta data model
for i, commentLine := range comments {
for line := 0; line < len(comments); line++ {
commentLine := comments[line]
attribute := strings.Split(commentLine, " ")[0]
value := strings.TrimSpace(commentLine[len(attribute):])
multilineBlock := false
if previousAttribute == attribute {
multilineBlock = true
}
switch strings.ToLower(attribute) {
case versionAttr:
parser.swagger.Info.Version = value
@@ -401,12 +412,14 @@ func parseGeneralAPIInfo(parser *Parser, comments []string) error {
continue
}
parser.swagger.Info.Description = value
case "@description.markdown":
commentInfo, err := getMarkdownForTag("api", parser.markdownFileDir)
if err != nil {
return err
}
parser.swagger.Info.Description = string(commentInfo)
case "@termsofservice":
parser.swagger.Info.TermsOfService = value
@@ -450,57 +463,67 @@ func parseGeneralAPIInfo(parser *Parser, comments []string) error {
replaceLastTag(parser.swagger.Tags, tag)
case "@tag.description.markdown":
tag := parser.swagger.Tags[len(parser.swagger.Tags)-1]
commentInfo, err := getMarkdownForTag(tag.TagProps.Name, parser.markdownFileDir)
if err != nil {
return err
}
tag.TagProps.Description = string(commentInfo)
replaceLastTag(parser.swagger.Tags, tag)
case "@tag.docs.url":
tag := parser.swagger.Tags[len(parser.swagger.Tags)-1]
tag.TagProps.ExternalDocs = &spec.ExternalDocumentation{
URL: value,
URL: value,
Description: "",
}
replaceLastTag(parser.swagger.Tags, tag)
case "@tag.docs.description":
tag := parser.swagger.Tags[len(parser.swagger.Tags)-1]
if tag.TagProps.ExternalDocs == nil {
return fmt.Errorf("%s needs to come after a @tags.docs.url", attribute)
}
tag.TagProps.ExternalDocs.Description = value
replaceLastTag(parser.swagger.Tags, tag)
case "@securitydefinitions.basic":
parser.swagger.SecurityDefinitions[value] = spec.BasicAuth()
case "@securitydefinitions.apikey":
attrMap, _, _, err := parseSecAttr(attribute, []string{"@in", "@name"}, comments[i+1:])
attrMap, _, extensions, err := parseSecAttr(attribute, []string{"@in", "@name"}, comments, &line)
if err != nil {
return err
}
parser.swagger.SecurityDefinitions[value] = spec.APIKeyAuth(attrMap["@name"], attrMap["@in"])
parser.swagger.SecurityDefinitions[value] = tryAddDescription(spec.APIKeyAuth(attrMap["@name"], attrMap["@in"]), extensions)
case "@securitydefinitions.oauth2.application":
attrMap, scopes, extensions, err := parseSecAttr(attribute, []string{"@tokenurl"}, comments[i+1:])
attrMap, scopes, extensions, err := parseSecAttr(attribute, []string{"@tokenurl"}, comments, &line)
if err != nil {
return err
}
parser.swagger.SecurityDefinitions[value] = secOAuth2Application(attrMap["@tokenurl"], scopes, extensions)
parser.swagger.SecurityDefinitions[value] = tryAddDescription(secOAuth2Application(attrMap["@tokenurl"], scopes, extensions), extensions)
case "@securitydefinitions.oauth2.implicit":
attrs, scopes, ext, err := parseSecAttr(attribute, []string{"@authorizationurl"}, comments[i+1:])
attrs, scopes, ext, err := parseSecAttr(attribute, []string{"@authorizationurl"}, comments, &line)
if err != nil {
return err
}
parser.swagger.SecurityDefinitions[value] = secOAuth2Implicit(attrs["@authorizationurl"], scopes, ext)
parser.swagger.SecurityDefinitions[value] = tryAddDescription(secOAuth2Implicit(attrs["@authorizationurl"], scopes, ext), ext)
case "@securitydefinitions.oauth2.password":
attrs, scopes, ext, err := parseSecAttr(attribute, []string{"@tokenurl"}, comments[i+1:])
attrs, scopes, ext, err := parseSecAttr(attribute, []string{"@tokenurl"}, comments, &line)
if err != nil {
return err
}
parser.swagger.SecurityDefinitions[value] = secOAuth2Password(attrs["@tokenurl"], scopes, ext)
parser.swagger.SecurityDefinitions[value] = tryAddDescription(secOAuth2Password(attrs["@tokenurl"], scopes, ext), ext)
case "@securitydefinitions.oauth2.accesscode":
attrs, scopes, ext, err := parseSecAttr(attribute, []string{"@tokenurl", "@authorizationurl"}, comments[i+1:])
attrs, scopes, ext, err := parseSecAttr(attribute, []string{"@tokenurl", "@authorizationurl"}, comments, &line)
if err != nil {
return err
}
parser.swagger.SecurityDefinitions[value] = secOAuth2AccessToken(attrs["@authorizationurl"], attrs["@tokenurl"], scopes, ext)
parser.swagger.SecurityDefinitions[value] = tryAddDescription(secOAuth2AccessToken(attrs["@authorizationurl"], attrs["@tokenurl"], scopes, ext), ext)
case "@query.collection.format":
parser.collectionFormatInQuery = value
default:
@@ -517,17 +540,21 @@ func parseGeneralAPIInfo(parser *Parser, comments []string) error {
break
}
}
// if it is present on security def, don't add it again
if extExistsInSecurityDef {
break
}
var valueJSON interface{}
split := strings.SplitAfter(commentLine, attribute+" ")
if len(split) < 2 {
return fmt.Errorf("annotation %s need a value", attribute)
}
extensionName := "x-" + strings.SplitAfter(attribute, prefixExtension)[1]
err := json.Unmarshal([]byte(split[1]), &valueJSON)
if err != nil {
return fmt.Errorf("annotation %s need a valid json value", attribute)
@@ -539,16 +566,28 @@ func parseGeneralAPIInfo(parser *Parser, comments []string) error {
if parser.swagger.Extensions == nil {
parser.swagger.Extensions = make(map[string]interface{})
}
parser.swagger.Extensions[attribute[1:]] = valueJSON
}
}
}
previousAttribute = attribute
}
return nil
}
func tryAddDescription(spec *spec.SecurityScheme, extensions map[string]interface{}) *spec.SecurityScheme {
if val, ok := extensions["@description"]; ok {
if str, ok := val.(string); ok {
spec.Description = str
}
}
return spec
}
// ParseAcceptComment parses comment for given `accept` comment string.
func (parser *Parser) ParseAcceptComment(commentLine string) error {
return parseMimeTypeList(commentLine, &parser.swagger.Consumes, "%v accept type can't be accepted")
@@ -572,11 +611,17 @@ func isGeneralAPIComment(comments []string) bool {
return true
}
func parseSecAttr(context string, search []string, lines []string) (map[string]string, map[string]string, map[string]interface{}, error) {
func parseSecAttr(context string, search []string, lines []string, index *int) (map[string]string, map[string]string, map[string]interface{}, error) {
attrMap := map[string]string{}
scopes := map[string]string{}
extensions := map[string]interface{}{}
for _, v := range lines {
// For the first line we get the attributes in the context parameter, so we skip to the next one
*index++
for ; *index < len(lines); *index++ {
v := lines[*index]
securityAttr := strings.ToLower(strings.Split(v, " ")[0])
for _, findterm := range search {
if securityAttr == findterm {
@@ -585,19 +630,31 @@ func parseSecAttr(context string, search []string, lines []string) (map[string]s
continue
}
}
isExists, err := isExistsScope(securityAttr)
if err != nil {
return nil, nil, nil, err
}
if isExists {
scopes[securityAttr[len(scopeAttrPrefix):]] = v[len(securityAttr):]
}
if strings.HasPrefix(securityAttr, "@x-") {
// Add the custom attribute without the @
extensions[securityAttr[1:]] = strings.TrimSpace(v[len(securityAttr):])
}
// Not mandatory field
if securityAttr == "@description" {
extensions[securityAttr] = strings.TrimSpace(v[len(securityAttr):])
}
// next securityDefinitions
if strings.Index(securityAttr, "@securitydefinitions.") == 0 {
// Go back to the previous line and break
*index--
break
}
}
@@ -609,8 +666,12 @@ func parseSecAttr(context string, search []string, lines []string) (map[string]s
return attrMap, scopes, extensions, nil
}
func secOAuth2Application(tokenURL string, scopes map[string]string,
extensions map[string]interface{}) *spec.SecurityScheme {
type (
authExtensions map[string]interface{}
authScopes map[string]string
)
func secOAuth2Application(tokenURL string, scopes authScopes, extensions authExtensions) *spec.SecurityScheme {
securityScheme := spec.OAuth2Application(tokenURL)
securityScheme.VendorExtensible.Extensions = handleSecuritySchemaExtensions(extensions)
for scope, description := range scopes {
@@ -620,10 +681,10 @@ func secOAuth2Application(tokenURL string, scopes map[string]string,
return securityScheme
}
func secOAuth2Implicit(authorizationURL string, scopes map[string]string,
extensions map[string]interface{}) *spec.SecurityScheme {
func secOAuth2Implicit(authorizationURL string, scopes authScopes, extensions authExtensions) *spec.SecurityScheme {
securityScheme := spec.OAuth2Implicit(authorizationURL)
securityScheme.VendorExtensible.Extensions = handleSecuritySchemaExtensions(extensions)
for scope, description := range scopes {
securityScheme.AddScope(scope, description)
}
@@ -631,10 +692,10 @@ func secOAuth2Implicit(authorizationURL string, scopes map[string]string,
return securityScheme
}
func secOAuth2Password(tokenURL string, scopes map[string]string,
extensions map[string]interface{}) *spec.SecurityScheme {
func secOAuth2Password(tokenURL string, scopes authScopes, extensions authExtensions) *spec.SecurityScheme {
securityScheme := spec.OAuth2Password(tokenURL)
securityScheme.VendorExtensible.Extensions = handleSecuritySchemaExtensions(extensions)
for scope, description := range scopes {
securityScheme.AddScope(scope, description)
}
@@ -642,10 +703,10 @@ func secOAuth2Password(tokenURL string, scopes map[string]string,
return securityScheme
}
func secOAuth2AccessToken(authorizationURL, tokenURL string,
scopes map[string]string, extensions map[string]interface{}) *spec.SecurityScheme {
func secOAuth2AccessToken(authorizationURL, tokenURL string, scopes authScopes, extensions authExtensions) *spec.SecurityScheme {
securityScheme := spec.OAuth2AccessToken(authorizationURL, tokenURL)
securityScheme.VendorExtensible.Extensions = handleSecuritySchemaExtensions(extensions)
for scope, description := range scopes {
securityScheme.AddScope(scope, description)
}
@@ -653,7 +714,7 @@ func secOAuth2AccessToken(authorizationURL, tokenURL string,
return securityScheme
}
func handleSecuritySchemaExtensions(providedExtensions map[string]interface{}) spec.Extensions {
func handleSecuritySchemaExtensions(providedExtensions authExtensions) spec.Extensions {
var extensions spec.Extensions
if len(providedExtensions) > 0 {
extensions = make(map[string]interface{}, len(providedExtensions))
@@ -675,6 +736,7 @@ func getMarkdownForTag(tagName string, dirPath string) ([]byte, error) {
if fileInfo.IsDir() {
continue
}
fileName := fileInfo.Name()
if !strings.Contains(fileName, ".md") {
@@ -683,6 +745,7 @@ func getMarkdownForTag(tagName string, dirPath string) ([]byte, error) {
if strings.Contains(fileName, tagName) {
fullPath := filepath.Join(dirPath, fileName)
commentInfo, err := ioutil.ReadFile(fullPath)
if err != nil {
return nil, fmt.Errorf("Failed to read markdown file %s error: %s ", fullPath, err)
@@ -729,29 +792,9 @@ func (parser *Parser) ParseRouterAPIInfo(fileName string, astFile *ast.File) err
}
}
for _, routeProperties := range operation.RouterProperties {
var pathItem spec.PathItem
var ok bool
pathItem, ok = parser.swagger.Paths.Paths[routeProperties.Path]
if !ok {
pathItem = spec.PathItem{}
}
op := refRouteMethodOp(&pathItem, routeProperties.HTTPMethod)
// check if we already have a operation for this path and method
if *op != nil {
err := fmt.Errorf("route %s %s is declared multiple times", routeProperties.HTTPMethod, routeProperties.Path)
if parser.Strict {
return err
}
parser.debug.Printf("warning: %s\n", err)
}
*op = &operation.Operation
parser.swagger.Paths.Paths[routeProperties.Path] = pathItem
err := processRouterOperation(parser, operation)
if err != nil {
return err
}
}
}
@@ -776,14 +819,48 @@ func refRouteMethodOp(item *spec.PathItem, method string) (op **spec.Operation)
case http.MethodOptions:
op = &item.Options
}
return
}
func processRouterOperation(parser *Parser, operation *Operation) error {
for _, routeProperties := range operation.RouterProperties {
var (
pathItem spec.PathItem
ok bool
)
pathItem, ok = parser.swagger.Paths.Paths[routeProperties.Path]
if !ok {
pathItem = spec.PathItem{}
}
op := refRouteMethodOp(&pathItem, routeProperties.HTTPMethod)
// check if we already have an operation for this path and method
if *op != nil {
err := fmt.Errorf("route %s %s is declared multiple times", routeProperties.HTTPMethod, routeProperties.Path)
if parser.Strict {
return err
}
parser.debug.Printf("warning: %s\n", err)
}
*op = &operation.Operation
parser.swagger.Paths.Paths[routeProperties.Path] = pathItem
}
return nil
}
func convertFromSpecificToPrimitive(typeName string) (string, error) {
name := typeName
if strings.ContainsRune(name, '.') {
name = strings.Split(name, ".")[1]
}
switch strings.ToUpper(name) {
case "TIME", "OBJECTID", "UUID":
return STRING, nil
@@ -812,6 +889,7 @@ func (parser *Parser) getTypeSchema(typeName string, file *ast.File, ref bool) (
if override, ok := parser.Overrides[typeSpecDef.FullPath()]; ok {
if override == "" {
parser.debug.Printf("Override detected for %s: ignoring", typeSpecDef.FullPath())
return nil, ErrSkippedField
}
@@ -821,6 +899,7 @@ func (parser *Parser) getTypeSchema(typeName string, file *ast.File, ref bool) (
if separator == -1 {
// treat as a swaggertype tag
parts := strings.Split(override, ",")
return BuildCustomSchema(parts)
}
@@ -830,6 +909,7 @@ func (parser *Parser) getTypeSchema(typeName string, file *ast.File, ref bool) (
schema, ok := parser.parsedSchemas[typeSpecDef]
if !ok {
var err error
schema, err = parser.ParseDefinition(typeSpecDef)
if err != nil {
if err == ErrRecursiveParseStruct && ref {
@@ -865,8 +945,10 @@ func (parser *Parser) renameRefSchemas() {
for _, refURL := range parser.toBeRenamedRefURLs {
parts := strings.Split(refURL.Fragment, "/")
name := parts[len(parts)-1]
if pkgPath, ok := parser.toBeRenamedSchemas[name]; ok {
parts[len(parts)-1] = parser.renameSchema(name, pkgPath)
refURL.Fragment = strings.Join(parts, "/")
}
}
@@ -895,6 +977,7 @@ func (parser *Parser) getRefTypeSchema(typeSpecDef *TypeSpecDef, schema *Schema)
} else {
parser.existSchemaNames[schema.Name] = schema
}
parser.swagger.Definitions[schema.Name] = spec.Schema{}
if schema.Schema != nil {
@@ -928,8 +1011,8 @@ func (parser *Parser) ParseDefinition(typeSpecDef *TypeSpecDef) (*Schema, error)
typeName := typeSpecDef.FullName()
refTypeName := TypeDocName(typeName, typeSpecDef.TypeSpec)
schema, ok := parser.parsedSchemas[typeSpecDef]
if ok {
schema, found := parser.parsedSchemas[typeSpecDef]
if found {
parser.debug.Printf("Skipping '%s', already parsed.", typeName)
return schema, nil
@@ -945,6 +1028,7 @@ func (parser *Parser) ParseDefinition(typeSpecDef *TypeSpecDef) (*Schema, error)
},
ErrRecursiveParseStruct
}
parser.structStack = append(parser.structStack, typeSpecDef)
parser.debug.Printf("Generating %s", typeName)
@@ -958,20 +1042,20 @@ func (parser *Parser) ParseDefinition(typeSpecDef *TypeSpecDef) (*Schema, error)
fillDefinitionDescription(definition, typeSpecDef.File, typeSpecDef)
}
s := Schema{
sch := Schema{
Name: refTypeName,
PkgPath: typeSpecDef.PkgPath,
Schema: definition,
}
parser.parsedSchemas[typeSpecDef] = &s
parser.parsedSchemas[typeSpecDef] = &sch
// update an empty schema as a result of recursion
s2, ok := parser.outputSchemas[typeSpecDef]
if ok {
s2, found := parser.outputSchemas[typeSpecDef]
if found {
parser.swagger.Definitions[s2.Name] = *definition
}
return &s, nil
return &sch, nil
}
func fullTypeName(pkgName, typeName string) string {
@@ -1014,13 +1098,16 @@ func extractDeclarationDescription(commentGroups ...*ast.CommentGroup) string {
}
isHandlingDescription := false
for _, comment := range commentGroup.List {
commentText := strings.TrimSpace(strings.TrimLeft(comment.Text, "/"))
attribute := strings.Split(commentText, " ")[0]
if strings.ToLower(attribute) != descriptionAttr {
if !isHandlingDescription {
continue
}
break
}
@@ -1088,8 +1175,8 @@ func (parser *Parser) parseTypeExpr(file *ast.File, typeExpr ast.Expr, ref bool)
}
func (parser *Parser) parseStruct(file *ast.File, fields *ast.FieldList) (*spec.Schema, error) {
required := make([]string, 0)
properties := make(map[string]spec.Schema)
required, properties := make([]string, 0), make(map[string]spec.Schema)
for _, field := range fields.List {
fieldProps, requiredFromAnon, err := parser.parseStructField(file, field)
if err != nil {
@@ -1099,10 +1186,13 @@ func (parser *Parser) parseStruct(file *ast.File, fields *ast.FieldList) (*spec.
return nil, err
}
if len(fieldProps) == 0 {
continue
}
required = append(required, requiredFromAnon...)
for k, v := range fieldProps {
properties[k] = v
}
@@ -1132,10 +1222,12 @@ func (parser *Parser) parseStructField(file *ast.File, field *ast.Field) (map[st
if err != nil {
return nil, nil, err
}
schema, err := parser.getTypeSchema(typeName, file, false)
if err != nil {
return nil, nil, err
}
if len(schema.Type) > 0 && schema.Type[0] == OBJECT {
if len(schema.Properties) == 0 {
return nil, nil, nil
@@ -1155,11 +1247,7 @@ func (parser *Parser) parseStructField(file *ast.File, field *ast.Field) (map[st
ps := parser.fieldParserFactory(parser, field)
ok, err := ps.ShouldSkip()
if err != nil {
return nil, nil, err
}
if ok {
if ps.ShouldSkip() {
return nil, nil, nil
}
@@ -1172,6 +1260,7 @@ func (parser *Parser) parseStructField(file *ast.File, field *ast.Field) (map[st
if err != nil {
return nil, nil, err
}
if schema == nil {
typeName, err := getFieldType(field.Type)
if err == nil {
@@ -1181,6 +1270,7 @@ func (parser *Parser) parseStructField(file *ast.File, field *ast.Field) (map[st
// unnamed type
schema, err = parser.parseTypeExpr(file, field.Type, false)
}
if err != nil {
return nil, nil, err
}
@@ -1192,10 +1282,12 @@ func (parser *Parser) parseStructField(file *ast.File, field *ast.Field) (map[st
}
var tagRequired []string
required, err := ps.IsRequired()
if err != nil {
return nil, nil, err
}
if required {
tagRequired = append(tagRequired, fieldName)
}
@@ -1214,7 +1306,6 @@ func getFieldType(field ast.Expr) (string, error) {
}
return fullTypeName(packageName, fieldType.Sel.Name), nil
case *ast.StarExpr:
fullName, err := getFieldType(fieldType.X)
if err != nil {
@@ -1232,6 +1323,7 @@ func (parser *Parser) GetSchemaTypePath(schema *spec.Schema, depth int) []string
if schema == nil || depth == 0 {
return nil
}
name := schema.Ref.String()
if name != "" {
if pos := strings.LastIndexByte(name, '/'); pos >= 0 {
@@ -1243,10 +1335,12 @@ func (parser *Parser) GetSchemaTypePath(schema *spec.Schema, depth int) []string
return nil
}
if len(schema.Type) > 0 {
switch schema.Type[0] {
case ARRAY:
depth--
s := []string{schema.Type[0]}
return append(s, parser.GetSchemaTypePath(schema.Items.Schema, depth)...)
@@ -1254,6 +1348,7 @@ func (parser *Parser) GetSchemaTypePath(schema *spec.Schema, depth int) []string
if schema.AdditionalProperties != nil && schema.AdditionalProperties.Schema != nil {
// for map
depth--
s := []string{schema.Type[0]}
return append(s, parser.GetSchemaTypePath(schema.AdditionalProperties.Schema, depth)...)
@@ -1304,6 +1399,7 @@ func defineTypeOfExample(schemaType, arrayType, exampleValue string) (interface{
if err != nil {
return nil, err
}
result = append(result, v)
}
@@ -1314,7 +1410,9 @@ func defineTypeOfExample(schemaType, arrayType, exampleValue string) (interface{
}
values := strings.Split(exampleValue, ",")
result := map[string]interface{}{}
for _, value := range values {
mapData := strings.Split(value, ":")
@@ -1323,10 +1421,14 @@ func defineTypeOfExample(schemaType, arrayType, exampleValue string) (interface{
if err != nil {
return nil, err
}
result[mapData[0]] = v
} else {
return nil, fmt.Errorf("example value %s should format: key:value", exampleValue)
continue
}
return nil, fmt.Errorf("example value %s should format: key:value", exampleValue)
}
return result, nil
@@ -1338,9 +1440,12 @@ func defineTypeOfExample(schemaType, arrayType, exampleValue string) (interface{
// GetAllGoFileInfo gets all Go source files information for given searchDir.
func (parser *Parser) getAllGoFileInfo(packageDir, searchDir string) error {
return filepath.Walk(searchDir, func(path string, f os.FileInfo, _ error) error {
if err := parser.Skip(path, f); err != nil {
err := parser.Skip(path, f)
if err != nil {
return err
} else if f.IsDir() {
}
if f.IsDir() {
return nil
}
@@ -1363,7 +1468,9 @@ func (parser *Parser) getAllGoFileInfoFromDeps(pkg *depth.Pkg) error {
if pkg.Raw == nil && pkg.Name == "C" {
return nil
}
srcDir := pkg.Raw.Dir
files, err := ioutil.ReadDir(srcDir) // only parsing files in the dir(don't contain sub dir files)
if err != nil {
return err
@@ -1414,24 +1521,29 @@ func (parser *Parser) checkOperationIDUniqueness() error {
for path, item := range parser.swagger.Paths.Paths {
var method, id string
for method = range allMethod {
op := refRouteMethodOp(&item, method)
if *op != nil {
id = (**op).ID
break
}
}
if id == "" {
continue
}
current := fmt.Sprintf("%s %s", method, path)
previous, ok := operationsIds[id]
if ok {
return fmt.Errorf(
"duplicated @id annotation '%s' found in '%s', previously declared in: '%s'",
id, current, previous)
}
operationsIds[id] = current
}

View File

@@ -26,6 +26,8 @@ const (
STRING = "string"
// FUNC represent a function value.
FUNC = "func"
// INTERFACE represent a interface value.
INTERFACE = "interface{}"
// ANY represent a any value.
ANY = "any"
// NIL represent a empty value.
@@ -104,7 +106,8 @@ func IsGolangPrimitiveType(typeName string) bool {
"float32",
"float64",
"bool",
"string":
"string",
"any":
return true
}
@@ -132,6 +135,7 @@ func TypeDocName(pkgName string, spec *ast.TypeSpec) string {
}
}
}
if spec.Name != nil {
return fullTypeName(strings.Split(pkgName, ".")[0], spec.Name.Name)
}
@@ -167,6 +171,7 @@ func BuildCustomSchema(types []string) (*spec.Schema, error) {
if len(types) == 1 {
return nil, errors.New("need array item type after array")
}
schema, err := BuildCustomSchema(types[1:])
if err != nil {
return nil, err
@@ -177,6 +182,7 @@ func BuildCustomSchema(types []string) (*spec.Schema, error) {
if len(types) == 1 {
return PrimitiveSchema(types[0]), nil
}
schema, err := BuildCustomSchema(types[1:])
if err != nil {
return nil, err

View File

@@ -21,31 +21,33 @@ type Spec struct {
// ReadDoc parses SwaggerTemplate into swagger document.
func (i *Spec) ReadDoc() string {
i.Description = strings.Replace(i.Description, "\n", "\\n", -1)
i.Description = strings.ReplaceAll(i.Description, "\n", "\\n")
t, err := template.New("swagger_info").Funcs(template.FuncMap{
tpl, err := template.New("swagger_info").Funcs(template.FuncMap{
"marshal": func(v interface{}) string {
a, _ := json.Marshal(v)
return string(a)
},
"escape": func(v interface{}) string {
// escape tabs
str := strings.Replace(v.(string), "\t", "\\t", -1)
var str = strings.ReplaceAll(v.(string), "\t", "\\t")
// replace " with \", and if that results in \\", replace that with \\\"
str = strings.Replace(str, "\"", "\\\"", -1)
return strings.Replace(str, "\\\\\"", "\\\\\\\"", -1)
str = strings.ReplaceAll(str, "\"", "\\\"")
return strings.ReplaceAll(str, "\\\\\"", "\\\\\\\"")
},
}).Parse(i.SwaggerTemplate)
if err != nil {
return i.SwaggerTemplate
}
var tpl bytes.Buffer
if err = t.Execute(&tpl, i); err != nil {
var doc bytes.Buffer
if err = tpl.Execute(&doc, i); err != nil {
return i.SwaggerTemplate
}
return tpl.String()
return doc.String()
}
// InstanceName returns Spec instance name.

View File

@@ -23,6 +23,7 @@ type Swagger interface {
func Register(name string, swagger Swagger) {
swaggerMu.Lock()
defer swaggerMu.Unlock()
if swagger == nil {
panic("swagger is nil")
}
@@ -34,6 +35,7 @@ func Register(name string, swagger Swagger) {
if _, ok := swags[name]; ok {
panic("Register called twice for swag: " + name)
}
swags[name] = swagger
}

View File

@@ -1,4 +1,4 @@
package swag
// Version of swag.
const Version = "v1.8.0"
const Version = "v1.8.1"