forked from ebhomengo/niki
1
0
Fork 0
niki/vendor/github.com/swaggo/swag/operation.go

2020 lines
34 KiB
Go
Raw Normal View History

2024-05-14 13:07:09 +00:00
package swag
import (
"encoding/json"
"fmt"
"go/ast"
goparser "go/parser"
"go/token"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/go-openapi/spec"
"golang.org/x/tools/go/loader"
)
// RouteProperties describes HTTP properties of a single router comment.
2024-05-14 13:07:09 +00:00
type RouteProperties struct {
HTTPMethod string
Path string
2024-05-14 13:07:09 +00:00
Deprecated bool
}
// Operation describes a single API operation on a path.
2024-05-14 13:07:09 +00:00
// For more information: https://github.com/swaggo/swag#api-operation
2024-05-14 13:07:09 +00:00
type Operation struct {
parser *Parser
2024-05-14 13:07:09 +00:00
codeExampleFilesDir string
2024-05-14 13:07:09 +00:00
spec.Operation
2024-05-14 13:07:09 +00:00
RouterProperties []RouteProperties
State string
2024-05-14 13:07:09 +00:00
}
var mimeTypeAliases = map[string]string{
"json": "application/json",
"xml": "text/xml",
"plain": "text/plain",
"html": "text/html",
"mpfd": "multipart/form-data",
2024-05-14 13:07:09 +00:00
"x-www-form-urlencoded": "application/x-www-form-urlencoded",
"json-api": "application/vnd.api+json",
"json-stream": "application/x-json-stream",
"octet-stream": "application/octet-stream",
"png": "image/png",
"jpeg": "image/jpeg",
"gif": "image/gif",
2024-05-14 13:07:09 +00:00
}
var mimeTypePattern = regexp.MustCompile("^[^/]+/[^/]+$")
// NewOperation creates a new Operation with default properties.
2024-05-14 13:07:09 +00:00
// map[int]Response.
2024-05-14 13:07:09 +00:00
func NewOperation(parser *Parser, options ...func(*Operation)) *Operation {
2024-05-14 13:07:09 +00:00
if parser == nil {
2024-05-14 13:07:09 +00:00
parser = New()
2024-05-14 13:07:09 +00:00
}
result := &Operation{
parser: parser,
2024-05-14 13:07:09 +00:00
RouterProperties: []RouteProperties{},
2024-05-14 13:07:09 +00:00
Operation: spec.Operation{
2024-05-14 13:07:09 +00:00
OperationProps: spec.OperationProps{
ID: "",
Description: "",
Summary: "",
Security: nil,
2024-05-14 13:07:09 +00:00
ExternalDocs: nil,
Deprecated: false,
Tags: []string{},
Consumes: []string{},
Produces: []string{},
Schemes: []string{},
Parameters: []spec.Parameter{},
2024-05-14 13:07:09 +00:00
Responses: &spec.Responses{
2024-05-14 13:07:09 +00:00
VendorExtensible: spec.VendorExtensible{
2024-05-14 13:07:09 +00:00
Extensions: spec.Extensions{},
},
2024-05-14 13:07:09 +00:00
ResponsesProps: spec.ResponsesProps{
Default: nil,
2024-05-14 13:07:09 +00:00
StatusCodeResponses: make(map[int]spec.Response),
},
},
},
2024-05-14 13:07:09 +00:00
VendorExtensible: spec.VendorExtensible{
2024-05-14 13:07:09 +00:00
Extensions: spec.Extensions{},
},
},
2024-05-14 13:07:09 +00:00
codeExampleFilesDir: "",
}
for _, option := range options {
2024-05-14 13:07:09 +00:00
option(result)
2024-05-14 13:07:09 +00:00
}
return result
2024-05-14 13:07:09 +00:00
}
// SetCodeExampleFilesDirectory sets the directory to search for codeExamples.
2024-05-14 13:07:09 +00:00
func SetCodeExampleFilesDirectory(directoryPath string) func(*Operation) {
2024-05-14 13:07:09 +00:00
return func(o *Operation) {
2024-05-14 13:07:09 +00:00
o.codeExampleFilesDir = directoryPath
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
// ParseComment parses comment for given comment string and returns error if error occurs.
2024-05-14 13:07:09 +00:00
func (operation *Operation) ParseComment(comment string, astFile *ast.File) error {
2024-05-14 13:07:09 +00:00
commentLine := strings.TrimSpace(strings.TrimLeft(comment, "/"))
2024-05-14 13:07:09 +00:00
if len(commentLine) == 0 {
2024-05-14 13:07:09 +00:00
return nil
2024-05-14 13:07:09 +00:00
}
fields := FieldsByAnySpace(commentLine, 2)
2024-05-14 13:07:09 +00:00
attribute := fields[0]
2024-05-14 13:07:09 +00:00
lowerAttribute := strings.ToLower(attribute)
2024-05-14 13:07:09 +00:00
var lineRemainder string
2024-05-14 13:07:09 +00:00
if len(fields) > 1 {
2024-05-14 13:07:09 +00:00
lineRemainder = fields[1]
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
switch lowerAttribute {
2024-05-14 13:07:09 +00:00
case stateAttr:
2024-05-14 13:07:09 +00:00
operation.ParseStateComment(lineRemainder)
2024-05-14 13:07:09 +00:00
case descriptionAttr:
2024-05-14 13:07:09 +00:00
operation.ParseDescriptionComment(lineRemainder)
2024-05-14 13:07:09 +00:00
case descriptionMarkdownAttr:
2024-05-14 13:07:09 +00:00
commentInfo, err := getMarkdownForTag(lineRemainder, operation.parser.markdownFileDir)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return err
2024-05-14 13:07:09 +00:00
}
operation.ParseDescriptionComment(string(commentInfo))
2024-05-14 13:07:09 +00:00
case summaryAttr:
2024-05-14 13:07:09 +00:00
operation.Summary = lineRemainder
2024-05-14 13:07:09 +00:00
case idAttr:
2024-05-14 13:07:09 +00:00
operation.ID = lineRemainder
2024-05-14 13:07:09 +00:00
case tagsAttr:
2024-05-14 13:07:09 +00:00
operation.ParseTagsComment(lineRemainder)
2024-05-14 13:07:09 +00:00
case acceptAttr:
2024-05-14 13:07:09 +00:00
return operation.ParseAcceptComment(lineRemainder)
2024-05-14 13:07:09 +00:00
case produceAttr:
2024-05-14 13:07:09 +00:00
return operation.ParseProduceComment(lineRemainder)
2024-05-14 13:07:09 +00:00
case paramAttr:
2024-05-14 13:07:09 +00:00
return operation.ParseParamComment(lineRemainder, astFile)
2024-05-14 13:07:09 +00:00
case successAttr, failureAttr, responseAttr:
2024-05-14 13:07:09 +00:00
return operation.ParseResponseComment(lineRemainder, astFile)
2024-05-14 13:07:09 +00:00
case headerAttr:
2024-05-14 13:07:09 +00:00
return operation.ParseResponseHeaderComment(lineRemainder, astFile)
2024-05-14 13:07:09 +00:00
case routerAttr:
2024-05-14 13:07:09 +00:00
return operation.ParseRouterComment(lineRemainder, false)
2024-05-14 13:07:09 +00:00
case deprecatedRouterAttr:
2024-05-14 13:07:09 +00:00
return operation.ParseRouterComment(lineRemainder, true)
2024-05-14 13:07:09 +00:00
case securityAttr:
2024-05-14 13:07:09 +00:00
return operation.ParseSecurityComment(lineRemainder)
2024-05-14 13:07:09 +00:00
case deprecatedAttr:
2024-05-14 13:07:09 +00:00
operation.Deprecate()
2024-05-14 13:07:09 +00:00
case xCodeSamplesAttr:
2024-05-14 13:07:09 +00:00
return operation.ParseCodeSample(attribute, commentLine, lineRemainder)
2024-05-14 13:07:09 +00:00
default:
2024-05-14 13:07:09 +00:00
return operation.ParseMetadata(attribute, lowerAttribute, lineRemainder)
2024-05-14 13:07:09 +00:00
}
return nil
2024-05-14 13:07:09 +00:00
}
// ParseCodeSample parse code sample.
2024-05-14 13:07:09 +00:00
func (operation *Operation) ParseCodeSample(attribute, _, lineRemainder string) error {
2024-05-14 13:07:09 +00:00
if lineRemainder == "file" {
2024-05-14 13:07:09 +00:00
data, err := getCodeExampleForSummary(operation.Summary, operation.codeExampleFilesDir)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return err
2024-05-14 13:07:09 +00:00
}
var valueJSON interface{}
err = json.Unmarshal(data, &valueJSON)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return fmt.Errorf("annotation %s need a valid json value", attribute)
2024-05-14 13:07:09 +00:00
}
// don't use the method provided by spec lib, because it will call toLower() on attribute names, which is wrongly
2024-05-14 13:07:09 +00:00
operation.Extensions[attribute[1:]] = valueJSON
return nil
2024-05-14 13:07:09 +00:00
}
// Fallback into existing logic
2024-05-14 13:07:09 +00:00
return operation.ParseMetadata(attribute, strings.ToLower(attribute), lineRemainder)
2024-05-14 13:07:09 +00:00
}
// ParseStateComment parse state comment.
2024-05-14 13:07:09 +00:00
func (operation *Operation) ParseStateComment(lineRemainder string) {
2024-05-14 13:07:09 +00:00
operation.State = lineRemainder
2024-05-14 13:07:09 +00:00
}
// ParseDescriptionComment parse description comment.
2024-05-14 13:07:09 +00:00
func (operation *Operation) ParseDescriptionComment(lineRemainder string) {
2024-05-14 13:07:09 +00:00
if operation.Description == "" {
2024-05-14 13:07:09 +00:00
operation.Description = lineRemainder
return
2024-05-14 13:07:09 +00:00
}
operation.Description += "\n" + lineRemainder
2024-05-14 13:07:09 +00:00
}
// ParseMetadata parse metadata.
2024-05-14 13:07:09 +00:00
func (operation *Operation) ParseMetadata(attribute, lowerAttribute, lineRemainder string) error {
2024-05-14 13:07:09 +00:00
// parsing specific meta data extensions
2024-05-14 13:07:09 +00:00
if strings.HasPrefix(lowerAttribute, "@x-") {
2024-05-14 13:07:09 +00:00
if len(lineRemainder) == 0 {
2024-05-14 13:07:09 +00:00
return fmt.Errorf("annotation %s need a value", attribute)
2024-05-14 13:07:09 +00:00
}
var valueJSON interface{}
err := json.Unmarshal([]byte(lineRemainder), &valueJSON)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return fmt.Errorf("annotation %s need a valid json value", attribute)
2024-05-14 13:07:09 +00:00
}
// don't use the method provided by spec lib, because it will call toLower() on attribute names, which is wrongly
2024-05-14 13:07:09 +00:00
operation.Extensions[attribute[1:]] = valueJSON
2024-05-14 13:07:09 +00:00
}
return nil
2024-05-14 13:07:09 +00:00
}
var paramPattern = regexp.MustCompile(`(\S+)\s+(\w+)\s+([\S. ]+?)\s+(\w+)\s+"([^"]+)"`)
func findInSlice(arr []string, target string) bool {
2024-05-14 13:07:09 +00:00
for _, str := range arr {
2024-05-14 13:07:09 +00:00
if str == target {
2024-05-14 13:07:09 +00:00
return true
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
return false
2024-05-14 13:07:09 +00:00
}
// ParseParamComment parses params return []string of param properties
2024-05-14 13:07:09 +00:00
// E.g. @Param queryText formData string true "The email for login"
2024-05-14 13:07:09 +00:00
//
2024-05-14 13:07:09 +00:00
// [param name] [paramType] [data type] [is mandatory?] [Comment]
2024-05-14 13:07:09 +00:00
//
2024-05-14 13:07:09 +00:00
// E.g. @Param some_id path int true "Some ID".
2024-05-14 13:07:09 +00:00
func (operation *Operation) ParseParamComment(commentLine string, astFile *ast.File) error {
2024-05-14 13:07:09 +00:00
matches := paramPattern.FindStringSubmatch(commentLine)
2024-05-14 13:07:09 +00:00
if len(matches) != 6 {
2024-05-14 13:07:09 +00:00
return fmt.Errorf("missing required param comment parameters \"%s\"", commentLine)
2024-05-14 13:07:09 +00:00
}
name := matches[1]
2024-05-14 13:07:09 +00:00
paramType := matches[2]
2024-05-14 13:07:09 +00:00
refType := TransToValidSchemeType(matches[3])
// Detect refType
2024-05-14 13:07:09 +00:00
objectType := OBJECT
if strings.HasPrefix(refType, "[]") {
2024-05-14 13:07:09 +00:00
objectType = ARRAY
2024-05-14 13:07:09 +00:00
refType = strings.TrimPrefix(refType, "[]")
2024-05-14 13:07:09 +00:00
refType = TransToValidSchemeType(refType)
2024-05-14 13:07:09 +00:00
} else if IsPrimitiveType(refType) ||
2024-05-14 13:07:09 +00:00
paramType == "formData" && refType == "file" {
2024-05-14 13:07:09 +00:00
objectType = PRIMITIVE
2024-05-14 13:07:09 +00:00
}
var enums []interface{}
2024-05-14 13:07:09 +00:00
if !IsPrimitiveType(refType) {
2024-05-14 13:07:09 +00:00
schema, _ := operation.parser.getTypeSchema(refType, astFile, false)
2024-05-14 13:07:09 +00:00
if schema != nil && len(schema.Type) == 1 && schema.Enum != nil {
2024-05-14 13:07:09 +00:00
if objectType == OBJECT {
2024-05-14 13:07:09 +00:00
objectType = PRIMITIVE
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
refType = TransToValidSchemeType(schema.Type[0])
2024-05-14 13:07:09 +00:00
enums = schema.Enum
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
requiredText := strings.ToLower(matches[4])
2024-05-14 13:07:09 +00:00
required := requiredText == "true" || requiredText == requiredLabel
2024-05-14 13:07:09 +00:00
description := matches[5]
param := createParameter(paramType, description, name, objectType, refType, required, enums, operation.parser.collectionFormatInQuery)
switch paramType {
2024-05-14 13:07:09 +00:00
case "path", "header", "query", "formData":
2024-05-14 13:07:09 +00:00
switch objectType {
2024-05-14 13:07:09 +00:00
case ARRAY:
2024-05-14 13:07:09 +00:00
if !IsPrimitiveType(refType) && !(refType == "file" && paramType == "formData") {
2024-05-14 13:07:09 +00:00
return fmt.Errorf("%s is not supported array type for %s", refType, paramType)
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
case PRIMITIVE:
2024-05-14 13:07:09 +00:00
break
2024-05-14 13:07:09 +00:00
case OBJECT:
2024-05-14 13:07:09 +00:00
schema, err := operation.parser.getTypeSchema(refType, astFile, false)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return err
2024-05-14 13:07:09 +00:00
}
if len(schema.Properties) == 0 {
2024-05-14 13:07:09 +00:00
return nil
2024-05-14 13:07:09 +00:00
}
items := schema.Properties.ToOrderedSchemaItems()
for _, item := range items {
2024-05-14 13:07:09 +00:00
name, prop := item.Name, &item.Schema
2024-05-14 13:07:09 +00:00
if len(prop.Type) == 0 {
2024-05-14 13:07:09 +00:00
prop = operation.parser.getUnderlyingSchema(prop)
2024-05-14 13:07:09 +00:00
if len(prop.Type) == 0 {
2024-05-14 13:07:09 +00:00
continue
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
nameOverrideType := paramType
2024-05-14 13:07:09 +00:00
// query also uses formData tags
2024-05-14 13:07:09 +00:00
if paramType == "query" {
2024-05-14 13:07:09 +00:00
nameOverrideType = "formData"
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
// load overridden type specific name from extensions if exists
2024-05-14 13:07:09 +00:00
if nameVal, ok := item.Schema.Extensions[nameOverrideType]; ok {
2024-05-14 13:07:09 +00:00
name = nameVal.(string)
2024-05-14 13:07:09 +00:00
}
switch {
2024-05-14 13:07:09 +00:00
case prop.Type[0] == ARRAY:
2024-05-14 13:07:09 +00:00
if prop.Items.Schema == nil {
2024-05-14 13:07:09 +00:00
continue
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
itemSchema := prop.Items.Schema
2024-05-14 13:07:09 +00:00
if len(itemSchema.Type) == 0 {
2024-05-14 13:07:09 +00:00
itemSchema = operation.parser.getUnderlyingSchema(prop.Items.Schema)
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
if len(itemSchema.Type) == 0 {
2024-05-14 13:07:09 +00:00
continue
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
if !IsSimplePrimitiveType(itemSchema.Type[0]) {
2024-05-14 13:07:09 +00:00
continue
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
param = createParameter(paramType, prop.Description, name, prop.Type[0], itemSchema.Type[0], findInSlice(schema.Required, item.Name), itemSchema.Enum, operation.parser.collectionFormatInQuery)
case IsSimplePrimitiveType(prop.Type[0]):
2024-05-14 13:07:09 +00:00
param = createParameter(paramType, prop.Description, name, PRIMITIVE, prop.Type[0], findInSlice(schema.Required, item.Name), nil, operation.parser.collectionFormatInQuery)
2024-05-14 13:07:09 +00:00
default:
2024-05-14 13:07:09 +00:00
operation.parser.debug.Printf("skip field [%s] in %s is not supported type for %s", name, refType, paramType)
2024-05-14 13:07:09 +00:00
continue
2024-05-14 13:07:09 +00:00
}
param.Nullable = prop.Nullable
2024-05-14 13:07:09 +00:00
param.Format = prop.Format
2024-05-14 13:07:09 +00:00
param.Default = prop.Default
2024-05-14 13:07:09 +00:00
param.Example = prop.Example
2024-05-14 13:07:09 +00:00
param.Extensions = prop.Extensions
2024-05-14 13:07:09 +00:00
param.CommonValidations.Maximum = prop.Maximum
2024-05-14 13:07:09 +00:00
param.CommonValidations.Minimum = prop.Minimum
2024-05-14 13:07:09 +00:00
param.CommonValidations.ExclusiveMaximum = prop.ExclusiveMaximum
2024-05-14 13:07:09 +00:00
param.CommonValidations.ExclusiveMinimum = prop.ExclusiveMinimum
2024-05-14 13:07:09 +00:00
param.CommonValidations.MaxLength = prop.MaxLength
2024-05-14 13:07:09 +00:00
param.CommonValidations.MinLength = prop.MinLength
2024-05-14 13:07:09 +00:00
param.CommonValidations.Pattern = prop.Pattern
2024-05-14 13:07:09 +00:00
param.CommonValidations.MaxItems = prop.MaxItems
2024-05-14 13:07:09 +00:00
param.CommonValidations.MinItems = prop.MinItems
2024-05-14 13:07:09 +00:00
param.CommonValidations.UniqueItems = prop.UniqueItems
2024-05-14 13:07:09 +00:00
param.CommonValidations.MultipleOf = prop.MultipleOf
2024-05-14 13:07:09 +00:00
param.CommonValidations.Enum = prop.Enum
2024-05-14 13:07:09 +00:00
operation.Operation.Parameters = append(operation.Operation.Parameters, param)
2024-05-14 13:07:09 +00:00
}
return nil
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
case "body":
2024-05-14 13:07:09 +00:00
if objectType == PRIMITIVE {
2024-05-14 13:07:09 +00:00
param.Schema = PrimitiveSchema(refType)
2024-05-14 13:07:09 +00:00
} else {
2024-05-14 13:07:09 +00:00
schema, err := operation.parseAPIObjectSchema(commentLine, objectType, refType, astFile)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return err
2024-05-14 13:07:09 +00:00
}
param.Schema = schema
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
default:
2024-05-14 13:07:09 +00:00
return fmt.Errorf("%s is not supported paramType", paramType)
2024-05-14 13:07:09 +00:00
}
err := operation.parseParamAttribute(commentLine, objectType, refType, paramType, &param)
if err != nil {
2024-05-14 13:07:09 +00:00
return err
2024-05-14 13:07:09 +00:00
}
operation.Operation.Parameters = append(operation.Operation.Parameters, param)
return nil
2024-05-14 13:07:09 +00:00
}
const (
formTag = "form"
jsonTag = "json"
uriTag = "uri"
headerTag = "header"
bindingTag = "binding"
defaultTag = "default"
enumsTag = "enums"
exampleTag = "example"
schemaExampleTag = "schemaExample"
formatTag = "format"
validateTag = "validate"
minimumTag = "minimum"
maximumTag = "maximum"
minLengthTag = "minLength"
maxLengthTag = "maxLength"
multipleOfTag = "multipleOf"
readOnlyTag = "readonly"
extensionsTag = "extensions"
2024-05-14 13:07:09 +00:00
collectionFormatTag = "collectionFormat"
)
var regexAttributes = map[string]*regexp.Regexp{
2024-05-14 13:07:09 +00:00
// for Enums(A, B)
2024-05-14 13:07:09 +00:00
enumsTag: regexp.MustCompile(`(?i)\s+enums\(.*\)`),
2024-05-14 13:07:09 +00:00
// for maximum(0)
2024-05-14 13:07:09 +00:00
maximumTag: regexp.MustCompile(`(?i)\s+maxinum|maximum\(.*\)`),
2024-05-14 13:07:09 +00:00
// for minimum(0)
2024-05-14 13:07:09 +00:00
minimumTag: regexp.MustCompile(`(?i)\s+mininum|minimum\(.*\)`),
2024-05-14 13:07:09 +00:00
// for default(0)
2024-05-14 13:07:09 +00:00
defaultTag: regexp.MustCompile(`(?i)\s+default\(.*\)`),
2024-05-14 13:07:09 +00:00
// for minlength(0)
2024-05-14 13:07:09 +00:00
minLengthTag: regexp.MustCompile(`(?i)\s+minlength\(.*\)`),
2024-05-14 13:07:09 +00:00
// for maxlength(0)
2024-05-14 13:07:09 +00:00
maxLengthTag: regexp.MustCompile(`(?i)\s+maxlength\(.*\)`),
2024-05-14 13:07:09 +00:00
// for format(email)
2024-05-14 13:07:09 +00:00
formatTag: regexp.MustCompile(`(?i)\s+format\(.*\)`),
2024-05-14 13:07:09 +00:00
// for extensions(x-example=test)
2024-05-14 13:07:09 +00:00
extensionsTag: regexp.MustCompile(`(?i)\s+extensions\(.*\)`),
2024-05-14 13:07:09 +00:00
// for collectionFormat(csv)
2024-05-14 13:07:09 +00:00
collectionFormatTag: regexp.MustCompile(`(?i)\s+collectionFormat\(.*\)`),
2024-05-14 13:07:09 +00:00
// example(0)
2024-05-14 13:07:09 +00:00
exampleTag: regexp.MustCompile(`(?i)\s+example\(.*\)`),
2024-05-14 13:07:09 +00:00
// schemaExample(0)
2024-05-14 13:07:09 +00:00
schemaExampleTag: regexp.MustCompile(`(?i)\s+schemaExample\(.*\)`),
}
func (operation *Operation) parseParamAttribute(comment, objectType, schemaType, paramType string, param *spec.Parameter) error {
2024-05-14 13:07:09 +00:00
schemaType = TransToValidSchemeType(schemaType)
for attrKey, re := range regexAttributes {
2024-05-14 13:07:09 +00:00
attr, err := findAttr(re, comment)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
continue
2024-05-14 13:07:09 +00:00
}
switch attrKey {
2024-05-14 13:07:09 +00:00
case enumsTag:
2024-05-14 13:07:09 +00:00
err = setEnumParam(param, attr, objectType, schemaType, paramType)
2024-05-14 13:07:09 +00:00
case minimumTag, maximumTag:
2024-05-14 13:07:09 +00:00
err = setNumberParam(param, attrKey, schemaType, attr, comment)
2024-05-14 13:07:09 +00:00
case defaultTag:
2024-05-14 13:07:09 +00:00
err = setDefault(param, schemaType, attr)
2024-05-14 13:07:09 +00:00
case minLengthTag, maxLengthTag:
2024-05-14 13:07:09 +00:00
err = setStringParam(param, attrKey, schemaType, attr, comment)
2024-05-14 13:07:09 +00:00
case formatTag:
2024-05-14 13:07:09 +00:00
param.Format = attr
2024-05-14 13:07:09 +00:00
case exampleTag:
2024-05-14 13:07:09 +00:00
err = setExample(param, schemaType, attr)
2024-05-14 13:07:09 +00:00
case schemaExampleTag:
2024-05-14 13:07:09 +00:00
err = setSchemaExample(param, schemaType, attr)
2024-05-14 13:07:09 +00:00
case extensionsTag:
2024-05-14 13:07:09 +00:00
param.Extensions = setExtensionParam(attr)
2024-05-14 13:07:09 +00:00
case collectionFormatTag:
2024-05-14 13:07:09 +00:00
err = setCollectionFormatParam(param, attrKey, objectType, attr, comment)
2024-05-14 13:07:09 +00:00
}
if err != nil {
2024-05-14 13:07:09 +00:00
return err
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
return nil
2024-05-14 13:07:09 +00:00
}
func findAttr(re *regexp.Regexp, commentLine string) (string, error) {
2024-05-14 13:07:09 +00:00
attr := re.FindString(commentLine)
l, r := strings.Index(attr, "("), strings.Index(attr, ")")
2024-05-14 13:07:09 +00:00
if l == -1 || r == -1 {
2024-05-14 13:07:09 +00:00
return "", fmt.Errorf("can not find regex=%s, comment=%s", re.String(), commentLine)
2024-05-14 13:07:09 +00:00
}
return strings.TrimSpace(attr[l+1 : r]), nil
2024-05-14 13:07:09 +00:00
}
func setStringParam(param *spec.Parameter, name, schemaType, attr, commentLine string) error {
2024-05-14 13:07:09 +00:00
if schemaType != STRING {
2024-05-14 13:07:09 +00:00
return fmt.Errorf("%s is attribute to set to a number. comment=%s got=%s", name, commentLine, schemaType)
2024-05-14 13:07:09 +00:00
}
n, err := strconv.ParseInt(attr, 10, 64)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return fmt.Errorf("%s is allow only a number got=%s", name, attr)
2024-05-14 13:07:09 +00:00
}
switch name {
2024-05-14 13:07:09 +00:00
case minLengthTag:
2024-05-14 13:07:09 +00:00
param.MinLength = &n
2024-05-14 13:07:09 +00:00
case maxLengthTag:
2024-05-14 13:07:09 +00:00
param.MaxLength = &n
2024-05-14 13:07:09 +00:00
}
return nil
2024-05-14 13:07:09 +00:00
}
func setNumberParam(param *spec.Parameter, name, schemaType, attr, commentLine string) error {
2024-05-14 13:07:09 +00:00
switch schemaType {
2024-05-14 13:07:09 +00:00
case INTEGER, NUMBER:
2024-05-14 13:07:09 +00:00
n, err := strconv.ParseFloat(attr, 64)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return fmt.Errorf("maximum is allow only a number. comment=%s got=%s", commentLine, attr)
2024-05-14 13:07:09 +00:00
}
switch name {
2024-05-14 13:07:09 +00:00
case minimumTag:
2024-05-14 13:07:09 +00:00
param.Minimum = &n
2024-05-14 13:07:09 +00:00
case maximumTag:
2024-05-14 13:07:09 +00:00
param.Maximum = &n
2024-05-14 13:07:09 +00:00
}
return nil
2024-05-14 13:07:09 +00:00
default:
2024-05-14 13:07:09 +00:00
return fmt.Errorf("%s is attribute to set to a number. comment=%s got=%s", name, commentLine, schemaType)
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
func setEnumParam(param *spec.Parameter, attr, objectType, schemaType, paramType string) error {
2024-05-14 13:07:09 +00:00
for _, e := range strings.Split(attr, ",") {
2024-05-14 13:07:09 +00:00
e = strings.TrimSpace(e)
value, err := defineType(schemaType, e)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return err
2024-05-14 13:07:09 +00:00
}
switch objectType {
2024-05-14 13:07:09 +00:00
case ARRAY:
2024-05-14 13:07:09 +00:00
param.Items.Enum = append(param.Items.Enum, value)
2024-05-14 13:07:09 +00:00
default:
2024-05-14 13:07:09 +00:00
switch paramType {
2024-05-14 13:07:09 +00:00
case "body":
2024-05-14 13:07:09 +00:00
param.Schema.Enum = append(param.Schema.Enum, value)
2024-05-14 13:07:09 +00:00
default:
2024-05-14 13:07:09 +00:00
param.Enum = append(param.Enum, value)
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
return nil
2024-05-14 13:07:09 +00:00
}
func setExtensionParam(attr string) spec.Extensions {
2024-05-14 13:07:09 +00:00
extensions := spec.Extensions{}
for _, val := range splitNotWrapped(attr, ',') {
2024-05-14 13:07:09 +00:00
parts := strings.SplitN(val, "=", 2)
2024-05-14 13:07:09 +00:00
if len(parts) == 2 {
2024-05-14 13:07:09 +00:00
extensions.Add(parts[0], parts[1])
continue
2024-05-14 13:07:09 +00:00
}
if len(parts[0]) > 0 && string(parts[0][0]) == "!" {
2024-05-14 13:07:09 +00:00
extensions.Add(parts[0][1:], false)
continue
2024-05-14 13:07:09 +00:00
}
extensions.Add(parts[0], true)
2024-05-14 13:07:09 +00:00
}
return extensions
2024-05-14 13:07:09 +00:00
}
func setCollectionFormatParam(param *spec.Parameter, name, schemaType, attr, commentLine string) error {
2024-05-14 13:07:09 +00:00
if schemaType == ARRAY {
2024-05-14 13:07:09 +00:00
param.CollectionFormat = TransToValidCollectionFormat(attr)
return nil
2024-05-14 13:07:09 +00:00
}
return fmt.Errorf("%s is attribute to set to an array. comment=%s got=%s", name, commentLine, schemaType)
2024-05-14 13:07:09 +00:00
}
func setDefault(param *spec.Parameter, schemaType string, value string) error {
2024-05-14 13:07:09 +00:00
val, err := defineType(schemaType, value)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return nil // Don't set a default value if it's not valid
2024-05-14 13:07:09 +00:00
}
param.Default = val
return nil
2024-05-14 13:07:09 +00:00
}
func setSchemaExample(param *spec.Parameter, schemaType string, value string) error {
2024-05-14 13:07:09 +00:00
val, err := defineType(schemaType, value)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return nil // Don't set a example value if it's not valid
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
// skip schema
2024-05-14 13:07:09 +00:00
if param.Schema == nil {
2024-05-14 13:07:09 +00:00
return nil
2024-05-14 13:07:09 +00:00
}
switch v := val.(type) {
2024-05-14 13:07:09 +00:00
case string:
2024-05-14 13:07:09 +00:00
// replaces \r \n \t in example string values.
2024-05-14 13:07:09 +00:00
param.Schema.Example = strings.NewReplacer(`\r`, "\r", `\n`, "\n", `\t`, "\t").Replace(v)
2024-05-14 13:07:09 +00:00
default:
2024-05-14 13:07:09 +00:00
param.Schema.Example = val
2024-05-14 13:07:09 +00:00
}
return nil
2024-05-14 13:07:09 +00:00
}
func setExample(param *spec.Parameter, schemaType string, value string) error {
2024-05-14 13:07:09 +00:00
val, err := defineType(schemaType, value)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return nil // Don't set a example value if it's not valid
2024-05-14 13:07:09 +00:00
}
param.Example = val
return nil
2024-05-14 13:07:09 +00:00
}
// defineType enum value define the type (object and array unsupported).
2024-05-14 13:07:09 +00:00
func defineType(schemaType string, value string) (v interface{}, err error) {
2024-05-14 13:07:09 +00:00
schemaType = TransToValidSchemeType(schemaType)
switch schemaType {
2024-05-14 13:07:09 +00:00
case STRING:
2024-05-14 13:07:09 +00:00
return value, nil
2024-05-14 13:07:09 +00:00
case NUMBER:
2024-05-14 13:07:09 +00:00
v, err = strconv.ParseFloat(value, 64)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return nil, fmt.Errorf("enum value %s can't convert to %s err: %s", value, schemaType, err)
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
case INTEGER:
2024-05-14 13:07:09 +00:00
v, err = strconv.Atoi(value)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return nil, fmt.Errorf("enum value %s can't convert to %s err: %s", value, schemaType, err)
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
case BOOLEAN:
2024-05-14 13:07:09 +00:00
v, err = strconv.ParseBool(value)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return nil, fmt.Errorf("enum value %s can't convert to %s err: %s", value, schemaType, err)
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
default:
2024-05-14 13:07:09 +00:00
return nil, fmt.Errorf("%s is unsupported type in enum value %s", schemaType, value)
2024-05-14 13:07:09 +00:00
}
return v, nil
2024-05-14 13:07:09 +00:00
}
// ParseTagsComment parses comment for given `tag` comment string.
2024-05-14 13:07:09 +00:00
func (operation *Operation) ParseTagsComment(commentLine string) {
2024-05-14 13:07:09 +00:00
for _, tag := range strings.Split(commentLine, ",") {
2024-05-14 13:07:09 +00:00
operation.Tags = append(operation.Tags, strings.TrimSpace(tag))
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
// ParseAcceptComment parses comment for given `accept` comment string.
2024-05-14 13:07:09 +00:00
func (operation *Operation) ParseAcceptComment(commentLine string) error {
2024-05-14 13:07:09 +00:00
return parseMimeTypeList(commentLine, &operation.Consumes, "%v accept type can't be accepted")
2024-05-14 13:07:09 +00:00
}
// ParseProduceComment parses comment for given `produce` comment string.
2024-05-14 13:07:09 +00:00
func (operation *Operation) ParseProduceComment(commentLine string) error {
2024-05-14 13:07:09 +00:00
return parseMimeTypeList(commentLine, &operation.Produces, "%v produce type can't be accepted")
2024-05-14 13:07:09 +00:00
}
// parseMimeTypeList parses a list of MIME Types for a comment like
2024-05-14 13:07:09 +00:00
// `produce` (`Content-Type:` response header) or
2024-05-14 13:07:09 +00:00
// `accept` (`Accept:` request header).
2024-05-14 13:07:09 +00:00
func parseMimeTypeList(mimeTypeList string, typeList *[]string, format string) error {
2024-05-14 13:07:09 +00:00
for _, typeName := range strings.Split(mimeTypeList, ",") {
2024-05-14 13:07:09 +00:00
if mimeTypePattern.MatchString(typeName) {
2024-05-14 13:07:09 +00:00
*typeList = append(*typeList, typeName)
continue
2024-05-14 13:07:09 +00:00
}
aliasMimeType, ok := mimeTypeAliases[typeName]
2024-05-14 13:07:09 +00:00
if !ok {
2024-05-14 13:07:09 +00:00
return fmt.Errorf(format, typeName)
2024-05-14 13:07:09 +00:00
}
*typeList = append(*typeList, aliasMimeType)
2024-05-14 13:07:09 +00:00
}
return nil
2024-05-14 13:07:09 +00:00
}
var routerPattern = regexp.MustCompile(`^(/[\w./\-{}+:$]*)[[:blank:]]+\[(\w+)]`)
// ParseRouterComment parses comment for given `router` comment string.
2024-05-14 13:07:09 +00:00
func (operation *Operation) ParseRouterComment(commentLine string, deprecated bool) error {
2024-05-14 13:07:09 +00:00
matches := routerPattern.FindStringSubmatch(commentLine)
2024-05-14 13:07:09 +00:00
if len(matches) != 3 {
2024-05-14 13:07:09 +00:00
return fmt.Errorf("can not parse router comment \"%s\"", commentLine)
2024-05-14 13:07:09 +00:00
}
signature := RouteProperties{
Path: matches[1],
2024-05-14 13:07:09 +00:00
HTTPMethod: strings.ToUpper(matches[2]),
2024-05-14 13:07:09 +00:00
Deprecated: deprecated,
}
if _, ok := allMethod[signature.HTTPMethod]; !ok {
2024-05-14 13:07:09 +00:00
return fmt.Errorf("invalid method: %s", signature.HTTPMethod)
2024-05-14 13:07:09 +00:00
}
operation.RouterProperties = append(operation.RouterProperties, signature)
return nil
2024-05-14 13:07:09 +00:00
}
// ParseSecurityComment parses comment for given `security` comment string.
2024-05-14 13:07:09 +00:00
func (operation *Operation) ParseSecurityComment(commentLine string) error {
2024-05-14 13:07:09 +00:00
if len(commentLine) == 0 {
2024-05-14 13:07:09 +00:00
operation.Security = []map[string][]string{}
2024-05-14 13:07:09 +00:00
return nil
2024-05-14 13:07:09 +00:00
}
var (
securityMap = make(map[string][]string)
2024-05-14 13:07:09 +00:00
securitySource = commentLine[strings.Index(commentLine, "@Security")+1:]
)
for _, securityOption := range strings.Split(securitySource, "||") {
2024-05-14 13:07:09 +00:00
securityOption = strings.TrimSpace(securityOption)
left, right := strings.Index(securityOption, "["), strings.Index(securityOption, "]")
if !(left == -1 && right == -1) {
2024-05-14 13:07:09 +00:00
scopes := securityOption[left+1 : right]
var options []string
for _, scope := range strings.Split(scopes, ",") {
2024-05-14 13:07:09 +00:00
options = append(options, strings.TrimSpace(scope))
2024-05-14 13:07:09 +00:00
}
securityKey := securityOption[0:left]
2024-05-14 13:07:09 +00:00
securityMap[securityKey] = append(securityMap[securityKey], options...)
2024-05-14 13:07:09 +00:00
} else {
2024-05-14 13:07:09 +00:00
securityKey := strings.TrimSpace(securityOption)
2024-05-14 13:07:09 +00:00
securityMap[securityKey] = []string{}
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
operation.Security = append(operation.Security, securityMap)
return nil
2024-05-14 13:07:09 +00:00
}
// findTypeDef attempts to find the *ast.TypeSpec for a specific type given the
2024-05-14 13:07:09 +00:00
// type's name and the package's import path.
2024-05-14 13:07:09 +00:00
// TODO: improve finding external pkg.
2024-05-14 13:07:09 +00:00
func findTypeDef(importPath, typeName string) (*ast.TypeSpec, error) {
2024-05-14 13:07:09 +00:00
cwd, err := os.Getwd()
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return nil, err
2024-05-14 13:07:09 +00:00
}
conf := loader.Config{
2024-05-14 13:07:09 +00:00
ParserMode: goparser.SpuriousErrors,
Cwd: cwd,
2024-05-14 13:07:09 +00:00
}
conf.Import(importPath)
lprog, err := conf.Load()
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return nil, err
2024-05-14 13:07:09 +00:00
}
// If the pkg is vendored, the actual pkg path is going to resemble
2024-05-14 13:07:09 +00:00
// something like "{importPath}/vendor/{importPath}"
2024-05-14 13:07:09 +00:00
for k := range lprog.AllPackages {
2024-05-14 13:07:09 +00:00
realPkgPath := k.Path()
if strings.Contains(realPkgPath, "vendor/"+importPath) {
2024-05-14 13:07:09 +00:00
importPath = realPkgPath
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
pkgInfo := lprog.Package(importPath)
if pkgInfo == nil {
2024-05-14 13:07:09 +00:00
return nil, fmt.Errorf("package was nil")
2024-05-14 13:07:09 +00:00
}
// TODO: possibly cache pkgInfo since it's an expensive operation
2024-05-14 13:07:09 +00:00
for i := range pkgInfo.Files {
2024-05-14 13:07:09 +00:00
for _, astDeclaration := range pkgInfo.Files[i].Decls {
2024-05-14 13:07:09 +00:00
generalDeclaration, ok := astDeclaration.(*ast.GenDecl)
2024-05-14 13:07:09 +00:00
if ok && generalDeclaration.Tok == token.TYPE {
2024-05-14 13:07:09 +00:00
for _, astSpec := range generalDeclaration.Specs {
2024-05-14 13:07:09 +00:00
typeSpec, ok := astSpec.(*ast.TypeSpec)
2024-05-14 13:07:09 +00:00
if ok {
2024-05-14 13:07:09 +00:00
if typeSpec.Name.String() == typeName {
2024-05-14 13:07:09 +00:00
return typeSpec, nil
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
return nil, fmt.Errorf("type spec not found")
2024-05-14 13:07:09 +00:00
}
var responsePattern = regexp.MustCompile(`^([\w,]+)\s+([\w{}]+)\s+([\w\-.\\{}=,\[\s\]]+)\s*(".*)?`)
// ResponseType{data1=Type1,data2=Type2}.
2024-05-14 13:07:09 +00:00
var combinedPattern = regexp.MustCompile(`^([\w\-./\[\]]+){(.*)}$`)
func (operation *Operation) parseObjectSchema(refType string, astFile *ast.File) (*spec.Schema, error) {
2024-05-14 13:07:09 +00:00
return parseObjectSchema(operation.parser, refType, astFile)
2024-05-14 13:07:09 +00:00
}
func parseObjectSchema(parser *Parser, refType string, astFile *ast.File) (*spec.Schema, error) {
2024-05-14 13:07:09 +00:00
switch {
2024-05-14 13:07:09 +00:00
case refType == NIL:
2024-05-14 13:07:09 +00:00
return nil, nil
2024-05-14 13:07:09 +00:00
case refType == INTERFACE:
2024-05-14 13:07:09 +00:00
return PrimitiveSchema(OBJECT), nil
2024-05-14 13:07:09 +00:00
case refType == ANY:
2024-05-14 13:07:09 +00:00
return PrimitiveSchema(OBJECT), nil
2024-05-14 13:07:09 +00:00
case IsGolangPrimitiveType(refType):
2024-05-14 13:07:09 +00:00
refType = TransToValidSchemeType(refType)
return PrimitiveSchema(refType), nil
2024-05-14 13:07:09 +00:00
case IsPrimitiveType(refType):
2024-05-14 13:07:09 +00:00
return PrimitiveSchema(refType), nil
2024-05-14 13:07:09 +00:00
case strings.HasPrefix(refType, "[]"):
2024-05-14 13:07:09 +00:00
schema, err := parseObjectSchema(parser, refType[2:], astFile)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return nil, err
2024-05-14 13:07:09 +00:00
}
return spec.ArrayProperty(schema), nil
2024-05-14 13:07:09 +00:00
case strings.HasPrefix(refType, "map["):
2024-05-14 13:07:09 +00:00
// ignore key type
2024-05-14 13:07:09 +00:00
idx := strings.Index(refType, "]")
2024-05-14 13:07:09 +00:00
if idx < 0 {
2024-05-14 13:07:09 +00:00
return nil, fmt.Errorf("invalid type: %s", refType)
2024-05-14 13:07:09 +00:00
}
refType = refType[idx+1:]
2024-05-14 13:07:09 +00:00
if refType == INTERFACE || refType == ANY {
2024-05-14 13:07:09 +00:00
return spec.MapProperty(nil), nil
2024-05-14 13:07:09 +00:00
}
schema, err := parseObjectSchema(parser, refType, astFile)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return nil, err
2024-05-14 13:07:09 +00:00
}
return spec.MapProperty(schema), nil
2024-05-14 13:07:09 +00:00
case strings.Contains(refType, "{"):
2024-05-14 13:07:09 +00:00
return parseCombinedObjectSchema(parser, refType, astFile)
2024-05-14 13:07:09 +00:00
default:
2024-05-14 13:07:09 +00:00
if parser != nil { // checking refType has existing in 'TypeDefinitions'
2024-05-14 13:07:09 +00:00
schema, err := parser.getTypeSchema(refType, astFile, true)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return nil, err
2024-05-14 13:07:09 +00:00
}
return schema, nil
2024-05-14 13:07:09 +00:00
}
return RefSchema(refType), nil
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
func parseFields(s string) []string {
2024-05-14 13:07:09 +00:00
nestLevel := 0
return strings.FieldsFunc(s, func(char rune) bool {
2024-05-14 13:07:09 +00:00
if char == '{' {
2024-05-14 13:07:09 +00:00
nestLevel++
return false
2024-05-14 13:07:09 +00:00
} else if char == '}' {
2024-05-14 13:07:09 +00:00
nestLevel--
return false
2024-05-14 13:07:09 +00:00
}
return char == ',' && nestLevel == 0
2024-05-14 13:07:09 +00:00
})
2024-05-14 13:07:09 +00:00
}
func parseCombinedObjectSchema(parser *Parser, refType string, astFile *ast.File) (*spec.Schema, error) {
2024-05-14 13:07:09 +00:00
matches := combinedPattern.FindStringSubmatch(refType)
2024-05-14 13:07:09 +00:00
if len(matches) != 3 {
2024-05-14 13:07:09 +00:00
return nil, fmt.Errorf("invalid type: %s", refType)
2024-05-14 13:07:09 +00:00
}
schema, err := parseObjectSchema(parser, matches[1], astFile)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return nil, err
2024-05-14 13:07:09 +00:00
}
fields, props := parseFields(matches[2]), map[string]spec.Schema{}
for _, field := range fields {
2024-05-14 13:07:09 +00:00
keyVal := strings.SplitN(field, "=", 2)
2024-05-14 13:07:09 +00:00
if len(keyVal) == 2 {
2024-05-14 13:07:09 +00:00
schema, err := parseObjectSchema(parser, keyVal[1], astFile)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return nil, err
2024-05-14 13:07:09 +00:00
}
if schema == nil {
2024-05-14 13:07:09 +00:00
schema = PrimitiveSchema(OBJECT)
2024-05-14 13:07:09 +00:00
}
props[keyVal[0]] = *schema
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
if len(props) == 0 {
2024-05-14 13:07:09 +00:00
return schema, nil
2024-05-14 13:07:09 +00:00
}
if schema.Ref.GetURL() == nil && len(schema.Type) > 0 && schema.Type[0] == OBJECT && len(schema.Properties) == 0 && schema.AdditionalProperties == nil {
2024-05-14 13:07:09 +00:00
schema.Properties = props
2024-05-14 13:07:09 +00:00
return schema, nil
2024-05-14 13:07:09 +00:00
}
return spec.ComposedSchema(*schema, spec.Schema{
2024-05-14 13:07:09 +00:00
SchemaProps: spec.SchemaProps{
Type: []string{OBJECT},
2024-05-14 13:07:09 +00:00
Properties: props,
},
}), nil
2024-05-14 13:07:09 +00:00
}
func (operation *Operation) parseAPIObjectSchema(commentLine, schemaType, refType string, astFile *ast.File) (*spec.Schema, error) {
2024-05-14 13:07:09 +00:00
if strings.HasSuffix(refType, ",") && strings.Contains(refType, "[") {
2024-05-14 13:07:09 +00:00
// regexp may have broken generic syntax. find closing bracket and add it back
2024-05-14 13:07:09 +00:00
allMatchesLenOffset := strings.Index(commentLine, refType) + len(refType)
2024-05-14 13:07:09 +00:00
lostPartEndIdx := strings.Index(commentLine[allMatchesLenOffset:], "]")
2024-05-14 13:07:09 +00:00
if lostPartEndIdx >= 0 {
2024-05-14 13:07:09 +00:00
refType += commentLine[allMatchesLenOffset : allMatchesLenOffset+lostPartEndIdx+1]
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
switch schemaType {
2024-05-14 13:07:09 +00:00
case OBJECT:
2024-05-14 13:07:09 +00:00
if !strings.HasPrefix(refType, "[]") {
2024-05-14 13:07:09 +00:00
return operation.parseObjectSchema(refType, astFile)
2024-05-14 13:07:09 +00:00
}
refType = refType[2:]
fallthrough
2024-05-14 13:07:09 +00:00
case ARRAY:
2024-05-14 13:07:09 +00:00
schema, err := operation.parseObjectSchema(refType, astFile)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return nil, err
2024-05-14 13:07:09 +00:00
}
return spec.ArrayProperty(schema), nil
2024-05-14 13:07:09 +00:00
default:
2024-05-14 13:07:09 +00:00
return PrimitiveSchema(schemaType), nil
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
// ParseResponseComment parses comment for given `response` comment string.
2024-05-14 13:07:09 +00:00
func (operation *Operation) ParseResponseComment(commentLine string, astFile *ast.File) error {
2024-05-14 13:07:09 +00:00
matches := responsePattern.FindStringSubmatch(commentLine)
2024-05-14 13:07:09 +00:00
if len(matches) != 5 {
2024-05-14 13:07:09 +00:00
err := operation.ParseEmptyResponseComment(commentLine)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return operation.ParseEmptyResponseOnly(commentLine)
2024-05-14 13:07:09 +00:00
}
return err
2024-05-14 13:07:09 +00:00
}
description := strings.Trim(matches[4], "\"")
schema, err := operation.parseAPIObjectSchema(commentLine, strings.Trim(matches[2], "{}"), strings.TrimSpace(matches[3]), astFile)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return err
2024-05-14 13:07:09 +00:00
}
for _, codeStr := range strings.Split(matches[1], ",") {
2024-05-14 13:07:09 +00:00
if strings.EqualFold(codeStr, defaultTag) {
2024-05-14 13:07:09 +00:00
operation.DefaultResponse().WithSchema(schema).WithDescription(description)
continue
2024-05-14 13:07:09 +00:00
}
code, err := strconv.Atoi(codeStr)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
2024-05-14 13:07:09 +00:00
}
resp := spec.NewResponse().WithSchema(schema).WithDescription(description)
2024-05-14 13:07:09 +00:00
if description == "" {
2024-05-14 13:07:09 +00:00
resp.WithDescription(http.StatusText(code))
2024-05-14 13:07:09 +00:00
}
operation.AddResponse(code, resp)
2024-05-14 13:07:09 +00:00
}
return nil
2024-05-14 13:07:09 +00:00
}
func newHeaderSpec(schemaType, description string) spec.Header {
2024-05-14 13:07:09 +00:00
return spec.Header{
2024-05-14 13:07:09 +00:00
SimpleSchema: spec.SimpleSchema{
2024-05-14 13:07:09 +00:00
Type: schemaType,
},
2024-05-14 13:07:09 +00:00
HeaderProps: spec.HeaderProps{
2024-05-14 13:07:09 +00:00
Description: description,
},
2024-05-14 13:07:09 +00:00
VendorExtensible: spec.VendorExtensible{
2024-05-14 13:07:09 +00:00
Extensions: nil,
},
2024-05-14 13:07:09 +00:00
CommonValidations: spec.CommonValidations{
Maximum: nil,
2024-05-14 13:07:09 +00:00
ExclusiveMaximum: false,
Minimum: nil,
2024-05-14 13:07:09 +00:00
ExclusiveMinimum: false,
MaxLength: nil,
MinLength: nil,
Pattern: "",
MaxItems: nil,
MinItems: nil,
UniqueItems: false,
MultipleOf: nil,
Enum: nil,
2024-05-14 13:07:09 +00:00
},
}
2024-05-14 13:07:09 +00:00
}
// ParseResponseHeaderComment parses comment for given `response header` comment string.
2024-05-14 13:07:09 +00:00
func (operation *Operation) ParseResponseHeaderComment(commentLine string, _ *ast.File) error {
2024-05-14 13:07:09 +00:00
matches := responsePattern.FindStringSubmatch(commentLine)
2024-05-14 13:07:09 +00:00
if len(matches) != 5 {
2024-05-14 13:07:09 +00:00
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
2024-05-14 13:07:09 +00:00
}
header := newHeaderSpec(strings.Trim(matches[2], "{}"), strings.Trim(matches[4], "\""))
headerKey := strings.TrimSpace(matches[3])
if strings.EqualFold(matches[1], "all") {
2024-05-14 13:07:09 +00:00
if operation.Responses.Default != nil {
2024-05-14 13:07:09 +00:00
operation.Responses.Default.Headers[headerKey] = header
2024-05-14 13:07:09 +00:00
}
if operation.Responses.StatusCodeResponses != nil {
2024-05-14 13:07:09 +00:00
for code, response := range operation.Responses.StatusCodeResponses {
2024-05-14 13:07:09 +00:00
response.Headers[headerKey] = header
2024-05-14 13:07:09 +00:00
operation.Responses.StatusCodeResponses[code] = response
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
return nil
2024-05-14 13:07:09 +00:00
}
for _, codeStr := range strings.Split(matches[1], ",") {
2024-05-14 13:07:09 +00:00
if strings.EqualFold(codeStr, defaultTag) {
2024-05-14 13:07:09 +00:00
if operation.Responses.Default != nil {
2024-05-14 13:07:09 +00:00
operation.Responses.Default.Headers[headerKey] = header
2024-05-14 13:07:09 +00:00
}
continue
2024-05-14 13:07:09 +00:00
}
code, err := strconv.Atoi(codeStr)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
2024-05-14 13:07:09 +00:00
}
if operation.Responses.StatusCodeResponses != nil {
2024-05-14 13:07:09 +00:00
response, responseExist := operation.Responses.StatusCodeResponses[code]
2024-05-14 13:07:09 +00:00
if responseExist {
2024-05-14 13:07:09 +00:00
response.Headers[headerKey] = header
operation.Responses.StatusCodeResponses[code] = response
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
return nil
2024-05-14 13:07:09 +00:00
}
var emptyResponsePattern = regexp.MustCompile(`([\w,]+)\s+"(.*)"`)
// ParseEmptyResponseComment parse only comment out status code and description,eg: @Success 200 "it's ok".
2024-05-14 13:07:09 +00:00
func (operation *Operation) ParseEmptyResponseComment(commentLine string) error {
2024-05-14 13:07:09 +00:00
matches := emptyResponsePattern.FindStringSubmatch(commentLine)
2024-05-14 13:07:09 +00:00
if len(matches) != 3 {
2024-05-14 13:07:09 +00:00
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
2024-05-14 13:07:09 +00:00
}
description := strings.Trim(matches[2], "\"")
for _, codeStr := range strings.Split(matches[1], ",") {
2024-05-14 13:07:09 +00:00
if strings.EqualFold(codeStr, defaultTag) {
2024-05-14 13:07:09 +00:00
operation.DefaultResponse().WithDescription(description)
continue
2024-05-14 13:07:09 +00:00
}
code, err := strconv.Atoi(codeStr)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
2024-05-14 13:07:09 +00:00
}
operation.AddResponse(code, spec.NewResponse().WithDescription(description))
2024-05-14 13:07:09 +00:00
}
return nil
2024-05-14 13:07:09 +00:00
}
// ParseEmptyResponseOnly parse only comment out status code ,eg: @Success 200.
2024-05-14 13:07:09 +00:00
func (operation *Operation) ParseEmptyResponseOnly(commentLine string) error {
2024-05-14 13:07:09 +00:00
for _, codeStr := range strings.Split(commentLine, ",") {
2024-05-14 13:07:09 +00:00
if strings.EqualFold(codeStr, defaultTag) {
2024-05-14 13:07:09 +00:00
_ = operation.DefaultResponse()
continue
2024-05-14 13:07:09 +00:00
}
code, err := strconv.Atoi(codeStr)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
2024-05-14 13:07:09 +00:00
}
operation.AddResponse(code, spec.NewResponse().WithDescription(http.StatusText(code)))
2024-05-14 13:07:09 +00:00
}
return nil
2024-05-14 13:07:09 +00:00
}
// DefaultResponse return the default response member pointer.
2024-05-14 13:07:09 +00:00
func (operation *Operation) DefaultResponse() *spec.Response {
2024-05-14 13:07:09 +00:00
if operation.Responses.Default == nil {
2024-05-14 13:07:09 +00:00
operation.Responses.Default = &spec.Response{
2024-05-14 13:07:09 +00:00
ResponseProps: spec.ResponseProps{
2024-05-14 13:07:09 +00:00
Description: "",
Headers: make(map[string]spec.Header),
2024-05-14 13:07:09 +00:00
},
}
2024-05-14 13:07:09 +00:00
}
return operation.Responses.Default
2024-05-14 13:07:09 +00:00
}
// AddResponse add a response for a code.
2024-05-14 13:07:09 +00:00
func (operation *Operation) AddResponse(code int, response *spec.Response) {
2024-05-14 13:07:09 +00:00
if response.Headers == nil {
2024-05-14 13:07:09 +00:00
response.Headers = make(map[string]spec.Header)
2024-05-14 13:07:09 +00:00
}
operation.Responses.StatusCodeResponses[code] = *response
2024-05-14 13:07:09 +00:00
}
// createParameter returns swagger spec.Parameter for given paramType, description, paramName, schemaType, required.
2024-05-14 13:07:09 +00:00
func createParameter(paramType, description, paramName, objectType, schemaType string, required bool, enums []interface{}, collectionFormat string) spec.Parameter {
2024-05-14 13:07:09 +00:00
// //five possible parameter types. query, path, body, header, form
2024-05-14 13:07:09 +00:00
result := spec.Parameter{
2024-05-14 13:07:09 +00:00
ParamProps: spec.ParamProps{
Name: paramName,
2024-05-14 13:07:09 +00:00
Description: description,
Required: required,
In: paramType,
2024-05-14 13:07:09 +00:00
},
}
if paramType == "body" {
2024-05-14 13:07:09 +00:00
return result
2024-05-14 13:07:09 +00:00
}
switch objectType {
2024-05-14 13:07:09 +00:00
case ARRAY:
2024-05-14 13:07:09 +00:00
result.Type = objectType
2024-05-14 13:07:09 +00:00
result.CollectionFormat = collectionFormat
2024-05-14 13:07:09 +00:00
result.Items = &spec.Items{
2024-05-14 13:07:09 +00:00
CommonValidations: spec.CommonValidations{
2024-05-14 13:07:09 +00:00
Enum: enums,
},
2024-05-14 13:07:09 +00:00
SimpleSchema: spec.SimpleSchema{
2024-05-14 13:07:09 +00:00
Type: schemaType,
},
}
2024-05-14 13:07:09 +00:00
case PRIMITIVE, OBJECT:
2024-05-14 13:07:09 +00:00
result.Type = schemaType
2024-05-14 13:07:09 +00:00
result.Enum = enums
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
return result
2024-05-14 13:07:09 +00:00
}
func getCodeExampleForSummary(summaryName string, dirPath string) ([]byte, error) {
2024-05-14 13:07:09 +00:00
dirEntries, err := os.ReadDir(dirPath)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return nil, err
2024-05-14 13:07:09 +00:00
}
for _, entry := range dirEntries {
2024-05-14 13:07:09 +00:00
if entry.IsDir() {
2024-05-14 13:07:09 +00:00
continue
2024-05-14 13:07:09 +00:00
}
fileName := entry.Name()
if !strings.Contains(fileName, ".json") {
2024-05-14 13:07:09 +00:00
continue
2024-05-14 13:07:09 +00:00
}
if strings.Contains(fileName, summaryName) {
2024-05-14 13:07:09 +00:00
fullPath := filepath.Join(dirPath, fileName)
commentInfo, err := os.ReadFile(fullPath)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return nil, fmt.Errorf("Failed to read code example file %s error: %s ", fullPath, err)
2024-05-14 13:07:09 +00:00
}
return commentInfo, nil
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
return nil, fmt.Errorf("unable to find code example file for tag %s in the given directory", summaryName)
2024-05-14 13:07:09 +00:00
}