github.com/emreu/go-swagger@v0.22.1/scan/operations.go (about)

     1  // +build !go1.11
     2  
     3  // Copyright 2015 go-swagger maintainers
     4  //
     5  // Licensed under the Apache License, Version 2.0 (the "License");
     6  // you may not use this file except in compliance with the License.
     7  // You may obtain a copy of the License at
     8  //
     9  //    http://www.apache.org/licenses/LICENSE-2.0
    10  //
    11  // Unless required by applicable law or agreed to in writing, software
    12  // distributed under the License is distributed on an "AS IS" BASIS,
    13  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14  // See the License for the specific language governing permissions and
    15  // limitations under the License.
    16  
    17  package scan
    18  
    19  import (
    20  	"fmt"
    21  	"go/ast"
    22  
    23  	"github.com/go-openapi/spec"
    24  
    25  	"golang.org/x/tools/go/loader"
    26  )
    27  
    28  func newOperationsParser(prog *loader.Program) *operationsParser {
    29  	return &operationsParser{
    30  		program: prog,
    31  	}
    32  }
    33  
    34  type operationsParser struct {
    35  	program     *loader.Program
    36  	definitions map[string]spec.Schema
    37  	operations  map[string]*spec.Operation
    38  	responses   map[string]spec.Response
    39  }
    40  
    41  func (op *operationsParser) Parse(gofile *ast.File, target interface{}, includeTags map[string]bool, excludeTags map[string]bool) error {
    42  	tgt := target.(*spec.Paths)
    43  	for _, comsec := range gofile.Comments {
    44  		content := parsePathAnnotation(rxOperation, comsec.List)
    45  
    46  		if content.Method == "" {
    47  			continue // it's not, next!
    48  		}
    49  
    50  		if !shouldAcceptTag(content.Tags, includeTags, excludeTags) {
    51  			if Debug {
    52  				fmt.Printf("operation %s %s is ignored due to tag rules\n", content.Method, content.Path)
    53  			}
    54  			continue
    55  		}
    56  
    57  		pthObj := tgt.Paths[content.Path]
    58  
    59  		op := setPathOperation(
    60  			content.Method, content.ID,
    61  			&pthObj, op.operations[content.ID])
    62  
    63  		op.Tags = content.Tags
    64  
    65  		sp := new(yamlSpecScanner)
    66  		sp.setTitle = func(lines []string) { op.Summary = joinDropLast(lines) }
    67  		sp.setDescription = func(lines []string) { op.Description = joinDropLast(lines) }
    68  
    69  		if err := sp.Parse(content.Remaining); err != nil {
    70  			return fmt.Errorf("operation (%s): %v", op.ID, err)
    71  		}
    72  		if err := sp.UnmarshalSpec(op.UnmarshalJSON); err != nil {
    73  			return fmt.Errorf("operation (%s): %v", op.ID, err)
    74  		}
    75  
    76  		if tgt.Paths == nil {
    77  			tgt.Paths = make(map[string]spec.PathItem)
    78  		}
    79  
    80  		tgt.Paths[content.Path] = pthObj
    81  	}
    82  
    83  	return nil
    84  }