github.com/djarvur/go-swagger@v0.18.0/scan/operations.go (about)

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