Remove BPA from Makefile
[icn.git] / cmd / bpa-operator / vendor / github.com / go-openapi / spec / schema_loader.go
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 spec
16
17 import (
18         "encoding/json"
19         "fmt"
20         "log"
21         "net/url"
22         "reflect"
23         "strings"
24
25         "github.com/go-openapi/swag"
26 )
27
28 // PathLoader function to use when loading remote refs
29 var PathLoader func(string) (json.RawMessage, error)
30
31 func init() {
32         PathLoader = func(path string) (json.RawMessage, error) {
33                 data, err := swag.LoadFromFileOrHTTP(path)
34                 if err != nil {
35                         return nil, err
36                 }
37                 return json.RawMessage(data), nil
38         }
39 }
40
41 // resolverContext allows to share a context during spec processing.
42 // At the moment, it just holds the index of circular references found.
43 type resolverContext struct {
44         // circulars holds all visited circular references, which allows shortcuts.
45         // NOTE: this is not just a performance improvement: it is required to figure out
46         // circular references which participate several cycles.
47         // This structure is privately instantiated and needs not be locked against
48         // concurrent access, unless we chose to implement a parallel spec walking.
49         circulars map[string]bool
50         basePath  string
51 }
52
53 func newResolverContext(originalBasePath string) *resolverContext {
54         return &resolverContext{
55                 circulars: make(map[string]bool),
56                 basePath:  originalBasePath, // keep the root base path in context
57         }
58 }
59
60 type schemaLoader struct {
61         root    interface{}
62         options *ExpandOptions
63         cache   ResolutionCache
64         context *resolverContext
65         loadDoc func(string) (json.RawMessage, error)
66 }
67
68 func (r *schemaLoader) transitiveResolver(basePath string, ref Ref) (*schemaLoader, error) {
69         if ref.IsRoot() || ref.HasFragmentOnly {
70                 return r, nil
71         }
72
73         baseRef, _ := NewRef(basePath)
74         currentRef := normalizeFileRef(&ref, basePath)
75         if strings.HasPrefix(currentRef.String(), baseRef.String()) {
76                 return r, nil
77         }
78
79         // Set a new root to resolve against
80         rootURL := currentRef.GetURL()
81         rootURL.Fragment = ""
82         root, _ := r.cache.Get(rootURL.String())
83
84         // shallow copy of resolver options to set a new RelativeBase when
85         // traversing multiple documents
86         newOptions := r.options
87         newOptions.RelativeBase = rootURL.String()
88         debugLog("setting new root: %s", newOptions.RelativeBase)
89         resolver, err := defaultSchemaLoader(root, newOptions, r.cache, r.context)
90         if err != nil {
91                 return nil, err
92         }
93
94         return resolver, nil
95 }
96
97 func (r *schemaLoader) updateBasePath(transitive *schemaLoader, basePath string) string {
98         if transitive != r {
99                 debugLog("got a new resolver")
100                 if transitive.options != nil && transitive.options.RelativeBase != "" {
101                         basePath, _ = absPath(transitive.options.RelativeBase)
102                         debugLog("new basePath = %s", basePath)
103                 }
104         }
105         return basePath
106 }
107
108 func (r *schemaLoader) resolveRef(ref *Ref, target interface{}, basePath string) error {
109         tgt := reflect.ValueOf(target)
110         if tgt.Kind() != reflect.Ptr {
111                 return fmt.Errorf("resolve ref: target needs to be a pointer")
112         }
113
114         refURL := ref.GetURL()
115         if refURL == nil {
116                 return nil
117         }
118
119         var res interface{}
120         var data interface{}
121         var err error
122         // Resolve against the root if it isn't nil, and if ref is pointing at the root, or has a fragment only which means
123         // it is pointing somewhere in the root.
124         root := r.root
125         if (ref.IsRoot() || ref.HasFragmentOnly) && root == nil && basePath != "" {
126                 if baseRef, erb := NewRef(basePath); erb == nil {
127                         root, _, _, _ = r.load(baseRef.GetURL())
128                 }
129         }
130         if (ref.IsRoot() || ref.HasFragmentOnly) && root != nil {
131                 data = root
132         } else {
133                 baseRef := normalizeFileRef(ref, basePath)
134                 debugLog("current ref is: %s", ref.String())
135                 debugLog("current ref normalized file: %s", baseRef.String())
136                 data, _, _, err = r.load(baseRef.GetURL())
137                 if err != nil {
138                         return err
139                 }
140         }
141
142         res = data
143         if ref.String() != "" {
144                 res, _, err = ref.GetPointer().Get(data)
145                 if err != nil {
146                         return err
147                 }
148         }
149         return swag.DynamicJSONToStruct(res, target)
150 }
151
152 func (r *schemaLoader) load(refURL *url.URL) (interface{}, url.URL, bool, error) {
153         debugLog("loading schema from url: %s", refURL)
154         toFetch := *refURL
155         toFetch.Fragment = ""
156
157         normalized := normalizeAbsPath(toFetch.String())
158
159         data, fromCache := r.cache.Get(normalized)
160         if !fromCache {
161                 b, err := r.loadDoc(normalized)
162                 if err != nil {
163                         return nil, url.URL{}, false, err
164                 }
165
166                 if err := json.Unmarshal(b, &data); err != nil {
167                         return nil, url.URL{}, false, err
168                 }
169                 r.cache.Set(normalized, data)
170         }
171
172         return data, toFetch, fromCache, nil
173 }
174
175 // isCircular detects cycles in sequences of $ref.
176 // It relies on a private context (which needs not be locked).
177 func (r *schemaLoader) isCircular(ref *Ref, basePath string, parentRefs ...string) (foundCycle bool) {
178         normalizedRef := normalizePaths(ref.String(), basePath)
179         if _, ok := r.context.circulars[normalizedRef]; ok {
180                 // circular $ref has been already detected in another explored cycle
181                 foundCycle = true
182                 return
183         }
184         foundCycle = swag.ContainsStringsCI(parentRefs, normalizedRef)
185         if foundCycle {
186                 r.context.circulars[normalizedRef] = true
187         }
188         return
189 }
190
191 // Resolve resolves a reference against basePath and stores the result in target
192 // Resolve is not in charge of following references, it only resolves ref by following its URL
193 // if the schema that ref is referring to has more refs in it. Resolve doesn't resolve them
194 // if basePath is an empty string, ref is resolved against the root schema stored in the schemaLoader struct
195 func (r *schemaLoader) Resolve(ref *Ref, target interface{}, basePath string) error {
196         return r.resolveRef(ref, target, basePath)
197 }
198
199 func (r *schemaLoader) deref(input interface{}, parentRefs []string, basePath string) error {
200         var ref *Ref
201         switch refable := input.(type) {
202         case *Schema:
203                 ref = &refable.Ref
204         case *Parameter:
205                 ref = &refable.Ref
206         case *Response:
207                 ref = &refable.Ref
208         case *PathItem:
209                 ref = &refable.Ref
210         default:
211                 return fmt.Errorf("deref: unsupported type %T", input)
212         }
213
214         curRef := ref.String()
215         if curRef != "" {
216                 normalizedRef := normalizeFileRef(ref, basePath)
217                 normalizedBasePath := normalizedRef.RemoteURI()
218
219                 if r.isCircular(normalizedRef, basePath, parentRefs...) {
220                         return nil
221                 }
222
223                 if err := r.resolveRef(ref, input, basePath); r.shouldStopOnError(err) {
224                         return err
225                 }
226
227                 // NOTE(fredbi): removed basePath check => needs more testing
228                 if ref.String() != "" && ref.String() != curRef {
229                         parentRefs = append(parentRefs, normalizedRef.String())
230                         return r.deref(input, parentRefs, normalizedBasePath)
231                 }
232         }
233
234         return nil
235 }
236
237 func (r *schemaLoader) shouldStopOnError(err error) bool {
238         if err != nil && !r.options.ContinueOnError {
239                 return true
240         }
241
242         if err != nil {
243                 log.Println(err)
244         }
245
246         return false
247 }
248
249 func defaultSchemaLoader(
250         root interface{},
251         expandOptions *ExpandOptions,
252         cache ResolutionCache,
253         context *resolverContext) (*schemaLoader, error) {
254
255         if cache == nil {
256                 cache = resCache
257         }
258         if expandOptions == nil {
259                 expandOptions = &ExpandOptions{}
260         }
261         absBase, _ := absPath(expandOptions.RelativeBase)
262         if context == nil {
263                 context = newResolverContext(absBase)
264         }
265         return &schemaLoader{
266                 root:    root,
267                 options: expandOptions,
268                 cache:   cache,
269                 context: context,
270                 loadDoc: func(path string) (json.RawMessage, error) {
271                         debugLog("fetching document at %q", path)
272                         return PathLoader(path)
273                 },
274         }, nil
275 }