github.com/snyk/vervet/v6@v6.2.4/ref_index.go (about)

     1  package vervet
     2  
     3  import (
     4  	"reflect"
     5  
     6  	"github.com/getkin/kin-openapi/openapi3"
     7  	"github.com/mitchellh/reflectwalk"
     8  )
     9  
    10  // RefIndex indexes the distinct references used in an OpenAPI document.
    11  type RefIndex struct {
    12  	refs map[string]struct{}
    13  }
    14  
    15  // NewRefIndex returns a new reference index on an OpenAPI document.
    16  func NewRefIndex(doc *openapi3.T) (*RefIndex, error) {
    17  	ix := &RefIndex{refs: map[string]struct{}{}}
    18  	if err := ix.index(doc); err != nil {
    19  		return nil, err
    20  	}
    21  	return ix, nil
    22  }
    23  
    24  func (ix *RefIndex) index(doc *openapi3.T) error {
    25  	return reflectwalk.Walk(doc, ix)
    26  }
    27  
    28  // HasRef returns whether the indexed document contains the given ref.
    29  func (ix *RefIndex) HasRef(ref string) bool {
    30  	_, ok := ix.refs[ref]
    31  	return ok
    32  }
    33  
    34  // Struct implements reflectwalk.StructWalker.
    35  func (ix *RefIndex) Struct(v reflect.Value) error {
    36  	if !v.CanInterface() {
    37  		return nil
    38  	}
    39  
    40  	switch val := v.Addr().Interface().(type) {
    41  	case *openapi3.SchemaRef:
    42  		ix.refs[val.Ref] = struct{}{}
    43  	case *openapi3.ParameterRef:
    44  		ix.refs[val.Ref] = struct{}{}
    45  	case *openapi3.HeaderRef:
    46  		ix.refs[val.Ref] = struct{}{}
    47  	case *openapi3.RequestBodyRef:
    48  		ix.refs[val.Ref] = struct{}{}
    49  	case *openapi3.ResponseRef:
    50  		ix.refs[val.Ref] = struct{}{}
    51  	case *openapi3.SecuritySchemeRef:
    52  		ix.refs[val.Ref] = struct{}{}
    53  	case *openapi3.ExampleRef:
    54  		ix.refs[val.Ref] = struct{}{}
    55  	case *openapi3.LinkRef:
    56  		ix.refs[val.Ref] = struct{}{}
    57  	case *openapi3.CallbackRef:
    58  		ix.refs[val.Ref] = struct{}{}
    59  	}
    60  	return nil
    61  }
    62  
    63  // StructField implements reflectwalk.StructWalker.
    64  func (*RefIndex) StructField(field reflect.StructField, v reflect.Value) error {
    65  	return nil
    66  }