Skip to content

Commit fd74bcf

Browse files
authored
refactor and lint code (#978)
* refactor and lint code * refactor and lint code * improve parser.go unit tests * improve parser.go unit tests * improve operation.go unit tests * improve operation.go unit tests * improve operation.go unit tests * improve operation.go unit tests * improve operation.go unit tests
1 parent b19e9cf commit fd74bcf

File tree

9 files changed

+693
-370
lines changed

9 files changed

+693
-370
lines changed

operation.go

Lines changed: 75 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -135,15 +135,16 @@ func (operation *Operation) ParseComment(comment string, astFile *ast.File) erro
135135
}
136136

137137
// ParseCodeSample godoc.
138-
func (operation *Operation) ParseCodeSample(attribute, commentLine, lineRemainder string) error {
138+
func (operation *Operation) ParseCodeSample(attribute, _, lineRemainder string) error {
139139
if lineRemainder == "file" {
140140
data, err := getCodeExampleForSummary(operation.Summary, operation.codeExampleFilesDir)
141141
if err != nil {
142142
return err
143143
}
144144

145145
var valueJSON interface{}
146-
if err := json.Unmarshal(data, &valueJSON); err != nil {
146+
err = json.Unmarshal(data, &valueJSON)
147+
if err != nil {
147148
return fmt.Errorf("annotation %s need a valid json value", attribute)
148149
}
149150

@@ -176,7 +177,8 @@ func (operation *Operation) ParseMetadata(attribute, lowerAttribute, lineRemaind
176177
}
177178

178179
var valueJSON interface{}
179-
if err := json.Unmarshal([]byte(lineRemainder), &valueJSON); err != nil {
180+
err := json.Unmarshal([]byte(lineRemainder), &valueJSON)
181+
if err != nil {
180182
return fmt.Errorf("annotation %s need a valid json value", attribute)
181183
}
182184

@@ -189,6 +191,16 @@ func (operation *Operation) ParseMetadata(attribute, lowerAttribute, lineRemaind
189191

190192
var paramPattern = regexp.MustCompile(`(\S+)[\s]+([\w]+)[\s]+([\S.]+)[\s]+([\w]+)[\s]+"([^"]+)"`)
191193

194+
func findInSlice(arr []string, target string) bool {
195+
for _, str := range arr {
196+
if str == target {
197+
return true
198+
}
199+
}
200+
201+
return false
202+
}
203+
192204
// ParseParamComment parses params return []string of param properties
193205
// E.g. @Param queryText formData string true "The email for login"
194206
// [param name] [paramType] [data type] [is mandatory?] [Comment]
@@ -248,15 +260,7 @@ func (operation *Operation) ParseParamComment(commentLine string, astFile *ast.F
248260
if len(schema.Properties) == 0 {
249261
return nil
250262
}
251-
find := func(arr []string, target string) bool {
252-
for _, str := range arr {
253-
if str == target {
254-
return true
255-
}
256-
}
257263

258-
return false
259-
}
260264
items := schema.Properties.ToOrderedSchemaItems()
261265
for _, item := range items {
262266
name := item.Name
@@ -269,7 +273,7 @@ func (operation *Operation) ParseParamComment(commentLine string, astFile *ast.F
269273
prop.Items.Schema != nil &&
270274
len(prop.Items.Schema.Type) > 0 &&
271275
IsSimplePrimitiveType(prop.Items.Schema.Type[0]):
272-
param = createParameter(paramType, prop.Description, name, prop.Type[0], find(schema.Required, name))
276+
param = createParameter(paramType, prop.Description, name, prop.Type[0], findInSlice(schema.Required, name))
273277
param.SimpleSchema.Type = prop.Type[0]
274278
if operation.parser != nil && operation.parser.collectionFormatInQuery != "" && param.CollectionFormat == "" {
275279
param.CollectionFormat = TransToValidCollectionFormat(operation.parser.collectionFormatInQuery)
@@ -280,7 +284,7 @@ func (operation *Operation) ParseParamComment(commentLine string, astFile *ast.F
280284
},
281285
}
282286
case IsSimplePrimitiveType(prop.Type[0]):
283-
param = createParameter(paramType, prop.Description, name, prop.Type[0], find(schema.Required, name))
287+
param = createParameter(paramType, prop.Description, name, prop.Type[0], findInSlice(schema.Required, name))
284288
default:
285289
Println(fmt.Sprintf("skip field [%s] in %s is not supported type for %s", name, refType, paramType))
286290

@@ -318,7 +322,8 @@ func (operation *Operation) ParseParamComment(commentLine string, astFile *ast.F
318322
return fmt.Errorf("%s is not supported paramType", paramType)
319323
}
320324

321-
if err := operation.parseAndExtractionParamAttribute(commentLine, objectType, refType, &param); err != nil {
325+
err := operation.parseAndExtractionParamAttribute(commentLine, objectType, refType, &param)
326+
if err != nil {
322327
return err
323328
}
324329
operation.Operation.Parameters = append(operation.Operation.Parameters, param)
@@ -495,9 +500,9 @@ func defineType(schemaType string, value string) (interface{}, error) {
495500
}
496501

497502
return v, nil
503+
default:
504+
return nil, fmt.Errorf("%s is unsupported type in enum value %s", schemaType, value)
498505
}
499-
500-
return nil, fmt.Errorf("%s is unsupported type in enum value %s", schemaType, value)
501506
}
502507

503508
// ParseTagsComment parses comment for given `tag` comment string.
@@ -529,13 +534,12 @@ func parseMimeTypeList(mimeTypeList string, typeList *[]string, format string) e
529534

530535
continue
531536
}
532-
if aliasMimeType, ok := mimeTypeAliases[typeName]; ok {
533-
*typeList = append(*typeList, aliasMimeType)
534-
535-
continue
537+
aliasMimeType, ok := mimeTypeAliases[typeName]
538+
if !ok {
539+
return fmt.Errorf(format, typeName)
536540
}
537541

538-
return fmt.Errorf(format, typeName)
542+
*typeList = append(*typeList, aliasMimeType)
539543
}
540544

541545
return nil
@@ -545,9 +549,8 @@ var routerPattern = regexp.MustCompile(`^(/[\w\.\/\-{}\+:]*)[[:blank:]]+\[(\w+)]
545549

546550
// ParseRouterComment parses comment for gived `router` comment string.
547551
func (operation *Operation) ParseRouterComment(commentLine string) error {
548-
var matches []string
549-
550-
if matches = routerPattern.FindStringSubmatch(commentLine); len(matches) != 3 {
552+
matches := routerPattern.FindStringSubmatch(commentLine)
553+
if len(matches) != 3 {
551554
return fmt.Errorf("can not parse router comment \"%s\"", commentLine)
552555
}
553556
path := matches[1]
@@ -572,8 +575,7 @@ func (operation *Operation) ParseSecurityComment(commentLine string) error {
572575
scopes := securitySource[l+1 : r]
573576
var s []string
574577
for _, scope := range strings.Split(scopes, ",") {
575-
scope = strings.TrimSpace(scope)
576-
s = append(s, scope)
578+
s = append(s, strings.TrimSpace(scope))
577579
}
578580
securityKey := securitySource[0:l]
579581
securityMap := map[string][]string{}
@@ -731,7 +733,8 @@ func (operation *Operation) parseCombinedObjectSchema(refType string, astFile *a
731733
fields := parseFields(matches[2])
732734
props := map[string]spec.Schema{}
733735
for _, field := range fields {
734-
if matches := strings.SplitN(field, "=", 2); len(matches) == 2 {
736+
matches := strings.SplitN(field, "=", 2)
737+
if len(matches) == 2 {
735738
schema, err := operation.parseObjectSchema(matches[1], astFile)
736739
if err != nil {
737740
return nil, err
@@ -777,9 +780,8 @@ func (operation *Operation) parseAPIObjectSchema(schemaType, refType string, ast
777780

778781
// ParseResponseComment parses comment for given `response` comment string.
779782
func (operation *Operation) ParseResponseComment(commentLine string, astFile *ast.File) error {
780-
var matches []string
781-
782-
if matches = responsePattern.FindStringSubmatch(commentLine); len(matches) != 5 {
783+
matches := responsePattern.FindStringSubmatch(commentLine)
784+
if len(matches) != 5 {
783785
err := operation.ParseEmptyResponseComment(commentLine)
784786
if err != nil {
785787
return operation.ParseEmptyResponseOnly(commentLine)
@@ -789,9 +791,7 @@ func (operation *Operation) ParseResponseComment(commentLine string, astFile *as
789791
}
790792

791793
responseDescription := strings.Trim(matches[4], "\"")
792-
schemaType := strings.Trim(matches[2], "{}")
793-
refType := matches[3]
794-
schema, err := operation.parseAPIObjectSchema(schemaType, refType, astFile)
794+
schema, err := operation.parseAPIObjectSchema(strings.Trim(matches[2], "{}"), matches[3], astFile)
795795
if err != nil {
796796
return err
797797
}
@@ -800,27 +800,29 @@ func (operation *Operation) ParseResponseComment(commentLine string, astFile *as
800800
if strings.EqualFold(codeStr, "default") {
801801
operation.DefaultResponse().Schema = schema
802802
operation.DefaultResponse().Description = responseDescription
803-
} else if code, err := strconv.Atoi(codeStr); err == nil {
804-
resp := &spec.Response{
805-
ResponseProps: spec.ResponseProps{Schema: schema, Description: responseDescription},
806-
}
807-
if resp.Description == "" {
808-
resp.Description = http.StatusText(code)
809-
}
810-
operation.AddResponse(code, resp)
811-
} else {
803+
804+
continue
805+
}
806+
code, err := strconv.Atoi(codeStr)
807+
if err != nil {
812808
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
813809
}
810+
resp := &spec.Response{
811+
ResponseProps: spec.ResponseProps{Schema: schema, Description: responseDescription},
812+
}
813+
if resp.Description == "" {
814+
resp.Description = http.StatusText(code)
815+
}
816+
operation.AddResponse(code, resp)
814817
}
815818

816819
return nil
817820
}
818821

819-
// ParseResponseHeaderComment parses comment for gived `response header` comment string.
820-
func (operation *Operation) ParseResponseHeaderComment(commentLine string, astFile *ast.File) error {
821-
var matches []string
822-
823-
if matches = responsePattern.FindStringSubmatch(commentLine); len(matches) != 5 {
822+
// ParseResponseHeaderComment parses comment for given `response header` comment string.
823+
func (operation *Operation) ParseResponseHeaderComment(commentLine string, _ *ast.File) error {
824+
matches := responsePattern.FindStringSubmatch(commentLine)
825+
if len(matches) != 5 {
824826
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
825827
}
826828

@@ -862,22 +864,22 @@ func (operation *Operation) ParseResponseHeaderComment(commentLine string, astFi
862864

863865
continue
864866
}
865-
if code, err := strconv.Atoi(codeStr); err == nil {
866-
if operation.Responses != nil && operation.Responses.StatusCodeResponses != nil {
867-
if response, responseExist := operation.Responses.StatusCodeResponses[code]; responseExist {
868-
if response.Headers == nil {
869-
response.Headers = make(map[string]spec.Header)
870-
}
871-
response.Headers[headerKey] = header
872867

873-
operation.Responses.StatusCodeResponses[code] = response
868+
code, err := strconv.Atoi(codeStr)
869+
if err != nil {
870+
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
871+
}
872+
if operation.Responses != nil && operation.Responses.StatusCodeResponses != nil {
873+
response, responseExist := operation.Responses.StatusCodeResponses[code]
874+
if responseExist {
875+
if response.Headers == nil {
876+
response.Headers = make(map[string]spec.Header)
874877
}
875-
}
878+
response.Headers[headerKey] = header
876879

877-
continue
880+
operation.Responses.StatusCodeResponses[code] = response
881+
}
878882
}
879-
880-
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
881883
}
882884

883885
return nil
@@ -887,9 +889,8 @@ var emptyResponsePattern = regexp.MustCompile(`([\w,]+)[\s]+"(.*)"`)
887889

888890
// ParseEmptyResponseComment parse only comment out status code and description,eg: @Success 200 "it's ok".
889891
func (operation *Operation) ParseEmptyResponseComment(commentLine string) error {
890-
var matches []string
891-
892-
if matches = emptyResponsePattern.FindStringSubmatch(commentLine); len(matches) != 3 {
892+
matches := emptyResponsePattern.FindStringSubmatch(commentLine)
893+
if len(matches) != 3 {
893894
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
894895
}
895896

@@ -901,15 +902,14 @@ func (operation *Operation) ParseEmptyResponseComment(commentLine string) error
901902
continue
902903
}
903904

904-
if code, err := strconv.Atoi(codeStr); err == nil {
905-
var response spec.Response
906-
response.Description = responseDescription
907-
operation.AddResponse(code, &response)
908-
909-
continue
905+
code, err := strconv.Atoi(codeStr)
906+
if err != nil {
907+
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
910908
}
911909

912-
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
910+
var response spec.Response
911+
response.Description = responseDescription
912+
operation.AddResponse(code, &response)
913913
}
914914

915915
return nil
@@ -923,15 +923,14 @@ func (operation *Operation) ParseEmptyResponseOnly(commentLine string) error {
923923

924924
continue
925925
}
926-
if code, err := strconv.Atoi(codeStr); err == nil {
927-
var response spec.Response
928-
// response.Description = http.StatusText(code)
929-
operation.AddResponse(code, &response)
930-
931-
continue
926+
code, err := strconv.Atoi(codeStr)
927+
if err != nil {
928+
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
932929
}
933930

934-
return fmt.Errorf("can not parse response comment \"%s\"", commentLine)
931+
var response spec.Response
932+
// response.Description = http.StatusText(code)
933+
operation.AddResponse(code, &response)
935934
}
936935

937936
return nil

0 commit comments

Comments
 (0)